@proof-labs/trading-sdk 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +391 -0
  3. package/dist/client.d.ts +640 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +1730 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/codec-adapter.d.ts +33 -0
  8. package/dist/codec-adapter.d.ts.map +1 -0
  9. package/dist/codec-adapter.js +419 -0
  10. package/dist/codec-adapter.js.map +1 -0
  11. package/dist/codec.d.ts +137 -0
  12. package/dist/codec.d.ts.map +1 -0
  13. package/dist/codec.js +229 -0
  14. package/dist/codec.js.map +1 -0
  15. package/dist/crypto.d.ts +78 -0
  16. package/dist/crypto.d.ts.map +1 -0
  17. package/dist/crypto.js +145 -0
  18. package/dist/crypto.js.map +1 -0
  19. package/dist/errors.d.ts +122 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +397 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/governance-query.d.ts +47 -0
  24. package/dist/governance-query.d.ts.map +1 -0
  25. package/dist/governance-query.js +525 -0
  26. package/dist/governance-query.js.map +1 -0
  27. package/dist/index.d.ts +11 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +22 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/testing.d.ts +25 -0
  32. package/dist/testing.d.ts.map +1 -0
  33. package/dist/testing.js +22 -0
  34. package/dist/testing.js.map +1 -0
  35. package/dist/trigger-history.d.ts +9 -0
  36. package/dist/trigger-history.d.ts.map +1 -0
  37. package/dist/trigger-history.js +442 -0
  38. package/dist/trigger-history.js.map +1 -0
  39. package/dist/triggers.d.ts +15 -0
  40. package/dist/triggers.d.ts.map +1 -0
  41. package/dist/triggers.js +399 -0
  42. package/dist/triggers.js.map +1 -0
  43. package/dist/tx-result.d.ts +53 -0
  44. package/dist/tx-result.d.ts.map +1 -0
  45. package/dist/tx-result.js +58 -0
  46. package/dist/tx-result.js.map +1 -0
  47. package/dist/types.d.ts +2085 -0
  48. package/dist/types.d.ts.map +1 -0
  49. package/dist/types.js +121 -0
  50. package/dist/types.js.map +1 -0
  51. package/dist/wasm/proof_trading_sdk_wasm.d.ts +98 -0
  52. package/dist/wasm/proof_trading_sdk_wasm.js +698 -0
  53. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
  54. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm.d.ts +19 -0
  55. package/dist/wasm-loader.d.ts +42 -0
  56. package/dist/wasm-loader.d.ts.map +1 -0
  57. package/dist/wasm-loader.js +95 -0
  58. package/dist/wasm-loader.js.map +1 -0
  59. package/package.json +72 -0
