@mysten/deepbook-v3 2.9.2 → 2.10.1

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 (204) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +21 -0
  3. package/dist/account-bindings/account-registry.d.mts +109 -0
  4. package/dist/account-bindings/account-registry.d.mts.map +1 -0
  5. package/dist/account-bindings/account-registry.mjs +56 -0
  6. package/dist/account-bindings/account-registry.mjs.map +1 -0
  7. package/dist/account-bindings/account.d.mts +176 -0
  8. package/dist/account-bindings/account.d.mts.map +1 -0
  9. package/dist/account-bindings/account.mjs +94 -0
  10. package/dist/account-bindings/account.mjs.map +1 -0
  11. package/dist/account-bindings/latest.d.mts +12 -0
  12. package/dist/account-bindings/latest.d.mts.map +1 -0
  13. package/dist/account-bindings/latest.mjs +19 -0
  14. package/dist/account-bindings/latest.mjs.map +1 -0
  15. package/dist/account.d.mts +46 -3
  16. package/dist/account.d.mts.map +1 -1
  17. package/dist/account.mjs +51 -2
  18. package/dist/account.mjs.map +1 -1
  19. package/dist/contracts/account/account.d.mts +25 -97
  20. package/dist/contracts/account/account.d.mts.map +1 -1
  21. package/dist/contracts/account/account.mjs +43 -35
  22. package/dist/contracts/account/account.mjs.map +1 -1
  23. package/dist/contracts/account/account_events.d.mts +20 -20
  24. package/dist/contracts/account/account_events.d.mts.map +1 -1
  25. package/dist/contracts/account/account_registry.d.mts +7 -54
  26. package/dist/contracts/account/account_registry.d.mts.map +1 -1
  27. package/dist/contracts/account/account_registry.mjs +2 -22
  28. package/dist/contracts/account/account_registry.mjs.map +1 -1
  29. package/dist/contracts/deepbook/account.d.mts +18 -18
  30. package/dist/contracts/deepbook/balances.d.mts +4 -4
  31. package/dist/contracts/deepbook/deep_price.d.mts +3 -3
  32. package/dist/contracts/deepbook/order.d.mts +12 -12
  33. package/dist/contracts/deepbook_predict/admin.d.mts +4 -4
  34. package/dist/contracts/deepbook_predict/admin.d.mts.map +1 -1
  35. package/dist/contracts/deepbook_predict/builder_code.d.mts +60 -13
  36. package/dist/contracts/deepbook_predict/builder_code.d.mts.map +1 -1
  37. package/dist/contracts/deepbook_predict/builder_code.mjs +55 -1
  38. package/dist/contracts/deepbook_predict/builder_code.mjs.map +1 -1
  39. package/dist/contracts/deepbook_predict/builder_code_events.d.mts +10 -10
  40. package/dist/contracts/deepbook_predict/config_events.d.mts +88 -84
  41. package/dist/contracts/deepbook_predict/config_events.d.mts.map +1 -1
  42. package/dist/contracts/deepbook_predict/config_events.mjs +8 -0
  43. package/dist/contracts/deepbook_predict/config_events.mjs.map +1 -1
  44. package/dist/contracts/deepbook_predict/expiry_market.d.mts +262 -101
  45. package/dist/contracts/deepbook_predict/expiry_market.d.mts.map +1 -1
  46. package/dist/contracts/deepbook_predict/expiry_market.mjs +320 -41
  47. package/dist/contracts/deepbook_predict/expiry_market.mjs.map +1 -1
  48. package/dist/contracts/deepbook_predict/market_lifecycle_cap.d.mts +5 -5
  49. package/dist/contracts/deepbook_predict/market_manager.d.mts +27 -27
  50. package/dist/contracts/deepbook_predict/order_events.d.mts +56 -54
  51. package/dist/contracts/deepbook_predict/order_events.d.mts.map +1 -1
  52. package/dist/contracts/deepbook_predict/order_events.mjs.map +1 -1
  53. package/dist/contracts/deepbook_predict/pause_cap.d.mts +5 -5
  54. package/dist/contracts/deepbook_predict/plp.d.mts +74 -74
  55. package/dist/contracts/deepbook_predict/plp.d.mts.map +1 -1
  56. package/dist/contracts/deepbook_predict/pool_valuation_cap.d.mts +5 -5
  57. package/dist/contracts/deepbook_predict/predict_account.d.mts +22 -17
  58. package/dist/contracts/deepbook_predict/predict_account.d.mts.map +1 -1
  59. package/dist/contracts/deepbook_predict/predict_account.mjs +12 -6
  60. package/dist/contracts/deepbook_predict/predict_account.mjs.map +1 -1
  61. package/dist/contracts/deepbook_predict/pricing.d.mts +67 -67
  62. package/dist/contracts/deepbook_predict/pricing.d.mts.map +1 -1
  63. package/dist/contracts/deepbook_predict/protocol_config.d.mts +127 -83
  64. package/dist/contracts/deepbook_predict/protocol_config.d.mts.map +1 -1
  65. package/dist/contracts/deepbook_predict/protocol_config.mjs +59 -1
  66. package/dist/contracts/deepbook_predict/protocol_config.mjs.map +1 -1
  67. package/dist/contracts/deepbook_predict/range_codec.d.mts +2 -2
  68. package/dist/contracts/deepbook_predict/registry.d.mts +32 -32
  69. package/dist/contracts/deepbook_predict/vault_events.d.mts +131 -131
  70. package/dist/contracts/deepbook_predict_math/lazer_price.d.mts +13 -13
  71. package/dist/contracts/deepbook_predict_math/math.d.mts +14 -14
  72. package/dist/contracts/deepbook_predict_orders/delayed_execution_config.d.mts +30 -30
  73. package/dist/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.mjs +6 -0
  74. package/dist/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.mjs.map +1 -1
  75. package/dist/contracts/deepbook_predict_orders/desk.d.mts +28 -28
  76. package/dist/contracts/deepbook_predict_orders/order_queue.d.mts +187 -187
  77. package/dist/contracts/deepbook_predict_orders/queue.d.mts +240 -62
  78. package/dist/contracts/deepbook_predict_orders/queue.d.mts.map +1 -1
  79. package/dist/contracts/deepbook_predict_orders/queue.mjs +306 -41
  80. package/dist/contracts/deepbook_predict_orders/queue.mjs.map +1 -1
  81. package/dist/contracts/deepbook_predict_orders/queue_events.d.mts +140 -140
  82. package/dist/contracts/deepbook_sessions/session_config.d.mts +8 -8
  83. package/dist/contracts/deepbook_sessions/session_config.d.mts.map +1 -1
  84. package/dist/contracts/deepbook_sessions/sessions.d.mts +271 -31
  85. package/dist/contracts/deepbook_sessions/sessions.d.mts.map +1 -1
  86. package/dist/contracts/deepbook_sessions/sessions.mjs +363 -3
  87. package/dist/contracts/deepbook_sessions/sessions.mjs.map +1 -1
  88. package/dist/deployments/mainnet.mjs.map +1 -1
  89. package/dist/deployments/testnet.d.mts.map +1 -1
  90. package/dist/deployments/testnet.mjs +7 -4
  91. package/dist/deployments/testnet.mjs.map +1 -1
  92. package/dist/predict/bindings/expiry-market.d.mts +57 -7
  93. package/dist/predict/bindings/expiry-market.d.mts.map +1 -1
  94. package/dist/predict/bindings/expiry-market.mjs +48 -2
  95. package/dist/predict/bindings/expiry-market.mjs.map +1 -1
  96. package/dist/predict/bindings/protocol-config.d.mts +5 -5
  97. package/dist/predict/bindings/protocol-config.mjs +4 -1
  98. package/dist/predict/bindings/protocol-config.mjs.map +1 -1
  99. package/dist/predict/bindings/queue.d.mts +30 -0
  100. package/dist/predict/bindings/queue.d.mts.map +1 -0
  101. package/dist/predict/bindings/queue.mjs +59 -0
  102. package/dist/predict/bindings/queue.mjs.map +1 -0
  103. package/dist/predict/bindings/rename.mjs +5 -1
  104. package/dist/predict/bindings/rename.mjs.map +1 -1
  105. package/dist/predict/client.d.mts.map +1 -1
  106. package/dist/predict/client.mjs +11 -5
  107. package/dist/predict/client.mjs.map +1 -1
  108. package/dist/predict/config/generated.d.mts +1 -1
  109. package/dist/predict/config/generated.d.mts.map +1 -1
  110. package/dist/predict/config/generated.mjs +1 -0
  111. package/dist/predict/config/generated.mjs.map +1 -1
  112. package/dist/predict/config/mainnet.mjs +3 -1
  113. package/dist/predict/config/mainnet.mjs.map +1 -1
  114. package/dist/predict/config/testnet.mjs +3 -1
  115. package/dist/predict/config/testnet.mjs.map +1 -1
  116. package/dist/predict/config/types.d.mts +23 -0
  117. package/dist/predict/config/types.d.mts.map +1 -1
  118. package/dist/predict/cost.d.mts +9 -1
  119. package/dist/predict/cost.d.mts.map +1 -1
  120. package/dist/predict/cost.mjs.map +1 -1
  121. package/dist/predict/errors.d.mts.map +1 -1
  122. package/dist/predict/errors.mjs +6 -2
  123. package/dist/predict/errors.mjs.map +1 -1
  124. package/dist/predict/index.d.mts +1 -1
  125. package/dist/predict/index.mjs +2 -2
  126. package/dist/predict/queue.d.mts +8 -4
  127. package/dist/predict/queue.d.mts.map +1 -1
  128. package/dist/predict/queue.mjs +8 -4
  129. package/dist/predict/queue.mjs.map +1 -1
  130. package/dist/predict/reads/balances.mjs +1 -1
  131. package/dist/predict/reads/queue.d.mts +3 -2
  132. package/dist/predict/reads/queue.d.mts.map +1 -1
  133. package/dist/predict/reads/queue.mjs +5 -4
  134. package/dist/predict/reads/queue.mjs.map +1 -1
  135. package/dist/predict/tx/authed.mjs +1 -1
  136. package/dist/predict/tx/common.d.mts.map +1 -1
  137. package/dist/predict/tx/common.mjs +3 -2
  138. package/dist/predict/tx/common.mjs.map +1 -1
  139. package/dist/predict/tx/trade.d.mts.map +1 -1
  140. package/dist/predict/tx/trade.mjs +3 -2
  141. package/dist/predict/tx/trade.mjs.map +1 -1
  142. package/dist/sessions.d.mts +10 -1
  143. package/dist/sessions.d.mts.map +1 -1
  144. package/dist/sessions.mjs.map +1 -1
  145. package/dist/transactions/balanceManager.d.mts +12 -12
  146. package/dist/transactions/balanceManager.d.mts.map +1 -1
  147. package/dist/transactions/deepbook.d.mts +20 -20
  148. package/dist/transactions/deepbook.d.mts.map +1 -1
  149. package/dist/transactions/deepbookAdmin.d.mts +4 -4
  150. package/dist/transactions/deepbookAdmin.d.mts.map +1 -1
  151. package/dist/transactions/marginAdmin.d.mts +7 -7
  152. package/dist/transactions/marginAdmin.d.mts.map +1 -1
  153. package/dist/transactions/marginLiquidations.d.mts +3 -3
  154. package/dist/transactions/marginMaintainer.d.mts +5 -5
  155. package/dist/transactions/marginMaintainer.d.mts.map +1 -1
  156. package/dist/transactions/marginManager.d.mts +32 -32
  157. package/dist/transactions/marginManager.d.mts.map +1 -1
  158. package/dist/transactions/marginPool.d.mts +18 -18
  159. package/dist/transactions/marginPool.d.mts.map +1 -1
  160. package/dist/transactions/marginRegistry.d.mts +16 -16
  161. package/dist/transactions/marginTPSL.d.mts +10 -10
  162. package/dist/transactions/marginTPSL.d.mts.map +1 -1
  163. package/dist/transactions/poolProxy.d.mts +8 -8
  164. package/dist/transactions/poolProxy.d.mts.map +1 -1
  165. package/dist/utils/constants.d.mts.map +1 -1
  166. package/dist/utils/constants.mjs +2 -2
  167. package/dist/utils/constants.mjs.map +1 -1
  168. package/package.json +1 -1
  169. package/src/account-bindings/account-registry.ts +39 -0
  170. package/src/account-bindings/account.ts +73 -0
  171. package/src/account-bindings/latest.ts +41 -0
  172. package/src/account.ts +89 -5
  173. package/src/contracts/account/account.ts +73 -4
  174. package/src/contracts/account/account_registry.ts +1 -1
  175. package/src/contracts/deepbook_predict/builder_code.ts +94 -2
  176. package/src/contracts/deepbook_predict/config_events.ts +7 -0
  177. package/src/contracts/deepbook_predict/expiry_market.ts +490 -44
  178. package/src/contracts/deepbook_predict/order_events.ts +6 -4
  179. package/src/contracts/deepbook_predict/predict_account.ts +12 -6
  180. package/src/contracts/deepbook_predict/protocol_config.ts +85 -0
  181. package/src/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.ts +14 -0
  182. package/src/contracts/deepbook_predict_orders/order_flow.ts +4 -0
  183. package/src/contracts/deepbook_predict_orders/queue.ts +495 -9
  184. package/src/contracts/deepbook_sessions/sessions.ts +538 -3
  185. package/src/deployments/mainnet.ts +4 -4
  186. package/src/deployments/testnet.ts +18 -7
  187. package/src/deployments/types.ts +14 -0
  188. package/src/predict/bindings/expiry-market.ts +87 -0
  189. package/src/predict/bindings/queue.ts +42 -0
  190. package/src/predict/bindings/rename.ts +5 -1
  191. package/src/predict/client.ts +25 -3
  192. package/src/predict/config/generated.ts +3 -0
  193. package/src/predict/config/mainnet.ts +4 -0
  194. package/src/predict/config/testnet.ts +4 -0
  195. package/src/predict/config/types.ts +23 -0
  196. package/src/predict/cost.ts +9 -1
  197. package/src/predict/errors.ts +11 -1
  198. package/src/predict/index.ts +1 -1
  199. package/src/predict/queue.ts +8 -4
  200. package/src/predict/reads/queue.ts +7 -4
  201. package/src/predict/tx/common.ts +2 -0
  202. package/src/predict/tx/trade.ts +3 -1
  203. package/src/sessions.ts +10 -1
  204. package/src/utils/constants.ts +8 -3
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/predict/errors.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Typed errors for the Predict SDK.\n//\n// Two failure kinds cross the SDK boundary:\n// - PredictInputError — a caller gave us something we rejected before touching\n// the chain (unknown underlying, malformed argument, …).\n// - PredictMoveError — a Move `abort` surfaced by a read/simulate. Predict's error\n// constants are plain `u64` codes, not clever errors, so the fullnode can't name\n// them: `decodeMoveAbort` maps `(module, code)` to the constant name with\n// ABORT_NAMES below. A clever-error name the fullnode does decode takes precedence.\n\n/** A caller-supplied argument the SDK rejected before building/sending a tx. */\nexport class PredictInputError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'PredictInputError';\n\t}\n}\n\n/** A Move `abort` decoded from a simulate/read failure. */\nexport class PredictMoveError extends Error {\n\treadonly module: string;\n\t/** Exact u64 abort code — bigint because clever-error encodings pack data\n\t * into the high bits, which Number would silently truncate. */\n\treadonly code: bigint;\n\t/** The `E…` constant name: the fullnode's clever-error name when it decodes\n\t * one, else the name {@link ABORT_NAMES} gives the module's plain code, or null\n\t * when neither knows the abort. */\n\treadonly abortName: string | null;\n\n\tconstructor(module: string, code: bigint, abortName: string | null) {\n\t\tsuper(\n\t\t\tabortName\n\t\t\t\t? `Move abort in ${module}: ${abortName} (code ${code})`\n\t\t\t\t: `Move abort in ${module}: code ${code}`,\n\t\t);\n\t\tthis.name = 'PredictMoveError';\n\t\tthis.module = module;\n\t\tthis.code = code;\n\t\tthis.abortName = abortName;\n\t}\n}\n\n// The structured MoveAbort execution error surfaced by `@mysten/sui` on a failed\n// simulate/execute. Read structurally rather than via the client's exported\n// `SuiClientTypes.ExecutionError` (`@mysten/sui/client`) so mocked simulate results\n// and future API-shape drift still satisfy it — the same convention reads/inspect.ts\n// uses for its simulate seam. Field provenance:\n// - `MoveAbort.abortCode` → u64 abort code as a decimal string.\n// - `MoveAbort.location.module` → the aborting module's short name.\n// - `MoveAbort.cleverError.constantName` → the `E…` error constant, decoded by the\n// fullnode from the clever-error bits of the abort code and surfaced by the gRPC\n// (`grpc/core.ts` parseMoveAbort) and GraphQL transports. Only a clever-error abort\n// carries one, and Predict's plain `u64` constants never do, so ABORT_NAMES names\n// those. JSON-RPC surfaces no `constantName` at all.\nexport interface MoveAbortError {\n\tMoveAbort?: {\n\t\tabortCode?: string | number | bigint;\n\t\tlocation?: { module?: string };\n\t\tcleverError?: { constantName?: string };\n\t};\n}\n\n/**\n * The error constants of the Predict modules the SDK's flows abort in, by module, as an array\n * indexed by the plain `u64` abort code (each module numbers its constants from 0 with no gaps).\n * Generated from the Move sources at deepbookv3 29117434. A published code never changes meaning:\n * new codes only append, so an older package version's codes are a prefix of its module's list.\n * Keyed by module name only, as the abort location reports it, so a same-named module in an\n * unrelated package would be named from this table too.\n */\nexport const ABORT_NAMES: Readonly<Record<string, readonly string[]>> = Object.freeze({\n\t// Predict (`deepbook_predict`). Append-only since v1, so older package versions use a prefix.\n\texpiry_market: [\n\t\t'EMintPaused',\n\t\t'EMarketNotSettled',\n\t\t'EMintCostAboveMax',\n\t\t'EMintProbabilityAboveMax',\n\t\t'EWrongPricer',\n\t\t'EReferenceTickObservationMissing',\n\t\t'EMintRedeemSameTimestamp',\n\t\t'ERedeemProbabilityBelowMin',\n\t\t'ERedeemProceedsBelowMin',\n\t\t'EMintCostCapRequired',\n\t\t'EMarketNotPendingValuation',\n\t\t'EMintCostAboveMaxPayout',\n\t\t'ENotSettledRedeemKeeper',\n\t\t'EDelayedExecutionRequired',\n\t\t'EOrderFailsLimits',\n\t\t'EInsufficientMarketCash',\n\t\t'EInvalidOrderTiming',\n\t\t'EInvalidOrderTerms',\n\t\t'EWrongMarket',\n\t\t'EWrongStage',\n\t\t'ENotRecordOwner',\n\t\t'EEscrowMismatch',\n\t\t'EWrongPrice',\n\t],\n\tprotocol_config: [\n\t\t'ETradingPaused',\n\t\t'EValuationInProgress',\n\t\t'EValuationNotInProgress',\n\t\t'EPackageVersionDisabled',\n\t\t'EVersionWatermarkNotAdvanced',\n\t\t'EProtocolFrozen',\n\t\t'ESnapshotInProgress',\n\t\t'ETradeWindowClosed',\n\t\t'ESettledRedeemKeeperAlreadyAdded',\n\t\t'ESettledRedeemKeeperNotFound',\n\t\t'EFlushOperatorAlreadyAdded',\n\t\t'EFlushOperatorNotFound',\n\t\t'ENotFlushOperator',\n\t\t'ECutoverNotReached',\n\t\t'EEwmaRetired',\n\t\t'EOrderFlowNotAllowed',\n\t],\n\t// Predict's live pricer, which every quote, plan and enqueue loads.\n\tpricing: [\n\t\t'EZeroForward',\n\t\t'ECannotBeNegative',\n\t\t'ENonPositiveVariance',\n\t\t'EInvalidRange',\n\t\t'EBlockScholesPriceStale',\n\t\t'EBlockScholesInputsInvalid',\n\t\t'EPythSpotInvalid',\n\t\t'EWrongPythFeed',\n\t\t'EWrongBlockScholesValueStore',\n\t\t'ELivePricingExpired',\n\t\t'EBlockScholesSVIStale',\n\t\t'EWrongBlockScholesSVIStore',\n\t\t'EBlockScholesPriceUnavailable',\n\t\t'EBlockScholesSVIUnavailable',\n\t\t'EBlockScholesMinVarianceInvalid',\n\t\t'EOracleWrittenInThisTransaction',\n\t\t'EBlockScholesInputTooWide',\n\t\t'EPythSpotUnavailable',\n\t\t'EPythSpotStale',\n\t\t'EPythForwardRequired',\n\t],\n\t// Admission, positions and the LP pool. `order` and `registry` are left out: DeepBook's core\n\t// package has modules of the same names, which this table would misname.\n\tstrike_exposure: [\n\t\t'EInvalidCloseQuantity',\n\t\t'EInvalidAdmissionTick',\n\t\t'EInvalidReferenceTick',\n\t\t'EReferenceTickAlreadySet',\n\t\t'ETermsExposureMismatch',\n\t\t'EMintQuantityBelowMin',\n\t\t'EInvalidInventoryImpactScale',\n\t],\n\tstrike_exposure_config: [\n\t\t'EEntryProbabilityOutOfBounds',\n\t\t'EInvalidEntryProbabilityBound',\n\t\t'EInvalidFeeProbability',\n\t\t'EPremiumBelowMinimum',\n\t],\n\tstrike_payout_tree: [\n\t\t'EInsufficientPayoutQuantity',\n\t\t'EMaxPayoutTreeNodes',\n\t\t'ENonMonotonePrice',\n\t\t'EStaleValuationSnapshot',\n\t\t'ESnapshotSeqNotIncreasing',\n\t\t'ENodeMissing',\n\t],\n\texpiry_cash: ['EInsufficientCash', 'EInventoryImpactRebateExceedsReserve'],\n\tpredict_account: ['EPositionAlreadyExists', 'EPositionNotFound'],\n\tbuilder_code: ['ENotOwner'],\n\tplp: [\n\t\t'EMissingExpiryValuation',\n\t\t'ENotBootstrapped',\n\t\t'EAlreadyBootstrapped',\n\t\t'EBelowMinBootstrapLiquidity',\n\t\t'EBelowMinFeeIncentiveSponsorship',\n\t\t'EMaxLiveExpiryMarketsExceeded',\n\t\t'EValuationSnapshotNotSealed',\n\t\t'EExpiryPricerAlreadySnapshotted',\n\t\t'EIncompleteValuationSnapshot',\n\t\t'EExpiredMarketNotSettled',\n\t\t'EValuationWindowExpired',\n\t\t'ESnapshotStageOpen',\n\t\t'EBelowMinUsdcContribution',\n\t\t'EContributionExceedsPriceCeiling',\n\t\t'EInsufficientFeeIncentiveReserve',\n\t],\n\tlp_book: [\n\t\t'ERequestNotFound',\n\t\t'EBelowMinSupplyRequest',\n\t\t'EBelowMinWithdrawRequest',\n\t\t'ENotRequestOwner',\n\t],\n\tpool_accounting: [\n\t\t'EUnknownRegisteredExpiry',\n\t\t'ERegisteredExpiryAlreadyExists',\n\t\t'EMaxExpiryFundingExceeded',\n\t\t'ETerminalAccountingStarted',\n\t],\n\t// The order-flow package (`deepbook_predict_orders`).\n\tqueue: [\n\t\t'EWrongDesk',\n\t\t'EWrongMarket',\n\t\t'EQueueStuck',\n\t\t'EQueueFull',\n\t\t'EAccountOrderCap',\n\t\t'EPastCutoff',\n\t\t'EMintCostCapRequired',\n\t\t'EFeeNotCovered',\n\t\t'EBelowMinSell',\n\t\t'ERecordNotOpen',\n\t\t'ENotRecordOwner',\n\t\t'EMarketNotSettled',\n\t\t'EMarketNotExpired',\n\t],\n\tdesk: ['EPackageVersionDisabled', 'EVersionWatermarkNotAdvanced', 'EProtocolFrozen'],\n\torder_queue: ['ERecordNotOpen'],\n\tdelayed_execution_config: [\n\t\t'EInvalidDelayMs',\n\t\t'EInvalidStallTimeoutMs',\n\t\t'EInvalidStuckThresholdMs',\n\t\t'EInvalidGapWaitMs',\n\t\t'EInvalidPythPriceBufferMs',\n\t\t'EInvalidSviMaxAgeMs',\n\t\t'EInvalidMintCapacity',\n\t\t'EInvalidSellCapacity',\n\t\t'EInvalidPerAccountCap',\n\t\t'EInvalidMinSellQuantity',\n\t\t'EInvalidOrderFee',\n\t\t'EInvalidSettleRefundBatch',\n\t\t'EInvalidSettlePayoutBatch',\n\t\t'EUnsupportedPythChannel',\n\t\t'EInvalidTiming',\n\t\t'EInvalidLimits',\n\t],\n\t// The math library (`deepbook_predict_math`).\n\tlazer_price: ['EPropertyNotRequested', 'EGenerationAfterEnvelope', 'EFeedMissing'],\n\t// Sessions (`deepbook_sessions`), which the `/sessions` Predict wrappers abort in.\n\tsessions: ['EInvalidSessionDuration', 'ESessionNotAuthorized', 'ESessionLimitExceeded'],\n\tsession_config: ['EPackageVersionDisabled', 'EVersionWatermarkNotAdvanced'],\n\t// The shared account (`deepbook_account`).\n\taccount_registry: ['EAppAlreadyAuthorized', 'EAppNotAuthorized', 'EAccountAlreadyExists'],\n});\n\n/** `std::option::EOPTION_NOT_SET`. */\nconst OPTION_NOT_SET = 0x40001n;\n\n/**\n * The constant name of a plain `u64` abort `code` in `module`, from {@link ABORT_NAMES}, or null\n * when the module or the code is unknown.\n */\nexport function abortNameFor(module: string, code: bigint): string | null {\n\t// The order-fee guard (`queueTx.assertOrderFeeAtMost`) aborts in the standard library's\n\t// `option`, whose constant isn't an index.\n\tif (module === 'option' && code === OPTION_NOT_SET) return 'EOPTION_NOT_SET';\n\t// Own keys only: a module named like an `Object.prototype` member is simply unknown.\n\tif (!Object.hasOwn(ABORT_NAMES, module)) return null;\n\tconst names = ABORT_NAMES[module];\n\tif (code < 0n || code >= BigInt(names.length)) return null;\n\treturn names[Number(code)];\n}\n\n/**\n * Decode a `@mysten/sui` MoveAbort execution error into a {@link PredictMoveError}.\n * Returns null when `error` carries no MoveAbort (InsufficientGas, a size error, any\n * non-abort failure), so callers can fall back to a plain Error.\n *\n * `abortName` is the chain-decoded clever-error constant when the fullnode surfaces one, and\n * otherwise the name {@link ABORT_NAMES} gives the module's plain code (Predict's constants are\n * plain codes, so this is the usual path). It is null when neither knows the abort.\n * `code` stays a bigint — a clever-error abort code packs the module, line, and\n * constant index into the high bits of the u64 and would lose precision as a Number.\n */\nexport function decodeMoveAbort(error: MoveAbortError | null | undefined): PredictMoveError | null {\n\tconst abort = error?.MoveAbort;\n\tif (!abort) return null;\n\tconst module = abort.location?.module ?? '';\n\tconst code = abort.abortCode != null ? BigInt(abort.abortCode) : 0n;\n\tconst abortName = abort.cleverError?.constantName ?? abortNameFor(module, code);\n\treturn new PredictMoveError(module, code, abortName);\n}\n\n// === Delayed execution (DBU-885) ===\n\n/**\n * Why a queued-order builder refused to add an enqueue. The builder reads the market first and\n * throws this instead of building a transaction the queue or protocol gates would abort, so a\n * refused order never fails the rest of a transaction. Each code mirrors one on-chain refusal. The\n * order's own limits at the current price are checked only on chain (`EOrderFailsLimits`).\n */\nexport type PredictPreflightCode =\n\t/**\n\t * Delayed execution isn't live: Predict's version watermark isn't raised\n\t * (`ECutoverNotReached`), or Predict doesn't allowlist the order-flow package yet\n\t * (`EOrderFlowNotAllowed`).\n\t */\n\t| 'not-live'\n\t/** The market has no `MarketQueue` yet: `queue::create_and_share` hasn't run for it. */\n\t| 'no-queue'\n\t/**\n\t * A version floor retired code this SDK calls: Predict's watermark is above the Predict\n\t * version it was built for (`protocol_config::EPackageVersionDisabled`), or the order desk's\n\t * floor is above its order-flow package (`desk::EPackageVersionDisabled`). Update the SDK.\n\t */\n\t| 'retired'\n\t/** Trading is paused, the protocol is frozen, or minting is paused on this market. */\n\t| 'paused'\n\t/** The market's pricing is delayed (`queue_stuck`). Enqueue aborts `EQueueStuck`. */\n\t| 'stuck'\n\t/**\n\t * The order's τ would land at or after the market's order cutoff (`EPastCutoff`). A\n\t * `read.planMint` or `read.planSell` plan on a market past its expiry throws it too, since the\n\t * chain has no live price to quote (`ELivePricingExpired`).\n\t */\n\t| 'past-cutoff'\n\t/** The market has its maximum unfinished mints or sells (`EQueueFull`). */\n\t| 'queue-full'\n\t/** The account has its maximum unfinished orders in this market (`EAccountOrderCap`). */\n\t| 'account-cap'\n\t/**\n\t * The account balance doesn't cover the order fee (`EFeeNotCovered`). A `read.planMint` plan\n\t * also reports it when the balance doesn't cover the plan's `totalDebit`, since its limits assume\n\t * the whole budget, or when the owner has no account yet. Prompt a top-up.\n\t */\n\t| 'fee'\n\t/** A mint's cash need is above the market's spare cash (`EInsufficientMarketCash`). */\n\t| 'market-cash'\n\t/**\n\t * The escrowed budget, or an exact-amount mint's premium cap, can't buy the minimum premium,\n\t * so the order fails its limits. A budget `read.planMint` plan also reports it when what the\n\t * budget buys without the fee subsidy, as admission prices it, has a premium below the minimum,\n\t * and throws it for a budget below the minimum premium or one no fill clears it with.\n\t */\n\t| 'min-premium'\n\t/**\n\t * The strike's entry probability is outside the market's entry band, so the chain refuses to\n\t * quote or admit it (`EOrderFailsLimits`). Pick a strike nearer the money. Only `read.planMint`\n\t * reports it, and the probability can still leave the band between plan and placement.\n\t */\n\t| 'entry-band'\n\t/**\n\t * The order's all-in cost without the fee subsidy is above its payout, so admission refuses it\n\t * at any slippage (`EOrderFailsLimits`), or for a budget, the fill costs about its payout, where\n\t * admission's sizing can't be previewed. Only `read.planMint` reports it, near a certain outcome.\n\t */\n\t| 'cost-above-payout'\n\t/** A sell is below the policy minimum, or leaves a remainder below it (`EBelowMinSell`). */\n\t| 'below-min-sell'\n\t/** The record to sell is missing or not Open (`ERecordNotOpen`). */\n\t| 'record-not-open'\n\t/** The record to sell belongs to another account (`ENotRecordOwner`). */\n\t| 'not-record-owner';\n\n/** A queued-order builder's refusal, raised before any transaction is built. */\nexport class PredictPreflightError extends Error {\n\treadonly code: PredictPreflightCode;\n\n\tconstructor(code: PredictPreflightCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'PredictPreflightError';\n\t\tthis.code = code;\n\t}\n}\n\n// Readable text for the aborts a trader, an app or a filler meets on the delayed-execution\n// paths, keyed by `module::EName` as `decodeMoveAbort` names it. The queue's own\n// checks are in the order-flow companion's `queue` and `desk` modules; Predict's admission, fill\n// and quote checks stay in `expiry_market` and `protocol_config`; the Lazer decode is in the math\n// library's `lazer_price`.\nconst PREDICT_ERROR_TEXT: Readonly<Record<string, string>> = Object.freeze({\n\t// Placement (`queue::enqueue_*`).\n\t'queue::EQueueStuck': 'Pricing is delayed for this market. Try again shortly.',\n\t'queue::EQueueFull': \"This market's order queue is full. Try again shortly.\",\n\t'queue::EAccountOrderCap': 'You already have the most waiting orders this market allows.',\n\t'queue::EPastCutoff': 'This market no longer takes orders before its expiry.',\n\t'queue::EFeeNotCovered': \"Your balance doesn't cover the order fee. Top up and retry.\",\n\t'queue::EBelowMinSell': 'The sell is below the minimum size, or leaves a remainder below it.',\n\t'queue::ERecordNotOpen': \"That position isn't open in this market anymore.\",\n\t'queue::ENotRecordOwner': 'That position belongs to another account.',\n\t'queue::EMintCostCapRequired': 'Set a maximum cost for the order.',\n\t'queue::EWrongDesk': 'That order queue belongs to another order desk.',\n\t'queue::EWrongMarket': \"That order queue doesn't belong to this market.\",\n\t'queue::EMarketNotSettled': \"The market hasn't settled yet.\",\n\t'queue::EMarketNotExpired': \"The market hasn't expired yet.\",\n\t'desk::EPackageVersionDisabled':\n\t\t'This order-flow package version is retired. Update to an SDK that calls the current package.',\n\t'desk::EProtocolFrozen': 'The protocol is frozen.',\n\t// The order-fee guard every SDK enqueue starts with. Predict's own `option` unwraps can abort the\n\t// same way, so the text hedges.\n\t'option::EOPTION_NOT_SET':\n\t\t\"This order wasn't placed: most likely the order fee rose after it was built. Build it again.\",\n\t// Predict's admission and quotes.\n\t'expiry_market::EDelayedExecutionRequired':\n\t\t'Immediate trades are retired on this market. Place a queued order instead.',\n\t'expiry_market::EOrderFailsLimits':\n\t\t\"The market can't take this order at the current price: it misses its price limits, its price is outside the market's entry range, or its premium is below the minimum.\",\n\t'expiry_market::EInsufficientMarketCash': \"This market can't take an order this size right now.\",\n\t'expiry_market::EMintCostCapRequired': 'Set a maximum cost for the order.',\n\t'expiry_market::EMintPaused': 'Minting is paused on this market.',\n\t'expiry_market::EInvalidOrderTiming': 'This market no longer takes orders before its expiry.',\n\t'expiry_market::EMarketNotSettled': \"The market hasn't settled yet.\",\n\t'strike_exposure_config::EEntryProbabilityOutOfBounds':\n\t\t\"This strike's price is outside the market's entry range. Pick a strike nearer the money.\",\n\t'strike_exposure_config::EPremiumBelowMinimum':\n\t\t\"The order's premium is below the 1 USDC minimum.\",\n\t'strike_exposure::EMintQuantityBelowMin':\n\t\t'The price moved, so the budget buys fewer contracts than the order asks for.',\n\t'strike_payout_tree::EMaxPayoutTreeNodes':\n\t\t'This market has no room for a new strike right now. Pick a strike that already has positions.',\n\t'expiry_cash::EInsufficientCash': \"This market can't take an order this size right now.\",\n\t// The LP pool.\n\t'lp_book::EBelowMinSupplyRequest': 'The deposit is below the minimum supply request.',\n\t'lp_book::EBelowMinWithdrawRequest': 'The withdrawal is below the minimum withdraw request.',\n\t// Live pricing. The unavailable and stale aborts clear once the oracles write again.\n\t'pricing::EBlockScholesPriceUnavailable':\n\t\t'Pricing is briefly unavailable for this market. Try again in a moment.',\n\t'pricing::EBlockScholesSVIUnavailable':\n\t\t'Pricing is briefly unavailable for this market. Try again in a moment.',\n\t'pricing::EBlockScholesPriceStale': \"This market's price feed is behind. Try again shortly.\",\n\t'pricing::EBlockScholesSVIStale': \"This market's price feed is behind. Try again shortly.\",\n\t'pricing::EPythSpotUnavailable': \"This market's live price is unavailable. Try again shortly.\",\n\t'pricing::EPythSpotStale': \"This market's live price is behind. Try again shortly.\",\n\t'pricing::ELivePricingExpired': 'This market has reached its expiry.',\n\t// Filler (`queue::commit`, decoding the Lazer update).\n\t'lazer_price::EGenerationAfterEnvelope':\n\t\t'The Pyth update was generated after its own timestamp envelope.',\n\t'lazer_price::EFeedMissing': \"The Pyth update doesn't carry this market's feed.\",\n\t'lazer_price::EPropertyNotRequested':\n\t\t\"The Pyth update doesn't carry the price property commit needs.\",\n\t// Sessions and the shared account.\n\t'sessions::ESessionNotAuthorized':\n\t\t\"This session key isn't authorized for the account, or its grant has expired.\",\n\t'sessions::ESessionLimitExceeded':\n\t\t'The account holds the most session keys it can. Revoke expired ones, then grant again.',\n\t'sessions::EInvalidSessionDuration': 'A session must last more than 0 ms and at most 30 days.',\n\t'session_config::EPackageVersionDisabled':\n\t\t'This sessions package version is retired. Update to an SDK that calls the current package.',\n\t'account_registry::EAppNotAuthorized':\n\t\t\"Trading through this app (such as Sessions) isn't enabled for accounts yet.\",\n\t'account_registry::EAccountAlreadyExists': 'This address already has an account.',\n\t// Protocol gates.\n\t'protocol_config::ECutoverNotReached':\n\t\t\"Queued orders aren't live yet: the protocol's version watermark hasn't been raised.\",\n\t'protocol_config::EOrderFlowNotAllowed':\n\t\t\"Queued orders aren't live yet: the protocol hasn't enabled the order-flow package.\",\n\t'protocol_config::EPackageVersionDisabled':\n\t\t'This package version is retired. Update to an SDK that calls the current package.',\n\t'protocol_config::EProtocolFrozen': 'The protocol is frozen.',\n\t'protocol_config::ETradingPaused': 'Trading is paused.',\n\t'protocol_config::ESnapshotInProgress': 'A pool valuation is running. Try again in a moment.',\n});\n\n/**\n * Readable text for a decoded Move abort on the Predict paths, or `null` when the abort isn't\n * one this SDK describes (an unknown name, or an abort `decodeMoveAbort` couldn't name). Callers\n * fall back to `e.message` on `null`, so new contract errors degrade to the raw abort rather\n * than to a wrong message.\n */\nexport function describePredictError(e: PredictMoveError): string | null {\n\tif (!e.abortName) return null;\n\treturn PREDICT_ERROR_TEXT[`${e.module}::${e.abortName}`] ?? null;\n}\n"],"mappings":";;AAaA,IAAa,oBAAb,cAAuC,MAAM;CAC5C,YAAY,SAAiB;AAC5B,QAAM,QAAQ;AACd,OAAK,OAAO;;;;AAKd,IAAa,mBAAb,cAAsC,MAAM;CAU3C,YAAY,QAAgB,MAAc,WAA0B;AACnE,QACC,YACG,iBAAiB,OAAO,IAAI,UAAU,SAAS,KAAK,KACpD,iBAAiB,OAAO,SAAS,OACpC;AACD,OAAK,OAAO;AACZ,OAAK,SAAS;AACd,OAAK,OAAO;AACZ,OAAK,YAAY;;;;;;;;;;;AAgCnB,MAAa,cAA2D,OAAO,OAAO;CAErF,eAAe;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,iBAAiB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAED,SAAS;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAGD,iBAAiB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,wBAAwB;EACvB;EACA;EACA;EACA;EACA;CACD,oBAAoB;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;CACD,aAAa,CAAC,qBAAqB,uCAAuC;CAC1E,iBAAiB,CAAC,0BAA0B,oBAAoB;CAChE,cAAc,CAAC,YAAY;CAC3B,KAAK;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,SAAS;EACR;EACA;EACA;EACA;EACA;CACD,iBAAiB;EAChB;EACA;EACA;EACA;EACA;CAED,OAAO;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,MAAM;EAAC;EAA2B;EAAgC;EAAkB;CACpF,aAAa,CAAC,iBAAiB;CAC/B,0BAA0B;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A0C;CAC1C,uCAAuC;CACvC,8BAA8B;CAC9B,sCAAsC;CACtC,oCAAoC;CACpC,wDACC;CACD,gDACC;CACD,0CACC;CACD,2CACC;CACD,kCAAkC;CAElC,mCAAmC;CACnC,qCAAqC;CAErC,0CACC;CACD,wCACC;CACD,oCAAoC;CACpC,kCAAkC;CAClC,iCAAiC;CACjC,2BAA2B;CAC3B,gCAAgC;CAEhC,yCACC;CACD,6BAA6B;CAC7B,sCACC;CAED,mCACC;CACD,mCACC;CACD,qCAAqC;CACrC,2CACC;CACD,uCACC;CACD,2CAA2C;CAE3C,uCACC;CACD,yCACC;CACD,4CACC;CACD,oCAAoC;CACpC,mCAAmC;CACnC,wCAAwC;CACxC,CAAC;;;;;;;AAQF,SAAgB,qBAAqB,GAAoC;AACxE,KAAI,CAAC,EAAE,UAAW,QAAO;AACzB,QAAO,mBAAmB,GAAG,EAAE,OAAO,IAAI,EAAE,gBAAgB"}
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/predict/errors.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Typed errors for the Predict SDK.\n//\n// Two failure kinds cross the SDK boundary:\n// - PredictInputError — a caller gave us something we rejected before touching\n// the chain (unknown underlying, malformed argument, …).\n// - PredictMoveError — a Move `abort` surfaced by a read/simulate. Predict's error\n// constants are plain `u64` codes, not clever errors, so the fullnode can't name\n// them: `decodeMoveAbort` maps `(module, code)` to the constant name with\n// ABORT_NAMES below. A clever-error name the fullnode does decode takes precedence.\n\n/** A caller-supplied argument the SDK rejected before building/sending a tx. */\nexport class PredictInputError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'PredictInputError';\n\t}\n}\n\n/** A Move `abort` decoded from a simulate/read failure. */\nexport class PredictMoveError extends Error {\n\treadonly module: string;\n\t/** Exact u64 abort code — bigint because clever-error encodings pack data\n\t * into the high bits, which Number would silently truncate. */\n\treadonly code: bigint;\n\t/** The `E…` constant name: the fullnode's clever-error name when it decodes\n\t * one, else the name {@link ABORT_NAMES} gives the module's plain code, or null\n\t * when neither knows the abort. */\n\treadonly abortName: string | null;\n\n\tconstructor(module: string, code: bigint, abortName: string | null) {\n\t\tsuper(\n\t\t\tabortName\n\t\t\t\t? `Move abort in ${module}: ${abortName} (code ${code})`\n\t\t\t\t: `Move abort in ${module}: code ${code}`,\n\t\t);\n\t\tthis.name = 'PredictMoveError';\n\t\tthis.module = module;\n\t\tthis.code = code;\n\t\tthis.abortName = abortName;\n\t}\n}\n\n// The structured MoveAbort execution error surfaced by `@mysten/sui` on a failed\n// simulate/execute. Read structurally rather than via the client's exported\n// `SuiClientTypes.ExecutionError` (`@mysten/sui/client`) so mocked simulate results\n// and future API-shape drift still satisfy it — the same convention reads/inspect.ts\n// uses for its simulate seam. Field provenance:\n// - `MoveAbort.abortCode` → u64 abort code as a decimal string.\n// - `MoveAbort.location.module` → the aborting module's short name.\n// - `MoveAbort.cleverError.constantName` → the `E…` error constant, decoded by the\n// fullnode from the clever-error bits of the abort code and surfaced by the gRPC\n// (`grpc/core.ts` parseMoveAbort) and GraphQL transports. Only a clever-error abort\n// carries one, and Predict's plain `u64` constants never do, so ABORT_NAMES names\n// those. JSON-RPC surfaces no `constantName` at all.\nexport interface MoveAbortError {\n\tMoveAbort?: {\n\t\tabortCode?: string | number | bigint;\n\t\tlocation?: { module?: string };\n\t\tcleverError?: { constantName?: string };\n\t};\n}\n\n/**\n * The error constants of the Predict modules the SDK's flows abort in, by module, as an array\n * indexed by the plain `u64` abort code (each module numbers its constants from 0 with no gaps).\n * Generated from the Move sources at deepbookv3 29117434. A published code never changes meaning:\n * new codes only append, so an older package version's codes are a prefix of its module's list.\n * Keyed by module name only, as the abort location reports it, so a same-named module in an\n * unrelated package would be named from this table too.\n */\nexport const ABORT_NAMES: Readonly<Record<string, readonly string[]>> = Object.freeze({\n\t// Predict (`deepbook_predict`). Append-only since v1, so older package versions use a prefix.\n\texpiry_market: [\n\t\t'EMintPaused',\n\t\t'EMarketNotSettled',\n\t\t'EMintCostAboveMax',\n\t\t'EMintProbabilityAboveMax',\n\t\t'EWrongPricer',\n\t\t'EReferenceTickObservationMissing',\n\t\t'EMintRedeemSameTimestamp',\n\t\t'ERedeemProbabilityBelowMin',\n\t\t'ERedeemProceedsBelowMin',\n\t\t'EMintCostCapRequired',\n\t\t'EMarketNotPendingValuation',\n\t\t'EMintCostAboveMaxPayout',\n\t\t'ENotSettledRedeemKeeper',\n\t\t'EDelayedExecutionRequired',\n\t\t'EOrderFailsLimits',\n\t\t'EInsufficientMarketCash',\n\t\t'EInvalidOrderTiming',\n\t\t'EInvalidOrderTerms',\n\t\t'EWrongMarket',\n\t\t'EWrongStage',\n\t\t'ENotRecordOwner',\n\t\t'EEscrowMismatch',\n\t\t'EWrongPrice',\n\t],\n\tprotocol_config: [\n\t\t'ETradingPaused',\n\t\t'EValuationInProgress',\n\t\t'EValuationNotInProgress',\n\t\t'EPackageVersionDisabled',\n\t\t'EVersionWatermarkNotAdvanced',\n\t\t'EProtocolFrozen',\n\t\t'ESnapshotInProgress',\n\t\t'ETradeWindowClosed',\n\t\t'ESettledRedeemKeeperAlreadyAdded',\n\t\t'ESettledRedeemKeeperNotFound',\n\t\t'EFlushOperatorAlreadyAdded',\n\t\t'EFlushOperatorNotFound',\n\t\t'ENotFlushOperator',\n\t\t'ECutoverNotReached',\n\t\t'EEwmaRetired',\n\t\t'EOrderFlowNotAllowed',\n\t\t// Predict v5: a builder trade before the watermark reaches the builder-fee version.\n\t\t'EBuilderFeeCutoverNotReached',\n\t],\n\t// Predict's live pricer, which every quote, plan and enqueue loads.\n\tpricing: [\n\t\t'EZeroForward',\n\t\t'ECannotBeNegative',\n\t\t'ENonPositiveVariance',\n\t\t'EInvalidRange',\n\t\t'EBlockScholesPriceStale',\n\t\t'EBlockScholesInputsInvalid',\n\t\t'EPythSpotInvalid',\n\t\t'EWrongPythFeed',\n\t\t'EWrongBlockScholesValueStore',\n\t\t'ELivePricingExpired',\n\t\t'EBlockScholesSVIStale',\n\t\t'EWrongBlockScholesSVIStore',\n\t\t'EBlockScholesPriceUnavailable',\n\t\t'EBlockScholesSVIUnavailable',\n\t\t'EBlockScholesMinVarianceInvalid',\n\t\t'EOracleWrittenInThisTransaction',\n\t\t'EBlockScholesInputTooWide',\n\t\t'EPythSpotUnavailable',\n\t\t'EPythSpotStale',\n\t\t'EPythForwardRequired',\n\t],\n\t// Admission, positions and the LP pool. `order` and `registry` are left out: DeepBook's core\n\t// package has modules of the same names, which this table would misname.\n\tstrike_exposure: [\n\t\t'EInvalidCloseQuantity',\n\t\t'EInvalidAdmissionTick',\n\t\t'EInvalidReferenceTick',\n\t\t'EReferenceTickAlreadySet',\n\t\t'ETermsExposureMismatch',\n\t\t'EMintQuantityBelowMin',\n\t\t'EInvalidInventoryImpactScale',\n\t],\n\tstrike_exposure_config: [\n\t\t'EEntryProbabilityOutOfBounds',\n\t\t'EInvalidEntryProbabilityBound',\n\t\t'EInvalidFeeProbability',\n\t\t'EPremiumBelowMinimum',\n\t],\n\tstrike_payout_tree: [\n\t\t'EInsufficientPayoutQuantity',\n\t\t'EMaxPayoutTreeNodes',\n\t\t'ENonMonotonePrice',\n\t\t'EStaleValuationSnapshot',\n\t\t'ESnapshotSeqNotIncreasing',\n\t\t'ENodeMissing',\n\t],\n\texpiry_cash: ['EInsufficientCash', 'EInventoryImpactRebateExceedsReserve'],\n\tpredict_account: ['EPositionAlreadyExists', 'EPositionNotFound'],\n\tbuilder_code: ['ENotOwner'],\n\tplp: [\n\t\t'EMissingExpiryValuation',\n\t\t'ENotBootstrapped',\n\t\t'EAlreadyBootstrapped',\n\t\t'EBelowMinBootstrapLiquidity',\n\t\t'EBelowMinFeeIncentiveSponsorship',\n\t\t'EMaxLiveExpiryMarketsExceeded',\n\t\t'EValuationSnapshotNotSealed',\n\t\t'EExpiryPricerAlreadySnapshotted',\n\t\t'EIncompleteValuationSnapshot',\n\t\t'EExpiredMarketNotSettled',\n\t\t'EValuationWindowExpired',\n\t\t'ESnapshotStageOpen',\n\t\t'EBelowMinUsdcContribution',\n\t\t'EContributionExceedsPriceCeiling',\n\t\t'EInsufficientFeeIncentiveReserve',\n\t],\n\tlp_book: [\n\t\t'ERequestNotFound',\n\t\t'EBelowMinSupplyRequest',\n\t\t'EBelowMinWithdrawRequest',\n\t\t'ENotRequestOwner',\n\t],\n\tpool_accounting: [\n\t\t'EUnknownRegisteredExpiry',\n\t\t'ERegisteredExpiryAlreadyExists',\n\t\t'EMaxExpiryFundingExceeded',\n\t\t'ETerminalAccountingStarted',\n\t],\n\t// The order-flow package (`deepbook_predict_orders`).\n\tqueue: [\n\t\t'EWrongDesk',\n\t\t'EWrongMarket',\n\t\t'EQueueStuck',\n\t\t'EQueueFull',\n\t\t'EAccountOrderCap',\n\t\t'EPastCutoff',\n\t\t'EMintCostCapRequired',\n\t\t'EFeeNotCovered',\n\t\t'EBelowMinSell',\n\t\t'ERecordNotOpen',\n\t\t'ENotRecordOwner',\n\t\t'EMarketNotSettled',\n\t\t'EMarketNotExpired',\n\t],\n\tdesk: ['EPackageVersionDisabled', 'EVersionWatermarkNotAdvanced', 'EProtocolFrozen'],\n\torder_queue: ['ERecordNotOpen'],\n\tdelayed_execution_config: [\n\t\t'EInvalidDelayMs',\n\t\t'EInvalidStallTimeoutMs',\n\t\t'EInvalidStuckThresholdMs',\n\t\t'EInvalidGapWaitMs',\n\t\t'EInvalidPythPriceBufferMs',\n\t\t'EInvalidSviMaxAgeMs',\n\t\t'EInvalidMintCapacity',\n\t\t'EInvalidSellCapacity',\n\t\t'EInvalidPerAccountCap',\n\t\t'EInvalidMinSellQuantity',\n\t\t'EInvalidOrderFee',\n\t\t'EInvalidSettleRefundBatch',\n\t\t'EInvalidSettlePayoutBatch',\n\t\t'EUnsupportedPythChannel',\n\t\t'EInvalidTiming',\n\t\t'EInvalidLimits',\n\t],\n\t// The math library (`deepbook_predict_math`).\n\tlazer_price: ['EPropertyNotRequested', 'EGenerationAfterEnvelope', 'EFeedMissing'],\n\t// Sessions (`deepbook_sessions`), which the `/sessions` Predict wrappers abort in.\n\tsessions: [\n\t\t'EInvalidSessionDuration',\n\t\t'ESessionNotAuthorized',\n\t\t'ESessionLimitExceeded',\n\t\t// Session builder approvals (Sessions v4, the Mainnet number).\n\t\t'EBuilderNotApproved',\n\t\t'EBuilderFeeAboveApproved',\n\t\t'EBuilderApprovalsNotEnabled',\n\t],\n\tsession_config: ['EPackageVersionDisabled', 'EVersionWatermarkNotAdvanced'],\n\t// The shared account (`deepbook_account`).\n\taccount_registry: ['EAppAlreadyAuthorized', 'EAppNotAuthorized', 'EAccountAlreadyExists'],\n});\n\n/** `std::option::EOPTION_NOT_SET`. */\nconst OPTION_NOT_SET = 0x40001n;\n\n/**\n * The constant name of a plain `u64` abort `code` in `module`, from {@link ABORT_NAMES}, or null\n * when the module or the code is unknown.\n */\nexport function abortNameFor(module: string, code: bigint): string | null {\n\t// The order-fee guard (`queueTx.assertOrderFeeAtMost`) aborts in the standard library's\n\t// `option`, whose constant isn't an index.\n\tif (module === 'option' && code === OPTION_NOT_SET) return 'EOPTION_NOT_SET';\n\t// Own keys only: a module named like an `Object.prototype` member is simply unknown.\n\tif (!Object.hasOwn(ABORT_NAMES, module)) return null;\n\tconst names = ABORT_NAMES[module];\n\tif (code < 0n || code >= BigInt(names.length)) return null;\n\treturn names[Number(code)];\n}\n\n/**\n * Decode a `@mysten/sui` MoveAbort execution error into a {@link PredictMoveError}.\n * Returns null when `error` carries no MoveAbort (InsufficientGas, a size error, any\n * non-abort failure), so callers can fall back to a plain Error.\n *\n * `abortName` is the chain-decoded clever-error constant when the fullnode surfaces one, and\n * otherwise the name {@link ABORT_NAMES} gives the module's plain code (Predict's constants are\n * plain codes, so this is the usual path). It is null when neither knows the abort.\n * `code` stays a bigint — a clever-error abort code packs the module, line, and\n * constant index into the high bits of the u64 and would lose precision as a Number.\n */\nexport function decodeMoveAbort(error: MoveAbortError | null | undefined): PredictMoveError | null {\n\tconst abort = error?.MoveAbort;\n\tif (!abort) return null;\n\tconst module = abort.location?.module ?? '';\n\tconst code = abort.abortCode != null ? BigInt(abort.abortCode) : 0n;\n\tconst abortName = abort.cleverError?.constantName ?? abortNameFor(module, code);\n\treturn new PredictMoveError(module, code, abortName);\n}\n\n// === Delayed execution (DBU-885) ===\n\n/**\n * Why a queued-order builder refused to add an enqueue. The builder reads the market first and\n * throws this instead of building a transaction the queue or protocol gates would abort, so a\n * refused order never fails the rest of a transaction. Each code mirrors one on-chain refusal. The\n * order's own limits at the current price are checked only on chain (`EOrderFailsLimits`).\n */\nexport type PredictPreflightCode =\n\t/**\n\t * Delayed execution isn't live: Predict's version watermark isn't raised\n\t * (`ECutoverNotReached`), or Predict doesn't allowlist the order-flow package yet\n\t * (`EOrderFlowNotAllowed`).\n\t */\n\t| 'not-live'\n\t/** The market has no `MarketQueue` yet: `queue::create_and_share` hasn't run for it. */\n\t| 'no-queue'\n\t/**\n\t * A version floor retired code this SDK calls: Predict's watermark is above the Predict\n\t * version it was built for (`protocol_config::EPackageVersionDisabled`), or the order desk's\n\t * floor is above its order-flow package (`desk::EPackageVersionDisabled`). Update the SDK.\n\t */\n\t| 'retired'\n\t/** Trading is paused, the protocol is frozen, or minting is paused on this market. */\n\t| 'paused'\n\t/** The market's pricing is delayed (`queue_stuck`). Enqueue aborts `EQueueStuck`. */\n\t| 'stuck'\n\t/**\n\t * The order's τ would land at or after the market's order cutoff (`EPastCutoff`). A\n\t * `read.planMint` or `read.planSell` plan on a market past its expiry throws it too, since the\n\t * chain has no live price to quote (`ELivePricingExpired`).\n\t */\n\t| 'past-cutoff'\n\t/** The market has its maximum unfinished mints or sells (`EQueueFull`). */\n\t| 'queue-full'\n\t/** The account has its maximum unfinished orders in this market (`EAccountOrderCap`). */\n\t| 'account-cap'\n\t/**\n\t * The account balance doesn't cover the order fee (`EFeeNotCovered`). A `read.planMint` plan\n\t * also reports it when the balance doesn't cover the plan's `totalDebit`, since its limits assume\n\t * the whole budget, or when the owner has no account yet. Prompt a top-up.\n\t */\n\t| 'fee'\n\t/** A mint's cash need is above the market's spare cash (`EInsufficientMarketCash`). */\n\t| 'market-cash'\n\t/**\n\t * The escrowed budget, or an exact-amount mint's premium cap, can't buy the minimum premium,\n\t * so the order fails its limits. A budget `read.planMint` plan also reports it when what the\n\t * budget buys without the fee subsidy, as admission prices it, has a premium below the minimum,\n\t * and throws it for a budget below the minimum premium or one no fill clears it with.\n\t */\n\t| 'min-premium'\n\t/**\n\t * The strike's entry probability is outside the market's entry band, so the chain refuses to\n\t * quote or admit it (`EOrderFailsLimits`). Pick a strike nearer the money. Only `read.planMint`\n\t * reports it, and the probability can still leave the band between plan and placement.\n\t */\n\t| 'entry-band'\n\t/**\n\t * The order's all-in cost without the fee subsidy is above its payout, so admission refuses it\n\t * at any slippage (`EOrderFailsLimits`), or for a budget, the fill costs about its payout, where\n\t * admission's sizing can't be previewed. Only `read.planMint` reports it, near a certain outcome.\n\t */\n\t| 'cost-above-payout'\n\t/** A sell is below the policy minimum, or leaves a remainder below it (`EBelowMinSell`). */\n\t| 'below-min-sell'\n\t/** The record to sell is missing or not Open (`ERecordNotOpen`). */\n\t| 'record-not-open'\n\t/** The record to sell belongs to another account (`ENotRecordOwner`). */\n\t| 'not-record-owner';\n\n/** A queued-order builder's refusal, raised before any transaction is built. */\nexport class PredictPreflightError extends Error {\n\treadonly code: PredictPreflightCode;\n\n\tconstructor(code: PredictPreflightCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'PredictPreflightError';\n\t\tthis.code = code;\n\t}\n}\n\n// Readable text for the aborts a trader, an app or a filler meets on the delayed-execution\n// paths, keyed by `module::EName` as `decodeMoveAbort` names it. The queue's own\n// checks are in the order-flow companion's `queue` and `desk` modules; Predict's admission, fill\n// and quote checks stay in `expiry_market` and `protocol_config`; the Lazer decode is in the math\n// library's `lazer_price`.\nconst PREDICT_ERROR_TEXT: Readonly<Record<string, string>> = Object.freeze({\n\t// Placement (`queue::enqueue_*`).\n\t'queue::EQueueStuck': 'Pricing is delayed for this market. Try again shortly.',\n\t'queue::EQueueFull': \"This market's order queue is full. Try again shortly.\",\n\t'queue::EAccountOrderCap': 'You already have the most waiting orders this market allows.',\n\t'queue::EPastCutoff': 'This market no longer takes orders before its expiry.',\n\t'queue::EFeeNotCovered': \"Your balance doesn't cover the order fee. Top up and retry.\",\n\t'queue::EBelowMinSell': 'The sell is below the minimum size, or leaves a remainder below it.',\n\t'queue::ERecordNotOpen': \"That position isn't open in this market anymore.\",\n\t'queue::ENotRecordOwner': 'That position belongs to another account.',\n\t'queue::EMintCostCapRequired': 'Set a maximum cost for the order.',\n\t'queue::EWrongDesk': 'That order queue belongs to another order desk.',\n\t'queue::EWrongMarket': \"That order queue doesn't belong to this market.\",\n\t'queue::EMarketNotSettled': \"The market hasn't settled yet.\",\n\t'queue::EMarketNotExpired': \"The market hasn't expired yet.\",\n\t'desk::EPackageVersionDisabled':\n\t\t'This order-flow package version is retired. Update to an SDK that calls the current package.',\n\t'desk::EProtocolFrozen': 'The protocol is frozen.',\n\t// The order-fee guard every SDK enqueue starts with. Predict's own `option` unwraps can abort the\n\t// same way, so the text hedges.\n\t'option::EOPTION_NOT_SET':\n\t\t\"This order wasn't placed: most likely the order fee rose after it was built. Build it again.\",\n\t// Predict's admission and quotes.\n\t'expiry_market::EDelayedExecutionRequired':\n\t\t'Immediate trades are retired on this market. Place a queued order instead.',\n\t'expiry_market::EOrderFailsLimits':\n\t\t\"The market can't take this order at the current price: it misses its price limits, its price is outside the market's entry range, or its premium is below the minimum.\",\n\t'expiry_market::EInsufficientMarketCash': \"This market can't take an order this size right now.\",\n\t'expiry_market::EMintCostCapRequired': 'Set a maximum cost for the order.',\n\t'expiry_market::EMintPaused': 'Minting is paused on this market.',\n\t'expiry_market::EInvalidOrderTiming': 'This market no longer takes orders before its expiry.',\n\t'expiry_market::EMarketNotSettled': \"The market hasn't settled yet.\",\n\t'strike_exposure_config::EEntryProbabilityOutOfBounds':\n\t\t\"This strike's price is outside the market's entry range. Pick a strike nearer the money.\",\n\t'strike_exposure_config::EPremiumBelowMinimum':\n\t\t\"The order's premium is below the 1 USDC minimum.\",\n\t'strike_exposure::EMintQuantityBelowMin':\n\t\t'The price moved, so the budget buys fewer contracts than the order asks for.',\n\t'strike_payout_tree::EMaxPayoutTreeNodes':\n\t\t'This market has no room for a new strike right now. Pick a strike that already has positions.',\n\t'expiry_cash::EInsufficientCash': \"This market can't take an order this size right now.\",\n\t// The LP pool.\n\t'lp_book::EBelowMinSupplyRequest': 'The deposit is below the minimum supply request.',\n\t'lp_book::EBelowMinWithdrawRequest': 'The withdrawal is below the minimum withdraw request.',\n\t// Live pricing. The unavailable and stale aborts clear once the oracles write again.\n\t'pricing::EBlockScholesPriceUnavailable':\n\t\t'Pricing is briefly unavailable for this market. Try again in a moment.',\n\t'pricing::EBlockScholesSVIUnavailable':\n\t\t'Pricing is briefly unavailable for this market. Try again in a moment.',\n\t'pricing::EBlockScholesPriceStale': \"This market's price feed is behind. Try again shortly.\",\n\t'pricing::EBlockScholesSVIStale': \"This market's price feed is behind. Try again shortly.\",\n\t'pricing::EPythSpotUnavailable': \"This market's live price is unavailable. Try again shortly.\",\n\t'pricing::EPythSpotStale': \"This market's live price is behind. Try again shortly.\",\n\t'pricing::ELivePricingExpired': 'This market has reached its expiry.',\n\t// Filler (`queue::commit`, decoding the Lazer update).\n\t'lazer_price::EGenerationAfterEnvelope':\n\t\t'The Pyth update was generated after its own timestamp envelope.',\n\t'lazer_price::EFeedMissing': \"The Pyth update doesn't carry this market's feed.\",\n\t'lazer_price::EPropertyNotRequested':\n\t\t\"The Pyth update doesn't carry the price property commit needs.\",\n\t// Sessions and the shared account.\n\t'sessions::ESessionNotAuthorized':\n\t\t\"This session key isn't authorized for the account, or its grant has expired.\",\n\t'sessions::ESessionLimitExceeded':\n\t\t'The account holds the most session keys it can. Revoke expired ones, then grant again.',\n\t'sessions::EInvalidSessionDuration': 'A session must last more than 0 ms and at most 30 days.',\n\t'session_config::EPackageVersionDisabled':\n\t\t'This sessions package version is retired. Update to an SDK that calls the current package.',\n\t'account_registry::EAppNotAuthorized':\n\t\t\"Trading through this app (such as Sessions) isn't enabled for accounts yet.\",\n\t'account_registry::EAccountAlreadyExists': 'This address already has an account.',\n\t// Protocol gates.\n\t'protocol_config::ECutoverNotReached':\n\t\t\"Queued orders aren't live yet: the protocol's version watermark hasn't been raised.\",\n\t'protocol_config::EOrderFlowNotAllowed':\n\t\t\"Queued orders aren't live yet: the protocol hasn't enabled the order-flow package.\",\n\t'protocol_config::EPackageVersionDisabled':\n\t\t'This package version is retired. Update to an SDK that calls the current package.',\n\t'protocol_config::EProtocolFrozen': 'The protocol is frozen.',\n\t'protocol_config::ETradingPaused': 'Trading is paused.',\n\t'protocol_config::ESnapshotInProgress': 'A pool valuation is running. Try again in a moment.',\n});\n\n/**\n * Readable text for a decoded Move abort on the Predict paths, or `null` when the abort isn't\n * one this SDK describes (an unknown name, or an abort `decodeMoveAbort` couldn't name). Callers\n * fall back to `e.message` on `null`, so new contract errors degrade to the raw abort rather\n * than to a wrong message.\n */\nexport function describePredictError(e: PredictMoveError): string | null {\n\tif (!e.abortName) return null;\n\treturn PREDICT_ERROR_TEXT[`${e.module}::${e.abortName}`] ?? null;\n}\n"],"mappings":";;AAaA,IAAa,oBAAb,cAAuC,MAAM;CAC5C,YAAY,SAAiB;AAC5B,QAAM,QAAQ;AACd,OAAK,OAAO;;;;AAKd,IAAa,mBAAb,cAAsC,MAAM;CAU3C,YAAY,QAAgB,MAAc,WAA0B;AACnE,QACC,YACG,iBAAiB,OAAO,IAAI,UAAU,SAAS,KAAK,KACpD,iBAAiB,OAAO,SAAS,OACpC;AACD,OAAK,OAAO;AACZ,OAAK,SAAS;AACd,OAAK,OAAO;AACZ,OAAK,YAAY;;;;;;;;;;;AAgCnB,MAAa,cAA2D,OAAO,OAAO;CAErF,eAAe;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,iBAAiB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;CAED,SAAS;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAGD,iBAAiB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,wBAAwB;EACvB;EACA;EACA;EACA;EACA;CACD,oBAAoB;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;CACD,aAAa,CAAC,qBAAqB,uCAAuC;CAC1E,iBAAiB,CAAC,0BAA0B,oBAAoB;CAChE,cAAc,CAAC,YAAY;CAC3B,KAAK;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,SAAS;EACR;EACA;EACA;EACA;EACA;CACD,iBAAiB;EAChB;EACA;EACA;EACA;EACA;CAED,OAAO;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,MAAM;EAAC;EAA2B;EAAgC;EAAkB;CACpF,aAAa,CAAC,iBAAiB;CAC/B,0BAA0B;EACzB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAED,aAAa;EAAC;EAAyB;EAA4B;EAAe;CAElF,UAAU;EACT;EACA;EACA;EAEA;EACA;EACA;EACA;CACD,gBAAgB,CAAC,2BAA2B,+BAA+B;CAE3E,kBAAkB;EAAC;EAAyB;EAAqB;EAAwB;CACzF,CAAC;;AAGF,MAAM,iBAAiB;;;;;AAMvB,SAAgB,aAAa,QAAgB,MAA6B;AAGzE,KAAI,WAAW,YAAY,SAAS,eAAgB,QAAO;AAE3D,KAAI,CAAC,OAAO,O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,4CACC;CACD,oCAAoC;CACpC,mCAAmC;CACnC,wCAAwC;CACxC,CAAC;;;;;;;AAQF,SAAgB,qBAAqB,GAAoC;AACxE,KAAI,CAAC,EAAE,UAAW,QAAO;AACzB,QAAO,mBAAmB,GAAG,EAAE,OAAO,IAAI,EAAE,gBAAgB"}
@@ -40,7 +40,7 @@ import { builder_code_events_d_exports } from "../contracts/deepbook_predict/bui
40
40
  import { config_events_d_exports } from "../contracts/deepbook_predict/config_events.mjs";
