@stryke-xyz/premarket-sdk 1.0.7 → 1.0.8

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.
package/README.md CHANGED
@@ -1,82 +1,27 @@
1
1
  # premarket-sdk
2
2
 
3
- TypeScript SDK for Stryke premarket integrations across:
3
+ TypeScript SDK for Stryke premarket integrations across onchain contracts,
4
+ backend APIs, and frontend runtimes.
4
5
 
5
- - `option-markets` contracts (`Exchange`, `MarketsRegistry`, `OptionMarketVault`)
6
- - `smart-account` contracts (`SimpleAccountFactory`, `EntryPoint`)
7
- - `premarkets-api` HTTP and WebSocket services
8
- - `premarkets-interface` frontend runtime
6
+ The package brings together:
9
7
 
10
- This package is the shared integration layer between onchain contracts and the
11
- application stack. It gives product teams one place to build orders, hash and
12
- sign typed data, encode contract calls, read market and user data, subscribe to
13
- live updates, and consume deployment constants.
8
+ - native `Exchange` order building, hashing, signing, math, and calldata
9
+ - `OptionMarketVault` token-id helpers, collateral math, and tx builders
10
+ - `MarketsRegistry` market serialization and admin calldata builders
11
+ - `OrderHelper` and `OrderbookApi` for application-facing integrations
12
+ - realtime sync clients for market depth and activity streams
13
+ - chain metadata, deployed addresses, and token constants
14
+ - smart-account derivation and deployment helpers
15
+ - shared transport DTOs for API and UI consumers
14
16
 
15
- ## What This Package Provides
17
+ ## Install
16
18
 
17
- - native `Exchange` order builders, hashing, typed-data signing helpers, and
18
- calldata builders
19
- - `OptionMarketVault` token-id helpers, collateral math, and transaction
20
- builders
21
- - `MarketsRegistry` market serialization and contract calldata builders
22
- - `OrderHelper` and `OrderbookApi` for backend and frontend integrations
23
- - realtime sync clients for market depth and activity streams
24
- - chain definitions, token metadata, and deployed contract addresses
25
- - smart-account address derivation and deployment checks
26
- - shared DTOs used by HTTP clients and frontend consumers
27
-
28
- ## Documentation Map
29
-
30
- The new documentation set lives alongside the legacy docs during migration.
31
- Start here, then drill into the module guide that matches the surface you are
32
- integrating.
33
-
34
- ### Module guides
35
-
36
- - [Exchange guide](./src/exchange/README.md)
37
- - [Vault guide](./src/vault/README.md)
38
- - [Registry guide](./src/registry/README.md)
39
- - [API guide](./src/api/README.md)
40
- - [Sync guide](./src/sync/README.md)
41
- - [Config guide](./src/config/README.md)
42
- - [Shared types guide](./src/shared/README.md)
43
- - [Utilities guide](./src/utils/README.md)
44
-
45
- ### Root-level exports
46
-
47
- The package root also exports a handful of single-file helpers that do not live
48
- under one directory package:
49
-
50
- - `smart-account`
51
- - Source: [`src/smart-account.ts`](./src/smart-account.ts)
52
- - Public surfaces: `SmartAccountHelper`, `getCurrentSalt`,
53
- `getSmartAccountAddress`, `getAccountCount`,
54
- `isSmartAccountDeployed`, `getCurrentSmartAccount`,
55
- `SmartAccountConfig`, `SmartAccountResult`
56
- - `address`
57
- - Source: [`src/address.ts`](./src/address.ts)
58
- - Public surface: `Address`
59
- - `bps`
60
- - Source: [`src/bps.ts`](./src/bps.ts)
61
- - Public surface: `Bps`
62
- - compatibility and address helpers
63
- - Source: [`src/constants.ts`](./src/constants.ts)
64
- - Public surfaces: `ZX`, `getExchangeContract`,
65
- `getLimitOrderContract`, `getMarketsRegistryContract`,
66
- `getNativeOrderFactoryContract`, `getNativeOrderImplContract`
67
- - generic utilities
68
- - Source: [`src/utils/mul-div.ts`](./src/utils/mul-div.ts),
69
- [`src/utils/rand-bigint.ts`](./src/utils/rand-bigint.ts),
70
- [`src/utils/orderUtils.ts`](./src/utils/orderUtils.ts)
71
- - Public surfaces: `mulDiv`, `Rounding`, `randBigInt`,
72
- `optionPrmToPrmTokenId`, `prmToOptionPrmTokenId`,
73
- `isComplementaryOptionTokenPair`, `verifyOrderSignature`
19
+ ```bash
20
+ bun add @stryke-xyz/premarket-sdk
21
+ ```
74
22
 
75
23
  ## Quick Start
76
24
 
