@hadron-fi/sdk 0.3.0 → 0.3.2

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/dist/index.d.mts CHANGED
@@ -85,6 +85,14 @@ interface DecodedFeeConfig {
85
85
  feeAdmin: PublicKey;
86
86
  feeRecipient: PublicKey;
87
87
  }
88
+ interface DecodedSpreadConfig {
89
+ initialized: boolean;
90
+ bump: number;
91
+ numTriggers: number;
92
+ admin: PublicKey;
93
+ config: PublicKey;
94
+ triggers: SpreadTriggerInput[];
95
+ }
88
96
  interface DecodedCurveUpdates {
89
97
  authority: PublicKey;
90
98
  curveMeta: PublicKey;
@@ -267,6 +275,48 @@ interface AllocateCurvePrefabsParams {
267
275
  maxPrefabSlots?: number;
268
276
  maxCurvePoints?: number;
269
277
  }
278
+ type OrderSide = "bid" | "ask";
279
+ interface PlaceOrderParams {
280
+ side: OrderSide;
281
+ /** Size in base tokens (human-readable, not atoms) */
282
+ size: number;
283
+ /** Spread from midprice in basis points */
284
+ spreadBps: number;
285
+ }
286
+ interface AmendOrderParams {
287
+ side: OrderSide;
288
+ /** 0-based index into the staged orders for that side */
289
+ level: number;
290
+ spreadBps?: number;
291
+ size?: number;
292
+ }
293
+ interface CancelOrderParams {
294
+ side: OrderSide;
295
+ level: number;
296
+ }
297
+ interface OrderbookLevel {
298
+ /** Absolute price (midprice * priceFactor) */
299
+ price: number;
300
+ /** Size at this level in base tokens */
301
+ size: number;
302
+ /** Cumulative size up to and including this level */
303
+ cumulative: number;
304
+ }
305
+ interface OrderbookState {
306
+ midprice: number;
307
+ bids: OrderbookLevel[];
308
+ asks: OrderbookLevel[];
309
+ inventory: {
310
+ base: number;
311
+ quote: number;
312
+ };
313
+ }
314
+ interface StagedOrder {
315
+ /** Size in base tokens (human-readable) */
316
+ size: number;
317
+ /** Spread from midprice in basis points */
318
+ spreadBps: number;
319
+ }
270
320
  interface PoolAddresses {
271
321
  config: PublicKey;
272
322
  configBump: number;
@@ -394,10 +444,153 @@ declare class Hadron {
394
444
  setPoolState(authority: PublicKey, params: SetPoolStateParams): TransactionInstruction;
395
445
  /** Build update delta staleness instruction. */
396
446
  updateDeltaStaleness(authority: PublicKey, params: UpdateDeltaStalenessParams): TransactionInstruction;
447
+ /** Build initialize spread config instruction. */
448
+ initializeSpreadConfig(payer: PublicKey, authority: PublicKey, params: InitializeSpreadConfigParams): TransactionInstruction;
449
+ /** Build update spread config instruction (full replacement). */
450
+ updateSpreadConfig(admin: PublicKey, params: UpdateSpreadConfigParams): TransactionInstruction;
451
+ /**
452
+ * Fetch current spread triggers, append new ones, and return the update ix.
453
+ * If a trigger for the same account already exists, its spreadBps is updated.
454
+ */
455
+ addSpreadTriggers(admin: PublicKey, triggers: SpreadTriggerInput[]): Promise<TransactionInstruction>;
456
+ /**
457
+ * Fetch current spread triggers, remove the given accounts, and return the update ix.
458
+ */
459
+ removeSpreadTriggers(admin: PublicKey, accounts: PublicKey[]): Promise<TransactionInstruction>;
460
+ /** Fetch and decode the current spread config triggers from chain. */
461
+ private fetchSpreadTriggers;
397
462
  /** Build close pool instruction. */
398
463
  closePool(authority: PublicKey): TransactionInstruction;
399
464
  }
400
465
 
466
+ /**
467
+ * High-level orderbook abstraction over a Hadron pool.
468
+ *
469
+ * Maps limit orders to risk curve points using `CurveXMode.Alternate`
470
+ * (absolute vault balance x-axis) and `RiskMode.Integrated`.
471
+ *
472
+ * ```ts
473
+ * const book = await HadronOrderbook.load({ connection, pool: poolAddress });
474
+ * book.placeOrder({ side: "bid", size: 100, spreadBps: 10 });
475
+ * book.placeOrder({ side: "ask", size: 100, spreadBps: 10 });
476
+ * const ixs = book.push(authority);
477
+ * ```
478
+ */
479
+ declare class HadronOrderbook {
480
+ /** Underlying Hadron pool instance. */
481
+ readonly pool: Hadron;
482
+ /** Decimals for token X (base). */
483
+ readonly decimalsX: number;
484
+ /** Decimals for token Y (quote). */
485
+ readonly decimalsY: number;
486
+ /** Vault X balance at time of load (atoms). */
487
+ readonly initialVaultX: bigint;
488
+ /** Vault Y balance at time of load (atoms). */
489
+ readonly initialVaultY: bigint;
490
+ private bidOrders;
491
+ private askOrders;
492
+ private bidsDirty;
493
+ private asksDirty;
494
+ private priceCurvesSet;
495
+ private riskBidInitialized;
496
+ private riskAskInitialized;
497
+ private committedBidPoints;
498
+ private committedAskPoints;
499
+ private constructor();
500
+ /**
501
+ * Load an orderbook from an existing on-chain pool.
502
+ * Fetches decimals and vault balances, and reconstructs staged orders
503
+ * from the active risk curves.
504
+ */
505
+ static load(params: {
506
+ connection: Connection;
507
+ pool: PublicKey;
508
+ }): Promise<HadronOrderbook>;
509
+ /**
510
+ * Wrap an existing Hadron instance as an orderbook.
511
+ * Useful for tests or when you already have the pool loaded.
512
+ */
513
+ static fromPool(pool: Hadron, decimalsX: number, decimalsY: number, initialVaultX: bigint, initialVaultY: bigint): HadronOrderbook;
514
+ /**
515
+ * Place a new order. Orders are staged locally and pushed on-chain via `push()`.
516
+ * Orders on each side are sorted by spreadBps ascending (tightest first).
517
+ * @throws If more than 31 orders on a side.
518
+ */
519
+ placeOrder(params: PlaceOrderParams): void;
520
+ /**
521
+ * Amend an existing order at the given level index.
522
+ * Re-sorts if spread changes.
523
+ * @throws On invalid index.
524
+ */
525
+ amendOrder(params: AmendOrderParams): void;
526
+ /**
527
+ * Cancel the order at the given level index.
528
+ * @throws On invalid index.
529
+ */
530
+ cancelOrder(params: CancelOrderParams): void;
531
+ /** Cancel all orders on one or both sides. */
532
+ cancelAll(side?: OrderSide): void;
533
+ /** Read-only access to staged bid orders. */
534
+ getBids(): readonly StagedOrder[];
535
+ /** Read-only access to staged ask orders. */
536
+ getAsks(): readonly StagedOrder[];
537
+ /**
538
+ * Build transaction instructions to push the current staged orders on-chain.
539
+ *
540
+ * 1. On first push, sets flat price curves (factor=1.0, Step interpolation).
541
+ * 2. If risk curves not yet initialized, uses setRiskCurveAbsolute (sets headers).
542
+ * 3. On subsequent pushes, computes a minimal diff and uses curve updates
543
+ * (submit + apply) when possible, falling back to full rewrite for large diffs.
544
+ */
545
+ push(authority: PublicKey): TransactionInstruction[];
546
+ /** Build an updateMidprice instruction. */
547
+ updateMidprice(authority: PublicKey, midprice: number, sequence?: bigint): TransactionInstruction;
548
+ /** Build a deposit instruction. */
549
+ deposit(user: PublicKey, params: DepositParams): TransactionInstruction;
550
+ /** Build a withdraw instruction. */
551
+ withdraw(user: PublicKey, params: WithdrawParams): TransactionInstruction;
552
+ /** Build a setPoolState instruction. */
553
+ setPoolState(authority: PublicKey, params: SetPoolStateParams): TransactionInstruction;
554
+ /**
555
+ * Get the current book state by reading on-chain risk curves + midprice.
556
+ * Reconstructs levels from curve points.
557
+ */
558
+ getBookState(): OrderbookState;
559
+ /**
560
+ * Compute the minimal set of curve update ops to transform `committed` into `desired`.
561
+ *
562
+ * Algorithm:
563
+ * 1. Scan left-to-right for factor-only diffs (amountIn unchanged) → Edit ops.
564
+ * 2. At the first structural diff (amountIn changed or length mismatch),
565
+ * truncate-and-rebuild: remove all from that index to end, then add desired.
566
+ * 3. Returns the ops array.
567
+ */
568
+ static computeCurveOps(committed: CurvePoint[], desired: CurvePoint[], curveType: CurveType): CurveUpdateOp[];
569
+ /** Convert SetRiskCurveAbsolutePointInput[] to CurvePoint[] for diffing. */
570
+ private static toCommittedPoints;
571
+ /**
572
+ * Build full setRiskCurveAbsolute instructions for sides that need initialization.
573
+ * After sending, snapshots committed points and marks sides as initialized.
574
+ */
575
+ private buildFullRiskCurveIxs;
576
+ /**
577
+ * Build curve update instructions (submit + apply pairs) for both sides.
578
+ * Falls back to full setRiskCurve rewrite if diff is too large.
579
+ */
580
+ private buildCurveUpdateIxs;
581
+ /** Fallback: full setRiskCurve rewrite for both sides. */
582
+ private buildFallbackRewrite;
583
+ private buildBidRiskPoints;
584
+ private buildAskRiskPoints;
585
+ /**
586
+ * Reconstruct staged orders from on-chain risk curves (after load).
587
+ * Assumes curves were set via this class (CurveXMode.Alternate, RiskMode.Integrated, Step).
588
+ */
589
+ private reconstructFromCurves;
590
+ private reconstructSide;
591
+ private curveSideToLevels;
592
+ }
593
+
401
594
  declare const HADRON_PROGRAM_ID: PublicKey;
402
595
  declare const CONFIG_SEED: Buffer<ArrayBuffer>;
403
596
  declare const MIDPRICE_ORACLE_SEED: Buffer<ArrayBuffer>;
@@ -463,6 +656,7 @@ declare function decodeCurveMeta(data: Uint8Array): DecodedCurveMeta;
463
656
  */
464
657
  declare function isSlotInitialized(initializedSlots: Uint8Array, curveType: CurveType, slot: number, maxSlots: number): boolean;
465
658
  declare function decodeFeeConfig(data: Uint8Array): DecodedFeeConfig;
659
+ declare function decodeSpreadConfig(data: Uint8Array): DecodedSpreadConfig;
466
660
  declare function decodeCurveUpdates(data: Uint8Array): DecodedCurveUpdates;
467
661
  /**
468
662
  * Decode a single curve side from a CurvePrefabs account.
@@ -537,9 +731,9 @@ declare function buildWithdraw(user: PublicKey, configPda: PublicKey, mintX: Pub
537
731
  * user_source, vault_source, vault_dest, user_dest, fee_config,
538
732
  * fee_recipient_ata, clock, curve_updates.
539
733
  *
540
- * Optional (for introspection): spread_config, instructions_sysvar.
734
+ * When spread config is initialized: spread_config (#16) + instructions_sysvar (#17).
541
735
  */
542
- declare function buildSwapExactIn(user: PublicKey, poolAddresses: PoolAddresses, mintX: PublicKey, mintY: PublicKey, tokenProgramX: PublicKey, tokenProgramY: PublicKey, params: SwapParams, programId?: PublicKey): TransactionInstruction;
736
+ declare function buildSwapExactIn(user: PublicKey, poolAddresses: PoolAddresses, mintX: PublicKey, mintY: PublicKey, tokenProgramX: PublicKey, tokenProgramY: PublicKey, params: SwapParams, programId?: PublicKey, spreadConfigInitialized?: boolean): TransactionInstruction;
543
737
 
544
738
  /**
545
739
  * Build a SetCurve instruction (price curve).
@@ -673,4 +867,4 @@ declare function buildUpdateDeltaStaleness(authority: PublicKey, configPda: Publ
673
867
  */
674
868
  declare function buildClosePool(authority: PublicKey, configPda: PublicKey, midpriceOraclePda: PublicKey, curveMetaPda: PublicKey, curvePrefabsPda: PublicKey, curveUpdatesPda: PublicKey, vaultX: PublicKey, vaultY: PublicKey, tokenProgramX: PublicKey, tokenProgramY: PublicKey, spreadConfigInitialized?: boolean, programId?: PublicKey): TransactionInstruction;
675
869
 
676
- export { ABSOLUTE_MAX_CURVE_POINTS, ABSOLUTE_MAX_PREFAB_SLOTS, type AllocateCurvePrefabsParams, CONFIG_SEED, CONFIG_SIZE, CURVE_META_SEED, CURVE_META_SIZE, CURVE_POINT_LEN, CURVE_PREFABS_SEED, CURVE_SIDE_HEADER, CURVE_UPDATES_SEED, CURVE_UPDATES_SIZE, CURVE_UPDATE_OP_SIZE, type CurvePoint, type CurveSide, CurveType, type CurveUpdateOp, CurveUpdateOpKind, CurveXMode, DEFAULT_MAX_CURVE_POINTS, DEFAULT_MAX_PREFAB_SLOTS, type DecodedConfig, type DecodedCurveMeta, type DecodedCurveUpdates, type DecodedFeeConfig, type DecodedMidpriceOracle, type DepositParams, Discriminator, FEE_CONFIG_SEED, FEE_CONFIG_SIZE, HADRON_PROGRAM_ID, Hadron, type InitializeFeeConfigParams, type InitializeParams, type InitializeSpreadConfigParams, Interpolation, MAX_CURVE_UPDATE_OPS, MAX_SETCURVE_POINTS, MIDPRICE_ORACLE_SEED, MIDPRICE_ORACLE_SIZE, type NominateAuthorityParams, OracleMode, POINT_DATA_SIZE, type PoolAddresses, PoolState, Q32_ONE, RiskMode, type RotateFeeAdminParams, SPREAD_CONFIG_SEED, type SetCurveBothParams, type SetCurveParams, type SetCurvePointInput, type SetPoolStateParams, type SetQuotingAuthorityParams, type SetRiskCurveAbsoluteBothParams, type SetRiskCurveAbsoluteParams, type SetRiskCurveAbsolutePointInput, type SetRiskCurveBothParams, type SetRiskCurveParams, type SetRiskCurvePointInput, Side, type SpreadTriggerInput, type SwapParams, type SwitchCurveParams, type UpdateBaseSpreadParams, type UpdateDeltaStalenessParams, type UpdateFeeConfigParams, type UpdateMidpriceAndBaseSpreadParams, type UpdateMidpriceParams, type UpdateSpreadConfigParams, type WithdrawParams, buildAcceptAuthority, buildAllocateCurvePrefabs, buildApplyCurveUpdates, buildClosePool, buildDeposit, buildInitialize, buildInitializeFeeConfig, buildInitializeSpreadConfig, buildNominateAuthority, buildRotateFeeAdmin, buildSetCurve, buildSetCurveBoth, buildSetPoolState, buildSetQuotingAuthority, buildSetRiskCurve, buildSetRiskCurveAbsolute, buildSetRiskCurveAbsoluteBoth, buildSetRiskCurveBoth, buildSubmitCurveUpdates, buildSwapExactIn, buildSwitchPriceCurve, buildSwitchRiskCurve, buildUpdateBaseSpread, buildUpdateDeltaStaleness, buildUpdateFeeConfig, buildUpdateMidprice, buildUpdateMidpriceAndBaseSpread, buildUpdateSpreadConfig, buildWithdraw, curvePrefabsSize, decodeActiveCurves, decodeConfig, decodeCurveMeta, decodeCurveSide, decodeCurveUpdates, decodeFeeConfig, decodeMidpriceOracle, derivePoolAddresses, fromQ32, getConfigAddress, getCurveMetaAddress, getCurvePrefabsAddress, getCurveUpdatesAddress, getFeeConfigAddress, getMidpriceOracleAddress, getOrCreateAta, getSpreadConfigAddress, isSlotInitialized, pctToQ32, toQ32 };
870
+ export { ABSOLUTE_MAX_CURVE_POINTS, ABSOLUTE_MAX_PREFAB_SLOTS, type AllocateCurvePrefabsParams, type AmendOrderParams, CONFIG_SEED, CONFIG_SIZE, CURVE_META_SEED, CURVE_META_SIZE, CURVE_POINT_LEN, CURVE_PREFABS_SEED, CURVE_SIDE_HEADER, CURVE_UPDATES_SEED, CURVE_UPDATES_SIZE, CURVE_UPDATE_OP_SIZE, type CancelOrderParams, type CurvePoint, type CurveSide, CurveType, type CurveUpdateOp, CurveUpdateOpKind, CurveXMode, DEFAULT_MAX_CURVE_POINTS, DEFAULT_MAX_PREFAB_SLOTS, type DecodedConfig, type DecodedCurveMeta, type DecodedCurveUpdates, type DecodedFeeConfig, type DecodedMidpriceOracle, type DecodedSpreadConfig, type DepositParams, Discriminator, FEE_CONFIG_SEED, FEE_CONFIG_SIZE, HADRON_PROGRAM_ID, Hadron, HadronOrderbook, type InitializeFeeConfigParams, type InitializeParams, type InitializeSpreadConfigParams, Interpolation, MAX_CURVE_UPDATE_OPS, MAX_SETCURVE_POINTS, MIDPRICE_ORACLE_SEED, MIDPRICE_ORACLE_SIZE, type NominateAuthorityParams, OracleMode, type OrderSide, type OrderbookLevel, type OrderbookState, POINT_DATA_SIZE, type PlaceOrderParams, type PoolAddresses, PoolState, Q32_ONE, RiskMode, type RotateFeeAdminParams, SPREAD_CONFIG_SEED, type SetCurveBothParams, type SetCurveParams, type SetCurvePointInput, type SetPoolStateParams, type SetQuotingAuthorityParams, type SetRiskCurveAbsoluteBothParams, type SetRiskCurveAbsoluteParams, type SetRiskCurveAbsolutePointInput, type SetRiskCurveBothParams, type SetRiskCurveParams, type SetRiskCurvePointInput, Side, type SpreadTriggerInput, type StagedOrder, type SwapParams, type SwitchCurveParams, type UpdateBaseSpreadParams, type UpdateDeltaStalenessParams, type UpdateFeeConfigParams, type UpdateMidpriceAndBaseSpreadParams, type UpdateMidpriceParams, type UpdateSpreadConfigParams, type WithdrawParams, buildAcceptAuthority, buildAllocateCurvePrefabs, buildApplyCurveUpdates, buildClosePool, buildDeposit, buildInitialize, buildInitializeFeeConfig, buildInitializeSpreadConfig, buildNominateAuthority, buildRotateFeeAdmin, buildSetCurve, buildSetCurveBoth, buildSetPoolState, buildSetQuotingAuthority, buildSetRiskCurve, buildSetRiskCurveAbsolute, buildSetRiskCurveAbsoluteBoth, buildSetRiskCurveBoth, buildSubmitCurveUpdates, buildSwapExactIn, buildSwitchPriceCurve, buildSwitchRiskCurve, buildUpdateBaseSpread, buildUpdateDeltaStaleness, buildUpdateFeeConfig, buildUpdateMidprice, buildUpdateMidpriceAndBaseSpread, buildUpdateSpreadConfig, buildWithdraw, curvePrefabsSize, decodeActiveCurves, decodeConfig, decodeCurveMeta, decodeCurveSide, decodeCurveUpdates, decodeFeeConfig, decodeMidpriceOracle, decodeSpreadConfig, derivePoolAddresses, fromQ32, getConfigAddress, getCurveMetaAddress, getCurvePrefabsAddress, getCurveUpdatesAddress, getFeeConfigAddress, getMidpriceOracleAddress, getOrCreateAta, getSpreadConfigAddress, isSlotInitialized, pctToQ32, toQ32 };
package/dist/index.d.ts CHANGED
@@ -85,6 +85,14 @@ interface DecodedFeeConfig {
85
85
  feeAdmin: PublicKey;
86
86
  feeRecipient: PublicKey;
87
87
  }
88
+ interface DecodedSpreadConfig {
89
+ initialized: boolean;
90
+ bump: number;
91
+ numTriggers: number;
92
+ admin: PublicKey;
93
+ config: PublicKey;
94
+ triggers: SpreadTriggerInput[];
95
+ }
88
96
  interface DecodedCurveUpdates {
89
97
  authority: PublicKey;
90
98
  curveMeta: PublicKey;
@@ -267,6 +275,48 @@ interface AllocateCurvePrefabsParams {
267
275
  maxPrefabSlots?: number;
268
276
  maxCurvePoints?: number;
269
277
  }
278
+ type OrderSide = "bid" | "ask";
279
+ interface PlaceOrderParams {
280
+ side: OrderSide;
281
+ /** Size in base tokens (human-readable, not atoms) */
282
+ size: number;
283
+ /** Spread from midprice in basis points */
284
+ spreadBps: number;
285
+ }
286
+ interface AmendOrderParams {
287
+ side: OrderSide;
288
+ /** 0-based index into the staged orders for that side */
289
+ level: number;
290
+ spreadBps?: number;
291
+ size?: number;
292
+ }
293
+ interface CancelOrderParams {
294
+ side: OrderSide;
295
+ level: number;
296
+ }
297
+ interface OrderbookLevel {
298
+ /** Absolute price (midprice * priceFactor) */
299
+ price: number;
300
+ /** Size at this level in base tokens */
301
+ size: number;
302
+ /** Cumulative size up to and including this level */
303
+ cumulative: number;
304
+ }
305
+ interface OrderbookState {
306
+ midprice: number;
307
+ bids: OrderbookLevel[];
308
+ asks: OrderbookLevel[];
309
+ inventory: {
310
+ base: number;
311
+ quote: number;
312
+ };
313
+ }
314
+ interface StagedOrder {
315
+ /** Size in base tokens (human-readable) */
316
+ size: number;
317
+ /** Spread from midprice in basis points */
318
+ spreadBps: number;
319
+ }
270
320
  interface PoolAddresses {
271
321
  config: PublicKey;
272
322
  configBump: number;
@@ -394,10 +444,153 @@ declare class Hadron {
394
444
  setPoolState(authority: PublicKey, params: SetPoolStateParams): TransactionInstruction;
395
445
  /** Build update delta staleness instruction. */
396
446
  updateDeltaStaleness(authority: PublicKey, params: UpdateDeltaStalenessParams): TransactionInstruction;
447
+ /** Build initialize spread config instruction. */
448
+ initializeSpreadConfig(payer: PublicKey, authority: PublicKey, params: InitializeSpreadConfigParams): TransactionInstruction;
449
+ /** Build update spread config instruction (full replacement). */
450
+ updateSpreadConfig(admin: PublicKey, params: UpdateSpreadConfigParams): TransactionInstruction;
451
+ /**
452
+ * Fetch current spread triggers, append new ones, and return the update ix.
453
+ * If a trigger for the same account already exists, its spreadBps is updated.
454
+ */
455
+ addSpreadTriggers(admin: PublicKey, triggers: SpreadTriggerInput[]): Promise<TransactionInstruction>;
456
+ /**
457
+ * Fetch current spread triggers, remove the given accounts, and return the update ix.
458
+ */
459
+ removeSpreadTriggers(admin: PublicKey, accounts: PublicKey[]): Promise<TransactionInstruction>;
460
+ /** Fetch and decode the current spread config triggers from chain. */
461
+ private fetchSpreadTriggers;
397
462
  /** Build close pool instruction. */
398
463
  closePool(authority: PublicKey): TransactionInstruction;
399
464
  }
400
465
 
466
+ /**
467
+ * High-level orderbook abstraction over a Hadron pool.
468
+ *
469
+ * Maps limit orders to risk curve points using `CurveXMode.Alternate`
470
+ * (absolute vault balance x-axis) and `RiskMode.Integrated`.
471
+ *
472
+ * ```ts
473
+ * const book = await HadronOrderbook.load({ connection, pool: poolAddress });
474
+ * book.placeOrder({ side: "bid", size: 100, spreadBps: 10 });
475
+ * book.placeOrder({ side: "ask", size: 100, spreadBps: 10 });
476
+ * const ixs = book.push(authority);
477
+ * ```
478
+ */
479
+ declare class HadronOrderbook {
480
+ /** Underlying Hadron pool instance. */
481
+ readonly pool: Hadron;
482
+ /** Decimals for token X (base). */
483
+ readonly decimalsX: number;
484
+ /** Decimals for token Y (quote). */
485
+ readonly decimalsY: number;
486
+ /** Vault X balance at time of load (atoms). */
487
+ readonly initialVaultX: bigint;
488
+ /** Vault Y balance at time of load (atoms). */
489
+ readonly initialVaultY: bigint;
490
+ private bidOrders;
491
+ private askOrders;
492
+ private bidsDirty;
493
+ private asksDirty;
494
+ private priceCurvesSet;
495
+ private riskBidInitialized;
496
+ private riskAskInitialized;
497
+ private committedBidPoints;
498
+ private committedAskPoints;
499
+ private constructor();
500
+ /**
501
+ * Load an orderbook from an existing on-chain pool.
502
+ * Fetches decimals and vault balances, and reconstructs staged orders
503
+ * from the active risk curves.
504
+ */
505
+ static load(params: {
506
+ connection: Connection;
507
+ pool: PublicKey;
508
+ }): Promise<HadronOrderbook>;
509
+ /**
510
+ * Wrap an existing Hadron instance as an orderbook.
511
+ * Useful for tests or when you already have the pool loaded.
512
+ */
513
+ static fromPool(pool: Hadron, decimalsX: number, decimalsY: number, initialVaultX: bigint, initialVaultY: bigint): HadronOrderbook;
514
+ /**
515
+ * Place a new order. Orders are staged locally and pushed on-chain via `push()`.
516
+ * Orders on each side are sorted by spreadBps ascending (tightest first).
517
+ * @throws If more than 31 orders on a side.
518
+ */
519
+ placeOrder(params: PlaceOrderParams): void;
520
+ /**
521
+ * Amend an existing order at the given level index.
522
+ * Re-sorts if spread changes.
523
+ * @throws On invalid index.
524
+ */
525
+ amendOrder(params: AmendOrderParams): void;
526
+ /**
527
+ * Cancel the order at the given level index.
528
+ * @throws On invalid index.
529
+ */
530
+ cancelOrder(params: CancelOrderParams): void;
531
+ /** Cancel all orders on one or both sides. */
532
+ cancelAll(side?: OrderSide): void;
533
+ /** Read-only access to staged bid orders. */
534
+ getBids(): readonly StagedOrder[];
535
+ /** Read-only access to staged ask orders. */
536
+ getAsks(): readonly StagedOrder[];
537
+ /**
538
+ * Build transaction instructions to push the current staged orders on-chain.
539
+ *
540
+ * 1. On first push, sets flat price curves (factor=1.0, Step interpolation).
541
+ * 2. If risk curves not yet initialized, uses setRiskCurveAbsolute (sets headers).
542
+ * 3. On subsequent pushes, computes a minimal diff and uses curve updates
543
+ * (submit + apply) when possible, falling back to full rewrite for large diffs.
544
+ */
545
+ push(authority: PublicKey): TransactionInstruction[];
546
+ /** Build an updateMidprice instruction. */
547
+ updateMidprice(authority: PublicKey, midprice: number, sequence?: bigint): TransactionInstruction;
548
+ /** Build a deposit instruction. */
549
+ deposit(user: PublicKey, params: DepositParams): TransactionInstruction;
550
+ /** Build a withdraw instruction. */
551
+ withdraw(user: PublicKey, params: WithdrawParams): TransactionInstruction;
552
+ /** Build a setPoolState instruction. */
553
+ setPoolState(authority: PublicKey, params: SetPoolStateParams): TransactionInstruction;
554
+ /**
555
+ * Get the current book state by reading on-chain risk curves + midprice.
556
+ * Reconstructs levels from curve points.
557
+ */
558
+ getBookState(): OrderbookState;
559
+ /**
560
+ * Compute the minimal set of curve update ops to transform `committed` into `desired`.
561
+ *
562
+ * Algorithm:
563
+ * 1. Scan left-to-right for factor-only diffs (amountIn unchanged) → Edit ops.
564
+ * 2. At the first structural diff (amountIn changed or length mismatch),
565
+ * truncate-and-rebuild: remove all from that index to end, then add desired.
566
+ * 3. Returns the ops array.
567
+ */
568
+ static computeCurveOps(committed: CurvePoint[], desired: CurvePoint[], curveType: CurveType): CurveUpdateOp[];
569
+ /** Convert SetRiskCurveAbsolutePointInput[] to CurvePoint[] for diffing. */
570
+ private static toCommittedPoints;
571
+ /**
572
+ * Build full setRiskCurveAbsolute instructions for sides that need initialization.
573
+ * After sending, snapshots committed points and marks sides as initialized.
574
+ */
575
+ private buildFullRiskCurveIxs;
576
+ /**
577
+ * Build curve update instructions (submit + apply pairs) for both sides.
578
+ * Falls back to full setRiskCurve rewrite if diff is too large.
579
+ */
580
+ private buildCurveUpdateIxs;
581
+ /** Fallback: full setRiskCurve rewrite for both sides. */
582
+ private buildFallbackRewrite;
583
+ private buildBidRiskPoints;
584
+ private buildAskRiskPoints;
585
+ /**
586
+ * Reconstruct staged orders from on-chain risk curves (after load).
587
+ * Assumes curves were set via this class (CurveXMode.Alternate, RiskMode.Integrated, Step).
588
+ */
589
+ private reconstructFromCurves;
590
+ private reconstructSide;
591
+ private curveSideToLevels;
592
+ }
593
+
401
594
  declare const HADRON_PROGRAM_ID: PublicKey;
402
595
  declare const CONFIG_SEED: Buffer<ArrayBuffer>;
403
596
  declare const MIDPRICE_ORACLE_SEED: Buffer<ArrayBuffer>;
@@ -463,6 +656,7 @@ declare function decodeCurveMeta(data: Uint8Array): DecodedCurveMeta;
463
656
  */
464
657
  declare function isSlotInitialized(initializedSlots: Uint8Array, curveType: CurveType, slot: number, maxSlots: number): boolean;
465
658
  declare function decodeFeeConfig(data: Uint8Array): DecodedFeeConfig;
659
+ declare function decodeSpreadConfig(data: Uint8Array): DecodedSpreadConfig;
466
660
  declare function decodeCurveUpdates(data: Uint8Array): DecodedCurveUpdates;
467
661
  /**
468
662
  * Decode a single curve side from a CurvePrefabs account.
@@ -537,9 +731,9 @@ declare function buildWithdraw(user: PublicKey, configPda: PublicKey, mintX: Pub
537
731
  * user_source, vault_source, vault_dest, user_dest, fee_config,
538
732
  * fee_recipient_ata, clock, curve_updates.
539
733
  *
540
- * Optional (for introspection): spread_config, instructions_sysvar.
734
+ * When spread config is initialized: spread_config (#16) + instructions_sysvar (#17).
541
735
  */
542
- declare function buildSwapExactIn(user: PublicKey, poolAddresses: PoolAddresses, mintX: PublicKey, mintY: PublicKey, tokenProgramX: PublicKey, tokenProgramY: PublicKey, params: SwapParams, programId?: PublicKey): TransactionInstruction;
736
+ declare function buildSwapExactIn(user: PublicKey, poolAddresses: PoolAddresses, mintX: PublicKey, mintY: PublicKey, tokenProgramX: PublicKey, tokenProgramY: PublicKey, params: SwapParams, programId?: PublicKey, spreadConfigInitialized?: boolean): TransactionInstruction;
543
737
 
544
738
  /**
545
739
  * Build a SetCurve instruction (price curve).
@@ -673,4 +867,4 @@ declare function buildUpdateDeltaStaleness(authority: PublicKey, configPda: Publ
673
867
  */
674
868
  declare function buildClosePool(authority: PublicKey, configPda: PublicKey, midpriceOraclePda: PublicKey, curveMetaPda: PublicKey, curvePrefabsPda: PublicKey, curveUpdatesPda: PublicKey, vaultX: PublicKey, vaultY: PublicKey, tokenProgramX: PublicKey, tokenProgramY: PublicKey, spreadConfigInitialized?: boolean, programId?: PublicKey): TransactionInstruction;
675
869
 
676
- export { ABSOLUTE_MAX_CURVE_POINTS, ABSOLUTE_MAX_PREFAB_SLOTS, type AllocateCurvePrefabsParams, CONFIG_SEED, CONFIG_SIZE, CURVE_META_SEED, CURVE_META_SIZE, CURVE_POINT_LEN, CURVE_PREFABS_SEED, CURVE_SIDE_HEADER, CURVE_UPDATES_SEED, CURVE_UPDATES_SIZE, CURVE_UPDATE_OP_SIZE, type CurvePoint, type CurveSide, CurveType, type CurveUpdateOp, CurveUpdateOpKind, CurveXMode, DEFAULT_MAX_CURVE_POINTS, DEFAULT_MAX_PREFAB_SLOTS, type DecodedConfig, type DecodedCurveMeta, type DecodedCurveUpdates, type DecodedFeeConfig, type DecodedMidpriceOracle, type DepositParams, Discriminator, FEE_CONFIG_SEED, FEE_CONFIG_SIZE, HADRON_PROGRAM_ID, Hadron, type InitializeFeeConfigParams, type InitializeParams, type InitializeSpreadConfigParams, Interpolation, MAX_CURVE_UPDATE_OPS, MAX_SETCURVE_POINTS, MIDPRICE_ORACLE_SEED, MIDPRICE_ORACLE_SIZE, type NominateAuthorityParams, OracleMode, POINT_DATA_SIZE, type PoolAddresses, PoolState, Q32_ONE, RiskMode, type RotateFeeAdminParams, SPREAD_CONFIG_SEED, type SetCurveBothParams, type SetCurveParams, type SetCurvePointInput, type SetPoolStateParams, type SetQuotingAuthorityParams, type SetRiskCurveAbsoluteBothParams, type SetRiskCurveAbsoluteParams, type SetRiskCurveAbsolutePointInput, type SetRiskCurveBothParams, type SetRiskCurveParams, type SetRiskCurvePointInput, Side, type SpreadTriggerInput, type SwapParams, type SwitchCurveParams, type UpdateBaseSpreadParams, type UpdateDeltaStalenessParams, type UpdateFeeConfigParams, type UpdateMidpriceAndBaseSpreadParams, type UpdateMidpriceParams, type UpdateSpreadConfigParams, type WithdrawParams, buildAcceptAuthority, buildAllocateCurvePrefabs, buildApplyCurveUpdates, buildClosePool, buildDeposit, buildInitialize, buildInitializeFeeConfig, buildInitializeSpreadConfig, buildNominateAuthority, buildRotateFeeAdmin, buildSetCurve, buildSetCurveBoth, buildSetPoolState, buildSetQuotingAuthority, buildSetRiskCurve, buildSetRiskCurveAbsolute, buildSetRiskCurveAbsoluteBoth, buildSetRiskCurveBoth, buildSubmitCurveUpdates, buildSwapExactIn, buildSwitchPriceCurve, buildSwitchRiskCurve, buildUpdateBaseSpread, buildUpdateDeltaStaleness, buildUpdateFeeConfig, buildUpdateMidprice, buildUpdateMidpriceAndBaseSpread, buildUpdateSpreadConfig, buildWithdraw, curvePrefabsSize, decodeActiveCurves, decodeConfig, decodeCurveMeta, decodeCurveSide, decodeCurveUpdates, decodeFeeConfig, decodeMidpriceOracle, derivePoolAddresses, fromQ32, getConfigAddress, getCurveMetaAddress, getCurvePrefabsAddress, getCurveUpdatesAddress, getFeeConfigAddress, getMidpriceOracleAddress, getOrCreateAta, getSpreadConfigAddress, isSlotInitialized, pctToQ32, toQ32 };
870
+ export { ABSOLUTE_MAX_CURVE_POINTS, ABSOLUTE_MAX_PREFAB_SLOTS, type AllocateCurvePrefabsParams, type AmendOrderParams, CONFIG_SEED, CONFIG_SIZE, CURVE_META_SEED, CURVE_META_SIZE, CURVE_POINT_LEN, CURVE_PREFABS_SEED, CURVE_SIDE_HEADER, CURVE_UPDATES_SEED, CURVE_UPDATES_SIZE, CURVE_UPDATE_OP_SIZE, type CancelOrderParams, type CurvePoint, type CurveSide, CurveType, type CurveUpdateOp, CurveUpdateOpKind, CurveXMode, DEFAULT_MAX_CURVE_POINTS, DEFAULT_MAX_PREFAB_SLOTS, type DecodedConfig, type DecodedCurveMeta, type DecodedCurveUpdates, type DecodedFeeConfig, type DecodedMidpriceOracle, type DecodedSpreadConfig, type DepositParams, Discriminator, FEE_CONFIG_SEED, FEE_CONFIG_SIZE, HADRON_PROGRAM_ID, Hadron, HadronOrderbook, type InitializeFeeConfigParams, type InitializeParams, type InitializeSpreadConfigParams, Interpolation, MAX_CURVE_UPDATE_OPS, MAX_SETCURVE_POINTS, MIDPRICE_ORACLE_SEED, MIDPRICE_ORACLE_SIZE, type NominateAuthorityParams, OracleMode, type OrderSide, type OrderbookLevel, type OrderbookState, POINT_DATA_SIZE, type PlaceOrderParams, type PoolAddresses, PoolState, Q32_ONE, RiskMode, type RotateFeeAdminParams, SPREAD_CONFIG_SEED, type SetCurveBothParams, type SetCurveParams, type SetCurvePointInput, type SetPoolStateParams, type SetQuotingAuthorityParams, type SetRiskCurveAbsoluteBothParams, type SetRiskCurveAbsoluteParams, type SetRiskCurveAbsolutePointInput, type SetRiskCurveBothParams, type SetRiskCurveParams, type SetRiskCurvePointInput, Side, type SpreadTriggerInput, type StagedOrder, type SwapParams, type SwitchCurveParams, type UpdateBaseSpreadParams, type UpdateDeltaStalenessParams, type UpdateFeeConfigParams, type UpdateMidpriceAndBaseSpreadParams, type UpdateMidpriceParams, type UpdateSpreadConfigParams, type WithdrawParams, buildAcceptAuthority, buildAllocateCurvePrefabs, buildApplyCurveUpdates, buildClosePool, buildDeposit, buildInitialize, buildInitializeFeeConfig, buildInitializeSpreadConfig, buildNominateAuthority, buildRotateFeeAdmin, buildSetCurve, buildSetCurveBoth, buildSetPoolState, buildSetQuotingAuthority, buildSetRiskCurve, buildSetRiskCurveAbsolute, buildSetRiskCurveAbsoluteBoth, buildSetRiskCurveBoth, buildSubmitCurveUpdates, buildSwapExactIn, buildSwitchPriceCurve, buildSwitchRiskCurve, buildUpdateBaseSpread, buildUpdateDeltaStaleness, buildUpdateFeeConfig, buildUpdateMidprice, buildUpdateMidpriceAndBaseSpread, buildUpdateSpreadConfig, buildWithdraw, curvePrefabsSize, decodeActiveCurves, decodeConfig, decodeCurveMeta, decodeCurveSide, decodeCurveUpdates, decodeFeeConfig, decodeMidpriceOracle, decodeSpreadConfig, derivePoolAddresses, fromQ32, getConfigAddress, getCurveMetaAddress, getCurvePrefabsAddress, getCurveUpdatesAddress, getFeeConfigAddress, getMidpriceOracleAddress, getOrCreateAta, getSpreadConfigAddress, isSlotInitialized, pctToQ32, toQ32 };