41
41
  import { order_events_d_exports } from "../contracts/deepbook_predict/order_events.mjs";
42
42
  import { vault_events_d_exports } from "../contracts/deepbook_predict/vault_events.mjs";
43
- import { queue_d_exports as queue_d_exports$1 } from "../contracts/deepbook_predict_orders/queue.mjs";
43
+ import { queue_d_exports as queue_d_exports$1 } from "./bindings/queue.mjs";
44
44
  import { desk_d_exports } from "../contracts/deepbook_predict_orders/desk.mjs";
45
45
  import { math_d_exports } from "../contracts/deepbook_predict_math/math.mjs";
46
46
  import { lazer_price_d_exports } from "../contracts/deepbook_predict_math/lazer_price.mjs";
@@ -24,9 +24,10 @@ import { deriveAccountWrapperId, generateAuth } from "./tx/common.mjs";
24
24
  import { pricing_exports as pricing_exports$1 } from "../contracts/deepbook_predict/pricing.mjs";
25
25
  import { plp_exports } from "../contracts/deepbook_predict/plp.mjs";
26
26
  import { desk_exports } from "../contracts/deepbook_predict_orders/desk.mjs";
27
- import { queue_exports as queue_exports$1 } from "../contracts/deepbook_predict_orders/queue.mjs";
28
27
  import { queue_exports as queue_exports$2 } from "./tx/queue.mjs";