@@ -0,0 +1,2085 @@
1
+ import type { ExecErrorInfo } from "./errors.js";
2
+ /** 20-byte account address (derived from Ed25519 public key). */
3
+ export type Address = Uint8Array;
4
+ /** Order side. */
5
+ export declare enum Side {
6
+ /** Buy / long. */
7
+ Buy = 1,
8
+ /** Sell / short. */
9
+ Sell = 2
10
+ }
11
+ /**
12
+ * Time-in-force policy for a limit order. Controls how unmatched
13
+ * quantity is handled after crossing the book.
14
+ *
15
+ * Wire encoding: msgpack enum variant (`Gtc`, `Ioc`, `Fok`).
16
+ */
17
+ export declare enum TimeInForce {
18
+ /** Good-Till-Cancelled: unmatched quantity rests on the book. The default. */
19
+ Gtc = 0,
20
+ /** Immediate-Or-Cancel: unmatched quantity is dropped after crossing. */
21
+ Ioc = 1,
22
+ /** Fill-Or-Kill: fully fill immediately or reject without mutation. */
23
+ Fok = 2
24
+ }
25
+ /** Wire-format action type identifiers. Each value is a single byte. */
26
+ export declare const ActionType: {
27
+ /** Place a limit order on the order book. */
28
+ readonly PlaceOrder: 1;
29
+ /** Cancel an existing resting order. */
30
+ readonly CancelOrder: 2;
31
+ /** Submit an oracle price update (relayer only). */
32
+ readonly OracleUpdate: 3;
33
+ /** Operator-only: submit a composite-CEX price for the multi-source mark
34
+ * median (BE-31 Phase B). Feeder infrastructure, not a trading action. */
35
+ readonly OracleUpdateComposite: 20;
36
+ /** Place a market order that crosses immediately. */
37
+ readonly MarketOrder: 4;
38
+ /** Credit USDC to an account (legacy, prefer ConfirmDeposit). */
39
+ readonly Deposit: 5;
40
+ /** Debit USDC from an account (direct withdraw, checks margin). */
41
+ readonly Withdraw: 6;
42
+ /** Register a new perpetual market with risk parameters (admin). */
43
+ readonly CreateMarket: 7;
44
+ /** User requests a USDC withdrawal to a Solana address. */
45
+ readonly WithdrawRequest: 8;
46
+ /** Relayer confirms an on-chain USDC deposit from Solana. */
47
+ readonly ConfirmDeposit: 9;
48
+ /** Relayer confirms a USDC withdrawal was sent on Solana. */
49
+ readonly ConfirmWithdrawal: 10;
50
+ /** Relayer marks a withdrawal as permanently failed; refunds balance. */
51
+ readonly FailWithdrawal: 11;
52
+ /** Receipt-gated confirmation: a finalized `Paid` bridge receipt + operator
53
+ * ed25519 quorum proof. Replaces the trusted relayer assertion in
54
+ * `ConfirmWithdrawal` (0x0a, still accepted). W28-20. */
55
+ readonly ConfirmWithdrawalReceipt: 34;
56
+ /** Receipt-gated failure: a finalized `Cancelled` bridge receipt + operator
57
+ * ed25519 quorum proof. Replaces the free-text `FailWithdrawal` (0x0b, still
58
+ * accepted); refunds only against a positive on-chain cancellation. W28-20. */
59
+ readonly FailWithdrawalReceipt: 35;
60
+ /** Records the operator-quorum-signed `WithdrawalAuthorizationV1` a terminal
61
+ * receipt (0x22/0x23) must settle against. Permissionless to submit. W28-20. */
62
+ readonly AuthorizeWithdrawal: 36;
63
+ /** Atomically replace a whole-position stop-loss/take-profit bracket. */
64
+ readonly SetPositionTriggers: 37;
65
+ /** Cancel the bracket attached to an exact position generation. */
66
+ readonly CancelPositionTriggers: 38;
67
+ /** Approve a delegate agent wallet to trade on the owner's behalf. */
68
+ readonly ApproveAgent: 12;
69
+ /** Revoke a previously approved agent wallet. */
70
+ readonly RevokeAgent: 13;
71
+ /** Create a 5-book impact-market family (admin). */
72
+ readonly CreateImpactMarket: 14;
73
+ /** Resolve an impact-market event with an outcome (admin). */
74
+ readonly ResolveEvent: 15;
75
+ /** Update a subset of `MarketConfig` tunables on a live market (admin).
76
+ * Fee tiering, funding-rate cap tightening, position-limit updates
77
+ * without a chain rebase. */
78
+ readonly UpdateMarketFees: 16;
79
+ /** User picks a per-market initial-margin override capped by the
80
+ * market's risk floor. `user_im_bps == 0` clears the override.
81
+ * Engine takes max(market.im_bps, user_im_bps) on every IM check.
82
+ * BE-16. */
83
+ readonly SetUserMarketLeverage: 22;
84
+ /** Close an entire position by placing an opposite-side IOC order at
85
+ * oracle±spread. Idempotent on already-closed positions. User-signed. */
86
+ readonly ClosePosition: 23;
87
+ /** Cancel a resting order by owner-scoped client order id. */
88
+ readonly CancelClientOrder: 24;
89
+ /** Cancel all resting orders for an owner, optionally market-scoped. */
90
+ readonly CancelAllOrders: 25;
91
+ /** Atomically cancel one resting order and place its replacement. */
92
+ readonly CancelReplaceOrder: 26;
93
+ /** Amend one resting order in place while preserving its exchange order ID. */
94
+ readonly AmendOrder: 27;
95
+ /** Native all-or-revert multi-leg basket order. */
96
+ readonly AtomicBasketOrder: 28;
97
+ /** Signed admin-multisig governance proposal. */
98
+ readonly ProposeAdminAction: 30;
99
+ /** Signed admin-multisig governance approval (carries full proposal context). */
100
+ readonly ApproveAdminAction: 31;
101
+ /** Signed admin-multisig governance rejection. */
102
+ readonly RejectAdminAction: 32;
103
+ /** Signed single-signer emergency action (pause/halt/reduce-only). */
104
+ readonly EmergencyAdminAction: 33;
105
+ };
106
+ /** Union of all valid action type byte values. */
107
+ export type ActionTypeValue = (typeof ActionType)[keyof typeof ActionType];
108
+ /** Place a limit order on the order book. */
109
+ export interface PlaceOrder {
110
+ /** Market identifier (unique integer). */
111
+ market: number;
112
+ /** Account address of the order owner (20 bytes). */
113
+ owner: Address;
114
+ /** Order side: Buy (1) or Sell (2). */
115
+ side: Side;
116
+ /** Limit price in micro-USDC (6 decimal places, e.g., 66752340000 = $66,752.34). */
117
+ price: bigint;
118
+ /** Order quantity in contracts (integer lots). */
119
+ quantity: bigint;
120
+ /** Optional client-assigned order ID for tracking. */
121
+ clientOrderId?: bigint | null;
122
+ /** When true, the engine rejects the order if it would cross the book on
123
+ * placement (PostOnlyWouldCross, code 34). For makers who require
124
+ * maker-side fills. Defaults to false. */
125
+ postOnly?: boolean;
126
+ /** When true, the order may only reduce an existing position. Same-side
127
+ * orders are rejected (ReduceOnlyWouldIncrease, code 35); over-closing
128
+ * is clamped to the position size. Defaults to false. */
129
+ reduceOnly?: boolean;
130
+ /**
131
+ * Time-in-force policy. Defaults to `TimeInForce.Gtc` for backward
132
+ * compat. `TimeInForce.Ioc` drops any unfilled quantity after crossing
133
+ * the book (no resting order). `TimeInForce.Fok` rejects unless the
134
+ * visible crossing book can fill the whole order immediately.
135
+ */
136
+ timeInForce?: TimeInForce;
137
+ }
138
+ /** Cancel an existing resting order by its engine-assigned ID. */
139
+ export interface CancelOrder {
140
+ /** Engine-assigned order ID to cancel. */
141
+ orderId: bigint;
142
+ /** Account address of the order owner (20 bytes). Must match the order's owner. */
143
+ owner: Address;
144
+ }
145
+ /** Cancel an existing resting order by the caller's client-assigned ID. */
146
+ export interface CancelClientOrder {
147
+ /** Account address of the order owner (20 bytes). */
148
+ owner: Address;
149
+ /** Client-assigned order ID to cancel. */
150
+ clientOrderId: bigint;
151
+ }
152
+ /** Cancel all resting orders for an account, optionally scoped to one market. */
153
+ export interface CancelAllOrders {
154
+ /** Account address whose resting orders should be cancelled. */
155
+ owner: Address;
156
+ /** Optional market scope; omit/null to cancel across all markets. */
157
+ market?: number | null;
158
+ }
159
+ /** Atomically cancel a resting order and place its replacement. */
160
+ export interface CancelReplaceOrder {
161
+ /** Account address whose order should be cancelled/replaced. */
162
+ owner: Address;
163
+ /** Engine-assigned order ID to cancel. Mutually exclusive with `cancelClientOrderId`. */
164
+ cancelOrderId?: bigint | null;
165
+ /** Owner-scoped client order ID to cancel. Mutually exclusive with `cancelOrderId`. */
166
+ cancelClientOrderId?: bigint | null;
167
+ /** Replacement order market. */
168
+ market: number;
169
+ /** Replacement order side. */
170
+ side: Side;
171
+ /** Replacement limit price. */
172
+ price: bigint;
173
+ /** Replacement quantity. */
174
+ quantity: bigint;
175
+ /** Optional client-assigned ID for the replacement order. */
176
+ clientOrderId?: bigint | null;
177
+ /** Replacement post-only flag. Defaults to false. */
178
+ postOnly?: boolean;
179
+ /** Replacement reduce-only flag. Defaults to false. */
180
+ reduceOnly?: boolean;
181
+ /** Replacement time-in-force policy. Defaults to GTC. */
182
+ timeInForce?: TimeInForce;
183
+ }
184
+ /** Amend a resting order without changing its exchange order ID. */
185
+ export interface AmendOrder {
186
+ /** Account address whose order should be amended. */
187
+ owner: Address;
188
+ /** Engine-assigned order ID to amend. */
189
+ orderId: bigint;
190
+ /** Optional replacement price. Omit/null to keep the existing price. */
191
+ newPrice?: bigint | null;
192
+ /** Optional new total order quantity. Omit/null to keep the existing quantity. */
193
+ newQuantity?: bigint | null;
194
+ }
195
+ /** Submit an oracle price update for a market (relayer only). */
196
+ export interface OracleUpdate {
197
+ /** Market identifier to update. */
198
+ market: number;
199
+ /** New oracle price in micro-USDC (6 decimal places, e.g., 66752340000 = $66,752.34). */
200
+ price: bigint;
201
+ /** Authorized oracle signer address (20 bytes). */
202
+ signer: Address;
203
+ /**
204
+ * Oracle publish timestamp in ms since Unix epoch. Must be strictly
205
+ * greater than the last accepted update on this market (engine
206
+ * rejects with code 30 `OracleTimestampNotMonotonic` otherwise).
207
+ * Added 2026-04-23 per audit B3 as replay protection for the
208
+ * relayer-signed oracle feed.
209
+ */
210
+ publishTimeMs: bigint;
211
+ }
212
+ /**
213
+ * **Operator action — not for trading integrations.** Submit a composite-CEX
214
+ * price for a market: BE-31 Phase B's third source for the multi-source
215
+ * mark-price median (oracle + book-mid + composite CEX index).
216
+ *
217
+ * A normal trading integration never submits this — it is feeder
218
+ * infrastructure run by the operator. The engine re-checks the signer against
219
+ * a **separate CEX-composite feeder allowlist** (a distinct trust domain from
220
+ * the {@link OracleUpdate} relay), so a non-feeder signer is rejected
221
+ * regardless. Markets ignore the composite entirely unless an operator has
222
+ * flipped them to `Median` via {@link UpdateMarketFees} (`markSourceMode = 1`).
223
+ *
224
+ * @remarks Operator-only. Requires a signer on the engine's CEX-composite
225
+ * feeder allowlist; not needed for trading integrations.
226
+ */
227
+ export interface OracleUpdateComposite {
228
+ /** Market identifier to update. */
229
+ market: number;
230
+ /** Composite price in micro-USDC (median/VWAP of `nSources` CEX feeds). */
231
+ price: bigint;
232
+ /** Number of CEX feeds that went into the composite. Observability only —
233
+ * the engine does not gate on it. Encodes as 0 when absent. */
234
+ nSources: number;
235
+ /** Authorized feeder signer (20 bytes), on the CEX-composite allowlist. */
236
+ signer: Address;
237
+ /** Feeder publish timestamp in ms since Unix epoch. Must be strictly
238
+ * greater than the last accepted composite on this market (replay guard,
239
+ * same semantics as {@link OracleUpdate.publishTimeMs}). */
240
+ publishTimeMs: bigint;
241
+ }
242
+ /** Place a market order that crosses immediately against resting orders. */
243
+ export interface MarketOrder {
244
+ /** Market identifier. */
245
+ market: number;
246
+ /** Account address of the order owner (20 bytes). */
247
+ owner: Address;
248
+ /** Order side: Buy (1) or Sell (2). */
249
+ side: Side;
250
+ /** Order quantity in contracts (integer lots). */
251
+ quantity: bigint;
252
+ /** Optional client-assigned order ID for tracking. */
253
+ clientOrderId?: bigint | null;
254
+ }
255
+ /**
256
+ * Credit USDC to an account (dev/bootstrap action).
257
+ *
258
+ * Per audit B1 (2026-04-23) this action requires a relayer-authorized
259
+ * signer — the envelope signer's derived address must equal `signer`,
260
+ * and `signer` must be on the on-chain relayer allowlist. Clients
261
+ * outside the allowlist see `UnauthorizedRelayer` at the engine.
262
+ * Prefer `ConfirmDeposit` for production flows tied to Solana bridge
263
+ * events.
264
+ */
265
+ export interface Deposit {
266
+ /** Account address to credit (20 bytes). */
267
+ owner: Address;
268
+ /** Deposit amount in microUSDC (6 decimal places, e.g., 100_000_000 = $100). */
269
+ amount: bigint;
270
+ /** Authorized relayer signer (20 bytes). Must match the envelope pubkey's derived owner. */
271
+ signer: Address;
272
+ }
273
+ /**
274
+ * Debit USDC from an account (direct withdraw, checks margin requirements).
275
+ *
276
+ * Per audit B2 (2026-04-23) same relayer-authorization contract as
277
+ * `Deposit`: the envelope signer must equal `signer` and that address
278
+ * must be on the relayer allowlist.
279
+ */
280
+ export interface Withdraw {
281
+ /** Account address to debit (20 bytes). */
282
+ owner: Address;
283
+ /** Withdrawal amount in microUSDC (6 decimal places, e.g., 100_000_000 = $100). */
284
+ amount: bigint;
285
+ /** Authorized relayer signer (20 bytes). Must match the envelope pubkey's derived owner. */
286
+ signer: Address;
287
+ }
288
+ /** Register a new perpetual market with its risk and fee parameters (admin action). */
289
+ export interface CreateMarket {
290
+ /** Market identifier (unique integer). */
291
+ market: number;
292
+ /** Initial margin requirement in basis points (e.g., 1000 = 10% = 10x max leverage). */
293
+ imBps: number;
294
+ /** Maintenance margin requirement in basis points (e.g., 500 = 5%). */
295
+ mmBps: number;
296
+ /** Taker fee rate in basis points (e.g., 5 = 0.05%). */
297
+ takerFeeBps: number;
298
+ /** Maker fee rate in basis points (e.g., 2 = 0.02%). */
299
+ makerFeeBps: number;
300
+ /** Authorized relayer signer address (20 bytes). */
301
+ signer: Address;
302
+ /** Funding interval in milliseconds (0 = funding disabled). */
303
+ fundingIntervalMs: bigint;
304
+ /** Maximum absolute funding rate per interval in basis points. */
305
+ maxFundingRateBps: number;
306
+ /**
307
+ * Bad-debt pool the market belongs to. Markets in different pools are
308
+ * insulated from each other's liquidation cascades. Optional — defaults
309
+ * to 0 on the wire (matches the engine's `serde(default)`), so omitting
310
+ * the field keeps a market in the shared pool 0.
311
+ */
312
+ poolId?: number;
313
+ /**
314
+ * Published size scale: order/position `quantity` is in units of
315
+ * 10^-szDecimals of the base asset (display/metadata only — the engine
316
+ * never reads it). MANDATORY: the engine struct has no `serde(default)`
317
+ * for this field, so a payload that omits it is rejected at decode. The
318
+ * scale is fixed at creation and immutable thereafter. Use 0 for
319
+ * integer-unit sizing.
320
+ */
321
+ szDecimals: number;
322
+ /**
323
+ * Human-readable ticker / short symbol (e.g. `BTC`). Display/metadata only
324
+ * — the engine never reads it. MANDATORY on the wire (no serde(default)),
325
+ * though an empty string is accepted; capped at 24 bytes by the engine.
326
+ * Fixed at creation and immutable thereafter.
327
+ */
328
+ ticker: string;
329
+ /**
330
+ * Aggregate market open-interest cap in contracts. Omitted, null, and 0 all
331
+ * mean uncapped and encode identically as the canonical 12-field payload
332
+ * with an explicit 0 tail. Legacy 11-field payloads still decode as 0n.
333
+ */
334
+ maxOpenInterest?: bigint | null;
335
+ }
336
+ /** User requests a USDC withdrawal to a Solana address. Debits balance immediately. */
337
+ export interface WithdrawRequest {
338
+ /** Account address requesting the withdrawal (20 bytes). */
339
+ owner: Address;
340
+ /** Withdrawal amount in microUSDC (6 decimal places). */
341
+ amount: bigint;
342
+ /** Solana destination public key (Ed25519, 32 bytes). */
343
+ solanaDestination: Uint8Array;
344
+ }
345
+ /**
346
+ * Position of a USDC transfer inside its Solana transaction: the top-level
347
+ * instruction index plus, for a transfer nested under a CPI, the inner
348
+ * instruction index (`null`/omitted when the transfer is the top-level
349
+ * instruction). Two transfers in one transaction share a signature and differ
350
+ * only here. Encodes as a positional 2-element array `[topIndex, innerIndex]`.
351
+ */
352
+ export interface DepositLocator {
353
+ topIndex: number;
354
+ innerIndex?: number | null;
355
+ }
356
+ /** Relayer confirms an on-chain USDC deposit from Solana. Credits the account. */
357
+ export interface ConfirmDeposit {
358
+ /** Account address to credit (20 bytes). */
359
+ owner: Address;
360
+ /** Deposit amount in microUSDC (6 decimal places). */
361
+ amount: bigint;
362
+ /** Solana transaction signature for idempotency (typically 64 bytes). */
363
+ solanaTxSig: Uint8Array;
364
+ /** Authorized relayer signer address (20 bytes). */
365
+ signer: Address;
366
+ /**
367
+ * Instruction locator within the signature. Omitted/`null` on pre-locator
368
+ * txs (the engine reads that as top-level instruction 0, no inner). Trailing
369
+ * optional field: absent still encodes as a trailing `nil`, so the payload is
370
+ * a 5-element array either way — an engine predating the locator rejects it.
371
+ * See the MAJOR-bump entry in CHANGELOG.md for the engine floor.
372
+ */
373
+ locator?: DepositLocator | null;
374
+ }
375
+ /** Relayer confirms a USDC withdrawal was sent on Solana. */
376
+ export interface ConfirmWithdrawal {
377
+ /** Engine-assigned withdrawal ID. */
378
+ withdrawalId: bigint;
379
+ /** Solana transaction signature (typically 64 bytes). */
380
+ solanaTxSig: Uint8Array;
381
+ /** Authorized relayer signer address (20 bytes). */
382
+ signer: Address;
383
+ }
384
+ /** Lifecycle status of a withdrawal record. Title-case strings are
385
+ * serde's default for unit variants — wire format is locked. */
386
+ export type WithdrawalStatus = "Pending" | "Completed" | "Failed";
387
+ /** On-chain withdrawal record returned by `queryWithdrawal`. Mirrors
388
+ * `exchange-core::types::WithdrawalRecord` field-for-field. */
389
+ export interface WithdrawalRecord {
390
+ /** Engine-assigned withdrawal id. */
391
+ id: bigint;
392
+ /** Account address that requested the withdrawal (20 bytes). */
393
+ owner: Address;
394
+ /** Withdrawal amount in microUSDC. */
395
+ amount: bigint;
396
+ /** Solana destination public key (Ed25519, 32 bytes). */
397
+ solanaDestination: Uint8Array;
398
+ /** Pending → Completed or Pending → Failed; never reverses. */
399
+ status: WithdrawalStatus;
400
+ /** Block height at which the request was admitted. */
401
+ requestHeight: bigint;
402
+ }
403
+ /** Relayer marks a withdrawal as permanently failed; refunds the debited balance. */
404
+ export interface FailWithdrawal {
405
+ /** Engine-assigned withdrawal ID. */
406
+ withdrawalId: bigint;
407
+ /** Human-readable reason for the failure. */
408
+ reason: string;
409
+ /** Authorized relayer signer address (20 bytes). */
410
+ signer: Address;
411
+ }
412
+ /**
413
+ * Wire mirror of the frozen `bridge_core::BridgeReceiptV1` (fixed 327-byte
414
+ * form) carried by the receipt-gated terminal withdrawal actions. The engine
415
+ * rebuilds the receipt, re-encodes, and verifies the operator quorum signed
416
+ * exactly those bytes — every field is signed, so tampering fails closed.
417
+ *
418
+ * Field order matches the Rust struct → MessagePack wire layout; never reorder.
419
+ */
420
+ export interface BridgeWithdrawalReceipt {
421
+ /** `bridge_core::DeploymentId` — pins Proof/Solana genesis, program, mint (32 bytes). */
422
+ deploymentId: Uint8Array;
423
+ /** `SHA256(Borsh(WithdrawalAuthorizationV1))` (32 bytes). */
424
+ authorizationDigest: Uint8Array;
425
+ /** Engine-assigned withdrawal ID. */
426
+ withdrawalId: bigint;
427
+ /** Terminal state wire byte: `1 = Paid`, `2 = Cancelled`. */
428
+ terminalState: number;
429
+ /** `bridge_core::VaultTier` wire byte. */
430
+ vaultTier: number;
431
+ /** Internal account that owns the withdrawal (20 bytes). */
432
+ proofOwner: Address;
433
+ /** Solana destination owner pubkey (32 bytes). */
434
+ destinationOwner: Uint8Array;
435
+ /** Solana destination token account (32 bytes). */
436
+ destinationTokenAcct: Uint8Array;
437
+ /** Withdrawal amount in microUSDC (6 dp). */
438
+ amountMicroUsdc: bigint;
439
+ /** Bridge fee in microUSDC (6 dp). */
440
+ feeMicroUsdc: bigint;
441
+ /** Registry epoch the authorization signer set was pinned to. */
442
+ authorizationSignerEpoch: bigint;
443
+ /** Solana transaction signature (64 bytes). */
444
+ solanaTxSignature: Uint8Array;
445
+ /** Solana finalized slot the receipt was observed at. */
446
+ finalizedSlot: bigint;
447
+ /** Solana finalized blockhash (32 bytes). */
448
+ finalizedBlockhash: Uint8Array;
449
+ /** Receipt quorum kind wire byte: `1 = operator m-of-n`, `2 = validator stake`. */
450
+ receiptQuorumKind: number;
451
+ /** Registry epoch the receipt authority set was pinned to. */
452
+ receiptAuthorityEpoch: bigint;
453
+ }
454
+ /**
455
+ * Operator ed25519 proof — mirror of
456
+ * `bridge_core::ReceiptProofV1::OperatorEd25519`. A signer bitmap plus one
457
+ * 64-byte signature per set bit, in ascending registry-index order.
458
+ *
459
+ * Never log the signatures.
460
+ */
461
+ export interface OperatorReceiptProof {
462
+ /** `ceil(registry_len / 8)` bytes; unused high bits zero. */
463
+ signerBitmap: Uint8Array;
464
+ /** One 64-byte ed25519 signature per set bit, ascending set-bit order. */
465
+ signatures: Uint8Array[];
466
+ }
467
+ /**
468
+ * Receipt-gated confirmation of a paid withdrawal (action `0x22`). Carries a
469
+ * finalized `Paid` {@link BridgeWithdrawalReceipt} and its
470
+ * {@link OperatorReceiptProof}. Permissionless to submit — the operator quorum
471
+ * in the receipt is the authority, not the envelope signer. Replaces the
472
+ * trusted relayer assertion in {@link ConfirmWithdrawal}.
473
+ */
474
+ export interface ConfirmWithdrawalReceipt {
475
+ /** The finalized `Paid` bridge receipt. */
476
+ receipt: BridgeWithdrawalReceipt;
477
+ /** Operator ed25519 quorum proof over the receipt bytes. */
478
+ proof: OperatorReceiptProof;
479
+ }
480
+ /**
481
+ * Receipt-gated failure of a cancelled withdrawal (action `0x23`). Carries a
482
+ * finalized `Cancelled` {@link BridgeWithdrawalReceipt} and its
483
+ * {@link OperatorReceiptProof}; refunds the debited balance only against a
484
+ * positive on-chain cancellation proof, never a timeout. Replaces the free-text
485
+ * {@link FailWithdrawal}.
486
+ */
487
+ export interface FailWithdrawalReceipt {
488
+ /** The finalized `Cancelled` bridge receipt. */
489
+ receipt: BridgeWithdrawalReceipt;
490
+ /** Operator ed25519 quorum proof over the receipt bytes. */
491
+ proof: OperatorReceiptProof;
492
+ }
493
+ /**
494
+ * Records the operator-quorum-signed `WithdrawalAuthorizationV1` for a pending
495
+ * withdrawal (action `0x24`), binding its digest to the record so a terminal
496
+ * receipt (`0x22`/`0x23`) can only settle an authorization the quorum actually
497
+ * issued. Permissionless to submit — the operator quorum in `proof` is the
498
+ * authority, not the envelope signer.
499
+ */
500
+ export interface AuthorizeWithdrawal {
501
+ /** The canonical `WithdrawalAuthorizationV1` bytes the quorum signed
502
+ * (`bridge_core::WithdrawalAuthorizationV1::encode`, fixed 221 bytes). */
503
+ authorization: Uint8Array;
504
+ /** Operator ed25519 quorum proof over the authorization bytes. */
505
+ proof: OperatorReceiptProof;
506
+ }
507
+ /** One optional limb of a whole-position protection bracket. */
508
+ export interface TriggerLimb {
509
+ /** Trigger threshold in micro-USDC; must be non-zero. */
510
+ triggerPrice: bigint;
511
+ /** IOC execution collar in basis points; must be in `1..=9999`. */
512
+ maxSlippageBps: number;
513
+ /** Optional non-zero client correlation id for this limb. */
514
+ clientTriggerId?: bigint | null;
515
+ }
516
+ /** Atomically replace the owner's complete stop-loss/take-profit bracket. */
517
+ export interface SetPositionTriggers {
518
+ market: number;
519
+ owner: Address;
520
+ /** Current position generation read from `/v1/triggers/{owner}`. */
521
+ expectedPositionEpoch: bigint;
522
+ stopLoss?: TriggerLimb | null;
523
+ takeProfit?: TriggerLimb | null;
524
+ /** Optional non-zero idempotency/correlation id for the whole bracket. */
525
+ clientGroupId?: bigint | null;
526
+ }
527
+ /** Cancel the active bracket for one exact position generation. */
528
+ export interface CancelPositionTriggers {
529
+ market: number;
530
+ owner: Address;
531
+ expectedPositionEpoch: bigint;
532
+ }
533
+ /** Complete multisig-controlled trigger policy for one market (admin tag 5). */
534
+ export interface SetTriggerMarketConfig {
535
+ market: number;
536
+ expectedCurrentVersion?: bigint | null;
537
+ enabled: boolean;
538
+ maxTriggerSlippageBps: number;
539
+ maxMarkAgeMs: bigint;
540
+ maxFuturePublishSkewMs: bigint;
541
+ maxActiveBrackets: bigint;
542
+ }
543
+ /**
544
+ * Approve a delegate keypair ("agent wallet") to trade on the owner's behalf.
545
+ * The agent can place/cancel orders but CANNOT withdraw or move funds.
546
+ */
547
+ export interface ApproveAgent {
548
+ /** Account address granting the delegation (20 bytes). */
549
+ owner: Address;
550
+ /** Ed25519 public key of the agent wallet (32 bytes). */
551
+ agentPubkey: Uint8Array;
552
+ }
553
+ /** Revoke a previously approved agent wallet. */
554
+ export interface RevokeAgent {
555
+ /** Account address revoking the delegation (20 bytes). */
556
+ owner: Address;
557
+ /** Ed25519 public key of the agent wallet to revoke (32 bytes). */
558
+ agentPubkey: Uint8Array;
559
+ }
560
+ /** Branch of a binary event. */
561
+ export declare enum Branch {
562
+ Yes = 1,
563
+ No = 2
564
+ }
565
+ /** Outcome of an impact-market event. */
566
+ export declare enum Outcome {
567
+ Yes = 1,
568
+ No = 2,
569
+ Void = 3
570
+ }
571
+ /**
572
+ * BE-54: comparison operator used by the auto-resolve oracle modes.
573
+ * `YES` fires iff `oracle_price <comparison> strike_price` (e.g.
574
+ * `GreaterThan` means the event resolves YES when the oracle reading is
575
+ * strictly greater than the strike). Equality on the boundary is
576
+ * distinguished by the `OrEqual` variants. Mirrors the engine's
577
+ * `PriceComparison` enum exactly.
578
+ */
579
+ export type PriceComparison = "GreaterThan" | "LessThan" | "GreaterThanOrEqual" | "LessThanOrEqual";
580
+ /**
581
+ * BE-54: how an impact-market event's YES/NO outcome is determined at
582
+ * deadline. Carried optionally on `CreateImpactMarket`; `undefined`
583
+ * (the wire `nil`) means `RelayerAttested` — the legacy default where
584
+ * the resolver supplies the outcome and the engine trusts it. The two
585
+ * auto-resolve modes derive YES/NO from an on-chain oracle reading and
586
+ * make the relayer's outcome a verifiable assertion (engine recomputes
587
+ * and rejects on mismatch). Use `RelayerAttested` for events that have
588
+ * no on-chain price (e.g. "did Apple announce X?").
589
+ */
590
+ export type EventOracleSource = {
591
+ kind: "UnderlyingPriceVsStrike";
592
+ strikePrice: bigint;
593
+ comparison: PriceComparison;
594
+ } | {
595
+ kind: "MarketOracle";
596
+ market: number;
597
+ strikePrice: bigint;
598
+ comparison: PriceComparison;
599
+ } | {
600
+ kind: "RelayerAttested";
601
+ };
602
+ /** Create an impact-market family with 4 child books (CPY/CPN/EBY/EBN). */
603
+ export interface CreateImpactMarket {
604
+ impactMarketId: number;
605
+ underlyingMarket: number;
606
+ childMarketBase: number;
607
+ question: string;
608
+ deadlineMs: bigint;
609
+ resolutionWindowMs: bigint;
610
+ imBps: number;
611
+ mmBps: number;
612
+ takerFeeBps: number;
613
+ makerFeeBps: number;
614
+ fundingIntervalMs: bigint;
615
+ maxFundingRateBps: number;
616
+ signer: Address;
617
+ /**
618
+ * BE-54: how this event's YES/NO outcome is determined at deadline.
619
+ * Optional — `undefined` (the wire `nil`) means `RelayerAttested`,
620
+ * which preserves the legacy behavior where the resolver supplies the
621
+ * outcome and the engine trusts it. Setting `UnderlyingPriceVsStrike`
622
+ * or `MarketOracle` makes the resolution self-verifying: the engine
623
+ * derives YES/NO from the named oracle's reading and rejects any
624
+ * `ResolveEvent` whose `outcome` doesn't match. `Outcome.Void`
625
+ * overrides the auto-derivation in either auto-resolve mode (operator
626
+ * escape hatch for unresolvable events).
627
+ */
628
+ oracleSource?: EventOracleSource;
629
+ /** Optional event body text for frontend detail pages. Encodes as "" when
630
+ * absent (matches the engine's `serde(default)`). */
631
+ description?: string;
632
+ /** Optional resolution criteria text. Encodes as "" when absent (matches
633
+ * the engine's `serde(default)`). */
634
+ rules?: string;
635
+ }
636
+ /** Resolve an impact-market event. */
637
+ export interface ResolveEvent {
638
+ impactMarketId: number;
639
+ outcome: Outcome;
640
+ signer: Address;
641
+ }
642
+ /**
643
+ * Update a subset of `MarketConfig` fields on an existing market.
644
+ * Every tunable is optional; `null`/`undefined` leaves the current
645
+ * value untouched. Requires relayer authorization.
646
+ *
647
+ * Built 2026-04-21 when we observed BTC funding spikes to −1608 bps
648
+ * under the seed-time max_funding_rate_bps = 3000 cap on a live
649
+ * chain we couldn't rebase. This is the engine-level lever to tighten
650
+ * parameters on a running market.
651
+ *
652
+ * `kind` and `szDecimals` remain immutable. Margin ratios may only be
653
+ * tightened by the engine; lowering either live risk floor is rejected.
654
+ */
655
+ export interface UpdateMarketFees {
656
+ market: number;
657
+ signer: Address;
658
+ /** New taker fee in basis points. Omit to leave unchanged. */
659
+ takerFeeBps?: number | null;
660
+ /** New maker fee in basis points. Omit to leave unchanged. */
661
+ makerFeeBps?: number | null;
662
+ /** New max funding rate cap in basis points per interval. 0 = disable funding. */
663
+ maxFundingRateBps?: number | null;
664
+ /** New funding interval in ms. Omit to leave unchanged. */
665
+ fundingIntervalMs?: bigint | null;
666
+ /** New per-account position cap in contracts. 0 = disable cap. */
667
+ maxPositionSize?: bigint | null;
668
+ /**
669
+ * New default order TTL in milliseconds. Omit to leave unchanged.
670
+ * 0 disables the end-of-block order-expiry sweep for this market.
671
+ * Added 2026-04-23 (see `run_order_expiry` in the engine): gives
672
+ * operators a live lever to auto-cancel stale MM quotes instead of
673
+ * requiring `make repair`.
674
+ */
675
+ defaultTtlMs?: bigint | null;
676
+ /**
677
+ * Flip net-delta portfolio margin on this market. Omit to leave
678
+ * unchanged. true = firing legs with the same underlying group into
679
+ * a single net position for MM/IM (|Σ signed_size| × settle ×
680
+ * weighted_bps); false = per-leg scenario margin. See
681
+ * `MarketConfig.netDeltaMargin` and `docs/margin-engine.md §6`.
682
+ * Safe to flip on at any time; flipping off can push accounts
683
+ * under MM.
684
+ */
685
+ netDeltaMargin?: boolean | null;
686
+ /**
687
+ * New tick size in micro-USDC. Omit (or null) to leave unchanged.
688
+ * 0 disables the tick gate (any price accepted). BE-48.
689
+ */
690
+ tickSize?: bigint | null;
691
+ /**
692
+ * New lot size in contracts. Omit (or null) to leave unchanged.
693
+ * 0 disables the lot gate (any quantity accepted). BE-48.
694
+ */
695
+ lotSize?: bigint | null;
696
+ /**
697
+ * Primary oracle signer for this market. Omit (or null) to leave
698
+ * unchanged. Pass an all-zero address (20 zero bytes) to
699
+ * clear the primary signer; setting `oracleStalenessMs` to 0 only
700
+ * temporarily disables the fallback gate while preserving the configured
701
+ * primary. BE-50.
702
+ */
703
+ primaryOracleSigner?: Address | null;
704
+ /**
705
+ * Oracle staleness threshold in ms. Omit (or null) to leave
706
+ * unchanged. Only consulted when `primaryOracleSigner` is set on
707
+ * the market. 0 disables the gate. BE-50.
708
+ */
709
+ oracleStalenessMs?: bigint | null;
710
+ /**
711
+ * BE-31 Phase A: mark-price source mode. Omit to leave unchanged.
712
+ * 0 = OracleOnly (legacy); 1 = Median (oracle + book-mid).
713
+ * Has no effect on impact-family child markets - those always
714
+ * mark off the EWMA per the no-oracle-MTM redesign.
715
+ */
716
+ markSourceMode?: 0 | 1 | null;
717
+ /**
718
+ * BE-31 Phase A: thin-book spread cap in bps for the median guard.
719
+ * Omit to leave unchanged. 0 resets to the engine default
720
+ * (DEFAULT_MAX_MARK_SPREAD_BPS = 100). Ignored unless
721
+ * `markSourceMode === 1`.
722
+ */
723
+ maxMarkSpreadBps?: number | null;
724
+ /**
725
+ * BE-31 Phase B: max age in ms for the composite-CEX price source.
726
+ * Omit to leave unchanged. 0 resets to the engine default
727
+ * (DEFAULT_CEX_COMPOSITE_STALENESS_MS = 30s).
728
+ */
729
+ cexCompositeStalenessMs?: bigint | null;
730
+ /**
731
+ * BE-26: enable partial liquidation for this market. Omit to leave
732
+ * unchanged. true closes one position at a time and rechecks MM.
733
+ */
734
+ partialLiquidationEnabled?: boolean | null;
735
+ /**
736
+ * Replace the rolling-volume fee-tier table. Omit to leave unchanged;
737
+ * [] clears volume tiers and falls back to flat taker/maker bps.
738
+ */
739
+ feeTiers?: FeeTier[] | null;
740
+ /**
741
+ * New initial margin ratio in basis points. Omit to leave unchanged.
742
+ * Must be greater than or equal to the current market value.
743
+ */
744
+ imBps?: number | null;
745
+ /**
746
+ * New maintenance margin ratio in basis points. Omit to leave unchanged.
747
+ * Must be greater than or equal to the current value, positive, and no
748
+ * greater than the resulting `imBps`.
749
+ */
750
+ mmBps?: number | null;
751
+ /**
752
+ * New aggregate open-interest cap in contracts. Omit to leave unchanged;
753
+ * 0 disables the cap.
754
+ */
755
+ maxOpenInterest?: bigint | null;
756
+ }
757
+ /** Lifecycle status of an impact-market family. */
758
+ export type ImpactMarketStatus = {
759
+ kind: "Trading";
760
+ } | {
761
+ kind: "PreResolution";
762
+ } | {
763
+ kind: "Resolved";
764
+ outcome: Outcome;
765
+ };
766
+ /** On-chain info for an impact-market family. */
767
+ export interface ImpactMarketInfo {
768
+ impactMarketId: number;
769
+ underlyingMarket: number;
770
+ cpyMarket: number;
771
+ cpnMarket: number;
772
+ ebyMarket: number;
773
+ ebnMarket: number;
774
+ question: string;
775
+ deadlineMs: bigint;
776
+ resolutionWindowMs: bigint;
777
+ status: ImpactMarketStatus;
778
+ createdMs: bigint;
779
+ resolvedMs: bigint;
780
+ /** BE-54: how the YES/NO outcome is determined at deadline. `undefined`
781
+ * (older gateways / pre-BE-54 records) means `RelayerAttested`. */
782
+ oracleSource?: EventOracleSource;
783
+ /** Event body text; `""` when the record has none. `undefined` only on
784
+ * gateways older than admin-actions v2 (field not served). */
785
+ description?: string;
786
+ /** Resolution criteria text; same shipping note as `description`. */
787
+ rules?: string;
788
+ }
789
+ /** Pick a per-account override on the initial-margin ratio for one
790
+ * market. Engine takes max(market.imBps, userImBps), so users can
791
+ * deleverage but not exceed the market's risk floor. `userImBps == 0`
792
+ * clears the override. User-signed (signer == owner). BE-16. */
793
+ export interface SetUserMarketLeverage {
794
+ /** Account address picking the override (20 bytes). Must equal the
795
+ * envelope signer's derived address. */
796
+ owner: Address;
797
+ /** Market identifier the override applies to. */
798
+ market: number;
799
+ /** Initial margin in basis points. `0` clears the override;
800
+ * otherwise must be `>= market.imBps` (engine rejects with
801
+ * `UserLeverageBelowMarketIm`, code 38). */
802
+ userImBps: number;
803
+ }
804
+ /** Close an entire position on a market by placing an opposite-side IOC
805
+ * order at oracle±spread. Idempotent: returns code=0 without events if
806
+ * no position exists. User-signed (signer == owner). S49. */
807
+ export interface ClosePosition {
808
+ /** Market identifier to close the position on. */
809
+ market: number;
810
+ /** Account address of the position owner (20 bytes). Must equal the
811
+ * envelope signer's derived address. */
812
+ owner: Address;
813
+ }
814
+ /** One leg of a native all-or-revert basket. The engine executes every leg as
815
+ * a fill-or-kill limit order; if any leg cannot fully fill at `price` or
816
+ * better, the whole transaction rolls back. */
817
+ export interface AtomicBasketLeg {
818
+ /** Market identifier for this leg. */
819
+ market: number;
820
+ /** Leg side: Buy or Sell. */
821
+ side: Side;
822
+ /** Worst acceptable execution price in micro-USDC. Buy legs will not pay
823
+ * above this; sell legs will not sell below it. */
824
+ price: bigint;
825
+ /** Leg quantity in contracts (integer lots). */
826
+ quantity: bigint;
827
+ /** Optional client-assigned order ID echoed in events for correlation. */
828
+ clientOrderId?: bigint | null;
829
+ /** When true, this leg may only reduce an existing position. */
830
+ reduceOnly?: boolean;
831
+ }
832
+ /** Native all-or-revert multi-leg basket order (action `0x1c`). Every leg fills
833
+ * fully or the entire transaction reverts through the tx overlay. */
834
+ export interface AtomicBasketOrder {
835
+ /** Account address of the basket owner (20 bytes). Must equal the envelope
836
+ * signer's derived address. */
837
+ owner: Address;
838
+ /** Ordered legs; each executes as a fill-or-kill limit order. */
839
+ legs: AtomicBasketLeg[];
840
+ /** Basket-wide slippage budget in basis points. The engine enforces each
841
+ * leg's explicit price limit; this value is emitted for auditability and
842
+ * client/UI reconciliation. Encodes as 0 when absent (NOT nil). */
843
+ maxSlippageBps?: number;
844
+ }
845
+ /**
846
+ * Trading actions — the surface a normal integration (market maker, bot,
847
+ * trader) uses. User-signed: each is authorized by the account that owns the
848
+ * order/position/funds it touches. This is the union you want by default.
849
+ */
850
+ export type TraderAction = {
851
+ type: "PlaceOrder";
852
+ data: PlaceOrder;
853
+ } | {
854
+ type: "CancelOrder";
855
+ data: CancelOrder;
856
+ } | {
857
+ type: "CancelClientOrder";
858
+ data: CancelClientOrder;
859
+ } | {
860
+ type: "CancelAllOrders";
861
+ data: CancelAllOrders;
862
+ } | {
863
+ type: "CancelReplaceOrder";
864
+ data: CancelReplaceOrder;
865
+ } | {
866
+ type: "AmendOrder";
867
+ data: AmendOrder;
868
+ } | {
869
+ type: "AtomicBasketOrder";
870
+ data: AtomicBasketOrder;
871
+ } | {
872
+ type: "MarketOrder";
873
+ data: MarketOrder;
874
+ } | {
875
+ type: "WithdrawRequest";
876
+ data: WithdrawRequest;
877
+ } | {
878
+ type: "ApproveAgent";
879
+ data: ApproveAgent;
880
+ } | {
881
+ type: "RevokeAgent";
882
+ data: RevokeAgent;
883
+ } | {
884
+ type: "SetUserMarketLeverage";
885
+ data: SetUserMarketLeverage;
886
+ } | {
887
+ type: "ClosePosition";
888
+ data: ClosePosition;
889
+ } | {
890
+ type: "SetPositionTriggers";
891
+ data: SetPositionTriggers;
892
+ } | {
893
+ type: "CancelPositionTriggers";
894
+ data: CancelPositionTriggers;
895
+ };
896
+ /**
897
+ * Operator actions — privileged infrastructure submitted by the operator's
898
+ * relayer / oracle relay / CEX-composite feeder, **not** by a trading
899
+ * integration. Each is gated by a dedicated engine allowlist (relayer, oracle,
900
+ * or composite-feeder); a normal trader's signer is rejected. They are part of
901
+ * the public wire contract (so operator tooling has one SDK), but a trading
902
+ * consumer should never need them. See the "Operator actions" section in
903
+ * AGENTS.md / README.md.
904
+ */
905
+ export type OperatorAction = {
906
+ type: "OracleUpdate";
907
+ data: OracleUpdate;
908
+ } | {
909
+ type: "OracleUpdateComposite";
910
+ data: OracleUpdateComposite;
911
+ } | {
912
+ type: "Deposit";
913
+ data: Deposit;
914
+ } | {
915
+ type: "Withdraw";
916
+ data: Withdraw;
917
+ } | {
918
+ type: "CreateMarket";
919
+ data: CreateMarket;
920
+ } | {
921
+ type: "ConfirmDeposit";
922
+ data: ConfirmDeposit;
923
+ } | {
924
+ type: "ConfirmWithdrawal";
925
+ data: ConfirmWithdrawal;
926
+ } | {
927
+ type: "FailWithdrawal";
928
+ data: FailWithdrawal;
929
+ } | {
930
+ type: "ConfirmWithdrawalReceipt";
931
+ data: ConfirmWithdrawalReceipt;
932
+ } | {
933
+ type: "FailWithdrawalReceipt";
934
+ data: FailWithdrawalReceipt;
935
+ } | {
936
+ type: "AuthorizeWithdrawal";
937
+ data: AuthorizeWithdrawal;
938
+ } | {
939
+ type: "CreateImpactMarket";
940
+ data: CreateImpactMarket;
941
+ } | {
942
+ type: "ResolveEvent";
943
+ data: ResolveEvent;
944
+ } | {
945
+ type: "UpdateMarketFees";
946
+ data: UpdateMarketFees;
947
+ };
948
+ /**
949
+ * Discriminated union of every exchange action. Equals
950
+ * {@link TraderAction} ∪ {@link OperatorAction}. `submitTx` accepts this full
951
+ * union — trading integrations can narrow to `TraderAction` to keep operator
952
+ * actions out of autocomplete.
953
+ */
954
+ /**
955
+ * Replacement admin signer roster. The engine assigns the next registry
956
+ * version; members are validated (sorted, duplicate-free) on-chain.
957
+ */
958
+ export interface UpdateAdminSignerRegistry {
959
+ /** Approvals the replacement roster will require. */
960
+ newThreshold: number;
961
+ /** Members of the replacement roster (each a 20-byte address). */
962
+ newMembers: Address[];
963
+ }
964
+ /**
965
+ * One item of a governance `Batch` — a CLOSED, non-recursive subset of
966
+ * `AdminAction` (market-creation shapes only, mirroring the engine's
967
+ * `AdminBatchItem`). A batch can never contain another batch or a
968
+ * registry change; the type makes that unrepresentable, exactly as the
969
+ * engine's enum does. Variant names are wire-identical to the
970
+ * `AdminAction` arms of the same name.
971
+ */
972
+ export type AdminBatchItem = {
973
+ kind: "CreateMarket";
974
+ value: CreateMarket;
975
+ } | {
976
+ kind: "CreateImpactMarket";
977
+ value: CreateImpactMarket;
978
+ };
979
+ /**
980
+ * Governance cancel of every resting order one account holds, optionally
981
+ * confined to one market (inner tag `0x08`). A one-shot sweep at quorum,
982
+ * not a freeze: the engine emits one `OrderCancelled` per order with reason
983
+ * `admin_force`. A zero `owner` is refused at propose; a `market` that does
984
+ * not exist fails the proposal at execution.
985
+ */
986
+ export interface CancelAllOrdersForAccount {
987
+ /** The account whose resting orders are cancelled (20-byte address). */
988
+ owner: Address;
989
+ /** Confine the cancel to one market; omit to sweep every market. */
990
+ market?: number | null;
991
+ }
992
+ /**
993
+ * Closed, typed set of operations executable through the multisig. The
994
+ * embedded `CreateMarket.signer` / `CreateImpactMarket.signer` must be
995
+ * zero — governance supplies the authorization, not the embedded address.
996
+ *
997
+ * `Batch` executes its items atomically in order against one overlay:
998
+ * all succeed or the proposal fails with no partial state. Admitted on
999
+ * chain only once admin-actions v2 activates (`CreateImpactMarket`
1000
+ * likewise); the engine refuses the tags below the activation height.
1001
+ */
1002
+ export type AdminAction = {
1003
+ kind: "CreateMarket";
1004
+ value: CreateMarket;
1005
+ } | {
1006
+ kind: "UpdateAdminSignerRegistry";
1007
+ value: UpdateAdminSignerRegistry;
1008
+ } | {
1009
+ kind: "CreateImpactMarket";
1010
+ value: CreateImpactMarket;
1011
+ } | {
1012
+ kind: "Batch";
1013
+ value: AdminBatchItem[];
1014
+ } | {
1015
+ kind: "SetTriggerMarketConfig";
1016
+ value: SetTriggerMarketConfig;
1017
+ } | {
1018
+ kind: "UnpauseBridge";
1019
+ } | {
1020
+ kind: "CancelAllOrdersForAccount";
1021
+ value: CancelAllOrdersForAccount;
1022
+ };
1023
+ /**
1024
+ * Closed set of immediate, loss-reducing single-signer actions. Reverse
1025
+ * transitions (unpause/resume) are intentionally absent — they require a
1026
+ * multisig `AdminAction`.
1027
+ */
1028
+ export type EmergencyAction = {
1029
+ kind: "PauseMarket";
1030
+ value: {
1031
+ marketId: number;
1032
+ };
1033
+ } | {
1034
+ kind: "HaltTrading";
1035
+ value?: Record<string, never>;
1036
+ } | {
1037
+ kind: "SetReduceOnly";
1038
+ value: {
1039
+ marketId: number;
1040
+ };
1041
+ };
1042
+ /** Signed governance proposal (action 0x1e). */
1043
+ export interface ProposeAdminAction {
1044
+ /** Address authorizing the proposal (20 bytes). */
1045
+ proposer: Address;
1046
+ /** Registry version under which the proposal is submitted. */
1047
+ registryVersion: bigint;
1048
+ /** Admin operation proposed for multisig execution. */
1049
+ action: AdminAction;
1050
+ }
1051
+ /**
1052
+ * Signed governance approval (action 0x1f). Carries the complete immutable
1053
+ * proposal context so a signer commits to — and can independently render —
1054
+ * exactly what they approve, never an id+hash alone.
1055
+ */
1056
+ export interface ApproveAdminAction {
1057
+ /** Address authorizing the approval (20 bytes). */
1058
+ approver: Address;
1059
+ /** Identifier of the proposal being approved. */
1060
+ proposalId: bigint;
1061
+ /** Registry version captured when the proposal was created. */
1062
+ registryVersion: bigint;
1063
+ /** Required approval count captured when the proposal was created. */
1064
+ threshold: number;
1065
+ /** Address that created the proposal (20 bytes). */
1066
+ proposer: Address;
1067
+ /** Block height at which the proposal was created. */
1068
+ createdHeight: bigint;
1069
+ /** Block timestamp at which the proposal was created, in milliseconds. */
1070
+ createdMs: bigint;
1071
+ /** Block timestamp after which the proposal expires, in milliseconds. */
1072
+ expiryMs: bigint;
1073
+ /** Typed admin operation being approved. */
1074
+ action: AdminAction;
1075
+ /** Domain-separated commitment to the immutable proposal context (32 bytes). */
1076
+ contentHash: Uint8Array;
1077
+ }
1078
+ /** Signed governance rejection (action 0x20). */
1079
+ export interface RejectAdminAction {
1080
+ /** Address authorizing the rejection (20 bytes). */
1081
+ rejecter: Address;
1082
+ /** Identifier of the proposal being rejected. */
1083
+ proposalId: bigint;
1084
+ /** Domain-separated commitment of the proposal being rejected (32 bytes). */
1085
+ contentHash: Uint8Array;
1086
+ }
1087
+ /** Signed single-signer emergency action (action 0x21). */
1088
+ export interface EmergencyAdminAction {
1089
+ /** Registry member authorizing the action (20 bytes). */
1090
+ signer: Address;
1091
+ /** Immediate loss-reducing operation to execute. */
1092
+ action: EmergencyAction;
1093
+ }
1094
+ /**
1095
+ * Governance actions — admin-multisig propose/approve/reject and the
1096
+ * single-signer emergency action. Authorized on-chain against the versioned
1097
+ * signer registry; a normal trader's signer is rejected.
1098
+ */
1099
+ export type GovernanceAction = {
1100
+ type: "ProposeAdminAction";
1101
+ data: ProposeAdminAction;
1102
+ } | {
1103
+ type: "ApproveAdminAction";
1104
+ data: ApproveAdminAction;
1105
+ } | {
1106
+ type: "RejectAdminAction";
1107
+ data: RejectAdminAction;
1108
+ } | {
1109
+ type: "EmergencyAdminAction";
1110
+ data: EmergencyAdminAction;
1111
+ };
1112
+ export type Action = TraderAction | OperatorAction | GovernanceAction;
1113
+ /** The installed admin signer roster. Absent (a `null` read) means multisig
1114
+ * administration is INACTIVE — never an empty roster. */
1115
+ export interface AdminSignerRegistry {
1116
+ /** Monotone, starts at 1, never reused; a rotation assigns +1. */
1117
+ version: bigint;
1118
+ /** Approvals required to execute a proposal (`2 <= threshold <= members`). */
1119
+ threshold: number;
1120
+ /** Canonically sorted, duplicate-free roster (each a 20-byte address). */
1121
+ members: Address[];
1122
+ }
1123
+ /** Why a pending proposal expired. */
1124
+ export type ExpiryReason = "Ttl" | "RegistryChanged";
1125
+ /**
1126
+ * Status of an admin proposal. Terminal states carry the payload the engine
1127
+ * committed with them, so a caller never has to re-derive WHY a proposal
1128
+ * ended: `Failed` carries the unnarrowed `ExecError` code, `Rejected` the
1129
+ * member whose rejection was decisive, `Expired` the reason.
1130
+ */
1131
+ export type ProposalStatus = {
1132
+ kind: "Pending";
1133
+ } | {
1134
+ kind: "Executed";
1135
+ } | {
1136
+ kind: "Failed";
1137
+ code: number;
1138
+ } | {
1139
+ kind: "Rejected";
1140
+ by: Address;
1141
+ } | {
1142
+ kind: "Expired";
1143
+ reason: ExpiryReason;
1144
+ };
1145
+ /**
1146
+ * One proposal, shaped by the engine for display AND offline verification.
1147
+ *
1148
+ * The context fields plus `actionCanonicalBytes` are exactly what an
1149
+ * approving signer needs to rebuild an `ApproveAdminAction` locally, without
1150
+ * trusting anything a user interface rendered — which is the point: an
1151
+ * approval is a commitment to specific bytes, so the bytes must be
1152
+ * reconstructible from chain state alone.
1153
+ */
1154
+ export interface ProposalDisplayInfo {
1155
+ proposalId: bigint;
1156
+ /** Status as written by the handlers. */
1157
+ statusStored: ProposalStatus;
1158
+ /**
1159
+ * Status with the engine's own lazy-expiry rule already applied: a stored
1160
+ * `Pending` past its `expiryMs` reads as `Expired { Ttl }`. The `status`
1161
+ * query filter matches THIS field, so no two readers can disagree by
1162
+ * applying different client-side staleness rules — prefer it for display.
1163
+ */
1164
+ statusEffective: ProposalStatus;
1165
+ /** Registry version the proposal was created under. */
1166
+ registryVersion: bigint;
1167
+ /** Approvals required, captured at creation. */
1168
+ threshold: number;
1169
+ proposer: Address;
1170
+ /** Distinct approving members. The proposer counts as approval #1. */
1171
+ approvals: Address[];
1172
+ rejections: Address[];
1173
+ createdHeight: bigint;
1174
+ createdMs: bigint;
1175
+ /** Block time after which the proposal expires. */
1176
+ expiryMs: bigint;
1177
+ /** Engine-owned discriminant of `action`, committed by the content hash. */
1178
+ actionTag: number;
1179
+ /** Typed decode of the proposed operation. */
1180
+ action: AdminAction;
1181
+ /** The EXACT stored engine-canonical bytes the content hash covers. */
1182
+ actionCanonicalBytes: Uint8Array;
1183
+ /** Domain-separated commitment to the immutable proposal context. */
1184
+ contentHash: Uint8Array;
1185
+ }
1186
+ /** A page of proposals, ascending by id. */
1187
+ export interface ProposalPage {
1188
+ proposals: ProposalDisplayInfo[];
1189
+ /** Last-seen id; pass as `cursor` for the next page. `null` = last page. */
1190
+ nextCursor: bigint | null;
1191
+ }
1192
+ /** Emitted when a limit order is placed on the order book. All string fields are stringified numbers. */
1193
+ export interface OrderPlacedEvent {
1194
+ type: "OrderPlaced";
1195
+ /** Engine-assigned order ID. */
1196
+ orderId: string;
1197
+ /** Market identifier. */
1198
+ market: string;
1199
+ /** Hex-encoded owner address. */
1200
+ owner: string;
1201
+ /** Order side ("Buy" or "Sell"). */
1202
+ side: string;
1203
+ /** Limit price in micro-USDC (6 dp, e.g., "66752340000" = $66,752.34). */
1204
+ price: string;
1205
+ /** Order quantity in contracts (integer lots). */
1206
+ quantity: string;
1207
+ /** Client-assigned order ID, or "0" when absent. */
1208
+ clientOrderId: string;
1209
+ }
1210
+ /** Emitted when an order is cancelled. */
1211
+ export interface OrderCancelledEvent {
1212
+ type: "OrderCancelled";
1213
+ /** Engine-assigned order ID. */
1214
+ orderId: string;
1215
+ /** Market identifier. */
1216
+ market: string;
1217
+ /** Hex-encoded owner address. */
1218
+ owner: string;
1219
+ /** Cancellation reason (e.g., "user_requested", "liquidation"). */
1220
+ reason: string;
1221
+ /** Client-assigned order ID, or "0" when absent. */
1222
+ clientOrderId: string;
1223
+ /** Quantity originally accepted onto the book. */
1224
+ originalQuantity: string;
1225
+ /** Quantity still resting when cancelled. */
1226
+ remainingQuantity: string;
1227
+ /** Cumulative maker quantity filled before cancellation. */
1228
+ filledQuantity: string;
1229
+ }
1230
+ /** Emitted when a trade (fill) is executed between a maker and taker. */
1231
+ export interface TradeExecutedEvent {
1232
+ type: "TradeExecuted";
1233
+ /** Unique fill identifier. */
1234
+ fillId: string;
1235
+ /** Market identifier. */
1236
+ market: string;
1237
+ /** Execution price in micro-USDC (6 dp). */
1238
+ price: string;
1239
+ /** Fill quantity in contracts (integer lots). */
1240
+ quantity: string;
1241
+ /** Engine-assigned order ID of the resting (maker) order. */
1242
+ makerOrderId: string;
1243
+ /** Maker client-assigned order ID, or "0" when absent. */
1244
+ makerClientOrderId: string;
1245
+ /** Hex-encoded maker address. */
1246
+ makerOwner: string;
1247
+ /** Maker's side ("Buy" or "Sell"). */
1248
+ makerSide: string;
1249
+ /** Hex-encoded taker address. */
1250
+ takerOwner: string;
1251
+ /** Taker client-assigned order ID, or "0" when absent. */
1252
+ takerClientOrderId: string;
1253
+ /** Taker fee in microUSDC. Current engine emits non-negative charges. */
1254
+ takerFee: string;
1255
+ /** Maker fee in microUSDC. Current engine emits non-negative charges. */
1256
+ makerFee: string;
1257
+ }
1258
+ /** Emitted alongside TradeExecuted to summarize fees for a fill. */
1259
+ export interface FeesCollectedEvent {
1260
+ type: "FeesCollected";
1261
+ /** Market identifier. */
1262
+ market: string;
1263
+ /** Hex-encoded taker address. */
1264
+ takerOwner: string;
1265
+ /** Taker fee in microUSDC (signed). */
1266
+ takerFee: string;
1267
+ /** Hex-encoded maker address. */
1268
+ makerOwner: string;
1269
+ /** Maker fee in microUSDC (signed). */
1270
+ makerFee: string;
1271
+ }
1272
+ /** Emitted when USDC is deposited into an account. */
1273
+ export interface DepositedEvent {
1274
+ type: "Deposited";
1275
+ /** Hex-encoded owner address. */
1276
+ owner: string;
1277
+ /** Deposited amount in microUSDC (6 dp). */
1278
+ amount: string;
1279
+ /** Balance after deposit in microUSDC (6 dp). */
1280
+ newBalance: string;
1281
+ }
1282
+ /** Emitted when USDC is withdrawn from an account. */
1283
+ export interface WithdrawnEvent {
1284
+ type: "Withdrawn";
1285
+ /** Hex-encoded owner address. */
1286
+ owner: string;
1287
+ /** Withdrawn amount in microUSDC (6 dp). */
1288
+ amount: string;
1289
+ /** Balance after withdrawal in microUSDC (6 dp). */
1290
+ newBalance: string;
1291
+ }
1292
+ /** Emitted when a position is opened or its size/entry changes due to a fill. */
1293
+ export interface PositionUpdatedEvent {
1294
+ type: "PositionUpdated";
1295
+ /** Hex-encoded owner address. */
1296
+ owner: string;
1297
+ /** Market identifier. */
1298
+ market: string;
1299
+ /** Position side ("Buy" = long, "Sell" = short). */
1300
+ side: string;
1301
+ /** Weighted-average entry price in micro-USDC (6 dp). */
1302
+ entryPrice: string;
1303
+ /** Absolute position size in contracts (integer lots). */
1304
+ size: string;
1305
+ }
1306
+ /** Emitted when a position is fully closed. */
1307
+ export interface PositionClosedEvent {
1308
+ type: "PositionClosed";
1309
+ /** Hex-encoded owner address. */
1310
+ owner: string;
1311
+ /** Market identifier. */
1312
+ market: string;
1313
+ /** Realized PnL in microUSDC (signed; positive = profit). */
1314
+ realizedPnl: string;
1315
+ }
1316
+ /** Emitted when the oracle price is updated for a market. */
1317
+ export interface PriceUpdatedEvent {
1318
+ type: "PriceUpdated";
1319
+ /** Market identifier. */
1320
+ market: string;
1321
+ /** New oracle price in micro-USDC (6 dp). */
1322
+ price: string;
1323
+ }
1324
+ /** Emitted when a new perpetual market is registered. */
1325
+ export interface MarketCreatedEvent {
1326
+ type: "MarketCreated";
1327
+ /** Market identifier. */
1328
+ market: string;
1329
+ /** Initial margin requirement in basis points. */
1330
+ imBps: string;
1331
+ /** Maintenance margin requirement in basis points. */
1332
+ mmBps: string;
1333
+ /** Taker fee rate in basis points. */
1334
+ takerFeeBps: string;
1335
+ /** Maker fee rate in basis points. */
1336
+ makerFeeBps: string;
1337
+ /** Funding interval in milliseconds (0 = disabled). */
1338
+ fundingIntervalMs: string;
1339
+ /** Maximum absolute funding rate per interval in basis points. */
1340
+ maxFundingRateBps: string;
1341
+ }
1342
+ /** Emitted when an account is liquidated due to insufficient maintenance margin. */
1343
+ export interface AccountLiquidatedEvent {
1344
+ type: "AccountLiquidated";
1345
+ /** Hex-encoded owner address. */
1346
+ owner: string;
1347
+ /** Market identifier. */
1348
+ market: string;
1349
+ /** Liquidated position side ("Buy" or "Sell"). */
1350
+ side: string;
1351
+ /** Liquidated position size in contracts (integer lots). */
1352
+ size: string;
1353
+ /** Mark price at liquidation in micro-USDC (6 dp). */
1354
+ markPrice: string;
1355
+ /** Realized PnL from liquidation in microUSDC (signed). */
1356
+ realizedPnl: string;
1357
+ }
1358
+ /** Emitted when periodic funding is applied to a market. */
1359
+ export interface FundingAppliedEvent {
1360
+ type: "FundingApplied";
1361
+ /** Market identifier. */
1362
+ market: string;
1363
+ /** Funding rate in basis points (signed; positive = longs pay shorts). */
1364
+ fundingRateBps: string;
1365
+ /** Cumulative funding index after this application (signed). */
1366
+ cumulativeFunding: string;
1367
+ /** Block timestamp in milliseconds when funding was applied. */
1368
+ timestampMs: string;
1369
+ }
1370
+ /** Emitted when funding is settled for an individual position. */
1371
+ export interface FundingSettledEvent {
1372
+ type: "FundingSettled";
1373
+ /** Hex-encoded owner address. */
1374
+ owner: string;
1375
+ /** Market identifier. */
1376
+ market: string;
1377
+ /** Funding payment in microUSDC (signed; positive = received, negative = paid). */
1378
+ payment: string;
1379
+ }
1380
+ /** Emitted when an agent wallet is approved for delegation. */
1381
+ export interface AgentApprovedEvent {
1382
+ type: "AgentApproved";
1383
+ /** Hex-encoded owner address. */
1384
+ owner: string;
1385
+ /** Hex-encoded agent address (derived from agentPubkey). */
1386
+ agent: string;
1387
+ /** Hex-encoded Ed25519 public key of the agent (32 bytes). */
1388
+ agentPubkey: string;
1389
+ }
1390
+ /** Emitted when an agent wallet delegation is revoked. */
1391
+ export interface AgentRevokedEvent {
1392
+ type: "AgentRevoked";
1393
+ /** Hex-encoded owner address. */
1394
+ owner: string;
1395
+ /** Hex-encoded agent address (derived from agentPubkey). */
1396
+ agent: string;
1397
+ /** Hex-encoded Ed25519 public key of the agent (32 bytes). */
1398
+ agentPubkey: string;
1399
+ }
1400
+ /**
1401
+ * Emitted exactly once at the end of every market-order tx that passes
1402
+ * envelope checks, regardless of how many fills happened.
1403
+ *
1404
+ * This is the authoritative "did my market order do anything?" signal:
1405
+ * - `filledQuantity == requestedQuantity` → fully filled
1406
+ * - `0 < filledQuantity < requestedQuantity` → partial fill, IOC remainder dropped
1407
+ * - `filledQuantity == 0` → no counterparty (or all counterparties were
1408
+ * the taker themselves and got rejected by self-match prevention)
1409
+ *
1410
+ * Without this event, callers would have to count downstream `TradeExecuted`
1411
+ * events and could not distinguish "no counterparty" from "trade events
1412
+ * arrived in a different stream view".
1413
+ */
1414
+ export interface MarketOrderProcessedEvent {
1415
+ type: "MarketOrderProcessed";
1416
+ market: string;
1417
+ /** Hex-encoded owner address. */
1418
+ owner: string;
1419
+ /** Side of the original market order ("Buy" or "Sell"). */
1420
+ side: string;
1421
+ /** Quantity originally requested (integer lots). */
1422
+ requestedQuantity: string;
1423
+ /** Quantity actually filled before IOC drop (integer lots). */
1424
+ filledQuantity: string;
1425
+ /** Client-assigned order ID of the IOC/market/close request, when present. */
1426
+ clientOrderId?: string;
1427
+ }
1428
+ /** Absolute post-mutation quantity at one orderbook price level. */
1429
+ export interface OrderbookLevelUpdatedEvent {
1430
+ type: "OrderbookLevelUpdated";
1431
+ /** Market identifier. */
1432
+ market: string;
1433
+ /** Book side ("Buy" or "Sell"). */
1434
+ side: string;
1435
+ /** Price level in micro-USDC. */
1436
+ price: string;
1437
+ /** Total resting quantity at this price after the mutation. */
1438
+ totalQuantity: string;
1439
+ /** Resting order count at this price after the mutation. */
1440
+ orderCount: string;
1441
+ }
1442
+ /** Union of all exchange events. */
1443
+ export type ExchangeEvent = OrderPlacedEvent | OrderCancelledEvent | TradeExecutedEvent | FeesCollectedEvent | DepositedEvent | WithdrawnEvent | PositionUpdatedEvent | PositionClosedEvent | PriceUpdatedEvent | MarketCreatedEvent | AccountLiquidatedEvent | FundingAppliedEvent | FundingSettledEvent | AgentApprovedEvent | AgentRevokedEvent | MarketOrderProcessedEvent | OrderbookLevelUpdatedEvent;
1444
+ /**
1445
+ * What produced a {@link TxResult}. Lets callers separate an engine rejection
1446
+ * from a transport/timeout failure without reverse-engineering the numeric
1447
+ * `code` (engine codes and synthesized HTTP statuses share that field):
1448
+ *
1449
+ * - `"ok"` — CheckTx accepted the tx (`code === 0`).
1450
+ * - `"engine"` — the engine rejected it with an `ExecError` (`code` 1..53/255);
1451
+ * see {@link TxResult.error} for the decoded name/description.
1452
+ * - `"transport"` — a gateway/HTTP-level failure (auth, rate-limit, body too
1453
+ * large, 5xx, non-JSON body). `code` is the synthesized HTTP
1454
+ * status, not an engine code.
1455
+ * - `"timeout"` — no final chain verdict is available yet (`code === -1`):
1456
+ * either the gateway returned a hash-only ambiguous response
1457
+ * or inclusion polling expired. The tx may still land.
1458
+ */
1459
+ export type TxOutcome = "ok" | "engine" | "transport" | "timeout";
1460
+ /** Result of submitting a transaction to the exchange. */
1461
+ export interface TxResult {
1462
+ /**
1463
+ * True iff the tx passed CheckTx (engine `code === 0`). Primary discriminant —
1464
+ * prefer `if (!result.ok)` over `result.code !== 0`.
1465
+ */
1466
+ ok: boolean;
1467
+ /**
1468
+ * Category of the outcome — see {@link TxOutcome}. Distinguishes engine
1469
+ * rejections from transport/timeout failures that also surface via `code`.
1470
+ */
1471
+ outcome: TxOutcome;
1472
+ /**
1473
+ * Status code. `0` on success; the engine `ExecError` code on
1474
+ * `outcome === "engine"`; a synthesized HTTP status on `"transport"`; `-1` on
1475
+ * `"timeout"`. Retained for back-compat with `result.code === 0` checks.
1476
+ */
1477
+ code: number;
1478
+ /**
1479
+ * Decoded engine error, populated automatically (via `decodeExecError`) when
1480
+ * `outcome === "engine"` and the code is known — so callers get a typed
1481
+ * `{ name, description }` without decoding it themselves. `null` for success,
1482
+ * transport/timeout failures, and unknown engine codes.
1483
+ */
1484
+ error: ExecErrorInfo | null;
1485
+ /** Transaction hash (hex-encoded). Empty string when the tx never got a hash. */
1486
+ hash: string;
1487
+ /** Block height at which the transaction was included. */
1488
+ height?: number;
1489
+ /** Human-readable log message (populated on error). */
1490
+ log?: string;
1491
+ /** ABCI events emitted by the transaction. */
1492
+ events?: TxEvent[];
1493
+ }
1494
+ /** A single ABCI event with key-value attributes. */
1495
+ export interface TxEvent {
1496
+ /** Event type string (e.g., "OrderPlaced", "TradeExecuted"). */
1497
+ type: string;
1498
+ /** Key-value attributes for the event. */
1499
+ attributes: {
1500
+ key: string;
1501
+ value: string;
1502
+ }[];
1503
+ }
1504
+ /** A single price level in the order book. */
1505
+ export interface OrderbookLevel {
1506
+ /** Price in micro-USDC (6 dp, e.g., 66752340000 = $66,752.34). */
1507
+ price: bigint;
1508
+ /** Total resting quantity at this level in contracts (integer lots). */
1509
+ totalQty: bigint;
1510
+ /** Number of resting orders at this level. */
1511
+ orderCount: number;
1512
+ }
1513
+ /** Aggregated order book snapshot for a market. */
1514
+ export interface Orderbook {
1515
+ /** Bid (buy) levels, sorted best (highest) first. */
1516
+ bids: OrderbookLevel[];
1517
+ /** Ask (sell) levels, sorted best (lowest) first. */
1518
+ asks: OrderbookLevel[];
1519
+ }
1520
+ /** A resting order on the book. Returned by `GET /v1/orders/{addr}`.
1521
+ * Wire shape: 6-tuple `[id, market, owner, side, price, quantity]`. */
1522
+ export interface OpenOrder {
1523
+ /** Engine-assigned order ID (monotonic within the market). */
1524
+ id: bigint;
1525
+ /** Market ID. */
1526
+ market: number;
1527
+ /** 20-byte owner address. */
1528
+ owner: Uint8Array;
1529
+ /** Order side. */
1530
+ side: "Buy" | "Sell";
1531
+ /** Limit price in micro-USDC. */
1532
+ price: bigint;
1533
+ /** Resting quantity in contracts. */
1534
+ quantity: bigint;
1535
+ }
1536
+ export type TriggerKind = "StopLoss" | "TakeProfit";
1537
+ export type TriggerLimbState = "Armed" | "Filled" | "Partial" | "NoFill" | "Rejected" | "Cancelled" | "Invalidated";
1538
+ export type TriggerOutcomeReason = "PositionClosed" | "PositionEpochChanged" | "PositionSideChanged" | "BelowMaintenance" | "IndeterminateAccount" | "MarketDisabled" | "MarkUnavailable" | "MarkStale" | "MarkFutureDated" | "NoEligibleLiquidity" | "SelfTradePrevention" | "WorkLimitReached" | "ExecutionRejected";
1539
+ /** Last deterministic evaluation of one stored trigger limb. */
1540
+ export interface TriggerEvaluation {
1541
+ height: bigint;
1542
+ frozenMark: bigint;
1543
+ limitPrice: bigint | null;
1544
+ requestedQuantity: bigint;
1545
+ filledQuantity: bigint;
1546
+ residualQuantity: bigint;
1547
+ reason: TriggerOutcomeReason | null;
1548
+ }
1549
+ /** Engine-owned state for one stop-loss/take-profit limb. */
1550
+ export interface StoredTriggerLimb {
1551
+ limbId: bigint;
1552
+ kind: TriggerKind;
1553
+ triggerPrice: bigint;
1554
+ maxSlippageBps: number;
1555
+ clientTriggerId: bigint | null;
1556
+ state: TriggerLimbState;
1557
+ lastEvaluation: TriggerEvaluation | null;
1558
+ }
1559
+ /** Effective trigger policy returned alongside each bracket. */
1560
+ export interface TriggerMarketConfig {
1561
+ version: bigint;
1562
+ enabled: boolean;
1563
+ maxTriggerSlippageBps: number;
1564
+ maxMarkAgeMs: bigint;
1565
+ maxFuturePublishSkewMs: bigint;
1566
+ maxActiveBrackets: bigint;
1567
+ }
1568
+ /** A governed trigger policy accepted in one block and effective next block. */
1569
+ export interface PendingTriggerMarketConfig {
1570
+ config: TriggerMarketConfig;
1571
+ acceptedHeight: bigint;
1572
+ effectiveHeight: bigint;
1573
+ }
1574
+ /** Current and scheduled policy for one trigger-enabled market. */
1575
+ export interface TriggerMarketConfigState {
1576
+ current: TriggerMarketConfig | null;
1577
+ pending: PendingTriggerMarketConfig | null;
1578
+ }
1579
+ /** One row returned by `GET /v1/triggers/markets`. */
1580
+ export interface TriggerMarketConfigInfo {
1581
+ market: number;
1582
+ state: TriggerMarketConfigState;
1583
+ }
1584
+ /** Why a stored bracket is or is not eligible at the finalized height. */
1585
+ export type TriggerEffectiveAvailability = {
1586
+ kind: "Available";
1587
+ } | {
1588
+ kind: "TriggerActionsInactive";
1589
+ } | {
1590
+ kind: "PendingActivation";
1591
+ } | {
1592
+ kind: "MigrationIncomplete";
1593
+ } | {
1594
+ kind: "ConfigurationMissing";
1595
+ } | {
1596
+ kind: "MarketDisabled";
1597
+ } | {
1598
+ kind: "Deferred";
1599
+ reason: TriggerOutcomeReason;
1600
+ };
1601
+ /** Current protected position generation and both optional limbs. */
1602
+ export interface PositionTriggerBracket {
1603
+ groupId: bigint;
1604
+ owner: Address;
1605
+ market: number;
1606
+ positionEpoch: bigint;
1607
+ positionSide: "Buy" | "Sell";
1608
+ acceptedHeight: bigint;
1609
+ activeFromHeight: bigint;
1610
+ clientGroupId: bigint | null;
1611
+ stopLoss: StoredTriggerLimb | null;
1612
+ takeProfit: StoredTriggerLimb | null;
1613
+ }
1614
+ /** One owner/market row returned by `GET /v1/triggers/{owner}`. */
1615
+ export interface PositionTriggerInfo {
1616
+ bracket: PositionTriggerBracket;
1617
+ marketConfig: TriggerMarketConfig | null;
1618
+ availability: TriggerEffectiveAvailability;
1619
+ }
1620
+ /** Next-height admission predicate returned by `GET /v1/triggers/status`. */
1621
+ export interface TriggerStatus {
1622
+ finalizedHeight: bigint;
1623
+ admissionHeight: bigint;
1624
+ actionsActive: boolean;
1625
+ }
1626
+ /** Time-window spelling accepted by the trigger-history indexer. */
1627
+ export type TriggerHistoryTime = string | number | bigint;
1628
+ /** Filters bound into an owner-history cursor. */
1629
+ export interface PositionTriggerHistoryFilters {
1630
+ market?: number;
1631
+ from?: TriggerHistoryTime;
1632
+ to?: TriggerHistoryTime;
1633
+ limit?: number;
1634
+ /** Opaque, non-empty token returned by the same filter set. */
1635
+ cursor?: string;
1636
+ }
1637
+ /** Filters bound into a shared market-history cursor. */
1638
+ export interface TriggerMarketHistoryFilters {
1639
+ from?: TriggerHistoryTime;
1640
+ to?: TriggerHistoryTime;
1641
+ limit?: number;
1642
+ /** Opaque, non-empty token returned by the same filter set. */
1643
+ cursor?: string;
1644
+ }
1645
+ export type PositionTriggerHistoryEventType = "position_triggers_set" | "position_triggers_cancelled" | "position_triggers_invalidated" | "position_trigger_activated" | "position_trigger_executed" | "position_trigger_deferred";
1646
+ export type TriggerMarketHistoryEventType = "trigger_market_deferred" | "trigger_market_resumed";
1647
+ export type TriggerHistoryEventType = PositionTriggerHistoryEventType | TriggerMarketHistoryEventType;
1648
+ /** Raw canonical engine attributes retained losslessly by the indexer. */
1649
+ export interface TriggerHistoryPayloadBase {
1650
+ readonly [key: string]: string;
1651
+ event_key: string;
1652
+ block_height: string;
1653
+ execution_ordinal: string;
1654
+ event_ordinal: string;
1655
+ market: string;
1656
+ }
1657
+ export interface OwnerTriggerHistoryPayloadBase extends TriggerHistoryPayloadBase {
1658
+ owner: string;
1659
+ position_epoch: string;
1660
+ group_id: string;
1661
+ }
1662
+ export interface PositionTriggersSetHistoryPayload extends OwnerTriggerHistoryPayloadBase {
1663
+ client_group_id: string;
1664
+ stop_limb_id: string;
1665
+ stop_client_trigger_id: string;
1666
+ take_profit_limb_id: string;
1667
+ take_profit_client_trigger_id: string;
1668
+ accepted_height: string;
1669
+ active_from_height: string;
1670
+ replaced_group_id: string;
1671
+ }
1672
+ export type PositionTriggersCancelledHistoryPayload = OwnerTriggerHistoryPayloadBase;
1673
+ export type PositionTriggersInvalidatedHistoryPayload = OwnerTriggerHistoryPayloadBase;
1674
+ export interface PositionTriggerActivatedHistoryPayload extends OwnerTriggerHistoryPayloadBase {
1675
+ limb_id: string;
1676
+ client_group_id: string;
1677
+ client_trigger_id: string;
1678
+ limb_kind: "stop_loss" | "take_profit";
1679
+ trigger_price: string;
1680
+ frozen_mark: string;
1681
+ limit_price: string;
1682
+ requested_quantity: string;
1683
+ execution_order_id: string;
1684
+ }
1685
+ export interface PositionTriggerExecutedHistoryPayload extends PositionTriggerActivatedHistoryPayload {
1686
+ filled_quantity: string;
1687
+ residual_quantity: string;
1688
+ /** Signed aggregate fee; kept as a decimal string. */
1689
+ total_fee: string;
1690
+ result: "filled" | "partial" | "no_fill" | "rejected" | "invalidated";
1691
+ /** Empty when the terminal outcome has no additional reason. */
1692
+ reason: string;
1693
+ }
1694
+ export interface PositionTriggerDeferredHistoryPayload extends OwnerTriggerHistoryPayloadBase {
1695
+ limb_id: string;
1696
+ client_group_id: string;
1697
+ client_trigger_id: string;
1698
+ limb_kind: "stop_loss" | "take_profit";
1699
+ trigger_price: string;
1700
+ frozen_mark: string;
1701
+ requested_quantity: string;
1702
+ reason: string;
1703
+ }
1704
+ export interface TriggerMarketDeferredHistoryPayload extends TriggerHistoryPayloadBase {
1705
+ reason: string;
1706
+ }
1707
+ export interface TriggerMarketResumedHistoryPayload extends TriggerHistoryPayloadBase {
1708
+ previous_reason: string;
1709
+ }
1710
+ /** One immutable chain-coordinate-keyed trigger history event. */
1711
+ export interface TriggerHistoryEvent<TType extends TriggerHistoryEventType, TOwner extends string | null, TPayload extends TriggerHistoryPayloadBase> {
1712
+ eventKey: string;
1713
+ blockHeight: string;
1714
+ executionOrdinal: string;
1715
+ eventOrdinal: string;
1716
+ blockTime: string;
1717
+ eventType: TType;
1718
+ owner: TOwner;
1719
+ market: string;
1720
+ payload: TPayload;
1721
+ }
1722
+ export type PositionTriggerHistoryEvent = TriggerHistoryEvent<"position_triggers_set", string, PositionTriggersSetHistoryPayload> | TriggerHistoryEvent<"position_triggers_cancelled", string, PositionTriggersCancelledHistoryPayload> | TriggerHistoryEvent<"position_triggers_invalidated", string, PositionTriggersInvalidatedHistoryPayload> | TriggerHistoryEvent<"position_trigger_activated", string, PositionTriggerActivatedHistoryPayload> | TriggerHistoryEvent<"position_trigger_executed", string, PositionTriggerExecutedHistoryPayload> | TriggerHistoryEvent<"position_trigger_deferred", string, PositionTriggerDeferredHistoryPayload>;
1723
+ export type TriggerMarketHistoryEvent = TriggerHistoryEvent<"trigger_market_deferred", null, TriggerMarketDeferredHistoryPayload> | TriggerHistoryEvent<"trigger_market_resumed", null, TriggerMarketResumedHistoryPayload>;
1724
+ export interface PositionTriggerHistoryPage {
1725
+ triggerEvents: PositionTriggerHistoryEvent[];
1726
+ /** Empty when exhausted; otherwise pass back unchanged. */
1727
+ nextCursor: string;
1728
+ }
1729
+ export interface TriggerMarketHistoryPage {
1730
+ triggerMarketEvents: TriggerMarketHistoryEvent[];
1731
+ /** Empty when exhausted; otherwise pass back unchanged. */
1732
+ nextCursor: string;
1733
+ }
1734
+ /** One row of the auto-deleveraging queue for a market. Returned sorted by
1735
+ * `adlScore` desc (front of the queue first). Decoded from the msgpack
1736
+ * 6-tuple `[owner, market, side, size, upnlNow, adlScore]`. Endpoint:
1737
+ * `GET /v1/adl/queue/{market}`. */
1738
+ export interface AdlQueueEntry {
1739
+ /** 20-byte owner address. */
1740
+ owner: Uint8Array;
1741
+ market: number;
1742
+ /** Position side: "Buy" = long, "Sell" = short. */
1743
+ side: "Buy" | "Sell";
1744
+ /** Position size in contracts. */
1745
+ size: bigint;
1746
+ /** Unrealized PnL at the current mark, signed. Always positive here
1747
+ * (only profitable positions are queued). */
1748
+ upnlNow: bigint;
1749
+ /** `max(0, upnlNow) × leverage_bps`. Higher = closer to the front of the
1750
+ * ADL queue. */
1751
+ adlScore: bigint;
1752
+ }
1753
+ /** One-round-trip market summary. Returned by `GET /v1/ticker/{market}`. */
1754
+ export interface Ticker {
1755
+ /** Market id as decimal string. */
1756
+ market: string;
1757
+ /** Last fill price in the 24h window (empty/"0" if no trades). */
1758
+ lastPrice: string;
1759
+ /** Σ quantity across the 24h window (integer contracts). */
1760
+ volume24hContracts: string;
1761
+ /** Signed 24h change in basis points. Empty/"0" if no trades. */
1762
+ change24hBps: string;
1763
+ /** Base64 msgpack FundingInfo (mark EWMA, oracle, funding rate, interval). */
1764
+ fundingMsgpackB64: string;
1765
+ /** Base64 msgpack OrderbookSnapshot at depth=1. Empty for fresh markets. */
1766
+ orderbookMsgpackB64: string;
1767
+ /** Null today — the engine doesn't track open interest yet. */
1768
+ openInterest: string | null;
1769
+ }
1770
+ /** Information about a single open position.
1771
+ *
1772
+ * Fields 0-5 are the raw `Position` state; fields 6-11 (the "now"/
1773
+ * "if_fires"/"if_dies"/"since" fields) are response-only enrichments
1774
+ * computed by `query_account` in the node. Indices are stable with
1775
+ * the msgpack wire tuple returned by `/v1/account/{address}` — older
1776
+ * SDK versions that only read indices 0-5 continue to work; indices
1777
+ * 6+ are undefined on older responses (gateway returns them as of
1778
+ * commit `[Sprint 1 Day 1]` / 2026-04-24).
1779
+ */
1780
+ export interface PositionInfo {
1781
+ /** [0] Owner address (20 bytes). */
1782
+ owner: Uint8Array;
1783
+ /** [1] Market identifier. */
1784
+ market: number;
1785
+ /** [2] Position side: "Buy" (long) or "Sell" (short). */
1786
+ side: "Buy" | "Sell";
1787
+ /** [3] Weighted-average entry price in micro-USDC (6 dp). */
1788
+ entryPrice: bigint;
1789
+ /** [4] Absolute position size in contracts (integer lots). */
1790
+ size: bigint;
1791
+ /** [5] Cumulative funding index at the time the position was last settled. */
1792
+ lastFundingIndex: bigint;
1793
+ /** [6] Unrealized P&L at the current mark, unconditional. Perp + CP use
1794
+ * the oracle as the current mark; binaries return 0 (no deterministic
1795
+ * current mark — use pnlIfFires/pnlIfDies for binary payoffs). */
1796
+ upnlNow?: bigint;
1797
+ /** [7] Maintenance margin this position contributes when its firing
1798
+ * branch is active. For Perp = always; for CP/Binary = zero under
1799
+ * the non-firing branch. */
1800
+ mmNow?: bigint;
1801
+ /** [8] Initial margin contribution, same semantics as mmNow. */
1802
+ imNow?: bigint;
1803
+ /** [9] Position value if its branch fires (μ = 1):
1804
+ * `sign(side) × (settle × size − entry × size)`
1805
+ * Perp always fires. CP fires when event resolves to its branch.
1806
+ * Binary fires + settles to BINARY_PRICE_MAX × size. */
1807
+ pnlIfFires?: bigint;
1808
+ /** [10] Position value if its branch does NOT fire (μ = 0):
1809
+ * `sign(side) × (0 − entry × size)`
1810
+ * Perp: equal to upnlNow (perps never die; reported for UI column
1811
+ * symmetry). CP/Binary: the non-firing payoff. */
1812
+ pnlIfDies?: bigint;
1813
+ /** [11] Funding accrued since the position's last settled funding index.
1814
+ * Positive = credit, negative = debit.
1815
+ * `-sign(side) × (cumulative − lastFundingIndex) × size / FUNDING_SCALE`
1816
+ */
1817
+ fundingSince?: bigint;
1818
+ /** [12] ADL queue score: `max(0, upnlNow) × leverage_used`. Higher
1819
+ * = closer to the front of the auto-deleveraging queue (Tier 3 of
1820
+ * the bad-debt waterfall). Only profitable positions have a
1821
+ * non-zero score; losers are liquidated long before they're at
1822
+ * risk of being ADL'd.
1823
+ *
1824
+ * Formula: `(positiveUpnl × notional × 10_000) / imNow`, with the
1825
+ * 10_000 factor expressing leverage in basis points so the product
1826
+ * fits in i64 cleanly. Returned as 0 for losing or non-firing
1827
+ * positions.
1828
+ *
1829
+ * UIs should rank positions by `adlScore` desc to compute a
1830
+ * per-market percentile and warn at >90th percentile (the v3
1831
+ * design-doc threshold). Added 2026-04-25. */
1832
+ adlScore?: bigint;
1833
+ /** [13] Persistent generation of this live position. This is the only
1834
+ * canonical first-attach input for `SetPositionTriggers`; absent means the
1835
+ * bounded legacy backfill has not reached this row and callers must refuse
1836
+ * trigger placement rather than guess `1`. */
1837
+ positionEpoch?: bigint;
1838
+ }
1839
+ /** One entry per active impact market the account touches. Tuple of
1840
+ * (impactMarketId, branch) where branch is "Yes" or "No". Ordering is
1841
+ * ascending by impactMarketId (deterministic across nodes).
1842
+ *
1843
+ * See AccountInfo.bindingScenario for semantics. */
1844
+ export interface BindingScenarioEntry {
1845
+ impactMarketId: number;
1846
+ branch: "Yes" | "No";
1847
+ }
1848
+ /** One row of the per-user deposit/withdraw cash-flow log. Covers four
1849
+ * event kinds — see the `kind` field. Feeds the Portfolio EquityChart
1850
+ * "equity over time" reconstruction (Jesse's P2 #6).
1851
+ *
1852
+ * Returned by `GET /v1/history/deposits/{address}` and `GET
1853
+ * /v1/history/withdrawals/{address}`, and by the `historyDeposits` /
1854
+ * `historyWithdrawals` InfoRequests. Shipped 2026-04-24. */
1855
+ export interface HistoryCashFlow {
1856
+ /** One of the four Rust event kinds. */
1857
+ kind: "deposit_confirmed" | "withdraw_requested" | "withdrawal_confirmed" | "withdrawal_failed";
1858
+ /** 20-byte owner address as hex. */
1859
+ owner: string;
1860
+ /** Amount in µUSDC (always positive). Use `signedDelta` for signed
1861
+ * balance-change reconstruction. May be empty for
1862
+ * `withdrawal_confirmed` (engine doesn't emit amount on ack). */
1863
+ amount: string;
1864
+ /** Signed balance delta for this event:
1865
+ * +amount for deposit_confirmed + withdrawal_failed (credit)
1866
+ * -amount for withdraw_requested (debit)
1867
+ * "0" for withdrawal_confirmed (no change) */
1868
+ signedDelta: string;
1869
+ /** Post-event balance. Available for deposit/request/failed;
1870
+ * empty for confirmed (no balance change on that event). */
1871
+ newBalance: string;
1872
+ /** Present on withdrawal events (request, confirmed, failed). */
1873
+ withdrawalId: string;
1874
+ /** Present on deposit_confirmed + withdrawal_confirmed. */
1875
+ solanaTxSig: string;
1876
+ /** Present on withdraw_requested only. */
1877
+ solanaDestination: string;
1878
+ /** Present on withdrawal_failed only. */
1879
+ reason: string;
1880
+ /** Block height at which the event landed. */
1881
+ blockHeight: number;
1882
+ /** Unix milliseconds. */
1883
+ timestamp: number;
1884
+ }
1885
+ /** One row of the per-user position-at-resolution log. Covers three
1886
+ * kinds — see `kind` field. Feeds Portfolio Resolved tab + Impact /
1887
+ * Prediction resolved-state "your outcome" block.
1888
+ *
1889
+ * Returned by `GET /v1/history/resolutions/{address}` and the
1890
+ * `historyResolutions` InfoRequest. Shipped 2026-04-24 (see Jesse's
1891
+ * P2 #7 in docs/api-scope.md). */
1892
+ export interface HistoryResolution {
1893
+ /** One of "conditional_settled" | "conditional_voided" | "prediction_settled". */
1894
+ kind: "conditional_settled" | "conditional_voided" | "prediction_settled";
1895
+ /** Impact-market family ID the resolved position belonged to. */
1896
+ impactMarketId: string;
1897
+ /** Child market ID (CPY/CPN or EBY/EBN). */
1898
+ market: string;
1899
+ /** 20-byte owner address as hex. */
1900
+ owner: string;
1901
+ /** Position side at resolution: "Buy" = long, "Sell" = short. */
1902
+ side: string;
1903
+ /** Position size at resolution, integer lots. String to preserve BIGINT. */
1904
+ size: string;
1905
+ /** Weighted-average entry price of the resolved position. */
1906
+ entryPrice: string;
1907
+ /** Settlement price. conditional_settled → mark_price;
1908
+ * prediction_settled → payoff_per_share (BINARY_PRICE_MAX winner, 0 loser);
1909
+ * conditional_voided → "" (no mark; void path returns margin, no cash movement). */
1910
+ settlementPrice: string;
1911
+ /** Signed realized PnL in µUSDC. conditional_voided → "0". */
1912
+ realizedPnl: string;
1913
+ /** Block height at which the resolution landed. */
1914
+ blockHeight: number;
1915
+ /** Unix milliseconds. */
1916
+ timestamp: number;
1917
+ }
1918
+ /** One row of the per-user position-history snapshot log. Each entry is
1919
+ * a point-in-time snapshot of a position written after each fill that
1920
+ * changes its state (open → grow → reduce → close). When `size` is "0"
1921
+ * the snapshot represents a CLOSE event; the immediately preceding
1922
+ * non-zero snapshot for the same `(owner, market, side)` carries the
1923
+ * weighted-average entry price.
1924
+ *
1925
+ * Returned by `GET /v1/history/positions/{address}` and the
1926
+ * `historyPositions` InfoRequest. The HTTP endpoint accepts optional
1927
+ * `?market=&from=&to=&limit=` filters; results are newest-first. */
1928
+ export interface HistoryPositionSnapshot {
1929
+ /** 20-byte owner address as hex. */
1930
+ owner: string;
1931
+ /** Market ID as a decimal string. */
1932
+ market: string;
1933
+ /** Position side: "Buy" = long, "Sell" = short. */
1934
+ side: string;
1935
+ /** Weighted-average entry price in µUSDC at the time of the snapshot. */
1936
+ entryPrice: string;
1937
+ /** Absolute position size in contracts. "0" = closed. */
1938
+ size: string;
1939
+ /** Block height at which the snapshot landed. */
1940
+ blockHeight: number;
1941
+ /** Unix milliseconds. */
1942
+ timestamp: number;
1943
+ }
1944
+ /** One executed fill from `/v1/history/fills/{owner}` (or `/v1/fills`). */
1945
+ export interface HistoryFill {
1946
+ /** Unsigned 64-bit fill identifier as a decimal string. NOTE: the indexer
1947
+ * currently emits it as a JSON number, so values beyond 2^53 would already
1948
+ * be rounded by JSON.parse before this client sees them — the string shape
1949
+ * here avoids adding a second rounding and is ready for a server-side
1950
+ * string cast (the same treatment price already gets). */
1951
+ fillId: string;
1952
+ market: number;
1953
+ blockHeight: number;
1954
+ /** RFC 3339 with nanoseconds, exactly as the indexer renders it. */
1955
+ blockTime: string;
1956
+ /** Price in µUSDC as a decimal string — never a float. */
1957
+ price: string;
1958
+ /** Quantity in contracts as a decimal string — never a float. */
1959
+ quantity: string;
1960
+ /** 20-byte maker address as hex. */
1961
+ makerOwner: string;
1962
+ /** 20-byte taker address as hex. */
1963
+ takerOwner: string;
1964
+ /** The maker's side: "Buy" or "Sell"; the taker took the other side. */
1965
+ makerSide: string;
1966
+ takerFee: number;
1967
+ makerFee: number;
1968
+ }
1969
+ /** One page of fills, newest first. An empty `nextCursor` means last page. */
1970
+ export interface HistoryFillsPage {
1971
+ fills: HistoryFill[];
1972
+ nextCursor: string;
1973
+ }
1974
+ /** Full account information including balance, positions, and margin state. */
1975
+ export interface AccountInfo {
1976
+ /** [0] Available USDC balance in microUSDC (6 dp, e.g., 100_000_000_000 = $100,000). */
1977
+ balance: bigint;
1978
+ /** [1] Open positions for this account. */
1979
+ positions: PositionInfo[];
1980
+ /** [2] Total equity (balance + unrealized PnL) in microUSDC (6 dp).
1981
+ * Scenario-aware: worst-case equity across all resolution outcomes. */
1982
+ equity: bigint;
1983
+ /** [3] Total maintenance margin requirement in microUSDC (6 dp).
1984
+ * Scenario-aware: max MM across all resolution outcomes. */
1985
+ totalMm: bigint;
1986
+ /** [4] Total initial margin requirement in microUSDC (6 dp). */
1987
+ totalIm: bigint;
1988
+ /** [5] Margin ratio in basis points (equity / total notional * 10000). */
1989
+ marginRatioBps: bigint;
1990
+ /** [6] Resolution scenario that maximizes totalMm — the "binding" outcome.
1991
+ * One entry per active impact market, ascending by impactMarketId.
1992
+ * Empty for perp-only accounts. Undefined on responses from gateways
1993
+ * older than 2026-04-24 (backward compat — the SDK decoder reads
1994
+ * msgpack arrays by index). See Jesse's P1 #3 in docs/api-scope.md. */
1995
+ bindingScenario?: BindingScenarioEntry[];
1996
+ /** [7] Cumulative trading fees paid (positive) or rebates received
1997
+ * (negative) by this account, in microUSDC. Updated atomically with
1998
+ * the fee debit at fill time. Powers the "lifetime trading cost"
1999
+ * line on the UI. New accounts read 0. Undefined on responses from
2000
+ * gateways predating 2026-05-03. BE-45. */
2001
+ feesAccrued?: bigint;
2002
+ /** [8] Rolling 30-day taker volume in microUSDC at the account's last
2003
+ * volume update. This is the value the engine uses to select market
2004
+ * fee tiers before the next fill. Undefined on older gateways. */
2005
+ volume30dMicroUsdc?: bigint;
2006
+ }
2007
+ /** Market kind discriminator. Wire shape mirrors the Rust `MarketKind`
2008
+ * enum exactly: `"Perp"` is a bare string, the parameterised variants
2009
+ * are `{ ConditionalPerp: [impactId, branch] }` /
2010
+ * `{ PredictionBinary: [impactId, branch] }`. */
2011
+ export type MarketKind = "Perp" | {
2012
+ ConditionalPerp: [number, "Yes" | "No"];
2013
+ } | {
2014
+ PredictionBinary: [number, "Yes" | "No"];
2015
+ };
2016
+ /** Mark-price source mode. Mirrors the engine's `MarkSourceMode` enum. */
2017
+ export type MarkSourceMode = "OracleOnly" | "Median";
2018
+ /** Configuration for a perpetual / conditional / binary market. The wire
2019
+ * form is a MessagePack positional array; indices mirror the Rust struct
2020
+ * field order in exchange-core/src/types.rs.
2021
+ * Fields after index 7 use `#[serde(default)]` so older on-chain records
2022
+ * decode cleanly. */
2023
+ export interface MarketConfig {
2024
+ /** [0] Market identifier (unique integer). */
2025
+ market: number;
2026
+ /** [1] Initial margin requirement in basis points (e.g., 1000 = 10% = 10x max leverage). */
2027
+ imBps: number;
2028
+ /** [2] Maintenance margin requirement in basis points (e.g., 500 = 5%). */
2029
+ mmBps: number;
2030
+ /** [3] Taker fee rate in basis points (e.g., 5 = 0.05%). */
2031
+ takerFeeBps: number;
2032
+ /** [4] Maker fee rate in basis points (e.g., 2 = 0.02%). */
2033
+ makerFeeBps: number;
2034
+ /** [5] Funding interval in milliseconds (0 = funding disabled). */
2035
+ fundingIntervalMs: bigint;
2036
+ /** [6] Maximum absolute funding rate per interval in basis points. */
2037
+ maxFundingRateBps: number;
2038
+ /** [7] Market kind. Defaults to `"Perp"` for legacy records lacking this field. */
2039
+ kind?: MarketKind;
2040
+ /** [8] Per-account absolute position cap in contracts. 0 = no limit. */
2041
+ maxPositionSize?: bigint;
2042
+ /** [9] Default order TTL in ms. 0 = no TTL. */
2043
+ defaultTtlMs?: bigint;
2044
+ /** [10] Net-delta portfolio margin opt-in. */
2045
+ netDeltaMargin?: boolean;
2046
+ /** [11] Insurance-fund pool ID. Markets in different pools are insulated
2047
+ * from each other's liquidation cascades. 0 = shared default pool. */
2048
+ poolId?: number;
2049
+ /** [12] Max oracle age (ms) before the engine refuses to read it. 0 = no check. */
2050
+ markPriceMaxOracleAgeMs?: bigint;
2051
+ /** [13] Volume-based fee tier table. Empty = flat taker/maker fees. */
2052
+ feeTiers?: FeeTier[];
2053
+ /** [14] Tick size in micro-USDC. 0 = no tick gate. */
2054
+ tickSize?: bigint;
2055
+ /** [15] Lot size in contracts. 0 = no lot gate. */
2056
+ lotSize?: bigint;
2057
+ /** [16] Primary oracle signer address (20 bytes). */
2058
+ primaryOracleSigner?: Address;
2059
+ /** [17] Oracle staleness window (ms) before fallback signers may publish. 0 = disabled. */
2060
+ oracleStalenessMs?: bigint;
2061
+ /** [18] Mark-price source mode. */
2062
+ markSourceMode?: MarkSourceMode;
2063
+ /** [19] Top-of-book spread cap (bps) for thin-book guard on Median mode. */
2064
+ maxMarkSpreadBps?: number;
2065
+ /** [20] Max age (ms) for composite-CEX price in Median mode. */
2066
+ cexCompositeStalenessMs?: bigint;
2067
+ /** [21] Enable partial liquidation (close per-market rather than all-or-nothing). */
2068
+ partialLiquidationEnabled?: boolean;
2069
+ /** [22] Published size scale: quantity is in units of 10^-szDecimals. */
2070
+ szDecimals?: number;
2071
+ /** [23] Human-readable ticker / short symbol (e.g. "BTC"). */
2072
+ ticker?: string;
2073
+ /** [24] Aggregate market open-interest cap in contracts. 0 = no cap. */
2074
+ maxOpenInterest?: bigint;
2075
+ }
2076
+ /** Per-tier fee schedule for the BE-47 volume-based maker-rebate program. */
2077
+ export interface FeeTier {
2078
+ /** [0] Minimum 30-day rolling taker volume in micro-USDC. */
2079
+ min30dVolumeMicroUsdc: bigint;
2080
+ /** [1] Maker fee in tenth-basis-points. Negative = maker rebate. */
2081
+ makerFeeTenthBps: number;
2082
+ /** [2] Taker fee in tenth-basis-points. */
2083
+ takerFeeTenthBps: number;
2084
+ }
2085
+ //# sourceMappingURL=types.d.ts.map