Instant Open
Instant Open is the delegated flow for opening a position — on both solver kinds (Enigma lowcap and Rasa majors); instantOpen dispatches on the resolved solver’s kind (see Per-solver behavior). The user signs an EIP-712 message, the SDK submits it to the solver, and the solver returns a tempQuoteId immediately — this confirms acceptance, while the position remains pending until an open notification or an on-chain read confirms the fill.
The SDK splits the flow into three functions on purpose:
prepareInstantOpenParams— resolve every derivable input (market metadata, mark price, locked params, fee rates) into the exact wire-shapedInstantOpenParametersbag.instantOpen— sign + submit. Requires the fully-resolved bag.instantOpenAuto— prepares the order, then signs and submits.
The split lets you access, cache, or override any step. It also has a latency implication: instantOpenAuto runs the prepare fetches inline, so the wall-clock from “user clicks” to “signature dialog” is prepare fetches + sign + POST. If you already have the pre-fetched data (from a preview screen, a quote review, an earlier order), call instantOpen directly and you get straight to sign + POST — faster fills, tighter price windows.
Plus read helpers for the pending queue: getInstantOpens (paginated list), getInstantOpenQuoteId (resolve on-chain id for a given tempQuoteId).
Import
import {
instantOpen,
instantOpenAuto,
limitOpenAuto,
prepareLimitOpenParams,
prepareInstantOpenParams,
getInstantOpenFees,
getInstantOpens,
getInstantOpenQuoteId,
type PrepareInstantOpenParameters,
type PrepareLimitOpenParameters,
type InstantOpenParameters,
type InstantOpenReturnType,
type InstantOpenAutoReturnType,
type InstantOpenEstimateMetadata,
type OpenEstimateStatus,
type PendingInstantOpen,
} from "@symmio/trading-core";The three-function split
instantOpenAuto prepares the order and passes it directly to instantOpen for signing
and submission. It does not perform an additional account-balance read or balance check
before signing. Frontends decide whether to check the account balance before requesting
submission.
The lower-level preparation and submission functions let you:
- You can cache the prepared bag (e.g. render a review screen with the resolved trade math and only submit after user confirmation).
- You can override any resolved field (e.g. pin a mark price you fetched elsewhere, skip a locked-params fetch by supplying it directly).
- You can run prepare early — kick off the fetches when the user opens the trade panel, then when they click Open you only sign + POST.
- You can inspect the exact numbers being signed before the network hop.
instantOpen on its own is the “I already have everything, just submit” primitive. Pair it with a manual prepareInstantOpenParams call staged earlier when open latency matters.
prepareInstantOpenParams
Pure resolver. Takes the minimal UI-shaped inputs (wallet, market, side, margin, leverage, slippage) and returns the full InstantOpenParameters bag needed by instantOpen.
Steps (in order):
- Validate the user’s
slippage— a non-finite value or one outside[0, 100)throwsINVALID_SLIPPAGEbefore any network work. On a lowcap (Enigma) solverslippagemay be omitted and is auto-derived: the SDK dry-runs the mark-sized order and sets the price bound to the estimated fill price plus 4% headroom (flat 4% off mark when the estimate is unavailable). On majors an omittedslippagethrowsSLIPPAGE_REQUIRED— the estimate-driven behavior in steps 4–5 is lowcap-only, and a majors prepare is unchanged from the classic flow (locks + platform fee, no estimate fetch). - Resolve market metadata, mark price, locked params, and fee rates — fetched concurrently, with any caller-supplied field short-circuiting its fetch.
- Run
calculateTradeParamsto deriverequestedOpenPrice, the mark-sizedquantity(initialMargin × leverage / markPrice),cva,lf,partyAmm,partyBmm,notional. - Dry-run the sized order via
GET /estimated-price: when the expected fill deviates from mark beyond the slippage tolerance (|estimated − mark| / mark > slippage/100), the call rejects withSLIPPAGE_EXCEEDED. Technical unavailability permits the reference-price fallback; a solver refusal or cancellation propagates. Pass a pre-fetchedestimatedOpenPriceto skip the round-trip, ornullwhen an estimate was already attempted but unavailable. The request has no added timeout. - Derive the
addMarginamount viacalculateMargin:locks + platformOpenFee + openSolverFee + staticSolverFeeOpen + expectedSettlementLoss— the open-side legs only. Close fees are not funded here; the contract charges them at close from the position (see Fees at close). Lowcap only — the open funds the solver’s open fee (hedgerFeeOpen × leveraged notional), its flat static open fee (a USD amount fromgetSolverInfo, size-independent) and the open-price settlement (side-awaremax(0, adverse fill − mark) × quantityvs the dry-run estimate) from the VA balance, so the SubAccount → VA transfer must fund every open-side leg. A lowcap SHORT additionally funds its locks atmark × 1.01(SHORT_FUNDING_BUFFER_PERCENT) — the request price is a contract floor, so a fill above it rescales the signed locks up and the prefund needs that headroom. On majors the margin stayslocks + platformFeeat the classic basis. - Convert every value to 18-decimal-wei
bigint.
const resolved = await prepareInstantOpenParams(config, {
from: sessionKey,
subAccountAddress,
market: { id: 1 },
positionType: PositionType.LONG,
initialMargin: "100",
leverage: 5,
slippage: 1,
});
// `resolved` is now inspectable, hashable, and ready to sign.
console.log(resolved.order.quantity, resolved.order.price, resolved.margin?.amount);Unavailable-estimate fallback
Preparation always needs a positive, finite reference mark that remains positive in contract units. It uses the supplied markPrice, or the price service when omitted. A missing mark produces RESOLVE_MARK_PRICE_NOT_FOUND; an unusable resolved mark produces OPEN_PRICE_UNAVAILABLE. Preparation rejects before signing or submitting a zero-price order. No historical price or no-shadow diagnostic is substituted automatically.
Lowcap opens use fallback for network failures, HTTP 408/429/5xx responses without a solver error envelope, and solver errors categorized as internal, unavailable, timeout or rate_limit. When the category is absent, a known technical code such as 3000 (internal) or 3405 (timeout) also permits fallback. A missing or unusable execution price permits fallback.
A missing estimate route and a missing market have different outcomes. The solver’s HTTP 404 with code 404, category validation and detail /estimated-price identifies the missing route and permits fallback. A bare 404, market error 3105, disabled market 3113, solver slippage refusal 3401, or permission failure stops preparation with OPEN_ESTIMATE_REJECTED. Error envelopes can arrive with HTTP 200. The SDK recognizes numeric and decimal-string codes in code and error_code and explicit failure markers such as successful: false. A usable execution price outside the user’s tolerance raises SLIPPAGE_EXCEEDED.
When unavailable, the mark remains the sizing reference and the signed price remains mark × (1 + slippage/100) for LONG or mark × (1 − slippage/100) for SHORT, at the market’s price precision. Explicit slippage is unchanged. If omitted, the existing lowcap default is 4%. Preparation and fees reserve settlement against that signed bound in both typed-margin and full-balance modes. The eventual fill remains subject to the solver and contract price checks; fallback does not guarantee execution or an exact fill price. See the contract execution-price rules .
When openEstimateStatus === "unavailable", label the mark as a reference estimate and expectedSettlementLoss as the settlement reserve at the user’s slippage limit. Actual settlement depends on the fill. Preparation waits for its estimate by default. An integrator can supply a deadline on a direct estimate request.
Full-balance funding (lowcap)
Fund with a typed initialMargin or with fund — never both. fund deploys the user’s entire selected collateral into the position’s Virtual Account and sizes the quantity to fit it. It is lowcap (Enigma) only.
With a typed initialMargin, the SubAccount keeps back whatever the position did not consume (locks + open-side fees + settlement). A user who deposited $100 and pressed “Max” therefore saw a smaller spendable figure and left dust behind. In full-balance mode the whole $100 moves to the VA, and the SDK shrinks the quantity instead so its locks + open-side fees + worst-case settlement fit inside it — nothing is stranded, and the figure deployed is the figure picked. Close fees are not sized into the budget; the contract charges them at close from the position (see Fees at close), so the same balance sizes a slightly larger position than it did when close fees were pre-funded. Any tiny remainder rides as free VA margin.
How it sizes:
- Static-fee carve — the solver’s flat static open fee (
getSolverInfo) is size-independent, so it would break the linear solve below. It is subtracted from the balance first and the position is sized against the remainder; a balance that cannot cover it throwsINVALID_TRADE_PARAMETERS. (The static close fee is not carved off — it is charged at close, not funded here.) - Probe — run the trade math with the remaining balance as margin input and price its cost legs. Every leg is linear in the sizing input at a fixed fill price, so
balance / probeMarginis the exact factor that makes locks + open-side fees + settlement equal the balance. - Rescale by that factor, less a
0.1%safety epsilon that (together with the maintenance-marginpartyAmmlock) absorbs a fill landing a hair worse than the estimate. - Lot snap — the rescaled quantity is snapped down to the market’s lot grid (falling back to the quantity-precision quantum when the market publishes no lot size), and the locked values are rebuilt from the exact snapped quantity. Down is the safe direction: less quantity always needs less margin.
- Cost invariant — the costs are recomputed and, while
locks + open-side fees + settlement > balance, the quantity steps down one grid step. The linear factor only mispredicts through precision rounding — worth at most a few quanta — so the loop is short and guarantees the funded VA is never smaller than what the signed quote locks. - Constraint validation — the final quantity is validated against the market’s published quote constraints (lot multiple, min/max notional, max quantity, min quote value, LF portion). A violation throws
QUOTE_CONSTRAINT_VIOLATED.
Budget sizing uses the existing trade formulas. The signed price is derived from
mark and slippage: mark × (1 + slippage / 100) for LONG and
mark × (1 - slippage / 100) for SHORT, rounded down to the market’s price precision.
Percentage opening fees use the final quantity times that signed price. SHORT
collateral uses the buffered mark basis mark × 1.01. Static opening fees are
taken from the budget before sizing. The expected fill price supplies the
settlement provision described below.
Settlement is budgeted at the expected fill when the dry-run estimate exists — and at the slippage bound (the signed request price vs mark) when it does not. Never at zero: a full-balance open leaves nothing behind in the SubAccount to absorb an optimistic estimate, so an unavailable estimate must fail safe.
Note the sizing factor can exceed 1: when the market’s locked-param percents sum below 100, a position’s locks + open-side fees cost less than the margin figure that sized it, so deploying everything can open a larger position than typing the same number as initialMargin. Full-balance sizes the quantity to fit the balance — in either direction. The estimate is only trusted at or below the probe size it was quoted for, though: when the factor would upsize past the probe, the sizing re-solves with settlement at the slippage bound (and when even the bound model no longer upsizes, it clamps to the probe size, where the estimate is still valid).
const resolved = await prepareInstantOpenParams(config, {
from: sessionKey,
subAccountAddress,
market: { id: 1 },
positionType: PositionType.LONG,
fund: { mode: "full-balance", balance: "100" }, // deploy all $100 — no initialMargin
leverage: 5,
// slippage optional on lowcap — auto-derived from the dry-run estimate
});
// addMargin === the full 100; quantity is sized so locks + open-side fees + settlement fit inside it (close fees charged at close).Automatic fallback from typed margin
For lowcap market opens, pass availableBalance alongside initialMargin to automatically fit an oversized position into the available collateral:
const prepared = await prepareInstantOpenParams(config, {
from: sessionKey,
subAccountAddress,
market: { id: 1 },
positionType: PositionType.LONG,
initialMargin: "100",
availableBalance: "100", // raw available collateral, before fee deductions
leverage: 5,
slippage: 1,
});
// prepared.fundingMode: "initial-margin" | "full-balance"
// prepared.order.quantity: final quantity, including any automatic reduction
await instantOpen(config, prepared);The SDK first rejects a typed initialMargin greater than availableBalance with INVALID_TRADE_PARAMETERS (“Initial margin exceeds available balance.”). For example, typing $101 with a $100 balance produces an error.
When the typed amount is within the balance, the SDK calculates the position’s required funding: locked margin, open-side fees, settlement provision, and the existing SHORT funding buffer. If this amount is greater than availableBalance, it uses the full-balance formula above and transfers the whole balance. At equality, or below it, typed sizing stays unchanged. For example, typing $100 with a $100 balance can produce a position requiring $102 after costs; that position is resized to fit $100.
availableBalance is a positive, finite decimal string supplied by the caller; the SDK does not fetch or reserve this balance. Use the raw SubAccount available balance, not the fee-adjusted maximum initial margin. Keep it current and pass the same inputs to preview and submission. The decision is recalculated on each call, so reducing the typed amount or increasing the balance can restore "initial-margin" mode.
This option is lowcap-only. It cannot accompany fund; explicit full-balance funding already supplies its own balance. Omitting it preserves existing typed-margin behavior. Market minimums, invalid inputs, slippage checks, and balances unable to cover the static open fee still produce errors. Close fees are not added to the open budget.
getInstantOpenFees accepts the same availableBalance and returns the same effective fundingMode and sized quantity. Even with includeSettlementInTotalFee: false, settlement remains part of the sizing budget; that option changes only the displayed fee total. Both query keys include availableBalance.
validateInstantOpenBalanceFunding
Run the same balance validation synchronously before fetching a price estimate or other trade inputs:
import { validateInstantOpenBalanceFunding } from "@symmio/trading-core";
validateInstantOpenBalanceFunding({
initialMargin: "100",
availableBalance: "100",
isLowcap: true,
});Pass optional initialMargin, availableBalance, and fund, plus required isLowcap (whether the selected solver supports lowcap opens). The function returns nothing when validation passes and does nothing when availableBalance is omitted. With a balance supplied, it throws INVALID_TRADE_PARAMETERS for nonpositive/nonfinite amounts or a typed margin above balance, AMBIGUOUS_FUNDING for fund plus availableBalance, and FULL_BALANCE_UNSUPPORTED when isLowcap is false. Preparation and fee preview also call it internally. It validates balance funding only; market constraints and complete order validation still run during preparation.
Quote preview — prepareInstantOpenParamsQueryOptions
prepareInstantOpenParams neither signs nor submits — it only resolves inputs and builds the params — so it is safe to run live as a read. prepareInstantOpenParamsQueryOptions(config, options) wraps it as a TanStack Query, so a UI can render a “quote preview” that is bit-for-bit the InstantOpenParameters the submit will sign: the same order (price + quantity), lockedParam, margin.amount, and solverFeeCaps. No separate local recomputation to drift, and the full-balance rescale + lot snap are included for free.
The query is disabled until a funding source exists (a non-empty initialMargin, or a fund with a balance). Pre-fill the optional inputs (markPrice, feeRates, lockedParamPercent, estimatedOpenPrice, market metadata) so the query function is pure and does no per-render network. The slippage gate still runs, so an out-of-tolerance estimate surfaces as the query error — the honest preview of a quote the submit would also reject.
Preparation accepts estimatedOpenPriceTimestamp (epoch milliseconds) for
compatibility but does not use it. Core does not expire caller-supplied estimates
based on their timestamp. The frontend decides when to refresh an estimate or
allow submission after a delay.
Disabled markets still support metadata resolution and order preparation. The
frontend can inspect isValid in the market listing and decide whether to offer
order submission.
For both preparation and fee preview, estimatedOpenPrice accepts a decimal string, null (explicitly unavailable; skip the fetch), or undefined/omission (fetch if needed). A technically unavailable estimate uses reference-price fallback: omitted slippage uses 4%, explicit slippage stays unchanged, the estimate gate is skipped, and both funding modes provision settlement at the signed price bound. Pass the same estimatedOpenPrice to preview and submission, preserving null. With automatic or explicit full-balance sizing, settlement affects the funding decision and final quantity as well as margin.amount. Keep the balance, mark price, fee inputs, and market metadata consistent too. In React, usePrepareInstantOpenParams wraps this and returns the estimate it used for exactly that.
import { prepareInstantOpenParamsQueryOptions, PositionType } from "@symmio/trading-core";
useQuery(
prepareInstantOpenParamsQueryOptions(config, {
subAccountAddress,
from: sessionKey,
market: { id: 1 },
positionType: PositionType.LONG,
initialMargin: "100",
leverage: 5,
slippage: 1,
}),
);
// data.order.quantity / data.lockedParam.cva / data.margin.amount — exactly what the send signs.Fee preview — getInstantOpenFees
Preview every fee a new quote pays at open, separated by leg plus the total, without signing or submitting anything. Same parameters shape as the wizard (minus the signer), same resolution and math — the preview equals what prepareInstantOpenParams charges for the same inputs. The result is a kind-discriminated union of the open-side legs only:
| Fee leg | Formula | Enigma (lowcap) | Rasa (majors) |
|---|---|---|---|
platformOpenFee | getFeeForUser.openFee × notional | ✔ | ✔ |
openSolverFee | hedgerFeeOpen × notional | ✔ | — |
staticSolverFeeOpen | flat USD (solver /info) | ✔ | — |
expectedSettlementLoss | max(0, adverse fill − mark) × quantity | ✔ | — |
Close fees are not part of this preview — the contract charges them at close from the position, and they are previewed in the close flow with getInstantCloseFees, where the close notional and the holding-time solver rate are real (concept: Fees at close).
totalFee sums the open legs. It includes the expectedSettlementLoss provision by default — the provision is part of what the open funds, even though it is a provision rather than a fee the solver keeps; pass includeSettlementInTotalFee: false to sum the fee legs only (the provision stays available as its own field). On majors totalFee is just platformOpenFee. notional (the leveraged notional the rates were applied to) is returned alongside for rate displays, together with quantity — the leveraged base-asset quantity the legs were computed on.
staticSolverFeeOpen is a flat USD amount from the solver’s getSolverInfo config — it does not scale with the notional, and is "0" when the solver publishes none; pre-fill solverInfo (the getSolverInfo result) to skip the fetch. The fetch is fail-soft: an unreachable /info prices the leg at "0" instead of failing the preview.
The funding one-of applies here too: pass a typed initialMargin or fund (see Full-balance funding). A fund preview runs the exact same sizing as the open — probe, linear rescale, lot snap, cost invariant, slippage-bound settlement fallback — so the legs and quantity equal what the open will actually charge and submit. Feed that quantity to TP/SL and constraint previews instead of re-deriving it from a typed figure. Full-balance sizing additionally consults the solver’s locked-param percents; pre-fill lockedParamPercent to skip that fetch.
const fees = await getInstantOpenFees(config, {
subAccountAddress,
market: { id: 1 },
positionType: PositionType.LONG,
initialMargin: "100",
leverage: 5,
// slippage — required on majors; omit on lowcap to auto-derive
});
console.log(fees.totalFee); // open legs summed (settlement provision included) — gate the open budget on this
if (fees.kind === "enigma") console.log(fees.openSolverFee, fees.expectedSettlementLoss);getInstantOpenFeesQueryOptions / getInstantOpenFeesQueryKey ship alongside for TanStack Query consumers; the React layer wraps them as useInstantOpenFees. Pass the preview’s markPrice / estimatedOpenPrice / feeRates into the subsequent prepareInstantOpenParams call to make the actual open zero-fetch and guarantee the charged fees match the previewed ones.
Parameters
Required = inputs only the caller can know (wallet, session key, trade intent). Optional = anything derivable from solver / price-service / on-chain reads.
Every optional field you pre-fill skips its network fetch. If you already have markPrice from a live price stream, lockedParamPercent from a cached solver read, or feeRates from an earlier getFeeForUser call, pass them in — prepareInstantOpenParams short-circuits each field and only fetches what’s still missing. Pass all four optional derivable fields and the function becomes pure math with zero network hops — the fastest possible path from UI inputs to a signed message.
| Name | Type | Required | Notes |
|---|---|---|---|
from | Address | ✔ | Session-key signer. |
subAccountAddress | Address | ✔ | SubAccount that owns the trade. |
market | InstantOpenMarketData | ✔ | { id }, plus optional pre-fetched metadata (precisions, minOpenSolverFeeCap / minCloseSolverFeeCap). |
positionType | PositionType | ✔ | LONG / SHORT. |
initialMargin | string | ✔ † | Decimal collateral amount. Provide this or fund. |
availableBalance | string? | Raw positive collateral budget enabling automatic fallback with initialMargin. Lowcap only; cannot accompany fund. | |
fund | FullBalanceFunding? | ✔ † | { mode: "full-balance", balance } — deploy the whole balance, size quantity to fit. Lowcap only. Or initialMargin. |
leverage | number | ✔ | Positive integer / decimal. |
slippage | number? | Percent (e.g. 1 for 1%). Required on majors; on lowcap, omit to auto-derive from the dry-run estimate + 4%. | |
markPrice | string? | Pre-fetched mark price (decimal). Omit to fetch via Enigma. | |
estimatedOpenPrice | string | null | Pre-fetched estimated fill price (decimal). Lowcap/Enigma only — ignored elsewhere. Omit to fetch via dry-run; null skips the fetch and uses the unavailable-estimate fallback. | |
lockedParamPercent | ApiLockedParamsBySymbolIdResponse? | Pre-fetched solver locked params. Omit to fetch via getLockedParams. | |
feeRates | FeeForUser? | Pre-fetched on-chain fee rates. Omit to fetch via getFeeForUser. | |
solverInfo | EnigmaSolverInfo? | Pre-fetched solver static fees. Lowcap/Enigma only — ignored elsewhere. Omit to fetch via getSolverInfo (fail-soft). | |
uuid | string? | Forwarded to InstantOpenParameters. | |
addMarginSalt | Hex? | Forwarded. | |
sendQuoteSalt | Hex? | Forwarded. | |
deadline | bigint? | Forwarded. | |
chainId | number? | Optional chain override. |
† Funding is one-of: pass exactly one of initialMargin or fund. Passing both throws AMBIGUOUS_FUNDING; passing neither throws INITIAL_MARGIN_REQUIRED.
Returns
PrepareInstantOpenParamsReturnType — the full InstantOpenParameters bag plus fundingMode: "initial-margin" | "full-balance" and InstantOpenEstimateMetadata. Pass it directly to instantOpen. These additional fields describe preparation; they are not signed order fields.
PrepareInstantOpenParamsData uses this same return type for query consumers. Fee results (BaseInstantOpenFees and its solver variants) also expose fundingMode.
OpenEstimateStatus and InstantOpenEstimateMetadata
type OpenEstimateStatus = "available" | "unavailable" | "unsupported";
interface InstantOpenEstimateMetadata {
openEstimateStatus: OpenEstimateStatus;
estimatedOpenPrice: string | null;
}
type InstantOpenAutoReturnType = InstantOpenReturnType & InstantOpenEstimateMetadata;| Field | Meaning |
|---|---|
openEstimateStatus | available: usable solver estimate; unavailable: lowcap reference-price fallback; unsupported: solver has no open estimate (majors behavior is unchanged). |
estimatedOpenPrice | Exact solver fill estimate, or null when unavailable/unsupported. This field never substitutes the mark. |
Preparation, all fee-result variants, and instantOpenAuto return this metadata. instantOpenAuto preserves the metadata from its single preparation alongside the accepted submission result. The lower-level instantOpen and prepared-request submit functions retain their existing return shape; keep the metadata from preparation when using those primitives. Prefer InstantOpenAutoReturnType for automatic submission results.
Errors
OPEN_PRICE_UNAVAILABLE— reference price is malformed, non-finite, nonpositive or unusable in contract units.OPEN_ESTIMATE_REJECTED— solver refused the estimate; fallback is prohibited.ESTIMATED_PRICE_CANCELLED— open estimate was cancelled; fallback is prohibited.SLIPPAGE_EXCEEDED— a valid estimate exceeds the selected tolerance.RESOLVE_MARKET_NOT_FOUND— solver has no market for that id.RESOLVE_MARKET_METADATA_INCOMPLETE— market response missing precision fields.RESOLVE_MARK_PRICE_NOT_FOUND— price service returned no tick for the symbol.INVALID_TRADE_PARAMETERS— invalid trade inputs, including a typedinitialMarginaboveavailableBalance, or a balance unable to cover the static open fee.AMBIGUOUS_FUNDING— bothinitialMarginandfund, or bothavailableBalanceandfund, were passed.INITIAL_MARGIN_REQUIRED— neitherinitialMarginnorfundwas passed.FULL_BALANCE_UNSUPPORTED—fundoravailableBalancewas used on a non-lowcap (majors) solver.QUOTE_CONSTRAINT_VIOLATED— the full-balance-sized quantity violates a published market constraint (lot multiple, min/max notional, max quantity, min quote value, LF portion).
instantOpen
Sign the EIP-712 message with config.getWalletClient({ from }) and POST it to the solver. This is the low-latency primitive — everything above (prepareInstantOpenParams) has already run; this step is just sign + network, plus one delegation read when a session key signs (see Delegation preflight).
const result = await instantOpen(config, resolved);
console.log(result.tempQuoteId);Use direct calls to instantOpen when open speed matters — typical pattern:
// on trade-panel mount, run prepare early:
const prepared = await prepareInstantOpenParams(config, uiInputs);
// user clicks Open — no fetch on the critical path:
const result = await instantOpen(config, prepared);Per-solver behavior
The two solver kinds open positions differently, and instantOpen dispatches on the resolved solver’s kind:
| Enigma (lowcap) | Rasa (majors) | |
|---|---|---|
| Operations signed | sendQuote, plus addMarginToNextVA when margin is present | one — sendQuote on the diamond |
| Margin model | optionally funds the next virtual account in the same request | cross-margin — no VA, no addMargin |
margin parameter | optional; omission submits only sendQuote | ignored |
| Muon signature | a placeholder, with its calldata region delegated to the solver via a FlexField | a live uPnl_A_withSymbolPrice attestation, fetched immediately before signing |
| Endpoint | /instant_trade/instant_open | /instant_trade/open |
Rasa’s attestation is encoded inside the signed calldata, so it cannot be cached or fetched afterwards — instantOpen fetches it for you on that path.
Enigma margin timelocks
On Enigma v0.8.6 deployments, submission reads the solver’s /info before signing.
When it advertises timelock_approval, the margin operation calls AccountLayer
executeTimelockOp around exactly one addMarginToNextVA. Its single approval
fixes the root account, unlocker, inner-calldata hash, deadline and salt. Only the
65 zero-filled signature bytes are delegated to the configured PartyB proxy;
approval fields, ABI offsets and inner calldata cannot be changed by that filler.
The canonical signature range starts at byte 352 after the function selector.
marginApprovalDeadline controls the embedded approval deadline, in Unix seconds.
It defaults to operationDeadline ?? quoteDeadline and must be positive, fit int64,
and leave at least 30 seconds. It is independent of /info’s validity_seconds,
which applies only to public POST /timelock-approval responses. Submission checks
the signed quote, both operation deadlines and the embedded approval against chain
time after signing; every deadline must still have at least 30 seconds remaining.
After an ambiguous POST, reconcile the existing request; do not automatically create
a new salt, signature or order. See prepared submission.
Before signing, allTimelockedBy must confirm the SDK’s ABI-derived 22-selector
set against the advertised unlocker and minimum delay. /info does not supply a
selector allowlist. Wrapped margin requires a root sub-account, not a VA;
both signed operations keep that root. These are account
timelocks, separate from InstantLayer session-key delegation. The SDK does not
configure them or request an approval from /timelock-approval. Owner approval of
a timelock setup belongs in a separate account-management flow. The solver still
checks admission conditions such as unresolved schedules and live approvals.
| Error code | Meaning |
|---|---|
INSTANT_OPEN_TIMELOCK_POLICY_REQUIRED | Required account timelocks are absent, use another unlocker, or have insufficient delay; nothing is signed or posted. |
INVALID_INSTANT_OPEN_TIMELOCK_METADATA | Advertised metadata is malformed or names another chain/AccountLayer. |
FETCH_INSTANT_OPEN_TIMELOCK_METADATA_FAILED | Solver requirements could not be fetched; submission stops. |
INSTANT_OPEN_TIMELOCK_APPROVAL_EXPIRED | Signing left less than 30 seconds of approval validity; prepare a fresh order. |
INSTANT_OPEN_ROOT_ACCOUNT_REQUIRED | Wrapped instant margin was requested for a virtual account; use its root. |
INSTANT_OPEN_DEADLINE_EXPIRED | A signed quote, operation or approval is too close to expiry to submit. Reconcile any earlier POST before creating a new intent. |
The delegation check still authorizes the fixed inner addMarginToNextVA selector,
not the wrapper. preflightDelegation: false skips only delegation reads; it never
bypasses the timelock policy check. No extra wrapper delegation is needed.
Solvers that do not advertise this metadata, or explicitly return timelock_enabled: false
with timelock_approval: null, keep their plain margin operation;
metadata fetch failures and malformed metadata never trigger that legacy path.
Enigma v0.8.5 and Rasa retain their existing encoding. See the
staging solver specification
and AccountLayer timelock semantics .
Prepared submission
prepareInstantOpen(config, parameters: InstantOpenParameters): Promise<PreparedInstantOpen>
signs an Enigma request without posting it. This is different from
prepareInstantOpenParams, which resolves trading inputs without signing.
submitPreparedInstantOpen(config, { prepared }): Promise<EnigmaInstantOpenResult>
sends those exact signed bytes once. It never obtains another signature, changes a
salt, or requests a public approval. SubmitPreparedInstantOpenParameters contains
only prepared: PreparedInstantOpen.
import { prepareInstantOpen, submitPreparedInstantOpen } from "@symmio/trading-core";
const signed = await prepareInstantOpen(config, resolvedParameters);
// Persist before POST using the application's durable storage.
await savePendingRequest(JSON.stringify(signed));
const admitted = await submitPreparedInstantOpen(config, { prepared: signed });
// Admission is not a transaction receipt or proof that a position opened.PreparedInstantOpen contains kind, chainId, deploymentKey, solverId,
request (signed sendQuote and optional addMargin), and timelock. It is JSON-safe
and can be restored without converting numeric strings into numbers. Treat the
entire object as immutable, including its UUID and recovery identity. Submission
copies it before asynchronous work and rejects a different deployment. Applications
must validate restored data and reconcile the original order’s status before any
explicit retransmission. An expired request cannot be refreshed by editing it.
The prepared API currently supports the Enigma wire protocol; unsupported solver
protocols fail before signing. Existing Rasa instantOpen behavior is unchanged.
Core does not prescribe storage, UI, retry intervals or automatic fallback.
Existing instant-open convenience hooks retain their previous mutation retry behavior.
For recoverable requests, compose the prepared API in an application mutation with
retry: false; do not allow a global retry policy to rerun the prepare/sign builder.
Timelock admission errors retain their raw response and expose
TimelockSolverError.details.
Delegation preflight
instantOpen signs with whatever key from resolves to — usually a session key. Before it signs anything, it checks that the key holds an active InstantLayer delegation from the sub-account for every operation it is about to sign: the quote-send, plus addMarginToNextVA on Enigma only when margin is present. A key without one fails right there with INSTANT_SIGNER_NOT_DELEGATED, before anything is signed or sent, instead of failing at the solver after the user tried to trade.
- Owner-signed opens skip the delegation reads. The sub-account’s owner needs no delegation; the check stops after reading the owner once per config.
- Session-key opens add one RPC round trip. The per-selector reads run in parallel; the first open for an account also reads the account and its owner, which are then cached.
- Grant the trade set once with
grantDelegationandgetInstantTradeRequiredSelectors(config, { chainId }). - Skip the check with
preflightDelegation: falsewhen your UI already gates the trade on delegation, for example withuseAreDelegationsActive.
It is the same check gasless runs before relaying a session-key write, so a key is judged the same way on both paths.
Parameters
InstantOpenParameters — the resolved bag from prepareInstantOpenParams. Every field is a concrete value; submission also performs the Rasa Muon read, Enigma timelock requirements, and delegation preflight described above.
preflightDelegation (default true) turns the delegation preflight off for one call. prepareInstantOpenParams passes it through, so instantOpenAuto and limitOpenAuto accept it too.
On a contractsVersion: "0.8.6" chain the Enigma flow signs sendQuote carrying solverFeeCaps (SolverFeeCaps — 18-decimal rate caps the quote authorizes for the solver’s open/close fees; the wizard fills the market minimums, falling back to a 1% default when the market publishes none and throwing INVALID_SOLVER_FEE_CAP on a malformed vendor string; omitting it on the primitive means zero caps, which a fee-charging solver rejects). On a "0.8.5" chain the flow signs the legacy sendQuoteWithAffiliateAndData and solverFeeCaps is ignored.
Lowcap callers can supply operationDeadline (Unix seconds) separately from the quote’s
deadline. It applies to both signed operations and defaults to deadline when omitted.
For example, deadline: chainTime + 300n and operationDeadline: chainTime + 60n
retain a five-minute quote with a one-minute execution window. Both fields are accepted
by preparation and the automatic flow.
The primitive also accepts markPrice in 18-decimal wei for the Muon placeholder;
it defaults to order.price for existing callers. Preparation sets the actual mark price.
Preparation converts the market’s minOpenSolverFeeCap directly to the signed
openRateCap, using the existing 1% fallback when the market omits the value.
Opening fee amounts do not increase this cap. See the contract documentation for
solver fee caps
and execution-price fees .
Passing a literal solverId binds the generic and narrows the return type. Omitting it lets the chain’s defaultSolverId decide at runtime. On Enigma, omitting margin intentionally submits only sendQuote; no zero-value margin operation is added.
Returns
InstantOpenReturnType — a union discriminated on kind, sharing { success, tempQuoteId?, partyBmm? }:
EnigmaInstantOpenResult—{ kind: "enigma", … }.RasaInstantOpenResult—{ kind: "rasa", …, rfq }, whererfqis the accepted request-for-quote echoed by Rasa, normalized to the same shapegetInstantOpensreturns.
tempQuoteId identifies the pending request until it anchors on-chain. Enigma rejects
responses with missing or invalid temporary IDs as INSTANT_OPEN_INVALID_RESPONSE.
A rejection body in HTTP 200 throws INSTANT_OPEN_REJECTED, preserving the response in
SymmApiError.responseData. Submission is not automatically retried.
Errors
INSTANT_SIGNER_NOT_DELEGATED(kind: "validation") when the signer lacks the delegation for an operation it would sign. The message names the signer, the sub-account and the missing selectors; nothing was signed or sent.INSTANT_OPEN_REJECTED,INSTANT_OPEN_INVALID_RESPONSE, orSEND_INSTANT_OPEN_FAILEDwhen submission fails.- Viem
UserRejectedRequestErrorwhen the user dismisses the signature dialog. SymmError(kind: "config") when chain config is missing a solver URL.
instantOpenAuto
Convenience wrapper: prepareInstantOpenParams + instantOpen in one call. Same parameter shape as prepareInstantOpenParams.
const result = await instantOpenAuto(config, {
from: sessionKey,
subAccountAddress,
market: { id: 1 },
positionType: PositionType.LONG,
initialMargin: "100",
leverage: 5,
slippage: 1,
});Latency: this variant does the prepare fetches inline, so the total wall-clock is prepare fetches + sign + POST. Fine for most flows; use prepareInstantOpenParams + instantOpen split when open time is critical (e.g. reacting to a live price change).
limitOpenAuto
The LIMIT-order variant. Same shape and split as instant open, but the caller passes a resting price and the order is signed with orderType = LIMIT, so the solver writes a pending on-chain quote at that price instead of filling immediately. Majors / Rasa only — the Enigma (lowcap) solver has no limit support, and limitOpenAuto throws UNSUPPORTED_BY_SOLVER on a solver that lacks the limitOrder capability. The send deadline defaults to 15 minutes (vs. 5 minutes for a market instant open).
const { tempQuoteId } = await limitOpenAuto(config, {
from: sessionKey,
subAccountAddress,
market: { id: 1 },
positionType: PositionType.LONG,
initialMargin: "100",
leverage: 5,
price: "64000", // resting limit price
});Under the hood it mirrors instantOpenAuto — prepareLimitOpenParams then the shared instantOpen primitive (which honors orderType = LIMIT):
export async function limitOpenAuto(config, parameters) {
const resolved = await prepareLimitOpenParams(config, parameters);
return instantOpen(config, resolved);
}The returned tempQuoteId identifies the resting order off-chain. It appears in getInstantOpens (off-chain) until it anchors, at which point it is a pending on-chain quote — read the reconciled list with the React useLimitOrders hook, and cancel it with requestToCancelQuote / forceCancelQuote (SYMMIO Contract).
prepareLimitOpenParams
The LIMIT-order resolver — same steps and inputs as prepareInstantOpenParams but takes the resting price (instead of slippage) and stamps orderType = LIMIT plus the 15-minute default deadline into the resolved InstantOpenParameters bag. Returns the inspectable bag instantOpen consumes.
getInstantOpens
Paginated list of the solver’s pending instant-opens for a SubAccount.
const page = await getInstantOpens(config, {
account: subAccount,
offset: 0n,
size: 20n,
});The reconciler (reconcileQuotes) consumes this list, so consumers rarely call it directly. Combine with resolveQuoteAccounts to know which predicted VAs to fetch on-chain reads across.
getInstantOpenQuoteId
Resolve the on-chain quoteId for a given tempQuoteId — the anchor mapping the solver reveals once the quote lands on-chain.
const quoteId = await getInstantOpenQuoteId(config, { tempQuoteId: -1001 });The reconciler and notification handlers use this to link temp ↔ on-chain rows automatically; consumers rarely need it manually.
calculateAvailableInstantOpenMargin
Pure function — the maximum initial margin an instant open can spend, shaving the raw available balance for the open fee (on the leveraged notional) and, for SHORT, a worst-case slippage fill. The close fee is not shaved — the contract charges it at close from the position (see Fees at close), not at open. All BigInt; clamps to 0n; returns 18-decimal wei. This estimates initial-margin capacity.
import { calculateAvailableInstantOpenMargin, PositionType } from "@symmio/trading-core";
const max = calculateAvailableInstantOpenMargin({
balance, // getAccountBalanceOf, 1e18
openFee, // getFeeForUser, 18-dec fixed-point
slippageFractionWei: 5n * 10n ** 16n, // 5%
leverage: 10,
positionType: PositionType.SHORT,
});available = balance
× max(0, 1 − slippageFactor) // SHORT: slippage, LONG: 0
× max(0, 1 − leverage × openFee)- Fee is charged on the leveraged notional — subtract
leverage × openFee. Only the open fee is shaved; the close fee is charged at close. - Slippage (SHORT only) — quantity is sized off
markPrice × (1 − s); a worse fill inflates notional by up to1 / (1 − s), so cap usable balance atbalance × (1 − s). LONG sets the request above mark, so fills deflate notional — no cap.
The closeFee parameter is deprecated: it is now optional and ignored (kept so existing callers still compile). Pass it or omit it — the shave is the same.
The React layer wraps this in useAvailableInstantOpenMargin, fed by useAccountBalanceOf + useFeeForUser.
Query / Mutation options
instantOpenMutationOptions(config)— TanStack mutation bag for theinstantOpenprimitive.instantOpenAutoMutationOptions(config)— TanStack mutation bag for theAutowrapper.getInstantOpensQueryOptions(config, options)— TanStack query bag for the pending list.getInstantOpenQuoteIdQueryOptions(config, options)— TanStack query bag for the temp-id resolver.
Related
- InstantLayer — the underlying delegated-write contract.
- Instant Close — the close-side analog.
- Unified Quotes —
PendingInstantOpenfeeds intoreconcileQuotes. - TP/SL — attach a TP/SL leg via
useInstantOpenWithTpSlin the React layer.
Pending-open compatibility fields
Enigma getInstantOpens rows expose optional createTime: number, the finite Unix-seconds creation timestamp supplied by the server. Missing or malformed timestamps remain absent. Rasa rows are unchanged.
GetInstantOpensParameters.appName?: string supplies the Enigma App-Name request header for consumers with an existing application routing requirement. Omit it to preserve the default request. Query options forward it and include it in query identity. Supplying it for Rasa throws UNSUPPORTED_BY_SOLVER before transport.