28
+ import { expiry_market_exports } from "./bindings/expiry-market.mjs";
29
29
  import { loadLivePricer } from "./tx/trade.mjs";
30
+ import { queue_exports as queue_exports$1 } from "./bindings/queue.mjs";
30
31
  import { orderFlowWitnessType } from "./reads/queue.mjs";
31
32
  import { predict_account_exports } from "../contracts/deepbook_predict/predict_account.mjs";
32
33
  import { range_codec_exports } from "../contracts/deepbook_predict/range_codec.mjs";
@@ -35,7 +36,6 @@ import { registry_exports } from "../contracts/deepbook_predict/registry.mjs";
35
36
  import { POSITION_LOT_SIZE, PredictClient, predict } from "./client.mjs";
36
37
  import { admin_exports } from "../contracts/deepbook_predict/admin.mjs";
37
38
  import { builder_code_exports } from "../contracts/deepbook_predict/builder_code.mjs";
38
- import { expiry_market_exports } from "./bindings/expiry-market.mjs";
39
39
  import { market_lifecycle_cap_exports } from "../contracts/deepbook_predict/market_lifecycle_cap.mjs";
40
40
  import { pause_cap_exports } from "../contracts/deepbook_predict/pause_cap.mjs";
41
41
  import { pool_valuation_cap_exports } from "../contracts/deepbook_predict/pool_valuation_cap.mjs";
@@ -19,15 +19,19 @@ declare const DELAYED_EXECUTION_VERSION = 4n;
19
19
  * Predict's `constants::current_version` of the package these bindings were generated from. Every
20
20
  * version-gated Predict call checks `chk_version`, which aborts `EPackageVersionDisabled` once
21
21
  * `ProtocolConfig.version_watermark` is above it, so a higher watermark retires the Predict code
22
- * this SDK calls. Bump it with Predict when regenerating.
22
+ * this SDK calls. Bump it with Predict when regenerating. Like `DELAYED_EXECUTION_VERSION` it is the
23
+ * code's version constant, which follows the Mainnet package number (5 ships as Mainnet v5 and runs
24
+ * as Testnet package v8), never the Testnet package number.
23
25
  */
24
- declare const PREDICT_PACKAGE_VERSION = 4n;
26
+ declare const PREDICT_PACKAGE_VERSION = 5n;
25
27
  /**
26
28
  * `desk::current_version` of the order-flow package these bindings were generated from. The desk's
27
29
  * version floor retires older companion code, so a floor above it means the package this SDK calls
28
- * aborts `EPackageVersionDisabled`. Bump it with the companion when regenerating.
30
+ * aborts `EPackageVersionDisabled`. Bump it with the companion when regenerating. It follows the
31
+ * Mainnet package number (2 ships as Mainnet v2 and runs as Testnet package v3), never the Testnet
32
+ * package number.
29
33
  */
30
- declare const ORDER_FLOW_PACKAGE_VERSION = 1n;
34
+ declare const ORDER_FLOW_PACKAGE_VERSION = 2n;
31
35
  /** `queue::phase_*`: what `settle_step` returns, the phase the next call runs. */
32
36
  declare const SETTLE_PHASE: Readonly<{
33
37
  /** Refunding the waiting orders (reason 5). */readonly DRAIN: 0; /** Paying the Open records, once Predict has settled the market. */
@@ -1 +1 @@
1
- {"version":3,"file":"queue.d.mts","names":[],"sources":["../../src/predict/queue.ts"],"mappings":";;;;;;;;;;;;;;;;cAkCa,yBAAA;;;;;;;cAQA,uBAAA;;;;;;cAOA,0BAAA;;cAGA,YAAA,EAAY,QAAA;;;;;;;;;;cAaZ,YAAA,EAAY,QAAA;EAAA;;;;;;;;cAWZ,UAAA,EAAU,QAAA;EAAA;;;;;;;cASV,aAAA,EAAa,QAAA;EAAA;;;;;;;;;;;cAab,YAAA,EAAY,QAAA;EAAA;;;;cAMZ,yBAAA;;;AApDb;;cA0Da,uBAAA;AAAA,KAED,eAAA;AAAA,KAGA,aAAA;;iBAoBI,eAAA,CAAgB,IAAA,WAAe,eAAA;;iBAK/B,aAAA,CAAc,IAAA,WAAe,aAAA;;iBAK7B,UAAA,CAAW,IAAA;;iBASX,UAAA,CAAW,IAAA;;UAKV,gBAAA;EAChB,IAAA;EACA,GAAA;;EAYA,IAAA;;EAEA,OAAA;;EAEA,IAAA;AAAA;;cAIY,cAAA,EAAgB,QAAA,CAAS,MAAA,SAAe,gBAAA;;iBA6DrC,YAAA,CAAa,IAAA,WAAe,gBAAA;;;;;UAkB3B,sBAAA;EAChB,OAAA;EACA,cAAA;EACA,gBAAA;EACA,SAAA;EACA,iBAAA;EApLyB;EAsLzB,WAAA;EACA,WAAA;EACA,YAAA;EACA,YAAA;EACA,aAAA;;EAEA,QAAA;EACA,eAAA;EACA,iBAAA;EACA,iBAAA;AAAA;;iBAIe,aAAA,CACf,CAAA,UAAW,wBAAA,kBACT,sBAAA;;iBAoBa,aAAA,CAAc,OAAA;;iBA0Bd,qBAAA,CAAsB,QAAA,UAAkB,mBAAA;;;;;AAhOxD;iBA2OgB,cAAA,CAAe,MAAA,UAAgB,mBAAA;;iBAO/B,YAAA,CAAa,aAAA,UAAuB,mBAAA;;AA5OpD;;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EAAU,YAAA,SApOb;EAsOG,QAAA,WAlOH;EAoOG,SAAA;AAAA;EAGA,KAAA;EACA,MAAA,EAAQ,gBAAA;EACR,YAAA,UAvNa;EAyNb,wBAAA;EACA,QAAA,EAAU,YAAA;EACV,QAAA,WAvNK;EAyNL,SAAA;AAAA;yEAIA,KAAA;EACA,WAAA;EACA,SAAA;EACA,YAAA,UApMH;EAsMG,SAAA;AAAA;EAEE,KAAA;AAAA;AApLN;;;;;;AAAA,KA6LY,WAAA;;;;;;AAxKZ;;iBA4LgB,SAAA,CACf,MAAA,EAAQ,WAAA,EACR,KAAA,UACA,IAAA;EAAQ,QAAA;EAAmB,OAAA;AAAA,IACzB,SAAA;;UA+Gc,eAAA;EAChB,QAAA;EACA,QAAA;EA5S6B;;;AA6D9B;EAoPC,KAAA;EACA,IAAA;EACA,KAAA;EACA,UAAA;EApPgB;EAsPhB,KAAA;EACA,MAAA;EAvP4B;;;;EA4P5B,MAAA,EAAQ,gBAAA;EApPG;;AACX;;;EAyPA,QAAA,EAAU,YAAA;EAtPV;EAwPA,cAAA;EAtPA;EAwPA,SAAA;EAvPA;EAyPA,aAAA;EAzPI;AAOL;;;EAuPC,SAAA;AAAA;;;;;;;iBASe,iBAAA,CACf,MAAA,WAAiB,UAAA,IACjB,IAAA,GAAM,GAAA,SAAY,eAAA,IAChB,GAAA,SAAY,eAAA"}
@@ -53,15 +53,19 @@ const DELAYED_EXECUTION_VERSION = 4n;
53
53
  * Predict's `constants::current_version` of the package these bindings were generated from. Every
54
54
  * version-gated Predict call checks `chk_version`, which aborts `EPackageVersionDisabled` once
55
55
  * `ProtocolConfig.version_watermark` is above it, so a higher watermark retires the Predict code
56
- * this SDK calls. Bump it with Predict when regenerating.
56
+ * this SDK calls. Bump it with Predict when regenerating. Like `DELAYED_EXECUTION_VERSION` it is the
57
+ * code's version constant, which follows the Mainnet package number (5 ships as Mainnet v5 and runs
58
+ * as Testnet package v8), never the Testnet package number.
57
59
  */