77
- The SDK is designed so an integrator can stay inside the package root for most
78
- common workflows.
79
-
80
25
  ```ts
81
26
  import {
82
27
  EXCHANGE,
@@ -106,23 +51,815 @@ const order = helper.buildOrder({
106
51
  tokenId: 42n,
107
52
  });
108
53
 
54
+ const signature = await helper.signEip712Order(order, walletClient);
109
55
  const payload = helper.serializeOrder(order);
110
56
 
111
57
  const api = new OrderbookApi({ baseUrl: "https://example.stryke.xyz" });
112
- await api.queryOrders({ marketId: payload.marketId });
58
+ await api.createOrder(
59
+ {
60
+ marketId: payload.marketId,
61
+ order: payload,
62
+ signature,
63
+ timeInForce: "GTC",
64
+ postOnly: false,
65
+ },
66
+ bearerToken,
67
+ );
68
+ ```
69
+
70
+ ## Source Layout
71
+
72
+ - `src/exchange`: native order model, EIP-712 helpers, order math, and exchange
73
+ calldata builders
74
+ - `src/api`: `OrderHelper`, `OrderbookApi`, and response deserializers
75
+ - `src/vault`: token-id derivation, collateral math, and vault tx builders
76
+ - `src/registry`: market serialization and registry calldata builders
77
+ - `src/sync`: realtime depth and activity clients
78
+ - `src/config`: supported chains, token metadata, and deployed addresses
79
+ - `src/shared`: transport DTOs shared across SDK, API, and UI
80
+ - `src/utils`: reusable math, randomness, token-pair, and signature helpers
81
+ - `src/smart-account.ts`: deterministic smart-account helpers
82
+ - `src/address.ts`: address convenience wrapper
83
+ - `src/bps.ts`: basis-point helper wrapper
84
+ - `src/constants.ts`: compatibility address helpers
85
+
86
+ ## Exchange Module
87
+
88
+ Source files:
89
+
90
+ - `src/exchange/index.ts`
91
+ - `src/exchange/types.ts`
92
+ - `src/exchange/order.ts`
93
+ - `src/exchange/eip712.ts`
94
+ - `src/exchange/math.ts`
95
+ - `src/exchange/exchange-contract.ts`
96
+ - `src/exchange/errors.ts`
97
+
98
+ This is the trading core of the SDK. It models Stryke's native order format,
99
+ mirrors the contract's EIP-712 schema, reproduces key fee and crossing math,
100
+ and encodes calldata for fills, matches, cancellation, and batching.
101
+
102
+ ### Core order model
103
+
104
+ The canonical in-memory type is `ExchangeOrder`, where numeric fields are
105
+ stored as `bigint`.
106
+
107
+ ```ts
108
+ export interface ExchangeOrder {
109
+ salt: bigint;
110
+ nonce: bigint;
111
+ marketId: bigint;
112
+ makingAmount: bigint;
113
+ takingAmount: bigint;
114
+ deadline: bigint;
115
+ maker: Address;
116
+ receiver: Address;
117
+ tradeType: TradeType;
118
+ signatureType: SignatureType;
119
+ tokenId: bigint;
120
+ }
121
+ ```
122
+
123
+ Related public types:
124
+
125
+ - `TradeType`: `BUY = 0`, `SELL = 1`
126
+ - `SignatureType`: `EIP712 = 0`, `ERC1271 = 1`
127
+ - `SerializedExchangeOrder`
128
+ - `ExchangeOrderStatus`
129
+ - `SerializedExchangeOrderStatus`
130
+ - `MulticallResult`
131
+
132
+ ### Order building and validation
133
+
134
+ Public helpers:
135
+
136
+ - `buildExchangeOrder(params)`
137
+ - `validateExchangeOrder(order)`
138
+ - `isOrderExpired(order, nowSec?)`
139
+ - `getExecutableMakingAmount(order, status)`
140
+ - `getExchangeOrderHash(order, chainId, exchangeAddress)`
141
+
142
+ Builder behavior:
143
+
144
+ - `salt` defaults to a random 96-bit-compatible value
145
+ - `receiver` defaults to `maker`
146
+ - `signatureType` defaults to `SignatureType.EIP712`
147
+ - `makingAmount`, `takingAmount`, and `deadline` must be positive
148
+
149
+ ```ts
150
+ import {
151
+ SignatureType,
152
+ TradeType,
153
+ buildExchangeOrder,
154
+ } from "@stryke-xyz/premarket-sdk";
155
+
156
+ const order = buildExchangeOrder({
157
+ maker: "0x1111111111111111111111111111111111111111",
158
+ nonce: 12n,
159
+ marketId: 7n,
160
+ makingAmount: 1_000_000n,
161
+ takingAmount: 500_000n,
162
+ deadline: 1_900_000_000n,
163
+ tradeType: TradeType.SELL,
164
+ signatureType: SignatureType.EIP712,
165
+ tokenId: 123456n,
166
+ });
167
+ ```
168
+
169
+ ### Signing and hashing
170
+
171
+ Important constants:
172
+
173
+ - `EXCHANGE_EIP712_NAME = "Exchange"`
174
+ - `EXCHANGE_EIP712_VERSION = "1"`
175
+ - `EXCHANGE_ORDER_TYPES`
176
+
177
+ Public helpers:
178
+
179
+ - `getExchangeDomain(chainId, verifyingContract)`
180
+ - `getExchangeTypedData(order, chainId, verifyingContract)`
181
+ - `hashExchangeOrder(order, chainId, verifyingContract)`
182
+ - `recoverExchangeOrderSigner(order, signature, chainId, verifyingContract)`
183
+
184
+ These helpers should be used anywhere exact onchain signature parity matters.
185
+
186
+ ### Serialization helpers
187
+
188
+ Public helpers:
189
+
190
+ - `serializeExchangeOrder(order)`
191
+ - `deserializeExchangeOrder(order)`
192
+ - `serializeOrderStatus(status)`
193
+ - `deserializeOrderStatus(status)`
194
+
195
+ Use these when moving between bigint-based local models and JSON-safe payloads.
196
+
197
+ ### Math helpers
198
+
199
+ Public constants:
200
+
201
+ - `EXCHANGE_ONE = 10n ** 18n`
202
+ - `FEE_RATE_BASE = 1_000_000n`
203
+
204
+ Public functions:
205
+
206
+ - `getTakingAmount(fillMakingAmount, orderMakingAmount, orderTakingAmount)`
207
+ - `getMakingAmount(fillTakingAmount, orderMakingAmount, orderTakingAmount)`
208
+ - `calculateFee(grossAmount, feeRate)`
209
+ - `applyFee(grossAmount, feeRate)`
210
+ - `getOrderPriceWad(order)`
211
+ - `optionPrmToPrmId(tokenId)`
212
+ - `isCrossing(orderA, orderB)`
213
+ - `hasValidTokenPairForMatch(orderA, orderB)`
214
+
215
+ ### Calldata builders
216
+
217
+ `ExchangeContract` wraps the shipped ABI and returns either raw calldata or a
218
+ lightweight transaction envelope.
219
+
220
+ Public methods:
221
+
222
+ - `getFillOrderCalldata(order, fillAmount, signature)`
223
+ - `buildFillOrderTx(order, fillAmount, signature)`
224
+ - `getMatchOrderCalldata(takerOrder, takerSignature, makerOrder, makerSignature, takerFillAmount, makerFillAmount)`
225
+ - `buildMatchOrderTx(takerOrder, takerSignature, makerOrder, makerSignature, takerFillAmount, makerFillAmount)`
226
+ - `getCancelOrderCalldata(order)`
227
+ - `getIncrementNonceCalldata()`
228
+ - `getSetResolverWhitelistCalldata(resolver, isWhitelisted)`
229
+ - `getSetFeeReceiverCalldata(newFeeReceiver)`
230
+ - `getPauseCalldata()`
231
+ - `getUnpauseCalldata()`
232
+ - `getMulticallCalldata(data, allowFailure?)`
233
+
234
+ `buildFillOrderTx` and `buildMatchOrderTx` return `{ to, data, value }`.
235
+ The remaining helpers return calldata only.
236
+
237
+ Restricted or admin-oriented surfaces:
238
+
239
+ - `getSetResolverWhitelistCalldata`
240
+ - `getSetFeeReceiverCalldata`
241
+ - `getPauseCalldata`
242
+ - `getUnpauseCalldata`
243
+
244
+ ### Error decoding
245
+
246
+ `decodeContractError` attempts to decode revert payloads against the shipped
247
+ `Exchange`, `OptionMarketVault`, and `MarketsRegistry` ABIs.
248
+
249
+ It returns either `null` or:
250
+
251
+ ```ts
252
+ interface DecodedContractError {
253
+ contract: "exchange" | "optionMarketVault" | "marketsRegistry";
254
+ name: string;
255
+ signature: string;
256
+ args: readonly unknown[];
257
+ }
258
+ ```
259
+
260
+ ## API Module
261
+
262
+ Source files:
263
+
264
+ - `src/api/index.ts`
265
+ - `src/api/order-helper.ts`
266
+ - `src/api/orderbook-api/index.ts`
267
+ - `src/api/orderbook-api/deserializers.ts`
268
+ - `src/shared/types.ts`
269
+
270
+ This module gives most applications the two highest-level integration surfaces:
271
+ `OrderHelper` for working with orders and `OrderbookApi` for HTTP reads and
272
+ writes.
273
+
274
+ ### OrderHelper
275
+
276
+ `OrderHelper` exists so consumers do not need to manually stitch together order
277
+ building, hashing, typed-data generation, signing, and serialization.
278
+
279
+ Constructor config:
280
+
281
+ - `chainId`
282
+ - `exchangeAddress`
283
+
284
+ Public methods:
285
+
286
+ - `buildOrder(params)`
287
+ - `buildSellOrder(params)`
288
+ - `buildBuyOrder(params)`
289
+ - `serializeOrder(order)`
290
+ - `hashOrder(order)`
291
+ - `getTypedData(order)`
292
+ - `signEip712Order(order, walletClient)`
293
+ - `signSimpleAccountOrder(order, ownerWalletClient)`
294
+ - `signOrder(order, walletClient)`
295
+ - `recoverOrderSigner(order, signature)`
296
+
297
+ ```ts
298
+ const signature = await helper.signEip712Order(order, walletClient);
299
+ const payloadOrder = helper.serializeOrder(order);
300
+ const signer = await helper.recoverOrderSigner(order, signature);
301
+ ```
302
+
303
+ ### OrderbookApi
304
+
305
+ `OrderbookApi` is a fetch-based client that normalizes URLs, handles the
306
+ backend envelope format, exposes typed return values, and produces clearer
307
+ integration errors.
308
+
309
+ Constructor config:
310
+
311
+ - `baseUrl`
312
+ - `fetchFn?`
313
+
314
+ Public order methods:
315
+
316
+ - `createOrder(params, bearerToken)`
317
+ - `getOrder(orderHash)`
318
+ - `queryOrders(params)`
319
+ - `getUserOrders(maker, marketId)`
320
+ - `getDepthSnapshot(marketId, tokenId)`
321
+
322
+ Public market methods:
323
+
324
+ - `getMarkets()`
325
+ - `getMarketRecentTrades(marketId, limit?)`
326
+ - `getMarket(marketId)`
327
+
328
+ Public user and analytics methods:
329
+
330
+ - `getUserPositions(userAddress)`
331
+ - `getUserTradingPnL(userAddress)`
332
+ - `getUserPnL(userAddress)`
333
+ - `getTokenPnL(userAddress, tokenId)`
334
+ - `getErc20PnL(userAddress, tokenAddress)`
335
+
336
+ Public history methods:
337
+
338
+ - `getUserHistories(userAddress, limit?)`
339
+ - `getMintHistory(userAddress, limit?)`
340
+ - `getRedeemHistory(userAddress, limit?)`
341
+ - `getUnwindHistory(userAddress, limit?)`
342
+ - `getTransferHistory(userAddress, limit?)`
343
+ - `getFillHistory(userAddress, limit?)`
344
+
345
+ Auth-related methods also exposed by the SDK:
346
+
347
+ - `getChallenge({ address, chainId })`
348
+ - `verifyAuth({ account, nonce, signature, chainId, expiresAt })`
349
+
350
+ Integration note:
351
+
352
+ - `getUserOrders` enforces `marketId` at runtime
353
+ - `queryOrders` may accept an optional `marketId` in TypeScript, but reliable
354
+ backend integration should still provide one
355
+
356
+ ### Deserializers
357
+
358
+ The API returns string-heavy DTOs because JSON cannot safely transport
359
+ `bigint`. Public helpers convert those payloads into bigint-friendly objects:
360
+
361
+ - `orderToBigInt`
362
+ - `storedOrderToBigInt`
363
+ - `ordersSnapshotToBigInt`
364
+ - `queryOrdersResponseToBigInt`
365
+ - `depthSnapshotToBigInt`
366
+ - `marketInstrumentToBigInt`
367
+ - `marketToBigInt`
368
+ - `marketsToBigInt`
369
+ - `positionToBigInt`
370
+ - `tradingPnLToBigInt`
371
+ - `mintHistoryToBigInt`
372
+ - `redeemHistoryToBigInt`
373
+ - `unwindHistoryToBigInt`
374
+ - `transferHistoryToBigInt`
375
+ - `fillHistoryToBigInt`
376
+
377
+ ## Vault Module
378
+
379
+ Source files:
380
+
381
+ - `src/vault/index.ts`
382
+ - `src/vault/types.ts`
383
+ - `src/vault/token-ids.ts`
384
+ - `src/vault/collateral.ts`
385
+ - `src/vault/transactions.ts`
386
+ - `src/vault/constants.ts`
387
+
388
+ This module is built around `OptionMarketVault`. It documents position token
389
+ derivation, collateral and settlement math, precision constants, roles, and
390
+ transaction builders.
391
+
392
+ ### Vault concepts
393
+
394
+ The vault mints paired ERC-6909 position ids:
395
+
396
+ - `PRM`: collateral-side position token, always even
397
+ - `oPRM`: option claim token, always odd
398
+
399
+ Pairing rules:
400
+
401
+ - `oPrmTokenId = prmTokenId | 1`
402
+ - `optionPrmToPrm(tokenId)` clears the low bit and returns the canonical `PRM`
403
+ id
404
+
405
+ ### Public types
406
+
407
+ Main exports:
408
+
409
+ - `VaultInstrument`
410
+ - `VaultMarket`
411
+ - `PrmInfo`
412
+ - `TokenIdParams`
413
+ - `MarketParams`
414
+ - `InstrumentParams`
415
+ - `SpreadBounds`
416
+
417
+ ### Precision constants and roles
418
+
419
+ Public constants:
420
+
421
+ - `VAULT_TOKEN_PRECISION = 1e18`
422
+ - `FEE_BPS_PRECISION = 1e6`
423
+ - `PNL_PRECISION = 1e18`
424
+ - `Role`
425
+ - `ROLE_NAMES`
426
+
427
+ ### Token-id helpers
428
+
429
+ Public helpers:
430
+
431
+ - `getPrmTokenId(params)`
432
+ - `getOptionPrmTokenId(params)`
433
+ - `prmToOptionTokenId(prmTokenId)`
434
+ - `optionPrmToPrm(oPrmTokenId)`
435
+ - `isPrmToken(tokenId)`
436
+ - `isOptionPrmToken(tokenId)`
437
+ - `getPositionId(tokenId, userAddress)`
438
+
439
+ Implementation detail:
440
+
441
+ - `getPrmTokenId` hashes vault address, instrument fields, expiry, and
442
+ `chainId`, then left-shifts once to force even parity
443
+
444
+ ### Collateral and settlement math
445
+
446
+ Public helpers:
447
+
448
+ - `getSpreadWidth(market)`
449
+ - `getSpreadBounds(instrument, market)`
450
+ - `calculateCollateralAmount(prmAmount, instrument, market)`
451
+ - `calculatePrmAmount(collateralAmount, instrument, market)`
452
+ - `calculateSpreadProfit(instrument, market, finalTick, positionSize)`
453
+ - `calculateSpreadLoss(instrument, market, finalTick, positionSize)`
454
+ - `calculateWithdrawableCollateral(instrument, market, finalTick, positionSize)`
455
+ - `getCollateralPerPosition(instrument, market)`
456
+ - `calculateDepositFees(collateralAmount, depositFeeBps, feeBpsPrecision?)`
457
+ - `calculateRedeemFees(profitAmount, redeemFeeBps, feeBpsPrecision?)`
458
+ - `isInTheMoney(instrument, market, finalTick)`
459
+ - `calculateMoneyness(instrument, market, finalTick)`
460
+
461
+ Important behavior:
462
+
463
+ - spread width falls back to `1` when `tickSpacing <= tickSize`
464
+ - strike-scaled collateral uses `instrument.tick`
465
+ - collateral calculation rounds up when the final division is not exact
466
+ - inverse `PRM` previews use floor division
467
+ - payoff and withdraw math use deterministic `bigint` arithmetic throughout
468
+
469
+ ### Transaction builders
470
+
471
+ These helpers return:
472
+
473
+ ```ts
474
+ export interface TransactionCall {
475
+ to: `0x${string}`;
476
+ value?: bigint;
477
+ data: Hex;
478
+ }
479
+ ```
480
+
481
+ User-facing lifecycle builders:
482
+
483
+ - `buildMintTransaction(vaultAddress, instrument, amount)`
484
+ - `buildWithdrawTransaction(vaultAddress, prmTokenId, amount, receiver)`
485
+ - `buildRedeemTransaction(vaultAddress, oPrmTokenId, receiver)`
486
+ - `buildUnwindTransaction(vaultAddress, prmTokenId, amount, receiver)`
487
+ - `buildRolloverTransaction(vaultAddress, oldPrmTokenId)`
488
+ - `buildApproveTransaction(tokenAddress, spender, amount?)`
489
+ - `buildBatchedMintTransactions(collateralTokenAddress, vaultAddress, instrument, collateralAmount, prmAmount)`
490
+ - `buildSetOperatorTransaction(vaultAddress, operator, approved)`
491
+
492
+ Restricted or role-gated builders:
493
+
494
+ - `buildDelegateRedeemTransaction`
495
+ - `buildDelegateRolloverTransaction`
496
+ - `buildDelegateWithdrawTransaction`
497
+ - `buildFillMarketDeliveryTransaction`
498
+ - `buildSetRolloverEnabledTransaction`
499
+ - `buildSetRoleTransaction`
500
+ - `buildUpdateFinalTickTransaction`
501
+ - `buildUpdateMarketExpiryTransaction`
502
+ - `buildUpdateMarketExpiryFromMarketTransaction`
503
+
504
+ ## Registry Module
505
+
506
+ Source files:
507
+
508
+ - `src/registry/index.ts`
509
+ - `src/registry/types.ts`
510
+ - `src/registry/markets-registry-contract.ts`
511
+
512
+ This module wraps the `MarketsRegistry` contract surface used for market
513
+ configuration and serialization.
514
+
515
+ ### Public types
516
+
517
+ Main exports:
518
+
519
+ - `MarketType`
520
+ - `ERC20xERC20`
521
+ - `ERC20xERC6909`
522
+ - `RegistryMarket`
523
+ - `SerializedRegistryMarket`
524
+
525
+ Core fields include token addresses, sizing parameters, expiry, fee fields, and
526
+ runtime flags such as `marketType`, `isCollateralScaled`, and `nonRollable`.
527
+
528
+ Serialization helpers:
529
+
530
+ - `serializeRegistryMarket(market)`
531
+ - `deserializeRegistryMarket(market)`
532
+
533
+ ### Contract wrapper
534
+
535
+ `MarketsRegistryContract` wraps the shipped ABI and returns calldata or a tx
536
+ envelope.
537
+
538
+ Public surfaces:
539
+
540
+ - `RegistryTransactionCall`
541
+ - `MarketsRegistryContract`
542
+ - `getAddMarketCalldata(market)`
543
+ - `buildAddMarketTx(market)`
544
+ - `getUpdateTokenCalldata(token, isStable, isDelete)`
545
+ - `getSetWhitelistedCalldata(account, allowed)`
546
+ - `getUpdateMarketExpiryCalldata(marketId, expiry)`
547
+ - `getMulticallCalldata(data)`
548
+
549
+ Important nuance:
550
+
551
+ - `buildAddMarketTx` returns a full tx object
552
+ - the remaining helpers return raw calldata only
553
+
554
+ Most registry writes are administrative and should not be treated as normal
555
+ end-user flows.
556
+
557
+ ## Sync Module
558
+
559
+ Source files:
560
+
561
+ - `src/sync/index.ts`
562
+ - `src/sync/types.ts`
563
+ - `src/sync/clients/base-client.ts`
564
+ - `src/sync/clients/order-client.ts`
565
+ - `src/sync/clients/activity-client.ts`
566
+
567
+ This module contains the realtime clients used to keep frontends and services
568
+ in sync with depth and activity streams.
569
+
570
+ ### Shared sync types
571
+
572
+ Public exports:
573
+
574
+ - `SyncStatus`
575
+ - `"connecting" | "syncing" | "synced" | "recovering" | "disconnected" | "error"`
576
+ - `OrderChange`
577
+ - `SequencedMessage`
578
+ - `SyncClientConfig`
579
+
580
+ ### MarketDepthSyncClient
581
+
582
+ Main config:
583
+
584
+ - `wsUrl`
585
+ - `marketId`
586
+ - `tokenIds`
587
+ - `heartbeatIntervalMs?`
588
+ - `heartbeatTimeoutMs?`
589
+ - `maxReconnectAttempts?`
590
+ - `initialReconnectDelayMs?`
591
+ - `maxReconnectDelayMs?`
592
+
593
+ Connection methods:
594
+
595
+ - `connect()`
596
+ - `disconnect()`
597
+ - `getStatus()`
598
+
599
+ Read methods:
600
+
601
+ - `getTokenIds()`
602
+ - `getTokenState(tokenId)`
603
+ - `getBids(tokenId)`
604
+ - `getAsks(tokenId)`
605
+ - `getBestBid(tokenId)`
606
+ - `getBestAsk(tokenId)`
607
+ - `getLastPrice(tokenId)`
608
+ - `getSeq(tokenId)`
609
+ - `getSpread(tokenId)`
610
+ - `getDepthAtPrice(tokenId, side, price)`
611
+
612
+ Listener hooks:
613
+
614
+ - `onStatus(callback)`
615
+ - `onSnapshot(callback)`
616
+ - `onDelta(callback)`
617
+
618
+ Public event types:
619
+
620
+ - `DepthLevel`
621
+ - `TokenDepthSnapshot`
622
+ - `DepthLevelUpdate`
623
+ - `DepthChangeEvent`
624
+ - `DepthUpdate`
625
+
626
+ Implementation details captured by the client:
627
+
628
+ - invalid non-websocket URLs are rejected
629
+ - `connect()` waits for initial snapshots
630
+ - sequence ids are deduplicated and gaps trigger recovery
631
+ - equivalent price strings such as `"1"` and `"1.000000"` are normalized
632
+
633
+ ### ActivitySyncClient
634
+
635
+ Config:
636
+
637
+ - `wsUrl`
638
+ - `marketId?`
639
+ - `userAddress?`
640
+ - `heartbeatIntervalMs?`
641
+ - `heartbeatTimeoutMs?`
642
+ - `maxReconnectAttempts?`
643
+ - `initialReconnectDelayMs?`
644
+ - `maxReconnectDelayMs?`
645
+
646
+ At least one of `marketId` or `userAddress` is required.
647
+
648
+ Connection methods:
649
+
650
+ - `connect()`
651
+ - `disconnect()`
652
+ - `getStatus()`
653
+
654
+ Listener hooks:
655
+
656
+ - `onStatus(callback)`
657
+ - `onOrderFill(callback)`
658
+ - `onUserFill(callback)`
659
+ - `onMarketFill(callback)`
660
+
661
+ Public event type:
662
+
663
+ - `OrderFillEvent`
664
+
665
+ ### BaseSyncClient
666
+
667
+ This is the advanced extension point for custom sequenced Redis-backed clients.
668
+
669
+ Public methods:
670
+
671
+ - `connect()`
672
+ - `disconnect()`
673
+ - `getStatus()`
674
+ - `isSynced()`
675
+ - `getLastSequence()`
676
+ - `getBufferedCount()`
677
+ - `onStatus(callback)`
678
+ - `onChange(callback)`
679
+ - `onSnapshot(callback)`
680
+
681
+ Subclass responsibilities:
682
+
683
+ - provide `fetchSnapshot()`
684
+ - provide `applyMessage(message)`
685
+
686
+ ## Config Module
687
+
688
+ Source files:
689
+
690
+ - `src/config/index.ts`
691
+ - `src/config/chains.ts`
692
+
693
+ This module is the SDK's deployment and chain registry. It centralizes
694
+ supported chain definitions, token metadata, and deployed contract addresses so
695
+ applications do not hardcode environment-specific values.
696
+
697
+ ### Chains
698
+
699
+ Exports from `src/config/chains.ts`:
700
+
701
+ - `megaETH`
702
+ - `SUPPORTED_CHAINS`
703
+
704
+ Runtime lookup from `src/config/index.ts`:
705
+
706
+ - `CHAIN_ID_TO_CHAIN`
707
+
708
+ ### Token metadata
709
+
710
+ Shared shape:
711
+
712
+ ```ts
713
+ export interface Token {
714
+ name: string;
715
+ symbol: string;
716
+ address: `0x${string}`;
717
+ decimals: number;
718
+ logoURI?: string;
719
+ }
113
720
  ```
