# Introduction
Source: https://docs.lamarge.trade/
A taker pays a token on one venue and receives a token on another, from a maker's pool.
Each venue settles in LaMarge's escrow on its chain, where the operator delivers from the maker's pool, or inside the venue, where the maker delivers each fill ([venues](https://docs.lamarge.trade/how-it-works#venues-and-balances)).
- Makers fund pools with their financial key and quote them with a separate quote key, through a credential that cannot move capital.
- The LaMarge operator relays escrow transactions and is trusted across chains ([trust model](https://docs.lamarge.trade/how-it-works#trust-model)).
- Clients: [`@lamarge/sdk`](https://docs.lamarge.trade/sdk) in TypeScript, the [`lamarge` crate](https://docs.lamarge.trade/rust-sdk) in Rust; the other pages describe the HTTP API.
- For LLMs: [`llms.txt`](https://docs.lamarge.trade/llms.txt), [`llms-full.txt`](https://docs.lamarge.trade/llms-full.txt) and the OpenAPI specification, [`openapi.txt`](https://docs.lamarge.trade/openapi.txt).
Check the deployment, sign in, set up accounts.
Every term, one line each.
Transfer with the SDK or over HTTP.
Credential, pool, quote lines, deliveries.
Capital, quotes, takes, settlement and signing.
Passive on escrow venues, active on Lighter and Aster.
Snapshots, replay and WebSocket.
A taker script and a maker bot.
# Concepts
Source: https://docs.lamarge.trade/concepts
## Roles and keys
| Term | Meaning |
|---|---|
| Taker | Pays a token on one venue and receives a token on another. |
| Maker | Supplies pools and prices them with quote lines. |
| Operator | LaMarge's key: relays escrow transactions, pays their gas and settles fills ([trust model](https://docs.lamarge.trade/how-it-works#trust-model)). |
| Master address | The address you sign in with; its [master session](https://docs.lamarge.trade/api-reference/overview#authentication) links accounts, funds, takes and withdraws. |
| Financial key | The key of the master address or of a linked account: signs funding, payments, withdrawals and closes. |
| Quote key | A separate EOA key that signs quote sets only. |
| Credential | An `mk_` bearer for one quote identity and its quote key, with scopes `read`, `quote`, `cancel`; it never moves capital. |
| Quote identity | What quotes a set of pools: the browser identity (the master address signs) or a credential's; its ID is the credential `id`. |
## Venues and funds
| Term | Meaning |
|---|---|
| Venue | An exchange LaMarge connects ([venues](https://docs.lamarge.trade/how-it-works#venues-and-balances)). |
| Escrow venue | `settlement: escrow`: payments and pools sit in LaMarge's escrow on the venue's chain. |
| In-venue settlement | `settlement: venue` (Lighter, Aster): the maker delivers each fill by a transfer inside the venue. |
| Linked account | Your account on a venue, identified by the address that owns it. |
| Setup step | An authorization a linked account gives once: escrow `permit`, Aster `agent`, Lighter `api_key` ([setup steps](https://docs.lamarge.trade/quickstart#setup-steps)). |
| Available balance | Your escrow balance outside any pool (offer ID zero): receipts, refunds, swept deposits. Takes pay from it first. |
| Pool | A maker order with `capital_pool: true`: inventory of one owner on one venue, quoted by one quote identity. On an escrow venue it is funded into the escrow; on Lighter or Aster it is the maker's account there. |
| `held`, `held_in` | What a pool holds, and where: `escrow`, or `venue` for a Lighter or Aster pool ([balances](https://docs.lamarge.trade/how-it-works#balances)). |
## Quoting
| Term | Meaning |
|---|---|
| Quote line | One venue's `buy` and `sell` price in USDC and the `stock` its pool offers ([quote lines](https://docs.lamarge.trade/how-it-works#quote-lines)). |
| Quote set | One pool's signed quotes, compiled by the server from the lines ([quotes](https://docs.lamarge.trade/how-it-works#quotes)). |
| Lease | A credential identity's admission window, 5 to 120 seconds, renewed by [`PUT /v1/quote-identities/{id}/lease`](https://docs.lamarge.trade/api-reference/quotes/lease). |
| Generation | The quote identity's counter. Renewing a lapsed lease or cancelling all quotes advances it and voids every earlier quote and draft. |
## Trading
| Term | Meaning |
|---|---|
| Take | Pay up to `amount_in` on one venue for at least `min_out` on another, from 1 to 8 fills under one payment signature ([takes](https://docs.lamarge.trade/how-it-works#takes)). |
| Fill | One pool's share of a take. Each fill settles on its own. |
| Delivery | `amount_out` reaching the taker: sent by the operator from an escrow pool, or transferred by the maker on Lighter or Aster. |
| Transfer | A recoverable take: the request is recorded under `client_transfer_id`, any shortfall is withdrawn from venue margin, then the take runs ([transfers](https://docs.lamarge.trade/api-reference/transfers/create)). |
| Wallet funding | `funding: "wallet"`: a take paid from the payer's escrow-token wallet and available balance, never from a venue account ([wallet funding](https://docs.lamarge.trade/how-it-works#wallet-funding)). |
| Wallet delivery | `destination: "wallet"`: a take's output transferred to any address on the receiving escrow's chain ([wallet delivery](https://docs.lamarge.trade/how-it-works#wallet-delivery)). |
| Direct transfer | A wallet deposit into a venue on the same chain, or a GMX Account withdrawal, without a maker ([direct transfers](https://docs.lamarge.trade/direct-transfers)). |
| Route | One take, or two through an intermediate venue, as [`GET /v1/routes`](https://docs.lamarge.trade/api-reference/market-data/get-route) plans it. |
| Intermediate venue | The venue a two-take route receives on, then pays from. |
| Grouped route | A two-take route signed at once: the first take pays from Lighter or Aster, the second from an escrow venue ([routes](https://docs.lamarge.trade/how-it-works#routes-through-another-venue)). |
| Move | One request from an endpoint to another, followed under one ID: LaMarge's part first, a bridge for the rest ([moves](https://docs.lamarge.trade/how-it-works#moves-and-bridges)). |
| Bridge | A move's external part, through Relay: its `order` binds what you sign to the recipient and the guaranteed output. |
| Account credit | The least a bridge deposits into a Polymarket, GMX or Aster account, which receives the bridge's whole output. |
## Deadlines
Each fill carries its own; read them, never compute them: `pay_by`, `t1` and `t2` ([deadlines and outcomes](https://docs.lamarge.trade/how-it-works#deadlines-and-outcomes)); for a delivery on Lighter or Aster, also `maker_accept_by`, `deliver_by` and `report_by` ([deadlines](https://docs.lamarge.trade/market-making#deadlines)).
# Quickstart
Source: https://docs.lamarge.trade/quickstart
Then [transfer as a taker](https://docs.lamarge.trade/taker-quickstart) or [make a market](https://docs.lamarge.trade/maker-quickstart). Terms: [concepts](https://docs.lamarge.trade/concepts).
| Step | `@lamarge/sdk` |
|---|---|
| [Check the deployment](#check-the-deployment) | `checkDeployment` |
| [Sign in](#sign-in) | `signIn` |
| [Link an account](#link) | `linkAccount` |
| [Run its setup steps](#setup-steps) | `setUpVenue` |
## Check the deployment
```sh
export API_URL=https://api.lamarge.trade
export APP_ORIGIN=https://app.lamarge.trade
curl "$API_URL/health"
curl "$API_URL/v1/venues"
curl "$API_URL/v1/books?from=polymarket&to=hyperliquid"
```
- `/health` answers 503 while chain observations, operator gas, the relay backlog or escrow integrity is not ready.
- Pin the operator, escrows, tokens and timings from the [deployment values](https://docs.lamarge.trade/how-it-works#deployment-values), never from `/v1/info` or `/v1/venues`.
## Sign in
1. [`POST /v1/auth/challenge`](https://docs.lamarge.trade/api-reference/authentication/challenge) with `{"address":"0xMASTER"}`.
2. Check that `message` names `APP_ORIGIN`, then sign it with `personal_sign`.
3. Send `{address, nonce, signature}` to [`POST /v1/auth/verify`](https://docs.lamarge.trade/api-reference/authentication/verify).
The returned `token` is the master session. Every step below sends it as `Authorization: Bearer $TOKEN`.
## Set up venue accounts
Link an account on each venue you use, then run its setup steps. The account is the address that owns it; on Polymarket, the signer EOA; on GMX, the owner of the GMX Account.
### Link
[`POST /v1/accounts/link`](https://docs.lamarge.trade/api-reference/account/link) with `{"venue":"polymarket","address":"0x…"}`. An address other than the master also signs the [link challenge](https://docs.lamarge.trade/api-reference/account/link-challenge) (`personal_sign`) and adds its `nonce` and `signature`.
On Lighter, the link records the address's master account index as `venue_wallet`.
### Setup steps
[`GET /v1/accounts/{venue}/setup`](https://docs.lamarge.trade/api-reference/account/setup) lists the account's steps, read from the venue now; `ready` once all are `done`. For each `required` step:
1. [`POST /v1/accounts/{venue}/setup/{step}`](https://docs.lamarge.trade/api-reference/account/setup-step) without a body. It returns `to_sign`: `kind`, `signer`, `ref`, and `typed_data` or `message`.
2. Check it ([signing](https://docs.lamarge.trade/how-it-works#signing)) and sign it with the account: `typed_data` as EIP-712, `message` with `personal_sign`.
3. Post `{"ref": "…", "signature": "0x…"}` to the same path.
4. A `pending` step is relayed: read the setup again until `done`.
| Venue | Step | Signs | Needed to |
|---|---|---|---|
| Hyperliquid, Polymarket, GMX | `permit` | An unlimited EIP-2612 permit to the escrow (GMX: Arbitrum USDC) | Pay from wallet funds; fund a pool |
| Aster | `agent` | Approval of LaMarge's agent (`LaMarge` in production, `LaMargeDev` in dev), `canPerpTrade` only, within 60 seconds | Pay, receive, make |
| Lighter | `api_key` | Lighter's `ChangePubKey` for LaMarge's key at index 254 in production, 253 in dev | Pay from Lighter |
A done step turns `required` again, with a `reason`, when the venue no longer shows it, it expires (the Aster agent after 365 days) or LaMarge's escrow, agent or key changes. A call that needs it answers `422 SETUP_REQUIRED` with its `venue` and `step`.
# Taker quickstart
Source: https://docs.lamarge.trade/taker-quickstart
A [transfer](https://docs.lamarge.trade/concepts#trading) pays `amount_in` on one venue and receives at least `min_out` on another, from maker pools. First run the [quickstart](https://docs.lamarge.trade/quickstart): sign in, then link and set up an account on both venues.
More than LaMarge's pools hold, or a pair they don't serve: a [move](https://docs.lamarge.trade/how-it-works#moves-and-bridges) fills what LaMarge can and bridges the rest, with the SDK's `moveFunds()`.
## With the SDK
1. `npm install @lamarge/sdk viem`
2. Copy the [taker script](https://docs.lamarge.trade/sdk#taker-script).
3. Run it with `API_URL`, `APP_ORIGIN` and `PRIVATE_KEY` set.
It signs in, links and sets up both accounts, then calls `transfer()`: create the transfer, withdraw any shortfall from venue margin, take, check and sign the payment, submit it. Rerun it after an interruption: it resumes the same transfer and never signs a payment twice.
## Over HTTP
With the master session as `$TOKEN`. Amounts are base units: 250 USDC is `250000000`.
### 1. Create the transfer
Persist `client_transfer_id` first: the same request returns the same transfer.
```sh
curl -X POST "$API_URL/v1/transfers" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{
"client_transfer_id": "rebalance-1",
"from": "hyperliquid", "to": "polymarket",
"amount_in": "250000000", "min_out": "249500000",
"payer": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4",
"recipient": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4"
}'
```
```json
{
"id": "0195f0c2-7a41-7c3e-9d2b-6f1e8a4b2c10",
"client_transfer_id": "rebalance-1",
"client_take_id": "transfer:0195f0c2-7a41-7c3e-9d2b-6f1e8a4b2c10",
"from": "hyperliquid", "to": "polymarket",
"amount_in": "250000000", "min_out": "249500000", "max_parts": 8,
"payer": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4",
"recipient": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4",
"from_chain_id": 999, "to_chain_id": 137,
"funding_plan": {
"observed_at": "2026-10-29T10:00:00Z", "venue": "hyperliquid",
"owner": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4",
"amount": "250000000", "deposit": "250000000",
"withdrawal_amount": "0", "withdrawal_to": null,
"payment_setup": "done", "signed_at_once": false,
"requests": [{ "kind": "pay_take", "signer": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4", "chain_id": 999 }]
},
"funding_plan_error": null,
"withdrawal_preparation": null, "withdrawal": null,
"take_id": null, "take_final": null,
"previous_transfer_id": null, "continuable": null, "grouped": null,
"cancelled_at": null, "created_at": "2026-10-29T10:00:00Z"
}
```
Read `funding_plan`:
- `payment_setup` `required`: do the `permit` [setup step](https://docs.lamarge.trade/quickstart#setup-steps) first.
- `withdrawal_amount` above `"0"`: withdraw it from venue margin first ([paying from venue margin](https://docs.lamarge.trade/how-it-works#paying-from-venue-margin)).
- Otherwise the wallet and the available balance cover the payment: take now.
### 2. Take
Send the transfer's terms, its `client_take_id` and its `id` as `transfer_intent_id`. Add `max_fee_bps` to accept the pair's [fee](https://docs.lamarge.trade/how-it-works#fees).
```sh
curl -X POST "$API_URL/v1/takes" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{
"client_take_id": "transfer:0195f0c2-7a41-7c3e-9d2b-6f1e8a4b2c10",
"transfer_intent_id": "0195f0c2-7a41-7c3e-9d2b-6f1e8a4b2c10",
"from": "hyperliquid", "to": "polymarket",
"amount_in": "250000000", "min_out": "249500000", "max_parts": 8
}'
```
The answer holds the [take](https://docs.lamarge.trade/how-it-works#takes), its fills in `PREPARED`, and one `pay_take` item to sign. Abridged:
```json
{
"take": {
"id": "0195f0c3-1b2e-7f40-8a6d-3c9e5d7a1f02",
"client_take_id": "transfer:0195f0c2-7a41-7c3e-9d2b-6f1e8a4b2c10",
"amount_in": "250000000", "amount_out": "249900040", "taker_fee": "0",
"fills": [{
"id": "0195f0c3-1b2e-7f40-8a6d-3c9e5d7a1f02",
"state": "PREPARED", "from_venue": "hyperliquid", "to_venue": "polymarket",
"amount_in": "250000000", "amount_out": "249900040",
"pay_by": "2026-10-29T10:00:46Z", "t1": "2026-10-29T10:02:46Z", "t2": "2026-10-29T12:00:01Z"
}]
},
"to_sign": [{
"kind": "pay_take",
"signer": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4",
"fill_id": "0195f0c3-1b2e-7f40-8a6d-3c9e5d7a1f02",
"typed_data": { "primaryType": "PayTake", "domain": { "name": "LaMarge", "version": "1", "chainId": 999, "verifyingContract": "0x…" }, "types": {}, "message": {} },
"attestation": {
"signature": "0x…",
"terms": { "take": "0x0195f0c27a417c3e9d2b6f1e8a4b2c1000000000000000000000000000000000", "from": "hyperliquid", "to": "polymarket", "recipient": "0x…", "token": "0x…", "amountOut": "249900040", "payBy": 1793268046 }
}
}]
}
```
Each item carries `attestation` when LaMarge attests it: LaMarge's signature that it asks this signer to sign this exact request, with the `terms` it commits to for the take (where it delivers, the token, the total and `payBy`). A signer that holds your key apart from the app calling LaMarge calls `verifyAttestation` from `@lamarge/sdk/attestation` with the request it is about to sign, the item's `attestation`, its own address and `ATTESTERS.production`. It throws unless LaMarge attests that request, and from `payBy` on; it returns the terms for the signer's own policy, such as refusing a `recipient` that isn't one of its addresses. A [wallet delivery](https://docs.lamarge.trade/how-it-works#wallet-delivery)'s terms are `WalletTakeTerms`: `destination: "wallet"`, `recipient` the address it transfers to, `token` the wallet token, `amountOut` the least received. The SDK passes each attestation to your `Signer` with the request (`signTypedData(request, { attestation })`, `signMessage(request, { attestation })`).
### 3. Sign and submit the payment
1. Check the `pay_take` item against your request ([signing](https://docs.lamarge.trade/how-it-works#signing)): payer, deposit, and one `LockPayment` per fill with its amount, recipient and deadlines.
2. Sign its `typed_data` as EIP-712 with the payer.
3. Before `pay_by`, submit it with the take ID as `fill_id`:
```sh
curl -X POST "$API_URL/v1/takes/$TAKE_ID/signatures" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"signatures":[{"kind":"pay_take","fill_id":"0195f0c3-1b2e-7f40-8a6d-3c9e5d7a1f02","signature":"0x…"}]}'
```
The answer lists the fills. After a lost answer, submit the same signature again; never sign a second payment for the take.
### 4. Follow the fills
Read [`GET /v1/takes/{id}`](https://docs.lamarge.trade/api-reference/takes/get-take), or [stream](https://docs.lamarge.trade/streaming) `fill.changed`, until every fill is final:
1. `RESERVED`: the operator reserved the maker's liquidity and sends your payment.
2. `PAID`: the payment is locked; the delivery is on its way.
3. `CLAIMING`: delivered: `amount_out` is in your account on `to_venue`.
4. `SETTLED`: the maker claimed your payment.
A fill that cannot settle ends `EXPIRED` (unpaid) or `REFUNDED` (payment returned to your available balance). [Outcomes](https://docs.lamarge.trade/how-it-works#deadlines-and-outcomes).
A fill delivered on Lighter or Aster first waits up to 15 seconds for its maker's acceptance; without it, the take expires unpaid.
# Maker quickstart
Source: https://docs.lamarge.trade/maker-quickstart
First run the [quickstart](https://docs.lamarge.trade/quickstart): sign in, then link and set up an account on each venue you supply or price. What each venue asks of a maker: [market making](https://docs.lamarge.trade/market-making). In TypeScript: the [provisioning and bot scripts](https://docs.lamarge.trade/sdk#market-making).
| Step | `@lamarge/sdk` |
|---|---|
| [Create the credential](#create-the-credential) | `Maker.createCredential` |
| [Fund a pool](#fund-a-pool) | `Maker.addCapital`, `Maker.waitForFunding` |
| [Quote](#quote) | `Quoter.lease`, `Quoter.publishLines` |
| [Accept and deliver on Lighter](#deliver-on-lighter), [on Aster](#deliver-on-aster) | `LighterDeliverer`, `AsterDeliverer` |
## Create the credential
With the master session, [`POST /v1/credentials`](https://docs.lamarge.trade/api-reference/credentials/create):
```json
{"name":"bot","quote_signer":"0xQUOTE_KEY_ADDRESS","scopes":["read","quote","cancel"],"expires_at":1795877000}
```
- `quote_signer` is the address of a separate EOA key ([quotes](https://docs.lamarge.trade/how-it-works#quotes)).
- `expires_at` is Unix seconds, at most 90 days ahead.
- The answer's `token` (`mk_…`) is returned once: it goes to the quoting host. Its `id` is the quote identity ID.
What each bearer can call: [authentication](https://docs.lamarge.trade/api-reference/overview#authentication).
## Fund a pool
Escrow venues (Hyperliquid, Polymarket, GMX), with the master session; the linked account signs.
1. Persist a new `client_request_id`.
2. [`POST /v1/maker/{venue}/prepare`](https://docs.lamarge.trade/api-reference/maker/prepare):
```json
{"client_request_id":"hl-pool-1","amount":"5000000","funding_source":"venue","quote_identity_id":"CREDENTIAL_ID"}
```
3. Check `funding` and every `to_sign` item ([maker capital](https://docs.lamarge.trade/how-it-works#maker-capital), [signing](https://docs.lamarge.trade/how-it-works#signing)). Sign each with its `signer`.
4. Before `expires_at`, send one signature per item to [`POST /v1/maker/preparations/{id}/signatures`](https://docs.lamarge.trade/api-reference/maker/submit-signatures): `{"signatures":[{"kind":"fund","signature":"0x…"}]}`.
5. Poll [`GET /v1/maker/preparations/{id}`](https://docs.lamarge.trade/api-reference/maker/get-preparation) until `state` is `complete` (the pool is `live`) or `failed` (the order's `error` says why).
On Lighter and Aster, nothing is funded: [open the pool](https://docs.lamarge.trade/market-making#before-quoting) instead.
On GMX, `funding_source` is `wallet`: move GMX Account funds to the linked address first with your own `transferOut` ([margin transfers](https://docs.lamarge.trade/how-it-works#margin-transfers)). Deliveries and releases land in GMX Accounts.
## Quote
With the credential as `$MAKER_TOKEN` and its `id` as `$IDENTITY_ID`.
1. Read the identity's [quote lines](https://docs.lamarge.trade/how-it-works#quote-lines) and their `revision` with [`GET /v1/quote-lines`](https://docs.lamarge.trade/api-reference/quotes/get-lines), and its pools with [`GET /v1/orders`](https://docs.lamarge.trade/api-reference/orders/list-orders) (`capital_pool: true`, with `available_to_quote`).
2. Renew the lease, 5 to 120 seconds:
```sh
curl -X PUT "$API_URL/v1/quote-identities/$IDENTITY_ID/lease" \
-H "Authorization: Bearer $MAKER_TOKEN" -H 'Content-Type: application/json' \
-d '{"ttl_seconds":30}'
```
3. [Prepare](https://docs.lamarge.trade/api-reference/quotes/prepare-lines) every line, one per venue. `valid_until` is Unix seconds within the next five minutes; `expected_revision` is the lines' `revision`.
```json
{"expected_revision":"0","valid_until":1793400025,"lines":[
{"venue":"hyperliquid","buy":null,"sell":"1.0002","stock":"5000000"},
{"venue":"polymarket","buy":"1","sell":null,"stock":"0"}]}
```
4. Rebuild each draft from your lines before signing ([quote lines](https://docs.lamarge.trade/how-it-works#quote-lines), [signing](https://docs.lamarge.trade/how-it-works#signing)). Sign each draft's single `quote_set` item with the quote key.
5. Publish `{"preparation_id":"…","signatures":[{"draft_id":"…","signature":"0x…"}]}` with [`POST /v1/quote-lines`](https://docs.lamarge.trade/api-reference/quotes/publish-lines), within five minutes of preparation, before `valid_until` and while the lease is live. Every pool switches at once, or none.
6. Repeat: renew the lease before it expires and publish again before `valid_until`. After a funding, publish again once the pool is `live`.
| Answer | Cause | Recovery |
|---|---|---|
| `429 RATE_LIMITED` | Request budget, or 100 unsigned drafts | Wait `Retry-After`, resend |
| `409 STALE_QUOTE` | Lease lapsed, generation or `cancel_epoch` changed, pool not `live`, or draft past `valid_until` or five minutes old | Reread the pool, renew the lease, prepare again |
| `409 STALE_SEQUENCE` | A later set was published | Prepare again |
| `409 STATE_CONFLICT` | The lines' `revision` moved; at preparation, a pool not `live` or moving capital, the lease lapsed or `valid_until` passed | Read lines and pools, prepare again |
| `422 ACCOUNT_NOT_LINKED` | A pool's or a destination's account is not linked, or was relinked | Link it |
| `422 SETUP_REQUIRED` | Step `error.step` of `error.venue` is not done | Do that step, or omit that destination |
| `401 UNAUTHENTICATED` | Credential expired, revoked or rotated | Stop; get the new bearer |
| `403 FORBIDDEN` | Missing scope, or identity revoked | Stop |
| `5xx`, lost answer | Server, venue or network fault | Resend the identical request |
Follow pools and fills with a [snapshot and replay](https://docs.lamarge.trade/streaming). Stop with [cancellation](https://docs.lamarge.trade/how-it-works#cancellation).
## Deliver on Lighter
Deadlines and refusals: [active market making](https://docs.lamarge.trade/market-making#active-market-making).
1. Accept each new fill with [`POST /v1/fills/{id}/accept`](https://docs.lamarge.trade/api-reference/takes/accept) before `maker_accept_by`. Accept only a fill you can deliver.
2. Once the fill is `PAID` with `payment_verified_at` set, read your transfer fee: `GET https://mainnet.zklighter.elliot.ai/api/v1/transferFeeInfo?account_index=&to_account_index=`, authenticated by your API key. Lighter charges it on top of the amount and refuses a transfer signed with another fee.
3. Sign one transfer:
| Field | Value |
|---|---|
| `ToAccountIndex` | `delivery_to` |
| `AssetIndex` | 3 (USDC) |
| `FromRouteType`, `ToRouteType` | 0 (collateral) |
| `Amount` | `amount_out`, base units |
| `USDCFee` | The fee read above |
| `Memo` | The fill ID's 16 bytes, then 16 zero bytes, as 64 hex characters |
| Nonce | Your API key's next nonce |
| `ExpiredAt` | `deliver_by`, Unix milliseconds, where your signer takes it |
| `L1Sig` | The owner's signature of Lighter's message |
4. Persist the signed transfer and its hash, then send it.
5. Once Lighter shows it executed, report it with [`POST /v1/fills/{id}/delivery`](https://docs.lamarge.trade/api-reference/takes/delivery) `{"tx_hash":"…"}` before `report_by`. Report again after `425` or `502`; `400` and `409` are final, except `not_due` before the payment locks.
Never sign a second transfer for a fill, or reuse a nonce, while a transfer is pending or of unknown outcome. A transfer that moved nothing (refused on first send, status 0 or above 3, or unexecuted at its expiry) may be replaced before `deliver_by`, at the nonce Lighter's `nextNonce` returns. After a restart, resend or report what you persisted before signing anything new.
## Deliver on Aster
1. Accept each new fill with [`POST /v1/fills/{id}/accept`](https://docs.lamarge.trade/api-reference/takes/accept) before `maker_accept_by`.
2. Keep the inventory in the Spot wallet, or move it there from margin: `POST https://fapi.asterdex.com/fapi/v3/asset/wallet/transfer`, `kindType` `FUTURE_SPOT`, by an agent with `canPerpTrade`. Keep the account public: Aster refuses a private account's transfers.
3. Once the fill is `PAID` with `payment_verified_at` set, send `POST https://chainapi.asterdex.com/aster-chain/v3/transfer?asset=USDT&amount=…&toAddress=…&clientTranId=…&nonce=…&user=…&signature=…`:
| Parameter | Value |
|---|---|
| `amount` | `amount_out` as decimal USDT, six decimals at most, rounded up |
| `toAddress` | `delivery_to`, checksummed |
| `clientTranId` | The fill ID as 32 hexadecimal characters |
| `nonce` | The current time in microseconds |
| `user` | Your address, checksummed |
| `signature` | The query before `&signature=`, signed as `Message{msg}` in the domain `{AsterSignTransaction, 1, 1666, 0x0}` with the account's key |
4. Report the reply's `transferId` with [`POST /v1/fills/{id}/delivery`](https://docs.lamarge.trade/api-reference/takes/delivery) `{"tx_hash":"…"}` until accepted, before `report_by`. `425` means the Spot histories do not show it yet.
- A lost answer is resent with the same `clientTranId` within a minute of its nonce: Aster returns the first transfer and moves nothing more.
- `032209 Daily transfer limit exceeded` means the Spot wallet holds too little.
- Never send one fill's transfer under another fill's ID.
# How LaMarge works
Source: https://docs.lamarge.trade/how-it-works
Terms: [concepts](https://docs.lamarge.trade/concepts).
## Trust model
The operator key sends every escrow transaction LaMarge relays and pays its gas.
- It reads the taker's escrow payment at the chain's final head (`finalized` by default; the head itself on Arbitrum), then pays the taker from the maker's pool on the other chain, under the maker's signed quote: the delivery.
- A payment from Lighter or Aster is a signed transfer the operator sends first ([paying from Lighter](#paying-from-lighter)).
- It keeps each fill's secret, which releases the payment to the maker, and shows it to the maker once the fill is delivered.
- On Lighter and Aster the maker delivers; the operator claims the payment for the maker once the delivery report is accepted, by `report_by`. A claim not landed by `t2` lets the payment return to the taker, even after a delivery ([active market making](https://docs.lamarge.trade/market-making#active-market-making)).
The escrows cannot see the other chain. A stolen operator key can deliver inventory under any unexpired quote signature and return a delivered fill's payment to its taker before the maker claims it. A secret leaked before the delivery lets anyone release the payment to the maker early, the delivery still owed.
Each chain's escrow is a UUPS proxy. Only the governance key can upgrade it, through a timelock set to zero delay during the closed beta; the operator has no upgrade authority. Governance therefore controls every escrow balance and allowance to it. Under the current implementation, owners withdraw their funds on chain ([recovery](https://docs.lamarge.trade/recovery)): the available balance at once, a pool after a one-day notice. Payments stay locked at most 24 hours.
## Venues and balances
| Venue | ID | Escrow chain | Token | Linked account | Authorization |
|---|---|---|---|---|---|
| Hyperliquid | `hyperliquid` | HyperEVM, 999 | USDC, 6 decimals | Owner of the HyperCore account, not an API wallet | Unlimited EIP-2612 permit to the escrow |
| Polymarket Perps | `polymarket` | Polygon, 137 | pUSD, 6 decimals | Signer EOA, with its Deposit Wallet or Safe | Unlimited EIP-2612 permit to the escrow |
| Aster | `aster` | None (`settlement: venue`); signatures name BSC, 56 | USDT, 18 decimals | Owner of the Aster account | LaMarge's agent, for 365 days |
| Lighter | `lighter` | None (`settlement: venue`) | USDC, 6 decimals | Owner of the Lighter master account, whose index is `venue_wallet` | LaMarge's API key, to pay from Lighter |
| GMX | `gmx` | Arbitrum, 42161 | USDC, 6 decimals | Owner of the GMX Account (multichain balance) | Unlimited EIP-2612 permit to the escrow |
- The tokens are distinct assets: never add their base units.
- The escrow spends an allowance only on actions its owner signs.
- LaMarge's Aster agent holds only `canPerpTrade`: it reads the account and moves margin to the account's own Spot wallet.
- A taker receiving on Lighter or Aster needs a linked account, and on Aster the agent. A taker paying from there signs a transfer ([Lighter](#paying-from-lighter), [Aster](#paying-from-aster)).
- `setup` in `/v1/me` and `/v1/balances` lists each account's [setup steps](https://docs.lamarge.trade/quickstart#setup-steps) with what each is `needed_for`.
### Opening an account
Lighter and Aster create an account at its first deposit, and LaMarge pays into them inside the venue: an account receives only once opened. LaMarge never makes that deposit.
- An account is open when its `/v1/balances` row has `read_at`, no `error` and `has_account` true. `balance.changed` announces each read; an account linked within the hour and still unopened is read every 30 seconds.
- Lighter links before its first deposit, with `venue_wallet` null until the deposit creates the master account. Until then its `api_key` step is `required`, and takes to or from it answer `STATE_CONFLICT` with reason `no_deposit`. Deposit at least 1 USDC through `deposit` on Lighter's Ethereum contract, or at least 5 USDC to the intent address Lighter's `POST /api/v1/createIntentAddress` returns for the owner (CCTP chains, Arbitrum and HyperEVM among them). A [wallet delivery](#wallet-delivery) with `max_parts` 1 can pay that address. Get the address from Lighter yourself: LaMarge does not vouch for it.
- Aster answers takes to an account without a deposit with `STATE_CONFLICT` and reason `no_deposit`. Anyone can open it: `depositFor(USDT, owner, amount, 0)` on Aster's BSC vault `0x128463A60784c4D3f46c23Af3f65Ed859Ba87974`: 0.000001 USDT is enough.
- Polymarket links only once the signer has a Deposit Wallet or Safe (`WALLET_NOT_FOUND`).
### Balances
[`GET /v1/balances`](https://docs.lamarge.trade/api-reference/account/balances) returns one row per linked account: `holdings.total` on that venue's side, of which `holdings.available` can move or be committed now and `holdings.locked` is the rest. Each amount appears once:
| Location | Field |
|---|---|
| Venue account | `equity`, of which `withdrawable` can leave; a Lighter or Aster pool's inventory, `holdings.pool`, is part of it |
| Venue wallet or Hyperliquid spot | `wallet` |
| trade.xyz, beside a standard Hyperliquid account's perps | `xyz.equity`, of which `xyz.withdrawable` can leave |
| Linked address on the escrow chain | `chain_balance` |
| Escrow, available balance | `escrow_balance` |
| Escrow, pools | `holdings.orders` |
| Escrow, fills in progress | `holdings.trades` |
| Deposit address, awaiting the sweep | `deposit_balance` |
- `xyz` is set for a standard Hyperliquid account (`mode` `default`, `disabled` or `dexAbstraction`), which holds trade.xyz, the HIP-3 dex `xyz`, apart from its perps. A unified or portfolio-margin account's one balance covers its perps, spot and trade.xyz: `xyz` is null.
- A pool's `held_in` tells where its `held` is: `escrow`, or `venue` for a Lighter or Aster pool, whose figure is its account's balance and never adds to `equity`.
- Pools another operator funded are read on chain by [`GET /v1/escrow`](https://docs.lamarge.trade/api-reference/escrow/list) with `in_balances` false: add them to the total.
- Venue values carry `read_at` and `error`, chain values `chain_read_at` and `chain_error`: check each pair on its own.
The available balance holds settlement receipts, refunded payments, refused venue deposits and tokens swept from `deposit_address`.
- Tokens there are swept once they reach one token, or in any amount within an hour of a withdrawal relayed there.
- Takes pay from it first, and maker capital uses it first.
- A maker's receipts go there. A taker's receipts are deposited into the destination venue.
- A fill's `payment_destination` and `maker_destination` read `venue`, or `escrow` when kept in the available balance.
### Margin transfers
1. [Prepare](https://docs.lamarge.trade/api-reference/withdrawals/prepare) `{venue, amount, to}`.
2. Sign the returned typed data with the linked account.
3. [Relay](https://docs.lamarge.trade/api-reference/withdrawals/relay) it within ten minutes of preparation.
| Venue | `to` | Signed message |
|---|---|---|
| Hyperliquid | `signer`: the linked address on HyperEVM | `HyperliquidTransaction:SendAsset`, decimal amount |
| Aster | `signer`: the linked address on BSC, Arbitrum or Ethereum (`chain_id`, each chain with its own limit and fee from [`GET /v1/withdrawals/chains`](https://docs.lamarge.trade/api-reference/withdrawals/chains)) | Aster `Action`, decimal amount including that chain's withdrawal fee; relayed with its own [`envelope`](https://docs.lamarge.trade/api-reference/withdrawals/relay) |
| Polymarket | `signer`; `wallet`, its venue wallet; or `escrow`, its deposit address | Polymarket `Withdraw`, base units |
| GMX | None: LaMarge relays no GMX withdrawal | Your own transaction: `transferOut((USDC, amount, 0, 0x0, 0x, (0x0, 0, [], 0)))`, no bridge and no bridge fee, on GMX's MultichainTransferRouter `0xC993eF170859DAE0241a3c12B8186e456Fa1c1B0`, to your own address on Arbitrum; a funding plan asks for it as `transfer_out` |
- An Aster withdrawal takes two signatures of the account at chain 56: the `Action`, then its `envelope`, signed at most 50 seconds before the relay.
- `to: "account"` with `recipient` sends to another existing account on the same venue (`kind` `send`): Hyperliquid's `SendAsset`; Aster's wallet-signed transfer (`clientTranId` starting with `s`, relayed within 50 seconds, no envelope, no fee); Polymarket's internal transfer, an `Op` whose `message.data` hashes the returned `op`. Rebuild that hash from `op` and check its recipient and amount before signing: the wallet shows only the hash. On Polymarket the recipient is the Perps account's owner address.
- On a standard Hyperliquid account, `dex: "xyz"` withdraws or sends from trade.xyz instead of the perps. A withdrawal's `from_dex` reads `xyz` when it left trade.xyz. A Hyperliquid delivery lands on the perps, never on trade.xyz.
- `relayed` is the venue's acknowledgement, not arrival. A Polymarket withdrawal or Hyperliquid transfer the venue did not answer stays `queued` and is sent again, unchanged, within its two minutes. `unknown` may have reached the venue: it blocks further transfers on that venue until it is resolved. A Polymarket withdrawal resolves from Polymarket's exchange: `relayed` once it executes, `refused` a little over an hour after signing if it never did. Never sign another transfer to work around it.
## Maker capital
Escrow venues. Lighter and Aster pools: [active market making](https://docs.lamarge.trade/market-making#before-quoting).
A pool (`capital_pool: true`) is the escrow inventory of one owner, venue and quote identity.
- The operator pays each delivery from it once the taker's payment is final. Through the API, releasing it is immediate; on chain, it takes a one-day notice ([recovery](https://docs.lamarge.trade/recovery#withdraw-a-pool)).
- Its 32-byte ID, the escrow `offerId`, comes from its first preparation and is reused by every later one.
- The quote identity fixes its quote signer: the master address for the browser identity, else the credential's `quote_signer`. Another signer needs a new credential and new capital.
[`POST /v1/maker/{venue}/prepare`](https://docs.lamarge.trade/api-reference/maker/prepare) adds `amount` to the pool of `quote_identity_id` (the browser identity when omitted):
- `funding` splits `amount` into `idle_amount` (available balance, used first), then `wallet_amount` or `venue_amount`, by [`funding_source`](https://docs.lamarge.trade/api-reference/maker/prepare). A GMX pool funds from the wallet only: move GMX Account funds there first with your own `transferOut`. `existing_available` is the pool's `available_to_quote` plus the available balance.
- `to_sign` holds a `fund` item, and a `margin_move` item when `venue_amount` is above zero. For the browser identity, a `quote_set` item re-signs the pool's current quotes, scaled to what remains.
- Check them ([signing](#signing)) and [submit](https://docs.lamarge.trade/api-reference/maker/submit-signatures) every signature before `expires_at`: one hour, ten minutes with a `margin_move`.
Rules:
- The first funding is at least 5 tokens.
- Adding capital is refused while a fill of the pool is reserved, or another funding, take payment or escrow withdrawal of the owner is pending on that venue. It pauses the pool's admissions until it lands or the preparation ends.
- Submission answers `STATE_CONFLICT`, cancelling the preparation, when the pool's `revision` changed (a fill or a publication). It answers `FORBIDDEN` when the identity's generation changed or, with a `quote_set` item, its lease lapsed: delete the preparation. Stop quoting a pool before preparing its funding; resume after submission.
- Each funding raises the pool's on-chain quote floor to `minQuoteSequence`, revoking every older set. The preparation's `quote_set`, when it has one, replaces it; otherwise the pool has no set until its quote key publishes one.
A preparation ends:
- `complete`: the pool is `live`.
- `cancelled` ([`DELETE`](https://docs.lamarge.trade/api-reference/maker/cancel-preparation), expiry or a changed revision): the pool returns to its prior state (`closed` for a new one).
- `failed`: its margin transfer or funding did not land. A first funding leaves the pool `failed` with an `error`; a top-up restores its previous state and prices.
### Releasing capital
- [`POST /v1/escrow/withdraw/prepare`](https://docs.lamarge.trade/api-reference/escrow/prepare-withdrawal) prepares an owner-signed `escrow_withdrawal` of `amount` from one pool or the available balance (`order_id` zero), to the venue margin (`to_margin: true`) or to the owner's address. [`POST /v1/escrow/withdraw`](https://docs.lamarge.trade/api-reference/escrow/withdraw) relays it. [`GET /v1/escrow`](https://docs.lamarge.trade/api-reference/escrow/list) lists what this can release.
- A pool keeps quoting what remains: it releases only its `available_to_quote`, what its reserved fills leave, and quotes without the amount until the withdrawal lands. All of it closes the pool.
- A pool another operator funded releases only once its owner's exit notice has run (`409 STATE_CONFLICT` before).
- [`POST /v1/closes`](https://docs.lamarge.trade/api-reference/closes/request-close) closes up to 50 pools. Empty ones close at once; the others need one `close_orders` item signed by the master, then [submitted](https://docs.lamarge.trade/api-reference/closes/submit-signature). Once every reserved fill is delivered or abandoned, the operator releases the funds into the owner's venue margin; a Lighter or Aster pool just closes.
Cancelling quotes releases no capital.
## Quote lines
A maker prices venues, not routes. A quote line gives, for one venue:
| Field | Meaning |
|---|---|
| `buy` | What the maker pays to receive one unit of the venue's token there |
| `sell` | What it asks to deliver one from its pool there; at least `buy` |
| `stock` | What its pool there offers, in base units |
| `min_fill` | Optional: the smallest fill of that pool's quotes; one token by default |
- Prices are USDC per unit, from 0.90 to 1.10, eight decimals at most; `null` leaves a side out.
- A taker paying on A and receiving on B from one maker gets `paid × buy[A] / sell[B]`. Two makers' lines never combine.
- [Publishing](https://docs.lamarge.trade/api-reference/quotes/publish-lines) replaces all of an identity's lines at once, for new takes. A take already prepared still executes at the set it was prepared under, within that set's budget and the pool's funds, until its `pay_by`; [cancelling quotes](https://docs.lamarge.trade/api-reference/quotes/cancel-all) withdraws it.
- Each pool with stock gets a quote set quoting every other line with a buy price whose venue can pay into it. Lighter and Aster never trade directly with each other.
- Each quote has `supply` and `quote_size` the stock, `receive = ceil(stock × sell × 10^dA / (buy × 10^dB))` with `d` each token's decimals, and the line's `min_fill`. Raise `min_fill` where each delivery costs a fee, as on Lighter.
- A venue needs no stock to receive. A pool without stock leaves the books. Changing one price re-signs every pool it affects, together.
[`GET /v1/markets`](https://docs.lamarge.trade/api-reference/market-data/get-markets) shows each venue's best lines among the makers the books show, its liquidity and its 24-hour volume. The best buy and the best sell can belong to different makers; a route's price is always one maker's pair.
## Quotes
Quote lines compile into quote sets. A quote set prices one pool for every destination it quotes, under one ECDSA signature of the pool's quote signer. The signer is an EOA key: publication refuses a contract's (ERC-1271) signature, which could be withdrawn once the taker paid. Each quote, named by its position `quote_index`, has:
- `venue`: the destination, never the pool's venue. The taker pays the `recipient` there, the maker's linked account.
- `supply`: pool-token base units the quote sells in total under the set.
- `receive`: destination-token base units for `supply`, the exact price. The taker pays `ceil(amount_out × receive / supply)`.
- `min_fill`: the smallest fill, in pool-token base units: at least 1 token, at most `supply`, `quote_size` and the fill cap, `limits.fill_max` in [`/v1/info`](https://docs.lamarge.trade/api-reference/market-data/info) (millionths of a token).
`quote_size` is the set's admission budget, shared by its quotes and not signed.
- A destination's levels are drawn best price first. Each shows the smallest of its remaining `supply`, the set's remaining `quote_size` and the pool's unreserved funds, less output and delivery fees.
- Every destination draws on the same funds. Each delivery spends signed budget permanently.
- Books sort by price, then age. A take skips the taker's own pools.
The server admits takes only under the current set of a `live` pool, before its `valid_until`, at its identity's current generation and, for a credential, while the credential is active and its [lease](https://docs.lamarge.trade/api-reference/quotes/lease) is live.
- A lease lasts 5 to 120 seconds. Renewing a lapsed one advances the generation: earlier quotes and drafts never return.
- A credential's `valid_until` is at most five minutes ahead. The browser identity has no lease and may use `253402214400`, no expiry.
- The server [prepares](https://docs.lamarge.trade/api-reference/quotes/prepare-lines) each set from the lines and allocates its sequence. Publication sends only `{draft_id, signature}`, within five minutes of preparation, at the same generation and `cancel_epoch`.
On chain, a signed set stays valid until `expiresAt = valid_until + maker_timeout_seconds + 1`, while its sequence is at or above the pool's floor and its budget is unspent. Leases and API cancellation do not revoke it. A stolen quote key can sell the whole pool at any price to a colluding taker: keep funded inventory within strategy limits.
### Cancellation
- [`DELETE /v1/orders/{id}/quotes`](https://docs.lamarge.trade/api-reference/orders/pull-quotes) removes one pool's set and advances its `cancel_epoch`, voiding earlier drafts.
- [`DELETE /v1/quote-identities/{id}/quotes`](https://docs.lamarge.trade/api-reference/quotes/cancel-all), the kill switch, removes every set of the identity and advances its generation.
- A lease left to expire stops admission. Rotating or revoking the credential removes its quotes.
Fills reserved before a cancellation continue and may settle.
`raiseQuoteFloor(owner, offerId, last_sequence + 1)` revokes signed sets on chain. Only the operator can call it before the pool's exit notice has run; after, the owner or the quote signer can too. The server does not read the floor: set above the server's next sequence, it makes deliveries under the pool's later sets and its fundings revert until the server's sequences reach it. Against a stolen quote key, [release the capital](#releasing-capital).
## Maker results
[`GET /v1/me/stats`](https://docs.lamarge.trade/api-reference/account/stats)'s `maker` is what your pools received less what they delivered, over every fill with a claimed leg: a payment once claimed, a delivery and its fee once delivered. Each token is valued at your mark there, the mid of the line's buy and sell, or its one price (a fill without a mark for both its tokens values each at 1): the spread your prices captured, apart from what holding the tokens gains or loses. `daily` sums it per UTC day, `pairs` per paying and delivering venue.
## Takes
A taker needs linked accounts on both venues, or only on the paying one for a [wallet delivery](#wallet-delivery).
1. [`POST /v1/takes`](https://docs.lamarge.trade/api-reference/takes/take): `amount_in` is the most paid, `min_out` the least received in total, `max_parts` 1 to 8. The server walks the book, one fill per price level, each capped at `fill_max` and at what the take left of its pool's funds, skipped below its `min_fill`. Together the fills must reach the `to` venue's `release_minimum` ([`GET /v1/venues`](https://docs.lamarge.trade/api-reference/market-data/list-venues)).
2. The fills are `PREPARED`: exact terms, no maker liquidity reserved. Check the single `pay_take` item and sign it before `pay_by`, then [submit it](https://docs.lamarge.trade/api-reference/takes/submit-signatures). Its `deposit` pulls what the available balance lacks from the linked address; each `LockPayment` pays one fill under its hashlock.
3. A fill delivered on Lighter or Aster waits for its maker's acceptance, by `maker_accept_by` ([active market making](https://docs.lamarge.trade/market-making#active-market-making)). A missed acceptance expires the whole take unpaid.
4. The operator rechecks the quotes, reserves every fill at once (`RESERVED`) and sends the deposit and every payment in one transaction, or none.
5. Each fill executes under the quote set it was prepared under: the maker publishing new prices meanwhile does not undo it. A quote cancelled, expired or run out meanwhile expires the take unpaid, with a `reason`: take again.
- Before signing, [`DELETE /v1/takes/{id}`](https://docs.lamarge.trade/api-reference/takes/cancel) cancels the take.
- When the available balance and the linked address together cannot cover the payment, the take answers `PREFUNDING_REQUIRED` and reserves nothing.
- Up to `limits.max_unpaid_takes` takes may await payment at once, each admitted against what the others hold of the same funds (`holdings.committed` in [balances](https://docs.lamarge.trade/api-reference/account/balances)).
- A payment already sent keeps its reservation until its outcome is known.
- A payment whose delivery has not landed by `t1` returns to the available balance right after it.
- Fills settle independently, so the total received can be below `min_out`.
### Fees
Each pair has a taker fee in basis points, the book's `taker_fee_bps`; makers pay none.
- Send `max_fee_bps` to accept it. A pair whose fee is higher refuses the take (`VALIDATION_ERROR`, `reason` `fee_above_max`). Without it, the take pays no fee.
- A transfer carries its take's consent; a route's second take, `then.max_fee_bps`. [`GET /v1/routes`](https://docs.lamarge.trade/api-reference/market-data/get-route) prices each leg for the `max_fee_bps` you pass.
- The fee is fixed per fill (`taker_fee`, in `taker_fee_venue`'s token) and carried by its `swap_id`, which the escrow reads. Paid from an escrow, it is part of `amount_in` and the maker receives the rest (`maker_in`). Paid from Lighter or Aster, the maker's pool delivers it on top of `amount_out` (`maker_out`).
- Before signing, check that each fill's `taker_fee` is the one its `swap_id` carries (the [SDK](https://docs.lamarge.trade/sdk) does).
### Wallet funding
`funding: "wallet"` on a transfer or a take pays only from the payer's escrow-token wallet and available balance on `from`'s escrow chain: nothing is withdrawn from the venue account. The default, `venue`, may [withdraw a shortfall](#paying-from-venue-margin). It needs `chain.wallet_funding` in [`GET /v1/venues`](https://docs.lamarge.trade/api-reference/market-data/list-venues), so never Lighter or Aster.
- `payer` defaults to the master, which needs no linked account on `from`; another payer is the account linked there. Where the take delivers is a separate choice ([wallet delivery](#wallet-delivery)).
- [`GET /v1/wallets/{venue}`](https://docs.lamarge.trade/api-reference/account/wallet-funding) reads the payer's `wallet` and `available` now, what other payments hold (`committed_wallet`, `committed_available`) and the rest (`spendable_wallet`, `spendable_available`). Before signing a prepared take, pass its `take_id` to leave its own hold out.
- [`POST /v1/wallets/{venue}/permit`](https://docs.lamarge.trade/api-reference/account/wallet-permit) with an empty body (or `payer`) prepares the escrow-token `permit`; post its `ref` and `signature` to the same route. Funds and the permit are checked again at payment.
- Refunds credit the payer's available balance. The master reads its own with [`GET /v1/escrow?owner=`](https://docs.lamarge.trade/api-reference/escrow/list) and withdraws it to its wallet with that `owner`, `order_id` zero and `to_margin: false` ([releasing capital](#releasing-capital)), without a linked account. Retry with the prepared withdrawal, never a new one.
#### Native USDC on Polygon
Polygon's escrow token is pUSD. Where `chain.wallet_funding.conversion` is set, a wallet-funded transfer from Polymarket can pay from native USDC: send `conversion: {amount_in, min_out}`: the USDC paid, at least 0.01, and the least pUSD credited, at least `ceil(amount_in × 9,995 / 10,000)`, which is also the transfer's `amount_in`. Without `conversion`, it pays pUSD.
1. [Prepare](https://docs.lamarge.trade/api-reference/transfers/prepare-conversion) the conversion: it returns its `nonce` and a `deadline` 30 minutes ahead. A payer has one open conversion at a time.
2. Before the wallet prompt, [post](https://docs.lamarge.trade/api-reference/transfers/report-conversion) an empty body: it moves `prepared` to `pending` once, across tabs and devices. After a lost answer, never prompt again.
3. From the payer, approve `amount_in` of native USDC to the escrow, then send it `convertDeposit(amount_in, min_out, nonce, deadline)`, paying POL gas. Report each broadcast `tx_hash`, replacements included, to the same route.
4. The conversion is `ready` once LaMarge reads its finalized event, reported or not. Until then the take answers `STATE_CONFLICT`.
The escrow credits the pUSD it measures, at least `min_out`, to the available balance: anything above `amount_in`, and any refund, stays there in pUSD. A transfer that replaces this one passes the conversion's `id`. Never prepare another conversion to recover an unknown broadcast.
### Wallet delivery
A take can transfer what it buys to any address on the receiving escrow's chain instead of the linked account: send `destination: "wallet"` and `recipient`.
| `to` | Chain | Recipient receives |
|---|---|---|
| `hyperliquid` | HyperEVM, 999 | USDC, `amount_out` |
| `polymarket` | Polygon, 137 | Native USDC, converted from pUSD: at least `minimum_received` |
| `gmx` | Arbitrum, 42161 | USDC, `amount_out` |
- Only where `chain.wallet` is set in [`GET /v1/venues`](https://docs.lamarge.trade/api-reference/market-data/list-venues), never on the paying venue's own chain (its withdrawal does that), and on a route only as the last take (`then.destination`).
- No account, setup or `release_minimum` on `to`; each part of a take delivers at least `chain.wallet.minimum` (0.01 USDC on Polygon). The recipient is any address but zero, the escrow, Polygon's converter, the escrow's and the wallet's token contracts and, on HyperEVM, a HyperCore system address.
- The `pay_take` signs the recipient as `receiveRecipient` and the wallet token as `receiveToken`; each fill's `swap_id` starts with a wallet tag (`0x1b4c4374729e`, or `0xfcb0d9ddb285` with a fee paid inside a venue), which the escrow reads: it pays such a swap id only by transfer, never into a venue. A [separate signer](https://docs.lamarge.trade/taker-quickstart) reads the recipient and the destination from the take's attestation (`WalletTakeTerms`).
- `amount_out`, `min_out` and fees stay in the escrow token. On Polygon each take's recipient receives at least `ceil(amount_out × 9,995 / 10,000)`; the conversion goes through Polymarket's offramp (pUSD to USDC.e, 1:1) and a Uniswap v4 USDC.e/USDC pool, and refuses less.
- The fill then shows `maker_destination` `wallet` and `received` (`token`, `amount`, `sender`): its share of the one transfer per recipient, the escrow (on Polygon the converter) sending it, in the transaction its `deliver` entry lists.
- A transfer the token refuses reverts the delivery: an escrow payment returns to the available balance as any undelivered one.
### Paying from Lighter
A take from Lighter into an escrow venue is one fill, where the deployment enables it (`VALIDATION_ERROR` otherwise).
1. Once per account, do the `api_key` [setup step](https://docs.lamarge.trade/quickstart#setup-steps). The key can place orders but never move funds to another owner. Replaced on Lighter, it is asked for again.
2. `to_sign` holds one `lighter_transfer`. Check on Lighter that `to_account_index` belongs to the maker's `maker_recipient` and `from_account_index` to you.
3. Build Lighter's transfer owner message from its terms, sign it with `personal_sign` and [submit](https://docs.lamarge.trade/api-reference/takes/submit-signatures) it before `pay_by`. Your account must hold `amount` plus `usdc_fee`, Lighter's fee, 0 or 1 USDC; the SDK signs no transfer whose fee is above that.
4. The operator simulates the delivery to you on the escrow. If it would fail, nothing is sent and the fill expires.
5. Then it signs your transfer with its key and sends it. The fill stays `RESERVED` until the transfer executes, then is `PAID` until the delivery, or `EXPIRED` if it ends unexecuted.
An executed transfer cannot return: the delivery is tried until `t1`, an hour after the take by default. An account backing a Lighter pool cannot pay.
### Paying from Aster
A take from Aster into an escrow venue is one fill, paid from your Spot wallet. LaMarge's agent moves any shortfall there from your margin.
1. `to_sign` holds one `aster_transfer`, the transfer request itself: `Message{msg}` at chain 1666, from your address to the maker's `maker_recipient`, of `amount_in` rounded up to six decimals, with the fill ID as `clientTranId` (32 hex characters) and a nonce 55 seconds ahead. Check those fields. Right before your wallet signs, [issue it again](https://docs.lamarge.trade/api-reference/takes/reissue-aster) with its `nonce`: the same request with a nonce 55 seconds after now, so a slow review never shortens its life (`matched` false: you held an older one, call again with the one returned).
2. Sign it with `eth_signTypedData_v4` on chain 1666 (add that network once, with [`POST /v1/venues/aster/rpc`](https://docs.lamarge.trade/api-reference/market-data/aster-signing-network) as its RPC URL), then [submit](https://docs.lamarge.trade/api-reference/takes/submit-signatures) it before `pay_by`.
3. The operator checks the delivery would land, as from Lighter, then relays your request. Aster accepts it until about a minute after its nonce.
4. Its execution, shown in both accounts' Spot histories, starts the delivery to you, tried until `t1`.
Your account must be public and hold the amount when the transfer is sent. An account backing an Aster pool cannot pay.
Two payments failed within 24 hours because of your account (key replaced, balance short, private account) suspend paying from Lighter and Aster (`403 FORBIDDEN`).
### Paying from venue margin
To pay from venue margin on an escrow venue, [create a transfer](https://docs.lamarge.trade/api-reference/transfers/create) first (`from_dex: "xyz"` to withdraw from a standard Hyperliquid account's trade.xyz). Its `funding_plan` gives the margin transfer still needed, in whole millionths of the token. [Prepare](https://docs.lamarge.trade/api-reference/transfers/prepare-funding) it, then:
- `signed_at_once` true (your permit done): take with the transfer's terms, `client_take_id` and `transfer_intent_id` right away, then [submit](https://docs.lamarge.trade/api-reference/takes/submit-signatures) the `pay_take` and the withdrawal's `margin_move` signature together. LaMarge sends the withdrawal, then the payment as soon as a chain read shows the funds at the linked address. The take's `pay_by` is a route's (`limits.route_pay_window_seconds`). Nothing moves unless both are signed.
- Otherwise [submit](https://docs.lamarge.trade/api-reference/transfers/submit-funding) the withdrawal, wait for `relayed` and the funds at the linked address, then take.
After a lost response, [recover the transfer](https://docs.lamarge.trade/api-reference/transfers/get) and its take before computing another shortfall: a payment may already have spent the wallet balance.
### Routes through another venue
No take joins Lighter and Aster. [`GET /v1/routes`](https://docs.lamarge.trade/api-reference/market-data/get-route) (session) returns the best route now: one take, or two through an intermediate venue when that pays at least 10 bps more.
1. Create the first transfer with `then`: the final venue, your account there, the second `amount_in` and its minimum.
2. Once its take can deliver nothing more, `continuable` shows what arrived, less what continuations hold and the next payment's fee.
3. Create the second from the intermediate venue with `previous_transfer_id`, for at most `continuable`. A continuation that never took is replaced by the next.
The two takes are not atomic: the second is priced after the first delivers, and the funds wait in your account on the intermediate venue. Cancelling the first, once final, ends the route.
Taken take by take, the second transfer pays from your account on the intermediate venue, as any transfer from there: from Hyperliquid or Polymarket it first [withdraws](#paying-from-venue-margin) from that account, from Lighter or Aster its take pays from it. That account signs these requests, whatever venue the route started from.
#### Grouped routes
A route whose first take pays from Lighter or Aster through an escrow venue can be grouped: signed at once.
1. With the first take prepared and unsigned, [prepare the route](https://docs.lamarge.trade/api-reference/transfers/prepare-grouped). LaMarge creates the second transfer and prepares its take, priced on the book now, for what the first take delivers.
2. Sign the first take's request and the second take's `pay_take`, the requests this preparation returns: for Aster prepared with `reissue`, the `pay_take` first, then the Aster request [issued again](https://docs.lamarge.trade/api-reference/takes/reissue-aster) right before you sign it (sign the one that call returns).
3. [Commit them together](https://docs.lamarge.trade/api-reference/transfers/commit-grouped) before `commit_by`.
4. Each fill either take delivers on Lighter or Aster waits for its maker's acceptance. Then both takes' pools are reserved together, just before the first payment.
5. The first take is delivered into your available balance on the intermediate chain, and LaMarge pays the second take from it. Nothing is left to sign.
- For Aster, preparation gives the first take about 90 seconds until `commit_by`. Prepare with `{"reissue": true}`, sign the second take's `pay_take` first, then [issue the Aster request again](https://docs.lamarge.trade/api-reference/takes/reissue-aster) and sign it last: it is sent as soon as you commit. Without `reissue`, its nonce is dated 20 seconds after `commit_by`, and the relay waits until 55 seconds before that nonce, so a fast signature can wait about 55 seconds before Aster is paid.
- `grouped_unavailable`, `TAKE_EXPIRED` on the commit, or an [abort](https://docs.lamarge.trade/api-reference/transfers/abort-grouped) ends the grouped attempt. Continuing take by take is a separate decision of yours.
- While the route is `prepared` or `committed`, only the route moves its takes and transfers (`grouped_route`). Your other takes go on; one grouped route is open at a time.
- Once `closed`, what is left continues from the first transfer's `continuable`, through a successor of the second, paid from your available balance.
## Moves and bridges
A move takes `amount_in` from one endpoint to another and follows every part under one ID. LaMarge's makers fill first, at the floor rate `min_out / amount_in`; an external bridge, [Relay](https://relay.link), carries the rest when LaMarge lacks liquidity or a route. Each part's floor is its share of `min_out`, rounded up.
[`GET /v1/moves/quote`](https://docs.lamarge.trade/api-reference/moves/quote) plans it: `lamarge` (a [route](#routes-through-another-venue) and its `budget`), `bridge` (an estimate), what neither carries (`unallocated`) and why a part is missing (`lamarge_unavailable`, `bridge_unavailable`). Nothing is reserved.
| Endpoint | LaMarge's part | Bridge from | Bridge to |
|---|---|---|---|
| `hyperliquid` | `funding: venue` | Perps, standard accounts: two signatures, no gas | Perps |
| `polymarket` | `funding: venue` | A withdrawal of pUSD to your wallet, then the wallet | The account, through calls on Polygon |
| `gmx` | `funding: venue` | A `transferOut` to your wallet, then the wallet | The account, through calls on Arbitrum |
| `aster` | Yes | — | The account, through calls on BSC; opens an unopened account |
| `lighter` | Yes | — | An existing account, by its index |
| `wallet`: HyperEVM USDC, Polygon pUSD or native USDC, Arbitrum USDC, BSC USDT | Wallet funding or delivery where the venue's chain offers it (not BSC) | Your wallet: an approval when short, then a deposit (gas) | The wallet |
1. [Create the move](https://docs.lamarge.trade/api-reference/moves/create) with its terms; the same `client_move_id` returns it.
2. Run LaMarge's part as a [transfer](https://docs.lamarge.trade/api-reference/transfers/create) with `move_id` (a route's first transfer only).
3. Once its payment is accepted (from a wallet: once paid), [create the bridge](https://docs.lamarge.trade/api-reference/moves/create-bridge) for the rest, and check every payload against its `order` before signing.
- From Hyperliquid: sign the nonce mapping and the `SendAsset` the order names, from the bridge's `source_dex` (`""` perps for a standard account, `spot` for a unified one), then [submit both](https://docs.lamarge.trade/api-reference/moves/sign-bridge).
- From a wallet: [fence](https://docs.lamarge.trade/api-reference/moves/report-bridge), approve the depository when [short](https://docs.lamarge.trade/api-reference/moves/bridge-funding), deposit, report each hash.
- From Polymarket or GMX: first move `amount_in` to your wallet with `move_id` (a [withdrawal](https://docs.lamarge.trade/api-reference/withdrawals/relay) or a [GMX withdrawal](https://docs.lamarge.trade/direct-transfers)), then bridge with `from_wallet`.
4. [Close the move](https://docs.lamarge.trade/api-reference/moves/close) with what no part carries. It is `settling` until every part is final, then `final`.
- LaMarge returns an `order` only when it pays and refunds no one but the move's payer and recipient, through the provider's pinned contracts, and its `id` is its hash. Check it again from your own terms before you sign, as the SDKs do: your signature should not rest on the API alone.
- A Polymarket, GMX or Aster account receives the bridge's whole output, at least `account_credit`, the part's floor (Polymarket: at least 5 pUSD); `wallet_surplus` is zero.
- Bridge states: `prepared`, `submitting`, `pending`, then `completed`, `refunded` (`refund` says what and where) or `stuck` (contact the provider with `request_id`); `failed` and `expired` debited nothing. A fenced deposit never expires: report `unsent` only when the wallet refused before broadcasting.
- The provider's solver holds the funds between the deposit and the fill or the refund; LaMarge never holds them and signs nothing for you. Refunds go to the payer, or on the destination chain to the recipient, in an asset the provider chooses.
- Not bridged yet: from Lighter, from Aster, from a portfolio-margin Hyperliquid account (`hyperliquid_mode`). LaMarge's own part still serves them.
## Deadlines and outcomes
| Field | Default | Meaning |
|---|---|---|
| `pay_by` | 45 s; 90 s from preparation for a grouped Aster first take; 150 s for a grouped route's second take and a take signed at once with its withdrawal | The payment is locked, or its venue transfer signed, by then |
| `t1` | `pay_by` + 120 s; 60 minutes after the take when paid from Lighter or Aster | Into an escrow venue, the delivery lands by then: the escrow refuses it later, and an undelivered payment returns at once |
| `t2` | 120 minutes | The payment becomes refundable by anyone, and no longer claimable |
- Defaults count from the take's preparation. `/v1/info` reports the deployment's timings (`pay_window_seconds`; `route_pay_window_seconds` for a grouped route's second take and a take signed at once); each fill carries its own.
- A fill delivered on Lighter or Aster adds `maker_accept_by`, `deliver_by` and `report_by` ([deadlines](https://docs.lamarge.trade/market-making#deadlines)).
- Admission stops while chain observations, escrow integrity, operator gas or relay capacity are not ready (`OPERATOR_UNAVAILABLE`).
A fill ends `SETTLED`, `EXPIRED`, `REFUNDED`, `TAKER_LOSS` or `MAKER_LOSS`. `payment_leg` and `maker_leg` give each side's state.
- `MAKER_LOSS`: a delivery whose payment was refunded unclaimed.
- `TAKER_LOSS`: a payment that could no longer return (executed on Lighter or Aster, or claimed early) and was not delivered by `t1`.
Each fill is delivered on its own, so a take can settle in part.
- A fill undelivered into an escrow venue by `t1` is abandoned. LaMarge returns its payment to the payer's available balance at once, or, from a minute before `t2`, by the ordinary refund after it.
- A fill abandoned on Lighter or Aster, its delivery not reported in time, returns early only with its maker's consent. The maker [prepares](https://docs.lamarge.trade/api-reference/takes/prepare-refund) it, verifies both chains, signs `RefundPayment` with its wallet and [submits](https://docs.lamarge.trade/api-reference/takes/refund) it with its master session. It credits the payer's available balance on the source chain; otherwise the payment waits for `t2`.
- If the operator stops, payments and claims are recoverable on chain ([recovery](https://docs.lamarge.trade/recovery)).
A fee replacement changes a transaction's hash: follow the resource's state, not the first hash.
## Signing
SIWE and link messages, `lighter_api_key` and `lighter_transfer` use `personal_sign`. Every other item uses EIP-712, `aster_transfer` at chain 1666. An authenticated response is no reason to sign: compare each item with your own request and configuration first. `@lamarge/sdk/protocol` implements these checks.
- Escrow items (`fund`, `quote_set`, `pay_take`, `refund_payment`, `escrow_withdrawal`, `close_orders`) use domain `LaMarge`, version `1`, their venue's escrow chain and the escrow pinned for it ([deployment values](#deployment-values)). `close_orders` always uses HyperEVM's.
- A fill delivered on Lighter or Aster has its `pay_take` and `refund_payment` in the paying venue's domain.
- A Lighter or Aster pool's `quote_set` uses that venue's chain ID and contract from the deployment values (Lighter's contract, Aster's vault), where nothing is sent, with the pool's linked address as `owner`. Each quote names its destination's chain, token and your linked account there.
A `quote_set` signs, under `primaryType` `QuoteSet`:
```
QuoteSet(address owner,bytes32 offerId,uint64 sequence,uint64 expiresAt,Quote[] quotes)Quote(string venue,uint256 chainId,address token,address recipient,uint256 supply,uint256 receive,uint256 minFill)
```
| Kind | Signer | Check |
|---|---|---|
| `permit` | Linked account | Hyperliquid, Polymarket and GMX only; the venue's token domain; `owner` the account, `spender` the escrow, `value` 2²⁵⁶ − 1, `deadline` within ten minutes |
| `margin_move` | Linked account | One venue withdrawal to the account itself, of `funding.venue_amount` in a maker preparation rounded up to whole millionths, timestamped within a minute of now |
| `fund` | Pool owner | `offerId` the pool ID, `amount` the preparation's, `deposit` = `wallet_amount + venue_amount`, `quoteSigner` yours, `operator` the reviewed one, `minQuoteSequence` above the pool's `last_sequence` (the preparation's `sequence` when it has one), `deadline` within an hour |
| `quote_set` | Pool's quote signer, an EOA key | `owner` and `offerId` the pool's, `sequence` above `last_sequence`, `expiresAt` = `valid_until + maker_timeout_seconds + 1`; exactly the destinations you asked, each with its venue's chain ID and token, your linked account there as `recipient`, and your `supply`, `receive` and `minFill`; in a maker preparation, the pool's other quotes rescaled to what remains |
| `pay_take` | Payer | `deposit` at most the total paid; one `LockPayment` per fill with its amount, maker recipient, hashlock, `pay_by` as `deadline`, `t2` as `refundAt`, pool, sequence, output and your receiving account, chain, token and escrow, of the same environment as the paying escrow |
| `refund_payment` | Payment beneficiary | `payer` and `swapId` identify the locked payment; `deadline` within an hour and no later than `t2`; the fill is delivered on Lighter or Aster, its `maker_leg` `ABANDONED`, no delivery accepted. Consenting gives up this payment |
| `escrow_withdrawal` | Pool owner | `offerId` the pool (zero for the available balance), `amount` and `toMargin` as asked, `deadline` within an hour |
| `close_orders` | Master | `account` the master, only the pools you listed, `deadline` within an hour |
### Deployment values
Pin these from this page, never from `/v1/info` or `/v1/venues`.
| | Dev | Production |
|---|---|---|
| Operator | `0xa7Fa4Ed0956d9C2E870D8743190a2d99473CAeF2` | `0x3Ce4125098E3c2902Df2e05d7608b14D3b33fEfa` |
| Escrow on HyperEVM (999) | `0x948E65c40442d935d4ee990BDbD01BdD825c4873` | `0x3100b7b49C0F9631c6AF25877b5A4E13a47AFad6` |
| Escrow on Polygon (137) | `0xA3FCA394739Ec4B984e908BD7A3c3b72d0ED77D1` | `0x3100b7b49C0F9631c6AF25877b5A4E13a47AFad6` |
| Escrow on Arbitrum (42161), GMX | `0x66e4C25D7e92c3E2765b021a748e740F775AC112` | `0x7b0c3eb38153614452A56bc9295D1bD084a9190A` |
| `maker_timeout_seconds`, `taker_timeout_seconds` | 3600, 7200 | 3600, 7200 |
| Aster agent name | `LaMargeDev` | `LaMarge` |
| Lighter API key index | 253 | 254 |
| Venue | Chain ID | Token |
|---|---|---|
| Hyperliquid | 999 | USDC `0xb88339CB7199b77E23DB6E890353E22632Ba630f` |
| Polymarket Perps | 137, `Withdraw` domain `0xdca4af75705dbb50f62437045aff9921947917d2` (signing terms only) | pUSD `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB`; native USDC `0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359` for wallet delivery, conversion and direct deposits |
| Aster | 56, vault `0x128463A60784c4D3f46c23Af3f65Ed859Ba87974` (signing terms only) | USDT `0x55d398326f99059fF775485246999027B3197955` |
| Lighter | 304, contract `0x3B4D794a66304F130a4Db8F2551B0070dfCf5ca7` | USDC `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`, as named in quotes and payments; nothing is sent there |
| GMX | 42161 | USDC `0xaf88d065e77c8cC2239327C5EDb3A432268e5831` |
# Market making
Source: https://docs.lamarge.trade/market-making
A maker supplies one venue from a [pool](https://docs.lamarge.trade/concepts#venues-and-funds) and prices it for the others with [quote lines](https://docs.lamarge.trade/how-it-works#quote-lines). What a take asks of the maker depends on the pool venue's `settlement` in [`GET /v1/venues`](https://docs.lamarge.trade/api-reference/market-data/list-venues).
| | Passive | Active |
|---|---|---|
| Venues | `escrow` | `venue`: Lighter, Aster |
| Capital | Funded into the escrow | Stays in the maker's account on the venue |
| After a take | Nothing: the operator settles | The bot accepts, delivers and reports each fill |
| Who | Any user with access, in the app or the API | Makers LaMarge approved, through the API |
| Bot offline | Reserved fills still settle | Fills expire unaccepted; paid fills are abandoned |
| Cost per fill | None: LaMarge pays the gas | The venue's transfer fee: per account on Lighter, none on Aster |
Steps over HTTP: [maker quickstart](https://docs.lamarge.trade/maker-quickstart). In TypeScript: [SDK](https://docs.lamarge.trade/sdk#market-making).
## What to follow
| Question | Field |
|---|---|
| How much can this pool quote now? | `available_to_quote` on [the order](https://docs.lamarge.trade/api-reference/orders/list-orders) |
| How much is mine, and how much can I move? | `holdings.total`, `holdings.available`, `holdings.locked` per venue in [`GET /v1/balances`](https://docs.lamarge.trade/api-reference/account/balances) |
| What is reserved and not delivered yet? | `maker_reserved`, then `maker_delivered_unpaid` until paid, in [`GET /v1/me/exposure`](https://docs.lamarge.trade/api-reference/account/exposure); Lighter and Aster rows have `chain_id` null |
Where a pool's funds are: `held` and `held_in` ([balances](https://docs.lamarge.trade/how-it-works#balances)).
## Passive market making
1. [Fund a pool](https://docs.lamarge.trade/maker-quickstart#fund-a-pool).
2. [Publish quote lines](https://docs.lamarge.trade/maker-quickstart#quote) and keep the lease alive.
3. For each fill, the operator waits for the taker's payment to be final, pays the taker from your pool, then claims the payment for you ([deadlines](https://docs.lamarge.trade/how-it-works#deadlines-and-outcomes)).
- GMX's escrow on Arbitrum acts at the chain's head, without waiting for Ethereum finality: a payment the sequencer later reorders away is not undone. Price that risk in your GMX quotes.
- A taker paying from Lighter or Aster pays your linked account there; the server reads that transfer before the delivery. On Lighter it accepts transfers the sequencer executed before Ethereum proves them; the deployment's fill cap bounds that risk.
- Your pool pays deliveries the operator vouches for, under your signed quotes: the escrow cannot see the payment on the other chain ([trust model](https://docs.lamarge.trade/how-it-works#trust-model)).
- Once a fill is delivered (`maker_leg` `CLAIMED`), its `secret` is in your fills ([`GET /v1/fills`](https://docs.lamarge.trade/api-reference/takes/list-fills)). It lets you claim the payment yourself ([recovery](https://docs.lamarge.trade/recovery#claim-a-payment)).
- Release capital through the API ([releasing capital](https://docs.lamarge.trade/how-it-works#releasing-capital)), or on chain after a one-day notice ([recovery](https://docs.lamarge.trade/recovery#withdraw-a-pool)).
## Active market making
The maker delivers each fill itself, by a transfer inside Lighter or Aster:
1. The taker signs. Each fill delivered on Lighter or Aster gets `maker_accept_by`, at most 15 seconds later.
2. The maker accepts it with [`POST /v1/fills/{id}/accept`](https://docs.lamarge.trade/api-reference/takes/accept). The taker's payment waits for every fill of the take to be accepted; one missed deadline expires the whole take unpaid.
3. The operator reserves the fills (`RESERVED`) and sends the payment. Once it is locked and verified, the fill is `PAID` with `payment_verified_at` set.
4. The maker transfers `amount_out` to `delivery_to`, executed by `deliver_by`.
5. The maker reports the transfer with [`POST /v1/fills/{id}/delivery`](https://docs.lamarge.trade/api-reference/takes/delivery) before `report_by`.
6. The operator claims the payment for the maker. The fill's `secret` lets the maker claim it too ([recovery](https://docs.lamarge.trade/recovery#claim-a-payment)).
An accepted fill is owed, even if you cancel your quotes or close the pool afterwards: accept only what the bot can deliver. A fill whose quotes you cancelled before accepting cannot be accepted (409) and expires unpaid. A retried acceptance of an accepted fill answers 204.
### Before quoting
1. Sign in once with your master address, then ask LaMarge on [Telegram](https://t.me/+EIYDGC_NT4kxZDRk) or [Discord](https://discord.gg/Cz3H7Q6xGu) to approve it (and to grant access while access is by invitation). Unapproved, a pool or line preparation answers `MAKER_NOT_APPROVED`.
2. On each escrow venue you buy on, link an account and complete its [setup](https://docs.lamarge.trade/quickstart#set-up-venue-accounts). It is the `recipient` of your quotes there.
3. Hold the inventory in an account owned by a dedicated address. Its key signs every delivery from the bot's host, where the master key never goes. It can withdraw the whole account: keep there only what the bot may deliver.
4. On Lighter, register an API key for that account with Lighter's `ChangePubKey`, signed by the owner, at an unused index from 4 to 252 (253 and 254 are LaMarge's). Read the account's fee per transfer ([how](https://docs.lamarge.trade/maker-quickstart#deliver-on-lighter)): 0 or 1 USDC so far; the order's `delivery_fee` shows the fee the server last read. A Standard account allows 60 requests a minute.
5. Open the pool with [`POST /v1/maker/{venue}/prepare`](https://docs.lamarge.trade/api-reference/maker/prepare), `"funding_source":"venue"`. Nothing is signed: the preparation is `complete` and the pool `live` at once. One account backs one pool.
6. Publish [quote lines](https://docs.lamarge.trade/how-it-works#quote-lines): the pool's venue with `sell` and `stock`, and a `buy` price on each escrow venue you receive on.
`amount` is a cap that deliveries consume. Within it, the pool offers what the account could transfer at the last balance read, less `delivery_fee` for each reserved fill and the next one; nothing once that read is two minutes old.
### Bot loop
1. Renew the lease and publish lines. A pool whose identity's lease was last renewed over two minutes ago leaves the book; back, the bot signs its quotes again.
2. Follow the identity's fills over the [stream](https://docs.lamarge.trade/streaming#websocket), from a snapshot.
3. Accept each fill with `maker_accept_by` set and `maker_accepted_at` null, before `maker_accept_by`, while it can deliver.
4. Deliver each `PAID` fill with `payment_verified_at` set, the earliest `deliver_by` first: one transfer of `amount_out` to `delivery_to`, never a second for the same fill ([Lighter](https://docs.lamarge.trade/maker-quickstart#deliver-on-lighter), [Aster](https://docs.lamarge.trade/maker-quickstart#deliver-on-aster)).
5. Report each executed transfer (on Aster, its `transferId`).
6. When it cannot deliver, stop accepting and stop quoting first.
7. To stop: stop accepting, cancel quotes, then keep delivering and reporting until no accepted fill is owed anything.
The SDK's [`AsterDeliverer` and `LighterDeliverer`](https://docs.lamarge.trade/sdk#quote-and-deliver) do steps 3 to 5 and accept only while their journal saves and no delivery's outcome is unknown.
A fill to accept, then deliver, as [`GET /v1/fills`](https://docs.lamarge.trade/api-reference/takes/list-fills) returns it (fields the bot reads):
```json
{
"id": "01a1379c-2f6e-7d3a-9b1e-5c0d2a7f4e81",
"role": "maker",
"state": "PAID",
"to_venue": "lighter",
"payment_leg": "LOCKED",
"maker_leg": "NONE",
"maker_accept_by": "2026-10-14T10:00:04Z",
"maker_accepted_at": "2026-10-14T10:00:01Z",
"payment_verified_at": "2026-10-14T10:00:05Z",
"amount_out": "250000000",
"delivery_to": "731033",
"deliver_by": "2026-10-14T10:02:30Z",
"report_by": "2026-10-14T11:49:45Z",
"delivery_fee": "0",
"delivery_hash": null
}
```
### Deadlines
Each fill carries its deadlines: read them, never compute them. `settlement.delivery` in [`/v1/info`](https://docs.lamarge.trade/api-reference/market-data/info) gives the deployment's offsets and `min_status`, the Lighter status a delivery needs.
| Deadline | Default | For | If missed |
|---|---|---|---|
| `maker_accept_by` | 15 s after the taker signs, at most `pay_by` | The maker's acceptance | The whole take expires unpaid |
| `pay_by` | 45 s after the take ([others](https://docs.lamarge.trade/how-it-works#deadlines-and-outcomes)) | The taker's payment | The fill expires; nothing is owed |
| `deliver_by` | `pay_by` + 2 minutes | The maker's transfer executes | A later transfer never counts: the maker's loss |
| Abandonment | `deliver_by` + 10 minutes | An accepted report | `maker_leg` becomes `ABANDONED`; the payment returns to the taker after `t2`, or earlier with the maker's consent |
| `report_by` | `t2` − 10 minutes | The report of a transfer executed by `deliver_by` | The payment returns to the taker; the transfer is the maker's loss |
A report is accepted until `report_by`, also once the leg is `ABANDONED`. Consenting to an early refund ([`refundPayment`](https://docs.lamarge.trade/sdk#withdrawals-and-refunds)) gives up the payment, and no report is accepted after it: check your journal and the venue first.
With Lighter's Python or WebAssembly signer, which cannot set the expiry at `deliver_by`, send nothing within a minute of `deliver_by`.
A refused report with `425` or `502` is sent again with the same hash; `400` and `409` are final, except `not_due` before the payment locks ([reasons](https://docs.lamarge.trade/api-reference/takes/delivery)).
### Retiring a pool
1. Close it with [`POST /v1/closes`](https://docs.lamarge.trade/api-reference/closes/request-close); sign `close_orders` unless its `held` is 0.
2. It closes at once when `held` is 0, otherwise once no fill awaits delivery. Accepted fills stay owed; reports are accepted until each fill's `report_by`.
A later preparation adds its `amount` to a live pool's cap and keeps its quotes. On a closed pool it reopens it without quotes, with a cap of what it delivered plus that `amount`.
LaMarge can withdraw an approval: the maker's pools leave the books at once; fills already reserved stay owed.
# Streaming and replay
Source: https://docs.lamarge.trade/streaming
## Snapshot, then replay
1. Read [`/v1/snapshot`](https://docs.lamarge.trade/api-reference/events/public-snapshot) for public books, or [`/v1/me/snapshot`](https://docs.lamarge.trade/api-reference/events/private-snapshot) with a session or `read` credential for your open orders, open fills and quote identities. Store its `cursor` with that state.
2. Replay events after the cursor over HTTP or WebSocket.
3. Apply each page in order, then persist your state and `next_cursor` together.
- Each event carries its resource's `revision`: skip revisions already applied.
- Its `data` is rendered when it is published, never older than the snapshot it follows.
- Events signal changes; a state can change more than once between two events.
- Snapshot and event rows are summaries. Read [`GET /v1/orders/{id}`](https://docs.lamarge.trade/api-reference/orders/get-order) for `last_sequence`, `available_to_quote` and `quote_set` before preparing a set.
- Above 1,000 rows a snapshot answers `503 SNAPSHOT_TOO_LARGE`: stop quoting. History pages cannot replace its cursor.
In TypeScript, [`changes`](https://docs.lamarge.trade/sdk#event-feed) does all three, WebSocket first and HTTP replay between connections.
## HTTP replay
```sh
curl "$API_URL/v1/me/events?after=$CURSOR&limit=100" -H "Authorization: Bearer $MAKER_TOKEN"
```
- A page can hold zero events with `has_more: true`: each request scans at most 1,000 journal positions. Always continue from `next_cursor`.
- Cursors are globally ordered decimal strings, with gaps between a subscriber's events.
- A cursor below the retained range or ahead of the journal answers `410 RESYNC_REQUIRED`: replace local state from a fresh snapshot.
## WebSocket
Connect to `wss://api.lamarge.trade/v1/stream` and send, within five seconds:
```json
{"token":"mk_PRIVATE_BEARER","after":"1234"}
```
- Omit `token` for public events only.
- Frames have the HTTP page shape. The server sends a page at least every 500 ms, even if empty.
- Any client message other than a ping or pong closes the stream, as does a frame that cannot be sent within five seconds. An invalid subscription closes it without a control frame.
A control frame with a `reason` can precede closure:
| `type` | Client action |
|---|---|
| `resync_required` | Fetch a fresh snapshot, replace local state, resume at its cursor |
| `authentication_required` | Stop authenticated activity; get a valid session or credential |
| `unavailable` | Keep the processed cursor; reconnect with backoff |
After a disconnection, resume from the last processed page's cursor, not the last received. Each `balance.changed` only says to refetch `/v1/balances`: a replay may omit a venue balance's earlier ones that moved no funds, never its latest. Only the initial authentication counts against the request budget. During a stream outage, stop renewing quotes on stale state: let the lease expire, or cancel.
## Event kinds
| Kind | Meaning |
|---|---|
| `book.changed` | Public: the `data.from` → `data.to` book changed; empty `data` means every book. Refetch the book |
| `trade` | Public: a settled fill's venues and amounts |
| `order.changed` | Order `state`, `sequence`, `cancel_epoch`, `held` and `held_in` |
| `fill.changed` | Fill state, role, legs, `from_venue` and `to_venue`, deadlines; for a delivery on Lighter or Aster, `maker_accept_by`, `maker_accepted_at`, `deliver_by`, `report_by`, `delivery_to`, `delivery_hash`, `delivery_fee` and `payment_verified_at` |
| `lease.changed` | Identity generation, lease and credential expiry, admission status |
| `balance.changed` | Observation times; refetch `/v1/balances` with a session |
| `withdrawal.changed` | Withdrawal state, amount and venue reference |
- `occurred_at` is the originating change's time.
- Private streams include public events. A credential sees only its own identity's orders, maker fills and lease.
- Streams never carry bearers, transaction bytes, signatures or secrets.
A quoting bot reacts to:
- `order.changed` not `live`, or with a null `sequence`: the order is off the book. Once it is `live`, reread it and publish a new set. A new `cancel_epoch` voids drafts prepared before it.
- `fill.changed` with `role: "maker"`: a reservation or its outcome changed the order's inventory; reread the order before sizing the next set.
- `lease.changed` with `active: false`: the lease lapsed, the credential ended or LaMarge disabled its quoting (renewal answers `403 FORBIDDEN`). Renew the lease, which advances the generation, and publish again; or stop.
- `fill.changed` for a Lighter or Aster pool with `maker_accept_by` set and `maker_accepted_at` null: accept it before `maker_accept_by` if you can deliver it; once `PAID`, deliver it ([bot loop](https://docs.lamarge.trade/market-making#bot-loop)).
Keep your own timers for admission deadlines and reconcile periodically even while connected.
## History
[Order](https://docs.lamarge.trade/api-reference/orders/history), [fill](https://docs.lamarge.trade/api-reference/takes/history), [withdrawal](https://docs.lamarge.trade/api-reference/withdrawals/history) and [trade](https://docs.lamarge.trade/api-reference/market-data/history) history pages use opaque backward cursors, unrelated to event cursors. Rows show current state: use [`GET /v1/orders/{id}`](https://docs.lamarge.trade/api-reference/orders/get-order) or [`GET /v1/takes/{id}`](https://docs.lamarge.trade/api-reference/takes/get-take) for signing and transaction details, and event replay for forward changes.
[`GET /v1/takes/history`](https://docs.lamarge.trade/api-reference/takes/complete-history), with a master session, pages whole takes with all their fills: use it for complete transfer receipts. [`GET /v1/fills`](https://docs.lamarge.trade/api-reference/takes/list-fills) lists only open fills and the last 50 final ones. A transfer's `take_final` tells when its take has ended.
# Direct transfers
Source: https://docs.lamarge.trade/direct-transfers
A direct transfer is a transaction your wallet sends, paying the gas: a deposit to the escrow, a GMX withdrawal to GMX's MultichainTransferRouter. No quote, no maker.
| `kind` | `venue` | `token` | Moves |
|---|---|---|---|
| `deposit` | `hyperliquid` | HyperEVM USDC | Wallet → the recipient's Hyperliquid account |
| `deposit` | `gmx` | Arbitrum USDC | Wallet → the recipient's GMX Account |
| `deposit` | `polymarket` | pUSD, or native USDC converted to pUSD | Wallet → the recipient's Polymarket Perps account |
| `withdrawal` | `gmx` | Arbitrum USDC | Your GMX Account → your wallet |
Tokens: [deployment values](https://docs.lamarge.trade/how-it-works#deployment-values).
- Offer a new one only where [`GET /v1/venues`](https://docs.lamarge.trade/api-reference/market-data/list-venues) shows `chain.direct_deposit` (or `chain.direct_withdrawal`) true; native USDC on Polygon also needs `chain.wallet_funding.conversion`.
- `owner`, the payer, is the master or the account linked on `venue`. A deposit's `recipient` is an account linked on `venue`, its receiving [setup](https://docs.lamarge.trade/quickstart#setup-steps) done: the venue's owner address, never a deposit address or a Polymarket wallet. A withdrawal's recipient is `owner`.
- `min_out` equals `amount`, except for native USDC on Polygon: at least 0.01 USDC in, and `min_out`, the least pUSD deposited, at least `ceil(amount × 9,995 / 10,000)`. A deposit's `min_out` reaches the venue's `release_minimum`.
- Hyperliquid and Polymarket withdrawals and sends use [margin transfers](https://docs.lamarge.trade/how-it-works#margin-transfers); cross-venue transfers use [takes](https://docs.lamarge.trade/how-it-works#takes), with [wallet funding](https://docs.lamarge.trade/how-it-works#wallet-funding) and [wallet delivery](https://docs.lamarge.trade/how-it-works#wallet-delivery) when needed.
## With the SDK
```ts
import { directTransfer } from "@lamarge/sdk/direct";
// client: signed in; signer: with sendTransaction; store: a durable SignatureStore.
const operation = await directTransfer(client, signer, {
client_operation_id: savedOperationId,
kind: "deposit",
venue: "polymarket",
owner: signer.address,
recipient: linkedPolymarketOwner,
token: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", // native USDC
amount: "10000000",
min_out: "9995000",
}, { store });
console.log(operation.state);
```
- Persist `client_operation_id` first. Resume with the same request and store: `directTransfer` reconciles a `pending` operation and never sends again after an unknown prompt or a lost answer.
- It checks the operation against the request and the pinned deployment, reads the funds, approves exactly `amount` only when the allowance is short, then sends the transaction. `beforeSigning` runs before each prompt (`step` `approve`, `deposit` or `withdrawal`); one that throws sends nothing.
- `signer.sendTransaction` calls its hash callback once broadcast and resolves once mined.
- `inspectDirectTransaction(transaction, owner, now?, recipient?)` checks, in an isolated signer, that a transaction is a direct call from `owner`, a deposit crediting `recipient` (`owner` by default), and returns its terms. It reads the chain, contract and calldata only: refuse a transaction with a non-zero native value yourself.
- The Rust SDK runs the same steps: `session.direct_transfer(&DirectRequest::deposit(..)?, &sender)`, its transactions sent through your `TransactionSender` ([Rust SDK](https://docs.lamarge.trade/rust-sdk)).
## Over HTTP
1. [`POST /v1/direct`](https://docs.lamarge.trade/api-reference/direct/create) with the request: it returns the operation, `prepared`, with its `escrow`, `nonce` and `deadline` (30 minutes ahead). The same `client_operation_id` and terms return the same operation.
2. [`GET /v1/direct/{id}/funding`](https://docs.lamarge.trade/api-reference/direct/funding) reads `balance` and `allowance` now. For a deposit, approve `amount` of `token` to the escrow when the allowance is short.
3. Before the wallet prompt, [post](https://docs.lamarge.trade/api-reference/direct/report) an empty body: it moves `prepared` to `pending` once, across tabs and devices. After a lost answer, never prompt again.
4. Send the transaction from `owner`: a deposit is `directDeposit(recipient, token, amount, min_out, nonce, deadline)` on the escrow; a GMX withdrawal is `transferOut` on GMX's MultichainTransferRouter ([margin transfers](https://docs.lamarge.trade/how-it-works#margin-transfers)).
5. Report each broadcast `tx_hash`, replacements included, to the same route, at most eight distinct hashes.
6. [`GET /v1/direct/{id}`](https://docs.lamarge.trade/api-reference/direct/get) until `confirmed`, `failed` or `expired`.
## Outcomes
- `confirmed`: final on chain, `received` the amount moved. Hyperliquid credits HyperCore afterwards: read the venue before spending it.
- `expired`: a deposit not executed by its `deadline`, or a withdrawal never sent, once the chain is read past it.
- `failed`: the reported withdrawal reverted.
- A deposit is found by its nonce, reported or not.
- A GMX withdrawal has no nonce: once `pending`, it stays so until its hash is reported and found final. Never send another one because it is slow.
# Recovery without LaMarge
Source: https://docs.lamarge.trade/recovery
Each call goes to the escrow of the chain that holds the funds ([deployment values](https://docs.lamarge.trade/how-it-works#deployment-values)), sent by you, paying the gas. `0x0…0` is the 32-byte zero ID: the available balance.
## Withdraw the available balance
`withdrawOffer(0x0…0, amount)`, from the owner, at any time. Tokens left at your deposit address join it first with `sweepDeposit(owner)`, which anyone can send.
## Withdraw a pool
1. `requestExit(orderId)` from the owner starts a one-day notice.
2. Once `exitAt(owner, orderId)` has passed, `withdrawOffer(orderId, amount)`. Before it, the call reverts with `TooEarly`.
- Asking again restarts the notice; nothing ends it.
- LaMarge stops quoting the pool when it reads the request, never funds it again, and releases it to your venue margin once its fills are delivered.
- Your next capital preparation opens a new pool.
- After the notice, the owner or the quote signer can also call `raiseQuoteFloor(owner, orderId, sequence)` to revoke signed quote sets below `sequence` ([cancellation](https://docs.lamarge.trade/how-it-works#cancellation)).
## Refund a payment
After the fill's `t2`, anyone can send `refund(payer, 0x0…0, swap_id)`: the payment returns to the payer's available balance.
## Claim a payment
A delivered fill (`maker_leg` `CLAIMED`) shows its maker the `secret`. Before `t2`, anyone can send `claimBatch([{owner: payer, offerId: 0x0…0, swapId: swap_id, secret}])` on the escrow of the fill's `from_venue`. It credits only `maker_recipient`'s available balance.
## Retired escrows
Funds left on a retired escrow stay there; recover them with the same calls on that contract.
| Escrow | Chains | Address | Calls |
|---|---|---|---|
| v5 | HyperEVM, Polygon, BSC | `0xEa5BA9e1C0F5Dde572bc08F3Af6A3e8B9dB73734` | `withdrawOffer(offerId, amount)`, `refund(owner, offerId, swapId)` |
| Production proxy | BSC | `0x3100b7b49C0F9631c6AF25877b5A4E13a47AFad6` | As v5 |
| v4 | HyperEVM, Polygon; BSC | `0xe0384a3026d52120c20c12ceb33e73096e1d2eca`; on BSC `0xf0946794b2932ca342e68a9fd54ad30e5ff952e3` | `withdrawOffer(offerId, amount)`, `refund(owner, swapId)` |
| v3 | HyperEVM, Polygon | `0x0eb336fb2a53743428cbe40902f284f89b762c68` | As v4 |
| v2 | HyperEVM, Polygon | `0x71b8e402257bffd288d6f733711cf2b10f0c0347` | As v4 |
| v1 | HyperEVM, Polygon | `0xf0946794b2932ca342e68a9fd54ad30e5ff952e3` | As v4 |
- v1 to v3 have no available balance (offer ID zero).
- A refunded payment goes to the payer's wallet on v1 to v4, to the payer's available balance on v5.
- A refunded maker lock returns to its offer: then `withdrawOffer`.
# TypeScript SDK
Source: https://docs.lamarge.trade/sdk
```sh
npm install @lamarge/sdk viem
```
[`@lamarge/sdk`](https://www.npmjs.com/package/@lamarge/sdk) runs in browsers, Bun and Node 22.12 or later. It ships ESM only, depends on `@noble/hashes` (keccak256 for Polymarket operations), takes `viem` as an optional peer dependency and is MIT licensed. Source: [snowbl-capital/lamarge-sdk-ts](https://github.com/snowbl-capital/lamarge-sdk-ts).
Before a signer sees anything, the SDK:
- checks every [`to_sign`](https://docs.lamarge.trade/how-it-works#signing) item against your request and the [deployment values](https://docs.lamarge.trade/how-it-works#deployment-values) it pins;
- stores each payment, funding and withdrawal signature, so a restart submits it again instead of signing anew;
- keeps [client IDs](https://docs.lamarge.trade/api-reference/overview#retries-and-recovery) stable across retries.
| Entry | Contents |
|---|---|
| `@lamarge/sdk` | Every API operation by its `operationId`, sign-in, account setup, transfers, takes, withdrawals, `Maker`, `Quoter`, the event feed |
| `@lamarge/sdk/protocol` | The pinned deployments, the bridge provider's pins and every pre-signature check, for clients that sign on their own |
| `@lamarge/sdk/aster` | `AsterDeliverer`: an active maker's deliveries inside Aster. Needs `viem` |
| `@lamarge/sdk/lighter` | `LighterDeliverer`: an active maker's deliveries inside Lighter, signed by Lighter's own signer, which your application holds |
| `@lamarge/sdk/attestation` | `verifyAttestation`, `ATTESTERS`: check LaMarge's attestation of a request before signing it |
| `@lamarge/sdk/direct` | `directTransfer`, `inspectDirectTransaction`: [direct transfers](https://docs.lamarge.trade/direct-transfers), without a maker |
| `@lamarge/sdk/move` | `moveFunds`, `movePlan`, `bridge`, `waitForBridge`: [moves](#moves-and-bridges), LaMarge first and a bridge for the rest; `moveQuery`, `moveVenue`: a move's quote query and an endpoint's LaMarge venue |
## Client and signer
```ts
import { createClient, signIn } from "@lamarge/sdk";
import { privateKeyToAccount } from "viem/accounts";
const client = createClient({ apiUrl: "https://api.lamarge.trade" });
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
await signIn(client, account, "https://app.lamarge.trade");
const balances = await client.call("getBalances");
const book = await client.call("getBook", { query: { from: "hyperliquid", to: "polymarket" } });
```
- `client.call` reaches any operation by the `operationId` its API reference page shows. Path, query and body are typed.
- `signIn` checks the chains, permit domains and settlement [`/v1/venues`](https://docs.lamarge.trade/api-reference/market-data/list-venues) names against the pinned deployments, then signs the [challenge](https://docs.lamarge.trade/api-reference/authentication/challenge) for your app's origin. The client then carries the session.
- A credential goes in `createClient({ apiUrl, token: "mk_…" })`.
- A signer is an address with `signMessage` and `signTypedData`: a viem `LocalAccount`, a KMS key through viem's `toAccount`, or a browser wallet's two methods. An optional `prepare(chainId)` readies a browser wallet (switches its network) before an Aster transfer is issued again and signed, so the transfer's life starts once the wallet is ready. Paying from GMX, converting native USDC on Polygon or sending a [direct transfer](https://docs.lamarge.trade/direct-transfers), it also needs `sendTransaction({ chainId, to, data }, sent)`: it calls `sent(hash)` once broadcast, resolves with the hash once mined and rejects a refusal or a revert. A `transferOut` broadcast is not sent again for ten minutes; a `LocalAccount` only signs, so give it a viem wallet client's `sendTransaction` and `waitForTransactionReceipt` on Arbitrum.
- Answers are typed, not validated: an enum value a newer server adds still type-checks.
## Accounts
```ts
import { linkAccount, setUpVenue } from "@lamarge/sdk";
await linkAccount(client, account, "polymarket");
await setUpVenue(client, "polymarket", account);
```
- `linkAccount` [links](https://docs.lamarge.trade/quickstart#link) an account. An address other than the master signs the link challenge once the SDK checked it names that venue.
- `setUpVenue` runs each [setup step](https://docs.lamarge.trade/quickstart#setup-steps) the venue does not show yet, checks it, signs it and waits until the venue shows it. `onProgress` names each step as it starts and while it is `confirming`.
- `asterAgentName` and `lighterKeyIndex` pin your deployment's slots (`ENVIRONMENT_SLOTS`: `LaMarge` and 254 in production, `LaMargeDev` and 253 in dev). Registering another environment's slot would replace that environment's agent or key.
- An Aster agent approval lists at most eight public addresses or ranges, each no wider than IPv4 /24 or IPv6 /64.
## Taker script
Signs in, sets up both accounts, then transfers 250 USDC from Hyperliquid to Polymarket. Rerun it after any interruption: it resumes the same transfer.
```ts
// API_URL=https://api.lamarge.trade APP_ORIGIN=https://app.lamarge.trade PRIVATE_KEY=0x… bun taker.ts
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { createClient, linkAccount, setUpVenue, signIn, transfer, TransferPending, type SignatureStore } from "@lamarge/sdk";
import { privateKeyToAccount } from "viem/accounts";
const { API_URL, APP_ORIGIN, PRIVATE_KEY } = process.env;
if (!API_URL || !APP_ORIGIN || !PRIVATE_KEY) throw new Error("Set API_URL, APP_ORIGIN and PRIVATE_KEY");
const account = privateKeyToAccount(PRIVATE_KEY as `0x${string}`);
const client = createClient({ apiUrl: API_URL });
// The transfer ID and every signature survive a restart.
const FILE = "taker-state.json";
const state: Record = existsSync(FILE) ? JSON.parse(readFileSync(FILE, "utf8")) : {};
const persist = () => writeFileSync(FILE, JSON.stringify(state), { mode: 0o600 });
const store: SignatureStore = {
load: key => state[`signature:${key}`],
save: (key, value) => { state[`signature:${key}`] = value; persist(); },
delete: key => { delete state[`signature:${key}`]; persist(); },
};
await signIn(client, account, APP_ORIGIN);
for (const venue of ["hyperliquid", "polymarket"]) {
await linkAccount(client, account, venue);
await setUpVenue(client, venue, account);
}
try {
const fills = await transfer(client, account, {
client_transfer_id: "rebalance-1",
transfer_id: typeof state.transfer_id === "string" ? state.transfer_id : undefined,
from: "hyperliquid", to: "polymarket", amount_in: "250000000", min_out: "249500000",
recipient: account.address, funding: "venue",
}, { store, onIntent: intent => { state.transfer_id = intent.id; persist(); } });
for (const fill of fills) console.log(fill.id, fill.state, fill.amount_out);
} catch (error) {
if (!(error instanceof TransferPending)) throw error;
console.log(`Not done yet (${error.reason}): run again later`);
}
```
`transfer` returns the take's fills once the payment is accepted; each fill then settles on its own. Follow them with [`changes`](#event-feed) or [`GET /v1/takes/{id}`](https://docs.lamarge.trade/api-reference/takes/get-take).
## Transfers
- `funding: "wallet"` pays only from the signer's escrow-token wallet and available balance ([wallet funding](https://docs.lamarge.trade/how-it-works#wallet-funding)); a shortfall stops before anything is signed. A master signer needs no linked account on `from`. A resumed transfer keeps the funding it was created with. On Polygon it pays pUSD unless the request has [`conversion`](#polygon-native-usdc).
- `funding: "venue"` first [withdraws](https://docs.lamarge.trade/how-it-works#paying-from-venue-margin) what is short from the venue account. Lighter and Aster always pay from their account: use `"venue"`. From GMX that withdrawal is the signer's own `transferOut` transaction (the plan's `transfer_out` request), paid in ETH on Arbitrum; a signer without `sendTransaction` stops before anything is signed.
- Persist `client_transfer_id`, the transfer ID `onIntent` names and the `store`. The same request with `transfer_id` resumes it: a stored signature is submitted again, never replaced. `memoryStore()` is lost with the process.
- `TransferPending.reason`: `arrival_unconfirmed` or `authorization_unconfirmed` (funds or permit not seen within `arrivalWaitMs`) and `unknown` (withdrawal outcome): run again later. `refused`: the venue refused the withdrawal.
- `max_fee_bps` accepts the pair's taker fee up to that many basis points, as the book's `taker_fee_bps` shows it ([fees](https://docs.lamarge.trade/how-it-works#fees)). Without it, the take pays no fee.
- `destination: "wallet"` transfers the take's output to `recipient`, any address on `to`'s escrow chain, instead of the linked account ([wallet delivery](https://docs.lamarge.trade/how-it-works#wallet-delivery)); nothing is read or required about an account on `to`. The SDK checks the wallet tag of each `swap_id`, the signed `receiveRecipient`, the pinned wallet token and the take's `minimum_received` before signing. On a route it applies to the last take.
- `beforeSigning`, on `transfer`, `take`, `route`, `withdraw` and `setUpVenue`, runs your own checks on each request after the SDK's and before it is first signed. One that throws signs nothing.
- `lock`, on `transfer`, `take` and `route`, wraps each take from its first read to its submission. Share it across your processes or tabs.
- `take` alone prepares a take, checks and signs its payment, and submits it. `checkQuote` and `minimumTake` read a book as the server matches it, fee included.
### Amount limits and slippage
`bookLimits(book, options)` gives a direct book's smallest take and its sweep up to `budget` (the whole book without it): `minimum` and `maximum`, each `{ pay, out, parts }` in base units, or `null` when nothing fits. It counts maker minimums, `minimum` (the delivery floor), the fill cap and the fee, and leaves out expired levels and `own` orders. A payment from Lighter or Aster (`fee.onDelivery`) takes one part; others up to `maxParts`, 8 by default.
```ts
import { bookLimits, deliveryFloor, slippageMinimum, takeFee } from "@lamarge/sdk";
const from = "hyperliquid", to = "polymarket";
const [book, venues, orders] = await Promise.all([
client.call("getBook", { query: { from, to } }),
client.call("getVenues"),
client.call("getOrders"),
]);
const limits = bookLimits(book, {
own: new Set(orders.map(order => order.id)),
minimum: deliveryFloor(venues, to, "venue"),
fee: takeFee(from, book.taker_fee_bps, book.taker_fee_bps),
budget: 250_000_000n, // what the payer can spend, after withdrawal fees and other commitments
});
if (limits) console.log(limits.minimum.pay, limits.maximum.pay, slippageMinimum(limits.maximum.out, 10));
```
- The result is a snapshot that reserves nothing; amounts between `minimum` and `maximum` can fall in a gap left by minimum fills. Requote the chosen amount before signing.
- `slippageMinimum(out, bps)` rounds `out` less `bps` (an integer from 0 to 10,000) down: a `min_out`.
- Venue withdrawal fees are apart; on Aster, keep room for its debit rounded up to six decimals. A wallet delivery's least output is the prepared take's `minimum_received`.
- For a two-take route, [`GET /v1/routes`](https://docs.lamarge.trade/api-reference/market-data/get-route) with `amount_in` your budget answers what the route can spend now (`amount_in`, `capped` when below your budget) and `amount_out`, the intermediate venue and your own orders accounted for. `min_out` applies to the budget you ask and scales down with a capped input: pass `slippageMinimum(referenceOut, bps)`. It gives no route minimum.
### Polygon native USDC
Where `chain.wallet_funding.conversion` is set, a wallet-funded transfer from Polymarket pays from native USDC ([how it works](https://docs.lamarge.trade/how-it-works#native-usdc-on-polygon)):
```ts
import { conversionMinimum, transfer } from "@lamarge/sdk";
const usdc = 10_000_000n; // 10 native USDC
const budget = conversionMinimum(usdc).toString(); // the least pUSD credited, also the transfer's amount_in
await transfer(client, account, {
client_transfer_id: "polygon-usdc-1",
from: "polymarket", to: "hyperliquid", funding: "wallet",
amount_in: budget, min_out: "9985000", recipient: account.address,
conversion: { amount_in: usdc.toString(), min_out: budget },
}, { store, onIntent: intent => { state.transfer_id = intent.id; persist(); } });
```
- The signer needs `sendTransaction` and POL for gas. When the allowance is short it approves exactly `amount_in` of USDC to the escrow, then sends `convertDeposit`; `beforeSigning` sees each as `kind: "conversion"`, `step` `approve` or `convert`, with `amount` (USDC) and `minOut` (pUSD).
- The take starts once LaMarge reads the conversion final. Resume with the same `transfer_id` and `conversion`: an unknown wallet answer never sends a second conversion, even from a fresh store.
- Refunds and anything converted above `amount_in` stay in the available balance in pUSD.
### Routes
`route` runs a two-take plan from [`GET /v1/routes`](https://docs.lamarge.trade/api-reference/market-data/get-route) as two transfers:
1. The first, under your `client_transfer_id`, names the route's end in `then`.
2. Once it delivered on the intermediate venue, the second, under `client_transfer_id` + `.2`, pays what the server leaves to continue (`continuable`).
- `viaSigner` signs on the intermediate venue when its linked account is another address.
- Taken take by take, the second transfer signs from the intermediate venue: through Hyperliquid or Polymarket, `beforeSigning` sees its funding withdrawal (`kind: "withdrawal"`, `venue` the intermediate venue) before its take, also when the route started from Lighter or Aster.
- The same request with `transfer_id`, the first transfer's ID, resumes the route.
- `grouped: true` signs a [grouped route](https://docs.lamarge.trade/how-it-works#routes-through-another-venue) at once. An unavailable, aborted or expired attempt throws `RouteAbandoned` (`reason`, `transferId`, `commitBy`, `lateByMs`). Rerun with `grouped: false` to continue take by take.
## Moves and bridges
`moveFunds` moves `amount_in` from one endpoint to another as one [move](https://docs.lamarge.trade/how-it-works#moves-and-bridges): LaMarge's makers first, as far as they fill at the floor rate `min_out / amount_in`, an external bridge for the rest.
```ts
import { moveFunds } from "@lamarge/sdk/move";
const move = await moveFunds(client, account, {
client_move_id: "rebalance-2", from: { venue: "hyperliquid" }, to: { venue: "polymarket" },
amount_in: "10000000000", min_out: "9950000000", payer: account.address, recipient: account.address,
}, { store });
console.log(move.state, move.unallocated, move.bridges.map(bridge => `${bridge.id} ${bridge.state}`));
```
- An endpoint is `{ venue }`, an account, or `{ venue: "wallet", chain_id, token }`: USDC on HyperEVM (999) or Arbitrum (42161), pUSD or native USDC on Polygon (137), USDT on BSC (56). To Lighter, `recipient` is the account index, which Lighter must show owned by the signer or `lighterOwner`.
- The move follows its first quote. Its LaMarge part runs as `transfer` or `route`, the root transfer attached by `move_id`. The bridge starts once that part's debit is fixed: from Hyperliquid, after the first take's payment is accepted; from a wallet, once that payment executed (`PAID`). With `sequential: true`, a two-take route ends first, so one wallet never has a bridge request open while the route's second take asks for its own; a second take no book pays at the floor then stops the run with `MovePending` `route`, the bridge starting on the next run. A Polymarket origin first withdraws to the signer, a GMX one sends its `transferOut`, both attached to the move; the bridge then leaves that wallet.
- Every part counts against `amount_in` in the store before it starts, until its final state shows nothing debited. A LaMarge take that ends unpaid frees its share; what its funding withdrawal already moved is bridged from the wallet, never withdrawn again.
- `movePlan(client, request, store)` returns the plan the move follows, its first quote kept in the store: read it before `moveFunds` to choose the signer of the account between a LaMarge route's takes (`viaSigner`). That signer signs the route's second take and, through Hyperliquid or Polymarket, a withdrawal from there, whatever the move's origin. A refusal stops the move with the funds in that account.
- What no part carries closes the move as `unallocated`, with its reason (`below_minimum`, `insufficient_liquidity`…).
- Persist `client_move_id` and the `store`; the same request resumes. `MovePending.reason`: `payment`, `withdrawal` (funds not yet in the wallet), `route` (with `sequential`, a second take waiting for liquidity), or `bridge` (an approval of unknown outcome, or an unsigned quote expiring), as `TransferPending` from the LaMarge part: run again later.
- `bridge(client, signer, moveId, { terms, client_bridge_id, amount_in, from_wallet }, { store })` runs one bridge. It rebuilds and checks the provider's order against `terms` (`checkBridgeOrder` in `@lamarge/sdk/protocol`), then signs a HyperCore origin's nonce mapping and `SendAsset`, or sends a wallet's `approve` and deposit. `beforeSigning` sees each as `kind: "bridge"`, `step` `sign`, `approve` or `deposit`, with the `venue` the funds leave. The mapping is signed for Ethereum (chain 1), the send for HyperEVM's 999; each is stored as soon as given, so a run interrupted between them asks only for the send (`mapped: true`).
- A wallet origin needs `sendTransaction` and gas; it approves exactly `amount_in` only when short, and a deposit whose outcome is unknown is never sent again.
- `waitForBridge(client, id)` reads a bridge until it is [final](https://docs.lamarge.trade/how-it-works#moves-and-bridges).
## Withdrawals and refunds
With `client` and `account` from [client and signer](#client-and-signer):
```ts
import { canRefundPayment } from "@lamarge/sdk/protocol";
import { memoryStore, refundPayment, withdraw } from "@lamarge/sdk";
import { createPublicClient, http } from "viem";
import { hyperEvm, polygon } from "viem/chains";
await withdraw(client, account, { id: "withdrawal-1", venue: "hyperliquid", amount: 5_000_000n, to: "signer" }, { store: memoryStore() });
// Aster limits each chain on its own: pick one that can take the amount and its fee.
const { chains } = await client.call("getWithdrawalChains", { query: { venue: "aster" } });
const amount = 100n * 10n ** 18n;
const chain = chains.find(c => BigInt(c.withdrawable) >= amount + BigInt(c.fee));
if (chain) await withdraw(client, account, { id: "withdrawal-2", venue: "aster", amount, to: "signer", chain_id: chain.chain_id }, { store: memoryStore() });
const readers = { 999: createPublicClient({ chain: hyperEvm, transport: http() }), 137: createPublicClient({ chain: polygon, transport: http() }) };
for (const fill of await client.call("getFills")) {
if (canRefundPayment(fill)) await refundPayment(client, account, fill, readers);
}
```
- `withdraw` moves an exact amount from Hyperliquid, Polymarket or Aster to the signer, or from Polymarket to its venue wallet. An Aster withdrawal goes to BSC, or to the `chain_id` you pick from `getWithdrawalChains` (Arbitrum, Ethereum), each chain with its own limit and fee; Aster's fee comes on top, and the signer also signs the envelope Aster relays it in. With `to: "account"` and `recipient`, it sends to another account on Hyperliquid, Polymarket or Aster. The same `id` returns the withdrawal or resubmits its signature; a refused one needs a new `id`.
- `refundPayment` consents, as the maker, to return the payment of a fill abandoned on Lighter or Aster ([outcomes](https://docs.lamarge.trade/how-it-works#deadlines-and-outcomes)). It signs only once the payment's escrow, read through your viem `PublicClient` for that chain, shows the payment still locked. `canRefundPayment` (`@lamarge/sdk/protocol`) tells which fills qualify.
## Market making
Two keys on two hosts. `Maker` holds the financial key and provisions capital. `Quoter` holds a [credential](https://docs.lamarge.trade/api-reference/credentials/create) and the quote key, and quotes, accepts and reports deliveries.
### Provision
On the financial key's host, once. This opens an Aster pool that receives on Hyperliquid; LaMarge must [approve](https://docs.lamarge.trade/market-making#active-market-making) you first.
```ts
// API_URL=… APP_ORIGIN=… OPERATOR_ADDRESS=… MASTER_PRIVATE_KEY=0x… ASTER_OWNER_PRIVATE_KEY=0x… QUOTE_SIGNER_ADDRESS=0x… bun provision.ts
import { writeFileSync } from "node:fs";
import { createClient, Maker, setUpVenue } from "@lamarge/sdk";
import { privateKeyToAccount } from "viem/accounts";
const env = (name: string) => { const value = process.env[name]; if (!value) throw new Error(`Set ${name}`); return value; };
const master = privateKeyToAccount(env("MASTER_PRIVATE_KEY") as `0x${string}`);
const asterOwner = privateKeyToAccount(env("ASTER_OWNER_PRIVATE_KEY") as `0x${string}`);
const maker = new Maker(createClient({ apiUrl: env("API_URL") }), master, env("OPERATOR_ADDRESS"), env("APP_ORIGIN"));
await maker.login();
await maker.link("hyperliquid"); // receives the takers' payments
await setUpVenue(maker.client, "hyperliquid", master); // its permit
await maker.link("aster", asterOwner); // the pool's account, with LaMarge's agent
const credential = await maker.createCredential("bot", env("QUOTE_SIGNER_ADDRESS"));
await maker.addCapital({ venue: "aster", amount: "5000000000000000000", client_request_id: "aster-pool-1", funding_source: "venue" },
credential, { owner: asterOwner.address });
writeFileSync("credential.json", JSON.stringify(credential), { mode: 0o600 });
```
- Take `OPERATOR_ADDRESS` from the [deployment values](https://docs.lamarge.trade/how-it-works#deployment-values) and `APP_ORIGIN` from the [addresses](https://docs.lamarge.trade/api-reference/overview#addresses).
- `maker.link(venue, owner)` links `owner`'s account; on Aster it also approves LaMarge's agent for the API's environment.
- `addCapital(input, credential, { store, owner })` checks the [preparation](https://docs.lamarge.trade/how-it-works#maker-capital) before the financial key signs it. `store` keeps the signed preparation for a restart; `owner` is the address linked on Lighter or Aster that holds the pool. On an escrow venue, follow it with `waitForFunding(order)`.
### Quote and deliver
On the quoting host, with the credential, the quote key and the pool's keys; never the master key.
```ts
// API_URL=… QUOTE_PRIVATE_KEY=0x… ASTER_OWNER_PRIVATE_KEY=0x… ASTER_AGENT_PRIVATE_KEY=0x… HYPERLIQUID_ADDRESS=0x… bun bot.ts
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { createClient, Quoter, type Credential, type DeliveryJournal } from "@lamarge/sdk";
import { AsterDeliverer, type AsterDelivery } from "@lamarge/sdk/aster";
import { privateKeyToAccount } from "viem/accounts";
const env = (name: string) => { const value = process.env[name]; if (!value) throw new Error(`Set ${name}`); return value; };
const key = (name: string) => privateKeyToAccount(env(name) as `0x${string}`);
const credential: Credential = JSON.parse(readFileSync("credential.json", "utf8"));
const quoter = new Quoter(createClient({ apiUrl: env("API_URL"), token: credential.token }), credential, key("QUOTE_PRIVATE_KEY"));
const JOURNAL = "aster-deliveries.json";
const journal: DeliveryJournal = {
load: () => existsSync(JOURNAL) ? JSON.parse(readFileSync(JOURNAL, "utf8")) : {},
save: deliveries => { writeFileSync(`${JOURNAL}.tmp`, JSON.stringify(deliveries), { mode: 0o600 }); renameSync(`${JOURNAL}.tmp`, JOURNAL); },
};
const deliverer = new AsterDeliverer(key("ASTER_OWNER_PRIVATE_KEY"), key("ASTER_AGENT_PRIVATE_KEY"), journal);
const lines = [
{ venue: "aster", buy: null, sell: "1.0005", stock: "5000000000000000000" },
{ venue: "hyperliquid", buy: "1", sell: null, stock: "0" },
];
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
let quoting = true, stopping = false;
process.once("SIGINT", () => { stopping = true; deliverer.stopAccepting(); });
const feedStop = new AbortController();
const feed = quoter.fillFeed(feedStop.signal);
const delivering = (async () => {
for (;;) {
await deliverer.run(feed).catch(error => console.error(error)); // accepts, delivers, reports
if (!quoting && await deliverer.outstanding(quoter) === 0) return;
await pause(500);
}
})();
while (!stopping) {
await quoter.lease(30);
const live = deliverer.blocked ? lines.map(line => ({ ...line, stock: "0" })) : lines;
await quoter.publishLines(live, { hyperliquid: env("HYPERLIQUID_ADDRESS") }, Math.floor(Date.now() / 1000) + 25);
await pause(10_000);
}
await quoter.cancelAll();
quoting = false;
await delivering;
feedStop.abort();
```
- `new Quoter(client, credential, quoteSigner)` checks that `quoteSigner` is the credential's `quote_signer`.
- `publishLines(lines, recipients, validUntil)` prepares the identity's [quote lines](https://docs.lamarge.trade/how-it-works#quote-lines), rebuilds each pool's quote set from your lines, signs and publishes them: every pool switches at once. `recipients` names your linked address on each venue you buy on.
- `prepareLines(lines, recipients, validUntil)` returns the same checked drafts unsigned, for a quote key that signs elsewhere; publish their signatures with `client.call("publishQuoteLines", …)`.
- `cancelAll()` pulls every pool's quotes. To pull one venue, publish its line with `stock: "0"`.
- `accept(fillId)` [accepts](https://docs.lamarge.trade/market-making#active-market-making) a fill delivered on Lighter or Aster; `deliver(fillId, txHash)` reports its transfer.
- `AsterDeliverer` and `LighterDeliverer` run over `quoter.fillFeed(signal)`. Each `run` accepts new fills before `maker_accept_by`, delivers paid fills, the earliest `deliver_by` first, persists each transfer in the journal before sending it and reports it.
- A deliverer accepts only while its journal saves and no delivery's outcome is unknown. `stopAccepting()` before shutdown; then cancel quotes and run until `outstanding()` is zero.
- `blocked` is true once deliveries have been stuck for 15 seconds: stop quoting that pool.
- The bot around them is yours: one process per journal, its storage, prices and shutdown.
## Event feed
```ts
import { changes } from "@lamarge/sdk";
const signal = new AbortController().signal;
for await (const change of changes(client, { scope: "private", signal })) {
if ("resync" in change) console.log("replace local state", change.resync);
else for (const event of change.events) console.log(event.kind, event.data);
}
```
`changes` takes a [snapshot](https://docs.lamarge.trade/streaming#snapshot-then-replay), then yields every page of events over the [WebSocket](https://docs.lamarge.trade/streaming#websocket), replays over HTTP between connections, and yields a new snapshot (`resync`) when the journal moved past the cursor. `scope: "public"` follows books and trades without a session.
## Errors and retries
- A refusal is a `LaMargeError`: `status`, `code`, `reason`, `requestId`, `retryable`, `retryAfterMs`, and `venue` and `step` for `SETUP_REQUIRED` ([errors](https://docs.lamarge.trade/api-reference/overview#errors)).
- Reads, and writes the SDK replays with the identical body, retry at most twice after a network failure or a `retryable` answer: after `Retry-After` when given, else a random wait of up to 500 ms, then up to 1 s. A write is never rebuilt; a cancellation is never replayed.
- `createClient` options: `fetch` for every request, Lighter's reads included; `timeoutMs` per request, 30 s by default; `retryRateLimited: false` throws a 429 at once; `maxAnswerBytes` refuses a longer answer; `sleep` makes a retry wait on the caller's clock.
- Most calls take an `AbortSignal`; `Maker` and `Quoter` methods do not. `take` and `transfer` take a `now` clock for the payment windows.
## Versions
Each version types the API of LaMarge's `main` when it is released; production may serve part of it later. Before 1.0 a minor version may break. A newly pinned deployment ships as a minor version, and older versions refuse to sign against it.
# Rust SDK
Source: https://docs.lamarge.trade/rust-sdk
```sh
cargo add lamarge chrono futures-util
cargo add tokio --features macros,rt-multi-thread
cargo add alloy-signer-local
```
[`lamarge`](https://crates.io/crates/lamarge) runs on Tokio, needs Rust 1.94.1 or later and is licensed MIT OR Apache-2.0. TLS is rustls with the platform verifier: slim and distroless images need system CA roots. HTTP requests honour `HTTPS_PROXY`; the event feed's WebSocket connects directly. API reference: [docs.rs/lamarge](https://docs.rs/lamarge). Source and examples: [snowbl-capital/lamarge-sdk-rs](https://github.com/snowbl-capital/lamarge-sdk-rs).
Before a signer sees anything, the crate:
- checks every [`to_sign`](https://docs.lamarge.trade/how-it-works#signing) item against your request and the [deployment values](https://docs.lamarge.trade/how-it-works#deployment-values) it pins;
- saves the signatures of takes, transfers, withdrawals, maker capital and wallet permits in your `Journal` before submitting them, and reuses them when the same request runs again; venue setup steps (setup permits included), closes and quote publications are not journalled and may sign again after an interruption;
- keeps [client IDs](https://docs.lamarge.trade/api-reference/overview#retries-and-recovery) stable across retries.
| Module | Contents |
|---|---|
| `lamarge` | `Client`, `ClientBuilder`, `Environment`, `LighterReads`, `Session`, `SavedSession`, `Quoter`, `MakerCredential`, `QuoteIdentity`, `Error`; host hooks `HttpExchange` (`HttpRequest`, `HttpAnswer`, `HostError`), `StreamConnector`, `TransactionSender`, `Transaction` |
| `lamarge::api` | Handles: `Market`, `Explorer`, `PublicEvents`, `Events`, `Account`, `Transfers`, `Takes`, `Fills`, `Orders`, `Withdrawals`, `Moves`, `Bridges`, `Directs`, `Credentials`; `PageRequest`, `RouteQuery`, `MoveQuery`, `MoveRequest`, `MoveRecipient`, `BridgeRequest`, `DirectRequest`, `CredentialRequest` |
| `lamarge::flows` | `TakeRequest`, `TransferRequest`, `TransferOutcome`, `TradeTerms`, `Recipient`, `WithdrawalRequest`, `WithdrawTo`, `MoveFundsRequest`, `MovePlan`, `MoveOutcome`, `MoveWait`, `RouteRequest`, `RouteLeg`, `RouteOutcome`, `RouteNotCommitted`, `groupable`, `ConversionTerms`, `ConversionPreview`, `DirectOutcome`, `DirectWait`, `DirectInspection`, `DirectStep`, `inspect_direct_transaction`, `check_direct_amounts`, `conversion_minimum`, `check_conversion_capability`, `POLYGON_USDC`, `POLYGON_FUNDING_CONVERTER`, `BridgeTerms`, `WalletDeposit`, `Maker`, `CapitalRequest`, `PriceLine`, `QuoteLinesRequest` |
| `lamarge::events` | `EventStream`, `Change`, `Snapshot`, `FillTracker` |
| `lamarge::book` | `SweepTerms`, `slippage_minimum`, `delivery_floor`; `sweep`, `limits` and `check` on `model::Book` |
| `lamarge::store` | `Journal`, `Store`, `MemoryStore`, `FileStore` |
| `lamarge::model`, `lamarge::types` | API answers, `Funding`; `Amount`, `SignedAmount`, `Price`, `Bps`, `VenueId`, IDs |
| `lamarge::protocol` | The pins (`CHAINS`, `ESCROW_DEPLOYMENTS`, `VENUE_DOMAINS`, `ENVIRONMENT_SLOTS`, `RELAY`, fee tags, Lighter and Aster constants) and every check a flow runs before a signature, named as the TypeScript SDK's `@lamarge/sdk/protocol` names them in snake case (`check_withdrawal`, `check_bridge_order`, `check_take_intent`…); a check returns the `Verified` payload to sign |
| `lamarge::attestation` | `verify_attestation`, `ATTESTERS`, `request_digest`, `SignRequest`, `Attested`: a separate signer's check that a request comes from LaMarge |
| `lamarge::funds` | `fresh`, `FRESH_MS`, `prefunded`, `sweepable`, `withdrawal_budget` of a `model::Balance` |
| `lamarge::delivery`, `lamarge::aster`, `lamarge::lighter` | `VenueDeliverer`, `FillSource`, `DeliveryVenue`, `DeliveryRecord`; `AsterDeliverer`; `LighterDeliverer`, `LighterSigner` |
## Client and signer
```rust
use alloy_signer_local::PrivateKeySigner;
use lamarge::{store::FileStore, types::VenueId, Client, Environment};
let client = Client::new(Environment::Production)?;
let book = client.market().book(&VenueId::Hyperliquid, &VenueId::Polymarket).await?;
let signer: PrivateKeySigner = std::env::var("LAMARGE_PRIVATE_KEY")?.parse()?;
let session = client.sign_in(signer, FileStore::open("lamarge-state")?).await?;
session.link_account(&VenueId::Hyperliquid).await?;
session.set_up_venue(&VenueId::Hyperliquid, None).await?;
let balances = session.account().balances().await?;
```
- `Environment::Production`, `Environment::Development`, or `Environment::Custom { api_url, app_origin }`.
- `sign_in` checks [`/v1/venues`](https://docs.lamarge.trade/api-reference/market-data/list-venues) against the pinned deployments, then signs the [challenge](https://docs.lamarge.trade/api-reference/authentication/challenge) for the environment's app origin. `Session::export` returns a `SavedSession`; `Client::resume_session` resumes it.
- A signer is any `alloy_signer::Signer`: a local key, a KMS key, a Ledger.
- The crate reads Lighter's public API directly to check account owners before a Lighter take (`Client::lighter_account_owner` reads one). `Client::builder(environment).lighter_reads(carrier)` sends those reads through your `LighterReads`, from your address and within your rate budget; the crate keeps its deadline and refuses any non-2xx answer as `Error::VenueApi` with its status.
- `ClientBuilder::http_exchange` sends every API request through your `HttpExchange`, and `stream_connector` opens the event WebSocket's connection through your `StreamConnector`. Requests keep the crate's deadline, retries and answer cap, with TLS left to your exchange; the crate runs TLS and the WebSocket over the connector's stream.
- Amounts are base units of each venue's token: `Amount::parse_venue(&venue, "250")`.
- An enum value a newer server adds decodes as `Unknown`.
## Takes and transfers
```rust
use lamarge::flows::{Recipient, TakeRequest, TradeTerms, TransferOutcome, TransferRequest};
let terms = TradeTerms::new(VenueId::Hyperliquid, VenueId::Polymarket, amount_in, min_out, Recipient::Account(me))
.max_fee_bps(book.taker_fee_bps);
let fills = session.take(&TakeRequest::new(ClientId::new("take-1")?, terms.clone())).await?;
match session.transfer(&TransferRequest::new(ClientId::new("transfer-1")?, terms)).await? {
TransferOutcome::Filled { fills, .. } => println!("{} fills", fills.len()),
TransferOutcome::Pending { reason, .. } => println!("pending ({reason:?}): run it again later"),
_ => {}
}
```
- `take` reserves at market, checks the [payment](https://docs.lamarge.trade/how-it-works#signing) against `terms` (amounts, parts, fee, recipient, windows, the pinned escrow; Lighter's own owner of a delivering account), signs, saves and submits it. Persist the whole request (it is serializable) before the first call: running it again resumes the take, never paying a fill past its reservation again.
- `transfer` [funds the take first](https://docs.lamarge.trade/how-it-works#paying-from-venue-margin): from Hyperliquid or Polymarket margin only the paying address's shortfall is withdrawn, signed with the take when the funding plan says so; from GMX margin the payer sends its own `transferOut` to its address, through `transfer_with`'s `TransactionSender`, once; with `.funding(Funding::Wallet)` nothing is withdrawn and the escrow's permit is signed first if needed; from Lighter or Aster the take pays directly. The same request resumes from the journal, also after a stale preparation or an expired take was replaced.
- `TransferRequest::conversion(ConversionTerms)` funds a wallet-funded transfer from Polymarket with native USDC converted to pUSD first, through `transfer_with`'s `TransactionSender` (an `approve` only when the allowance is short, then the conversion); `Session::conversion_preview` tells, before any is asked, whether an `approve` is needed, how many transactions follow and whether the wallet's balance covers the conversion.
- `route` / `route_with` run a `RouteRequest` from `from` through `via` to `to` in two transfers, the second paying what the first left on `via`, as a transfer from `via`: taken take by take through Hyperliquid or Polymarket, the signer on `via` signs a withdrawal from there, whatever `from` is; with `RouteRequest::grouped` a route whose first take pays inside Lighter or Aster through an escrow venue (`groupable`) is signed and committed at once, or ends in `Error::RouteNotCommitted`.
- `Recipient::Wallet(address)` delivers by plain transfer on the receiving escrow chain; `Recipient::Account` into the account linked there.
- `withdraw` moves a `WithdrawalRequest` amount out of Hyperliquid, Polymarket or Aster, or sends it to another account (`WithdrawTo`); an Aster withdrawal goes to BSC, or with `.chain(42161)` / `.chain(1)` to Arbitrum or Ethereum (each with its own limit and fee at Aster, listed by `withdrawals().chains(&VenueId::Aster)`), Aster's fee on top, relayed in an envelope the session signs too; `WithdrawTo::VenueWallet(wallet)` names the linked Polymarket wallet, never read from the API; `.dex(Dex::Xyz)` pays a Hyperliquid withdrawal or send from a standard account's trade.xyz balance. The same request returns the outcome, never a second withdrawal.
- `direct_transfer(&DirectRequest, &sender)` runs a [direct transfer](https://docs.lamarge.trade/direct-transfers), as the TypeScript SDK's `directTransfer`: `DirectRequest::deposit` from the session's wallet into its own chain's venue (on Polymarket, native USDC converted to at least its `conversion_minimum` of pUSD), or `DirectRequest::gmx_withdrawal`. It checks the operation against the request and the pinned deployment, reads the venue's capability and the funds, sends an `approve` only when the allowance is short, then the deposit or `transferOut`, fenced first and never asked again while its outcome is unknown; a deposit the wallet refused is asked again under its same nonce. `DirectOutcome::Waiting` says what it waits for; run the same request again. `inspect_direct_transaction` checks a transaction's chain, contract and calldata in an isolated signer as `inspectDirectTransaction` does; it does not see the native value, so refuse a non-zero value yourself.
## Moves and bridges
A [move](https://docs.lamarge.trade/how-it-works#moves-and-bridges) sends `amount_in` to one destination: LaMarge's makers fill what they can, an external bridge (Relay) carries the rest. `move_funds_with` runs it to its end, as the TypeScript SDK's `moveFunds`.
```rust
use lamarge::{api::{MoveRecipient, MoveRequest}, flows::{MoveFundsRequest, MoveOutcome}, model::MoveEndpoint};
let (from, to) = (MoveEndpoint::account(&VenueId::Hyperliquid), MoveEndpoint::wallet(42161, usdc));
let recipient = MoveRecipient::Address(deposit_address);
let terms = MoveRequest::new(ClientId::new("move-1")?, from, to, amount_in, min_out, me, &recipient);
let request = MoveFundsRequest::new(terms, recipient)?;
match session.move_funds_with(&request, Some(&sender)).await? {
MoveOutcome::Closed(found) => println!("closed, {:?} unallocated", found.unallocated),
MoveOutcome::Pending { reason, .. } => println!("pending ({reason:?}): run it again later"),
_ => {}
}
```
- The plan is the move's first quote (`move_plan`), journalled under its `client_move_id` and read back by every later run; the same id with other terms is refused.
- LaMarge's part runs first, one take or a route through a venue between, attached to the move. A route's second transfer pays from the venue between: through Hyperliquid or Polymarket, its signer signs a withdrawal from there, whatever the move's origin, and a refusal stops the move with the funds in that account. The bridge for the rest starts once it ran, and once its payment executed when the bridge leaves a wallet. A Polymarket origin first withdraws the rest to the payer's wallet there, under the move; a GMX origin by the payer's own `transferOut`, recorded as a direct operation (`directs()`), checked against the pinned GMX deployment, fenced before the sender is asked and sent once.
- A LaMarge part that ends unpaid frees its share: what its funding withdrawal moved is bridged from the wallet, the rest from the origin. A bridge refused for a lasting reason (`insufficient_liquidity`, `below_minimum`, `unsupported`, `slippage`, `hyperliquid_mode`, `disabled`), or a venue settled inside itself (Lighter, Aster), leaves its amount unallocated; the move is closed with it and the first reason.
- Every part is counted against `amount_in` in the journal before it is created; a part from the wallet only within what the move's withdrawals put there.
- A `HyperCore` bridge's nonce mapping and send are each journalled once signed and submitted again, never signed anew. A wallet bridge's `approve` and deposit go through your `TransactionSender`: the `approve` only when the allowance is short, the deposit after the bridge is fenced, never asked again while its outcome is unknown.
- Run the same request again after `MoveOutcome::Pending`: `Payment`, `Withdrawal`, `Bridge`, `Route` or `Transfer(reason)` says what it waits for.
The manual path, keeping the move's budget yourself:
```rust
use lamarge::{api::{BridgeRequest, MoveQuery, MoveRecipient, MoveRequest}, flows::{BridgeTerms, TransferRequest}, model::MoveEndpoint};
let (from, to) = (MoveEndpoint::account(&VenueId::Hyperliquid), MoveEndpoint::wallet(42161, usdc));
let recipient = MoveRecipient::Address(me);
let plan = session.moves().quote(&MoveQuery::new(from.clone(), to.clone(), amount_in, min_out, recipient)).await?;
let request = MoveRequest::new(ClientId::new("move-1")?, from, to, amount_in, min_out, me, &recipient);
let created = session.moves().create(&request).await?;
// LaMarge's part: a transfer attached to the move.
session.transfer(&TransferRequest::new(ClientId::new("move-1.lamarge")?, terms).move_id(created.id)).await?;
// The rest: a bridge, checked against your own terms before anything is signed.
let bridge = session.bridges().create(created.id, &BridgeRequest::new(ClientId::new("move-1.bridge")?, rest)).await?;
let terms = BridgeTerms::for_move(&request, recipient, rest)?;
session.sign_bridge(&bridge, &terms).await?;
session.moves().close(created.id, Amount::ZERO, None).await?;
```
- `sign_bridge` (HyperCore origin) and `bridge_deposit` (wallet origin) check the order against `BridgeTerms` and the pinned Relay contracts. `for_move` takes the part's floor as its share of the move's `min_out`, and a Polymarket, GMX or Aster account's credit as that floor, at least the venue's minimum. A Lighter recipient's owner is read on Lighter's API.
- `sign_bridge` signs Relay's nonce mapping and the `SendAsset` to Relay's depository, then submits both. `bridge_deposit` returns the `approve` (only when the allowance is short) and the deposit: call `bridges().fence(id)` before prompting, send them yourself, report each hash with `report_transaction`, or `report_unsent` when the wallet refused before broadcasting. Never send a deposit again after an unknown outcome.
- Keep the move's budget yourself, from your own records: the parts that may still debit (bridges not `failed` or `expired`, each transfer at its take's `amount_in`, withdrawals feeding a bridge) stay within the move's `amount_in`, and each part's floor is at least its share of `min_out`, rounded up. The server refuses bridges beyond `amount_in`; the crate does not track them.
## Market making
Two keys on two hosts, as in [market making](https://docs.lamarge.trade/market-making#passive-market-making): the financial key provisions capital, the quote key quotes.
```rust
use lamarge::{api::CredentialRequest, flows::{CapitalRequest, PriceLine, QuoteLinesRequest}, model::Funding, MakerCredential};
// Financial key's host, once.
let request = CredentialRequest::new("quoter-1", quote_signer, Duration::from_hours(720));
let credential = MakerCredential::from(session.credentials().create(&request).await?);
let maker = session.maker(operator);
let capital = CapitalRequest::new(ClientId::new("pool-hl-1")?, VenueId::Hyperliquid, amount, Funding::Wallet);
let order = maker.add_capital(&capital, &credential.identity).await?;
maker.wait_for_funding(&order, Duration::from_secs(600)).await?;
// Quoting host, every few seconds.
let quoter = client.quoter(credential, quote_key).await?;
quoter.lease(Duration::from_secs(30)).await?;
let lines = vec![
PriceLine::new(VenueId::Hyperliquid, stock).sell("1.0005".parse()?),
PriceLine::new(VenueId::Polymarket, Amount::ZERO).buy("0.9995".parse()?),
];
let recipients = BTreeMap::from([(VenueId::Polymarket, polymarket_account)]);
quoter.publish_lines(&QuoteLinesRequest::new(lines, recipients, Utc::now() + TimeDelta::seconds(25))).await?;
```
- `operator` comes from the [deployment values](https://docs.lamarge.trade/how-it-works#deployment-values) you reviewed, never from the API.
- `add_capital` checks the [preparation](https://docs.lamarge.trade/how-it-works#maker-capital) before the financial key signs it; the same request resumes it. Pools on Hyperliquid, Polymarket and GMX; GMX funds from the wallet only.
- `publish_lines` rebuilds each pool's quote set from your [quote lines](https://docs.lamarge.trade/how-it-works#quote-lines) before the quote key signs: every pool switches at once. `recipients` names your linked address on each venue you buy on.
- `cancel_all` pulls every pool's quotes; `Maker::close_orders` [releases](https://docs.lamarge.trade/how-it-works#releasing-capital) capital.
- Deliveries inside a venue: `lighter::LighterDeliverer` and `aster::AsterDeliverer` (both `delivery::VenueDeliverer`) accept requested deliveries, send each paid fill's transfer once, persisted in a `Journal` before it is sent, and report it (`Fills::accept`, `Fills::deliver`). Run them on every change of the quoter's fills; `blocked()` tells the pool to stop quoting while an outcome stays unknown. Lighter's API key stays in your `LighterSigner`; the owner's message is checked against the transfer the key signed before the owner signs it. Venue requests go through your `HttpExchange`.
- `refund_payment(fill, reader)` gives a taker's payment back early for a fill abandoned inside its venue, once your `ChainReader` reads the lock from the pinned escrow the consent names; `protocol::check_escrow_withdrawal` checks an order's available-balance withdrawal.
## Event feed
```rust
use futures_util::StreamExt;
use lamarge::events::{Change, FillTracker};
let mut feed = quoter.events().subscribe();
let mut fills = FillTracker::default();
while let Some(change) = feed.next().await {
let change = change?;
fills.apply(&change);
if let Change::Resync(snapshot) = &change { println!("resync at {}", snapshot.cursor()); }
}
```
`subscribe` takes a [snapshot](https://docs.lamarge.trade/streaming#snapshot-then-replay), then yields each page of events over the [WebSocket](https://docs.lamarge.trade/streaming#websocket), replays over HTTP between connections and yields a new snapshot (`Change::Resync`) when the journal moved past the cursor. `Client::events` is the public feed; `Session::events` and `Quoter::events` are private, follow session renewals and end with `Error::SignedOut` on sign-out.
## Attestations and proofs
A signer holding a taker's key apart from the app checks that a request comes from LaMarge: `attestation::verify_attestation(&request, address, &attestation, attestation::ATTESTERS.production, now)` returns a take's terms, or a setup step. `protocol::check_escrow_proof_typed` checks a signed quote set, funding or payment against every v5 deployment, retired ones included. `protocol::transfer_hash` and `read_transfer_tx_info` read a sent Lighter transfer back.
# Overview
Source: https://docs.lamarge.trade/api-reference/overview
## Addresses
| Service | URL |
| --- | --- |
| Application / SIWE `APP_ORIGIN` | `https://app.lamarge.trade` |
| API base / `API_URL` | `https://api.lamarge.trade` |
| Documentation | `https://docs.lamarge.trade` |
Application routes are under `/v1`; `/health` (readiness, 200 or 503) is not.
## Conventions
- JSON is `snake_case`. Request bodies are limited to 64 KiB and reject unknown fields.
- Amounts are decimal strings of token base units: `"1000000"` is one USDC or pUSD; USDT has 18 decimals. Hyperliquid and Aster withdrawal messages sign decimal token amounts instead.
- Response times are RFC 3339 UTC, except a quote line preparation's `valid_until` and its drafts' `expires_at`; those and request deadlines are Unix seconds. `x-server-time` is Unix milliseconds.
- Order IDs are 32-byte hex; other resource IDs are UUIDs. Event cursors, revisions, generations and cancellation epochs are decimal strings: keep them lossless. Quote sequences are integers.
- Client IDs (`client_request_id`, `client_take_id`, `client_transfer_id`) are 1–64 ASCII letters, digits, `_`, `-`, `.` or `:`.
- Every response carries `x-request-id` and `x-server-time`. CORS exposes them and `Retry-After` to the app origins.
## Authentication
Public market data needs no token. Private calls send `Authorization: Bearer TOKEN`.
A master session comes from the SIWE [challenge](https://docs.lamarge.trade/api-reference/authentication/challenge) and [verify](https://docs.lamarge.trade/api-reference/authentication/verify) routes; the message names `APP_ORIGIN`. It is required to link accounts, fund and close capital, take, transfer, withdraw and manage credentials. The session authenticates the request; the linked account owner still signs each financial item.
A maker credential is an `mk_` bearer bound to one quote identity and its quote signer:
| Scope | Allows, within its identity |
|---|---|
| `read` | Orders, maker fills, their histories, exposure, private snapshot, replay and stream |
| `quote` | Lease renewal, quote line preparation and publication, fill acceptance, delivery reports |
| `cancel` | Per-order and identity-wide cancellation |
A credential never moves capital, links accounts, takes or closes orders, and never sees balances, withdrawals or other identities. Rotation replaces the bearer, keeps the identity and quote signer, and removes current quotes. A master session can call these routes too, for each of its identities.
When `/v1/info` reports `access.mode: "invite"`, an account makes new commitments only once it redeems an access code in the app or LaMarge grants access; until then, or while suspended, they answer `ACCESS_REQUIRED`.
## Retries and recovery
Persist `client_request_id`, `client_take_id` or `client_transfer_id` before the first request. Repeating an ID with the same parameters returns the existing resource, whatever its state; other parameters answer `STATE_CONFLICT`. A new attempt after a cancelled, expired or failed one needs a new ID. There is no `Idempotency-Key` header.
Recover a maker preparation by repeating its request or with [`GET /v1/maker/preparations/{id}`](https://docs.lamarge.trade/api-reference/maker/get-preparation), and a take with [`GET /v1/takes/{id}`](https://docs.lamarge.trade/api-reference/takes/get-take). Check state and deadlines before signing a recovered item. A venue withdrawal is deduplicated by its exact signed operation; resending it returns its record. For a take funded from venue margin, recover its [transfer](https://docs.lamarge.trade/api-reference/transfers/get) first.
Live state: [snapshot, then replay](https://docs.lamarge.trade/streaming). The SDK follows these rules ([errors and retries](https://docs.lamarge.trade/sdk#errors-and-retries)).
## Errors
Every error except `/health` readiness has this shape:
```json
{"error":{"code":"STATE_CONFLICT","message":"…","request_id":"018f…","retryable":false}}
```
Branch on `code`, never on `message`. Some errors add a stable `reason`, listed on their route, such as a refused [delivery report](https://docs.lamarge.trade/api-reference/takes/delivery). `retryable` is a transport hint, not permission to create a new economic intent. Any route may answer `429` or `500`; route pages do not list them. On 429, or any error with `Retry-After`, wait that many seconds and retry the same request; `retryable` is then true. A path segment that is not UTF-8 once percent-decoded answers `400 VALIDATION_ERROR` on any route.
| Code | HTTP | Meaning |
|---|---|---|
| `VALIDATION_ERROR`, `BAD_SIGNATURE` | 400 | Invalid input, unknown fields, or a wrong or expired signature |
| `WITHDRAWAL_EXPIRED` | 400 | A new venue withdrawal not signed within the last ten minutes, or prepared too long ago to be signed with its take |
| `CAPTCHA_FAILED` | 400 | Access code captcha refused |
| `UNAUTHENTICATED` | 401 | Missing, invalid, expired or revoked bearer |
| `FORBIDDEN` | 403 | Missing credential scope or unusable quote identity |
| `ACCESS_REQUIRED` | 403 | Access not granted, or suspended |
| `MAKER_NOT_APPROVED` | 403 | Supplying Lighter or Aster needs an approved maker |
| `NOT_FOUND` | 404 | Unknown route, or unknown or foreign resource |
| `METHOD_NOT_ALLOWED` | 405 | Method not supported by the route |
| `STATE_CONFLICT` | 409 | State, lease, generation or reused client ID conflicts |
| `ACCOUNT_IN_USE` | 409 | Linked to another user, or used by open orders, fills or unresolved withdrawals |
| `PREFUNDING_REQUIRED` | 409 | The available balance and the linked address cannot cover the payment |
| `STALE_SEQUENCE`, `STALE_QUOTE` | 409 | A later quote set won, or the quote, lease or order changed |
| `INSUFFICIENT_LIQUIDITY`, `SLIPPAGE` | 409 | The book cannot fill the take, or pays less than `min_out` |
| `FILL_IN_PROGRESS` | 409 | Too many takes await payment, or one this take must follow (see `reason`) |
| `TAKE_EXPIRED` | 409 | The take expired before its signature; take again |
| `RESYNC_REQUIRED` | 410 | Replay cursor outside the retained journal |
| `PAYLOAD_TOO_LARGE` | 413 | Request body above 64 KiB |
| `DELIVERY_PENDING` | 425 | Delivery unknown to the venue or not yet at the required status; report it again |
| `VENUE_DISABLED`, `ACCOUNT_NOT_LINKED`, `WALLET_NOT_FOUND` | 422 | Venue disabled, account not linked, or no Polymarket wallet |
| `SETUP_REQUIRED` | 422 | A setup step is missing or no longer accepted: do `error.step` on `error.venue` |
| `RATE_LIMITED` | 429 | Request, draft, stream or server capacity exhausted |
| `VENUE_REJECTED` | 502 | Explicit venue refusal; not retryable |
| `VENUE_UNAVAILABLE` | 502 | Venue or chain did not answer |
| `INTERNAL` | 500 | Server fault; keep the request ID |
| `OPERATOR_UNAVAILABLE` | 503 | Chain observations, operator gas, relay capacity or escrow integrity not ready |
| `SNAPSHOT_TOO_LARGE` | 503 | A bounded selection exceeds 1,000 rows; no partial result |
## Limits
`GET /v1/info` returns the deployment's limits and settlement timings. Defaults:
| Resource | Limit |
|---|---|
| Authenticated requests | 60/s, burst 120; shared by a user's sessions, separate per credential |
| SIWE challenge | Per address burst 6, 6/min; overall 60/s, burst 120 |
| SIWE verify | Per address burst 12, 12/min; overall 60/s, burst 120 |
| Sessions, credentials | 32 active each per user: a new session revokes the oldest, a 33rd credential answers `STATE_CONFLICT`; sessions last 7 days, credentials at most 90 days |
| Maker order | One per owner, venue and quote identity; first funding at least 5 tokens |
| Fill output | `min_fill` at least 1 token; at most `fill_max`, 1,000 tokens |
| Quote admission (`valid_until`) | Credential: at most 300 s ahead; browser: up to 300 s, or none |
| Quote lease | Credential: 5–120 s |
| Unsigned drafts | 100 per identity; publish within 5 minutes |
| Close request | 50 distinct orders |
| Pending escrow withdrawals | 10 per owner and chain |
| Take | `max_parts` 1–8; payment window 45 s by default, at most 60 s |
| Signing window | Maker preparation: 1 hour, 10 minutes with a margin transfer; closes: 1 hour; sign-in and link messages, payment permit, venue withdrawal: 10 minutes; Aster agent approval: 60 s |
| Snapshot, open order and fill lists, a book | 1,000 rows; 503 above |
| History and event pages | 100 by default, at most 500; take history at most 100 |
| Replay retention | 24 hours or 1 million events, whichever is smaller |
| WebSocket | 256 connections, at most 64 anonymous; subscribe within 5 s; inbound messages at most 4 KiB |
Public market data is not charged to a user's request budget.