Acta Web Client SDK (TypeScript)
The TS SDK wraps the taker WebSocket protocol: auth, market and position queries, RFQs for five products, and sponsored transactions.
Wire messages, errors and enums are in Taker API reference. SDK event callbacks mirror wire message names in lowerCamelCase. TypeScript types define the payloads.
Installation
npm install @acta-markets/ts-sdk
This guide covers version 0.5.2. It speaks WS protocol 1.0.0 and targets the program deployed to devnet and mainnet; both use the same program ID, and GET /api/v1/venue returns the authoritative program_id. Refer to opcodes and errors by name through the generated constants exported from @acta-markets/ts-sdk (*_DISCRIMINATOR for opcodes, ACTA_CONTRACT_ERROR__* for errors), not by number. The package README and changelog cover the vault builders.
The wire is closed. The client does not dispatch a frame that lacks a required field or carries an unknown enum value. A message whose type the SDK does not know is reported on the unknownMessage event. Absent facts are tagged unions; null appears only as next_cursor on the last page. Wire addresses are validated when a frame is decoded. server_now_at_ms and sent_at_ms use milliseconds, and expires_at uses Unix seconds.
Taker-only apps should import @acta-markets/ts-sdk/ws: client, auth, RFQ and sponsored-tx signing, without instruction builders or IDL. The SDK is built on @solana/kit; you do not need @solana/web3.js. Spread economics helpers and account reads are in @acta-markets/ts-sdk/chain, and public reads such as the venue are in @acta-markets/ts-sdk/http.
Quick start
1. Auth provider
wallet is a connected wallet adapter that exposes its current publicKey and signMessage. walletPublicKeyBase58 is the account used for this client's authentication. Recreate the client when that account changes.
import { WalletAuthProvider } from "@acta-markets/ts-sdk/ws";
const authProvider = new WalletAuthProvider({
publicKeyBase58: walletPublicKeyBase58,
signMessage: async (msg: Uint8Array) => await wallet.signMessage(msg), // 64-byte ed25519
});
Other providers: KeypairAuthProvider (Node, CI, bots; import from @acta-markets/ts-sdk/ws/keypair) and CustomAuthProvider (remote signer).
Frontend wallets (Phantom, Privy). WS auth requires signMessage (ed25519 over the UTF-8 challenge). For sponsored-tx signing, verifyAndSignTakerFill(...) checks the served transaction against the accepted quote and then signs with signMessage (no @solana/web3.js) or with the wallet's signTransaction for its own transaction preview (step 8). If a wallet does not expose signMessage, use CustomAuthProvider with a backend signer. ActaWsClient validates the challenge format before it calls any auth provider. Raw clients can call validateAuthChallenge before signing.
2. Connect
onDisconnect, products, clientName and clientVersion are required. The client sends them in Hello together with protocol version 1.0.0.
import { ActaWsClient } from "@acta-markets/ts-sdk/ws";
// Devnet; for mainnet use "wss://beta-api.acta.markets"
const wssEndpoint = "wss://devnet-api.acta.markets";
const ws = new ActaWsClient({
url: wssEndpoint,
role: "taker",
onDisconnect: "keep_quotes",
products: ["covered_call", "cash_secured_put", "call_spread", "put_spread", "cash_put"],
clientName: "my-app",
clientVersion: "0.1.0",
});
// Register handlers and load the saved session before connecting (next step).
ws.on("connected", () => console.log("Connected"));
ws.on("error", (e) => console.error("Error:", e));
onDisconnectis"cancel_quotes"or"keep_quotes".productsis a non-empty list of the five product names. The SDK sends it in everySubscribe. The server uses it for maker and vault sessions and does not use it to filter what a taker receives.- The client appends
/takerto the base URL fromrole.
Alternative: ws.connectAnonymous() and later await ws.authenticate(authProvider).
3. Authenticate with session resume
const sessionKey = `acta_session:${wssEndpoint}:${walletPublicKeyBase58}`;
const expiryKey = `${sessionKey}:expires_at`;
ws.on("authenticated", (sessionId, expiresAt, makerPda) => {
// makerPda is null for a taker.
localStorage.setItem(sessionKey, sessionId);
localStorage.setItem(expiryKey, String(expiresAt));
});
const savedSessionId = localStorage.getItem(sessionKey);
const savedExpiresAt = Number(localStorage.getItem(expiryKey) || "0");
const sessionId = savedSessionId && Date.now() / 1000 < savedExpiresAt
? savedSessionId
: undefined;
ws.connectAndAuthenticate(authProvider, { sessionId });
Register application handlers before calling connectAndAuthenticate. It tries the supplied session, then the auth provider on session_expired. Do not also send ResumeAuth or start another authentication from connected. connected means the socket is open and Welcome has arrived. authenticated means authentication and the server's connection handoff are complete.
Persist credentials per wallet and environment. Resume succeeds without a wallet popup. Fresh authentication does not restore ownership of an older credential's pending signature. See Delivery and recovery.
expiresAt is a number in Unix seconds. A saved credential with a missing or expired deadline should use fresh authentication. The deadline limits starting another resume. It does not end an already authenticated connection.
4. Subscribe and track positions
subscribe(channels, mints) takes a required mint filter. ALL_MINTS selects every mint.
import { ALL_MINTS } from "@acta-markets/ts-sdk/ws";
ws.on("authenticated", () => ws.subscribe(["chain_events"], ALL_MINTS));
// A taker's own positions arrive on the session as full rows, without a subscription.
ws.on("positionUpdated", (position, updateType) => {
// position.state: "open" | "funded" | "liquidated" | "settled"
console.log(updateType, position.pda, position.state, position.total_premium);
});
ws.on("chainEvent", (ev) => {
// ev.event_type, for example "PositionSettled"
console.log("Chain event:", ev);
});
The client keeps ws.state.positions (a Map keyed by position PDA). It merges Positions responses and PositionUpdated pushes and applies a row only if its revision is newer than the stored one, so positionUpdated does not fire for duplicates or old rows. comparePositionRevision(a, b) from @acta-markets/ts-sdk/ws compares two revisions (slot, transaction_index, instruction_index) lexicographically; use it if you read raw Positions pages yourself. Switching the auth provider or logging out clears the cache. Each row carries underlying_price: { type: "available", price, published_at } with the trusted oracle price of the underlying in the quote token (1e9), or { type: "unavailable" }. Use it with terms, side and quantity for the current value of a position.
Subscriptions restore on reconnect.
5. Browse markets
ws.on("markets", (markets) => console.log(markets));
ws.getMarkets();
// Descriptors include products, size_rule, decimals and oracle PDAs. Fetch before createRfq.
ws.on("marketDescriptors", (descriptors) => { /* cache these */ });
ws.getMarketDescriptors(); // tradable markets only
Each market and descriptor carries products, the pair's products for that market's side. A put market (is_put: true) lists a subset of cash_secured_put, put_spread and cash_put. A call market lists a subset of covered_call and call_spread. settlement is { "type": "pending" } until the market settles, then { "type": "fixed", "price" }. Offer the user only products that appear in products.
To list positions, pass the full filter message. ALL_POSITIONS selects everything:
import { ALL_POSITIONS } from "@acta-markets/ts-sdk/ws";
ws.on("positions", (positions) => { /* PositionInfo[] */ });
ws.getPositions(ALL_POSITIONS);
// Filtered: { market: { type: "only", value: marketPda }, underlying_mint: { type: "all" },
// status: ["open"], min_expiry_ts: { type: "unbounded" } }
6. Create RFQ
Prerequisite: call getMarketDescriptors() and wait for the marketDescriptors event before createRfq. The SDK validates quantity against the market's size_rule (min_size <= quantity <= max_size, (quantity - min_size) % step === 0). Local failures throw before send. A missing server-side rule returns missing_size_rule_for_underlying_mint.
quantity is always in underlying atoms, including for cash-secured puts, spreads and cash puts. Convert a quote-token budget to quote atoms (amount * 10^quote_decimals), then use the integer floor-and-step calculation in Quantity and collateral by product. Use the strike for a cash-secured put or cash put, and upper_strike - lower_strike for a spread. quoteAmountToQuantity rounds to the nearest atom and does not apply size_rule; its result is not a budget-safe RFQ quantity.
terms is a tagged union. side is "sell" to write the product for the premium or "buy" to buy it, see Buying options:
ws.on("rfqCreated", (rfq) => console.log(rfq.rfq_id, rfq.expires_at, rfq.order_options));
ws.on("quoteReceived", (quote) => {
// quote.terms is one of rfq.order_options. price is gross; AcceptQuote uses the gross price, hash-bound via order_id.
// net_price is what a seller receives after the protocol fee, or the gross price a buyer pays.
console.log("Quote:", quote.net_price, "from", quote.maker_owner);
});
await ws.createRfq({
market_pda: marketPdaBase58,
terms: { type: "covered_call", strike: "136000000000" },
side: "sell",
quantity: "1000000000", // 1 SOL in lamports; must satisfy size_rule
timeout_seconds: 30,
request_id: crypto.randomUUID(), // required; also the idempotency key
});
Other products:
{ type: "cash_secured_put", strike: "136000000000" }
{ type: "call_spread", lower_strike: "150000000000", upper_strike: "160000000000" }
{ type: "put_spread", lower_strike: "130000000000", upper_strike: "140000000000" }
{ type: "cash_put", strike: "136000000000" }
Spread and cash put strikes must be multiples of the underlying's strike_tick (1e9-scaled; read it from TokenInfo.role). A spread needs lower_strike < upper_strike, and a call spread needs lower_strike > 0. The market's is_put must match the product's side.
createRfq takes the RfqRequest message and resolves with its request_id on the server's CommandAccepted and rejects with ActaWsRequestError on the matching RequestError, a timeout or a disconnect. RfqCreated echoes request_id and may arrive before or after that receipt. Repeating a createRfq with the same request_id while the RFQ is open is rejected with duplicate_rfq_id, which means the first attempt created it; after the RFQ closes the same id opens a new one. createRfqOnce handles this: it owns the id and resends a lost reply only while the RFQ could still be open. The RFQ TTL is your timeout_seconds, which must be within the venue range min_rfq_timeout_seconds .. max_rfq_timeout_seconds from GET /api/v1/venue.
For spreads and cash puts, order_options holds exactly your terms.
Spread economics
Spreads and cash puts are cash-settled in the quote mint. The writer posts collateral C and receives the net premium. At expiry the holder gets ceil(min(intrinsic, width) * quantity) capped at C, and the writer gets the rest. On a sell you are the writer; on a buy you are the holder. The chain entry point has the exact bigint helpers:
import { ActaHttpClient } from "@acta-markets/ts-sdk/http";
import { SpreadType, spreadPremium, spreadSettlement } from "@acta-markets/ts-sdk/chain";
const venue = await new ActaHttpClient({ baseUrl: "https://devnet-api.acta.markets" })
.venue(AbortSignal.timeout(5_000));
const terms = {
positionType: SpreadType.PutSpread,
lowerStrike: 130_000_000_000n,
upperStrike: 140_000_000_000n,
quantity: 5_000_000_000n,
quoteDecimals: 6,
underlyingDecimals: 9,
};
// Fees belong to the quote token (`getTokens()` or `/api/v1/tokens`).
const fees = quoteToken.protocol_fees;
if (fees.type !== "quote") throw new Error("quote token has no fee config");
// collateral, grossPremium, protocolFee, netPremium (quote atoms)
const economics = spreadPremium(
terms,
BigInt(quote.price), // gross price, 0 < price < width
fees.premium_bps,
fees.volume_bps,
);
// At settlement price S: holderPayoff and writerReturn sum to economics.collateral
const { holderPayoff, writerReturn } = spreadSettlement(terms, 133_000_000_000n, economics.collateral);
spreadPremium throws when the price is not strictly between 0 and the width after rounding. The fee is min(premium_fee, volume_fee). For a cash put, map the terms with executionTerms(terms) from @acta-markets/ts-sdk/ws, which returns a put spread with legs (0, strike), and use SpreadType.PutSpread with lowerStrike: 0n.
Buying options
With side: "buy" you buy the product. The maker writes it from its Maker PDA custody, so only makers subscribed to taker_buy_rfqs with enough custody receive the RFQ. The best buy quote is the lowest price. If no maker can receive it, the RFQ closes at once with reason: "no_eligible_makers".
await ws.createRfq({
market_pda: marketPdaBase58,
terms: { type: "covered_call", strike: "150000000000" },
side: "buy",
quantity: "1000000000",
timeout_seconds: 30,
request_id: crypto.randomUUID(),
});
Accept and sign as for a sell: verifyAndSignTakerFill reads the side from the RFQ and refuses a fill whose side, terms or amounts differ. You pay the gross premium in the quote mint and become the position holder; the maker is the writer. Vault makers do not write buys.
A bought covered call or cash-secured put is exercised by depositing the settlement amount (quote for a call, underlying for a put) strictly before expiry_ts. You sign and pay for this transaction yourself:
import { fetchMarket, fetchPosition } from "@acta-markets/ts-sdk";
import { flows } from "@acta-markets/ts-sdk/chain";
const { ixs } = await flows.buildDepositFundsIxs({
programId,
payer: buyer.address,
owner: buyer,
position: (await fetchPosition(rpc, positionPda)).data,
market: (await fetchMarket(rpc, marketPda)).data,
});
Until expiry_ts you can take the deposit back with flows.buildWithdrawFundsIxs (same arguments); the position is open again and can be funded again. Native SOL comes back wrapped.
To fund several bought positions of one wallet, flows.buildDepositFundsBatchIxs({ programId, payer, owner, items: [{ position, market }] }) returns transactions, each a set of instructions for one transaction (up to nine deposits, fewer across markets), and deposits with each positionPda and amount. Sign the transactions together with signAllTransactions; each lands on its own.
Without a deposit all collateral returns to the writer at expiry, also in the money; the position settles as not_exercised. A bought spread or cash put needs no deposit and settles in cash: holder_payoff is yours. While the chain has settled a position and the server has not sealed that slot, its state is terminal_pending { slot, outcome }; show it, but do not count it.
7. Cancel RFQ
ws.cancelRfq(rfqId);
// Listen for rfqClosed with reason="taker_cancelled"
8. Accept quote and sign
verifyAndSignTakerFill rebuilds the fill from the accepted quote and the RFQ's terms and calls the wallet only if the served transaction matches. It checks:
- the configured program and chain, and the market PDA;
- the order ID recomputed from the quote, quantity and taker (it must equal
quote.order_id); - the maker's Ed25519 signature over that order ID right before the open instruction;
- the open instruction with the quoted terms, quantity, price, validity and nonce (a spread or cash put opens with the quote-mint collateral);
- the ATA creates and, for a covered call on wSOL, a wrap of at most the collateral;
- the keeper as fee payer in slot 0, which is not the taker;
- no other signers or instructions, and a compute budget within
bounds.
A mismatch throws VaultIntentError and nothing is signed.
Inputs the helper needs:
keeper: the canonicalGlobalConfig.hotAuthorityaddress. Read it once from chain.makerVault:await fetchMakerVault(rpc, quote.maker_owner), which is a decodedVaultwhen the quote's maker is a vault PDA andnullfor an ordinary maker. A vault maker needs the account; without it the fill is verified as an ordinary maker's. On a buy from a vault the helper checksOpenPositionForVaultWriter(orOpenSpreadForVaultWriter) with holder byte1: your wallet signs and pays from its quote ATA, and the vault delegate's Ed25519 check covers only the order id.rfq: aTakerFillRfqbuilt from the RFQ (below). Both variants needrfq_id,market_descriptor(the descriptor'smarket_descriptor),terms,side,quantityandorder_options. A spread or cash put also needsunderlying_decimalsandquote_decimalsfrom the descriptor, and itsorder_optionsmust hold exactlyterms.tables: address lookup tables,{}for sponsored fills.
TakerFillRfq is a union: the physical variant (terms is covered_call or cash_secured_put) and the cash variant (terms is a spread or cash_put, with decimals). Build it with a function that narrows terms:
import type {
CashPutTerms, MarketDescriptorInfo, PhysicalOptionTerms, RfqCreatedMessage,
SpreadOptionTerms, TakerFillRfq,
} from "@acta-markets/ts-sdk/ws";
function fillRfq(created: RfqCreatedMessage, descriptor: MarketDescriptorInfo, quantity: number): TakerFillRfq {
const base = { rfq_id: created.rfq_id, market_descriptor: descriptor.market_descriptor, side: created.side, quantity };
const { terms } = created;
if (terms.type === "covered_call" || terms.type === "cash_secured_put") {
return {
...base,
terms,
order_options: created.order_options.filter(
(o): o is PhysicalOptionTerms => o.type === "covered_call" || o.type === "cash_secured_put",
),
};
}
return {
...base,
terms,
order_options: created.order_options.filter(
(o): o is SpreadOptionTerms | CashPutTerms => o.type !== "covered_call" && o.type !== "cash_secured_put",
),
underlying_decimals: descriptor.underlying_decimals,
quote_decimals: descriptor.quote_decimals,
};
}
import { address, createSolanaRpc } from "@solana/kit";
import {
fetchGlobalConfigByAddress,
fetchMakerVault,
findGlobalConfigPda,
} from "@acta-markets/ts-sdk/chain";
import { ActaWsRequestError, verifyAndSignTakerFill } from "@acta-markets/ts-sdk/ws";
const rpc = createSolanaRpc(rpcUrl);
const globalConfig = await fetchGlobalConfigByAddress(rpc, await findGlobalConfigPda());
const keeper = globalConfig.account.hotAuthority;
let connectionEpoch = 0;
ws.on("stateChange", () => { connectionEpoch++; });
// acceptedQuote: the QuoteReceivedMessage you accepted; descriptor: the cached
// MarketDescriptorInfo of the RFQ's market; rfqCreated: the RfqCreated frame; requestedQuantity: what you passed to createRfq.
ws.on("sponsoredTxToSign", async (id, txBase64, signatureDeadline, lastValidBlockHeight) => {
if (id !== orderIdHex || !ws.isAuthenticated()) return;
const epoch = connectionEpoch;
const walletMatches = () => wallet.publicKey?.toBase58() === walletPublicKeyBase58;
const expired = () => Date.now() / 1000 >= signatureDeadline;
if (!walletMatches() || expired()) return;
let signedTxBase64: string;
try {
signedTxBase64 = await verifyAndSignTakerFill({
txBase64,
quote: acceptedQuote,
rfq: fillRfq(rfqCreated, descriptor, requestedQuantity),
keeper,
taker: address(walletPublicKeyBase58),
makerVault: await fetchMakerVault(rpc, acceptedQuote.maker_owner),
tables: {},
bounds: { maxUnitLimit: 400_000, maxUnitPriceMicroLamports: 100_000 },
signer: wallet,
});
} catch (error) {
console.error(id, error); // do not submit; cancel the RFQ or pick another quote
return;
}
if (epoch !== connectionEpoch || id !== orderIdHex || !walletMatches() || expired()) return;
// Sends the order at most once; a lost reply is resolved with GetOrderStatus, not a resend.
const outcome = await ws.submitOrderOnce({ orderIdHex: id, txBase64: signedTxBase64 });
if (outcome.type === "rejected") {
// Not forwarded: act on outcome.action (fix_request, refresh, ...), or choose another quote.
} else if (outcome.type === "reconciled" && outcome.state.type !== "confirmed") {
// pending or unknown: wait for OrderConfirmed / OrderFailed; never sign this order again.
}
});
try {
await ws.acceptQuote(rfqId, makerPubkey, orderIdHex);
} catch (err) {
if (err instanceof ActaWsRequestError) console.error(err.kind, err.error);
}
acceptQuote resolves on CommandAccepted and rejects with ActaWsRequestError on its RequestError, a timeout or a disconnect; SponsoredTxToSign may arrive before or after the receipt. submitOrderOnce above applies the following rules for you. A rejected submitSignedSponsoredTx carries err.delivery. not_forwarded means this attempt was not sent; if every attempt for the order returned it, retrying or choosing another quote is safe. unknown, or no delivery (timeout, disconnect), means it may have been sent: query GetOrderStatus before signing or submitting anything for that RFQ. lastValidBlockHeight is the block height the served transaction's blockhash is valid through.
verifyAndSignTakerFill fills signature slot 1, the taker's slot. The keeper pays fees and signs slot 0, for ordinary and vault makers alike.
orderIdHex is the application's selected order. If the wallet, connection or selection changes during signing, discard that result. Track the sent state before submitting and use the recovery rules below when the result is uncertain.
Browser wallets. To show the wallet's own transaction preview and simulation, pass signer: { signTransaction: async (wire) => (await wallet.signTransaction(VersionedTransaction.deserialize(wire))).serialize() }. The SDK verifies the transaction before the wallet sees it and verifies what the wallet returns again (a wallet that reorders account keys passes; one that adds or changes instructions does not). Never call wallet.signTransaction on a served transaction directly. @solana/web3.js is needed only for that UX path. It is the wallet adapter's own dependency, not the SDK's.
9. Track order status
ws.on("orderAccepted", (orderIdHex, orderVersion) => {});
ws.on("orderSubmitted", (orderIdHex, txSignature, orderVersion) => {});
ws.on("orderConfirmed", (orderIdHex, positionPda, orderVersion) => {});
ws.on("orderFailed", (orderIdHex, reason, orderVersion) => {});
ws.on("rfqClosed", (data) => {
// Terminal: clean up RFQ state.
// data.reason: "expired" | "taker_cancelled" | "filled" | "market_expired" | "no_eligible_makers" | "server_shutdown"
// data.your_quote and data.winner are { type: "none" } when they do not apply.
});
10. Recover an interrupted order
Persist the selected rfq_id, maker, order_id, auth session and whether SubmitSignedSponsoredTx was sent, scoped to the wallet and backend. Keep them across reconnect and page reload, separately from the browsing cache. Do not persist signed transaction payloads for replay.
After a successful resume of the same auth session, reconcile with GetMyActiveRfqs. If the same order is still pending_signature, repeat only that exact AcceptQuote to retrieve its signing payload, and respect the original signature deadline. If it is enqueued, or the transaction was already sent, query GetOrderStatus instead of signing or submitting again.
ws.on("orderStatus", ({ order_id, state }) => {
switch (state.type) {
case "confirmed":
console.log(order_id, "opened position", state.position_pda);
break;
case "pending":
console.log(order_id, "execution pending");
break;
case "unknown":
console.log(order_id, "outcome unresolved");
break;
}
});
OrderFailed, a timeout and unknown do not prove nonexecution. Do not automatically replay a trading command after losing its response. When RfqAvailableAgain reopens an auction, refresh the available quotes. The discarded winning quote is not an automatic retry target.
Connection management
// Devnet; for mainnet use "wss://beta-api.acta.markets"
const wssEndpoint = "wss://devnet-api.acta.markets";
const ws = new ActaWsClient({
url: wssEndpoint,
role: "taker",
onDisconnect: "keep_quotes",
products: ["covered_call", "cash_secured_put", "call_spread", "put_spread", "cash_put"],
clientName: "my-app",
clientVersion: "0.1.0",
autoReconnect: true,
reconnectDelay: 1000,
maxReconnectDelay: 30000,
reconnectJitterRatio: 0.2,
pingInterval: 30000,
maxPendingMessages: 100,
pendingMessagesOverflowPolicy: "drop_oldest", // "drop_oldest" | "drop_newest" | "throw"
});
ws.on("disconnected", (code, reason) => {});
// code: a server close code (4000–4006; see ws-common.md) or one of the client's own drops:
// 4900 "pong_timeout", 4901 "auth_error".
Close code 4006 (unsupported_protocol_version) means the server did not accept the protocolVersion the client sent. The default is 1.0.0; leave it unset.
Recovery on reconnect. The SDK reconnects and resumes authentication after network drops. A skipped unknown or invalid frame triggers the same reads, at most once every 5 seconds, with autoReconcile on. After authenticated, it restores the desired subscriptions and, with the default autoReconcile, requests GetMyActiveRfqs and GetPositions (all positions). Authentication alone does not mean these reads have completed.
Wait for those responses before rebuilding application state, and request GetOrderStatus for each unresolved order. Apply the exact-order recovery rules above. Do not clear an unresolved order because it is missing from an RFQ or position response.
Transport note: during reconnect, WebSocket control frames (Ping, Pong) may arrive before the first protocol JSON message. The client ignores control frames until Welcome or Error.
Error handling
ws.on("error", (e) => {
if (e.type === "Generic") console.error(e.data.code, e.data.message);
else console.error(e.type);
});
ws.on("requestError", (envelope) => {
// { request_id, error: ServerError, delivery: "not_applicable" | "not_forwarded" | "unknown" }
});
Every query has two forms. getMarkets(), getPositions(args), getOrderStatus(id) and the rest return a request_id; match it against msg.request_id on the response event. The Async form (getMarketsAsync(), getPositionsAsync(args), getMyCapsAsync(), …) returns a promise of the whole response, all pages included, and rejects with ActaWsRequestError.
Error codes and OrderFailed reasons: Taker API reference. Common cases: Integration FAQ.
Other features
- Invite gating (closed mainnet). If
requireInvitefires, redeem before trading viaredeemInvite(rawCode). Claim your own code withclaimReferralCodeand inspect stats withgetMyReferralInfo. Errors: Taker API reference. - Token caps.
getTokenCaps(includeMarkets)->tokenCapsevent. The flag is required and the server ignores it. The response carriestokens,markets,quotesandquote_liabilities, all always present. Schema: Taker API reference and Capacity limits. - Earn summary.
getEarnSummary()->earnSummaryevent. APR range (aprisunavailableoravailable { min, max }) and capacity per asset for landing pages. - Market price snapshot.
getTokenMarketsInfo(underlyingMint)->tokenMarketsInforeturns backendreference_price, size rules, decimals and indicative premiums together. See TokenMarketsInfo. Correlate the response with the returned request ID and the mint you requested; the response does not echo the mint. Refresh while the view is active; the Acta web app uses 30 seconds. - Indicative prices.
getIndicativePrices({ market, position_type, side })->indicativePricesevent. Available forcovered_callandcash_secured_put, per takerside: each strike'spriceis the median maker price ({ type: "quoted", price }, or{ type: "none" }), net of the protocol fee forselland the gross price paid forbuy. A spread or cash put request returns anErrorwithspread_invalid_strikes. Non-binding UI reference prices; the server refreshes roughly every 30s. - Expiries.
getExpiries({ underlying_mint, quote_mint, is_put })takes{ type: "all" }or{ type: "only", value }for each filter. - APR inputs. Use spot and indicative premium from the same
TokenMarketsInforesponse. Suppress the preview when the price is unavailable or the indicativefreshnessis notfresh. Clear cached metadata after a failed refresh or disconnect. Pyth credentials belong on the backend, not in browser code. - APR and APY helper.
computeApyFromScaledPrices({ underlyingAmount, grossPremiumPerUnit1e9, spotPrice1e9, secondsToExpiry })from@acta-markets/ts-sdk/wsreturns{ premiumNotional, collateralNotional, termYield, apr, apy }.spotPrice1e9is required: collateral is valued at spot for calls and puts.computeApyFromAmounts({ underlyingAmount, premiumPerUnderlying, spotPrice, secondsToExpiry })takes human units. For the market preview, pass thesellsidebest_priceasgrossPremiumPerUnit1e9: the backend already nets the protocol fee out of it. Do not subtract the fee a second time. - Fill premium.
totalPremiumQuoteAtoms(price, quantity, underlyingDecimals, quoteDecimals)returns the gross premium in quote atoms as abigint, rounded as the contract rounds it. The net premium istotal_premiumon the position row. - Nonces.
generateNonce()from@acta-markets/ts-sdk/wsreturns a freshbigintnonce for signed orders. - Program events.
decodeActaEventsFromLogsScoped(logs, programId)from@acta-markets/ts-sdkdecodes only events emitted by that program. - Instruction builders. Builders in
@acta-markets/ts-sdk/chainthat resolve a mint's token program needtokenProgramorrpc. With neither they throw. - Vault catalog. An authenticated session subscribed to
vaultsreceivesvaultCatalogChanged({ vault_pda }) when a vault is created, re-delegated or closed, andvaultProjectionAdvancedwhen a vault's state changes. Neither is replayed. Re-list vaults withGET /api/v1/vaults(or reload/api/v1/vaults/{pda}) on them and after everyauthenticated.
Production notes
- Sponsored transactions are v0
VersionedTransactions. ThesignTransactionsigner requires versioned transaction support and can show the wallet's preview. AsignMessagesigner signs raw message bytes and does not guarantee a transaction preview. - If the wallet cannot sign arbitrary bytes, WS auth does not work directly. Use a server-side signer through
CustomAuthProvider. - Cache
keeperand the market descriptors. Re-read descriptors onreferenceChanged.
Support
- Devnet:
wss://devnet-api.acta.markets - Mainnet:
wss://beta-api.acta.markets - Questions: contact the Acta team