114
721
 
115
- For the exact order model, fill semantics, fee math, and typed-data schema, use
116
- the [Exchange guide](./src/exchange/README.md). For API payloads and response
117
- DTOs, use the [API guide](./src/api/README.md) and
118
- [Shared types guide](./src/shared/README.md).
722
+ Public token maps:
723
+
724
+ - `WETH`
725
+ - `USDC`
726
+ - `USDM`
727
+ - `USDT0`
728
+
729
+ Important nuance:
730
+
731
+ - `USDM`, `USDT0`, `MARKETS_REGISTRY`, `FEE_REGISTRY`, and
732
+ `ERC_TOKENS_RESTRICTION_MODULE` are partial maps because those deployments do
733
+ not exist on every supported chain
734
+
735
+ ### Contract address maps
736
+
737
+ Public address maps:
738
+
739
+ - `PERMIT2_ADDRESS`
740
+ - `OPTION_MARKET_VAULT`
741
+ - `EXCHANGE`
742
+ - `MARKETS_REGISTRY`
743
+ - `ENTRY_POINT`
744
+ - `SIMPLE_ACCOUNT_FACTORY`
745
+ - `FEE_REGISTRY`
746
+ - `ERC_TOKENS_RESTRICTION_MODULE`
747
+
748
+ ## Shared DTOs
749
+
750
+ Source files:
751
+
752
+ - `src/shared/index.ts`
753
+ - `src/shared/types.ts`
754
+
755
+ These types are the transport layer between the SDK, the HTTP API, and
756
+ frontend consumers. Numeric fields are usually strings so they can be moved
757
+ safely over JSON.
758
+
759
+ ### Order transport types
760
+
761
+ Main exports:
762
+
763
+ - `Order`
764
+ - `OrderSignature`
765
+ - `OrderStatus`
766
+ - `TimeInForce`
767
+ - `CreateOrderParams`
768
+ - `CreateOrderRequest`
769
+ - `StoredOrder`
770
+ - `MatchableOrder`
771
+ - `MatchRequest`
772
+ - `MatchedOrder`
773
+ - `MatchResult`
774
+ - `CreateOrderResult`
775
+ - `OrderQueryParams`
776
+ - `OrderResponse`
777
+ - `OrdersSnapshot`
778
+ - `QueryOrdersResponse`
779
+ - `DepthSnapshot`
780
+
781
+ Main order write shape:
782
+
783
+ ```ts
784
+ export interface CreateOrderParams {
785
+ marketId: string;
786
+ order: Order;
787
+ signature: OrderSignature;
788
+ operator?: string;
789
+ timeInForce?: TimeInForce;
790
+ postOnly?: boolean;
791
+ }
792
+ ```
793
+
794
+ Main order read shape:
795
+
796
+ ```ts
797
+ export interface StoredOrder {
798
+ orderHash: string;
799
+ signature: OrderSignature;
800
+ marketId: string;
801
+ tokenId: string;
802
+ remainingMakerAmount: string;
803
+ order: Order;
804
+ operator?: string;
805
+ createdAt: number;
806
+ status: OrderStatus;
807
+ side: "bid" | "ask";
808
+ price: number;
809
+ }
810
+ ```
811
+
812
+ ### Market DTOs
813
+
814
+ Public exports:
815
+
816
+ - `MarketInstrument`
817
+ - `Market`
818
+ - `MarketResponse`
819
+ - `MarketsResponse`
820
+
821
+ `MarketInstrument` carries strike-level data such as paired token ids,
822
+ top-of-book values, recent prices, collateral totals, and supply.
823
+
824
+ `Market` wraps market-level metadata such as pricing increments, token
825
+ addresses, fee fields, expiry, and nested `instruments`.
826
+
827
+ ### Position and PnL DTOs
828
+
829
+ Public exports:
830
+
831
+ - `UserPosition`
832
+ - `TradingPnL`
833
+ - `UserPnL`
834
+ - `TokenPnL`
835
+ - `Erc20PnL`
836
+
837
+ ### History DTOs
838
+
839
+ Public exports:
119
840
 
