@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
@@ -22,7 +22,7 @@ import { DeepbookPredictOrdersConfig } from "../../contracts/deepbook_predict_or
22
22
  */
23
23
  type GeneratedConfig = DeepbookPredictConfig & AccountConfig & {
24
24
  predictPackageId: string;
25
- predictPackageIdV1: string;
25
+ predictPackageIdV1: string; /** The ORIGINAL account ID: type tags and derived addresses are built from it. */
26
26
  accountPackageId: string;
27
27
  accountRegistry: string;
28
28
  };
@@ -1 +1 @@
1
- {"version":3,"file":"generated.d.mts","names":[],"sources":["../../../src/predict/config/generated.ts"],"mappings":";;;;;;;;;AAwBA;;;;;;;;;;;;AAQA;KARY,eAAA,GAAkB,qBAAA,GAC7B,aAAA;EACC,gBAAA;EACA,kBAAA;EACA,gBAAA;EACA,eAAA;AAAA;AAAA,iBAGc,iBAAA,CAAkB,GAAA,EAAK,aAAA,GAAgB,eAAA;;AAmBvD;;;;;KAAY,qBAAA,GAAwB,eAAA,GACnC,2BAAA,GACA,yBAAA;EACC,sBAAA;EACA,wBAAA;EACA,SAAA;EACA,aAAA;AAAA;;;;;;;iBASc,cAAA,CAAe,GAAA,EAAK,aAAA,GAAgB,qBAAA"}
1
+ {"version":3,"file":"generated.d.mts","names":[],"sources":["../../../src/predict/config/generated.ts"],"mappings":";;;;;;;;;AAwBA;;;;;;;;;;;;AASA;KATY,eAAA,GAAkB,qBAAA,GAC7B,aAAA;EACC,gBAAA;EACA,kBAAA,UAMqC;EAJrC,gBAAA;EACA,eAAA;AAAA;AAAA,iBAGc,iBAAA,CAAkB,GAAA,EAAK,aAAA,GAAgB,eAAA;AAqBvD;;;;;;AAAA,KAAY,qBAAA,GAAwB,eAAA,GACnC,2BAAA,GACA,yBAAA;EACC,sBAAA;EACA,wBAAA;EACA,SAAA;EACA,aAAA;AAAA;;;;;;AASF;iBAAgB,cAAA,CAAe,GAAA,EAAK,aAAA,GAAgB,qBAAA"}
@@ -6,6 +6,7 @@ function toGeneratedConfig(cfg) {
6
6
  predictPackageId: cfg.packages.predict,
7
7
  predictPackageIdV1: cfg.packages.predictV1 ?? cfg.packages.predict,
8
8
  accountPackageId: cfg.packages.account,
9
+ accountPackageIdLatest: cfg.packages.accountLatest,
9
10
  protocolConfig: cfg.objects.protocolConfig,
10
11
  poolVault: cfg.objects.poolVault,
11
12
  registry: cfg.objects.registry,
@@ -1 +1 @@
1
- {"version":3,"file":"generated.mjs","names":[],"sources":["../../../src/predict/config/generated.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport type { AccountConfig } from '../../account.js';\nimport type { DeepbookPredictConfig } from '../../contracts/deepbook_predict/config-arguments.js';\nimport type { DeepbookPredictMathConfig } from '../../contracts/deepbook_predict_math/config-arguments.js';\nimport type { DeepbookPredictOrdersConfig } from '../../contracts/deepbook_predict_orders/config-arguments.js';\nimport { PredictInputError } from '../errors.js';\nimport type { PredictConfig } from './types.js';\n\n/**\n * The flat config slice the generated bindings resolve `options.config` against, projected from\n * the nested public `PredictConfig`. Each generated call declares only the keys it consumes, so a\n * single object carrying all of them satisfies every call site.\n *\n * Typed as the intersection of the two generated interfaces on purpose: if codegen adds, drops, or\n * renames a config key, this file stops compiling instead of silently building a PTB against the\n * wrong object.\n *\n * `predictPackageId` is narrowed to `string` because codegen types package ids as optional, while\n * this projection always supplies one. `predictPackageIdV1` separately supplies the original\n * identity for existing struct tags and dynamic-field keys. The two account ids restate a narrowing\n * `AccountConfig` already applies, so they are redundant today; they are kept so this projection\n * still compiles to plain ids if that package ever widens them back.\n */\nexport type GeneratedConfig = DeepbookPredictConfig &\n\tAccountConfig & {\n\t\tpredictPackageId: string;\n\t\tpredictPackageIdV1: string;\n\t\taccountPackageId: string;\n\t\taccountRegistry: string;\n\t};\n\nexport function toGeneratedConfig(cfg: PredictConfig): GeneratedConfig {\n\treturn {\n\t\tpredictPackageId: cfg.packages.predict,\n\t\tpredictPackageIdV1: cfg.packages.predictV1 ?? cfg.packages.predict,\n\t\taccountPackageId: cfg.packages.account,\n\t\tprotocolConfig: cfg.objects.protocolConfig,\n\t\tpoolVault: cfg.objects.poolVault,\n\t\tregistry: cfg.objects.registry,\n\t\toracleRegistry: cfg.objects.oracleRegistry,\n\t\taccountRegistry: cfg.objects.accountRegistry,\n\t};\n}\n\n/**\n * {@link GeneratedConfig} plus the order-flow companion (`deepbook_predict_orders`) and the math\n * library: the slice the queued-order thunks and reads take. A queued order calls the companion,\n * which calls into Predict, so one object carries both packages' keys. `predictOrdersPackageIdV1`\n * is the companion's original ID, which types `OrderFlow` and the queue events.\n */\nexport type OrdersGeneratedConfig = GeneratedConfig &\n\tDeepbookPredictOrdersConfig &\n\tDeepbookPredictMathConfig & {\n\t\tpredictOrdersPackageId: string;\n\t\tpredictOrdersPackageIdV1: string;\n\t\torderDesk: string;\n\t\tqueueRegistry: string;\n\t};\n\n/**\n * Project a config that records delayed execution onto {@link OrdersGeneratedConfig}. Throws\n * `PredictInputError` while the config lacks the Predict upgrade, the companion package, its desk\n * or its queue registry: building a queued order against a guessed package would abort on chain\n * or, worse, address the wrong one.\n */\nexport function toOrdersConfig(cfg: PredictConfig): OrdersGeneratedConfig {\n\tconst { predictDelayedExecution, predictOrders, predictOrdersV1, predictMath } = cfg.packages;\n\tconst { orderDesk, queueRegistry } = cfg.objects;\n\tif (!predictDelayedExecution || !predictOrders || !orderDesk || !queueRegistry) {\n\t\tconst missing = [\n\t\t\t!predictDelayedExecution && '`packages.predictDelayedExecution`',\n\t\t\t!predictOrders && '`packages.predictOrders`',\n\t\t\t!orderDesk && '`objects.orderDesk`',\n\t\t\t!queueRegistry && '`objects.queueRegistry`',\n\t\t].filter(Boolean);\n\t\tthrow new PredictInputError(\n\t\t\t`delayed execution isn't recorded for ${cfg.network} in this SDK version (missing ` +\n\t\t\t\t`${missing.join(', ')}): pass a \\`config\\` that records the Predict upgrade, the ` +\n\t\t\t\t'`deepbook_predict_orders` package, its order desk and its queue registry',\n\t\t);\n\t}\n\treturn {\n\t\t...toGeneratedConfig(cfg),\n\t\tpredictOrdersPackageId: predictOrders,\n\t\tpredictOrdersPackageIdV1: predictOrdersV1 ?? predictOrders,\n\t\tpredictMathPackageId: predictMath,\n\t\torderDesk,\n\t\tqueueRegistry,\n\t};\n}\n"],"mappings":";;;AAgCA,SAAgB,kBAAkB,KAAqC;AACtE,QAAO;EACN,kBAAkB,IAAI,SAAS;EAC/B,oBAAoB,IAAI,SAAS,aAAa,IAAI,SAAS;EAC3D,kBAAkB,IAAI,SAAS;EAC/B,gBAAgB,IAAI,QAAQ;EAC5B,WAAW,IAAI,QAAQ;EACvB,UAAU,IAAI,QAAQ;EACtB,gBAAgB,IAAI,QAAQ;EAC5B,iBAAiB,IAAI,QAAQ;EAC7B;;;;;;;;AAwBF,SAAgB,eAAe,KAA2C;CACzE,MAAM,EAAE,yBAAyB,eAAe,iBAAiB,gBAAgB,IAAI;CACrF,MAAM,EAAE,WAAW,kBAAkB,IAAI;AACzC,KAAI,CAAC,2BAA2B,CAAC,iBAAiB,CAAC,aAAa,CAAC,eAAe;EAC/E,MAAM,UAAU;GACf,CAAC,2BAA2B;GAC5B,CAAC,iBAAiB;GAClB,CAAC,aAAa;GACd,CAAC,iBAAiB;GAClB,CAAC,OAAO,QAAQ;AACjB,QAAM,IAAI,kBACT,wCAAwC,IAAI,QAAQ,gCAChD,QAAQ,KAAK,KAAK,CAAC,uIAEvB;;AAEF,QAAO;EACN,GAAG,kBAAkB,IAAI;EACzB,wBAAwB;EACxB,0BAA0B,mBAAmB;EAC7C,sBAAsB;EACtB;EACA;EACA"}
1
+ {"version":3,"file":"generated.mjs","names":[],"sources":["../../../src/predict/config/generated.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport type { AccountConfig } from '../../account.js';\nimport type { DeepbookPredictConfig } from '../../contracts/deepbook_predict/config-arguments.js';\nimport type { DeepbookPredictMathConfig } from '../../contracts/deepbook_predict_math/config-arguments.js';\nimport type { DeepbookPredictOrdersConfig } from '../../contracts/deepbook_predict_orders/config-arguments.js';\nimport { PredictInputError } from '../errors.js';\nimport type { PredictConfig } from './types.js';\n\n/**\n * The flat config slice the generated bindings resolve `options.config` against, projected from\n * the nested public `PredictConfig`. Each generated call declares only the keys it consumes, so a\n * single object carrying all of them satisfies every call site.\n *\n * Typed as the intersection of the two generated interfaces on purpose: if codegen adds, drops, or\n * renames a config key, this file stops compiling instead of silently building a PTB against the\n * wrong object.\n *\n * `predictPackageId` is narrowed to `string` because codegen types package ids as optional, while\n * this projection always supplies one. `predictPackageIdV1` separately supplies the original\n * identity for existing struct tags and dynamic-field keys. The two account ids restate a narrowing\n * `AccountConfig` already applies, so they are redundant today; they are kept so this projection\n * still compiles to plain ids if that package ever widens them back.\n */\nexport type GeneratedConfig = DeepbookPredictConfig &\n\tAccountConfig & {\n\t\tpredictPackageId: string;\n\t\tpredictPackageIdV1: string;\n\t\t/** The ORIGINAL account ID: type tags and derived addresses are built from it. */\n\t\taccountPackageId: string;\n\t\taccountRegistry: string;\n\t};\n\nexport function toGeneratedConfig(cfg: PredictConfig): GeneratedConfig {\n\treturn {\n\t\tpredictPackageId: cfg.packages.predict,\n\t\tpredictPackageIdV1: cfg.packages.predictV1 ?? cfg.packages.predict,\n\t\taccountPackageId: cfg.packages.account,\n\t\t// The account bindings call this when present (see `account-bindings/latest.ts`).\n\t\taccountPackageIdLatest: cfg.packages.accountLatest,\n\t\tprotocolConfig: cfg.objects.protocolConfig,\n\t\tpoolVault: cfg.objects.poolVault,\n\t\tregistry: cfg.objects.registry,\n\t\toracleRegistry: cfg.objects.oracleRegistry,\n\t\taccountRegistry: cfg.objects.accountRegistry,\n\t};\n}\n\n/**\n * {@link GeneratedConfig} plus the order-flow companion (`deepbook_predict_orders`) and the math\n * library: the slice the queued-order thunks and reads take. A queued order calls the companion,\n * which calls into Predict, so one object carries both packages' keys. `predictOrdersPackageIdV1`\n * is the companion's original ID, which types `OrderFlow` and the queue events.\n */\nexport type OrdersGeneratedConfig = GeneratedConfig &\n\tDeepbookPredictOrdersConfig &\n\tDeepbookPredictMathConfig & {\n\t\tpredictOrdersPackageId: string;\n\t\tpredictOrdersPackageIdV1: string;\n\t\torderDesk: string;\n\t\tqueueRegistry: string;\n\t};\n\n/**\n * Project a config that records delayed execution onto {@link OrdersGeneratedConfig}. Throws\n * `PredictInputError` while the config lacks the Predict upgrade, the companion package, its desk\n * or its queue registry: building a queued order against a guessed package would abort on chain\n * or, worse, address the wrong one.\n */\nexport function toOrdersConfig(cfg: PredictConfig): OrdersGeneratedConfig {\n\tconst { predictDelayedExecution, predictOrders, predictOrdersV1, predictMath } = cfg.packages;\n\tconst { orderDesk, queueRegistry } = cfg.objects;\n\tif (!predictDelayedExecution || !predictOrders || !orderDesk || !queueRegistry) {\n\t\tconst missing = [\n\t\t\t!predictDelayedExecution && '`packages.predictDelayedExecution`',\n\t\t\t!predictOrders && '`packages.predictOrders`',\n\t\t\t!orderDesk && '`objects.orderDesk`',\n\t\t\t!queueRegistry && '`objects.queueRegistry`',\n\t\t].filter(Boolean);\n\t\tthrow new PredictInputError(\n\t\t\t`delayed execution isn't recorded for ${cfg.network} in this SDK version (missing ` +\n\t\t\t\t`${missing.join(', ')}): pass a \\`config\\` that records the Predict upgrade, the ` +\n\t\t\t\t'`deepbook_predict_orders` package, its order desk and its queue registry',\n\t\t);\n\t}\n\treturn {\n\t\t...toGeneratedConfig(cfg),\n\t\tpredictOrdersPackageId: predictOrders,\n\t\tpredictOrdersPackageIdV1: predictOrdersV1 ?? predictOrders,\n\t\tpredictMathPackageId: predictMath,\n\t\torderDesk,\n\t\tqueueRegistry,\n\t};\n}\n"],"mappings":";;;AAiCA,SAAgB,kBAAkB,KAAqC;AACtE,QAAO;EACN,kBAAkB,IAAI,SAAS;EAC/B,oBAAoB,IAAI,SAAS,aAAa,IAAI,SAAS;EAC3D,kBAAkB,IAAI,SAAS;EAE/B,wBAAwB,IAAI,SAAS;EACrC,gBAAgB,IAAI,QAAQ;EAC5B,WAAW,IAAI,QAAQ;EACvB,UAAU,IAAI,QAAQ;EACtB,gBAAgB,IAAI,QAAQ;EAC5B,iBAAiB,IAAI,QAAQ;EAC7B;;;;;;;;AAwBF,SAAgB,eAAe,KAA2C;CACzE,MAAM,EAAE,yBAAyB,eAAe,iBAAiB,gBAAgB,IAAI;CACrF,MAAM,EAAE,WAAW,kBAAkB,IAAI;AACzC,KAAI,CAAC,2BAA2B,CAAC,iBAAiB,CAAC,aAAa,CAAC,eAAe;EAC/E,MAAM,UAAU;GACf,CAAC,2BAA2B;GAC5B,CAAC,iBAAiB;GAClB,CAAC,aAAa;GACd,CAAC,iBAAiB;GAClB,CAAC,OAAO,QAAQ;AACjB,QAAM,IAAI,kBACT,wCAAwC,IAAI,QAAQ,gCAChD,QAAQ,KAAK,KAAK,CAAC,uIAEvB;;AAEF,QAAO;EACN,GAAG,kBAAkB,IAAI;EACzB,wBAAwB;EACxB,0BAA0B,mBAAmB;EAC7C,sBAAsB;EACtB;EACA;EACA"}
@@ -15,7 +15,9 @@ const MAINNET_CONFIG = Object.freeze({
15
15
  network: "mainnet",
16
16
  packages: Object.freeze({
17
17
  ...MAINNET_PREDICT.packages,
18
- predictDelayedExecution: "0x98235c5842831c9b5f51dc637cf34c91db2aca5510802eb6ebfec63f5b71a7bb"
18
+ predictDelayedExecution: "0x98235c5842831c9b5f51dc637cf34c91db2aca5510802eb6ebfec63f5b71a7bb",
19
+ predictCurrentVersion: 4n,
20
+ predictOrdersCurrentVersion: 1n
19
21
  }),
20
22
  objects: Object.freeze({
21
23
  ...MAINNET_PREDICT.objects,
@@ -1 +1 @@
1
- {"version":3,"file":"mainnet.mjs","names":[],"sources":["../../../src/predict/config/mainnet.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { MAINNET_PREDICT } from '../../deployments/mainnet.js';\nimport type { PredictConfig } from './types.js';\n\n/**\n * Mainnet deployment constants, read from the shared generated record in\n * `src/deployments/` rather than transcribed here. `/account` and `/sessions` read slices of\n * that same record, so a redeploy (`pnpm sync-deployment`) moves every subpath together and\n * they cannot end up addressing different deployments.\n *\n * The record is generated from the deploy tooling's `deployment.mainnet.json`; see\n * `scripts/sync-deployment.ts`. `getDeployment('mainnet')` names the deployment and the\n * deepbookv3 commit these ids came from.\n */\nexport const MAINNET_CONFIG: PredictConfig = Object.freeze({\n\t// The record widens `network` to `string` so the published types don't pin a literal;\n\t// this file is the mainnet config by construction.\n\tnetwork: 'mainnet',\n\t// Delayed execution (DBU-885) is recorded on Mainnet. The generated record carries the package\n\t// IDs that move with upgrades (Predict, `deepbook_predict_orders`, `deepbook_predict_math`) and\n\t// the Lazer `State`. The three IDs pinned below are in no publication record and never move:\n\t// the Predict version that introduced delayed execution (Mainnet v4), which defines its new\n\t// types and events, and the `OrderDesk` and `QueueRegistry` that `deepbook_predict_orders`'s\n\t// `init` shared at publish.\n\tpackages: Object.freeze({\n\t\t...MAINNET_PREDICT.packages,\n\t\tpredictDelayedExecution: '0x98235c5842831c9b5f51dc637cf34c91db2aca5510802eb6ebfec63f5b71a7bb',\n\t}),\n\tobjects: Object.freeze({\n\t\t...MAINNET_PREDICT.objects,\n\t\torderDesk: '0x87b0a87262aacf58eaff567eed2fb7cb0f9cbc1f5ce33ef79216cd26d13a1b5b',\n\t\tqueueRegistry: '0x8d4f0c671862f065ac7f2c2cb24abc47cf75ed8fc8e5e52c1d4bdfa53eee164f',\n\t}),\n\tquoteCoinType: MAINNET_PREDICT.quoteCoinType,\n\tcoinTypes: MAINNET_PREDICT.coinTypes,\n\tunits: MAINNET_PREDICT.units,\n\tunderlyings: MAINNET_PREDICT.underlyings,\n\toracle: MAINNET_PREDICT.oracle,\n});\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAa,iBAAgC,OAAO,OAAO;CAG1D,SAAS;CAOT,UAAU,OAAO,OAAO;EACvB,GAAG,gBAAgB;EACnB,yBAAyB;EACzB,CAAC;CACF,SAAS,OAAO,OAAO;EACtB,GAAG,gBAAgB;EACnB,WAAW;EACX,eAAe;EACf,CAAC;CACF,eAAe,gBAAgB;CAC/B,WAAW,gBAAgB;CAC3B,OAAO,gBAAgB;CACvB,aAAa,gBAAgB;CAC7B,QAAQ,gBAAgB;CACxB,CAAC"}
1
+ {"version":3,"file":"mainnet.mjs","names":[],"sources":["../../../src/predict/config/mainnet.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { MAINNET_PREDICT } from '../../deployments/mainnet.js';\nimport type { PredictConfig } from './types.js';\n\n/**\n * Mainnet deployment constants, read from the shared generated record in\n * `src/deployments/` rather than transcribed here. `/account` and `/sessions` read slices of\n * that same record, so a redeploy (`pnpm sync-deployment`) moves every subpath together and\n * they cannot end up addressing different deployments.\n *\n * The record is generated from the deploy tooling's `deployment.mainnet.json`; see\n * `scripts/sync-deployment.ts`. `getDeployment('mainnet')` names the deployment and the\n * deepbookv3 commit these ids came from.\n */\nexport const MAINNET_CONFIG: PredictConfig = Object.freeze({\n\t// The record widens `network` to `string` so the published types don't pin a literal;\n\t// this file is the mainnet config by construction.\n\tnetwork: 'mainnet',\n\t// Delayed execution (DBU-885) is recorded on Mainnet. The generated record carries the package\n\t// IDs that move with upgrades (Predict, `deepbook_predict_orders`, `deepbook_predict_math`) and\n\t// the Lazer `State`. The three IDs pinned below are in no publication record and never move:\n\t// the Predict version that introduced delayed execution (Mainnet v4), which defines its new\n\t// types and events, and the `OrderDesk` and `QueueRegistry` that `deepbook_predict_orders`'s\n\t// `init` shared at publish.\n\tpackages: Object.freeze({\n\t\t...MAINNET_PREDICT.packages,\n\t\tpredictDelayedExecution: '0x98235c5842831c9b5f51dc637cf34c91db2aca5510802eb6ebfec63f5b71a7bb',\n\t\t// The version constants the call targets compile: Predict v4 compiles 4 and orders v1 compiles\n\t\t// 1. Move them with the call targets at the Version 5 upgrade (to 5 and 2).\n\t\tpredictCurrentVersion: 4n,\n\t\tpredictOrdersCurrentVersion: 1n,\n\t}),\n\tobjects: Object.freeze({\n\t\t...MAINNET_PREDICT.objects,\n\t\torderDesk: '0x87b0a87262aacf58eaff567eed2fb7cb0f9cbc1f5ce33ef79216cd26d13a1b5b',\n\t\tqueueRegistry: '0x8d4f0c671862f065ac7f2c2cb24abc47cf75ed8fc8e5e52c1d4bdfa53eee164f',\n\t}),\n\tquoteCoinType: MAINNET_PREDICT.quoteCoinType,\n\tcoinTypes: MAINNET_PREDICT.coinTypes,\n\tunits: MAINNET_PREDICT.units,\n\tunderlyings: MAINNET_PREDICT.underlyings,\n\toracle: MAINNET_PREDICT.oracle,\n});\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAa,iBAAgC,OAAO,OAAO;CAG1D,SAAS;CAOT,UAAU,OAAO,OAAO;EACvB,GAAG,gBAAgB;EACnB,yBAAyB;EAGzB,uBAAuB;EACvB,6BAA6B;EAC7B,CAAC;CACF,SAAS,OAAO,OAAO;EACtB,GAAG,gBAAgB;EACnB,WAAW;EACX,eAAe;EACf,CAAC;CACF,eAAe,gBAAgB;CAC/B,WAAW,gBAAgB;CAC3B,OAAO,gBAAgB;CACvB,aAAa,gBAAgB;CAC7B,QAAQ,gBAAgB;CACxB,CAAC"}
@@ -15,7 +15,9 @@ const TESTNET_CONFIG = Object.freeze({
15
15
  network: "testnet",
16
16
  packages: Object.freeze({
17
17
  ...TESTNET_PREDICT.packages,
18
- predictDelayedExecution: "0x0654ecbed7c0f2645d9de7cb6cf08e65c2ee05cdbb39a415f17a6bd1cd92e267"
18
+ predictDelayedExecution: "0x0654ecbed7c0f2645d9de7cb6cf08e65c2ee05cdbb39a415f17a6bd1cd92e267",
19
+ predictCurrentVersion: 5n,
20
+ predictOrdersCurrentVersion: 2n
19
21
  }),
20
22
  objects: Object.freeze({
21
23
  ...TESTNET_PREDICT.objects,
@@ -1 +1 @@
1
- {"version":3,"file":"testnet.mjs","names":[],"sources":["../../../src/predict/config/testnet.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { TESTNET_PREDICT } from '../../deployments/testnet.js';\nimport type { PredictConfig } from './types.js';\n\n/**\n * Testnet deployment constants, read from the shared generated record in\n * `src/deployments/` rather than transcribed here. `/account` and `/sessions` read slices of\n * that same record, so a redeploy (`pnpm sync-deployment`) moves every subpath together and\n * they cannot end up addressing different deployments.\n *\n * The record is generated from the deploy tooling's `deployment.testnet.json`; see\n * `scripts/sync-deployment.ts`. `getDeployment('testnet')` names the deployment and the\n * deepbookv3 commit these ids came from.\n */\nexport const TESTNET_CONFIG: PredictConfig = Object.freeze({\n\t// The record widens `network` to `string` so the published types don't pin a literal;\n\t// this file is the testnet config by construction.\n\tnetwork: 'testnet',\n\t// Delayed execution (DBU-885) is recorded on Testnet. The generated record carries the package\n\t// IDs that move with upgrades (Predict, `deepbook_predict_orders`, `deepbook_predict_math`) and\n\t// the Lazer `State`. The three IDs pinned below are in no publication record and never move:\n\t// the Predict version that introduced delayed execution (Testnet v5), which defines its new\n\t// types and events, and the `OrderDesk` and `QueueRegistry` that `deepbook_predict_orders`'s\n\t// `init` shared at publish.\n\tpackages: Object.freeze({\n\t\t...TESTNET_PREDICT.packages,\n\t\tpredictDelayedExecution: '0x0654ecbed7c0f2645d9de7cb6cf08e65c2ee05cdbb39a415f17a6bd1cd92e267',\n\t}),\n\tobjects: Object.freeze({\n\t\t...TESTNET_PREDICT.objects,\n\t\torderDesk: '0x160fc026c4143f3dec36acfc6556379d54661d37fe28ad837b6a85e42aeddfea',\n\t\tqueueRegistry: '0xe9d75ed05b089d52a660a94b94963cdc89aeb7f3c75b57f76771454c81faae1f',\n\t}),\n\tquoteCoinType: TESTNET_PREDICT.quoteCoinType,\n\tcoinTypes: TESTNET_PREDICT.coinTypes,\n\tunits: TESTNET_PREDICT.units,\n\tunderlyings: TESTNET_PREDICT.underlyings,\n\toracle: TESTNET_PREDICT.oracle,\n});\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAa,iBAAgC,OAAO,OAAO;CAG1D,SAAS;CAOT,UAAU,OAAO,OAAO;EACvB,GAAG,gBAAgB;EACnB,yBAAyB;EACzB,CAAC;CACF,SAAS,OAAO,OAAO;EACtB,GAAG,gBAAgB;EACnB,WAAW;EACX,eAAe;EACf,CAAC;CACF,eAAe,gBAAgB;CAC/B,WAAW,gBAAgB;CAC3B,OAAO,gBAAgB;CACvB,aAAa,gBAAgB;CAC7B,QAAQ,gBAAgB;CACxB,CAAC"}
1
+ {"version":3,"file":"testnet.mjs","names":[],"sources":["../../../src/predict/config/testnet.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { TESTNET_PREDICT } from '../../deployments/testnet.js';\nimport type { PredictConfig } from './types.js';\n\n/**\n * Testnet deployment constants, read from the shared generated record in\n * `src/deployments/` rather than transcribed here. `/account` and `/sessions` read slices of\n * that same record, so a redeploy (`pnpm sync-deployment`) moves every subpath together and\n * they cannot end up addressing different deployments.\n *\n * The record is generated from the deploy tooling's `deployment.testnet.json`; see\n * `scripts/sync-deployment.ts`. `getDeployment('testnet')` names the deployment and the\n * deepbookv3 commit these ids came from.\n */\nexport const TESTNET_CONFIG: PredictConfig = Object.freeze({\n\t// The record widens `network` to `string` so the published types don't pin a literal;\n\t// this file is the testnet config by construction.\n\tnetwork: 'testnet',\n\t// Delayed execution (DBU-885) is recorded on Testnet. The generated record carries the package\n\t// IDs that move with upgrades (Predict, `deepbook_predict_orders`, `deepbook_predict_math`) and\n\t// the Lazer `State`. The three IDs pinned below are in no publication record and never move:\n\t// the Predict version that introduced delayed execution (Testnet v5), which defines its new\n\t// types and events, and the `OrderDesk` and `QueueRegistry` that `deepbook_predict_orders`'s\n\t// `init` shared at publish.\n\tpackages: Object.freeze({\n\t\t...TESTNET_PREDICT.packages,\n\t\tpredictDelayedExecution: '0x0654ecbed7c0f2645d9de7cb6cf08e65c2ee05cdbb39a415f17a6bd1cd92e267',\n\t\t// The version constants the call targets compile (Version 5: Predict 5, orders 2, as Mainnet\n\t\t// will ship them), not their Testnet package numbers (v8, v3). Move them with the call targets.\n\t\tpredictCurrentVersion: 5n,\n\t\tpredictOrdersCurrentVersion: 2n,\n\t}),\n\tobjects: Object.freeze({\n\t\t...TESTNET_PREDICT.objects,\n\t\torderDesk: '0x160fc026c4143f3dec36acfc6556379d54661d37fe28ad837b6a85e42aeddfea',\n\t\tqueueRegistry: '0xe9d75ed05b089d52a660a94b94963cdc89aeb7f3c75b57f76771454c81faae1f',\n\t}),\n\tquoteCoinType: TESTNET_PREDICT.quoteCoinType,\n\tcoinTypes: TESTNET_PREDICT.coinTypes,\n\tunits: TESTNET_PREDICT.units,\n\tunderlyings: TESTNET_PREDICT.underlyings,\n\toracle: TESTNET_PREDICT.oracle,\n});\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAa,iBAAgC,OAAO,OAAO;CAG1D,SAAS;CAOT,UAAU,OAAO,OAAO;EACvB,GAAG,gBAAgB;EACnB,yBAAyB;EAGzB,uBAAuB;EACvB,6BAA6B;EAC7B,CAAC;CACF,SAAS,OAAO,OAAO;EACtB,GAAG,gBAAgB;EACnB,WAAW;EACX,eAAe;EACf,CAAC;CACF,eAAe,gBAAgB;CAC/B,WAAW,gBAAgB;CAC3B,OAAO,gBAAgB;CACvB,aAAa,gBAAgB;CAC7B,QAAQ,gBAAgB;CACxB,CAAC"}
@@ -36,8 +36,31 @@ interface PredictPackages {
36
36
  predictOrdersV1?: string;
37
37
  /** The `deepbook_predict_math` package ID, for its pure calls and layouts. */
38
38
  predictMath?: string;
39
+ /**
40
+ * ORIGINAL `account` package ID: type tags (`DataKey`, events) and the derived wrapper and
41
+ * account addresses are built from it, so it never moves.
42
+ */
39
43
  account: string;
44
+ /**
45
+ * Latest `account` package once the network has upgraded it: the call target of every account
46
+ * call in a Predict PTB (`generate_auth`, `deposit_funds`, `load_account`, …). A PTB can't call
47
+ * a package at an older version than another package in it links, and Predict's Version 5
48
+ * links account v2. Omit while account is at v1: calls then target `account`.
49
+ */
50
+ accountLatest?: string;
40
51
  propbook: string;
52
+ /**
53
+ * Predict's `constants::current_version` compiled into `predict`, the call target. A
54
+ * `ProtocolConfig.version_watermark` above it retires the code this config calls. It follows the
55
+ * Mainnet package number, not the Testnet one (Testnet's package v8 compiles 5). Defaults to
56
+ * `PREDICT_PACKAGE_VERSION`, the version these bindings were generated from.
57
+ */
58
+ predictCurrentVersion?: bigint;
59
+ /**
60
+ * `desk::current_version` compiled into `predictOrders`. A desk floor above it retires the
61
+ * order-flow code this config calls. Defaults to `ORDER_FLOW_PACKAGE_VERSION`.
62
+ */
63
+ predictOrdersCurrentVersion?: bigint;
41
64
  }
42
65
  /**
43
66
  * Per-underlying oracle wiring: the propbook underlying id plus the feed object ids the
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../src/predict/config/types.ts"],"mappings":";;AAaA;;;;;;;;;;UAAiB,eAAA;EA2BhB;EAzBA,OAAA;EAyBQ;EAvBR,SAAA;EA+BgC;;;;;;EAxBhC,uBAAA;EAgCA;;;AAID;;EA9BC,aAAA;EAgCU;;;;;EA1BV,eAAA;EA0BA;EAxBA,WAAA;EACA,OAAA;EACA,QAAA;AAAA;;;;;;UAQgB,gBAAA;EAChB,MAAA;EACA,oBAAA;EA2C0B;EAzC1B,QAAA;EA4CC;EA1CD,sBAAA;EA4CC;EA1CD,oBAAA;AAAA;;UAIgB,aAAA;EAChB,OAAA;EACA,QAAA,EAAU,eAAA;EACV,OAAA;IACC,QAAA;IACA,cAAA;IACA,SAAA;IACA,cAAA;IACA,eAAA;;;;;IAKA,SAAA;;;;;;IAMA,aAAA;EAAA;;;;;;;EAQD,aAAA;;;;;;EAMA,SAAA;IAAa,GAAA;IAAa,IAAA;EAAA;;EAE1B,KAAA;IACC,eAAA;IACA,eAAA;IACA,iBAAA;IACA,wBAAA;EAAA;EAED,WAAA,EAAa,MAAA,SAAe,gBAAA;;;;;EAK5B,MAAA;mFAEC,cAAA;EAAA;AAAA"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../../src/predict/config/types.ts"],"mappings":";;AAaA;;;;;;;;;;UAAiB,eAAA;EAqChB;EAnCA,OAAA;EA2CA;EAzCA,SAAA;EA8C2B;;AAQ5B;;;;EA/CC,uBAAA;EAiDA;;;;;EA3CA,aAAA;EAqDgB;;;;;EA/ChB,eAAA;EAwFmB;EAtFnB,WAAA;EA8CA;;;;EAzCA,OAAA;EA6CC;;;;;;EAtCD,aAAA;EACA,QAAA;EAiEa;;;;;;EA1Db,qBAAA;EAkEA;;;;EA7DA,2BAAA;AAAA;;;;;;UAQgB,gBAAA;EAChB,MAAA;EACA,oBAAA;;EAEA,QAAA;;EAEA,sBAAA;;EAEA,oBAAA;AAAA;;UAIgB,aAAA;EAChB,OAAA;EACA,QAAA,EAAU,eAAA;EACV,OAAA;IACC,QAAA;IACA,cAAA;IACA,SAAA;IACA,cAAA;IACA,eAAA;;;;;IAKA,SAAA;;;;;;IAMA,aAAA;EAAA;;;;;;;EAQD,aAAA;;;;;;EAMA,SAAA;IAAa,GAAA;IAAa,IAAA;EAAA;;EAE1B,KAAA;IACC,eAAA;IACA,eAAA;IACA,iBAAA;IACA,wBAAA;EAAA;EAED,WAAA,EAAa,MAAA,SAAe,gBAAA;;;;;EAK5B,MAAA;mFAEC,cAAA;EAAA;AAAA"}
@@ -169,7 +169,11 @@ interface MintInputsBase {
169
169
  nowMs?: number | bigint;
170
170
  /** Boundary probabilities, or a pricer snapshot plus the range's strikes. */
171
171
  probabilities: ProbabilitySource;
172
- /** Whether the minting account carries a builder code (it pays the builder fee). */
172
+ /**
173
+ * Whether the minting account carries a builder code and pays the account-attached builder fee:
174
+ * Predict v4 semantics. From Predict Version 5 an attached code charges nothing (a builder fee
175
+ * is passed on each trade instead), so leave this `false` on a network running Version 5.
176
+ */
173
177
  builderCode?: boolean;
174
178
  /** The expiry's remaining sponsored fee balance (`fee_incentive_balance`). Default `0n`. */
175
179
  feeIncentiveBalance?: number | bigint;
@@ -293,6 +297,10 @@ interface RedeemLiveInputs {
293
297
  closeQuantity: number | bigint;
294
298
  /** Current position payout quantity, when known. Validates the close and returns the remainder. */
295
299
  positionQuantity?: number | bigint;
300
+ /**
301
+ * Whether the selling account pays the account-attached builder fee: Predict v4 semantics.
302
+ * Leave it `false` on a network running Version 5, where an attached code charges nothing.
303
+ */
296
304
  builderCode?: boolean;
297
305
  penaltyRate?: bigint;
298
306
  /** Pre-trade payout-tree terms. Required when inventory impact is enabled. */
@@ -1 +1 @@
1
- {"version":3,"file":"cost.d.mts","names":[],"sources":["../../src/predict/cost.ts"],"mappings":";;;;;;;;cA8Ca,aAAA;;cAEA,iBAAA;;cAEA,WAAA;;cAEA,sBAAA;;cAEA,oBAAA;;;;;;;;;cASA,0BAAA;;cAEA,iBAAA;;iBAgEG,QAAA,CAAS,CAAA;;;;;;;;UAcR,SAAA;;EAEhB,OAAA;;EAEA,MAAA;;EAEA,iBAAA;;EAEA,sBAAA;;EAEA,mBAAA;;EAEA,mBAAA;;EAEA,sBAAA;;EAEA,oBAAA;EAjHyB;EAmHzB,mBAAA;AAAA;;AAjHD;;;;;AAEA;;;cA2Ha,kBAAA,EAAoB,SAAA;;AAzHjC;;UAwIiB,UAAA;EAxIkB;EA0IlC,OAAA;EAxIY;EA0IZ,QAAA;AAAA;;;AAjID;KAuIY,iBAAA,GACX,UAAA;EAAe,MAAA,EAAQ,YAAA;EAAc,KAAA;EAAsB,KAAA;AAAA;;UAG3C,eAAA;EAChB,IAAA;EACA,QAAA;AAAA;;UAIgB,gBAAA;EAChB,OAAA;EAhFiC;EAkFjC,WAAA;EApEyB;EAsEzB,eAAA;AAAA;;;UAKgB,aAAA;EAnEhB;EAqEA,SAAA;EAjEA;EAmEA,WAAA;EA/DA;EAiEA,cAAA;AAAA;;AAnDD;UAwDiB,cAAA,SAAuB,aAAA;;EAEvC,mBAAA;AAAA;AA3CD;;AAAA,iBAkGgB,gBAAA,CAAiB,OAAA,UAAiB,WAAA;;;iBASlC,mBAAA,CAAoB,MAAA,EAAQ,SAAA,EAAW,cAAA;;;;;;;iBAgCvC,UAAA,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GAAmB,kBAAA;;;;;UAkE7C,UAAA;EAChB,SAAA;EACA,UAAA;;EAEA,QAAA;AAAA;;;iBAKe,gBAAA,CAAiB,OAAA,UAAiB,OAAA,YAAsC,UAAA;;;;;;;;;iBAgBxE,aAAA,CACf,OAAA,UACA,kBAAA,UACA,WAAA,UACA,OAAA;;;;iBAYe,YAAA,CACf,KAAA,EAAO,UAAA,EACP,WAAA;EACI,KAAA;EAAsB,KAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"cost.mjs","names":["quantity"],"sources":["../../src/predict/cost.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Client-side ALL-IN cost math for Predict trades — the fee layer `pricing.ts` stops short of.\n// `pricing.*` answers \"what is this contract worth?\" (the probability); this module answers\n// \"what does the chain debit me for it?\" and \"what does closing it credit me?\", with NO chain\n// call: no `devInspect`, no dry run, no simulate.\n//\n// It is an EXACT integer port of the deployed cost path, function for function:\n//\n// mint `expiry_market::mint_quote_at` / `compute_mint_quote`\n// -> premium + (trading_fee - fee_incentive_subsidy) + builder_fee + penalty_fee\n// + inventory_impact_charge\n// budget `expiry_market::quote_exact_cost_terms` (the `mint_exact_cost` lot search)\n// redeem `expiry_market::redeem_live`'s payment decomposition\n// -> gross + inventory_impact_rebate - trading_fee - builder_fee - penalty\n// fees `strike_exposure_config::trading_fee` (per-boundary Bernoulli fee + expiry ramp),\n// `expiry_market::builder_fee_amount`, `ewma::penalty_fee`,\n// `strike_exposure::mint_range_inventory_impact` / `live_close_inventory_impact`\n//\n// Every rounding step is the chain's: `mul_down`, `mul_div_down` and a bit-identical\n// `sqrt_down` (same Newton schedule as `fixed_math::math`), all on bigints. So given the same\n// inputs the chain uses, these return the chain's numbers to the raw unit — the fee layer\n// carries no approximation of its own.\n//\n// Local float probabilities (`pricing.upProbability`, ~1e-4) introduce approximation.\n// With raw probabilities AND the same fee, account, book and clock inputs as execution,\n// the arithmetic matches the chain. `exactProbabilities` only identifies the probability\n// input format; it does not certify the source or freshness of any state. A nonzero\n// inventory-impact policy requires book data. Congestion defaults to a zero rate; supply\n// the actual rate when enabled. Use `read.quoteMint` / `read.quoteRedeem` for a simulation\n// against current account and market state, including the execution gates these previews\n// do not check (ownership, pauses, trade window, oracle freshness and cash backing).\n//\n// The fee POLICY is a per-market snapshot taken at creation (`StrikeExposureConfig`). The\n// chain exposes no getter for `base_fee`/`min_fee`, so `read.feePolicy(market)` decodes it from\n// the `ExpiryMarket` object. The market's `MarketCreated` event carries it too.\n\nimport { PredictInputError } from './errors.js';\nimport type { PricerInputs } from './pricing.js';\nimport { upProbability } from './pricing.js';\nimport { POS_INF_TICK } from './ticks.js';\nimport { fromRaw, U64_MAX, usdcToRaw } from './units.js';\n\n// === Protocol constants (mirrors of `deepbook_predict::constants` / `fixed_math::math`) ===\n\n/** `math::float_scaling` — 1e9 is 1.0 for every rate and probability here. */\nexport const FLOAT_SCALING = 1_000_000_000n;\n/** `constants::position_lot_size` — quantity is an integer number of these. */\nexport const POSITION_LOT_SIZE = 10_000n;\n/** `constants::min_premium` — a mint below this premium aborts `EPremiumBelowMinimum`. */\nexport const MIN_PREMIUM = 1_000_000n;\n/** `constants::builder_fee_multiplier` — the builder's cut of the trading fee (10%). */\nexport const BUILDER_FEE_MULTIPLIER = 100_000_000n;\n/** `constants::max_builder_fee_rate` — cap on the builder fee as a share of quantity (0.5%). */\nexport const MAX_BUILDER_FEE_RATE = 5_000_000n;\n/**\n * The default sponsor share of a trader's mint fee (20%), and the rate the chain reads while the\n * admin hasn't set one.\n * @deprecated From delayed execution (DBU-885) the rate is admin-set: read it with\n * `protocol_config::fee_incentive_subsidy_rate` (`read.queue(...).protocol.feeIncentiveSubsidyRate`)\n * and pass it as `feeIncentiveSubsidyRate`. A hardcoded 20% underquotes every mint once the rate\n * moves.\n */\nexport const FEE_INCENTIVE_SUBSIDY_RATE = 200_000_000n;\n/** `order::max_quantity_lots` — the order ID's 32-bit lot field. */\nexport const MAX_QUANTITY_LOTS = (1n << 32n) - 1n;\n\n// === Fixed-point primitives (mirrors of `fixed_math::math`) ===\n\nconst mulDown = (x: bigint, y: bigint): bigint => (x * y) / FLOAT_SCALING;\nconst divDown = (x: bigint, y: bigint): bigint => (x * FLOAT_SCALING) / y;\nconst mulDivDown = (x: bigint, y: bigint, denominator: bigint): bigint => (x * y) / denominator;\nconst min = (a: bigint, b: bigint): bigint => (a < b ? a : b);\nconst max = (a: bigint, b: bigint): bigint => (a > b ? a : b);\n\n// Move's unsigned types enforce these domains before arithmetic. JS bigint does not.\nfunction assertUint(value: bigint, name: string, maximum = U64_MAX, minimum = 0n): void {\n\tif (typeof value !== 'bigint' || value < minimum || value > maximum) {\n\t\tthrow new PredictInputError(\n\t\t\t`${name} must be an integer in [${minimum}, ${maximum}], got ${value}`,\n\t\t);\n\t}\n}\n\n// `math::sqrt_initial_guess_u128` — power-of-two seed for the Newton iteration.\nfunction sqrtInitialGuess(x: bigint): bigint {\n\tlet bits = 0n;\n\tlet val = x;\n\tif (val >= 1n << 64n) {\n\t\tval >>= 64n;\n\t\tbits += 64n;\n\t}\n\tif (val >= 1n << 32n) {\n\t\tval >>= 32n;\n\t\tbits += 32n;\n\t}\n\tif (val >= 1n << 16n) {\n\t\tval >>= 16n;\n\t\tbits += 16n;\n\t}\n\tif (val >= 1n << 8n) {\n\t\tval >>= 8n;\n\t\tbits += 8n;\n\t}\n\tif (val >= 1n << 4n) {\n\t\tval >>= 4n;\n\t\tbits += 4n;\n\t}\n\tif (val >= 1n << 2n) {\n\t\tval >>= 2n;\n\t\tbits += 2n;\n\t}\n\tif (val >= 1n << 1n) bits += 1n;\n\treturn 1n << ((bits + 1n) / 2n);\n}\n\n// `math::sqrt_u128_down` — seven Newton steps then one correcting decrement, exactly as the\n// chain runs them, so this agrees with the contract raw unit for raw unit rather than merely\n// to within a rounding step.\nfunction sqrtU128Down(x: bigint): bigint {\n\tif (x === 0n) return 0n;\n\tif (x < 4n) return 1n;\n\tlet g = sqrtInitialGuess(x);\n\tfor (let i = 0; i < 7; i++) g = (g + x / g) / 2n;\n\tif (g > x / g) g -= 1n;\n\treturn g;\n}\n\n/** `math::sqrt_down` — square root of a 1e9-scaled value, 1e9-scaled, rounded down. */\nexport function sqrtDown(x: bigint): bigint {\n\tassertUint(x, 'sqrt input');\n\treturn sqrtU128Down(x * FLOAT_SCALING);\n}\n\n// === Policy and state inputs ===\n\n/**\n * One market's fee policy: the `StrikeExposureConfig` it snapshotted at creation, in raw 1e9\n * rates. Snapshotted means later admin changes do NOT reprice a market already trading, so\n * read it per market with `read.feePolicy(market)` (the `MarketCreated` event carries every field\n * too) rather than assuming the template. The last three are the inventory-impact parameters, inert while\n * `inventoryImpactMaxRate` is `0n` (the shipped value).\n */\nexport interface FeePolicy {\n\t/** `base_fee` — multiplies `sqrt(p·(1−p))`. */\n\tbaseFee: bigint;\n\t/** `min_fee` — per-unit floor, applied per boundary leg before the ramp. */\n\tminFee: bigint;\n\t/** `expiry_fee_window_ms` — window before expiry over which the fee ramps. */\n\texpiryFeeWindowMs: bigint;\n\t/** `expiry_fee_max_multiplier` — multiplier reached at expiry; 1e9 disables the ramp. */\n\texpiryFeeMaxMultiplier: bigint;\n\t/** `min_entry_probability` — mint admission floor on the entry probability. */\n\tminEntryProbability: bigint;\n\t/** `max_entry_probability` — mint admission ceiling on the entry probability. */\n\tmaxEntryProbability: bigint;\n\t/** `inventory_impact_max_rate` — maximum marginal impact rate; `0n` disables impact. */\n\tinventoryImpactMaxRate: bigint;\n\t/** `inventory_impact_scale` — the market's `max_expiry_allocation`, the curve's `B`. */\n\tinventoryImpactScale: bigint;\n\t/** `backing_buffer_lambda` — the buffer on non-peak payout in the liability formula. */\n\tbackingBufferLambda: bigint;\n}\n\n/**\n * The shipped template (`config_constants` defaults): 10% Bernoulli fee, a 2.2% per-leg floor,\n * a one-day ramp window that is inert at a 1.0 multiplier, a 1%–99% entry band, and inventory\n * impact disabled. Neither recorded deployment's template matches it any more: both charge a\n * 20.4% Bernoulli fee, ramp it to 3× over the last 60 s and admit entries in 25%–75% (checked\n * 2026-10-09), so a live market's costs from this policy come out low. Pass\n * `read.feePolicy(market)` instead. This stays for tests and for a deployment still on the\n * defaults.\n */\nexport const SHIPPED_FEE_POLICY: FeePolicy = Object.freeze({\n\tbaseFee: 100_000_000n,\n\tminFee: 22_000_000n,\n\texpiryFeeWindowMs: 86_400_000n,\n\texpiryFeeMaxMultiplier: FLOAT_SCALING,\n\tminEntryProbability: 10_000_000n,\n\tmaxEntryProbability: 990_000_000n,\n\tinventoryImpactMaxRate: 0n,\n\tinventoryImpactScale: 0n,\n\tbackingBufferLambda: 310_000_000n,\n});\n\n/** A range's two boundary UP probabilities, raw 1e9. `null` is an infinite boundary — the\n * −∞ lower of a DOWN order and the +∞ higher of an UP order — which is priced at the digital\n * limit and pays no fee leg. */\nexport interface Boundaries {\n\t/** `P(settle > lower)`, or `null` for the −∞ lower bound. */\n\tlowerUp: bigint | null;\n\t/** `P(settle > higher)`, or `null` for the +∞ higher bound. */\n\thigherUp: bigint | null;\n}\n\n/** Where a quote's probabilities come from: boundary probabilities you already hold (raw 1e9,\n * e.g. `probabilityToRaw((await read.price(...)).up)`) or a local pricer snapshot plus\n * the range's strikes in USD (`null` for an infinite side). */\nexport type ProbabilitySource =\n\tBoundaries | { pricer: PricerInputs; lower: number | null; upper: number | null };\n\n/** The market's gas-price EWMA (`ewma::EwmaState`), both fields 1e9-scaled. */\nexport interface CongestionState {\n\tmean: bigint;\n\tvariance: bigint;\n}\n\n/** The protocol's congestion knobs (`EwmaConfig`). Shipped disabled. */\nexport interface CongestionPolicy {\n\tenabled: boolean;\n\t/** `penalty_rate` — per-unit surcharge charged when the z-score fires. */\n\tpenaltyRate: bigint;\n\t/** `z_score_threshold` — how many standard deviations above the mean gas must sit. */\n\tzScoreThreshold: bigint;\n}\n\n/** Pre-trade payout-tree reads a mint's inventory-impact charge is evaluated against\n * (`strike_exposure::quote_mint_range`). All in quote units. */\nexport interface MintBookTerms {\n\t/** `M` — largest summed net payout at any one settlement price. */\n\tmaxPayout: bigint;\n\t/** `T` — sum of every live order's payout. */\n\ttotalPayout: bigint;\n\t/** The payout peak inside the mint's own `(lower, higher]`. */\n\trangeMaxPayout: bigint;\n}\n\n/** The same reads for a live close, which also needs the peak OUTSIDE the order's range\n * (`strike_exposure::live_close_inventory_impact`). */\nexport interface CloseBookTerms extends MintBookTerms {\n\t/** The payout peak in the complement of the order's range. */\n\tcomplementMaxPayout: bigint;\n}\n\nfunction assertFeePolicy(policy: FeePolicy): void {\n\tassertUint(policy.baseFee, 'baseFee', FLOAT_SCALING);\n\tassertUint(policy.minFee, 'minFee', FLOAT_SCALING);\n\tassertUint(policy.expiryFeeWindowMs, 'expiryFeeWindowMs', U64_MAX, 1n);\n\tassertUint(\n\t\tpolicy.expiryFeeMaxMultiplier,\n\t\t'expiryFeeMaxMultiplier',\n\t\t10n * FLOAT_SCALING,\n\t\tFLOAT_SCALING,\n\t);\n\tassertUint(policy.minEntryProbability, 'minEntryProbability', FLOAT_SCALING);\n\tassertUint(policy.maxEntryProbability, 'maxEntryProbability', FLOAT_SCALING);\n\tif (policy.minEntryProbability >= policy.maxEntryProbability) {\n\t\tthrow new PredictInputError('minEntryProbability must be below maxEntryProbability');\n\t}\n\tassertUint(policy.inventoryImpactMaxRate, 'inventoryImpactMaxRate', FLOAT_SCALING);\n\tassertUint(policy.backingBufferLambda, 'backingBufferLambda', FLOAT_SCALING);\n\tassertUint(\n\t\tpolicy.inventoryImpactScale,\n\t\t'inventoryImpactScale',\n\t\tU64_MAX,\n\t\tpolicy.inventoryImpactMaxRate === 0n ? 0n : 1n,\n\t);\n}\n\nfunction assertBoundaries(boundaries: Boundaries): void {\n\tif (boundaries.lowerUp !== null) assertUint(boundaries.lowerUp, 'lowerUp', FLOAT_SCALING);\n\tif (boundaries.higherUp !== null) assertUint(boundaries.higherUp, 'higherUp', FLOAT_SCALING);\n}\n\nfunction assertBook(book: MintBookTerms): void {\n\tassertUint(book.totalPayout, 'totalPayout');\n\tassertUint(book.maxPayout, 'maxPayout', book.totalPayout);\n\tassertUint(book.rangeMaxPayout, 'rangeMaxPayout', book.maxPayout);\n}\n\nfunction assertCostInputs(\n\tinputs: Pick<MintInputsBase, 'fees' | 'book' | 'penaltyRate' | 'lotSize'>,\n): void {\n\tassertFeePolicy(inputs.fees);\n\tassertUint(inputs.penaltyRate ?? 0n, 'penaltyRate', FLOAT_SCALING);\n\tassertUint(inputs.lotSize ?? POSITION_LOT_SIZE, 'lotSize', U64_MAX / MAX_QUANTITY_LOTS, 1n);\n\tif (inputs.fees.inventoryImpactMaxRate > 0n && !inputs.book) {\n\t\tthrow new PredictInputError('book is required when inventory impact is enabled');\n\t}\n\tif (inputs.book) assertBook(inputs.book);\n}\n\n// === Fee components ===\n\n/** `strike_exposure_config::raw_bernoulli_fee_rate` — `base_fee · sqrt(p·(1−p))`, the fee rate\n * before the `min_fee` floor and the expiry ramp. Zero at the certain ends. */\nexport function bernoulliFeeRate(baseFee: bigint, probability: bigint): bigint {\n\tassertUint(baseFee, 'baseFee', FLOAT_SCALING);\n\tassertUint(probability, 'probability (EInvalidFeeProbability)', FLOAT_SCALING);\n\tif (probability === 0n || probability === FLOAT_SCALING) return 0n;\n\treturn mulDown(baseFee, sqrtDown(mulDown(probability, FLOAT_SCALING - probability)));\n}\n\n/** `strike_exposure_config::expiry_fee_multiplier` — 1.0 outside the window, rising linearly\n * to `expiry_fee_max_multiplier` at expiry. */\nexport function expiryFeeMultiplier(policy: FeePolicy, timeToExpiryMs: bigint): bigint {\n\tassertFeePolicy(policy);\n\tassertUint(timeToExpiryMs, 'timeToExpiryMs');\n\tif (timeToExpiryMs >= policy.expiryFeeWindowMs) return FLOAT_SCALING;\n\treturn (\n\t\tFLOAT_SCALING +\n\t\tmulDivDown(\n\t\t\tpolicy.expiryFeeMaxMultiplier - FLOAT_SCALING,\n\t\t\tpolicy.expiryFeeWindowMs - timeToExpiryMs,\n\t\t\tpolicy.expiryFeeWindowMs,\n\t\t)\n\t);\n}\n\n// `strike_exposure_config::leg_trading_fee` — one finite boundary's fee, floored then ramped,\n// rounded down at each step.\nfunction legTradingFee(\n\tpolicy: FeePolicy,\n\tprobability: bigint,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): bigint {\n\tconst base = max(bernoulliFeeRate(policy.baseFee, probability), policy.minFee);\n\treturn mulDown(mulDown(base, expiryFeeMultiplier(policy, timeToExpiryMs)), quantity);\n}\n\n/**\n * `strike_exposure_config::trading_fee` — the fee for a whole range, charged PER FINITE\n * BOUNDARY with each leg floored and ramped independently. A binary order has one finite\n * boundary and pays one leg; a two-sided range pays two, so it is not the same fee as the\n * range's own probability would suggest.\n */\nexport function tradingFee(\n\tpolicy: FeePolicy,\n\tboundaries: Boundaries,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBoundaries(boundaries);\n\tassertUint(quantity, 'quantity');\n\tassertUint(timeToExpiryMs, 'timeToExpiryMs');\n\tconst lower =\n\t\tboundaries.lowerUp === null\n\t\t\t? 0n\n\t\t\t: legTradingFee(policy, boundaries.lowerUp, quantity, timeToExpiryMs);\n\tconst higher =\n\t\tboundaries.higherUp === null\n\t\t\t? 0n\n\t\t\t: legTradingFee(policy, boundaries.higherUp, quantity, timeToExpiryMs);\n\treturn lower + higher;\n}\n\n/** `expiry_market::builder_fee_amount` — an account carrying a builder code pays the builder a\n * multiple of its trading fee, capped as a share of quantity. */\nexport function builderFee(fee: bigint, quantity: bigint, hasBuilderCode: boolean): bigint {\n\tassertUint(fee, 'fee');\n\tassertUint(quantity, 'quantity');\n\tif (!hasBuilderCode) return 0n;\n\treturn min(mulDown(fee, BUILDER_FEE_MULTIPLIER), mulDown(quantity, MAX_BUILDER_FEE_RATE));\n}\n\n/** `expiry_market::fee_incentive_subsidy_amount` — a sponsor pays part of the trader's MINT\n * fee, bounded by the expiry's remaining sponsored balance. Mints only; redeems pay in full.\n * `rate` is the protocol's `fee_incentive_subsidy_rate` (1e9-scaled), 20% when omitted. */\nexport function feeIncentiveSubsidy(\n\tfee: bigint,\n\tfeeIncentiveBalance: bigint,\n\trate: bigint = FEE_INCENTIVE_SUBSIDY_RATE,\n): bigint {\n\tassertUint(fee, 'fee');\n\tassertUint(feeIncentiveBalance, 'feeIncentiveBalance');\n\tassertUint(rate, 'feeIncentiveSubsidyRate', FLOAT_SCALING);\n\treturn min(mulDown(fee, rate), feeIncentiveBalance);\n}\n\n/**\n * `ewma::penalty_fee`'s firing test, as a per-unit RATE: `penalty_rate` when the transaction's\n * gas price is a high outlier against the market's pre-trade EWMA, else zero. It is a rate and\n * not an amount because the surcharge is `rate · quantity`, and a budget search has to reprice\n * it at every candidate quantity. `gasPrice` is the raw reference gas price (not 1e9-scaled),\n * as `tx_context::gas_price` reports it.\n */\nexport function congestionPenaltyRate(\n\tpolicy: CongestionPolicy,\n\tstate: CongestionState,\n\tgasPrice: bigint,\n): bigint {\n\tassertUint(policy.penaltyRate, 'penaltyRate', FLOAT_SCALING);\n\tassertUint(policy.zScoreThreshold, 'zScoreThreshold');\n\tassertUint(state.mean, 'mean');\n\tassertUint(state.variance, 'variance');\n\tassertUint(gasPrice, 'gasPrice', U64_MAX / FLOAT_SCALING);\n\tif (!policy.enabled || state.variance === 0n) return 0n;\n\tconst scaled = gasPrice * FLOAT_SCALING;\n\tif (scaled <= state.mean) return 0n;\n\tconst zScore = divDown(scaled - state.mean, sqrtDown(state.variance));\n\tif (zScore <= policy.zScoreThreshold) return 0n;\n\treturn policy.penaltyRate;\n}\n\n// `strike_exposure::live_payout_liability_from_terms` — `M + lambda·(T − M)`.\nfunction payoutLiability(policy: FeePolicy, maxPayout: bigint, totalPayout: bigint): bigint {\n\treturn maxPayout + mulDown(policy.backingBufferLambda, totalPayout - maxPayout);\n}\n\n/**\n * `strike_exposure::inventory_impact_potential_for_liability` — the book-level potential\n * `phi(L)`: marginal rate rising linearly to `inventory_impact_max_rate` over the scale `B`,\n * flat at the cap above it. Trades are charged the DIFFERENCE of two evaluations, which is\n * what makes inventory cycles telescope to zero.\n */\nexport function inventoryImpactPotential(policy: FeePolicy, liability: bigint): bigint {\n\tassertFeePolicy(policy);\n\tassertUint(liability, 'liability');\n\tif (policy.inventoryImpactMaxRate === 0n || liability === 0n) return 0n;\n\tconst scale = policy.inventoryImpactScale;\n\tconst capped = min(liability, scale);\n\tconst utilization = mulDivDown(capped, FLOAT_SCALING, scale);\n\tconst marginalRate = mulDown(policy.inventoryImpactMaxRate, utilization);\n\tconst potentialAtCapped = mulDown(marginalRate, capped) / 2n;\n\tif (liability <= scale) return potentialAtCapped;\n\treturn potentialAtCapped + mulDown(policy.inventoryImpactMaxRate, liability - scale);\n}\n\n/** `strike_exposure::mint_range_inventory_impact` — the charge a mint of `quantity` over a\n * range pays: the exact rise in the book potential. Zero at the shipped rate of `0n`. */\nexport function mintInventoryImpact(\n\tpolicy: FeePolicy,\n\tbook: MintBookTerms,\n\tquantity: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBook(book);\n\tassertUint(quantity, 'quantity', U64_MAX - book.totalPayout);\n\tif (policy.inventoryImpactMaxRate === 0n || quantity === 0n) return 0n;\n\tconst before = payoutLiability(policy, book.maxPayout, book.totalPayout);\n\tconst after = payoutLiability(\n\t\tpolicy,\n\t\tmax(book.maxPayout, book.rangeMaxPayout + quantity),\n\t\tbook.totalPayout + quantity,\n\t);\n\treturn inventoryImpactPotential(policy, after) - inventoryImpactPotential(policy, before);\n}\n\n/** `strike_exposure::live_close_inventory_impact` — the rebate a live close of `payout`\n * receives: the exact fall in the same potential. Zero at the shipped rate of `0n`. */\nexport function closeInventoryImpact(\n\tpolicy: FeePolicy,\n\tbook: CloseBookTerms,\n\tpayout: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBook(book);\n\tassertUint(book.complementMaxPayout, 'complementMaxPayout', book.maxPayout);\n\tif (max(book.rangeMaxPayout, book.complementMaxPayout) !== book.maxPayout) {\n\t\tthrow new PredictInputError('maxPayout must equal the larger range or complement payout');\n\t}\n\tassertUint(payout, 'close payout', book.rangeMaxPayout);\n\tif (policy.inventoryImpactMaxRate === 0n || payout === 0n) return 0n;\n\tconst before = payoutLiability(policy, book.maxPayout, book.totalPayout);\n\tconst after = payoutLiability(\n\t\tpolicy,\n\t\tmax(book.rangeMaxPayout - payout, book.complementMaxPayout),\n\t\tbook.totalPayout - payout,\n\t);\n\treturn inventoryImpactPotential(policy, before) - inventoryImpactPotential(policy, after);\n}\n\n// === Probabilities ===\n\n/** `pricing::probability` — the range's own probability, `up(lower) − up(higher)` with the\n * chain's saturating subtraction and its infinite-boundary defaults. */\nexport function rangeProbability(boundaries: Boundaries): bigint {\n\tassertBoundaries(boundaries);\n\tconst lower = boundaries.lowerUp ?? FLOAT_SCALING;\n\tconst higher = boundaries.higherUp ?? 0n;\n\treturn lower > higher ? lower - higher : 0n;\n}\n\n// Float probability -> the chain's raw 1e9 domain, clamped like `compute_nd2`'s own clamp.\nfunction toRawProbability(p: number): bigint {\n\tif (!Number.isFinite(p)) throw new PredictInputError(`probability is not finite: ${p}`);\n\tconst raw = BigInt(Math.round(p * Number(FLOAT_SCALING)));\n\treturn raw < 0n ? 0n : raw > FLOAT_SCALING ? FLOAT_SCALING : raw;\n}\n\n/** Price a range's two boundaries with the local float pricer. `lower`/`upper` are strikes in\n * USD; pass `null` for an infinite side (`{ lower: strike, upper: null }` is an UP order,\n * `{ lower: null, upper: strike }` a DOWN order). Carries the pricer's ~1e-4 approximation. */\nexport function boundaryProbabilities(\n\tpricer: PricerInputs,\n\tlower: number | null,\n\tupper: number | null,\n): Boundaries {\n\treturn {\n\t\tlowerUp: lower === null ? null : toRawProbability(upProbability(pricer, lower)),\n\t\thigherUp: upper === null ? null : toRawProbability(upProbability(pricer, upper)),\n\t};\n}\n\nfunction resolveBoundaries(source: ProbabilitySource): { boundaries: Boundaries; exact: boolean } {\n\tlet boundaries: Boundaries;\n\tlet exact: boolean;\n\tif ('pricer' in source) {\n\t\tconst { lower, upper } = source;\n\t\tif (lower !== null && upper !== null && lower >= upper) {\n\t\t\tthrow new PredictInputError(`lower strike ${lower} must be below ${upper} (EInvalidRange)`);\n\t\t}\n\t\tboundaries = boundaryProbabilities(source.pricer, lower, upper);\n\t\texact = false;\n\t} else {\n\t\tboundaries = source;\n\t\texact = true;\n\t}\n\tassertBoundaries(boundaries);\n\t// `(-inf, +inf]` is the whole outcome space; `order::assert_valid_order_shape` rejects it.\n\tif (boundaries.lowerUp === null && boundaries.higherUp === null) {\n\t\tthrow new PredictInputError('a range cannot be infinite on both sides (EInvalidRange)');\n\t}\n\treturn { boundaries, exact };\n}\n\n// `number` is a human amount in USDC decimals, `bigint` is already raw — the SDK-wide\n// convention for every financial parameter.\nfunction rawAmount(value: number | bigint): bigint {\n\tconst raw = typeof value === 'bigint' ? value : usdcToRaw(value);\n\tassertUint(raw, 'amount');\n\treturn raw;\n}\n\nfunction rawMs(value: number | bigint): bigint {\n\tif (typeof value === 'number' && !Number.isSafeInteger(value)) {\n\t\tthrow new PredictInputError(`timestamp must be a safe integer in milliseconds, got ${value}`);\n\t}\n\tconst raw = typeof value === 'bigint' ? value : BigInt(value);\n\tassertUint(raw, 'timestamp');\n\treturn raw;\n}\n\n// === Mint ===\n\n/** Inputs shared by the exact-quantity mint quote and the budget-sized one. */\ninterface MintInputsBase {\n\t/** The market's snapshotted fee policy. */\n\tfees: FeePolicy;\n\t/** Market expiry, ms since epoch. */\n\texpiryMs: number | bigint;\n\t/** The clock the trade will price against, ms since epoch. Defaults to `Date.now()`. */\n\tnowMs?: number | bigint;\n\t/** Boundary probabilities, or a pricer snapshot plus the range's strikes. */\n\tprobabilities: ProbabilitySource;\n\t/** Whether the minting account carries a builder code (it pays the builder fee). */\n\tbuilderCode?: boolean;\n\t/** The expiry's remaining sponsored fee balance (`fee_incentive_balance`). Default `0n`. */\n\tfeeIncentiveBalance?: number | bigint;\n\t/**\n\t * The protocol's admin-set mint fee subsidy rate (`protocol_config::fee_incentive_subsidy_rate`),\n\t * 1e9-scaled. Defaults to the 20% the chain reads while unset.\n\t */\n\tfeeIncentiveSubsidyRate?: bigint;\n\t/**\n\t * Per-unit congestion surcharge rate — see {@link congestionPenaltyRate}. Default `0n`. A\n\t * queued (delayed-execution) fill pays no congestion penalty, so queued previews keep it 0.\n\t */\n\tpenaltyRate?: bigint;\n\t/** Pre-trade payout-tree terms. Required when inventory impact is enabled. */\n\tbook?: MintBookTerms;\n\t/** The deployment's `position_lot_size`. Defaults to the Move constant, `10_000n`. */\n\tlotSize?: bigint;\n}\n\n/** Inputs for {@link mintCost}: an exact payout quantity. */\nexport interface MintCostInputs extends MintInputsBase {\n\t/** Maximum payout bought, in quote units — `number` is human USD, `bigint` is raw. */\n\tquantity: number | bigint;\n}\n\n/** Inputs for {@link mintCostForBudget}: an all-in budget, the `mint_exact_cost` shape. */\nexport interface MintBudgetInputs extends MintInputsBase {\n\t/** The total to spend, fees included. */\n\tbudget: number | bigint;\n\t/** Floor on the fill; a smaller result aborts, as `mint_exact_cost` does. Default one lot. */\n\tminQuantity?: number | bigint;\n\t/** The account's settled USDC. The chain caps the budget at it before sizing; pass it to\n\t * reproduce that cap (and to let `U64_MAX` mean \"my whole balance\"). */\n\taccountBalance?: number | bigint;\n}\n\n/** One mint's cost decomposition — the fields of the chain's `MintQuote`, in human units with\n * the exact integers alongside. `cost` is the account debit. */\nexport interface MintCost {\n\t/** Maximum payout bought (human quote units). */\n\tquantity: number;\n\t/** Fill price, 0..1 per $1 of payout, before fees. */\n\tentryProbability: number;\n\t/** Premium into LP backing. */\n\tpremium: number;\n\t/** `referral` is not here: it is a split of protocol proceeds, not a trader debit. */\n\tfees: { trading: number; subsidy: number; builder: number; penalty: number; impact: number };\n\t/** All-in account debit: `premium + (trading − subsidy) + builder + penalty + impact`. */\n\tcost: number;\n\t/** All-in price per $1 of payout — `cost / quantity`, the number to compare across venues. */\n\tcostPerContract: number;\n\t/** Maximum payout divided by the all-in debit, including fees. */\n\tpayoutMultiple: number;\n\traw: {\n\t\tquantity: bigint;\n\t\tentryProbability: bigint;\n\t\tpremium: bigint;\n\t\ttradingFee: bigint;\n\t\tsubsidy: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\timpactCharge: bigint;\n\t\tcost: bigint;\n\t};\n\t/** True when boundary probabilities were supplied as raw integers rather than priced\n\t * locally in float. Does not verify their source, freshness or the other quote inputs. */\n\texactProbabilities: boolean;\n}\n\n/** Budget-sized mint plus the budget information needed to render an order preview. */\nexport interface MintBudgetCost extends Omit<MintCost, 'raw'> {\n\t/** Requested all-in budget, before the optional account-balance cap. */\n\tbudget: number;\n\t/** Budget after the optional account-balance cap. */\n\teffectiveBudget: number;\n\t/** Requested budget minus actual cost, including any balance-cap shortfall. */\n\tunspentBudget: number;\n\traw: MintCost['raw'] & {\n\t\tbudget: bigint;\n\t\teffectiveBudget: bigint;\n\t\tunspentBudget: bigint;\n\t};\n}\n\n// `strike_exposure_config::assert_mint_probability_policy`, applied where\n// `assert_range_mint_probability_policy` applies it: each finite leg and the range itself.\nfunction assertProbabilityPolicy(policy: FeePolicy, probability: bigint): void {\n\tif (probability < policy.minEntryProbability || probability > policy.maxEntryProbability) {\n\t\tthrow new PredictInputError(\n\t\t\t`entry probability ${probability} outside the market's [${policy.minEntryProbability}, ` +\n\t\t\t\t`${policy.maxEntryProbability}] admission band (EEntryProbabilityOutOfBounds)`,\n\t\t);\n\t}\n}\n\nfunction assertRangeMintPolicy(policy: FeePolicy, boundaries: Boundaries): void {\n\tif (boundaries.lowerUp !== null) assertProbabilityPolicy(policy, boundaries.lowerUp);\n\tif (boundaries.higherUp !== null) {\n\t\tassertProbabilityPolicy(policy, FLOAT_SCALING - boundaries.higherUp);\n\t}\n\tassertProbabilityPolicy(policy, rangeProbability(boundaries));\n}\n\nfunction assertValidQuantity(quantity: bigint, lotSize: bigint): void {\n\tif (quantity <= 0n || quantity % lotSize !== 0n || quantity / lotSize > MAX_QUANTITY_LOTS) {\n\t\tthrow new PredictInputError(\n\t\t\t`quantity ${quantity} must be a positive multiple of the ${lotSize} lot size, at most ` +\n\t\t\t\t`${MAX_QUANTITY_LOTS} lots (EInvalidQuantity)`,\n\t\t);\n\t}\n}\n\nfunction timeToExpiry(expiryMs: bigint, nowMs: bigint): bigint {\n\tif (nowMs >= expiryMs) {\n\t\tthrow new PredictInputError(\n\t\t\t`market expired at ${expiryMs}; a live trade at ${nowMs} aborts (ELivePricingExpired)`,\n\t\t);\n\t}\n\treturn expiryMs - nowMs;\n}\n\n// The all-in sum, `expiry_market::mint_quote_at`, with no admission checks — the one place the\n// cost is assembled, shared by the quote and the budget search exactly as the contract shares\n// it. Rounding order is the chain's: every component is floored before it is summed.\nfunction mintQuoteAt(\n\tinputs: MintInputsBase,\n\tboundaries: Boundaries,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): {\n\tpremium: bigint;\n\tfee: bigint;\n\tsubsidy: bigint;\n\tbuilder: bigint;\n\tpenalty: bigint;\n\timpact: bigint;\n\tcost: bigint;\n} {\n\tconst premium = mulDown(rangeProbability(boundaries), quantity);\n\tconst fee = tradingFee(inputs.fees, boundaries, quantity, timeToExpiryMs);\n\tconst subsidy = feeIncentiveSubsidy(\n\t\tfee,\n\t\trawAmount(inputs.feeIncentiveBalance ?? 0n),\n\t\tinputs.feeIncentiveSubsidyRate,\n\t);\n\tconst builder = builderFee(fee, quantity, inputs.builderCode ?? false);\n\tconst penalty = mulDown(inputs.penaltyRate ?? 0n, quantity);\n\tconst impact = inputs.book ? mintInventoryImpact(inputs.fees, inputs.book, quantity) : 0n;\n\treturn {\n\t\tpremium,\n\t\tfee,\n\t\tsubsidy,\n\t\tbuilder,\n\t\tpenalty,\n\t\timpact,\n\t\tcost: premium + (fee - subsidy) + builder + penalty + impact,\n\t};\n}\n\nfunction mintCostFrom(\n\tinputs: MintInputsBase,\n\tboundaries: Boundaries,\n\texact: boolean,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): MintCost {\n\tconst q = mintQuoteAt(inputs, boundaries, quantity, timeToExpiryMs);\n\tconst probability = rangeProbability(boundaries);\n\treturn {\n\t\tquantity: fromRaw(quantity, 6),\n\t\tentryProbability: fromRaw(probability, 9),\n\t\tpremium: fromRaw(q.premium, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(q.fee, 6),\n\t\t\tsubsidy: fromRaw(q.subsidy, 6),\n\t\t\tbuilder: fromRaw(q.builder, 6),\n\t\t\tpenalty: fromRaw(q.penalty, 6),\n\t\t\timpact: fromRaw(q.impact, 6),\n\t\t},\n\t\tcost: fromRaw(q.cost, 6),\n\t\tcostPerContract: quantity === 0n ? 0 : Number(q.cost) / Number(quantity),\n\t\tpayoutMultiple: Number(quantity) / Number(q.cost),\n\t\traw: {\n\t\t\tquantity,\n\t\t\tentryProbability: probability,\n\t\t\tpremium: q.premium,\n\t\t\ttradingFee: q.fee,\n\t\t\tsubsidy: q.subsidy,\n\t\t\tbuilderFee: q.builder,\n\t\t\tpenaltyFee: q.penalty,\n\t\t\timpactCharge: q.impact,\n\t\t\tcost: q.cost,\n\t\t},\n\t\texactProbabilities: exact,\n\t};\n}\n\n/**\n * All-in cost of minting an exact payout quantity — the `mint_exact_quantity` shape, priced\n * entirely client-side. Mirrors `compute_mint_quote`, including its admission checks: the\n * entry-probability band on each finite leg and on the range, the `min_premium` floor, the lot\n * grid, and the `all_in_cost <= quantity` bound (a contract may never cost more than it can\n * pay out). Each violation throws the `PredictInputError` naming the abort the chain would\n * have raised.\n */\nexport function mintCost(inputs: MintCostInputs): MintCost {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst quantity = rawAmount(inputs.quantity);\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\n\tassertRangeMintPolicy(inputs.fees, boundaries);\n\tconst premium = mulDown(rangeProbability(boundaries), quantity);\n\tif (premium < MIN_PREMIUM) {\n\t\tthrow new PredictInputError(\n\t\t\t`premium ${premium} is below the ${MIN_PREMIUM} minimum (EPremiumBelowMinimum)`,\n\t\t);\n\t}\n\tassertValidQuantity(quantity, lotSize);\n\n\tconst quote = mintCostFrom(inputs, boundaries, exact, quantity, ttl);\n\tif (quote.raw.cost > quantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`all-in cost ${quote.raw.cost} exceeds the maximum payout ${quantity} ` +\n\t\t\t\t`(EMintCostAboveMaxPayout)`,\n\t\t);\n\t}\n\treturn quote;\n}\n\n/**\n * A fill whose ALL-IN cost fits a budget — `expiry_market::mint_exact_cost` computed\n * client-side, with the same lot search over the same cost function, so the answer is the\n * quantity that entrypoint would size and the cost it would debit.\n *\n * Without it a \"spend exactly $X\" flow has to guess: every fee is charged ON TOP of the\n * premium, so the caller subtracts an estimated fee load, pads it against an abort, and\n * systematically underspends. Here the whole search runs locally; submit the all-in budget\n * through `tx.mintCost` on deployments carrying `mint_exact_cost`.\n *\n * Sizing also respects the fill's maximum payout and the 32-bit lot cap; either can leave\n * substantial budget unspent. When only the budget binds, one more lot would exceed it.\n * If the budget fill exceeds its maximum payout, the contract's step-down is best effort:\n * rounding can make it miss a larger admissible fill, including one meeting `minQuantity`.\n * The chain caps the budget at the account balance first ({@link MintBudgetInputs.accountBalance}).\n */\nexport function mintCostForBudget(inputs: MintBudgetInputs): MintBudgetCost {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\tconst minQuantity = inputs.minQuantity === undefined ? lotSize : rawAmount(inputs.minQuantity);\n\tconst requestedBudget = rawAmount(inputs.budget);\n\tlet budget = requestedBudget;\n\tif (inputs.accountBalance !== undefined) budget = min(budget, rawAmount(inputs.accountBalance));\n\n\tassertRangeMintPolicy(inputs.fees, boundaries);\n\n\t// `strike_exposure::max_quantity_for_premium` — the premium-only fit bounds the all-in\n\t// fit from above, because every other term is non-negative.\n\tconst probability = rangeProbability(boundaries);\n\tlet lo = 0n;\n\tlet hi = MAX_QUANTITY_LOTS;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi + 1n) / 2n;\n\t\tif (mulDown(probability, mid * lotSize) <= budget) lo = mid;\n\t\telse hi = mid - 1n;\n\t}\n\n\t// `expiry_market::quote_exact_cost_terms`, first half: the budget search proper. Exact,\n\t// because every all-in term is nondecreasing in quantity for fixed pre-trade state.\n\tconst allInCostAt = (quantity: bigint) => mintQuoteAt(inputs, boundaries, quantity, ttl).cost;\n\thi = lo;\n\tlo = 0n;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi + 1n) / 2n;\n\t\tif (allInCostAt(mid * lotSize) <= budget) lo = mid;\n\t\telse hi = mid - 1n;\n\t}\n\tconst budgetLots = lo;\n\tconst budgetQuantity = budgetLots * lotSize;\n\n\t// Second half: the maximum-payout bound (`cost <= quantity`) is deliberately NOT part of\n\t// that search. It is not monotone — cost and quantity both rise, and the independent floors\n\t// in each cost term let `cost(q) <= q` flip back to true at a larger lot wherever unit cost\n\t// sits within rounding of one — so binary-searching it would discard admissible fills. It is\n\t// consulted only when the budget fill breaches it, and the step-down runs strictly below\n\t// that fill, so every candidate already fits the budget.\n\t// This fallback mirrors Move's best-effort search; its nonmonotone predicate means it\n\t// can miss larger admissible fills, including one satisfying minQuantity.\n\tlet lots = budgetLots;\n\tif (budgetLots > 0n && allInCostAt(budgetQuantity) > budgetQuantity) {\n\t\tlet stepLo = 0n;\n\t\tlet stepHi = budgetLots - 1n;\n\t\twhile (stepLo < stepHi) {\n\t\t\tconst mid = (stepLo + stepHi + 1n) / 2n;\n\t\t\tconst candidate = mid * lotSize;\n\t\t\tif (allInCostAt(candidate) <= candidate) stepLo = mid;\n\t\t\telse stepHi = mid - 1n;\n\t\t}\n\t\t// No admissible smaller fill: fall back to the budget fill, which then fails the\n\t\t// maximum-payout bound below exactly as the chain's own quote aborts on it.\n\t\tlots = stepLo === 0n ? budgetLots : stepLo;\n\t}\n\n\tconst quantity = lots * lotSize;\n\tif (quantity < minQuantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`budget ${budget} sizes ${quantity}, below the ${minQuantity} minimum ` +\n\t\t\t\t`(EMintQuantityBelowMin)`,\n\t\t);\n\t}\n\tconst premium = mulDown(probability, quantity);\n\tif (premium < MIN_PREMIUM) {\n\t\tthrow new PredictInputError(\n\t\t\t`budget ${budget} sizes a premium of ${premium}, below the ${MIN_PREMIUM} minimum ` +\n\t\t\t\t`(EPremiumBelowMinimum)`,\n\t\t);\n\t}\n\tassertValidQuantity(quantity, lotSize);\n\tconst quote = mintCostFrom(inputs, boundaries, exact, quantity, ttl);\n\tif (quote.raw.cost > quantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`sized fill inside budget ${budget} costs more than it can pay out: ${quote.raw.cost} ` +\n\t\t\t\t`exceeds ${quantity} (EMintCostAboveMaxPayout)`,\n\t\t);\n\t}\n\treturn {\n\t\t...quote,\n\t\tbudget: fromRaw(requestedBudget, 6),\n\t\teffectiveBudget: fromRaw(budget, 6),\n\t\tunspentBudget: fromRaw(requestedBudget - quote.raw.cost, 6),\n\t\traw: {\n\t\t\t...quote.raw,\n\t\t\tbudget: requestedBudget,\n\t\t\teffectiveBudget: budget,\n\t\t\tunspentBudget: requestedBudget - quote.raw.cost,\n\t\t},\n\t};\n}\n\n// === Live redeem ===\n\n/** Inputs for {@link redeemLiveProceeds}. The range is the ORDER's own range — the same two\n * boundaries it was minted over, which is what `redeem_live` reprices. */\nexport interface RedeemLiveInputs {\n\tfees: FeePolicy;\n\texpiryMs: number | bigint;\n\tnowMs?: number | bigint;\n\t/** The order's boundary probabilities now, or a pricer snapshot plus the order's strikes. */\n\tprobabilities: ProbabilitySource;\n\t/** Payout being closed — the whole order, or part of it. */\n\tcloseQuantity: number | bigint;\n\t/** Current position payout quantity, when known. Validates the close and returns the remainder. */\n\tpositionQuantity?: number | bigint;\n\tbuilderCode?: boolean;\n\tpenaltyRate?: bigint;\n\t/** Pre-trade payout-tree terms. Required when inventory impact is enabled. */\n\tbook?: CloseBookTerms;\n\tlotSize?: bigint;\n}\n\n/** What a live close credits the account, decomposed. */\nexport interface RedeemLiveProceeds {\n\t/** NET credited to the account. */\n\tproceeds: number;\n\t/** Close value before fees: the range's current probability times the closed payout. */\n\tgross: number;\n\tfees: { trading: number; builder: number; penalty: number; impactRebate: number };\n\tquantityClosed: number;\n\t/** Unclosed payout quantity, or null when positionQuantity was not supplied. */\n\tremainingQuantity: number | null;\n\t/** Net credited per $1 of closed payout; includes fees and the inventory rebate. */\n\tproceedsPerContract: number;\n\t/** Current range probability, 0..1, before amount rounding and fees. */\n\tprobability: number;\n\traw: {\n\t\tproceeds: bigint;\n\t\tgross: bigint;\n\t\ttradingFee: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\timpactRebate: bigint;\n\t\tquantityClosed: bigint;\n\t\tremainingQuantity: bigint | null;\n\t\t/** 1e9-scaled range probability; locally priced inputs remain approximate. */\n\t\tprobability: bigint;\n\t};\n\t/** Identifies raw probability inputs; does not verify their source or state freshness. */\n\texactProbabilities: boolean;\n}\n\n/**\n * Net proceeds of closing a live position — `expiry_market::redeem_live`'s payment\n * decomposition, client-side. The mirror of {@link mintCost}: the same per-boundary trading\n * fee and builder fee, the same congestion surcharge, and the inventory-impact term as a\n * REBATE rather than a charge. There is no sponsor subsidy on a close (incentives subsidise\n * mints only), and each deduction is clamped at the payout remaining after the ones before it,\n * exactly as the contract clamps them, so a close can never cost more than it releases.\n *\n * Use this for a local UI preview from a supplied snapshot. `read.quoteRedeem` simulates\n * the actual close and remains the pre-trade check for ownership, remaining position size,\n * live-market gates and current fees. `proceeds` is what `min_proceeds` is compared against\n * on the real call; this preview does not guarantee execution at that amount.\n */\nexport function redeemLiveProceeds(inputs: RedeemLiveInputs): RedeemLiveProceeds {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst quantity = rawAmount(inputs.closeQuantity);\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\tassertValidQuantity(quantity, lotSize);\n\n\tconst positionQuantity =\n\t\tinputs.positionQuantity === undefined ? null : rawAmount(inputs.positionQuantity);\n\tif (positionQuantity !== null) {\n\t\tassertValidQuantity(positionQuantity, lotSize);\n\t\tif (quantity > positionQuantity)\n\t\t\tthrow new PredictInputError('closeQuantity exceeds positionQuantity');\n\t}\n\tconst remainingQuantity = positionQuantity === null ? null : positionQuantity - quantity;\n\tconst probability = rangeProbability(boundaries);\n\tconst gross = mulDown(probability, quantity);\n\tconst fee = min(tradingFee(inputs.fees, boundaries, quantity, ttl), gross);\n\tconst builder = min(builderFee(fee, quantity, inputs.builderCode ?? false), gross - fee);\n\tconst penalty = min(mulDown(inputs.penaltyRate ?? 0n, quantity), gross - fee - builder);\n\tconst rebate = inputs.book ? closeInventoryImpact(inputs.fees, inputs.book, quantity) : 0n;\n\tconst proceeds = gross + rebate - fee - builder - penalty;\n\n\treturn {\n\t\tproceeds: fromRaw(proceeds, 6),\n\t\tgross: fromRaw(gross, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(fee, 6),\n\t\t\tbuilder: fromRaw(builder, 6),\n\t\t\tpenalty: fromRaw(penalty, 6),\n\t\t\timpactRebate: fromRaw(rebate, 6),\n\t\t},\n\t\tquantityClosed: fromRaw(quantity, 6),\n\t\tremainingQuantity: remainingQuantity === null ? null : fromRaw(remainingQuantity, 6),\n\t\tproceedsPerContract: Number(proceeds) / Number(quantity),\n\t\tprobability: fromRaw(probability, 9),\n\t\traw: {\n\t\t\tproceeds,\n\t\t\tgross,\n\t\t\ttradingFee: fee,\n\t\t\tbuilderFee: builder,\n\t\t\tpenaltyFee: penalty,\n\t\t\timpactRebate: rebate,\n\t\t\tquantityClosed: quantity,\n\t\t\tremainingQuantity,\n\t\t\tprobability,\n\t\t},\n\t\texactProbabilities: exact,\n\t};\n}\n\n// === Order IDs ===\n\nconst QUANTITY_LOTS_OFFSET = 100n;\nconst LOWER_TICK_OFFSET = 70n;\nconst HIGHER_TICK_OFFSET = 40n;\nconst TICK_MASK = POS_INF_TICK; // `constants::pos_inf_tick` is the full 30-bit mask\n/** `constants::pos_inf_tick` — the +∞ sentinel in an order's higher-tick field. */\nexport { POS_INF_TICK };\nconst U32_MASK = (1n << 32n) - 1n;\n\n/** The contract terms packed into an order ID (`deepbook_predict::order`). Tick `0` as the\n * lower bound is −∞ and {@link POS_INF_TICK} as the higher is +∞; multiply a finite tick by\n * the market's `tickSize` for its raw strike. Use it to feed a position from `read.positions`\n * into {@link redeemLiveProceeds}. */\nexport interface OrderRange {\n\tlowerTick: bigint;\n\thigherTick: bigint;\n\t/** Minted payout: `quantity_lots · position_lot_size`. */\n\tquantity: bigint;\n}\n\n/** Decode an order ID's range and quantity — the TypeScript mirror of `order::lower_tick` /\n * `higher_tick` / `quantity`. */\nexport function decodeOrderRange(orderId: bigint, lotSize: bigint = POSITION_LOT_SIZE): OrderRange {\n\treturn {\n\t\tlowerTick: (orderId >> LOWER_TICK_OFFSET) & TICK_MASK,\n\t\thigherTick: (orderId >> HIGHER_TICK_OFFSET) & TICK_MASK,\n\t\tquantity: ((orderId >> QUANTITY_LOTS_OFFSET) & U32_MASK) * lotSize,\n\t};\n}\n\n/**\n * What an order pays at settlement, raw USDC: its full quantity when the settlement price lies\n * in `(lower, higher]`, else 0. The mirror of `strike_exposure::settled_order_payout`, which\n * rounds the settlement price up to the market's tick grid (`range_codec::limit_tick`) before\n * comparing it with the order's ticks, so a price inside a tick counts as that tick's upper edge.\n * Pass `read.settlement`'s `settlementPriceRaw` and `tickSizeRaw`, and the config's\n * `units.positionLotSize` when it isn't the default.\n */\nexport function settledPayout(\n\torderId: bigint,\n\tsettlementPriceRaw: bigint,\n\ttickSizeRaw: bigint,\n\tlotSize: bigint = POSITION_LOT_SIZE,\n): bigint {\n\tif (tickSizeRaw <= 0n) throw new PredictInputError('tickSizeRaw must be positive');\n\tconst { lowerTick, higherTick, quantity } = decodeOrderRange(orderId, lotSize);\n\tconst limit = (settlementPriceRaw + tickSizeRaw - 1n) / tickSizeRaw;\n\tconst inRange = lowerTick < limit && (higherTick === POS_INF_TICK || limit <= higherTick);\n\treturn inRange ? quantity : 0n;\n}\n\n/** The strikes an {@link OrderRange} prices against, in USD, with `null` for each infinite\n * side — the shape {@link boundaryProbabilities} takes. `tickSize` is the market's raw tick\n * size (`ActiveMarket.tickSize` in USD, or the raw value from the deployment). */\nexport function orderStrikes(\n\trange: OrderRange,\n\ttickSizeRaw: bigint,\n): { lower: number | null; upper: number | null } {\n\treturn {\n\t\tlower: range.lowerTick === 0n ? null : fromRaw(range.lowerTick * tickSizeRaw, 9),\n\t\tupper: range.higherTick === POS_INF_TICK ? null : fromRaw(range.higherTick * tickSizeRaw, 9),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,gBAAgB;;AAE7B,MAAa,oBAAoB;;AAEjC,MAAa,cAAc;;AAE3B,MAAa,yBAAyB;;AAEtC,MAAa,uBAAuB;;;;;;;;;AASpC,MAAa,6BAA6B;;AAE1C,MAAa,qBAAqB,MAAM,OAAO;AAI/C,MAAM,WAAW,GAAW,MAAuB,IAAI,IAAK;AAC5D,MAAM,WAAW,GAAW,MAAuB,IAAI,gBAAiB;AACxE,MAAM,cAAc,GAAW,GAAW,gBAAiC,IAAI,IAAK;AACpF,MAAM,OAAO,GAAW,MAAuB,IAAI,IAAI,IAAI;AAC3D,MAAM,OAAO,GAAW,MAAuB,IAAI,IAAI,IAAI;AAG3D,SAAS,WAAW,OAAe,MAAc,UAAU,SAAS,UAAU,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C,mBAAmB,sBAAsB,OAAO,OAAO,QAAQ,mBAAmB,EAAE;EACpF,qBAAqB,OAAO,SAAS,GAAG,OAAO,SAAS;EACxD,aAAa,QAAQ,aAAa,EAAE;EACpC,KAAK;GACJ;GACA;GACA,YAAY;GACZ,YAAY;GACZ,YAAY;GACZ,cAAc;GACd,gBAAgB;GAChB;GACA;GACA;EACD,oBAAoB;EACpB;;AAKF,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,YAAY;AAGlB,MAAM,YAAY,MAAM,OAAO;;;AAe/B,SAAgB,iBAAiB,SAAiB,UAAkB,mBAA+B;AAClG,QAAO;EACN,WAAY,WAAW,oBAAqB;EAC5C,YAAa,WAAW,qBAAsB;EAC9C,WAAY,WAAW,uBAAwB,YAAY;EAC3D;;;;;;;;;;AAWF,SAAgB,cACf,SACA,oBACA,aACA,UAAkB,mBACT;AACT,KAAI,eAAe,GAAI,OAAM,IAAI,kBAAkB,+BAA+B;CAClF,MAAM,EAAE,WAAW,YAAY,aAAa,iBAAiB,SAAS,QAAQ;CAC9E,MAAM,SAAS,qBAAqB,cAAc,MAAM;AAExD,QADgB,YAAY,UAAU,eAAe,gBAAgB,SAAS,cAC7D,WAAW;;;;;AAM7B,SAAgB,aACf,OACA,aACiD;AACjD,QAAO;EACN,OAAO,MAAM,cAAc,KAAK,OAAO,QAAQ,MAAM,YAAY,aAAa,EAAE;EAChF,OAAO,MAAM,eAAe,eAAe,OAAO,QAAQ,MAAM,aAAa,aAAa,EAAE;EAC5F"}
1
+ {"version":3,"file":"cost.mjs","names":["quantity"],"sources":["../../src/predict/cost.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Client-side ALL-IN cost math for Predict trades — the fee layer `pricing.ts` stops short of.\n// `pricing.*` answers \"what is this contract worth?\" (the probability); this module answers\n// \"what does the chain debit me for it?\" and \"what does closing it credit me?\", with NO chain\n// call: no `devInspect`, no dry run, no simulate.\n//\n// It is an EXACT integer port of the deployed cost path, function for function:\n//\n// mint `expiry_market::mint_quote_at` / `compute_mint_quote`\n// -> premium + (trading_fee - fee_incentive_subsidy) + builder_fee + penalty_fee\n// + inventory_impact_charge\n// budget `expiry_market::quote_exact_cost_terms` (the `mint_exact_cost` lot search)\n// redeem `expiry_market::redeem_live`'s payment decomposition\n// -> gross + inventory_impact_rebate - trading_fee - builder_fee - penalty\n// fees `strike_exposure_config::trading_fee` (per-boundary Bernoulli fee + expiry ramp),\n// `expiry_market::builder_fee_amount`, `ewma::penalty_fee`,\n// `strike_exposure::mint_range_inventory_impact` / `live_close_inventory_impact`\n//\n// Every rounding step is the chain's: `mul_down`, `mul_div_down` and a bit-identical\n// `sqrt_down` (same Newton schedule as `fixed_math::math`), all on bigints. So given the same\n// inputs the chain uses, these return the chain's numbers to the raw unit — the fee layer\n// carries no approximation of its own.\n//\n// Local float probabilities (`pricing.upProbability`, ~1e-4) introduce approximation.\n// With raw probabilities AND the same fee, account, book and clock inputs as execution,\n// the arithmetic matches the chain. `exactProbabilities` only identifies the probability\n// input format; it does not certify the source or freshness of any state. A nonzero\n// inventory-impact policy requires book data. Congestion defaults to a zero rate; supply\n// the actual rate when enabled. Use `read.quoteMint` / `read.quoteRedeem` for a simulation\n// against current account and market state, including the execution gates these previews\n// do not check (ownership, pauses, trade window, oracle freshness and cash backing).\n//\n// The fee POLICY is a per-market snapshot taken at creation (`StrikeExposureConfig`). The\n// chain exposes no getter for `base_fee`/`min_fee`, so `read.feePolicy(market)` decodes it from\n// the `ExpiryMarket` object. The market's `MarketCreated` event carries it too.\n\nimport { PredictInputError } from './errors.js';\nimport type { PricerInputs } from './pricing.js';\nimport { upProbability } from './pricing.js';\nimport { POS_INF_TICK } from './ticks.js';\nimport { fromRaw, U64_MAX, usdcToRaw } from './units.js';\n\n// === Protocol constants (mirrors of `deepbook_predict::constants` / `fixed_math::math`) ===\n\n/** `math::float_scaling` — 1e9 is 1.0 for every rate and probability here. */\nexport const FLOAT_SCALING = 1_000_000_000n;\n/** `constants::position_lot_size` — quantity is an integer number of these. */\nexport const POSITION_LOT_SIZE = 10_000n;\n/** `constants::min_premium` — a mint below this premium aborts `EPremiumBelowMinimum`. */\nexport const MIN_PREMIUM = 1_000_000n;\n/** `constants::builder_fee_multiplier` — the builder's cut of the trading fee (10%). */\nexport const BUILDER_FEE_MULTIPLIER = 100_000_000n;\n/** `constants::max_builder_fee_rate` — cap on the builder fee as a share of quantity (0.5%). */\nexport const MAX_BUILDER_FEE_RATE = 5_000_000n;\n/**\n * The default sponsor share of a trader's mint fee (20%), and the rate the chain reads while the\n * admin hasn't set one.\n * @deprecated From delayed execution (DBU-885) the rate is admin-set: read it with\n * `protocol_config::fee_incentive_subsidy_rate` (`read.queue(...).protocol.feeIncentiveSubsidyRate`)\n * and pass it as `feeIncentiveSubsidyRate`. A hardcoded 20% underquotes every mint once the rate\n * moves.\n */\nexport const FEE_INCENTIVE_SUBSIDY_RATE = 200_000_000n;\n/** `order::max_quantity_lots` — the order ID's 32-bit lot field. */\nexport const MAX_QUANTITY_LOTS = (1n << 32n) - 1n;\n\n// === Fixed-point primitives (mirrors of `fixed_math::math`) ===\n\nconst mulDown = (x: bigint, y: bigint): bigint => (x * y) / FLOAT_SCALING;\nconst divDown = (x: bigint, y: bigint): bigint => (x * FLOAT_SCALING) / y;\nconst mulDivDown = (x: bigint, y: bigint, denominator: bigint): bigint => (x * y) / denominator;\nconst min = (a: bigint, b: bigint): bigint => (a < b ? a : b);\nconst max = (a: bigint, b: bigint): bigint => (a > b ? a : b);\n\n// Move's unsigned types enforce these domains before arithmetic. JS bigint does not.\nfunction assertUint(value: bigint, name: string, maximum = U64_MAX, minimum = 0n): void {\n\tif (typeof value !== 'bigint' || value < minimum || value > maximum) {\n\t\tthrow new PredictInputError(\n\t\t\t`${name} must be an integer in [${minimum}, ${maximum}], got ${value}`,\n\t\t);\n\t}\n}\n\n// `math::sqrt_initial_guess_u128` — power-of-two seed for the Newton iteration.\nfunction sqrtInitialGuess(x: bigint): bigint {\n\tlet bits = 0n;\n\tlet val = x;\n\tif (val >= 1n << 64n) {\n\t\tval >>= 64n;\n\t\tbits += 64n;\n\t}\n\tif (val >= 1n << 32n) {\n\t\tval >>= 32n;\n\t\tbits += 32n;\n\t}\n\tif (val >= 1n << 16n) {\n\t\tval >>= 16n;\n\t\tbits += 16n;\n\t}\n\tif (val >= 1n << 8n) {\n\t\tval >>= 8n;\n\t\tbits += 8n;\n\t}\n\tif (val >= 1n << 4n) {\n\t\tval >>= 4n;\n\t\tbits += 4n;\n\t}\n\tif (val >= 1n << 2n) {\n\t\tval >>= 2n;\n\t\tbits += 2n;\n\t}\n\tif (val >= 1n << 1n) bits += 1n;\n\treturn 1n << ((bits + 1n) / 2n);\n}\n\n// `math::sqrt_u128_down` — seven Newton steps then one correcting decrement, exactly as the\n// chain runs them, so this agrees with the contract raw unit for raw unit rather than merely\n// to within a rounding step.\nfunction sqrtU128Down(x: bigint): bigint {\n\tif (x === 0n) return 0n;\n\tif (x < 4n) return 1n;\n\tlet g = sqrtInitialGuess(x);\n\tfor (let i = 0; i < 7; i++) g = (g + x / g) / 2n;\n\tif (g > x / g) g -= 1n;\n\treturn g;\n}\n\n/** `math::sqrt_down` — square root of a 1e9-scaled value, 1e9-scaled, rounded down. */\nexport function sqrtDown(x: bigint): bigint {\n\tassertUint(x, 'sqrt input');\n\treturn sqrtU128Down(x * FLOAT_SCALING);\n}\n\n// === Policy and state inputs ===\n\n/**\n * One market's fee policy: the `StrikeExposureConfig` it snapshotted at creation, in raw 1e9\n * rates. Snapshotted means later admin changes do NOT reprice a market already trading, so\n * read it per market with `read.feePolicy(market)` (the `MarketCreated` event carries every field\n * too) rather than assuming the template. The last three are the inventory-impact parameters, inert while\n * `inventoryImpactMaxRate` is `0n` (the shipped value).\n */\nexport interface FeePolicy {\n\t/** `base_fee` — multiplies `sqrt(p·(1−p))`. */\n\tbaseFee: bigint;\n\t/** `min_fee` — per-unit floor, applied per boundary leg before the ramp. */\n\tminFee: bigint;\n\t/** `expiry_fee_window_ms` — window before expiry over which the fee ramps. */\n\texpiryFeeWindowMs: bigint;\n\t/** `expiry_fee_max_multiplier` — multiplier reached at expiry; 1e9 disables the ramp. */\n\texpiryFeeMaxMultiplier: bigint;\n\t/** `min_entry_probability` — mint admission floor on the entry probability. */\n\tminEntryProbability: bigint;\n\t/** `max_entry_probability` — mint admission ceiling on the entry probability. */\n\tmaxEntryProbability: bigint;\n\t/** `inventory_impact_max_rate` — maximum marginal impact rate; `0n` disables impact. */\n\tinventoryImpactMaxRate: bigint;\n\t/** `inventory_impact_scale` — the market's `max_expiry_allocation`, the curve's `B`. */\n\tinventoryImpactScale: bigint;\n\t/** `backing_buffer_lambda` — the buffer on non-peak payout in the liability formula. */\n\tbackingBufferLambda: bigint;\n}\n\n/**\n * The shipped template (`config_constants` defaults): 10% Bernoulli fee, a 2.2% per-leg floor,\n * a one-day ramp window that is inert at a 1.0 multiplier, a 1%–99% entry band, and inventory\n * impact disabled. Neither recorded deployment's template matches it any more: both charge a\n * 20.4% Bernoulli fee, ramp it to 3× over the last 60 s and admit entries in 25%–75% (checked\n * 2026-10-09), so a live market's costs from this policy come out low. Pass\n * `read.feePolicy(market)` instead. This stays for tests and for a deployment still on the\n * defaults.\n */\nexport const SHIPPED_FEE_POLICY: FeePolicy = Object.freeze({\n\tbaseFee: 100_000_000n,\n\tminFee: 22_000_000n,\n\texpiryFeeWindowMs: 86_400_000n,\n\texpiryFeeMaxMultiplier: FLOAT_SCALING,\n\tminEntryProbability: 10_000_000n,\n\tmaxEntryProbability: 990_000_000n,\n\tinventoryImpactMaxRate: 0n,\n\tinventoryImpactScale: 0n,\n\tbackingBufferLambda: 310_000_000n,\n});\n\n/** A range's two boundary UP probabilities, raw 1e9. `null` is an infinite boundary — the\n * −∞ lower of a DOWN order and the +∞ higher of an UP order — which is priced at the digital\n * limit and pays no fee leg. */\nexport interface Boundaries {\n\t/** `P(settle > lower)`, or `null` for the −∞ lower bound. */\n\tlowerUp: bigint | null;\n\t/** `P(settle > higher)`, or `null` for the +∞ higher bound. */\n\thigherUp: bigint | null;\n}\n\n/** Where a quote's probabilities come from: boundary probabilities you already hold (raw 1e9,\n * e.g. `probabilityToRaw((await read.price(...)).up)`) or a local pricer snapshot plus\n * the range's strikes in USD (`null` for an infinite side). */\nexport type ProbabilitySource =\n\tBoundaries | { pricer: PricerInputs; lower: number | null; upper: number | null };\n\n/** The market's gas-price EWMA (`ewma::EwmaState`), both fields 1e9-scaled. */\nexport interface CongestionState {\n\tmean: bigint;\n\tvariance: bigint;\n}\n\n/** The protocol's congestion knobs (`EwmaConfig`). Shipped disabled. */\nexport interface CongestionPolicy {\n\tenabled: boolean;\n\t/** `penalty_rate` — per-unit surcharge charged when the z-score fires. */\n\tpenaltyRate: bigint;\n\t/** `z_score_threshold` — how many standard deviations above the mean gas must sit. */\n\tzScoreThreshold: bigint;\n}\n\n/** Pre-trade payout-tree reads a mint's inventory-impact charge is evaluated against\n * (`strike_exposure::quote_mint_range`). All in quote units. */\nexport interface MintBookTerms {\n\t/** `M` — largest summed net payout at any one settlement price. */\n\tmaxPayout: bigint;\n\t/** `T` — sum of every live order's payout. */\n\ttotalPayout: bigint;\n\t/** The payout peak inside the mint's own `(lower, higher]`. */\n\trangeMaxPayout: bigint;\n}\n\n/** The same reads for a live close, which also needs the peak OUTSIDE the order's range\n * (`strike_exposure::live_close_inventory_impact`). */\nexport interface CloseBookTerms extends MintBookTerms {\n\t/** The payout peak in the complement of the order's range. */\n\tcomplementMaxPayout: bigint;\n}\n\nfunction assertFeePolicy(policy: FeePolicy): void {\n\tassertUint(policy.baseFee, 'baseFee', FLOAT_SCALING);\n\tassertUint(policy.minFee, 'minFee', FLOAT_SCALING);\n\tassertUint(policy.expiryFeeWindowMs, 'expiryFeeWindowMs', U64_MAX, 1n);\n\tassertUint(\n\t\tpolicy.expiryFeeMaxMultiplier,\n\t\t'expiryFeeMaxMultiplier',\n\t\t10n * FLOAT_SCALING,\n\t\tFLOAT_SCALING,\n\t);\n\tassertUint(policy.minEntryProbability, 'minEntryProbability', FLOAT_SCALING);\n\tassertUint(policy.maxEntryProbability, 'maxEntryProbability', FLOAT_SCALING);\n\tif (policy.minEntryProbability >= policy.maxEntryProbability) {\n\t\tthrow new PredictInputError('minEntryProbability must be below maxEntryProbability');\n\t}\n\tassertUint(policy.inventoryImpactMaxRate, 'inventoryImpactMaxRate', FLOAT_SCALING);\n\tassertUint(policy.backingBufferLambda, 'backingBufferLambda', FLOAT_SCALING);\n\tassertUint(\n\t\tpolicy.inventoryImpactScale,\n\t\t'inventoryImpactScale',\n\t\tU64_MAX,\n\t\tpolicy.inventoryImpactMaxRate === 0n ? 0n : 1n,\n\t);\n}\n\nfunction assertBoundaries(boundaries: Boundaries): void {\n\tif (boundaries.lowerUp !== null) assertUint(boundaries.lowerUp, 'lowerUp', FLOAT_SCALING);\n\tif (boundaries.higherUp !== null) assertUint(boundaries.higherUp, 'higherUp', FLOAT_SCALING);\n}\n\nfunction assertBook(book: MintBookTerms): void {\n\tassertUint(book.totalPayout, 'totalPayout');\n\tassertUint(book.maxPayout, 'maxPayout', book.totalPayout);\n\tassertUint(book.rangeMaxPayout, 'rangeMaxPayout', book.maxPayout);\n}\n\nfunction assertCostInputs(\n\tinputs: Pick<MintInputsBase, 'fees' | 'book' | 'penaltyRate' | 'lotSize'>,\n): void {\n\tassertFeePolicy(inputs.fees);\n\tassertUint(inputs.penaltyRate ?? 0n, 'penaltyRate', FLOAT_SCALING);\n\tassertUint(inputs.lotSize ?? POSITION_LOT_SIZE, 'lotSize', U64_MAX / MAX_QUANTITY_LOTS, 1n);\n\tif (inputs.fees.inventoryImpactMaxRate > 0n && !inputs.book) {\n\t\tthrow new PredictInputError('book is required when inventory impact is enabled');\n\t}\n\tif (inputs.book) assertBook(inputs.book);\n}\n\n// === Fee components ===\n\n/** `strike_exposure_config::raw_bernoulli_fee_rate` — `base_fee · sqrt(p·(1−p))`, the fee rate\n * before the `min_fee` floor and the expiry ramp. Zero at the certain ends. */\nexport function bernoulliFeeRate(baseFee: bigint, probability: bigint): bigint {\n\tassertUint(baseFee, 'baseFee', FLOAT_SCALING);\n\tassertUint(probability, 'probability (EInvalidFeeProbability)', FLOAT_SCALING);\n\tif (probability === 0n || probability === FLOAT_SCALING) return 0n;\n\treturn mulDown(baseFee, sqrtDown(mulDown(probability, FLOAT_SCALING - probability)));\n}\n\n/** `strike_exposure_config::expiry_fee_multiplier` — 1.0 outside the window, rising linearly\n * to `expiry_fee_max_multiplier` at expiry. */\nexport function expiryFeeMultiplier(policy: FeePolicy, timeToExpiryMs: bigint): bigint {\n\tassertFeePolicy(policy);\n\tassertUint(timeToExpiryMs, 'timeToExpiryMs');\n\tif (timeToExpiryMs >= policy.expiryFeeWindowMs) return FLOAT_SCALING;\n\treturn (\n\t\tFLOAT_SCALING +\n\t\tmulDivDown(\n\t\t\tpolicy.expiryFeeMaxMultiplier - FLOAT_SCALING,\n\t\t\tpolicy.expiryFeeWindowMs - timeToExpiryMs,\n\t\t\tpolicy.expiryFeeWindowMs,\n\t\t)\n\t);\n}\n\n// `strike_exposure_config::leg_trading_fee` — one finite boundary's fee, floored then ramped,\n// rounded down at each step.\nfunction legTradingFee(\n\tpolicy: FeePolicy,\n\tprobability: bigint,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): bigint {\n\tconst base = max(bernoulliFeeRate(policy.baseFee, probability), policy.minFee);\n\treturn mulDown(mulDown(base, expiryFeeMultiplier(policy, timeToExpiryMs)), quantity);\n}\n\n/**\n * `strike_exposure_config::trading_fee` — the fee for a whole range, charged PER FINITE\n * BOUNDARY with each leg floored and ramped independently. A binary order has one finite\n * boundary and pays one leg; a two-sided range pays two, so it is not the same fee as the\n * range's own probability would suggest.\n */\nexport function tradingFee(\n\tpolicy: FeePolicy,\n\tboundaries: Boundaries,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBoundaries(boundaries);\n\tassertUint(quantity, 'quantity');\n\tassertUint(timeToExpiryMs, 'timeToExpiryMs');\n\tconst lower =\n\t\tboundaries.lowerUp === null\n\t\t\t? 0n\n\t\t\t: legTradingFee(policy, boundaries.lowerUp, quantity, timeToExpiryMs);\n\tconst higher =\n\t\tboundaries.higherUp === null\n\t\t\t? 0n\n\t\t\t: legTradingFee(policy, boundaries.higherUp, quantity, timeToExpiryMs);\n\treturn lower + higher;\n}\n\n/** `expiry_market::builder_fee_amount` — an account carrying a builder code pays the builder a\n * multiple of its trading fee, capped as a share of quantity. */\nexport function builderFee(fee: bigint, quantity: bigint, hasBuilderCode: boolean): bigint {\n\tassertUint(fee, 'fee');\n\tassertUint(quantity, 'quantity');\n\tif (!hasBuilderCode) return 0n;\n\treturn min(mulDown(fee, BUILDER_FEE_MULTIPLIER), mulDown(quantity, MAX_BUILDER_FEE_RATE));\n}\n\n/** `expiry_market::fee_incentive_subsidy_amount` — a sponsor pays part of the trader's MINT\n * fee, bounded by the expiry's remaining sponsored balance. Mints only; redeems pay in full.\n * `rate` is the protocol's `fee_incentive_subsidy_rate` (1e9-scaled), 20% when omitted. */\nexport function feeIncentiveSubsidy(\n\tfee: bigint,\n\tfeeIncentiveBalance: bigint,\n\trate: bigint = FEE_INCENTIVE_SUBSIDY_RATE,\n): bigint {\n\tassertUint(fee, 'fee');\n\tassertUint(feeIncentiveBalance, 'feeIncentiveBalance');\n\tassertUint(rate, 'feeIncentiveSubsidyRate', FLOAT_SCALING);\n\treturn min(mulDown(fee, rate), feeIncentiveBalance);\n}\n\n/**\n * `ewma::penalty_fee`'s firing test, as a per-unit RATE: `penalty_rate` when the transaction's\n * gas price is a high outlier against the market's pre-trade EWMA, else zero. It is a rate and\n * not an amount because the surcharge is `rate · quantity`, and a budget search has to reprice\n * it at every candidate quantity. `gasPrice` is the raw reference gas price (not 1e9-scaled),\n * as `tx_context::gas_price` reports it.\n */\nexport function congestionPenaltyRate(\n\tpolicy: CongestionPolicy,\n\tstate: CongestionState,\n\tgasPrice: bigint,\n): bigint {\n\tassertUint(policy.penaltyRate, 'penaltyRate', FLOAT_SCALING);\n\tassertUint(policy.zScoreThreshold, 'zScoreThreshold');\n\tassertUint(state.mean, 'mean');\n\tassertUint(state.variance, 'variance');\n\tassertUint(gasPrice, 'gasPrice', U64_MAX / FLOAT_SCALING);\n\tif (!policy.enabled || state.variance === 0n) return 0n;\n\tconst scaled = gasPrice * FLOAT_SCALING;\n\tif (scaled <= state.mean) return 0n;\n\tconst zScore = divDown(scaled - state.mean, sqrtDown(state.variance));\n\tif (zScore <= policy.zScoreThreshold) return 0n;\n\treturn policy.penaltyRate;\n}\n\n// `strike_exposure::live_payout_liability_from_terms` — `M + lambda·(T − M)`.\nfunction payoutLiability(policy: FeePolicy, maxPayout: bigint, totalPayout: bigint): bigint {\n\treturn maxPayout + mulDown(policy.backingBufferLambda, totalPayout - maxPayout);\n}\n\n/**\n * `strike_exposure::inventory_impact_potential_for_liability` — the book-level potential\n * `phi(L)`: marginal rate rising linearly to `inventory_impact_max_rate` over the scale `B`,\n * flat at the cap above it. Trades are charged the DIFFERENCE of two evaluations, which is\n * what makes inventory cycles telescope to zero.\n */\nexport function inventoryImpactPotential(policy: FeePolicy, liability: bigint): bigint {\n\tassertFeePolicy(policy);\n\tassertUint(liability, 'liability');\n\tif (policy.inventoryImpactMaxRate === 0n || liability === 0n) return 0n;\n\tconst scale = policy.inventoryImpactScale;\n\tconst capped = min(liability, scale);\n\tconst utilization = mulDivDown(capped, FLOAT_SCALING, scale);\n\tconst marginalRate = mulDown(policy.inventoryImpactMaxRate, utilization);\n\tconst potentialAtCapped = mulDown(marginalRate, capped) / 2n;\n\tif (liability <= scale) return potentialAtCapped;\n\treturn potentialAtCapped + mulDown(policy.inventoryImpactMaxRate, liability - scale);\n}\n\n/** `strike_exposure::mint_range_inventory_impact` — the charge a mint of `quantity` over a\n * range pays: the exact rise in the book potential. Zero at the shipped rate of `0n`. */\nexport function mintInventoryImpact(\n\tpolicy: FeePolicy,\n\tbook: MintBookTerms,\n\tquantity: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBook(book);\n\tassertUint(quantity, 'quantity', U64_MAX - book.totalPayout);\n\tif (policy.inventoryImpactMaxRate === 0n || quantity === 0n) return 0n;\n\tconst before = payoutLiability(policy, book.maxPayout, book.totalPayout);\n\tconst after = payoutLiability(\n\t\tpolicy,\n\t\tmax(book.maxPayout, book.rangeMaxPayout + quantity),\n\t\tbook.totalPayout + quantity,\n\t);\n\treturn inventoryImpactPotential(policy, after) - inventoryImpactPotential(policy, before);\n}\n\n/** `strike_exposure::live_close_inventory_impact` — the rebate a live close of `payout`\n * receives: the exact fall in the same potential. Zero at the shipped rate of `0n`. */\nexport function closeInventoryImpact(\n\tpolicy: FeePolicy,\n\tbook: CloseBookTerms,\n\tpayout: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBook(book);\n\tassertUint(book.complementMaxPayout, 'complementMaxPayout', book.maxPayout);\n\tif (max(book.rangeMaxPayout, book.complementMaxPayout) !== book.maxPayout) {\n\t\tthrow new PredictInputError('maxPayout must equal the larger range or complement payout');\n\t}\n\tassertUint(payout, 'close payout', book.rangeMaxPayout);\n\tif (policy.inventoryImpactMaxRate === 0n || payout === 0n) return 0n;\n\tconst before = payoutLiability(policy, book.maxPayout, book.totalPayout);\n\tconst after = payoutLiability(\n\t\tpolicy,\n\t\tmax(book.rangeMaxPayout - payout, book.complementMaxPayout),\n\t\tbook.totalPayout - payout,\n\t);\n\treturn inventoryImpactPotential(policy, before) - inventoryImpactPotential(policy, after);\n}\n\n// === Probabilities ===\n\n/** `pricing::probability` — the range's own probability, `up(lower) − up(higher)` with the\n * chain's saturating subtraction and its infinite-boundary defaults. */\nexport function rangeProbability(boundaries: Boundaries): bigint {\n\tassertBoundaries(boundaries);\n\tconst lower = boundaries.lowerUp ?? FLOAT_SCALING;\n\tconst higher = boundaries.higherUp ?? 0n;\n\treturn lower > higher ? lower - higher : 0n;\n}\n\n// Float probability -> the chain's raw 1e9 domain, clamped like `compute_nd2`'s own clamp.\nfunction toRawProbability(p: number): bigint {\n\tif (!Number.isFinite(p)) throw new PredictInputError(`probability is not finite: ${p}`);\n\tconst raw = BigInt(Math.round(p * Number(FLOAT_SCALING)));\n\treturn raw < 0n ? 0n : raw > FLOAT_SCALING ? FLOAT_SCALING : raw;\n}\n\n/** Price a range's two boundaries with the local float pricer. `lower`/`upper` are strikes in\n * USD; pass `null` for an infinite side (`{ lower: strike, upper: null }` is an UP order,\n * `{ lower: null, upper: strike }` a DOWN order). Carries the pricer's ~1e-4 approximation. */\nexport function boundaryProbabilities(\n\tpricer: PricerInputs,\n\tlower: number | null,\n\tupper: number | null,\n): Boundaries {\n\treturn {\n\t\tlowerUp: lower === null ? null : toRawProbability(upProbability(pricer, lower)),\n\t\thigherUp: upper === null ? null : toRawProbability(upProbability(pricer, upper)),\n\t};\n}\n\nfunction resolveBoundaries(source: ProbabilitySource): { boundaries: Boundaries; exact: boolean } {\n\tlet boundaries: Boundaries;\n\tlet exact: boolean;\n\tif ('pricer' in source) {\n\t\tconst { lower, upper } = source;\n\t\tif (lower !== null && upper !== null && lower >= upper) {\n\t\t\tthrow new PredictInputError(`lower strike ${lower} must be below ${upper} (EInvalidRange)`);\n\t\t}\n\t\tboundaries = boundaryProbabilities(source.pricer, lower, upper);\n\t\texact = false;\n\t} else {\n\t\tboundaries = source;\n\t\texact = true;\n\t}\n\tassertBoundaries(boundaries);\n\t// `(-inf, +inf]` is the whole outcome space; `order::assert_valid_order_shape` rejects it.\n\tif (boundaries.lowerUp === null && boundaries.higherUp === null) {\n\t\tthrow new PredictInputError('a range cannot be infinite on both sides (EInvalidRange)');\n\t}\n\treturn { boundaries, exact };\n}\n\n// `number` is a human amount in USDC decimals, `bigint` is already raw — the SDK-wide\n// convention for every financial parameter.\nfunction rawAmount(value: number | bigint): bigint {\n\tconst raw = typeof value === 'bigint' ? value : usdcToRaw(value);\n\tassertUint(raw, 'amount');\n\treturn raw;\n}\n\nfunction rawMs(value: number | bigint): bigint {\n\tif (typeof value === 'number' && !Number.isSafeInteger(value)) {\n\t\tthrow new PredictInputError(`timestamp must be a safe integer in milliseconds, got ${value}`);\n\t}\n\tconst raw = typeof value === 'bigint' ? value : BigInt(value);\n\tassertUint(raw, 'timestamp');\n\treturn raw;\n}\n\n// === Mint ===\n\n/** Inputs shared by the exact-quantity mint quote and the budget-sized one. */\ninterface MintInputsBase {\n\t/** The market's snapshotted fee policy. */\n\tfees: FeePolicy;\n\t/** Market expiry, ms since epoch. */\n\texpiryMs: number | bigint;\n\t/** The clock the trade will price against, ms since epoch. Defaults to `Date.now()`. */\n\tnowMs?: number | bigint;\n\t/** Boundary probabilities, or a pricer snapshot plus the range's strikes. */\n\tprobabilities: ProbabilitySource;\n\t/**\n\t * Whether the minting account carries a builder code and pays the account-attached builder fee:\n\t * Predict v4 semantics. From Predict Version 5 an attached code charges nothing (a builder fee\n\t * is passed on each trade instead), so leave this `false` on a network running Version 5.\n\t */\n\tbuilderCode?: boolean;\n\t/** The expiry's remaining sponsored fee balance (`fee_incentive_balance`). Default `0n`. */\n\tfeeIncentiveBalance?: number | bigint;\n\t/**\n\t * The protocol's admin-set mint fee subsidy rate (`protocol_config::fee_incentive_subsidy_rate`),\n\t * 1e9-scaled. Defaults to the 20% the chain reads while unset.\n\t */\n\tfeeIncentiveSubsidyRate?: bigint;\n\t/**\n\t * Per-unit congestion surcharge rate — see {@link congestionPenaltyRate}. Default `0n`. A\n\t * queued (delayed-execution) fill pays no congestion penalty, so queued previews keep it 0.\n\t */\n\tpenaltyRate?: bigint;\n\t/** Pre-trade payout-tree terms. Required when inventory impact is enabled. */\n\tbook?: MintBookTerms;\n\t/** The deployment's `position_lot_size`. Defaults to the Move constant, `10_000n`. */\n\tlotSize?: bigint;\n}\n\n/** Inputs for {@link mintCost}: an exact payout quantity. */\nexport interface MintCostInputs extends MintInputsBase {\n\t/** Maximum payout bought, in quote units — `number` is human USD, `bigint` is raw. */\n\tquantity: number | bigint;\n}\n\n/** Inputs for {@link mintCostForBudget}: an all-in budget, the `mint_exact_cost` shape. */\nexport interface MintBudgetInputs extends MintInputsBase {\n\t/** The total to spend, fees included. */\n\tbudget: number | bigint;\n\t/** Floor on the fill; a smaller result aborts, as `mint_exact_cost` does. Default one lot. */\n\tminQuantity?: number | bigint;\n\t/** The account's settled USDC. The chain caps the budget at it before sizing; pass it to\n\t * reproduce that cap (and to let `U64_MAX` mean \"my whole balance\"). */\n\taccountBalance?: number | bigint;\n}\n\n/** One mint's cost decomposition — the fields of the chain's `MintQuote`, in human units with\n * the exact integers alongside. `cost` is the account debit. */\nexport interface MintCost {\n\t/** Maximum payout bought (human quote units). */\n\tquantity: number;\n\t/** Fill price, 0..1 per $1 of payout, before fees. */\n\tentryProbability: number;\n\t/** Premium into LP backing. */\n\tpremium: number;\n\t/** `referral` is not here: it is a split of protocol proceeds, not a trader debit. */\n\tfees: { trading: number; subsidy: number; builder: number; penalty: number; impact: number };\n\t/** All-in account debit: `premium + (trading − subsidy) + builder + penalty + impact`. */\n\tcost: number;\n\t/** All-in price per $1 of payout — `cost / quantity`, the number to compare across venues. */\n\tcostPerContract: number;\n\t/** Maximum payout divided by the all-in debit, including fees. */\n\tpayoutMultiple: number;\n\traw: {\n\t\tquantity: bigint;\n\t\tentryProbability: bigint;\n\t\tpremium: bigint;\n\t\ttradingFee: bigint;\n\t\tsubsidy: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\timpactCharge: bigint;\n\t\tcost: bigint;\n\t};\n\t/** True when boundary probabilities were supplied as raw integers rather than priced\n\t * locally in float. Does not verify their source, freshness or the other quote inputs. */\n\texactProbabilities: boolean;\n}\n\n/** Budget-sized mint plus the budget information needed to render an order preview. */\nexport interface MintBudgetCost extends Omit<MintCost, 'raw'> {\n\t/** Requested all-in budget, before the optional account-balance cap. */\n\tbudget: number;\n\t/** Budget after the optional account-balance cap. */\n\teffectiveBudget: number;\n\t/** Requested budget minus actual cost, including any balance-cap shortfall. */\n\tunspentBudget: number;\n\traw: MintCost['raw'] & {\n\t\tbudget: bigint;\n\t\teffectiveBudget: bigint;\n\t\tunspentBudget: bigint;\n\t};\n}\n\n// `strike_exposure_config::assert_mint_probability_policy`, applied where\n// `assert_range_mint_probability_policy` applies it: each finite leg and the range itself.\nfunction assertProbabilityPolicy(policy: FeePolicy, probability: bigint): void {\n\tif (probability < policy.minEntryProbability || probability > policy.maxEntryProbability) {\n\t\tthrow new PredictInputError(\n\t\t\t`entry probability ${probability} outside the market's [${policy.minEntryProbability}, ` +\n\t\t\t\t`${policy.maxEntryProbability}] admission band (EEntryProbabilityOutOfBounds)`,\n\t\t);\n\t}\n}\n\nfunction assertRangeMintPolicy(policy: FeePolicy, boundaries: Boundaries): void {\n\tif (boundaries.lowerUp !== null) assertProbabilityPolicy(policy, boundaries.lowerUp);\n\tif (boundaries.higherUp !== null) {\n\t\tassertProbabilityPolicy(policy, FLOAT_SCALING - boundaries.higherUp);\n\t}\n\tassertProbabilityPolicy(policy, rangeProbability(boundaries));\n}\n\nfunction assertValidQuantity(quantity: bigint, lotSize: bigint): void {\n\tif (quantity <= 0n || quantity % lotSize !== 0n || quantity / lotSize > MAX_QUANTITY_LOTS) {\n\t\tthrow new PredictInputError(\n\t\t\t`quantity ${quantity} must be a positive multiple of the ${lotSize} lot size, at most ` +\n\t\t\t\t`${MAX_QUANTITY_LOTS} lots (EInvalidQuantity)`,\n\t\t);\n\t}\n}\n\nfunction timeToExpiry(expiryMs: bigint, nowMs: bigint): bigint {\n\tif (nowMs >= expiryMs) {\n\t\tthrow new PredictInputError(\n\t\t\t`market expired at ${expiryMs}; a live trade at ${nowMs} aborts (ELivePricingExpired)`,\n\t\t);\n\t}\n\treturn expiryMs - nowMs;\n}\n\n// The all-in sum, `expiry_market::mint_quote_at`, with no admission checks — the one place the\n// cost is assembled, shared by the quote and the budget search exactly as the contract shares\n// it. Rounding order is the chain's: every component is floored before it is summed.\nfunction mintQuoteAt(\n\tinputs: MintInputsBase,\n\tboundaries: Boundaries,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): {\n\tpremium: bigint;\n\tfee: bigint;\n\tsubsidy: bigint;\n\tbuilder: bigint;\n\tpenalty: bigint;\n\timpact: bigint;\n\tcost: bigint;\n} {\n\tconst premium = mulDown(rangeProbability(boundaries), quantity);\n\tconst fee = tradingFee(inputs.fees, boundaries, quantity, timeToExpiryMs);\n\tconst subsidy = feeIncentiveSubsidy(\n\t\tfee,\n\t\trawAmount(inputs.feeIncentiveBalance ?? 0n),\n\t\tinputs.feeIncentiveSubsidyRate,\n\t);\n\tconst builder = builderFee(fee, quantity, inputs.builderCode ?? false);\n\tconst penalty = mulDown(inputs.penaltyRate ?? 0n, quantity);\n\tconst impact = inputs.book ? mintInventoryImpact(inputs.fees, inputs.book, quantity) : 0n;\n\treturn {\n\t\tpremium,\n\t\tfee,\n\t\tsubsidy,\n\t\tbuilder,\n\t\tpenalty,\n\t\timpact,\n\t\tcost: premium + (fee - subsidy) + builder + penalty + impact,\n\t};\n}\n\nfunction mintCostFrom(\n\tinputs: MintInputsBase,\n\tboundaries: Boundaries,\n\texact: boolean,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): MintCost {\n\tconst q = mintQuoteAt(inputs, boundaries, quantity, timeToExpiryMs);\n\tconst probability = rangeProbability(boundaries);\n\treturn {\n\t\tquantity: fromRaw(quantity, 6),\n\t\tentryProbability: fromRaw(probability, 9),\n\t\tpremium: fromRaw(q.premium, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(q.fee, 6),\n\t\t\tsubsidy: fromRaw(q.subsidy, 6),\n\t\t\tbuilder: fromRaw(q.builder, 6),\n\t\t\tpenalty: fromRaw(q.penalty, 6),\n\t\t\timpact: fromRaw(q.impact, 6),\n\t\t},\n\t\tcost: fromRaw(q.cost, 6),\n\t\tcostPerContract: quantity === 0n ? 0 : Number(q.cost) / Number(quantity),\n\t\tpayoutMultiple: Number(quantity) / Number(q.cost),\n\t\traw: {\n\t\t\tquantity,\n\t\t\tentryProbability: probability,\n\t\t\tpremium: q.premium,\n\t\t\ttradingFee: q.fee,\n\t\t\tsubsidy: q.subsidy,\n\t\t\tbuilderFee: q.builder,\n\t\t\tpenaltyFee: q.penalty,\n\t\t\timpactCharge: q.impact,\n\t\t\tcost: q.cost,\n\t\t},\n\t\texactProbabilities: exact,\n\t};\n}\n\n/**\n * All-in cost of minting an exact payout quantity — the `mint_exact_quantity` shape, priced\n * entirely client-side. Mirrors `compute_mint_quote`, including its admission checks: the\n * entry-probability band on each finite leg and on the range, the `min_premium` floor, the lot\n * grid, and the `all_in_cost <= quantity` bound (a contract may never cost more than it can\n * pay out). Each violation throws the `PredictInputError` naming the abort the chain would\n * have raised.\n */\nexport function mintCost(inputs: MintCostInputs): MintCost {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst quantity = rawAmount(inputs.quantity);\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\n\tassertRangeMintPolicy(inputs.fees, boundaries);\n\tconst premium = mulDown(rangeProbability(boundaries), quantity);\n\tif (premium < MIN_PREMIUM) {\n\t\tthrow new PredictInputError(\n\t\t\t`premium ${premium} is below the ${MIN_PREMIUM} minimum (EPremiumBelowMinimum)`,\n\t\t);\n\t}\n\tassertValidQuantity(quantity, lotSize);\n\n\tconst quote = mintCostFrom(inputs, boundaries, exact, quantity, ttl);\n\tif (quote.raw.cost > quantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`all-in cost ${quote.raw.cost} exceeds the maximum payout ${quantity} ` +\n\t\t\t\t`(EMintCostAboveMaxPayout)`,\n\t\t);\n\t}\n\treturn quote;\n}\n\n/**\n * A fill whose ALL-IN cost fits a budget — `expiry_market::mint_exact_cost` computed\n * client-side, with the same lot search over the same cost function, so the answer is the\n * quantity that entrypoint would size and the cost it would debit.\n *\n * Without it a \"spend exactly $X\" flow has to guess: every fee is charged ON TOP of the\n * premium, so the caller subtracts an estimated fee load, pads it against an abort, and\n * systematically underspends. Here the whole search runs locally; submit the all-in budget\n * through `tx.mintCost` on deployments carrying `mint_exact_cost`.\n *\n * Sizing also respects the fill's maximum payout and the 32-bit lot cap; either can leave\n * substantial budget unspent. When only the budget binds, one more lot would exceed it.\n * If the budget fill exceeds its maximum payout, the contract's step-down is best effort:\n * rounding can make it miss a larger admissible fill, including one meeting `minQuantity`.\n * The chain caps the budget at the account balance first ({@link MintBudgetInputs.accountBalance}).\n */\nexport function mintCostForBudget(inputs: MintBudgetInputs): MintBudgetCost {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\tconst minQuantity = inputs.minQuantity === undefined ? lotSize : rawAmount(inputs.minQuantity);\n\tconst requestedBudget = rawAmount(inputs.budget);\n\tlet budget = requestedBudget;\n\tif (inputs.accountBalance !== undefined) budget = min(budget, rawAmount(inputs.accountBalance));\n\n\tassertRangeMintPolicy(inputs.fees, boundaries);\n\n\t// `strike_exposure::max_quantity_for_premium` — the premium-only fit bounds the all-in\n\t// fit from above, because every other term is non-negative.\n\tconst probability = rangeProbability(boundaries);\n\tlet lo = 0n;\n\tlet hi = MAX_QUANTITY_LOTS;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi + 1n) / 2n;\n\t\tif (mulDown(probability, mid * lotSize) <= budget) lo = mid;\n\t\telse hi = mid - 1n;\n\t}\n\n\t// `expiry_market::quote_exact_cost_terms`, first half: the budget search proper. Exact,\n\t// because every all-in term is nondecreasing in quantity for fixed pre-trade state.\n\tconst allInCostAt = (quantity: bigint) => mintQuoteAt(inputs, boundaries, quantity, ttl).cost;\n\thi = lo;\n\tlo = 0n;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi + 1n) / 2n;\n\t\tif (allInCostAt(mid * lotSize) <= budget) lo = mid;\n\t\telse hi = mid - 1n;\n\t}\n\tconst budgetLots = lo;\n\tconst budgetQuantity = budgetLots * lotSize;\n\n\t// Second half: the maximum-payout bound (`cost <= quantity`) is deliberately NOT part of\n\t// that search. It is not monotone — cost and quantity both rise, and the independent floors\n\t// in each cost term let `cost(q) <= q` flip back to true at a larger lot wherever unit cost\n\t// sits within rounding of one — so binary-searching it would discard admissible fills. It is\n\t// consulted only when the budget fill breaches it, and the step-down runs strictly below\n\t// that fill, so every candidate already fits the budget.\n\t// This fallback mirrors Move's best-effort search; its nonmonotone predicate means it\n\t// can miss larger admissible fills, including one satisfying minQuantity.\n\tlet lots = budgetLots;\n\tif (budgetLots > 0n && allInCostAt(budgetQuantity) > budgetQuantity) {\n\t\tlet stepLo = 0n;\n\t\tlet stepHi = budgetLots - 1n;\n\t\twhile (stepLo < stepHi) {\n\t\t\tconst mid = (stepLo + stepHi + 1n) / 2n;\n\t\t\tconst candidate = mid * lotSize;\n\t\t\tif (allInCostAt(candidate) <= candidate) stepLo = mid;\n\t\t\telse stepHi = mid - 1n;\n\t\t}\n\t\t// No admissible smaller fill: fall back to the budget fill, which then fails the\n\t\t// maximum-payout bound below exactly as the chain's own quote aborts on it.\n\t\tlots = stepLo === 0n ? budgetLots : stepLo;\n\t}\n\n\tconst quantity = lots * lotSize;\n\tif (quantity < minQuantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`budget ${budget} sizes ${quantity}, below the ${minQuantity} minimum ` +\n\t\t\t\t`(EMintQuantityBelowMin)`,\n\t\t);\n\t}\n\tconst premium = mulDown(probability, quantity);\n\tif (premium < MIN_PREMIUM) {\n\t\tthrow new PredictInputError(\n\t\t\t`budget ${budget} sizes a premium of ${premium}, below the ${MIN_PREMIUM} minimum ` +\n\t\t\t\t`(EPremiumBelowMinimum)`,\n\t\t);\n\t}\n\tassertValidQuantity(quantity, lotSize);\n\tconst quote = mintCostFrom(inputs, boundaries, exact, quantity, ttl);\n\tif (quote.raw.cost > quantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`sized fill inside budget ${budget} costs more than it can pay out: ${quote.raw.cost} ` +\n\t\t\t\t`exceeds ${quantity} (EMintCostAboveMaxPayout)`,\n\t\t);\n\t}\n\treturn {\n\t\t...quote,\n\t\tbudget: fromRaw(requestedBudget, 6),\n\t\teffectiveBudget: fromRaw(budget, 6),\n\t\tunspentBudget: fromRaw(requestedBudget - quote.raw.cost, 6),\n\t\traw: {\n\t\t\t...quote.raw,\n\t\t\tbudget: requestedBudget,\n\t\t\teffectiveBudget: budget,\n\t\t\tunspentBudget: requestedBudget - quote.raw.cost,\n\t\t},\n\t};\n}\n\n// === Live redeem ===\n\n/** Inputs for {@link redeemLiveProceeds}. The range is the ORDER's own range — the same two\n * boundaries it was minted over, which is what `redeem_live` reprices. */\nexport interface RedeemLiveInputs {\n\tfees: FeePolicy;\n\texpiryMs: number | bigint;\n\tnowMs?: number | bigint;\n\t/** The order's boundary probabilities now, or a pricer snapshot plus the order's strikes. */\n\tprobabilities: ProbabilitySource;\n\t/** Payout being closed — the whole order, or part of it. */\n\tcloseQuantity: number | bigint;\n\t/** Current position payout quantity, when known. Validates the close and returns the remainder. */\n\tpositionQuantity?: number | bigint;\n\t/**\n\t * Whether the selling account pays the account-attached builder fee: Predict v4 semantics.\n\t * Leave it `false` on a network running Version 5, where an attached code charges nothing.\n\t */\n\tbuilderCode?: boolean;\n\tpenaltyRate?: bigint;\n\t/** Pre-trade payout-tree terms. Required when inventory impact is enabled. */\n\tbook?: CloseBookTerms;\n\tlotSize?: bigint;\n}\n\n/** What a live close credits the account, decomposed. */\nexport interface RedeemLiveProceeds {\n\t/** NET credited to the account. */\n\tproceeds: number;\n\t/** Close value before fees: the range's current probability times the closed payout. */\n\tgross: number;\n\tfees: { trading: number; builder: number; penalty: number; impactRebate: number };\n\tquantityClosed: number;\n\t/** Unclosed payout quantity, or null when positionQuantity was not supplied. */\n\tremainingQuantity: number | null;\n\t/** Net credited per $1 of closed payout; includes fees and the inventory rebate. */\n\tproceedsPerContract: number;\n\t/** Current range probability, 0..1, before amount rounding and fees. */\n\tprobability: number;\n\traw: {\n\t\tproceeds: bigint;\n\t\tgross: bigint;\n\t\ttradingFee: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\timpactRebate: bigint;\n\t\tquantityClosed: bigint;\n\t\tremainingQuantity: bigint | null;\n\t\t/** 1e9-scaled range probability; locally priced inputs remain approximate. */\n\t\tprobability: bigint;\n\t};\n\t/** Identifies raw probability inputs; does not verify their source or state freshness. */\n\texactProbabilities: boolean;\n}\n\n/**\n * Net proceeds of closing a live position — `expiry_market::redeem_live`'s payment\n * decomposition, client-side. The mirror of {@link mintCost}: the same per-boundary trading\n * fee and builder fee, the same congestion surcharge, and the inventory-impact term as a\n * REBATE rather than a charge. There is no sponsor subsidy on a close (incentives subsidise\n * mints only), and each deduction is clamped at the payout remaining after the ones before it,\n * exactly as the contract clamps them, so a close can never cost more than it releases.\n *\n * Use this for a local UI preview from a supplied snapshot. `read.quoteRedeem` simulates\n * the actual close and remains the pre-trade check for ownership, remaining position size,\n * live-market gates and current fees. `proceeds` is what `min_proceeds` is compared against\n * on the real call; this preview does not guarantee execution at that amount.\n */\nexport function redeemLiveProceeds(inputs: RedeemLiveInputs): RedeemLiveProceeds {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst quantity = rawAmount(inputs.closeQuantity);\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\tassertValidQuantity(quantity, lotSize);\n\n\tconst positionQuantity =\n\t\tinputs.positionQuantity === undefined ? null : rawAmount(inputs.positionQuantity);\n\tif (positionQuantity !== null) {\n\t\tassertValidQuantity(positionQuantity, lotSize);\n\t\tif (quantity > positionQuantity)\n\t\t\tthrow new PredictInputError('closeQuantity exceeds positionQuantity');\n\t}\n\tconst remainingQuantity = positionQuantity === null ? null : positionQuantity - quantity;\n\tconst probability = rangeProbability(boundaries);\n\tconst gross = mulDown(probability, quantity);\n\tconst fee = min(tradingFee(inputs.fees, boundaries, quantity, ttl), gross);\n\tconst builder = min(builderFee(fee, quantity, inputs.builderCode ?? false), gross - fee);\n\tconst penalty = min(mulDown(inputs.penaltyRate ?? 0n, quantity), gross - fee - builder);\n\tconst rebate = inputs.book ? closeInventoryImpact(inputs.fees, inputs.book, quantity) : 0n;\n\tconst proceeds = gross + rebate - fee - builder - penalty;\n\n\treturn {\n\t\tproceeds: fromRaw(proceeds, 6),\n\t\tgross: fromRaw(gross, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(fee, 6),\n\t\t\tbuilder: fromRaw(builder, 6),\n\t\t\tpenalty: fromRaw(penalty, 6),\n\t\t\timpactRebate: fromRaw(rebate, 6),\n\t\t},\n\t\tquantityClosed: fromRaw(quantity, 6),\n\t\tremainingQuantity: remainingQuantity === null ? null : fromRaw(remainingQuantity, 6),\n\t\tproceedsPerContract: Number(proceeds) / Number(quantity),\n\t\tprobability: fromRaw(probability, 9),\n\t\traw: {\n\t\t\tproceeds,\n\t\t\tgross,\n\t\t\ttradingFee: fee,\n\t\t\tbuilderFee: builder,\n\t\t\tpenaltyFee: penalty,\n\t\t\timpactRebate: rebate,\n\t\t\tquantityClosed: quantity,\n\t\t\tremainingQuantity,\n\t\t\tprobability,\n\t\t},\n\t\texactProbabilities: exact,\n\t};\n}\n\n// === Order IDs ===\n\nconst QUANTITY_LOTS_OFFSET = 100n;\nconst LOWER_TICK_OFFSET = 70n;\nconst HIGHER_TICK_OFFSET = 40n;\nconst TICK_MASK = POS_INF_TICK; // `constants::pos_inf_tick` is the full 30-bit mask\n/** `constants::pos_inf_tick` — the +∞ sentinel in an order's higher-tick field. */\nexport { POS_INF_TICK };\nconst U32_MASK = (1n << 32n) - 1n;\n\n/** The contract terms packed into an order ID (`deepbook_predict::order`). Tick `0` as the\n * lower bound is −∞ and {@link POS_INF_TICK} as the higher is +∞; multiply a finite tick by\n * the market's `tickSize` for its raw strike. Use it to feed a position from `read.positions`\n * into {@link redeemLiveProceeds}. */\nexport interface OrderRange {\n\tlowerTick: bigint;\n\thigherTick: bigint;\n\t/** Minted payout: `quantity_lots · position_lot_size`. */\n\tquantity: bigint;\n}\n\n/** Decode an order ID's range and quantity — the TypeScript mirror of `order::lower_tick` /\n * `higher_tick` / `quantity`. */\nexport function decodeOrderRange(orderId: bigint, lotSize: bigint = POSITION_LOT_SIZE): OrderRange {\n\treturn {\n\t\tlowerTick: (orderId >> LOWER_TICK_OFFSET) & TICK_MASK,\n\t\thigherTick: (orderId >> HIGHER_TICK_OFFSET) & TICK_MASK,\n\t\tquantity: ((orderId >> QUANTITY_LOTS_OFFSET) & U32_MASK) * lotSize,\n\t};\n}\n\n/**\n * What an order pays at settlement, raw USDC: its full quantity when the settlement price lies\n * in `(lower, higher]`, else 0. The mirror of `strike_exposure::settled_order_payout`, which\n * rounds the settlement price up to the market's tick grid (`range_codec::limit_tick`) before\n * comparing it with the order's ticks, so a price inside a tick counts as that tick's upper edge.\n * Pass `read.settlement`'s `settlementPriceRaw` and `tickSizeRaw`, and the config's\n * `units.positionLotSize` when it isn't the default.\n */\nexport function settledPayout(\n\torderId: bigint,\n\tsettlementPriceRaw: bigint,\n\ttickSizeRaw: bigint,\n\tlotSize: bigint = POSITION_LOT_SIZE,\n): bigint {\n\tif (tickSizeRaw <= 0n) throw new PredictInputError('tickSizeRaw must be positive');\n\tconst { lowerTick, higherTick, quantity } = decodeOrderRange(orderId, lotSize);\n\tconst limit = (settlementPriceRaw + tickSizeRaw - 1n) / tickSizeRaw;\n\tconst inRange = lowerTick < limit && (higherTick === POS_INF_TICK || limit <= higherTick);\n\treturn inRange ? quantity : 0n;\n}\n\n/** The strikes an {@link OrderRange} prices against, in USD, with `null` for each infinite\n * side — the shape {@link boundaryProbabilities} takes. `tickSize` is the market's raw tick\n * size (`ActiveMarket.tickSize` in USD, or the raw value from the deployment). */\nexport function orderStrikes(\n\trange: OrderRange,\n\ttickSizeRaw: bigint,\n): { lower: number | null; upper: number | null } {\n\treturn {\n\t\tlower: range.lowerTick === 0n ? null : fromRaw(range.lowerTick * tickSizeRaw, 9),\n\t\tupper: range.higherTick === POS_INF_TICK ? null : fromRaw(range.higherTick * tickSizeRaw, 9),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,gBAAgB;;AAE7B,MAAa,oBAAoB;;AAEjC,MAAa,cAAc;;AAE3B,MAAa,yBAAyB;;AAEtC,MAAa,uBAAuB;;;;;;;;;AASpC,MAAa,6BAA6B;;AAE1C,MAAa,qBAAqB,MAAM,OAAO;AAI/C,MAAM,WAAW,GAAW,MAAuB,IAAI,IAAK;AAC5D,MAAM,WAAW,GAAW,MAAuB,IAAI,gBAAiB;AACxE,MAAM,cAAc,GAAW,GAAW,gBAAiC,IAAI,IAAK;AACpF,MAAM,OAAO,GAAW,MAAuB,IAAI,IAAI,IAAI;AAC3D,MAAM,OAAO,GAAW,MAAuB,IAAI,IAAI,IAAI;AAG3D,SAAS,WAAW,OAAe,MAAc,UAAU,SAAS,UAAU,IAAU;AACvF,KAAI,OAAO,UAAU,YAAY,QAAQ,WAAW,QAAQ,QAC3D,OAAM,IAAI,kBACT,GAAG,KAAK,0BAA0B,QAAQ,IAAI,QAAQ,SAAS,QAC/D;;AAKH,SAAS,iBAAiB,GAAmB;CAC5C,IAAI,OAAO;CACX,IAAI,MAAM;AACV,KAAI,OAAO,MAAM,KAAK;AACrB,UAAQ;AACR,UAAQ;;AAET,KAAI,OAAO,MAAM,KAAK;AACrB,UAAQ;AACR,UAAQ;;AAET,KAAI,OAAO,MAAM,KAAK;AACrB,UAAQ;AACR,UAAQ;;A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AA;AAAA;;;;;;;iBAqGzB,oBAAA,CAAqB,CAAA,EAAG,gBAAA"}
1
+ {"version":3,"file":"errors.d.mts","names":[],"sources":["../../src/predict/errors.ts"],"mappings":";;cAaa,iBAAA,SAA0B,KAAA;cAC1B,OAAA;AAAA;;cAOA,gBAAA,SAAyB,KAAA;EAAA,SAC5B,MAAA;EARG;;EAAA,SAWH,IAAA;EAJG;;;EAAA,SAQH,SAAA;cAEG,MAAA,UAAgB,IAAA,UAAc,SAAA;AAAA;AAAA,UAyB1B,cAAA;EAChB,SAAA;IACC,SAAA;IACA,QAAA;MAAa,MAAA;IAAA;IACb,WAAA;MAAgB,YAAA;IAAA;EAAA;AAAA;;;;;AA8OlB;;;;;AAgEA;;iBAjFgB,eAAA,CAAgB,KAAA,EAAO,cAAA,sBAAoC,gBAAA;;;;;;;KAiB/D,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAgEC,qBAAA,SAA8B,KAAA;EAAA,SACjC,IAAA,EAAM,oBAAA;cAEH,IAAA,EAAM,oBAAA,EAAsB,OAAA;AAAA;;;;;;;iBAqGzB,oBAAA,CAAqB,CAAA,EAAG,gBAAA"}
@@ -66,7 +66,8 @@ const ABORT_NAMES = Object.freeze({
66
66
  "ENotFlushOperator",
67
67
  "ECutoverNotReached",
68
68
  "EEwmaRetired",
69
- "EOrderFlowNotAllowed"
69
+ "EOrderFlowNotAllowed",
70
+ "EBuilderFeeCutoverNotReached"
70
71
  ],
71
72
  pricing: [
72
73
  "EZeroForward",
@@ -192,7 +193,10 @@ const ABORT_NAMES = Object.freeze({
192
193
  sessions: [
193
194
  "EInvalidSessionDuration",
194
195
  "ESessionNotAuthorized",
195
- "ESessionLimitExceeded"
196
+ "ESessionLimitExceeded",
197
+ "EBuilderNotApproved",
198
+ "EBuilderFeeAboveApproved",
199
+ "EBuilderApprovalsNotEnabled"
196
200
  ],
197
201
  session_config: ["EPackageVersionDisabled", "EVersionWatermarkNotAdvanced"],
198
202
  account_registry: [