@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.
Before a signer sees anything, the SDK:
- checks every
to_signitem against your request and the deployment values it pins; - stores each payment, funding and withdrawal signature, so a restart submits it again instead of signing anew;
- keeps client IDs stable across retries.
Client and signer
client.callreaches any operation by theoperationIdits API reference page shows. Path, query and body are typed.signInchecks the chains, permit domains and settlement/v1/venuesnames against the pinned deployments, then signs the 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
signMessageandsignTypedData: a viemLocalAccount, a KMS key through viem’stoAccount, or a browser wallet’s two methods. An optionalprepare(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, it also needssendTransaction({ chainId, to, data }, sent): it callssent(hash)once broadcast, resolves with the hash once mined and rejects a refusal or a revert. AtransferOutbroadcast is not sent again for ten minutes; aLocalAccountonly signs, so give it a viem wallet client’ssendTransactionandwaitForTransactionReceipton Arbitrum. - Answers are typed, not validated: an enum value a newer server adds still type-checks.
Accounts
linkAccountlinks an account. An address other than the master signs the link challenge once the SDK checked it names that venue.setUpVenueruns each setup step the venue does not show yet, checks it, signs it and waits until the venue shows it.onProgressnames each step as it starts and while it isconfirming.asterAgentNameandlighterKeyIndexpin your deployment’s slots (ENVIRONMENT_SLOTS:LaMargeand 254 in production,LaMargeDevand 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.transfer returns the take’s fills once the payment is accepted; each fill then settles on its own. Follow them with changes or GET /v1/takes/{id}.
Transfers
funding: "wallet"pays only from the signer’s escrow-token wallet and available balance (wallet funding); a shortfall stops before anything is signed. A master signer needs no linked account onfrom. A resumed transfer keeps the funding it was created with. On Polygon it pays pUSD unless the request hasconversion.funding: "venue"first withdraws 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 owntransferOuttransaction (the plan’stransfer_outrequest), paid in ETH on Arbitrum; a signer withoutsendTransactionstops before anything is signed.- Persist
client_transfer_id, the transfer IDonIntentnames and thestore. The same request withtransfer_idresumes it: a stored signature is submitted again, never replaced.memoryStore()is lost with the process. TransferPending.reason:arrival_unconfirmedorauthorization_unconfirmed(funds or permit not seen withinarrivalWaitMs) andunknown(withdrawal outcome): run again later.refused: the venue refused the withdrawal.max_fee_bpsaccepts the pair’s taker fee up to that many basis points, as the book’staker_fee_bpsshows it (fees). Without it, the take pays no fee.destination: "wallet"transfers the take’s output torecipient, any address onto’s escrow chain, instead of the linked account (wallet delivery); nothing is read or required about an account onto. The SDK checks the wallet tag of eachswap_id, the signedreceiveRecipient, the pinned wallet token and the take’sminimum_receivedbefore signing. On a route it applies to the last take.beforeSigning, ontransfer,take,route,withdrawandsetUpVenue, runs your own checks on each request after the SDK’s and before it is first signed. One that throws signs nothing.lock, ontransfer,takeandroute, wraps each take from its first read to its submission. Share it across your processes or tabs.takealone prepares a take, checks and signs its payment, and submits it.checkQuoteandminimumTakeread 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.
- The result is a snapshot that reserves nothing; amounts between
minimumandmaximumcan fall in a gap left by minimum fills. Requote the chosen amount before signing. slippageMinimum(out, bps)roundsoutlessbps(an integer from 0 to 10,000) down: amin_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/routeswithamount_inyour budget answers what the route can spend now (amount_in,cappedwhen below your budget) andamount_out, the intermediate venue and your own orders accounted for.min_outapplies to the budget you ask and scales down with a capped input: passslippageMinimum(referenceOut, bps). It gives no route minimum.
Polygon native USDC
Wherechain.wallet_funding.conversion is set, a wallet-funded transfer from Polymarket pays from native USDC (how it works):
- The signer needs
sendTransactionand POL for gas. When the allowance is short it approves exactlyamount_inof USDC to the escrow, then sendsconvertDeposit;beforeSigningsees each askind: "conversion",stepapproveorconvert, withamount(USDC) andminOut(pUSD). - The take starts once LaMarge reads the conversion final. Resume with the same
transfer_idandconversion: an unknown wallet answer never sends a second conversion, even from a fresh store. - Refunds and anything converted above
amount_instay in the available balance in pUSD.
Routes
route runs a two-take plan from GET /v1/routes as two transfers:
- The first, under your
client_transfer_id, names the route’s end inthen. - Once it delivered on the intermediate venue, the second, under
client_transfer_id+.2, pays what the server leaves to continue (continuable).
viaSignersigns 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,
beforeSigningsees its funding withdrawal (kind: "withdrawal",venuethe 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: truesigns a grouped route at once. An unavailable, aborted or expired attempt throwsRouteAbandoned(reason,transferId,commitBy,lateByMs). Rerun withgrouped: falseto continue take by take.
Moves and bridges
moveFunds moves amount_in from one endpoint to another as one move: LaMarge’s makers first, as far as they fill at the floor rate min_out / amount_in, an external bridge for the rest.
- 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,recipientis the account index, which Lighter must show owned by the signer orlighterOwner. - The move follows its first quote. Its LaMarge part runs as
transferorroute, the root transfer attached bymove_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). Withsequential: 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 withMovePendingroute, the bridge starting on the next run. A Polymarket origin first withdraws to the signer, a GMX one sends itstransferOut, both attached to the move; the bridge then leaves that wallet. - Every part counts against
amount_inin 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 beforemoveFundsto 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_idand thestore; the same request resumes.MovePending.reason:payment,withdrawal(funds not yet in the wallet),route(withsequential, a second take waiting for liquidity), orbridge(an approval of unknown outcome, or an unsigned quote expiring), asTransferPendingfrom 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 againstterms(checkBridgeOrderin@lamarge/sdk/protocol), then signs a HyperCore origin’s nonce mapping andSendAsset, or sends a wallet’sapproveand deposit.beforeSigningsees each askind: "bridge",stepsign,approveordeposit, with thevenuethe 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
sendTransactionand gas; it approves exactlyamount_inonly when short, and a deposit whose outcome is unknown is never sent again. waitForBridge(client, id)reads a bridge until it is final.
Withdrawals and refunds
Withclient and account from client and signer:
withdrawmoves 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 thechain_idyou pick fromgetWithdrawalChains(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. Withto: "account"andrecipient, it sends to another account on Hyperliquid, Polymarket or Aster. The sameidreturns the withdrawal or resubmits its signature; a refused one needs a newid.refundPaymentconsents, as the maker, to return the payment of a fill abandoned on Lighter or Aster (outcomes). It signs only once the payment’s escrow, read through your viemPublicClientfor 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 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 you first.- Take
OPERATOR_ADDRESSfrom the deployment values andAPP_ORIGINfrom the addresses. maker.link(venue, owner)linksowner’s account; on Aster it also approves LaMarge’s agent for the API’s environment.addCapital(input, credential, { store, owner })checks the preparation before the financial key signs it.storekeeps the signed preparation for a restart;owneris the address linked on Lighter or Aster that holds the pool. On an escrow venue, follow it withwaitForFunding(order).
Quote and deliver
On the quoting host, with the credential, the quote key and the pool’s keys; never the master key.new Quoter(client, credential, quoteSigner)checks thatquoteSigneris the credential’squote_signer.publishLines(lines, recipients, validUntil)prepares the identity’s quote lines, rebuilds each pool’s quote set from your lines, signs and publishes them: every pool switches at once.recipientsnames 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 withclient.call("publishQuoteLines", …).cancelAll()pulls every pool’s quotes. To pull one venue, publish its line withstock: "0".accept(fillId)accepts a fill delivered on Lighter or Aster;deliver(fillId, txHash)reports its transfer.AsterDelivererandLighterDelivererrun overquoter.fillFeed(signal). Eachrunaccepts new fills beforemaker_accept_by, delivers paid fills, the earliestdeliver_byfirst, 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 untiloutstanding()is zero. blockedis 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
changes takes a snapshot, then yields every page of events over the 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, andvenueandstepforSETUP_REQUIRED(errors). - Reads, and writes the SDK replays with the identical body, retry at most twice after a network failure or a
retryableanswer: afterRetry-Afterwhen 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. createClientoptions:fetchfor every request, Lighter’s reads included;timeoutMsper request, 30 s by default;retryRateLimited: falsethrows a 429 at once;maxAnswerBytesrefuses a longer answer;sleepmakes a retry wait on the caller’s clock.- Most calls take an
AbortSignal;MakerandQuotermethods do not.takeandtransfertake anowclock for the payment windows.
Versions
Each version types the API of LaMarge’smain 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.