120
- ## Smart-Account Helpers
841
+ - `MintHistoryItem`
842
+ - `RedeemHistoryItem`
843
+ - `UnwindHistoryItem`
844
+ - `TransferHistoryItem`
845
+ - `OrderFillHistoryItem`
846
+ - `MarketTradeItem`
847
+ - `UserHistories`
121
848
 
122
- The package root exports the smart-account helpers from
123
- [`src/smart-account.ts`](./src/smart-account.ts). These helpers are for
124
- deterministic account derivation and deployment checks that match the
125
- `SimpleAccountFactory`-style contract surface used by the wider Stryke stack.
849
+ `UserHistories` groups `mints`, `redeems`, `unwinds`, `transfers`, and
850
+ `fills`.
851
+
852
+ ## Root-Level Helpers
853
+
854
+ ### Smart-account helpers
855
+
856
+ Source file:
857
+
858
+ - `src/smart-account.ts`
859
+
860
+ These helpers are for deterministic account derivation and deployment checks
861
+ aligned with the `SimpleAccountFactory`-style surface used elsewhere in the
862
+ Stryke stack.
126
863
 
127
864
  Public types:
128
865
 
@@ -146,33 +883,15 @@ Public class:
146
883
  - `getCurrent(client, owner, depositor)`
147
884
  - `isDeployed(client, address)`