58
- const PREDICT_PACKAGE_VERSION = 4n;
60
+ const PREDICT_PACKAGE_VERSION = 5n;
59
61
  /**
60
62
  * `desk::current_version` of the order-flow package these bindings were generated from. The desk's
61
63
  * version floor retires older companion code, so a floor above it means the package this SDK calls
62
- * aborts `EPackageVersionDisabled`. Bump it with the companion when regenerating.
64
+ * aborts `EPackageVersionDisabled`. Bump it with the companion when regenerating. It follows the
65
+ * Mainnet package number (2 ships as Mainnet v2 and runs as Testnet package v3), never the Testnet
66
+ * package number.
63
67
  */
64
- const ORDER_FLOW_PACKAGE_VERSION = 1n;
68
+ const ORDER_FLOW_PACKAGE_VERSION = 2n;
65
69
  /** `queue::phase_*`: what `settle_step` returns, the phase the next call runs. */
66
70
  const SETTLE_PHASE = Object.freeze({
67
71
  DRAIN: 0,
@@ -1 +1 @@
1
- {"version":3,"file":"queue.mjs","names":["max","q"],"sources":["../../src/predict/queue.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Delayed execution (DBU-885): the codes, cash-need math, timing previews and order-state views\n// for queued orders. Pure functions over raw bigints, no network. Exported as the `queue`\n// namespace, like `cost` and `pricing`.\n//\n// A queued order is placed now and priced later at Pyth's signed price for its τ, a channel\n// tick shortly after placement. A keeper (or anyone, see `fill` in `tx/queue.ts`) commits the\n// price and resolves the order: a fill, or a refund with a reason code. A filled mint stays in\n// its market's queue as an Open record until `enqueue_redeem_open` sells it or the queue's\n// settlement walk (`settle_step`) pays it.\n//\n// The queue lives in the order-flow companion, `deepbook_predict_orders`. The code values mirror\n// its `order_queue` getters, and the cash-need formulas are 1:1 ports (rounding included) of\n// `deepbook_predict_math::math::need_*`, which Predict's admission charges. Probabilities and λ\n// are 1e9-scaled.\n\nimport type { DelayedExecutionPolicy as DelayedExecutionPolicyBcs } from '../contracts/deepbook_predict_orders/delayed_execution_config.js';\nimport type { OrderView as OrderViewBcs } from '../contracts/deepbook_predict_orders/order_queue.js';\nimport { FLOAT_SCALING, MAX_QUANTITY_LOTS, POSITION_LOT_SIZE, decodeOrderRange } from './cost.js';\nimport type { QueueEvent } from './decode.js';\nimport { PredictInputError } from './errors.js';\nimport { U64_MAX } from './units.js';\n\n// === Codes ===\n\n/**\n * Predict's `constants::current_version` from the upgrade that added delayed execution. Enqueue\n * works once `ProtocolConfig.version_watermark` reaches it (Predict's admission aborts\n * `ECutoverNotReached` until then). The retired immediate trades (`mint_exact_*`, `redeem_live`)\n * always abort in that package, and the older packages they still run in are retired by the same\n * bump. The same on both networks: it is the code's version constant, not the on-chain package\n * version (Mainnet v4, Testnet v5).\n */\nexport const DELAYED_EXECUTION_VERSION = 4n;\n\n/**\n * Predict's `constants::current_version` of the package these bindings were generated from. Every\n * version-gated Predict call checks `chk_version`, which aborts `EPackageVersionDisabled` once\n * `ProtocolConfig.version_watermark` is above it, so a higher watermark retires the Predict code\n * this SDK calls. Bump it with Predict when regenerating.\n */\nexport const PREDICT_PACKAGE_VERSION = 4n;\n\n/**\n * `desk::current_version` of the order-flow package these bindings were generated from. The desk's\n * version floor retires older companion code, so a floor above it means the package this SDK calls\n * aborts `EPackageVersionDisabled`. Bump it with the companion when regenerating.\n */\nexport const ORDER_FLOW_PACKAGE_VERSION = 1n;\n\n/** `queue::phase_*`: what `settle_step` returns, the phase the next call runs. */\nexport const SETTLE_PHASE = Object.freeze({\n\t/** Refunding the waiting orders (reason 5). */\n\tDRAIN: 0,\n\t/** Paying the Open records, once Predict has settled the market. */\n\tPAY: 1,\n\t/**\n\t * The payout walk reached the last record and `MarketPayoutsCompleted` was emitted. A record\n\t * the market couldn't pay (`OpenRecordPayoutSkipped`) stays Open and unpaid.\n\t */\n\tDONE: 2,\n} as const);\n\n/** `order_queue::status_*`. Never renumbered on chain; unknown codes still decode. */\nexport const ORDER_STATUS = Object.freeze({\n\tPENDING: 0,\n\tCOMMITTED: 1,\n\tOPEN: 2,\n\tREFUNDED: 3,\n\tCLOSED: 4,\n\t/** Reserved: nothing sets it at launch. Counts as unfinished. */\n\tREFUND_DUE: 5,\n} as const);\n\n/** `order_queue::kind_*`. `REDEEM_LIVE` is reserved and never used by v4. */\nexport const ORDER_KIND = Object.freeze({\n\tEXACT_QUANTITY: 0,\n\tEXACT_AMOUNT: 1,\n\tEXACT_COST: 2,\n\tREDEEM_LIVE: 3,\n\tREDEEM_OPEN: 4,\n} as const);\n\n/** `order_queue::reason_*`. `0` in a record's result means filled. */\nexport const REFUND_REASON = Object.freeze({\n\tLIMITS: 1,\n\tADMISSION: 2,\n\tNO_PRICE: 3,\n\tMISSING_NODE: 4,\n\tDEADLINE: 5,\n\tFREEZE: 6,\n\tADMIN: 7,\n\tNO_CASH: 8,\n\tRECIPIENT_DENIED: 9,\n} as const);\n\n/** The Pyth Lazer channels the queue prices on (`delayed_execution_config`). */\nexport const PYTH_CHANNEL = Object.freeze({\n\tFIXED_RATE_50MS: 2,\n\tFIXED_RATE_200MS: 3,\n} as const);\n\n/** Predict's `constants::deadline_expiry_margin_ms`: every deadline is at least this long before expiry. */\nexport const DEADLINE_EXPIRY_MARGIN_MS = 5_000n;\n\n/**\n * How long after an order's deadline the app waits before offering \"Refund my order\". Keepers\n * refund overdue orders on their own, so the button only matters when they are all down.\n */\nexport const REFUND_REQUEST_GRACE_MS = 5_000n;\n\nexport type OrderStatusName =\n\t'pending' | 'committed' | 'open' | 'refunded' | 'closed' | 'refund-due' | 'unknown';\n\nexport type OrderKindName =\n\t'exact-quantity' | 'exact-amount' | 'exact-cost' | 'redeem-live' | 'redeem-open' | 'unknown';\n\nconst STATUS_NAMES: readonly OrderStatusName[] = [\n\t'pending',\n\t'committed',\n\t'open',\n\t'refunded',\n\t'closed',\n\t'refund-due',\n];\nconst KIND_NAMES: readonly OrderKindName[] = [\n\t'exact-quantity',\n\t'exact-amount',\n\t'exact-cost',\n\t'redeem-live',\n\t'redeem-open',\n];\n\n/** A status code's name, or `'unknown'` for a code this SDK version predates. */\nexport function orderStatusName(code: number): OrderStatusName {\n\treturn STATUS_NAMES[code] ?? 'unknown';\n}\n\n/** A kind code's name, or `'unknown'` for a code this SDK version predates. */\nexport function orderKindName(code: number): OrderKindName {\n\treturn KIND_NAMES[code] ?? 'unknown';\n}\n\n/** Whether a kind code is a queued mint (exact quantity, exact amount or exact cost). */\nexport function isMintKind(kind: number): boolean {\n\treturn (\n\t\tkind === ORDER_KIND.EXACT_QUANTITY ||\n\t\tkind === ORDER_KIND.EXACT_AMOUNT ||\n\t\tkind === ORDER_KIND.EXACT_COST\n\t);\n}\n\n/** Whether a kind code is a queued sell. */\nexport function isSellKind(kind: number): boolean {\n\treturn kind === ORDER_KIND.REDEEM_OPEN || kind === ORDER_KIND.REDEEM_LIVE;\n}\n\n/** What a refund reason means for the trader. */\nexport interface RefundReasonInfo {\n\tcode: number;\n\tkey:\n\t\t| 'limits'\n\t\t| 'admission'\n\t\t| 'no-price'\n\t\t| 'missing-node'\n\t\t| 'deadline'\n\t\t| 'freeze'\n\t\t| 'admin'\n\t\t| 'no-cash'\n\t\t| 'recipient-denied'\n\t\t| 'unknown';\n\t/** Display text for the refund. */\n\ttext: string;\n\t/** Whether the order fee was kept (reasons 1 and 2). `null` for an unknown code. */\n\tfeeKept: boolean | null;\n\t/** False for codes v4 reserves but never sets (3 and 6), and for unknown codes. */\n\tlive: boolean;\n}\n\n/** Every reason code v4 defines, with its text and fee treatment. */\nexport const REFUND_REASONS: Readonly<Record<number, RefundReasonInfo>> = Object.freeze({\n\t1: {\n\t\tcode: 1,\n\t\tkey: 'limits',\n\t\ttext: \"Your price limits weren't met at the fill price. Refunded, the order fee is kept.\",\n\t\tfeeKept: true,\n\t\tlive: true,\n\t},\n\t2: {\n\t\tcode: 2,\n\t\tkey: 'admission',\n\t\ttext: \"The market couldn't accept the order at the fill price. Refunded, the order fee is kept.\",\n\t\tfeeKept: true,\n\t\tlive: true,\n\t},\n\t3: {\n\t\tcode: 3,\n\t\tkey: 'no-price',\n\t\ttext: 'No price arrived for the order. Refunded in full.',\n\t\tfeeKept: false,\n\t\tlive: false,\n\t},\n\t4: {\n\t\tcode: 4,\n\t\tkey: 'missing-node',\n\t\ttext: \"The market couldn't place the order. Refunded in full.\",\n\t\tfeeKept: false,\n\t\tlive: true,\n\t},\n\t5: {\n\t\tcode: 5,\n\t\tkey: 'deadline',\n\t\ttext: \"The order wasn't priced before its deadline. Refunded in full.\",\n\t\tfeeKept: false,\n\t\tlive: true,\n\t},\n\t6: {\n\t\tcode: 6,\n\t\tkey: 'freeze',\n\t\ttext: 'The protocol was frozen. Refunded in full.',\n\t\tfeeKept: false,\n\t\tlive: false,\n\t},\n\t7: { code: 7, key: 'admin', text: 'Refunded in full by an admin.', feeKept: false, live: true },\n\t8: {\n\t\tcode: 8,\n\t\tkey: 'no-cash',\n\t\ttext: \"The market couldn't pay right now. Refunded in full.\",\n\t\tfeeKept: false,\n\t\tlive: true,\n\t},\n\t9: {\n\t\tcode: 9,\n\t\tkey: 'recipient-denied',\n\t\ttext: \"The account's receive address can't take USDC right now (it is on USDC's deny list, or USDC is paused). Refunded in full, and the refund waits in the order until it can be claimed.\",\n\t\tfeeKept: false,\n\t\tlive: true,\n\t},\n});\n\n/** A reason code's meaning. Unknown codes map to `key: 'unknown'` rather than throwing. */\nexport function refundReason(code: number): RefundReasonInfo {\n\treturn (\n\t\tREFUND_REASONS[code] ?? {\n\t\t\tcode,\n\t\t\tkey: 'unknown',\n\t\t\ttext: `Refunded (code ${code}).`,\n\t\t\tfeeKept: null,\n\t\t\tlive: false,\n\t\t}\n\t);\n}\n\n// === Policy ===\n\n/**\n * `delayed_execution_config::DelayedExecutionPolicy` with camelCase keys, as the companion's\n * `OrderDesk` holds it (`desk::policy`). Times in ms, USDC raw.\n */\nexport interface DelayedExecutionPolicy {\n\tdelayMs: bigint;\n\tstallTimeoutMs: bigint;\n\tstuckThresholdMs: bigint;\n\tgapWaitMs: bigint;\n\tpythPriceBufferMs: bigint;\n\t/** {@link PYTH_CHANNEL}: `2` is 50 ms, `3` is 200 ms. */\n\tpythChannel: number;\n\tsviMaxAgeMs: bigint;\n\tmintCapacity: bigint;\n\tsellCapacity: bigint;\n\tperAccountCap: bigint;\n\t/** Flat USDC fee charged at enqueue, raw. */\n\torderFee: bigint;\n\tminSellQuantity: bigint;\n\tsettleRefundBatch: bigint;\n\tsettlePayoutBatch: bigint;\n}\n\n/** Map the generated policy layout to {@link DelayedExecutionPolicy}. */\nexport function policyFromBcs(\n\tp: (typeof DelayedExecutionPolicyBcs)['$inferType'],\n): DelayedExecutionPolicy {\n\treturn {\n\t\tdelayMs: p.delay_ms,\n\t\tstallTimeoutMs: p.stall_timeout_ms,\n\t\tstuckThresholdMs: p.stuck_threshold_ms,\n\t\tgapWaitMs: p.gap_wait_ms,\n\t\tpythPriceBufferMs: p.pyth_price_buffer_ms,\n\t\tpythChannel: p.pyth_channel,\n\t\tsviMaxAgeMs: p.svi_max_age_ms,\n\t\tmintCapacity: p.mint_capacity,\n\t\tsellCapacity: p.sell_capacity,\n\t\tperAccountCap: p.per_account_cap,\n\t\torderFee: p.order_fee,\n\t\tminSellQuantity: p.min_sell_quantity,\n\t\tsettleRefundBatch: p.settle_refund_batch,\n\t\tsettlePayoutBatch: p.settle_payout_batch,\n\t};\n}\n\n/** `delayed_execution_config::channel_tick_ms`: 50 ms for channel 2, 200 ms for channel 3. */\nexport function channelTickMs(channel: number): bigint {\n\tif (channel === PYTH_CHANNEL.FIXED_RATE_50MS) return 50n;\n\tif (channel === PYTH_CHANNEL.FIXED_RATE_200MS) return 200n;\n\tthrow new PredictInputError(`unsupported Pyth Lazer channel ${channel}`);\n}\n\n// === Cash need (`deepbook_predict_math::math::need_*`) ===\n\nfunction assertUint(value: bigint, name: string, max: bigint = U64_MAX): void {\n\tif (typeof value !== 'bigint' || value < 0n || value > max) {\n\t\tthrow new PredictInputError(`${name} must be a bigint in [0, ${max}], got ${String(value)}`);\n\t}\n}\n\n// `math::mul_div_up`, including its abort on a zero denominator and a u64 overflow.\nfunction mulDivUp(x: bigint, y: bigint, denominator: bigint): bigint {\n\tif (denominator === 0n) throw new PredictInputError('division by zero (EInputZero)');\n\treturn (x * y + denominator - 1n) / denominator;\n}\n\nfunction plusOne(need: bigint): bigint {\n\tif (need >= U64_MAX) throw new PredictInputError('cash need overflows u64');\n\treturn need + 1n;\n}\n\n/** Exact-quantity mint cash need: `⌈quantity · (1 − p_min)⌉ + 1`. */\nexport function cashNeedExactQuantity(quantity: bigint, minEntryProbability: bigint): bigint {\n\tassertUint(quantity, 'quantity');\n\tassertUint(minEntryProbability, 'minEntryProbability', FLOAT_SCALING);\n\treturn plusOne(mulDivUp(quantity, FLOAT_SCALING - minEntryProbability, FLOAT_SCALING));\n}\n\n/**\n * Budget mint cash need: `⌈(budget + 1) · (1 / p_min − 1)⌉ + 1`, rounded as Move rounds it (one\n * `mul_div_up` of `(budget + 1) · (1e9 − p_min) / p_min`). Exact-amount mints pass\n * `min(max_premium, budget)`. `p_min = 0` throws, as the Move division aborts.\n */\nexport function cashNeedBudget(budget: bigint, minEntryProbability: bigint): bigint {\n\tassertUint(budget, 'budget', U64_MAX - 1n);\n\tassertUint(minEntryProbability, 'minEntryProbability', FLOAT_SCALING);\n\treturn plusOne(mulDivUp(budget + 1n, FLOAT_SCALING - minEntryProbability, minEntryProbability));\n}\n\n/** Sell cash need: `⌈close_quantity · (1 − λ)⌉ + 1`. */\nexport function cashNeedSell(closeQuantity: bigint, backingBufferLambda: bigint): bigint {\n\tassertUint(closeQuantity, 'closeQuantity');\n\tassertUint(backingBufferLambda, 'backingBufferLambda', FLOAT_SCALING);\n\treturn plusOne(mulDivUp(closeQuantity, FLOAT_SCALING - backingBufferLambda, FLOAT_SCALING));\n}\n\n/**\n * Whether the account can pay the order fee: a mint needs `available > fee` (it escrows a budget\n * on top), a sell needs `available ≥ fee` (it escrows only the fee). `available` is\n * `account::balance<USDC>`, unsettled accumulator funds included.\n */\nexport function feeCovered(\n\tside: 'mint' | 'sell',\n\tavailableRaw: bigint,\n\torderFeeRaw: bigint,\n): boolean {\n\treturn side === 'mint' ? availableRaw > orderFeeRaw : availableRaw >= orderFeeRaw;\n}\n\n/** Inputs for {@link mintBudget}. */\nexport interface MintBudgetInputs {\n\t/** {@link ORDER_KIND}: a mint kind. */\n\tkind: number;\n\tmaxCostRaw: bigint;\n\tavailableRaw: bigint;\n\torderFeeRaw: bigint;\n\t/** Required for exact quantity: a fill never costs more than its quantity. */\n\tquantityRaw?: bigint;\n}\n\n/**\n * The budget a queued mint escrows: `min(max_cost, available − fee)`, and for exact quantity also\n * at most the quantity. `null` when the balance doesn't cover the fee. Enqueue debits the budget\n * plus the order fee, and the unspent budget comes back at the fill.\n */\nexport function mintBudget(inputs: MintBudgetInputs): bigint | null {\n\tif (!feeCovered('mint', inputs.availableRaw, inputs.orderFeeRaw)) return null;\n\tconst budget = min(inputs.maxCostRaw, inputs.availableRaw - inputs.orderFeeRaw);\n\tif (inputs.kind !== ORDER_KIND.EXACT_QUANTITY) return budget;\n\tif (inputs.quantityRaw == null) {\n\t\tthrow new PredictInputError('quantityRaw is required for an exact-quantity budget');\n\t}\n\treturn min(budget, inputs.quantityRaw);\n}\n\n/** Inputs for {@link mintCashNeed}. */\nexport interface MintCashNeedInputs {\n\tkind: number;\n\t/** The escrowed budget, from {@link mintBudget}. */\n\tbudgetRaw: bigint;\n\tminEntryProbability: bigint;\n\t/** Exact quantity: the quantity ordered. */\n\tquantityRaw?: bigint;\n\t/** Exact amount: the premium cap. */\n\tmaxPremiumRaw?: bigint;\n}\n\n/** A queued mint's cash need, picking the formula the contract picks for its kind. */\nexport function mintCashNeed(inputs: MintCashNeedInputs): bigint {\n\tconst p = inputs.minEntryProbability;\n\tswitch (inputs.kind) {\n\t\tcase ORDER_KIND.EXACT_QUANTITY:\n\t\t\tif (inputs.quantityRaw == null) throw new PredictInputError('quantityRaw is required');\n\t\t\treturn cashNeedExactQuantity(inputs.quantityRaw, p);\n\t\tcase ORDER_KIND.EXACT_AMOUNT:\n\t\t\tif (inputs.maxPremiumRaw == null) throw new PredictInputError('maxPremiumRaw is required');\n\t\t\treturn cashNeedBudget(min(inputs.maxPremiumRaw, inputs.budgetRaw), p);\n\t\tcase ORDER_KIND.EXACT_COST:\n\t\t\treturn cashNeedBudget(inputs.budgetRaw, p);\n\t\tdefault:\n\t\t\tthrow new PredictInputError(`kind ${inputs.kind} is not a mint`);\n\t}\n}\n\n/**\n * A sell's cash need against the market's spare cash. Sells are never refused for market cash at\n * placement: the keeper funds the market before τ, and a sell the market still can't cover at the\n * fill is refunded in full (reason 8). `short` flags that risk, and the sell builder can add\n * `rebalance_expiry_cash` after the enqueue to fund the market at once.\n */\nexport function sellCashCheck(\n\tcloseQuantityRaw: bigint,\n\tspareCashRaw: bigint,\n\tbackingBufferLambda: bigint,\n): { needRaw: bigint; short: boolean } {\n\tconst needRaw = cashNeedSell(closeQuantityRaw, backingBufferLambda);\n\treturn { needRaw, short: needRaw > spareCashRaw };\n}\n\n// === Largest mint the market takes now ===\n\n/** Inputs for {@link maxMintNow}. */\nexport interface MaxMintInputs {\n\t/** `'exact-quantity'` sizes a quantity; `'budget'` sizes an exact-cost or exact-amount spend. */\n\tshape: 'exact-quantity' | 'budget';\n\t/** Market cash above required cash (`MarketQueueState.spareCash`). */\n\tspareCashRaw: bigint;\n\t/** The minimum entry probability from `expiry_market::order_flow_state`, 1e9-scaled. */\n\tminEntryProbability: bigint;\n\t/** `account::balance<USDC>`. Bounds a budget spend at `available − fee`. */\n\tavailableRaw?: bigint;\n\torderFeeRaw?: bigint;\n\t/** The deployment's `position_lot_size`. Defaults to `10_000n`. */\n\tlotSize?: bigint;\n\t/** Margin left below spare cash, in basis points. Default 100 (1%). */\n\theadroomBps?: bigint;\n\t/** When the reads were taken, echoed back as `asOfMs`. */\n\tasOfMs?: bigint;\n}\n\n/** The largest mint a market takes right now, and what binds it. A snapshot: see {@link maxMintNow}. */\nexport interface MaxMintNow {\n\t/**\n\t * The cash-limited maximum: a quantity for `'exact-quantity'`, a spend for `'budget'`. `null`\n\t * when cash doesn't bind (`p_min ≥ 1`).\n\t */\n\tcashLimitRaw: bigint | null;\n\t/** `available − fee` for `'budget'`, when a balance was given. `null` otherwise. */\n\tbalanceLimitRaw: bigint | null;\n\t/** The smaller of the two limits, or `null` when neither binds. */\n\tmaxRaw: bigint | null;\n\tlimitedBy: 'cash' | 'balance' | 'none';\n\tasOfMs: bigint | null;\n}\n\n/**\n * The largest queued mint a market's spare cash admits now (\"Max right now\"). Predict's admission\n * refuses a mint whose cash need is above spare cash (`EInsufficientMarketCash`). For exact quantity this\n * is the largest lot multiple `q` with `cashNeedExactQuantity(q) ≤ S`; for a budget it is the\n * largest `b` with `cashNeedBudget(b) ≤ S`, where `S` is spare cash less the headroom.\n *\n * It is a snapshot: fills lower spare cash, and the keeper's rebalance after each enqueue raises\n * it. Other waiting orders don't count against a mint. For exact quantity this caps only the\n * cash side: size the balance side with `cost.mintCostForBudget` at `available − fee`. A budget\n * mint with `p_min = 0` can't be placed at all (the cash need divides by `p_min`), so it reads 0.\n */\nexport function maxMintNow(inputs: MaxMintInputs): MaxMintNow {\n\tconst p = inputs.minEntryProbability;\n\tassertUint(p, 'minEntryProbability', FLOAT_SCALING);\n\tassertUint(inputs.spareCashRaw, 'spareCashRaw');\n\tconst headroom = inputs.headroomBps ?? 100n;\n\tif (headroom < 0n || headroom > 10_000n) {\n\t\tthrow new PredictInputError(`headroomBps must be in [0, 10000], got ${headroom}`);\n\t}\n\tconst spare = inputs.spareCashRaw - (inputs.spareCashRaw * headroom) / 10_000n;\n\tconst asOfMs = inputs.asOfMs ?? null;\n\n\tlet cashLimitRaw: bigint | null;\n\tlet balanceLimitRaw: bigint | null = null;\n\tif (inputs.shape === 'exact-quantity') {\n\t\tconst lot = inputs.lotSize ?? POSITION_LOT_SIZE;\n\t\tif (p >= FLOAT_SCALING) {\n\t\t\tcashLimitRaw = null;\n\t\t} else if (spare < 2n) {\n\t\t\tcashLimitRaw = 0n;\n\t\t} else {\n\t\t\tconst cap = MAX_QUANTITY_LOTS * lot;\n\t\t\tlet q = min(((spare - 1n) * FLOAT_SCALING) / (FLOAT_SCALING - p), cap);\n\t\t\tq -= q % lot;\n\t\t\twhile (q > 0n && cashNeedExactQuantity(q, p) > spare) q -= lot;\n\t\t\tcashLimitRaw = q;\n\t\t}\n\t} else {\n\t\tif (p === 0n) {\n\t\t\tcashLimitRaw = 0n;\n\t\t} else if (p >= FLOAT_SCALING) {\n\t\t\tcashLimitRaw = null;\n\t\t} else if (spare < 2n) {\n\t\t\tcashLimitRaw = 0n;\n\t\t} else {\n\t\t\tlet b = ((spare - 1n) * p) / (FLOAT_SCALING - p) - 1n;\n\t\t\twhile (b > 0n && cashNeedBudget(b, p) > spare) b -= 1n;\n\t\t\tcashLimitRaw = b > 0n ? b : 0n;\n\t\t}\n\t\tif (inputs.availableRaw != null) {\n\t\t\tconst fee = inputs.orderFeeRaw ?? 0n;\n\t\t\tbalanceLimitRaw = inputs.availableRaw > fee ? inputs.availableRaw - fee : 0n;\n\t\t}\n\t}\n\n\tif (cashLimitRaw == null && balanceLimitRaw == null) {\n\t\treturn { cashLimitRaw, balanceLimitRaw, maxRaw: null, limitedBy: 'none', asOfMs };\n\t}\n\tif (balanceLimitRaw == null || (cashLimitRaw != null && cashLimitRaw <= balanceLimitRaw)) {\n\t\treturn { cashLimitRaw, balanceLimitRaw, maxRaw: cashLimitRaw, limitedBy: 'cash', asOfMs };\n\t}\n\treturn { cashLimitRaw, balanceLimitRaw, maxRaw: balanceLimitRaw, limitedBy: 'balance', asOfMs };\n}\n\n// === Timing ===\n\n/** `(resolve_head, next_id, last_tau_ms, last_committed_tau_ms)` from `queue::queue_heads`. */\nexport interface QueueHeads {\n\tresolveHead: bigint;\n\tnextId: bigint;\n\tlastTauMs: bigint;\n\tlastCommittedTauMs: bigint;\n}\n\n/**\n * `expiry − max(no_trade_window_ms, stall_timeout_ms + 5_000)`, saturating at 0: enqueue requires\n * the order's τ below it.\n */\nexport function orderCutoffMs(\n\texpiryMs: bigint,\n\tpolicy: Pick<DelayedExecutionPolicy, 'stallTimeoutMs'>,\n\tnoTradeWindowMs: bigint,\n): bigint {\n\tconst margin = max(noTradeWindowMs, policy.stallTimeoutMs + DEADLINE_EXPIRY_MARGIN_MS);\n\treturn expiryMs > margin ? expiryMs - margin : 0n;\n}\n\n/** Inputs for {@link previewTiming}. */\nexport interface TimingPreviewInputs {\n\tnowMs: bigint;\n\tpolicy: Pick<DelayedExecutionPolicy, 'delayMs' | 'stallTimeoutMs' | 'pythChannel'>;\n\theads: QueueHeads;\n\texpiryMs: bigint;\n\tnoTradeWindowMs: bigint;\n\t/**\n\t * The newest order's channel, when known. A channel change pushes τ past the last τ, so one\n\t * cohort never mixes channels. The public reads don't expose it, so it is optional.\n\t */\n\tlastChannel?: number;\n}\n\n/** A display preview of the τ, deadline and cutoff an order placed now would get. */\nexport interface TimingPreview {\n\ttauMs: bigint;\n\t/** `min(τ + stall, expiry)`. The chain also keeps deadlines non-decreasing. */\n\tdeadlineMs: bigint;\n\tcutoffMs: bigint;\n\ttickMs: bigint;\n\t/** Whether τ is before the cutoff, so enqueue would accept the timing. */\n\tbeforeCutoff: boolean;\n}\n\n/**\n * Preview `order_queue::plan_timing`: τ is the policy channel's last tick at or before\n * `now + delay`, never below the last τ, and pushed past the last committed τ. Display only:\n * the contract uses the consensus timestamp, which can differ from the local clock.\n */\nexport function previewTiming(inputs: TimingPreviewInputs): TimingPreview {\n\tconst { policy, heads } = inputs;\n\tconst tickMs = channelTickMs(policy.pythChannel);\n\tconst rounded = ((inputs.nowMs + policy.delayMs) / tickMs) * tickMs;\n\tlet tauMs = max(rounded, heads.lastTauMs);\n\tif (\n\t\tinputs.lastChannel != null &&\n\t\theads.nextId > 0n &&\n\t\tinputs.lastChannel !== policy.pythChannel\n\t) {\n\t\ttauMs = max(rounded, nextTickAfter(heads.lastTauMs, tickMs));\n\t}\n\tif (tauMs <= heads.lastCommittedTauMs) tauMs = nextTickAfter(heads.lastCommittedTauMs, tickMs);\n\tconst deadlineMs = min(tauMs + policy.stallTimeoutMs, inputs.expiryMs);\n\tconst cutoffMs = orderCutoffMs(inputs.expiryMs, policy, inputs.noTradeWindowMs);\n\treturn { tauMs, deadlineMs, cutoffMs, tickMs, beforeCutoff: tauMs < cutoffMs };\n}\n\nfunction nextTickAfter(timeMs: bigint, tickMs: bigint): bigint {\n\treturn (timeMs / tickMs + 1n) * tickMs;\n}\n\n// === Slippage ===\n\n/** Inputs for {@link slippageBand}. All times in ms. */\nexport interface SlippageBandInputs {\n\t/** The quoted probability, in (0, 1). */\n\tprobability: number;\n\ttimeToExpiryMs: number;\n\t/** The policy's delay. */\n\tdelayMs: number;\n\t/** The channel tick: 50 or 200. */\n\ttickMs: number;\n\t/** Time between the quote and the enqueue landing. Default 500. */\n\tsigningMs?: number;\n\t/** Time between τ and the fill. Default 500. */\n\tresolveMs?: number;\n\t/** Standard deviations of movement to allow. Default 2. */\n\tk?: number;\n}\n\n/**\n * A heuristic band for a queued order's price limits: `Δp ≈ k · φ(Φ⁻¹(p)) · √(h / T)`, the\n * probability move of a digital under Brownian motion over the horizon `h` (delay + tick +\n * resolve + signing), scaled by the time `T` left. Use `maxProbability = p + Δp` on exact-quantity\n * mints and `minProbability = p − Δp` on sells, and size cost caps at the shifted probability.\n * A sizing aid pending product sign-off, not a contract rule.\n */\nexport function slippageBand(inputs: SlippageBandInputs): {\n\thorizonMs: number;\n\tdeltaProbability: number;\n\tmaxProbability: number;\n\tminProbability: number;\n} {\n\tconst p = inputs.probability;\n\tif (!(p > 0 && p < 1)) {\n\t\tthrow new PredictInputError(`probability must be in (0, 1), got ${p}`);\n\t}\n\tconst horizonMs =\n\t\tinputs.delayMs + inputs.tickMs + (inputs.resolveMs ?? 500) + (inputs.signingMs ?? 500);\n\tconst k = inputs.k ?? 2;\n\tconst delta =\n\t\tinputs.timeToExpiryMs <= horizonMs\n\t\t\t? 1\n\t\t\t: Math.min(\n\t\t\t\t\t1,\n\t\t\t\t\tk * normalPdf(inverseNormalCdf(p)) * Math.sqrt(horizonMs / inputs.timeToExpiryMs),\n\t\t\t\t);\n\treturn {\n\t\thorizonMs,\n\t\tdeltaProbability: delta,\n\t\tmaxProbability: Math.min(1, p + delta),\n\t\tminProbability: Math.max(0, p - delta),\n\t};\n}\n\n// === Order limits from a quote ===\n//\n// A queued order prices at its τ, after the quote. Its limits bound how far the price may move\n// against it in the meantime. `slippageRaw` is that move in price per contract, an absolute amount\n// and never a percentage: a contract pays $1, so 10¢ is `100_000_000n` (1e9-scaled). Each helper\n// turns a quote at the current price into the limits the enqueue takes.\n\n/** The quote a set of mint limits is sized from: the chain quote at the current price. */\nexport interface MintLimitsInputs {\n\t/** The quote's all-in cost after its fee subsidy, order fee excluded. */\n\tquoteCostRaw: bigint;\n\t/** The quote's payout quantity. */\n\tquoteQuantityRaw: bigint;\n\t/** The quote's entry probability, 1e9-scaled. */\n\tentryProbabilityRaw: bigint;\n\t/** The price move to allow per contract, 1e9-scaled: 10¢ is `100_000_000n`. */\n\tslippageRaw: bigint;\n\t/**\n\t * The quote's fee subsidy (`fee_incentive_subsidy`). Defaults to `0n`. Enqueue admission checks\n\t * the order's limits without the subsidy, and the subsidy can run out before the fill, so the\n\t * limits add it back: they are sized from the unsubsidized cost.\n\t */\n\tfeeIncentiveSubsidyRaw?: bigint;\n\t/** The deployment's `position_lot_size`. Defaults to `10_000n`. */\n\tlotSize?: bigint;\n}\n\n// Raw USDC a budget floor leaves for the per-component rounding of the fill's cost: the premium,\n// the trading, builder and referral fees and the inventory impact each round on their own.\nconst COST_ROUNDING_SLACK = 10n;\n\n/** All-in price per $1 of payout, 1e9-scaled and rounded up. */\nexport interface PricePerContract {\n\t/** The quote's price, after its fee subsidy. */\n\tnowRaw: bigint;\n\t/** The worst price the limits admit: the price without the fee subsidy, plus the slippage. */\n\tworstRaw: bigint;\n}\n\nfunction pricePerContract(inputs: MintLimitsInputs): PricePerContract {\n\tconst subsidy = inputs.feeIncentiveSubsidyRaw ?? 0n;\n\tassertUint(inputs.quoteCostRaw, 'quoteCostRaw');\n\tassertUint(inputs.quoteQuantityRaw, 'quoteQuantityRaw');\n\tassertUint(inputs.slippageRaw, 'slippageRaw', FLOAT_SCALING);\n\tassertUint(subsidy, 'feeIncentiveSubsidyRaw');\n\tif (inputs.quoteQuantityRaw === 0n) {\n\t\tthrow new PredictInputError('the quote buys no payout, so it sizes no limits');\n\t}\n\tconst nowRaw = mulDivUp(inputs.quoteCostRaw, FLOAT_SCALING, inputs.quoteQuantityRaw);\n\tconst unsubsidizedRaw = mulDivUp(\n\t\tinputs.quoteCostRaw + subsidy,\n\t\tFLOAT_SCALING,\n\t\tinputs.quoteQuantityRaw,\n\t);\n\treturn { nowRaw, worstRaw: unsubsidizedRaw + inputs.slippageRaw };\n}\n\n/**\n * Limits for a queued all-in budget mint (`enqueueMintCost`): the payout floor at the worst price.\n * The fill buys what `budgetRaw` buys at τ and refunds the order when that is below\n * `minQuantityRaw`, so the order fills while the all-in price per $1 of payout stays within\n * `slippageRaw` of the quote.\n */\nexport function budgetMintLimits(inputs: MintLimitsInputs & { budgetRaw: bigint }): {\n\tminQuantityRaw: bigint;\n\tpricePerContract: PricePerContract;\n} {\n\tassertUint(inputs.budgetRaw, 'budgetRaw');\n\tconst price = pricePerContract(inputs);\n\tconst lot = inputs.lotSize ?? POSITION_LOT_SIZE;\n\t// The fill rounds the premium and each fee on its own, so a quantity's cost can sit above\n\t// `quantity × price`. The floor leaves a few raw units of the budget for that. Inventory impact\n\t// can round by more, so `read.planMint` also checks the floor with exact quotes.\n\tconst spendable =\n\t\tinputs.budgetRaw > COST_ROUNDING_SLACK ? inputs.budgetRaw - COST_ROUNDING_SLACK : 0n;\n\tconst quantity = (spendable * FLOAT_SCALING) / price.worstRaw;\n\treturn { minQuantityRaw: (quantity / lot) * lot, pricePerContract: price };\n}\n\n/**\n * Limits for a queued exact-quantity mint (`enqueueMint`): the entry-probability cap and the\n * all-in cost cap at the worst price. The cost cap never exceeds the quantity, since a contract\n * never costs more than it pays.\n */\nexport function exactMintLimits(inputs: MintLimitsInputs): {\n\tmaxCostRaw: bigint;\n\tmaxProbabilityRaw: bigint;\n\tpricePerContract: PricePerContract;\n} {\n\tassertUint(inputs.entryProbabilityRaw, 'entryProbabilityRaw', FLOAT_SCALING);\n\tconst price = pricePerContract(inputs);\n\tconst maxCostRaw = mulDivUp(inputs.quoteQuantityRaw, price.worstRaw, FLOAT_SCALING);\n\tconst maxProbabilityRaw = inputs.entryProbabilityRaw + inputs.slippageRaw;\n\treturn {\n\t\tmaxCostRaw: min(maxCostRaw, inputs.quoteQuantityRaw),\n\t\tmaxProbabilityRaw: min(maxProbabilityRaw, FLOAT_SCALING),\n\t\tpricePerContract: price,\n\t};\n}\n\n/**\n * Limits for a queued early sell (`enqueueSell`): the close-probability floor and the proceeds\n * floor at the worst price. `proceedsRaw` is the quote's proceeds before the order fee, as\n * `minProceeds` is.\n */\nexport function sellLimits(inputs: {\n\tproceedsRaw: bigint;\n\tcloseQuantityRaw: bigint;\n\tprobabilityRaw: bigint;\n\tslippageRaw: bigint;\n}): { minProceedsRaw: bigint; minProbabilityRaw: bigint } {\n\tassertUint(inputs.proceedsRaw, 'proceedsRaw');\n\tassertUint(inputs.closeQuantityRaw, 'closeQuantityRaw');\n\tassertUint(inputs.probabilityRaw, 'probabilityRaw', FLOAT_SCALING);\n\tassertUint(inputs.slippageRaw, 'slippageRaw', FLOAT_SCALING);\n\tconst give = mulDivUp(inputs.closeQuantityRaw, inputs.slippageRaw, FLOAT_SCALING);\n\treturn {\n\t\tminProceedsRaw: inputs.proceedsRaw > give ? inputs.proceedsRaw - give : 0n,\n\t\tminProbabilityRaw:\n\t\t\tinputs.probabilityRaw > inputs.slippageRaw ? inputs.probabilityRaw - inputs.slippageRaw : 0n,\n\t};\n}\n\nfunction normalPdf(x: number): number {\n\treturn Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI);\n}\n\n// Acklam's rational approximation of Φ⁻¹, relative error below 1.15e-9.\nfunction inverseNormalCdf(p: number): number {\n\tconst a = [\n\t\t-3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 1.38357751867269e2,\n\t\t-3.066479806614716e1, 2.506628277459239,\n\t];\n\tconst b = [\n\t\t-5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1,\n\t\t-1.328068155288572e1,\n\t];\n\tconst c = [\n\t\t-7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, -2.549732539343734,\n\t\t4.374664141464968, 2.938163982698783,\n\t];\n\tconst d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996, 3.754408661907416];\n\tconst low = 0.02425;\n\tif (p < low) {\n\t\tconst q = Math.sqrt(-2 * Math.log(p));\n\t\treturn (\n\t\t\t(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /\n\t\t\t((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)\n\t\t);\n\t}\n\tif (p > 1 - low) {\n\t\tconst q = Math.sqrt(-2 * Math.log(1 - p));\n\t\treturn -(\n\t\t\t(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /\n\t\t\t((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)\n\t\t);\n\t}\n\tconst q = p - 0.5;\n\tconst r = q * q;\n\treturn (\n\t\t((((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q) /\n\t\t(((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)\n\t);\n}\n\n// === Order state ===\n\n/**\n * A queue record as `queue::order` returns it: the generated `order_queue::OrderView` layout, a\n * copy of the record without Predict's receipt and the escrow balance (`funds` is its value).\n */\nexport type QueuedOrder = (typeof OrderViewBcs)['$inferType'];\n\n/** The position a record holds: a filled mint's, a sell's, or a partial sell's remainder. */\nexport interface HeldPosition {\n\torderId: bigint;\n\trootId: bigint;\n\topenedAtMs: bigint;\n\t/**\n\t * The position's payout quantity, decoded from `orderId` at the Move lot size: a filled\n\t * mint's quantity, or what a partial sell left Open.\n\t */\n\tquantityRaw: bigint;\n}\n\ninterface OrderViewBase {\n\tstatus: number;\n\tkind: number;\n\tkindName: OrderKindName;\n\tside: 'mint' | 'sell' | 'unknown';\n}\n\n/**\n * What the app shows for one queued order. `placed` → `priced` → one of `filled` / `refunded`.\n * Report `filled` only from the record or the fill event, never from a resolve simulation.\n */\nexport type OrderView = OrderViewBase &\n\t(\n\t\t| {\n\t\t\t\tstate: 'placed';\n\t\t\t\ttauMs: bigint;\n\t\t\t\tdeadlineMs: bigint;\n\t\t\t\t/** τ has passed and the price hasn't been committed yet. */\n\t\t\t\tawaitingPrice: boolean;\n\t\t\t\t/** Keepers refund an unfinished order at its deadline. */\n\t\t\t\tautoRefundByMs: bigint;\n\t\t\t\t/** Offer \"Refund my order\": unfinished and {@link REFUND_REQUEST_GRACE_MS} past the deadline. */\n\t\t\t\tcanRequestRefund: boolean;\n\t\t }\n\t\t| {\n\t\t\t\tstate: 'priced';\n\t\t\t\ttauMs: bigint;\n\t\t\t\t/** The committed update's tick: τ, or a backup tick. */\n\t\t\t\ttickMs: bigint;\n\t\t\t\t/** The committed Pyth price, 1e9-scaled. */\n\t\t\t\tpriceRaw: bigint;\n\t\t\t\tdeadlineMs: bigint;\n\t\t\t\tmsToDeadline: bigint;\n\t\t\t\tautoRefundByMs: bigint;\n\t\t\t\tcanRequestRefund: boolean;\n\t\t }\n\t\t| {\n\t\t\t\tstate: 'refunding';\n\t\t\t\treason: RefundReasonInfo;\n\t\t\t\tdeadlineMs: bigint;\n\t\t\t\tcanRequestRefund: boolean;\n\t\t }\n\t\t| {\n\t\t\t\tstate: 'filled';\n\t\t\t\t/**\n\t\t\t\t * Filled quantity (mint) or closed quantity (sell). A partial sell's remainder is\n\t\t\t\t * `position.quantityRaw`.\n\t\t\t\t */\n\t\t\t\tquantityRaw: bigint;\n\t\t\t\t/** Cost paid (mint) or proceeds before the order fee (sell). */\n\t\t\t\tamountRaw: bigint;\n\t\t\t\tfinishedAtMs: bigint;\n\t\t\t\t/** The Open record's position: a filled mint, or a partial sell's remainder. */\n\t\t\t\tposition: HeldPosition | null;\n\t\t\t\t/** Whether `enqueue_redeem_open` can sell this record now. */\n\t\t\t\tsellable: boolean;\n\t\t\t\t/** See {@link ParkedFunds}. */\n\t\t\t\tparkedRaw: bigint;\n\t\t }\n\t\t| {\n\t\t\t\tstate: 'refunded';\n\t\t\t\treason: RefundReasonInfo;\n\t\t\t\tfinishedAtMs: bigint;\n\t\t\t\t/** A refunded sell keeps its position as an Open record, sellable again. */\n\t\t\t\tpositionBackAsOpenRecord: boolean;\n\t\t\t\tposition: HeldPosition | null;\n\t\t\t\tsellable: boolean;\n\t\t\t\t/** See {@link ParkedFunds}. */\n\t\t\t\tparkedRaw: bigint;\n\t\t }\n\t\t| {\n\t\t\t\t/** A filled mint's record whose position was later sold or settled. */\n\t\t\t\tstate: 'closed';\n\t\t\t\tquantityRaw: bigint;\n\t\t\t\tamountRaw: bigint;\n\t\t\t\tfinishedAtMs: bigint;\n\t\t\t\t/** See {@link ParkedFunds}. */\n\t\t\t\tparkedRaw: bigint;\n\t\t }\n\t\t| { state: 'unknown' }\n\t);\n\n/**\n * `parkedRaw` on a finished record: USDC the record kept because its receive address couldn't take\n * it (on USDC's deny list, or USDC paused) when its change or refund was sent. It is the\n * record's `funds`, which holds only parked USDC once the order finishes. Anyone can send it with\n * `claim_parked` once the address is clear. `0n` when nothing is parked.\n */\nexport type ParkedFunds = bigint;\n\nfunction heldPosition(p: QueuedOrder['position'], lotSize?: bigint): HeldPosition | null {\n\treturn p.order_id === 0n\n\t\t? null\n\t\t: {\n\t\t\t\torderId: p.order_id,\n\t\t\t\trootId: p.root_id,\n\t\t\t\topenedAtMs: p.opened_at_ms,\n\t\t\t\tquantityRaw: decodeOrderRange(p.order_id, lotSize).quantity,\n\t\t\t};\n}\n\n/**\n * Map a queue record to its display state. `nowMs` drives the refund flags. A record is sellable\n * while it is Open, holds a position, and `nowMs` is before the cutoff (`opts.cutoffMs`, or the\n * record's own placement cutoff when omitted). Unknown status or kind codes map to `unknown`.\n * `opts.lotSize` is the config's position lot (default 10,000, Predict's), which decodes a held\n * position's quantity.\n */\nexport function orderView(\n\trecord: QueuedOrder,\n\tnowMs: bigint,\n\topts: { cutoffMs?: bigint; lotSize?: bigint } = {},\n): OrderView {\n\tconst kind = record.kind;\n\tconst base: OrderViewBase = {\n\t\tstatus: record.status,\n\t\tkind,\n\t\tkindName: orderKindName(kind),\n\t\tside: isMintKind(kind) ? 'mint' : isSellKind(kind) ? 'sell' : 'unknown',\n\t};\n\tif (base.side === 'unknown') return { ...base, state: 'unknown' };\n\tconst { tau_ms: tauMs, deadline_ms: deadlineMs } = record.timing;\n\tconst canRequestRefund = nowMs >= deadlineMs + REFUND_REQUEST_GRACE_MS;\n\tconst position = heldPosition(record.position, opts.lotSize);\n\tconst cutoffMs = opts.cutoffMs ?? record.timing.cutoff_ms;\n\tconst sellable = position != null && nowMs < cutoffMs;\n\tconst result = record.result;\n\t// Only read on the finished statuses below, where `funds` holds parked USDC, not escrow.\n\tconst parkedRaw = record.funds;\n\tswitch (record.status) {\n\t\tcase ORDER_STATUS.PENDING:\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'placed',\n\t\t\t\ttauMs,\n\t\t\t\tdeadlineMs,\n\t\t\t\tawaitingPrice: nowMs >= tauMs,\n\t\t\t\tautoRefundByMs: deadlineMs,\n\t\t\t\tcanRequestRefund,\n\t\t\t};\n\t\tcase ORDER_STATUS.COMMITTED:\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'priced',\n\t\t\t\ttauMs,\n\t\t\t\ttickMs: record.price.tick_ms,\n\t\t\t\tpriceRaw: record.price.spot,\n\t\t\t\tdeadlineMs,\n\t\t\t\tmsToDeadline: deadlineMs > nowMs ? deadlineMs - nowMs : 0n,\n\t\t\t\tautoRefundByMs: deadlineMs,\n\t\t\t\tcanRequestRefund,\n\t\t\t};\n\t\tcase ORDER_STATUS.REFUND_DUE:\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'refunding',\n\t\t\t\treason: refundReason(result.reason),\n\t\t\t\tdeadlineMs,\n\t\t\t\tcanRequestRefund,\n\t\t\t};\n\t\tcase ORDER_STATUS.OPEN:\n\t\t\tif (base.side === 'sell' && result.reason > 0) {\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tstate: 'refunded',\n\t\t\t\t\treason: refundReason(result.reason),\n\t\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\t\tpositionBackAsOpenRecord: true,\n\t\t\t\t\tposition,\n\t\t\t\t\tsellable,\n\t\t\t\t\tparkedRaw,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'filled',\n\t\t\t\tquantityRaw: result.quantity,\n\t\t\t\tamountRaw: result.amount,\n\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\tposition,\n\t\t\t\tsellable,\n\t\t\t\tparkedRaw,\n\t\t\t};\n\t\tcase ORDER_STATUS.REFUNDED:\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'refunded',\n\t\t\t\treason: refundReason(result.reason),\n\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\tpositionBackAsOpenRecord: false,\n\t\t\t\tposition: null,\n\t\t\t\tsellable: false,\n\t\t\t\tparkedRaw,\n\t\t\t};\n\t\tcase ORDER_STATUS.CLOSED:\n\t\t\t// A sell record that filled stays `filled` after its remainder moves on; a mint record\n\t\t\t// (or a refunded sell sold again) is `closed` once its position left.\n\t\t\tif (base.side === 'sell' && result.reason === 0 && result.quantity > 0n) {\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tstate: 'filled',\n\t\t\t\t\tquantityRaw: result.quantity,\n\t\t\t\t\tamountRaw: result.amount,\n\t\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\t\tposition: null,\n\t\t\t\t\tsellable: false,\n\t\t\t\t\tparkedRaw,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'closed',\n\t\t\t\tquantityRaw: result.quantity,\n\t\t\t\tamountRaw: result.amount,\n\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\tparkedRaw,\n\t\t\t};\n\t\tdefault:\n\t\t\treturn { ...base, state: 'unknown' };\n\t}\n}\n\n/** One record's state rebuilt from events, for the app's event path (indexer or own effects). */\nexport interface OrderEventState {\n\tmarketId: string;\n\trecordId: bigint;\n\t/**\n\t * `closed`: the record's position moved into a later sell's record (`enqueue_redeem_open` closes\n\t * the source record), so this record holds nothing any more.\n\t */\n\tstate: 'placed' | 'priced' | 'filled' | 'refunded' | 'settled' | 'closed';\n\tkind: number | null;\n\ttauMs: bigint | null;\n\tdeadlineMs: bigint | null;\n\t/** Set once priced: the committed Pyth price as a float (`spot / 1e9`) and its tick. */\n\tprice: number | null;\n\ttickMs: bigint | null;\n\t/**\n\t * Set on a refund. The settlement drain (`settle_step`) refunds the orders still waiting at\n\t * expiry with reason 5 (deadline), like a keeper's deadline refund.\n\t */\n\treason: RefundReasonInfo | null;\n\t/**\n\t * The position the record holds now, or null. A sell's record takes its source's position at\n\t * enqueue and keeps it through a refund, a fill leaves a mint's new position or a partial\n\t * sell's remainder, and a later sell, a full close or settlement clears it.\n\t */\n\tposition: HeldPosition | null;\n\t/** For a sell: the record its position came from. */\n\tsourceRecordId: bigint | null;\n\t/** Set when `settle_step` or `pay_open` paid the record (0 for a loser). */\n\tpayoutRaw: bigint | null;\n\t/** True after `OpenRecordPayoutSkipped`: the record stays Open, unpaid for now. */\n\tpayoutSkipped: boolean;\n\t/**\n\t * USDC the record holds parked (`RecordFundsParked`, summed) until `RecordFundsClaimed`. See\n\t * {@link ParkedFunds}.\n\t */\n\tparkedRaw: bigint;\n}\n\n/**\n * Fold decoded queue events (in chain order) into per-record states, keyed `marketId:recordId`.\n * The app shows Placed from the enqueue's own effects, Priced at the cohort commit, and switches to\n * Filled or Refunded on `QueuedOrderFilled` / `QueuedOrderRefunded`. Events for records that never\n * appeared enqueued still create an entry, so a partial event window works.\n */\nexport function reduceOrderEvents(\n\tevents: readonly QueueEvent[],\n\tinto: Map<string, OrderEventState> = new Map(),\n): Map<string, OrderEventState> {\n\tconst entry = (marketId: string, recordId: bigint): OrderEventState => {\n\t\tconst key = `${marketId}:${recordId}`;\n\t\tlet s = into.get(key);\n\t\tif (!s) {\n\t\t\ts = {\n\t\t\t\tmarketId,\n\t\t\t\trecordId,\n\t\t\t\tstate: 'placed',\n\t\t\t\tkind: null,\n\t\t\t\ttauMs: null,\n\t\t\t\tdeadlineMs: null,\n\t\t\t\tprice: null,\n\t\t\t\ttickMs: null,\n\t\t\t\treason: null,\n\t\t\t\tposition: null,\n\t\t\t\tsourceRecordId: null,\n\t\t\t\tpayoutRaw: null,\n\t\t\t\tpayoutSkipped: false,\n\t\t\t\tparkedRaw: 0n,\n\t\t\t};\n\t\t\tinto.set(key, s);\n\t\t}\n\t\treturn s;\n\t};\n\tfor (const e of events) {\n\t\tswitch (e.type) {\n\t\t\tcase 'enqueued': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.kind = e.kind;\n\t\t\t\ts.tauMs = e.timing.tauMs;\n\t\t\t\ts.deadlineMs = e.timing.deadlineMs;\n\t\t\t\t// A sell moves the whole position out of its source record, which the chain marks\n\t\t\t\t// Closed, and into the new record, which holds it until the sell fills or refunds.\n\t\t\t\ts.position = e.position;\n\t\t\t\ts.sourceRecordId = e.sourceRecordId;\n\t\t\t\tif (e.sourceRecordId != null) {\n\t\t\t\t\tconst source = entry(e.marketId, e.sourceRecordId);\n\t\t\t\t\tsource.state = 'closed';\n\t\t\t\t\tsource.position = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'cohort-committed':\n\t\t\t\tfor (const s of into.values()) {\n\t\t\t\t\tif (\n\t\t\t\t\t\ts.marketId === e.marketId &&\n\t\t\t\t\t\ts.state === 'placed' &&\n\t\t\t\t\t\ts.recordId >= e.firstRecordId &&\n\t\t\t\t\t\ts.recordId <= e.lastRecordId\n\t\t\t\t\t) {\n\t\t\t\t\t\ts.state = 'priced';\n\t\t\t\t\t\ts.price = e.price;\n\t\t\t\t\t\ts.tickMs = e.tickMs;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'filled': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.state = 'filled';\n\t\t\t\ts.kind = e.kind;\n\t\t\t\ts.tickMs = e.tickMs;\n\t\t\t\ts.position = e.position;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'refunded': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.state = 'refunded';\n\t\t\t\ts.kind = e.kind;\n\t\t\t\ts.reason = e.reason;\n\t\t\t\t// A refunded sell keeps its position, Open and sellable again from this record.\n\t\t\t\tif (!e.positionReturned) s.position = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'open-record-settled': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.state = 'settled';\n\t\t\t\ts.payoutRaw = e.raw.payout;\n\t\t\t\ts.payoutSkipped = false;\n\t\t\t\ts.position = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'open-record-payout-skipped': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.payoutSkipped = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'record-funds-parked': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.parkedRaw += e.raw.amount;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'record-funds-claimed': {\n\t\t\t\t// `claim_parked` sends everything the record had parked.\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.parkedRaw = 0n;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn into;\n}\n\nfunction min(a: bigint, b: bigint): bigint {\n\treturn a < b ? a : b;\n}\n\nfunction max(a: bigint, b: bigint): bigint {\n\treturn a > b ? a : b;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,4BAA4B;;;;;;;AAQzC,MAAa,0BAA0B;;;;;;AAOvC,MAAa,6BAA6B;;AAG1C,MAAa,eAAe,OAAO,OAAO;CAEzC,OAAO;CAEP,KAAK;CAKL,MAAM;CACN,CAAU;;AAGX,MAAa,eAAe,OAAO,OAAO;CACzC,SAAS;CACT,WAAW;CACX,MAAM;CACN,UAAU;CACV,QAAQ;CAER,YAAY;CACZ,CAAU;;AAGX,MAAa,aAAa,OAAO,OAAO;CACvC,gBAAgB;CAChB,cAAc;CACd,YAAY;CACZ,aAAa;CACb,aAAa;CACb,CAAU;;AAGX,MAAa,gBAAgB,OAAO,OAAO;CAC1C,QAAQ;CACR,WAAW;CACX,UAAU;CACV,cAAc;CACd,UAAU;CACV,QAAQ;CACR,OAAO;CACP,SAAS;CACT,kBAAkB;CAClB,CAAU;;AAGX,MAAa,eAAe,OAAO,OAAO;CACzC,iBAAiB;CACjB,kBAAkB;CAClB,CAAU;;AAGX,MAAa,4BAA4B;;;;;AAMzC,MAAa,0BAA0B;AAQvC,MAAM,eAA2C;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;AACD,MAAM,aAAuC;CAC5C;CACA;CACA;CACA;CACA;CACA;;AAGD,SAAgB,gBAAgB,MAA+B;AAC9D,QAAO,aAAa,SAAS;;;AAI9B,SAAgB,cAAc,MAA6B;AAC1D,QAAO,WAAW,SAAS;;;AAI5B,SAAgB,WAAW,MAAuB;AACjD,QACC,SAAS,WAAW,kBACpB,SAAS,WAAW,g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,CAC5B,KACC,EAAE,aAAa,EAAE,YACjB,EAAE,UAAU,YACZ,EAAE,YAAY,EAAE,iBAChB,EAAE,YAAY,EAAE,cACf;AACD,MAAE,QAAQ;AACV,MAAE,QAAQ,EAAE;AACZ,MAAE,SAAS,EAAE;;AAGf;EACD,KAAK,UAAU;GACd,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,QAAQ;AACV,KAAE,OAAO,EAAE;AACX,KAAE,SAAS,EAAE;AACb,KAAE,WAAW,EAAE;AACf;;EAED,KAAK,YAAY;GAChB,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,QAAQ;AACV,KAAE,OAAO,EAAE;AACX,KAAE,SAAS,EAAE;AAEb,OAAI,CAAC,EAAE,iBAAkB,GAAE,WAAW;AACtC;;EAED,KAAK,uBAAuB;GAC3B,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,QAAQ;AACV,KAAE,YAAY,EAAE,IAAI;AACpB,KAAE,gBAAgB;AAClB,KAAE,WAAW;AACb;;EAED,KAAK,8BAA8B;GAClC,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,gBAAgB;AAClB;;EAED,KAAK,uBAAuB;GAC3B,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,aAAa,EAAE,IAAI;AACrB;;EAED,KAAK,wBAAwB;GAE5B,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,YAAY;AACd;;EAED,QACC;;AAGH,QAAO;;AAGR,SAAS,IAAI,GAAW,GAAmB;AAC1C,QAAO,IAAI,IAAI,IAAI;;AAGpB,SAAS,IAAI,GAAW,GAAmB;AAC1C,QAAO,IAAI,IAAI,IAAI"}
1
+ {"version":3,"file":"queue.mjs","names":["max","q"],"sources":["../../src/predict/queue.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Delayed execution (DBU-885): the codes, cash-need math, timing previews and order-state views\n// for queued orders. Pure functions over raw bigints, no network. Exported as the `queue`\n// namespace, like `cost` and `pricing`.\n//\n// A queued order is placed now and priced later at Pyth's signed price for its τ, a channel\n// tick shortly after placement. A keeper (or anyone, see `fill` in `tx/queue.ts`) commits the\n// price and resolves the order: a fill, or a refund with a reason code. A filled mint stays in\n// its market's queue as an Open record until `enqueue_redeem_open` sells it or the queue's\n// settlement walk (`settle_step`) pays it.\n//\n// The queue lives in the order-flow companion, `deepbook_predict_orders`. The code values mirror\n// its `order_queue` getters, and the cash-need formulas are 1:1 ports (rounding included) of\n// `deepbook_predict_math::math::need_*`, which Predict's admission charges. Probabilities and λ\n// are 1e9-scaled.\n\nimport type { DelayedExecutionPolicy as DelayedExecutionPolicyBcs } from '../contracts/deepbook_predict_orders/delayed_execution_config.js';\nimport type { OrderView as OrderViewBcs } from '../contracts/deepbook_predict_orders/order_queue.js';\nimport { FLOAT_SCALING, MAX_QUANTITY_LOTS, POSITION_LOT_SIZE, decodeOrderRange } from './cost.js';\nimport type { QueueEvent } from './decode.js';\nimport { PredictInputError } from './errors.js';\nimport { U64_MAX } from './units.js';\n\n// === Codes ===\n\n/**\n * Predict's `constants::current_version` from the upgrade that added delayed execution. Enqueue\n * works once `ProtocolConfig.version_watermark` reaches it (Predict's admission aborts\n * `ECutoverNotReached` until then). The retired immediate trades (`mint_exact_*`, `redeem_live`)\n * always abort in that package, and the older packages they still run in are retired by the same\n * bump. The same on both networks: it is the code's version constant, not the on-chain package\n * version (Mainnet v4, Testnet v5).\n */\nexport const DELAYED_EXECUTION_VERSION = 4n;\n\n/**\n * Predict's `constants::current_version` of the package these bindings were generated from. Every\n * version-gated Predict call checks `chk_version`, which aborts `EPackageVersionDisabled` once\n * `ProtocolConfig.version_watermark` is above it, so a higher watermark retires the Predict code\n * this SDK calls. Bump it with Predict when regenerating. Like `DELAYED_EXECUTION_VERSION` it is the\n * code's version constant, which follows the Mainnet package number (5 ships as Mainnet v5 and runs\n * as Testnet package v8), never the Testnet package number.\n */\nexport const PREDICT_PACKAGE_VERSION = 5n;\n\n/**\n * `desk::current_version` of the order-flow package these bindings were generated from. The desk's\n * version floor retires older companion code, so a floor above it means the package this SDK calls\n * aborts `EPackageVersionDisabled`. Bump it with the companion when regenerating. It follows the\n * Mainnet package number (2 ships as Mainnet v2 and runs as Testnet package v3), never the Testnet\n * package number.\n */\nexport const ORDER_FLOW_PACKAGE_VERSION = 2n;\n\n/** `queue::phase_*`: what `settle_step` returns, the phase the next call runs. */\nexport const SETTLE_PHASE = Object.freeze({\n\t/** Refunding the waiting orders (reason 5). */\n\tDRAIN: 0,\n\t/** Paying the Open records, once Predict has settled the market. */\n\tPAY: 1,\n\t/**\n\t * The payout walk reached the last record and `MarketPayoutsCompleted` was emitted. A record\n\t * the market couldn't pay (`OpenRecordPayoutSkipped`) stays Open and unpaid.\n\t */\n\tDONE: 2,\n} as const);\n\n/** `order_queue::status_*`. Never renumbered on chain; unknown codes still decode. */\nexport const ORDER_STATUS = Object.freeze({\n\tPENDING: 0,\n\tCOMMITTED: 1,\n\tOPEN: 2,\n\tREFUNDED: 3,\n\tCLOSED: 4,\n\t/** Reserved: nothing sets it at launch. Counts as unfinished. */\n\tREFUND_DUE: 5,\n} as const);\n\n/** `order_queue::kind_*`. `REDEEM_LIVE` is reserved and never used by v4. */\nexport const ORDER_KIND = Object.freeze({\n\tEXACT_QUANTITY: 0,\n\tEXACT_AMOUNT: 1,\n\tEXACT_COST: 2,\n\tREDEEM_LIVE: 3,\n\tREDEEM_OPEN: 4,\n} as const);\n\n/** `order_queue::reason_*`. `0` in a record's result means filled. */\nexport const REFUND_REASON = Object.freeze({\n\tLIMITS: 1,\n\tADMISSION: 2,\n\tNO_PRICE: 3,\n\tMISSING_NODE: 4,\n\tDEADLINE: 5,\n\tFREEZE: 6,\n\tADMIN: 7,\n\tNO_CASH: 8,\n\tRECIPIENT_DENIED: 9,\n} as const);\n\n/** The Pyth Lazer channels the queue prices on (`delayed_execution_config`). */\nexport const PYTH_CHANNEL = Object.freeze({\n\tFIXED_RATE_50MS: 2,\n\tFIXED_RATE_200MS: 3,\n} as const);\n\n/** Predict's `constants::deadline_expiry_margin_ms`: every deadline is at least this long before expiry. */\nexport const DEADLINE_EXPIRY_MARGIN_MS = 5_000n;\n\n/**\n * How long after an order's deadline the app waits before offering \"Refund my order\". Keepers\n * refund overdue orders on their own, so the button only matters when they are all down.\n */\nexport const REFUND_REQUEST_GRACE_MS = 5_000n;\n\nexport type OrderStatusName =\n\t'pending' | 'committed' | 'open' | 'refunded' | 'closed' | 'refund-due' | 'unknown';\n\nexport type OrderKindName =\n\t'exact-quantity' | 'exact-amount' | 'exact-cost' | 'redeem-live' | 'redeem-open' | 'unknown';\n\nconst STATUS_NAMES: readonly OrderStatusName[] = [\n\t'pending',\n\t'committed',\n\t'open',\n\t'refunded',\n\t'closed',\n\t'refund-due',\n];\nconst KIND_NAMES: readonly OrderKindName[] = [\n\t'exact-quantity',\n\t'exact-amount',\n\t'exact-cost',\n\t'redeem-live',\n\t'redeem-open',\n];\n\n/** A status code's name, or `'unknown'` for a code this SDK version predates. */\nexport function orderStatusName(code: number): OrderStatusName {\n\treturn STATUS_NAMES[code] ?? 'unknown';\n}\n\n/** A kind code's name, or `'unknown'` for a code this SDK version predates. */\nexport function orderKindName(code: number): OrderKindName {\n\treturn KIND_NAMES[code] ?? 'unknown';\n}\n\n/** Whether a kind code is a queued mint (exact quantity, exact amount or exact cost). */\nexport function isMintKind(kind: number): boolean {\n\treturn (\n\t\tkind === ORDER_KIND.EXACT_QUANTITY ||\n\t\tkind === ORDER_KIND.EXACT_AMOUNT ||\n\t\tkind === ORDER_KIND.EXACT_COST\n\t);\n}\n\n/** Whether a kind code is a queued sell. */\nexport function isSellKind(kind: number): boolean {\n\treturn kind === ORDER_KIND.REDEEM_OPEN || kind === ORDER_KIND.REDEEM_LIVE;\n}\n\n/** What a refund reason means for the trader. */\nexport interface RefundReasonInfo {\n\tcode: number;\n\tkey:\n\t\t| 'limits'\n\t\t| 'admission'\n\t\t| 'no-price'\n\t\t| 'missing-node'\n\t\t| 'deadline'\n\t\t| 'freeze'\n\t\t| 'admin'\n\t\t| 'no-cash'\n\t\t| 'recipient-denied'\n\t\t| 'unknown';\n\t/** Display text for the refund. */\n\ttext: string;\n\t/** Whether the order fee was kept (reasons 1 and 2). `null` for an unknown code. */\n\tfeeKept: boolean | null;\n\t/** False for codes v4 reserves but never sets (3 and 6), and for unknown codes. */\n\tlive: boolean;\n}\n\n/** Every reason code v4 defines, with its text and fee treatment. */\nexport const REFUND_REASONS: Readonly<Record<number, RefundReasonInfo>> = Object.freeze({\n\t1: {\n\t\tcode: 1,\n\t\tkey: 'limits',\n\t\ttext: \"Your price limits weren't met at the fill price. Refunded, the order fee is kept.\",\n\t\tfeeKept: true,\n\t\tlive: true,\n\t},\n\t2: {\n\t\tcode: 2,\n\t\tkey: 'admission',\n\t\ttext: \"The market couldn't accept the order at the fill price. Refunded, the order fee is kept.\",\n\t\tfeeKept: true,\n\t\tlive: true,\n\t},\n\t3: {\n\t\tcode: 3,\n\t\tkey: 'no-price',\n\t\ttext: 'No price arrived for the order. Refunded in full.',\n\t\tfeeKept: false,\n\t\tlive: false,\n\t},\n\t4: {\n\t\tcode: 4,\n\t\tkey: 'missing-node',\n\t\ttext: \"The market couldn't place the order. Refunded in full.\",\n\t\tfeeKept: false,\n\t\tlive: true,\n\t},\n\t5: {\n\t\tcode: 5,\n\t\tkey: 'deadline',\n\t\ttext: \"The order wasn't priced before its deadline. Refunded in full.\",\n\t\tfeeKept: false,\n\t\tlive: true,\n\t},\n\t6: {\n\t\tcode: 6,\n\t\tkey: 'freeze',\n\t\ttext: 'The protocol was frozen. Refunded in full.',\n\t\tfeeKept: false,\n\t\tlive: false,\n\t},\n\t7: { code: 7, key: 'admin', text: 'Refunded in full by an admin.', feeKept: false, live: true },\n\t8: {\n\t\tcode: 8,\n\t\tkey: 'no-cash',\n\t\ttext: \"The market couldn't pay right now. Refunded in full.\",\n\t\tfeeKept: false,\n\t\tlive: true,\n\t},\n\t9: {\n\t\tcode: 9,\n\t\tkey: 'recipient-denied',\n\t\ttext: \"The account's receive address can't take USDC right now (it is on USDC's deny list, or USDC is paused). Refunded in full, and the refund waits in the order until it can be claimed.\",\n\t\tfeeKept: false,\n\t\tlive: true,\n\t},\n});\n\n/** A reason code's meaning. Unknown codes map to `key: 'unknown'` rather than throwing. */\nexport function refundReason(code: number): RefundReasonInfo {\n\treturn (\n\t\tREFUND_REASONS[code] ?? {\n\t\t\tcode,\n\t\t\tkey: 'unknown',\n\t\t\ttext: `Refunded (code ${code}).`,\n\t\t\tfeeKept: null,\n\t\t\tlive: false,\n\t\t}\n\t);\n}\n\n// === Policy ===\n\n/**\n * `delayed_execution_config::DelayedExecutionPolicy` with camelCase keys, as the companion's\n * `OrderDesk` holds it (`desk::policy`). Times in ms, USDC raw.\n */\nexport interface DelayedExecutionPolicy {\n\tdelayMs: bigint;\n\tstallTimeoutMs: bigint;\n\tstuckThresholdMs: bigint;\n\tgapWaitMs: bigint;\n\tpythPriceBufferMs: bigint;\n\t/** {@link PYTH_CHANNEL}: `2` is 50 ms, `3` is 200 ms. */\n\tpythChannel: number;\n\tsviMaxAgeMs: bigint;\n\tmintCapacity: bigint;\n\tsellCapacity: bigint;\n\tperAccountCap: bigint;\n\t/** Flat USDC fee charged at enqueue, raw. */\n\torderFee: bigint;\n\tminSellQuantity: bigint;\n\tsettleRefundBatch: bigint;\n\tsettlePayoutBatch: bigint;\n}\n\n/** Map the generated policy layout to {@link DelayedExecutionPolicy}. */\nexport function policyFromBcs(\n\tp: (typeof DelayedExecutionPolicyBcs)['$inferType'],\n): DelayedExecutionPolicy {\n\treturn {\n\t\tdelayMs: p.delay_ms,\n\t\tstallTimeoutMs: p.stall_timeout_ms,\n\t\tstuckThresholdMs: p.stuck_threshold_ms,\n\t\tgapWaitMs: p.gap_wait_ms,\n\t\tpythPriceBufferMs: p.pyth_price_buffer_ms,\n\t\tpythChannel: p.pyth_channel,\n\t\tsviMaxAgeMs: p.svi_max_age_ms,\n\t\tmintCapacity: p.mint_capacity,\n\t\tsellCapacity: p.sell_capacity,\n\t\tperAccountCap: p.per_account_cap,\n\t\torderFee: p.order_fee,\n\t\tminSellQuantity: p.min_sell_quantity,\n\t\tsettleRefundBatch: p.settle_refund_batch,\n\t\tsettlePayoutBatch: p.settle_payout_batch,\n\t};\n}\n\n/** `delayed_execution_config::channel_tick_ms`: 50 ms for channel 2, 200 ms for channel 3. */\nexport function channelTickMs(channel: number): bigint {\n\tif (channel === PYTH_CHANNEL.FIXED_RATE_50MS) return 50n;\n\tif (channel === PYTH_CHANNEL.FIXED_RATE_200MS) return 200n;\n\tthrow new PredictInputError(`unsupported Pyth Lazer channel ${channel}`);\n}\n\n// === Cash need (`deepbook_predict_math::math::need_*`) ===\n\nfunction assertUint(value: bigint, name: string, max: bigint = U64_MAX): void {\n\tif (typeof value !== 'bigint' || value < 0n || value > max) {\n\t\tthrow new PredictInputError(`${name} must be a bigint in [0, ${max}], got ${String(value)}`);\n\t}\n}\n\n// `math::mul_div_up`, including its abort on a zero denominator and a u64 overflow.\nfunction mulDivUp(x: bigint, y: bigint, denominator: bigint): bigint {\n\tif (denominator === 0n) throw new PredictInputError('division by zero (EInputZero)');\n\treturn (x * y + denominator - 1n) / denominator;\n}\n\nfunction plusOne(need: bigint): bigint {\n\tif (need >= U64_MAX) throw new PredictInputError('cash need overflows u64');\n\treturn need + 1n;\n}\n\n/** Exact-quantity mint cash need: `⌈quantity · (1 − p_min)⌉ + 1`. */\nexport function cashNeedExactQuantity(quantity: bigint, minEntryProbability: bigint): bigint {\n\tassertUint(quantity, 'quantity');\n\tassertUint(minEntryProbability, 'minEntryProbability', FLOAT_SCALING);\n\treturn plusOne(mulDivUp(quantity, FLOAT_SCALING - minEntryProbability, FLOAT_SCALING));\n}\n\n/**\n * Budget mint cash need: `⌈(budget + 1) · (1 / p_min − 1)⌉ + 1`, rounded as Move rounds it (one\n * `mul_div_up` of `(budget + 1) · (1e9 − p_min) / p_min`). Exact-amount mints pass\n * `min(max_premium, budget)`. `p_min = 0` throws, as the Move division aborts.\n */\nexport function cashNeedBudget(budget: bigint, minEntryProbability: bigint): bigint {\n\tassertUint(budget, 'budget', U64_MAX - 1n);\n\tassertUint(minEntryProbability, 'minEntryProbability', FLOAT_SCALING);\n\treturn plusOne(mulDivUp(budget + 1n, FLOAT_SCALING - minEntryProbability, minEntryProbability));\n}\n\n/** Sell cash need: `⌈close_quantity · (1 − λ)⌉ + 1`. */\nexport function cashNeedSell(closeQuantity: bigint, backingBufferLambda: bigint): bigint {\n\tassertUint(closeQuantity, 'closeQuantity');\n\tassertUint(backingBufferLambda, 'backingBufferLambda', FLOAT_SCALING);\n\treturn plusOne(mulDivUp(closeQuantity, FLOAT_SCALING - backingBufferLambda, FLOAT_SCALING));\n}\n\n/**\n * Whether the account can pay the order fee: a mint needs `available > fee` (it escrows a budget\n * on top), a sell needs `available ≥ fee` (it escrows only the fee). `available` is\n * `account::balance<USDC>`, unsettled accumulator funds included.\n */\nexport function feeCovered(\n\tside: 'mint' | 'sell',\n\tavailableRaw: bigint,\n\torderFeeRaw: bigint,\n): boolean {\n\treturn side === 'mint' ? availableRaw > orderFeeRaw : availableRaw >= orderFeeRaw;\n}\n\n/** Inputs for {@link mintBudget}. */\nexport interface MintBudgetInputs {\n\t/** {@link ORDER_KIND}: a mint kind. */\n\tkind: number;\n\tmaxCostRaw: bigint;\n\tavailableRaw: bigint;\n\torderFeeRaw: bigint;\n\t/** Required for exact quantity: a fill never costs more than its quantity. */\n\tquantityRaw?: bigint;\n}\n\n/**\n * The budget a queued mint escrows: `min(max_cost, available − fee)`, and for exact quantity also\n * at most the quantity. `null` when the balance doesn't cover the fee. Enqueue debits the budget\n * plus the order fee, and the unspent budget comes back at the fill.\n */\nexport function mintBudget(inputs: MintBudgetInputs): bigint | null {\n\tif (!feeCovered('mint', inputs.availableRaw, inputs.orderFeeRaw)) return null;\n\tconst budget = min(inputs.maxCostRaw, inputs.availableRaw - inputs.orderFeeRaw);\n\tif (inputs.kind !== ORDER_KIND.EXACT_QUANTITY) return budget;\n\tif (inputs.quantityRaw == null) {\n\t\tthrow new PredictInputError('quantityRaw is required for an exact-quantity budget');\n\t}\n\treturn min(budget, inputs.quantityRaw);\n}\n\n/** Inputs for {@link mintCashNeed}. */\nexport interface MintCashNeedInputs {\n\tkind: number;\n\t/** The escrowed budget, from {@link mintBudget}. */\n\tbudgetRaw: bigint;\n\tminEntryProbability: bigint;\n\t/** Exact quantity: the quantity ordered. */\n\tquantityRaw?: bigint;\n\t/** Exact amount: the premium cap. */\n\tmaxPremiumRaw?: bigint;\n}\n\n/** A queued mint's cash need, picking the formula the contract picks for its kind. */\nexport function mintCashNeed(inputs: MintCashNeedInputs): bigint {\n\tconst p = inputs.minEntryProbability;\n\tswitch (inputs.kind) {\n\t\tcase ORDER_KIND.EXACT_QUANTITY:\n\t\t\tif (inputs.quantityRaw == null) throw new PredictInputError('quantityRaw is required');\n\t\t\treturn cashNeedExactQuantity(inputs.quantityRaw, p);\n\t\tcase ORDER_KIND.EXACT_AMOUNT:\n\t\t\tif (inputs.maxPremiumRaw == null) throw new PredictInputError('maxPremiumRaw is required');\n\t\t\treturn cashNeedBudget(min(inputs.maxPremiumRaw, inputs.budgetRaw), p);\n\t\tcase ORDER_KIND.EXACT_COST:\n\t\t\treturn cashNeedBudget(inputs.budgetRaw, p);\n\t\tdefault:\n\t\t\tthrow new PredictInputError(`kind ${inputs.kind} is not a mint`);\n\t}\n}\n\n/**\n * A sell's cash need against the market's spare cash. Sells are never refused for market cash at\n * placement: the keeper funds the market before τ, and a sell the market still can't cover at the\n * fill is refunded in full (reason 8). `short` flags that risk, and the sell builder can add\n * `rebalance_expiry_cash` after the enqueue to fund the market at once.\n */\nexport function sellCashCheck(\n\tcloseQuantityRaw: bigint,\n\tspareCashRaw: bigint,\n\tbackingBufferLambda: bigint,\n): { needRaw: bigint; short: boolean } {\n\tconst needRaw = cashNeedSell(closeQuantityRaw, backingBufferLambda);\n\treturn { needRaw, short: needRaw > spareCashRaw };\n}\n\n// === Largest mint the market takes now ===\n\n/** Inputs for {@link maxMintNow}. */\nexport interface MaxMintInputs {\n\t/** `'exact-quantity'` sizes a quantity; `'budget'` sizes an exact-cost or exact-amount spend. */\n\tshape: 'exact-quantity' | 'budget';\n\t/** Market cash above required cash (`MarketQueueState.spareCash`). */\n\tspareCashRaw: bigint;\n\t/** The minimum entry probability from `expiry_market::order_flow_state`, 1e9-scaled. */\n\tminEntryProbability: bigint;\n\t/** `account::balance<USDC>`. Bounds a budget spend at `available − fee`. */\n\tavailableRaw?: bigint;\n\torderFeeRaw?: bigint;\n\t/** The deployment's `position_lot_size`. Defaults to `10_000n`. */\n\tlotSize?: bigint;\n\t/** Margin left below spare cash, in basis points. Default 100 (1%). */\n\theadroomBps?: bigint;\n\t/** When the reads were taken, echoed back as `asOfMs`. */\n\tasOfMs?: bigint;\n}\n\n/** The largest mint a market takes right now, and what binds it. A snapshot: see {@link maxMintNow}. */\nexport interface MaxMintNow {\n\t/**\n\t * The cash-limited maximum: a quantity for `'exact-quantity'`, a spend for `'budget'`. `null`\n\t * when cash doesn't bind (`p_min ≥ 1`).\n\t */\n\tcashLimitRaw: bigint | null;\n\t/** `available − fee` for `'budget'`, when a balance was given. `null` otherwise. */\n\tbalanceLimitRaw: bigint | null;\n\t/** The smaller of the two limits, or `null` when neither binds. */\n\tmaxRaw: bigint | null;\n\tlimitedBy: 'cash' | 'balance' | 'none';\n\tasOfMs: bigint | null;\n}\n\n/**\n * The largest queued mint a market's spare cash admits now (\"Max right now\"). Predict's admission\n * refuses a mint whose cash need is above spare cash (`EInsufficientMarketCash`). For exact quantity this\n * is the largest lot multiple `q` with `cashNeedExactQuantity(q) ≤ S`; for a budget it is the\n * largest `b` with `cashNeedBudget(b) ≤ S`, where `S` is spare cash less the headroom.\n *\n * It is a snapshot: fills lower spare cash, and the keeper's rebalance after each enqueue raises\n * it. Other waiting orders don't count against a mint. For exact quantity this caps only the\n * cash side: size the balance side with `cost.mintCostForBudget` at `available − fee`. A budget\n * mint with `p_min = 0` can't be placed at all (the cash need divides by `p_min`), so it reads 0.\n */\nexport function maxMintNow(inputs: MaxMintInputs): MaxMintNow {\n\tconst p = inputs.minEntryProbability;\n\tassertUint(p, 'minEntryProbability', FLOAT_SCALING);\n\tassertUint(inputs.spareCashRaw, 'spareCashRaw');\n\tconst headroom = inputs.headroomBps ?? 100n;\n\tif (headroom < 0n || headroom > 10_000n) {\n\t\tthrow new PredictInputError(`headroomBps must be in [0, 10000], got ${headroom}`);\n\t}\n\tconst spare = inputs.spareCashRaw - (inputs.spareCashRaw * headroom) / 10_000n;\n\tconst asOfMs = inputs.asOfMs ?? null;\n\n\tlet cashLimitRaw: bigint | null;\n\tlet balanceLimitRaw: bigint | null = null;\n\tif (inputs.shape === 'exact-quantity') {\n\t\tconst lot = inputs.lotSize ?? POSITION_LOT_SIZE;\n\t\tif (p >= FLOAT_SCALING) {\n\t\t\tcashLimitRaw = null;\n\t\t} else if (spare < 2n) {\n\t\t\tcashLimitRaw = 0n;\n\t\t} else {\n\t\t\tconst cap = MAX_QUANTITY_LOTS * lot;\n\t\t\tlet q = min(((spare - 1n) * FLOAT_SCALING) / (FLOAT_SCALING - p), cap);\n\t\t\tq -= q % lot;\n\t\t\twhile (q > 0n && cashNeedExactQuantity(q, p) > spare) q -= lot;\n\t\t\tcashLimitRaw = q;\n\t\t}\n\t} else {\n\t\tif (p === 0n) {\n\t\t\tcashLimitRaw = 0n;\n\t\t} else if (p >= FLOAT_SCALING) {\n\t\t\tcashLimitRaw = null;\n\t\t} else if (spare < 2n) {\n\t\t\tcashLimitRaw = 0n;\n\t\t} else {\n\t\t\tlet b = ((spare - 1n) * p) / (FLOAT_SCALING - p) - 1n;\n\t\t\twhile (b > 0n && cashNeedBudget(b, p) > spare) b -= 1n;\n\t\t\tcashLimitRaw = b > 0n ? b : 0n;\n\t\t}\n\t\tif (inputs.availableRaw != null) {\n\t\t\tconst fee = inputs.orderFeeRaw ?? 0n;\n\t\t\tbalanceLimitRaw = inputs.availableRaw > fee ? inputs.availableRaw - fee : 0n;\n\t\t}\n\t}\n\n\tif (cashLimitRaw == null && balanceLimitRaw == null) {\n\t\treturn { cashLimitRaw, balanceLimitRaw, maxRaw: null, limitedBy: 'none', asOfMs };\n\t}\n\tif (balanceLimitRaw == null || (cashLimitRaw != null && cashLimitRaw <= balanceLimitRaw)) {\n\t\treturn { cashLimitRaw, balanceLimitRaw, maxRaw: cashLimitRaw, limitedBy: 'cash', asOfMs };\n\t}\n\treturn { cashLimitRaw, balanceLimitRaw, maxRaw: balanceLimitRaw, limitedBy: 'balance', asOfMs };\n}\n\n// === Timing ===\n\n/** `(resolve_head, next_id, last_tau_ms, last_committed_tau_ms)` from `queue::queue_heads`. */\nexport interface QueueHeads {\n\tresolveHead: bigint;\n\tnextId: bigint;\n\tlastTauMs: bigint;\n\tlastCommittedTauMs: bigint;\n}\n\n/**\n * `expiry − max(no_trade_window_ms, stall_timeout_ms + 5_000)`, saturating at 0: enqueue requires\n * the order's τ below it.\n */\nexport function orderCutoffMs(\n\texpiryMs: bigint,\n\tpolicy: Pick<DelayedExecutionPolicy, 'stallTimeoutMs'>,\n\tnoTradeWindowMs: bigint,\n): bigint {\n\tconst margin = max(noTradeWindowMs, policy.stallTimeoutMs + DEADLINE_EXPIRY_MARGIN_MS);\n\treturn expiryMs > margin ? expiryMs - margin : 0n;\n}\n\n/** Inputs for {@link previewTiming}. */\nexport interface TimingPreviewInputs {\n\tnowMs: bigint;\n\tpolicy: Pick<DelayedExecutionPolicy, 'delayMs' | 'stallTimeoutMs' | 'pythChannel'>;\n\theads: QueueHeads;\n\texpiryMs: bigint;\n\tnoTradeWindowMs: bigint;\n\t/**\n\t * The newest order's channel, when known. A channel change pushes τ past the last τ, so one\n\t * cohort never mixes channels. The public reads don't expose it, so it is optional.\n\t */\n\tlastChannel?: number;\n}\n\n/** A display preview of the τ, deadline and cutoff an order placed now would get. */\nexport interface TimingPreview {\n\ttauMs: bigint;\n\t/** `min(τ + stall, expiry)`. The chain also keeps deadlines non-decreasing. */\n\tdeadlineMs: bigint;\n\tcutoffMs: bigint;\n\ttickMs: bigint;\n\t/** Whether τ is before the cutoff, so enqueue would accept the timing. */\n\tbeforeCutoff: boolean;\n}\n\n/**\n * Preview `order_queue::plan_timing`: τ is the policy channel's last tick at or before\n * `now + delay`, never below the last τ, and pushed past the last committed τ. Display only:\n * the contract uses the consensus timestamp, which can differ from the local clock.\n */\nexport function previewTiming(inputs: TimingPreviewInputs): TimingPreview {\n\tconst { policy, heads } = inputs;\n\tconst tickMs = channelTickMs(policy.pythChannel);\n\tconst rounded = ((inputs.nowMs + policy.delayMs) / tickMs) * tickMs;\n\tlet tauMs = max(rounded, heads.lastTauMs);\n\tif (\n\t\tinputs.lastChannel != null &&\n\t\theads.nextId > 0n &&\n\t\tinputs.lastChannel !== policy.pythChannel\n\t) {\n\t\ttauMs = max(rounded, nextTickAfter(heads.lastTauMs, tickMs));\n\t}\n\tif (tauMs <= heads.lastCommittedTauMs) tauMs = nextTickAfter(heads.lastCommittedTauMs, tickMs);\n\tconst deadlineMs = min(tauMs + policy.stallTimeoutMs, inputs.expiryMs);\n\tconst cutoffMs = orderCutoffMs(inputs.expiryMs, policy, inputs.noTradeWindowMs);\n\treturn { tauMs, deadlineMs, cutoffMs, tickMs, beforeCutoff: tauMs < cutoffMs };\n}\n\nfunction nextTickAfter(timeMs: bigint, tickMs: bigint): bigint {\n\treturn (timeMs / tickMs + 1n) * tickMs;\n}\n\n// === Slippage ===\n\n/** Inputs for {@link slippageBand}. All times in ms. */\nexport interface SlippageBandInputs {\n\t/** The quoted probability, in (0, 1). */\n\tprobability: number;\n\ttimeToExpiryMs: number;\n\t/** The policy's delay. */\n\tdelayMs: number;\n\t/** The channel tick: 50 or 200. */\n\ttickMs: number;\n\t/** Time between the quote and the enqueue landing. Default 500. */\n\tsigningMs?: number;\n\t/** Time between τ and the fill. Default 500. */\n\tresolveMs?: number;\n\t/** Standard deviations of movement to allow. Default 2. */\n\tk?: number;\n}\n\n/**\n * A heuristic band for a queued order's price limits: `Δp ≈ k · φ(Φ⁻¹(p)) · √(h / T)`, the\n * probability move of a digital under Brownian motion over the horizon `h` (delay + tick +\n * resolve + signing), scaled by the time `T` left. Use `maxProbability = p + Δp` on exact-quantity\n * mints and `minProbability = p − Δp` on sells, and size cost caps at the shifted probability.\n * A sizing aid pending product sign-off, not a contract rule.\n */\nexport function slippageBand(inputs: SlippageBandInputs): {\n\thorizonMs: number;\n\tdeltaProbability: number;\n\tmaxProbability: number;\n\tminProbability: number;\n} {\n\tconst p = inputs.probability;\n\tif (!(p > 0 && p < 1)) {\n\t\tthrow new PredictInputError(`probability must be in (0, 1), got ${p}`);\n\t}\n\tconst horizonMs =\n\t\tinputs.delayMs + inputs.tickMs + (inputs.resolveMs ?? 500) + (inputs.signingMs ?? 500);\n\tconst k = inputs.k ?? 2;\n\tconst delta =\n\t\tinputs.timeToExpiryMs <= horizonMs\n\t\t\t? 1\n\t\t\t: Math.min(\n\t\t\t\t\t1,\n\t\t\t\t\tk * normalPdf(inverseNormalCdf(p)) * Math.sqrt(horizonMs / inputs.timeToExpiryMs),\n\t\t\t\t);\n\treturn {\n\t\thorizonMs,\n\t\tdeltaProbability: delta,\n\t\tmaxProbability: Math.min(1, p + delta),\n\t\tminProbability: Math.max(0, p - delta),\n\t};\n}\n\n// === Order limits from a quote ===\n//\n// A queued order prices at its τ, after the quote. Its limits bound how far the price may move\n// against it in the meantime. `slippageRaw` is that move in price per contract, an absolute amount\n// and never a percentage: a contract pays $1, so 10¢ is `100_000_000n` (1e9-scaled). Each helper\n// turns a quote at the current price into the limits the enqueue takes.\n\n/** The quote a set of mint limits is sized from: the chain quote at the current price. */\nexport interface MintLimitsInputs {\n\t/** The quote's all-in cost after its fee subsidy, order fee excluded. */\n\tquoteCostRaw: bigint;\n\t/** The quote's payout quantity. */\n\tquoteQuantityRaw: bigint;\n\t/** The quote's entry probability, 1e9-scaled. */\n\tentryProbabilityRaw: bigint;\n\t/** The price move to allow per contract, 1e9-scaled: 10¢ is `100_000_000n`. */\n\tslippageRaw: bigint;\n\t/**\n\t * The quote's fee subsidy (`fee_incentive_subsidy`). Defaults to `0n`. Enqueue admission checks\n\t * the order's limits without the subsidy, and the subsidy can run out before the fill, so the\n\t * limits add it back: they are sized from the unsubsidized cost.\n\t */\n\tfeeIncentiveSubsidyRaw?: bigint;\n\t/** The deployment's `position_lot_size`. Defaults to `10_000n`. */\n\tlotSize?: bigint;\n}\n\n// Raw USDC a budget floor leaves for the per-component rounding of the fill's cost: the premium,\n// the trading, builder and referral fees and the inventory impact each round on their own.\nconst COST_ROUNDING_SLACK = 10n;\n\n/** All-in price per $1 of payout, 1e9-scaled and rounded up. */\nexport interface PricePerContract {\n\t/** The quote's price, after its fee subsidy. */\n\tnowRaw: bigint;\n\t/** The worst price the limits admit: the price without the fee subsidy, plus the slippage. */\n\tworstRaw: bigint;\n}\n\nfunction pricePerContract(inputs: MintLimitsInputs): PricePerContract {\n\tconst subsidy = inputs.feeIncentiveSubsidyRaw ?? 0n;\n\tassertUint(inputs.quoteCostRaw, 'quoteCostRaw');\n\tassertUint(inputs.quoteQuantityRaw, 'quoteQuantityRaw');\n\tassertUint(inputs.slippageRaw, 'slippageRaw', FLOAT_SCALING);\n\tassertUint(subsidy, 'feeIncentiveSubsidyRaw');\n\tif (inputs.quoteQuantityRaw === 0n) {\n\t\tthrow new PredictInputError('the quote buys no payout, so it sizes no limits');\n\t}\n\tconst nowRaw = mulDivUp(inputs.quoteCostRaw, FLOAT_SCALING, inputs.quoteQuantityRaw);\n\tconst unsubsidizedRaw = mulDivUp(\n\t\tinputs.quoteCostRaw + subsidy,\n\t\tFLOAT_SCALING,\n\t\tinputs.quoteQuantityRaw,\n\t);\n\treturn { nowRaw, worstRaw: unsubsidizedRaw + inputs.slippageRaw };\n}\n\n/**\n * Limits for a queued all-in budget mint (`enqueueMintCost`): the payout floor at the worst price.\n * The fill buys what `budgetRaw` buys at τ and refunds the order when that is below\n * `minQuantityRaw`, so the order fills while the all-in price per $1 of payout stays within\n * `slippageRaw` of the quote.\n */\nexport function budgetMintLimits(inputs: MintLimitsInputs & { budgetRaw: bigint }): {\n\tminQuantityRaw: bigint;\n\tpricePerContract: PricePerContract;\n} {\n\tassertUint(inputs.budgetRaw, 'budgetRaw');\n\tconst price = pricePerContract(inputs);\n\tconst lot = inputs.lotSize ?? POSITION_LOT_SIZE;\n\t// The fill rounds the premium and each fee on its own, so a quantity's cost can sit above\n\t// `quantity × price`. The floor leaves a few raw units of the budget for that. Inventory impact\n\t// can round by more, so `read.planMint` also checks the floor with exact quotes.\n\tconst spendable =\n\t\tinputs.budgetRaw > COST_ROUNDING_SLACK ? inputs.budgetRaw - COST_ROUNDING_SLACK : 0n;\n\tconst quantity = (spendable * FLOAT_SCALING) / price.worstRaw;\n\treturn { minQuantityRaw: (quantity / lot) * lot, pricePerContract: price };\n}\n\n/**\n * Limits for a queued exact-quantity mint (`enqueueMint`): the entry-probability cap and the\n * all-in cost cap at the worst price. The cost cap never exceeds the quantity, since a contract\n * never costs more than it pays.\n */\nexport function exactMintLimits(inputs: MintLimitsInputs): {\n\tmaxCostRaw: bigint;\n\tmaxProbabilityRaw: bigint;\n\tpricePerContract: PricePerContract;\n} {\n\tassertUint(inputs.entryProbabilityRaw, 'entryProbabilityRaw', FLOAT_SCALING);\n\tconst price = pricePerContract(inputs);\n\tconst maxCostRaw = mulDivUp(inputs.quoteQuantityRaw, price.worstRaw, FLOAT_SCALING);\n\tconst maxProbabilityRaw = inputs.entryProbabilityRaw + inputs.slippageRaw;\n\treturn {\n\t\tmaxCostRaw: min(maxCostRaw, inputs.quoteQuantityRaw),\n\t\tmaxProbabilityRaw: min(maxProbabilityRaw, FLOAT_SCALING),\n\t\tpricePerContract: price,\n\t};\n}\n\n/**\n * Limits for a queued early sell (`enqueueSell`): the close-probability floor and the proceeds\n * floor at the worst price. `proceedsRaw` is the quote's proceeds before the order fee, as\n * `minProceeds` is.\n */\nexport function sellLimits(inputs: {\n\tproceedsRaw: bigint;\n\tcloseQuantityRaw: bigint;\n\tprobabilityRaw: bigint;\n\tslippageRaw: bigint;\n}): { minProceedsRaw: bigint; minProbabilityRaw: bigint } {\n\tassertUint(inputs.proceedsRaw, 'proceedsRaw');\n\tassertUint(inputs.closeQuantityRaw, 'closeQuantityRaw');\n\tassertUint(inputs.probabilityRaw, 'probabilityRaw', FLOAT_SCALING);\n\tassertUint(inputs.slippageRaw, 'slippageRaw', FLOAT_SCALING);\n\tconst give = mulDivUp(inputs.closeQuantityRaw, inputs.slippageRaw, FLOAT_SCALING);\n\treturn {\n\t\tminProceedsRaw: inputs.proceedsRaw > give ? inputs.proceedsRaw - give : 0n,\n\t\tminProbabilityRaw:\n\t\t\tinputs.probabilityRaw > inputs.slippageRaw ? inputs.probabilityRaw - inputs.slippageRaw : 0n,\n\t};\n}\n\nfunction normalPdf(x: number): number {\n\treturn Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI);\n}\n\n// Acklam's rational approximation of Φ⁻¹, relative error below 1.15e-9.\nfunction inverseNormalCdf(p: number): number {\n\tconst a = [\n\t\t-3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 1.38357751867269e2,\n\t\t-3.066479806614716e1, 2.506628277459239,\n\t];\n\tconst b = [\n\t\t-5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1,\n\t\t-1.328068155288572e1,\n\t];\n\tconst c = [\n\t\t-7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, -2.549732539343734,\n\t\t4.374664141464968, 2.938163982698783,\n\t];\n\tconst d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996, 3.754408661907416];\n\tconst low = 0.02425;\n\tif (p < low) {\n\t\tconst q = Math.sqrt(-2 * Math.log(p));\n\t\treturn (\n\t\t\t(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /\n\t\t\t((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)\n\t\t);\n\t}\n\tif (p > 1 - low) {\n\t\tconst q = Math.sqrt(-2 * Math.log(1 - p));\n\t\treturn -(\n\t\t\t(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /\n\t\t\t((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)\n\t\t);\n\t}\n\tconst q = p - 0.5;\n\tconst r = q * q;\n\treturn (\n\t\t((((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q) /\n\t\t(((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)\n\t);\n}\n\n// === Order state ===\n\n/**\n * A queue record as `queue::order` returns it: the generated `order_queue::OrderView` layout, a\n * copy of the record without Predict's receipt and the escrow balance (`funds` is its value).\n */\nexport type QueuedOrder = (typeof OrderViewBcs)['$inferType'];\n\n/** The position a record holds: a filled mint's, a sell's, or a partial sell's remainder. */\nexport interface HeldPosition {\n\torderId: bigint;\n\trootId: bigint;\n\topenedAtMs: bigint;\n\t/**\n\t * The position's payout quantity, decoded from `orderId` at the Move lot size: a filled\n\t * mint's quantity, or what a partial sell left Open.\n\t */\n\tquantityRaw: bigint;\n}\n\ninterface OrderViewBase {\n\tstatus: number;\n\tkind: number;\n\tkindName: OrderKindName;\n\tside: 'mint' | 'sell' | 'unknown';\n}\n\n/**\n * What the app shows for one queued order. `placed` → `priced` → one of `filled` / `refunded`.\n * Report `filled` only from the record or the fill event, never from a resolve simulation.\n */\nexport type OrderView = OrderViewBase &\n\t(\n\t\t| {\n\t\t\t\tstate: 'placed';\n\t\t\t\ttauMs: bigint;\n\t\t\t\tdeadlineMs: bigint;\n\t\t\t\t/** τ has passed and the price hasn't been committed yet. */\n\t\t\t\tawaitingPrice: boolean;\n\t\t\t\t/** Keepers refund an unfinished order at its deadline. */\n\t\t\t\tautoRefundByMs: bigint;\n\t\t\t\t/** Offer \"Refund my order\": unfinished and {@link REFUND_REQUEST_GRACE_MS} past the deadline. */\n\t\t\t\tcanRequestRefund: boolean;\n\t\t }\n\t\t| {\n\t\t\t\tstate: 'priced';\n\t\t\t\ttauMs: bigint;\n\t\t\t\t/** The committed update's tick: τ, or a backup tick. */\n\t\t\t\ttickMs: bigint;\n\t\t\t\t/** The committed Pyth price, 1e9-scaled. */\n\t\t\t\tpriceRaw: bigint;\n\t\t\t\tdeadlineMs: bigint;\n\t\t\t\tmsToDeadline: bigint;\n\t\t\t\tautoRefundByMs: bigint;\n\t\t\t\tcanRequestRefund: boolean;\n\t\t }\n\t\t| {\n\t\t\t\tstate: 'refunding';\n\t\t\t\treason: RefundReasonInfo;\n\t\t\t\tdeadlineMs: bigint;\n\t\t\t\tcanRequestRefund: boolean;\n\t\t }\n\t\t| {\n\t\t\t\tstate: 'filled';\n\t\t\t\t/**\n\t\t\t\t * Filled quantity (mint) or closed quantity (sell). A partial sell's remainder is\n\t\t\t\t * `position.quantityRaw`.\n\t\t\t\t */\n\t\t\t\tquantityRaw: bigint;\n\t\t\t\t/** Cost paid (mint) or proceeds before the order fee (sell). */\n\t\t\t\tamountRaw: bigint;\n\t\t\t\tfinishedAtMs: bigint;\n\t\t\t\t/** The Open record's position: a filled mint, or a partial sell's remainder. */\n\t\t\t\tposition: HeldPosition | null;\n\t\t\t\t/** Whether `enqueue_redeem_open` can sell this record now. */\n\t\t\t\tsellable: boolean;\n\t\t\t\t/** See {@link ParkedFunds}. */\n\t\t\t\tparkedRaw: bigint;\n\t\t }\n\t\t| {\n\t\t\t\tstate: 'refunded';\n\t\t\t\treason: RefundReasonInfo;\n\t\t\t\tfinishedAtMs: bigint;\n\t\t\t\t/** A refunded sell keeps its position as an Open record, sellable again. */\n\t\t\t\tpositionBackAsOpenRecord: boolean;\n\t\t\t\tposition: HeldPosition | null;\n\t\t\t\tsellable: boolean;\n\t\t\t\t/** See {@link ParkedFunds}. */\n\t\t\t\tparkedRaw: bigint;\n\t\t }\n\t\t| {\n\t\t\t\t/** A filled mint's record whose position was later sold or settled. */\n\t\t\t\tstate: 'closed';\n\t\t\t\tquantityRaw: bigint;\n\t\t\t\tamountRaw: bigint;\n\t\t\t\tfinishedAtMs: bigint;\n\t\t\t\t/** See {@link ParkedFunds}. */\n\t\t\t\tparkedRaw: bigint;\n\t\t }\n\t\t| { state: 'unknown' }\n\t);\n\n/**\n * `parkedRaw` on a finished record: USDC the record kept because its receive address couldn't take\n * it (on USDC's deny list, or USDC paused) when its change or refund was sent. It is the\n * record's `funds`, which holds only parked USDC once the order finishes. Anyone can send it with\n * `claim_parked` once the address is clear. `0n` when nothing is parked.\n */\nexport type ParkedFunds = bigint;\n\nfunction heldPosition(p: QueuedOrder['position'], lotSize?: bigint): HeldPosition | null {\n\treturn p.order_id === 0n\n\t\t? null\n\t\t: {\n\t\t\t\torderId: p.order_id,\n\t\t\t\trootId: p.root_id,\n\t\t\t\topenedAtMs: p.opened_at_ms,\n\t\t\t\tquantityRaw: decodeOrderRange(p.order_id, lotSize).quantity,\n\t\t\t};\n}\n\n/**\n * Map a queue record to its display state. `nowMs` drives the refund flags. A record is sellable\n * while it is Open, holds a position, and `nowMs` is before the cutoff (`opts.cutoffMs`, or the\n * record's own placement cutoff when omitted). Unknown status or kind codes map to `unknown`.\n * `opts.lotSize` is the config's position lot (default 10,000, Predict's), which decodes a held\n * position's quantity.\n */\nexport function orderView(\n\trecord: QueuedOrder,\n\tnowMs: bigint,\n\topts: { cutoffMs?: bigint; lotSize?: bigint } = {},\n): OrderView {\n\tconst kind = record.kind;\n\tconst base: OrderViewBase = {\n\t\tstatus: record.status,\n\t\tkind,\n\t\tkindName: orderKindName(kind),\n\t\tside: isMintKind(kind) ? 'mint' : isSellKind(kind) ? 'sell' : 'unknown',\n\t};\n\tif (base.side === 'unknown') return { ...base, state: 'unknown' };\n\tconst { tau_ms: tauMs, deadline_ms: deadlineMs } = record.timing;\n\tconst canRequestRefund = nowMs >= deadlineMs + REFUND_REQUEST_GRACE_MS;\n\tconst position = heldPosition(record.position, opts.lotSize);\n\tconst cutoffMs = opts.cutoffMs ?? record.timing.cutoff_ms;\n\tconst sellable = position != null && nowMs < cutoffMs;\n\tconst result = record.result;\n\t// Only read on the finished statuses below, where `funds` holds parked USDC, not escrow.\n\tconst parkedRaw = record.funds;\n\tswitch (record.status) {\n\t\tcase ORDER_STATUS.PENDING:\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'placed',\n\t\t\t\ttauMs,\n\t\t\t\tdeadlineMs,\n\t\t\t\tawaitingPrice: nowMs >= tauMs,\n\t\t\t\tautoRefundByMs: deadlineMs,\n\t\t\t\tcanRequestRefund,\n\t\t\t};\n\t\tcase ORDER_STATUS.COMMITTED:\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'priced',\n\t\t\t\ttauMs,\n\t\t\t\ttickMs: record.price.tick_ms,\n\t\t\t\tpriceRaw: record.price.spot,\n\t\t\t\tdeadlineMs,\n\t\t\t\tmsToDeadline: deadlineMs > nowMs ? deadlineMs - nowMs : 0n,\n\t\t\t\tautoRefundByMs: deadlineMs,\n\t\t\t\tcanRequestRefund,\n\t\t\t};\n\t\tcase ORDER_STATUS.REFUND_DUE:\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'refunding',\n\t\t\t\treason: refundReason(result.reason),\n\t\t\t\tdeadlineMs,\n\t\t\t\tcanRequestRefund,\n\t\t\t};\n\t\tcase ORDER_STATUS.OPEN:\n\t\t\tif (base.side === 'sell' && result.reason > 0) {\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tstate: 'refunded',\n\t\t\t\t\treason: refundReason(result.reason),\n\t\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\t\tpositionBackAsOpenRecord: true,\n\t\t\t\t\tposition,\n\t\t\t\t\tsellable,\n\t\t\t\t\tparkedRaw,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'filled',\n\t\t\t\tquantityRaw: result.quantity,\n\t\t\t\tamountRaw: result.amount,\n\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\tposition,\n\t\t\t\tsellable,\n\t\t\t\tparkedRaw,\n\t\t\t};\n\t\tcase ORDER_STATUS.REFUNDED:\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'refunded',\n\t\t\t\treason: refundReason(result.reason),\n\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\tpositionBackAsOpenRecord: false,\n\t\t\t\tposition: null,\n\t\t\t\tsellable: false,\n\t\t\t\tparkedRaw,\n\t\t\t};\n\t\tcase ORDER_STATUS.CLOSED:\n\t\t\t// A sell record that filled stays `filled` after its remainder moves on; a mint record\n\t\t\t// (or a refunded sell sold again) is `closed` once its position left.\n\t\t\tif (base.side === 'sell' && result.reason === 0 && result.quantity > 0n) {\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tstate: 'filled',\n\t\t\t\t\tquantityRaw: result.quantity,\n\t\t\t\t\tamountRaw: result.amount,\n\t\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\t\tposition: null,\n\t\t\t\t\tsellable: false,\n\t\t\t\t\tparkedRaw,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstate: 'closed',\n\t\t\t\tquantityRaw: result.quantity,\n\t\t\t\tamountRaw: result.amount,\n\t\t\t\tfinishedAtMs: result.finished_at_ms,\n\t\t\t\tparkedRaw,\n\t\t\t};\n\t\tdefault:\n\t\t\treturn { ...base, state: 'unknown' };\n\t}\n}\n\n/** One record's state rebuilt from events, for the app's event path (indexer or own effects). */\nexport interface OrderEventState {\n\tmarketId: string;\n\trecordId: bigint;\n\t/**\n\t * `closed`: the record's position moved into a later sell's record (`enqueue_redeem_open` closes\n\t * the source record), so this record holds nothing any more.\n\t */\n\tstate: 'placed' | 'priced' | 'filled' | 'refunded' | 'settled' | 'closed';\n\tkind: number | null;\n\ttauMs: bigint | null;\n\tdeadlineMs: bigint | null;\n\t/** Set once priced: the committed Pyth price as a float (`spot / 1e9`) and its tick. */\n\tprice: number | null;\n\ttickMs: bigint | null;\n\t/**\n\t * Set on a refund. The settlement drain (`settle_step`) refunds the orders still waiting at\n\t * expiry with reason 5 (deadline), like a keeper's deadline refund.\n\t */\n\treason: RefundReasonInfo | null;\n\t/**\n\t * The position the record holds now, or null. A sell's record takes its source's position at\n\t * enqueue and keeps it through a refund, a fill leaves a mint's new position or a partial\n\t * sell's remainder, and a later sell, a full close or settlement clears it.\n\t */\n\tposition: HeldPosition | null;\n\t/** For a sell: the record its position came from. */\n\tsourceRecordId: bigint | null;\n\t/** Set when `settle_step` or `pay_open` paid the record (0 for a loser). */\n\tpayoutRaw: bigint | null;\n\t/** True after `OpenRecordPayoutSkipped`: the record stays Open, unpaid for now. */\n\tpayoutSkipped: boolean;\n\t/**\n\t * USDC the record holds parked (`RecordFundsParked`, summed) until `RecordFundsClaimed`. See\n\t * {@link ParkedFunds}.\n\t */\n\tparkedRaw: bigint;\n}\n\n/**\n * Fold decoded queue events (in chain order) into per-record states, keyed `marketId:recordId`.\n * The app shows Placed from the enqueue's own effects, Priced at the cohort commit, and switches to\n * Filled or Refunded on `QueuedOrderFilled` / `QueuedOrderRefunded`. Events for records that never\n * appeared enqueued still create an entry, so a partial event window works.\n */\nexport function reduceOrderEvents(\n\tevents: readonly QueueEvent[],\n\tinto: Map<string, OrderEventState> = new Map(),\n): Map<string, OrderEventState> {\n\tconst entry = (marketId: string, recordId: bigint): OrderEventState => {\n\t\tconst key = `${marketId}:${recordId}`;\n\t\tlet s = into.get(key);\n\t\tif (!s) {\n\t\t\ts = {\n\t\t\t\tmarketId,\n\t\t\t\trecordId,\n\t\t\t\tstate: 'placed',\n\t\t\t\tkind: null,\n\t\t\t\ttauMs: null,\n\t\t\t\tdeadlineMs: null,\n\t\t\t\tprice: null,\n\t\t\t\ttickMs: null,\n\t\t\t\treason: null,\n\t\t\t\tposition: null,\n\t\t\t\tsourceRecordId: null,\n\t\t\t\tpayoutRaw: null,\n\t\t\t\tpayoutSkipped: false,\n\t\t\t\tparkedRaw: 0n,\n\t\t\t};\n\t\t\tinto.set(key, s);\n\t\t}\n\t\treturn s;\n\t};\n\tfor (const e of events) {\n\t\tswitch (e.type) {\n\t\t\tcase 'enqueued': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.kind = e.kind;\n\t\t\t\ts.tauMs = e.timing.tauMs;\n\t\t\t\ts.deadlineMs = e.timing.deadlineMs;\n\t\t\t\t// A sell moves the whole position out of its source record, which the chain marks\n\t\t\t\t// Closed, and into the new record, which holds it until the sell fills or refunds.\n\t\t\t\ts.position = e.position;\n\t\t\t\ts.sourceRecordId = e.sourceRecordId;\n\t\t\t\tif (e.sourceRecordId != null) {\n\t\t\t\t\tconst source = entry(e.marketId, e.sourceRecordId);\n\t\t\t\t\tsource.state = 'closed';\n\t\t\t\t\tsource.position = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'cohort-committed':\n\t\t\t\tfor (const s of into.values()) {\n\t\t\t\t\tif (\n\t\t\t\t\t\ts.marketId === e.marketId &&\n\t\t\t\t\t\ts.state === 'placed' &&\n\t\t\t\t\t\ts.recordId >= e.firstRecordId &&\n\t\t\t\t\t\ts.recordId <= e.lastRecordId\n\t\t\t\t\t) {\n\t\t\t\t\t\ts.state = 'priced';\n\t\t\t\t\t\ts.price = e.price;\n\t\t\t\t\t\ts.tickMs = e.tickMs;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'filled': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.state = 'filled';\n\t\t\t\ts.kind = e.kind;\n\t\t\t\ts.tickMs = e.tickMs;\n\t\t\t\ts.position = e.position;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'refunded': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.state = 'refunded';\n\t\t\t\ts.kind = e.kind;\n\t\t\t\ts.reason = e.reason;\n\t\t\t\t// A refunded sell keeps its position, Open and sellable again from this record.\n\t\t\t\tif (!e.positionReturned) s.position = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'open-record-settled': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.state = 'settled';\n\t\t\t\ts.payoutRaw = e.raw.payout;\n\t\t\t\ts.payoutSkipped = false;\n\t\t\t\ts.position = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'open-record-payout-skipped': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.payoutSkipped = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'record-funds-parked': {\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.parkedRaw += e.raw.amount;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'record-funds-claimed': {\n\t\t\t\t// `claim_parked` sends everything the record had parked.\n\t\t\t\tconst s = entry(e.marketId, e.recordId);\n\t\t\t\ts.parkedRaw = 0n;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn into;\n}\n\nfunction min(a: bigint, b: bigint): bigint {\n\treturn a < b ? a : b;\n}\n\nfunction max(a: bigint, b: bigint): bigint {\n\treturn a > b ? a : b;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,4BAA4B;;;;;;;;;AAUzC,MAAa,0BAA0B;;;;;;;;AASvC,MAAa,6BAA6B;;AAG1C,MAAa,eAAe,OAAO,OAAO;CAEzC,OAAO;CAEP,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AAO,EAAE;AACX,KAAE,SAAS,EAAE;AAEb,OAAI,CAAC,EAAE,iBAAkB,GAAE,WAAW;AACtC;;EAED,KAAK,uBAAuB;GAC3B,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,QAAQ;AACV,KAAE,YAAY,EAAE,IAAI;AACpB,KAAE,gBAAgB;AAClB,KAAE,WAAW;AACb;;EAED,KAAK,8BAA8B;GAClC,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,gBAAgB;AAClB;;EAED,KAAK,uBAAuB;GAC3B,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,aAAa,EAAE,IAAI;AACrB;;EAED,KAAK,wBAAwB;GAE5B,MAAM,IAAI,MAAM,EAAE,UAAU,EAAE,SAAS;AACvC,KAAE,YAAY;AACd;;EAED,QACC;;AAGH,QAAO;;AAGR,SAAS,IAAI,GAAW,GAAmB;AAC1C,QAAO,IAAI,IAAI,IAAI;;AAGpB,SAAS,IAAI,GAAW,GAAmB;AAC1C,QAAO,IAAI,IAAI,IAAI"}
@@ -1,4 +1,4 @@
1
- import { balance, loadAccount } from "../../contracts/account/account.mjs";
1
+ import { balance, loadAccount } from "../../account-bindings/account.mjs";
2
2
  import { inspectReturns } from "./inspect.mjs";
3
3
  import { deriveAccountWrapperIdFrom } from "../tx/common.mjs";
4
4
  import { parseU64LE } from "./parse.mjs";
@@ -96,8 +96,9 @@ interface MarketQueueState {
96
96
  * `EDelayedExecutionRequired`.
97
97
  * - `'unsupported'`: the watermark is raised but this SDK's config has no delayed-execution
98
98
  * record for the network. Upgrade the SDK, or pass a config that records it.
99
- * - `'retired'`: the watermark is above the Predict code version this SDK calls
100
- * (`PREDICT_PACKAGE_VERSION`), so every version-gated call aborts `EPackageVersionDisabled`.
99
+ * - `'retired'`: the watermark is above the Predict code version the config calls
100
+ * (`packages.predictCurrentVersion`, else `PREDICT_PACKAGE_VERSION`), so every version-gated
101
+ * call aborts `EPackageVersionDisabled`.
101
102
  * Upgrade the SDK.
102
103
  */
103
104
  type ExecutionMode = 'immediate' | 'awaiting-cutover' | 'delayed' | 'unsupported' | 'retired';
@@ -1 +1 @@
1
- {"version":3,"file":"queue.d.mts","names":[],"sources":["../../../src/predict/reads/queue.ts"],"mappings":";;;;;;;;;iBAsCgB,oBAAA,CACf,MAAA,EAAQ,IAAA,CAAK,qBAAA;AADd;AAAA,UAOiB,gBAAA;EAChB,QAAA;EAPY;EASZ,OAAA;EACA,QAAA;EACA,UAAA;EACA,WAAA;EACA,YAAA;EAPgB;;;;EAYhB,SAAA;EA0DU;EAxDV,eAAA;EAwDqB;EAtDrB,mBAAA;EAbA;EAeA,mBAAA;EAbA;EAeA,mBAAA;EAbA;EAeA,KAAA;EACA,OAAA;IACC,KAAA;IACA,sBAAA,iBALD;IAOC,oCAAA;EAAA;EAED,KAAA,EAAO,UAAA;EAJN;EAMD,OAAA;IAAW,KAAA;IAAe,KAAA;EAAA;EAAf;;;;EAKX,MAAA;IAAU,MAAA;IAAgB,MAAA;IAAgB,SAAA;EAAA;EAIjC;EAFT,IAAA;IACC,EAAA;IACA,MAAA,EAAQ,sBAAA;IACR,gBAAA;EAAA;EAED,QAAA;IACC,eAAA,UAYA;IAVA,uBAAA;IACA,aAAA;IACA,MAAA,WAmBA;IAjBA,gBAAA;IAoBS;;;AAyLX;;IAvME,gBAAA;EAAA;EAuMuB;EApMxB,OAAA;IACC,SAAA;;;;;IAKA,aAAA;IAEA,YAAA;EAAA;;EAGD,OAAA,GAAU,WAAA;AAAA;;;;;;;;;;;;;;;;;KAyLC,aAAA"}
1
+ {"version":3,"file":"queue.d.mts","names":[],"sources":["../../../src/predict/reads/queue.ts"],"mappings":";;;;;;;;;iBAuCgB,oBAAA,CACf,MAAA,EAAQ,IAAA,CAAK,qBAAA;AADd;AAAA,UAOiB,gBAAA;EAChB,QAAA;EAPY;EASZ,OAAA;EACA,QAAA;EACA,UAAA;EACA,WAAA;EACA,YAAA;EAPgB;;;;EAYhB,SAAA;EA0DU;EAxDV,eAAA;EAwDqB;EAtDrB,mBAAA;EAbA;EAeA,mBAAA;EAbA;EAeA,mBAAA;EAbA;EAeA,KAAA;EACA,OAAA;IACC,KAAA;IACA,sBAAA,iBALD;IAOC,oCAAA;EAAA;EAED,KAAA,EAAO,UAAA;EAJN;EAMD,OAAA;IAAW,KAAA;IAAe,KAAA;EAAA;EAAf;;;;EAKX,MAAA;IAAU,MAAA;IAAgB,MAAA;IAAgB,SAAA;EAAA;EAIjC;EAFT,IAAA;IACC,EAAA;IACA,MAAA,EAAQ,sBAAA;IACR,gBAAA;EAAA;EAED,QAAA;IACC,eAAA,UAYA;IAVA,uBAAA;IACA,aAAA;IACA,MAAA,WAmBA;IAjBA,gBAAA;IAoBS;;;AA0LX;;IAxME,gBAAA;EAAA;EAwMuB;EArMxB,OAAA;IACC,SAAA;;;;;IAKA,aAAA;IAEA,YAAA;EAAA;;EAGD,OAAA,GAAU,WAAA;AAAA;;;;;;;;;;;;;;;;;;KA0LC,aAAA"}
@@ -1,15 +1,16 @@
1
- import { balance, loadAccount } from "../../contracts/account/account.mjs";
1
+ import { balance, loadAccount } from "../../account-bindings/account.mjs";
2
2
  import { OrderView } from "../../contracts/deepbook_predict_orders/order_queue.mjs";
3
3
  import { DelayedExecutionPolicy } from "../../contracts/deepbook_predict_orders/delayed_execution_config.mjs";
4
4
  import { DELAYED_EXECUTION_VERSION, PREDICT_PACKAGE_VERSION, policyFromBcs } from "../queue.mjs";
5
5
  import { inspectReturns } from "./inspect.mjs";
6
6
  import { deriveAccountIdFrom, deriveAccountWrapperIdFrom } from "../tx/common.mjs";
7
7
  import { policy, versionWatermark as versionWatermark$1 } from "../../contracts/deepbook_predict_orders/desk.mjs";
8
- import { order, payoutProgress, pendingCounts, queueHeads, queueStuck, quoteRedeemOpen as quoteRedeemOpen$1, waitingCohorts, waitingOrders } from "../../contracts/deepbook_predict_orders/queue.mjs";
8
+ import { order, payoutProgress, pendingCounts, queueHeads, queueStuck, waitingCohorts, waitingOrders } from "../../contracts/deepbook_predict_orders/queue.mjs";
9
9
  import { queueIdOf } from "../tx/queue.mjs";
10
10
  import { MintQuote, RedeemQuote, backingBufferLambda, cashBalance, expiry, mintPaused, orderFlowState, quoteMint, quoteMintExactCostForAccount, quoteMintForAccount as quoteMintForAccount$1, requiredCash } from "../../contracts/deepbook_predict/expiry_market.mjs";
11
11
  import { loadLivePricer } from "../tx/trade.mjs";
12
12
  import { ProtocolConfig, feeIncentiveSubsidyRate, frozen, isOrderFlow, noTradeWindowMs, tradingPaused, versionWatermark as versionWatermark$2 } from "../../contracts/deepbook_predict/protocol_config.mjs";
13
+ import { quoteRedeemOpen as quoteRedeemOpen$1 } from "../bindings/queue.mjs";
13
14
  import { parseOptionalU64, parseU64LE } from "./parse.mjs";
14
15
  import { bcs } from "@mysten/sui/bcs";
15
16
  import { Transaction } from "@mysten/sui/transactions";
@@ -223,10 +224,10 @@ async function versionWatermark(client, protocolConfigId) {
223
224
  * (`packages.predictDelayedExecution`), which makes the config's Predict call target the package
224
225
  * that retired the immediate trades. It defaults to `recordsDelayedExecution`.
225
226
  */
226
- function executionModeFor(watermark, recordsDelayedExecution, recordsPredictUpgrade = recordsDelayedExecution) {
227
+ function executionModeFor(watermark, recordsDelayedExecution, recordsPredictUpgrade = recordsDelayedExecution, predictCurrentVersion = PREDICT_PACKAGE_VERSION) {
227
228
  if (watermark >= DELAYED_EXECUTION_VERSION) {
228
229
  if (!recordsDelayedExecution) return "unsupported";
229
- return watermark > PREDICT_PACKAGE_VERSION ? "retired" : "delayed";
230
+ return watermark > predictCurrentVersion ? "retired" : "delayed";
230
231
  }
231
232
  return recordsDelayedExecution || recordsPredictUpgrade ? "awaiting-cutover" : "immediate";
232
233
  }