148
885
 
149
- ```ts
150
- import {
151
- SIMPLE_ACCOUNT_FACTORY,
152
- SmartAccountHelper,
153
- } from "@stryke-xyz/premarket-sdk";
886
+ These helpers do not execute user operations and are intentionally small.
154
887
 
155
- const helper = new SmartAccountHelper({
156
- factoryAddress: SIMPLE_ACCOUNT_FACTORY[4326],
157
- });
888
+ ### Address
158
889
 
159
- const account = await helper.getCurrent(client, owner, depositor);
160
- ```
161
-
162
- These helpers are intentionally small. They do not execute user operations or
163
- act as a full account-abstraction SDK. Their job is to keep address derivation
164
- and deployment checks aligned with the factory contract.
165
-
166
- ## Address And Bps Helpers
167
-
168
- Two utility classes are exported from the package root for common app-side
169
- operations.
890
+ Source file:
170
891
 
171
- ### `Address`
892
+ - `src/address.ts`
172
893
 
173
- Source: [`src/address.ts`](./src/address.ts)
174
-
175
- Public surfaces:
894
+ Public surface:
176
895
 
177
896
  - `Address.NATIVE_CURRENCY`
178
897
  - `Address.zeroAddress`
@@ -184,14 +903,13 @@ Public surfaces:
184
903
  - `isZero()`
185
904
  - `lastHalf()`
186
905
 
187
- This helper wraps address normalization and a few convenience checks that are
188
- useful in UI and backend code.
906
+ ### Bps
189
907
 
190
- ### `Bps`
908
+ Source file:
191
909
 
192
- Source: [`src/bps.ts`](./src/bps.ts)
910
+ - `src/bps.ts`
193
911
 
194
- Public surfaces:
912
+ Public surface:
195
913
 
196
914
  - `Bps.ZERO`
197
915
  - `Bps.fromPercent(val, base?)`
@@ -202,16 +920,15 @@ Public surfaces:
202
920
  - `toFraction(base?)`
203
921
  - `toString()`
204
922
 
205
- `Bps` is a small helper around basis-point values in the inclusive range
206
- `[0, 10000]`.
923
+ `Bps` constrains values to the inclusive range `[0, 10000]`.
207
924
 
208
- ## Compatibility Constants And Utilities
925
+ ### Compatibility constants
209
926
 
210
- ### Constants helpers
927
+ Source file:
211
928
 
212
- Source: [`src/constants.ts`](./src/constants.ts)
929
+ - `src/constants.ts`
213
930
 
214
- Public surfaces:
931
+ Public surface:
215
932
 
216
933
  - `ZX`
217
934
  - `getExchangeContract(chainId)`
@@ -220,40 +937,55 @@ Public surfaces:
220
937
  - `getNativeOrderFactoryContract(chainId)`
221
938
  - `getNativeOrderImplContract(chainId)`
222
939
 
223
- The exchange and registry accessors are still useful. The native order factory
224
- and impl helpers are compatibility-oriented and should be treated as legacy
225
- bridge helpers rather than the center of new integrations.
940
+ The exchange and registry accessors remain useful. The native order factory and
941
+ impl helpers are mostly compatibility-oriented bridge helpers.
226
942
 
227
- ### Utility functions
943
+ ## Utilities
228
944
 
229
- For the detailed utility reference, use the
230
- [Utilities guide](./src/utils/README.md). The public root-level utility exports
231
- are:
945
+ Source files:
946
+
947
+ - `src/utils/mul-div.ts`
948
+ - `src/utils/rand-bigint.ts`
949
+ - `src/utils/orderUtils.ts`
950
+
951
+ This folder contains small reusable helpers that do not belong to a single
952
+ domain module but are still part of the public SDK surface.
953
+
954
+ ### `mulDiv` and `Rounding`
955
+
956
+ Public exports:
232
957
 
233
- - `mulDiv`
234
958
  - `Rounding`
235
- - `randBigInt`
236
- - `optionPrmToPrmTokenId`
237
- - `prmToOptionPrmTokenId`
238
- - `isComplementaryOptionTokenPair`
239
- - `verifyOrderSignature`
959
+ - `Ceil`
960
+ - `Floor`
961
+ - `mulDiv(a, b, x, rounding?)`
240
962
 
241
- ## Documentation Principles
963
+ `mulDiv` performs integer multiplication and division in one step using
964
+ `bigint` arithmetic.
242
965
 
243
- The new docs aim to serve both technical readers and product-adjacent readers:
966
+ ### `randBigInt`
244
967
 
245
- - each module guide starts with purpose and system role
246
- - every guide links directly to source files that implement the behavior
247
- - public exports are documented in terms of both intent and exact runtime shape
248
- - examples stay realistic and contract-aligned
249
- - restricted or sensitive surfaces are acknowledged, but the docs avoid becoming
250
- an admin or auth operations manual
968
+ Public export:
251
969
 
252
- ## Install
970
+ - `randBigInt(max)`
253
971
 
254
- ```bash
255
- bun add @stryke-xyz/premarket-sdk
256
- ```
972
+ Behavior:
973
+
974
+ - returns a cryptographically secure random bigint in `[0, max]`
975
+ - requires `globalThis.crypto.getRandomValues`
976
+ - throws if no secure random source is available
977
+
978
+ ### Order utility helpers
979
+
980
+ Public exports:
981
+
982
+ - `optionPrmToPrmTokenId(tokenId)`
983
+ - `prmToOptionPrmTokenId(prmTokenId)`
984
+ - `isComplementaryOptionTokenPair(tokenIdA, tokenIdB)`
985
+ - `verifyOrderSignature(order, signature, chainId, exchangeAddress)`
986
+
987
+ These overlap conceptually with the exchange and vault modules, but they are
988
+ useful when a caller wants the smallest possible helper surface.
257
989
 
258
990
  ## Development
259
991
 
@@ -263,27 +995,28 @@ bun run build
263
995
  bun test src
264
996
  ```
265
997
 
266
- ## Source Layout
998
+ Available scripts from `package.json`:
267
999
 
268
- - [`src/exchange`](./src/exchange): native order model, typed-data, math, and
269
- exchange calldata builders
270
- - [`src/vault`](./src/vault): token-id helpers, collateral math, and vault
271
- transaction builders
272
- - [`src/registry`](./src/registry): market serialization and registry calldata
273
- builders
274
- - [`src/api`](./src/api): `OrderHelper`, `OrderbookApi`, and deserializers
275
- - [`src/sync`](./src/sync): realtime market depth and activity clients
276
- - [`src/config`](./src/config): chains, addresses, and token constants
277
- - [`src/shared`](./src/shared): transport DTOs used across SDK, API, and UI
1000
+ - `bun run build`
1001
+ - `bun run test`
1002
+ - `bun run typecheck`
1003
+ - `bun run test:e2e`
1004
+ - `bun run fill-orderbook`
278
1005
 
279
1006
  ## Legacy Docs
280
1007
 
281
- The current docs remain available during the transition:
282
-
283
- - [Cross-repo guide](./docs/CROSS_REPO_INTEGRATION.md)
284
- - [Orderbook integration quick reference](./docs/orderbook-integration.md)
285
- - [SDK API reference](./docs/API_REFERENCE.md)
286
- - [Refactor notes and protocol specs](./docs/refactor-docs)
287
-
288
- Once the new documentation set is fully adopted, these older guides can be
289
- trimmed or removed with less migration risk.
1008
+ The repository still contains older reference material under `docs/`:
1009
+
1010
+ - `docs/CROSS_REPO_INTEGRATION.md`
1011
+ - `docs/orderbook-integration.md`
1012
+ - `docs/API_REFERENCE.md`
1013
+ - `docs/refactor-docs/LimitOrderProtocol_FEE_HOWTO.md`
1014
+ - `docs/refactor-docs/OptionMarketVault_AUDITOR_SPEC.md`
1015
+ - `docs/refactor-docs/OptionMarketVault_CEO_SUMMARY.md`
1016
+ - `docs/refactor-docs/OptionMarketVault_DEV_SPEC.md`
1017
+ - `docs/refactor-docs/OptionMarketVault_PUBLIC.md`
1018
+ - `docs/refactor-docs/SDK_TECHNICAL_SPEC.md`
1019
+
1020
+ This root README is now the single repository-level README entry point, while
1021
+ the `docs/` directory remains available for deeper historical or protocol
1022
+ context.