@mysten/deepbook-v3 2.6.4 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +153 -0
- package/PREDICT.md +389 -61
- package/dist/contracts/account/account.d.mts +23 -23
- package/dist/contracts/account/account.d.mts.map +1 -1
- package/dist/contracts/account/account_registry.d.mts +13 -13
- package/dist/contracts/deepbook/account.d.mts +18 -18
- package/dist/contracts/deepbook/balances.d.mts +4 -4
- package/dist/contracts/deepbook/deep_price.d.mts +3 -3
- package/dist/contracts/deepbook/order.d.mts +12 -12
- package/dist/contracts/deepbook_predict/admin.d.mts +4 -4
- package/dist/contracts/deepbook_predict/builder_code.d.mts +11 -11
- package/dist/contracts/deepbook_predict/builder_code_events.d.mts +10 -10
- package/dist/contracts/deepbook_predict/config_events.d.mts +93 -68
- package/dist/contracts/deepbook_predict/config_events.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/config_events.mjs +45 -1
- package/dist/contracts/deepbook_predict/config_events.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/deps/std/type_name.mjs +17 -0
- package/dist/contracts/deepbook_predict/deps/std/type_name.mjs.map +1 -0
- package/dist/contracts/deepbook_predict/expiry_market.d.mts +652 -235
- package/dist/contracts/deepbook_predict/expiry_market.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/expiry_market.mjs +652 -186
- package/dist/contracts/deepbook_predict/expiry_market.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/lp_book.mjs +1 -1
- package/dist/contracts/deepbook_predict/market_lifecycle_cap.d.mts +5 -5
- package/dist/contracts/deepbook_predict/market_manager.d.mts +27 -27
- package/dist/contracts/deepbook_predict/order_events.d.mts +50 -50
- package/dist/contracts/deepbook_predict/order_events.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/order_events.mjs +3 -1
- package/dist/contracts/deepbook_predict/order_events.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/pause_cap.d.mts +5 -5
- package/dist/contracts/deepbook_predict/plp.d.mts +184 -82
- package/dist/contracts/deepbook_predict/plp.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/plp.mjs +126 -7
- package/dist/contracts/deepbook_predict/plp.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/pool_accounting.mjs +1 -1
- package/dist/contracts/deepbook_predict/pool_valuation_cap.d.mts +5 -5
- package/dist/contracts/deepbook_predict/predict_account.d.mts +14 -14
- package/dist/contracts/deepbook_predict/pricing.d.mts +91 -58
- package/dist/contracts/deepbook_predict/pricing.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/pricing.mjs +30 -3
- package/dist/contracts/deepbook_predict/pricing.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/pricing_config.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/protocol_config.d.mts +400 -92
- package/dist/contracts/deepbook_predict/protocol_config.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/protocol_config.mjs +451 -61
- package/dist/contracts/deepbook_predict/protocol_config.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/range_codec.d.mts +2 -2
- package/dist/contracts/deepbook_predict/registry.d.mts +28 -28
- package/dist/contracts/deepbook_predict/strike_exposure.mjs +1 -1
- package/dist/contracts/deepbook_predict/strike_payout_tree.mjs +17 -12
- package/dist/contracts/deepbook_predict/strike_payout_tree.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/vault_events.d.mts +154 -106
- package/dist/contracts/deepbook_predict/vault_events.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/vault_events.mjs +57 -1
- package/dist/contracts/deepbook_predict/vault_events.mjs.map +1 -1
- package/dist/contracts/deepbook_predict_math/config-arguments.d.mts +10 -0
- package/dist/contracts/deepbook_predict_math/config-arguments.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_math/lazer_price.d.mts +106 -0
- package/dist/contracts/deepbook_predict_math/lazer_price.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_math/lazer_price.mjs +125 -0
- package/dist/contracts/deepbook_predict_math/lazer_price.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_math/math.d.mts +284 -0
- package/dist/contracts/deepbook_predict_math/math.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_math/math.mjs +364 -0
- package/dist/contracts/deepbook_predict_math/math.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/config-arguments.d.mts +13 -0
- package/dist/contracts/deepbook_predict_orders/config-arguments.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_orders/delayed_execution_config.d.mts +215 -0
- package/dist/contracts/deepbook_predict_orders/delayed_execution_config.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_orders/delayed_execution_config.mjs +215 -0
- package/dist/contracts/deepbook_predict_orders/delayed_execution_config.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.mjs +87 -0
- package/dist/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/deps/deepbook_predict/pricing.mjs +52 -0
- package/dist/contracts/deepbook_predict_orders/deps/deepbook_predict/pricing.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/deps/fixed_math/i64.mjs +25 -0
- package/dist/contracts/deepbook_predict_orders/deps/fixed_math/i64.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/deps/sui/balance.mjs +21 -0
- package/dist/contracts/deepbook_predict_orders/deps/sui/balance.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/deps/sui/table.mjs +39 -0
- package/dist/contracts/deepbook_predict_orders/deps/sui/table.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/desk.d.mts +187 -0
- package/dist/contracts/deepbook_predict_orders/desk.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_orders/desk.mjs +261 -0
- package/dist/contracts/deepbook_predict_orders/desk.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/order_queue.d.mts +1042 -0
- package/dist/contracts/deepbook_predict_orders/order_queue.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_orders/order_queue.mjs +849 -0
- package/dist/contracts/deepbook_predict_orders/order_queue.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/queue.d.mts +683 -0
- package/dist/contracts/deepbook_predict_orders/queue.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_orders/queue.mjs +912 -0
- package/dist/contracts/deepbook_predict_orders/queue.mjs.map +1 -0
- package/dist/contracts/deepbook_predict_orders/queue_events.d.mts +195 -0
- package/dist/contracts/deepbook_predict_orders/queue_events.d.mts.map +1 -0
- package/dist/contracts/deepbook_predict_orders/queue_events.mjs +187 -0
- package/dist/contracts/deepbook_predict_orders/queue_events.mjs.map +1 -0
- package/dist/contracts/deepbook_sessions/session_config.d.mts +8 -8
- package/dist/contracts/deepbook_sessions/sessions.d.mts +163 -28
- package/dist/contracts/deepbook_sessions/sessions.d.mts.map +1 -1
- package/dist/contracts/deepbook_sessions/sessions.mjs +234 -5
- package/dist/contracts/deepbook_sessions/sessions.mjs.map +1 -1
- package/dist/deployments/mainnet.mjs +7 -4
- package/dist/deployments/mainnet.mjs.map +1 -1
- package/dist/deployments/testnet.mjs +7 -4
- package/dist/deployments/testnet.mjs.map +1 -1
- package/dist/predict/bindings/expiry-market.d.mts +77 -0
- package/dist/predict/bindings/expiry-market.d.mts.map +1 -0
- package/dist/predict/bindings/expiry-market.mjs +139 -0
- package/dist/predict/bindings/expiry-market.mjs.map +1 -0
- package/dist/predict/bindings/protocol-config.d.mts +39 -0
- package/dist/predict/bindings/protocol-config.d.mts.map +1 -0
- package/dist/predict/bindings/protocol-config.mjs +90 -0
- package/dist/predict/bindings/protocol-config.mjs.map +1 -0
- package/dist/predict/bindings/rename.mjs +9 -0
- package/dist/predict/bindings/rename.mjs.map +1 -0
- package/dist/predict/client.d.mts +595 -16
- package/dist/predict/client.d.mts.map +1 -1
- package/dist/predict/client.mjs +986 -10
- package/dist/predict/client.mjs.map +1 -1
- package/dist/predict/config/generated.d.mts +22 -1
- package/dist/predict/config/generated.d.mts.map +1 -1
- package/dist/predict/config/generated.mjs +30 -1
- package/dist/predict/config/generated.mjs.map +1 -1
- package/dist/predict/config/mainnet.mjs +11 -3
- package/dist/predict/config/mainnet.mjs.map +1 -1
- package/dist/predict/config/testnet.mjs +11 -3
- package/dist/predict/config/testnet.mjs.map +1 -1
- package/dist/predict/config/types.d.mts +50 -1
- package/dist/predict/config/types.d.mts.map +1 -1
- package/dist/predict/cost.d.mts +38 -11
- package/dist/predict/cost.d.mts.map +1 -1
- package/dist/predict/cost.mjs +37 -11
- package/dist/predict/cost.mjs.map +1 -1
- package/dist/predict/decode.d.mts +251 -1
- package/dist/predict/decode.d.mts.map +1 -1
- package/dist/predict/decode.mjs +342 -4
- package/dist/predict/decode.mjs.map +1 -1
- package/dist/predict/errors.d.mts +69 -6
- package/dist/predict/errors.d.mts.map +1 -1
- package/dist/predict/errors.mjs +277 -4
- package/dist/predict/errors.mjs.map +1 -1
- package/dist/predict/index.d.mts +21 -10
- package/dist/predict/index.mjs +24 -12
- package/dist/predict/queue-id.d.mts +13 -0
- package/dist/predict/queue-id.d.mts.map +1 -0
- package/dist/predict/queue-id.mjs +19 -0
- package/dist/predict/queue-id.mjs.map +1 -0
- package/dist/predict/queue.d.mts +505 -0
- package/dist/predict/queue.d.mts.map +1 -0
- package/dist/predict/queue.mjs +774 -0
- package/dist/predict/queue.mjs.map +1 -0
- package/dist/predict/reads/balances.mjs +1 -1
- package/dist/predict/reads/markets.mjs +46 -5
- package/dist/predict/reads/markets.mjs.map +1 -1
- package/dist/predict/reads/pool.mjs +1 -1
- package/dist/predict/reads/pricing.d.mts +1 -1
- package/dist/predict/reads/queue.d.mts +105 -0
- package/dist/predict/reads/queue.d.mts.map +1 -0
- package/dist/predict/reads/queue.mjs +445 -0
- package/dist/predict/reads/queue.mjs.map +1 -0
- package/dist/predict/ticks.d.mts +9 -1
- package/dist/predict/ticks.d.mts.map +1 -1
- package/dist/predict/ticks.mjs +18 -1
- package/dist/predict/ticks.mjs.map +1 -1
- package/dist/predict/tx/authed.mjs +1 -1
- package/dist/predict/tx/common.d.mts.map +1 -1
- package/dist/predict/tx/common.mjs +12 -1
- package/dist/predict/tx/common.mjs.map +1 -1
- package/dist/predict/tx/queue.d.mts +220 -0
- package/dist/predict/tx/queue.d.mts.map +1 -0
- package/dist/predict/tx/queue.mjs +399 -0
- package/dist/predict/tx/queue.mjs.map +1 -0
- package/dist/predict/tx/trade.d.mts.map +1 -1
- package/dist/predict/tx/trade.mjs +61 -43
- package/dist/predict/tx/trade.mjs.map +1 -1
- package/dist/sessions.d.mts +90 -2
- package/dist/sessions.d.mts.map +1 -1
- package/dist/sessions.mjs +107 -2
- package/dist/sessions.mjs.map +1 -1
- package/dist/transactions/balanceManager.d.mts +12 -12
- package/dist/transactions/balanceManager.d.mts.map +1 -1
- package/dist/transactions/deepbook.d.mts +20 -20
- package/dist/transactions/deepbook.d.mts.map +1 -1
- package/dist/transactions/deepbookAdmin.d.mts +4 -4
- package/dist/transactions/deepbookAdmin.d.mts.map +1 -1
- package/dist/transactions/marginAdmin.d.mts +7 -7
- package/dist/transactions/marginAdmin.d.mts.map +1 -1
- package/dist/transactions/marginLiquidations.d.mts +3 -3
- package/dist/transactions/marginMaintainer.d.mts +5 -5
- package/dist/transactions/marginMaintainer.d.mts.map +1 -1
- package/dist/transactions/marginManager.d.mts +32 -32
- package/dist/transactions/marginManager.d.mts.map +1 -1
- package/dist/transactions/marginPool.d.mts +18 -18
- package/dist/transactions/marginRegistry.d.mts +16 -16
- package/dist/transactions/marginTPSL.d.mts +10 -10
- package/dist/transactions/marginTPSL.d.mts.map +1 -1
- package/dist/transactions/poolProxy.d.mts +8 -8
- package/dist/transactions/poolProxy.d.mts.map +1 -1
- package/package.json +4 -4
- package/src/contracts/deepbook_predict/config_events.ts +39 -0
- package/src/contracts/deepbook_predict/deps/std/type_name.ts +24 -0
- package/src/contracts/deepbook_predict/expiry_market.ts +960 -169
- package/src/contracts/deepbook_predict/order_events.ts +3 -1
- package/src/contracts/deepbook_predict/plp.ts +150 -9
- package/src/contracts/deepbook_predict/pricing.ts +46 -7
- package/src/contracts/deepbook_predict/pricing_config.ts +3 -1
- package/src/contracts/deepbook_predict/protocol_config.ts +648 -33
- package/src/contracts/deepbook_predict/strike_payout_tree.ts +25 -21
- package/src/contracts/deepbook_predict/vault_events.ts +65 -0
- package/src/contracts/deepbook_predict_math/config-arguments.ts +6 -0
- package/src/contracts/deepbook_predict_math/lazer_price.ts +196 -0
- package/src/contracts/deepbook_predict_math/math.ts +553 -0
- package/src/contracts/deepbook_predict_orders/config-arguments.ts +11 -0
- package/src/contracts/deepbook_predict_orders/delayed_execution_config.ts +430 -0
- package/src/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.ts +108 -0
- package/src/contracts/deepbook_predict_orders/deps/deepbook_predict/pricing.ts +58 -0
- package/src/contracts/deepbook_predict_orders/deps/fixed_math/i64.ts +21 -0
- package/src/contracts/deepbook_predict_orders/deps/sui/balance.ts +19 -0
- package/src/contracts/deepbook_predict_orders/deps/sui/table.ts +37 -0
- package/src/contracts/deepbook_predict_orders/desk.ts +419 -0
- package/src/contracts/deepbook_predict_orders/order_flow.ts +19 -0
- package/src/contracts/deepbook_predict_orders/order_queue.ts +1670 -0
- package/src/contracts/deepbook_predict_orders/queue.ts +1394 -0
- package/src/contracts/deepbook_predict_orders/queue_events.ts +189 -0
- package/src/contracts/deepbook_sessions/sessions.ts +355 -4
- package/src/deployments/mainnet.ts +7 -2
- package/src/deployments/testnet.ts +7 -2
- package/src/deployments/types.ts +14 -1
- package/src/predict/bindings/expiry-market.ts +127 -0
- package/src/predict/bindings/protocol-config.ts +59 -0
- package/src/predict/bindings/rename.ts +14 -0
- package/src/predict/client.ts +2076 -13
- package/src/predict/config/generated.ts +50 -0
- package/src/predict/config/mainnet.ts +16 -2
- package/src/predict/config/testnet.ts +16 -2
- package/src/predict/config/types.ts +51 -1
- package/src/predict/cost.ts +62 -14
- package/src/predict/decode.ts +691 -2
- package/src/predict/errors.ts +391 -14
- package/src/predict/index.ts +87 -6
- package/src/predict/queue-id.ts +22 -0
- package/src/predict/queue.ts +1231 -0
- package/src/predict/reads/markets.ts +30 -0
- package/src/predict/reads/queue.ts +606 -0
- package/src/predict/ticks.ts +35 -0
- package/src/predict/tx/common.ts +25 -1
- package/src/predict/tx/queue.ts +525 -0
- package/src/predict/tx/trade.ts +80 -49
- package/src/sessions.ts +206 -1
|
@@ -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`), and the\n// chain exposes no getter for `base_fee`/`min_fee` — take it from the market's `MarketCreated`\n// event (an indexer, or `decode`), or use {@link SHIPPED_FEE_POLICY} for the shipped template.\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/** `constants::fee_incentive_subsidy_rate` — sponsor share of a trader's mint fee (20%). */\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 (the `MarketCreated` event carries every field) rather than assuming the\n * 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. A market that was created under these values charges exactly this; one\n * created after an admin change does not, which is why the per-market snapshot is the real\n * answer. Verify against the deployment's `MarketCreated` before pricing money on it.\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. */\nexport function feeIncentiveSubsidy(fee: bigint, feeIncentiveBalance: bigint): bigint {\n\tassertUint(fee, 'fee');\n\tassertUint(feeIncentiveBalance, 'feeIncentiveBalance');\n\treturn min(mulDown(fee, FEE_INCENTIVE_SUBSIDY_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/** Per-unit congestion surcharge rate — see {@link congestionPenaltyRate}. Default `0n`. */\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(fee, rawAmount(inputs.feeIncentiveBalance ?? 0n));\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/** 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;;AAEpC,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,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,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;;;;;AAMF,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/** 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,yBA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c,KAAK,OAAO,QAAQ,MAAM,YAAY,aAAa,EAAE;EAChF,OAAO,MAAM,eAAe,eAAe,OAAO,QAAQ,MAAM,aAAa,aAAa,EAAE;EAC5F"}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { OrderEnqueued } from "../contracts/deepbook_predict_orders/queue_events.mjs";
|
|
2
|
+
import { DelayedExecutionPolicy, HeldPosition, OrderKindName, RefundReasonInfo } from "./queue.mjs";
|
|
3
|
+
|
|
1
4
|
//#region src/predict/decode.d.ts
|
|
2
5
|
/** The slice of an executed/simulated transaction result the decoders need. */
|
|
3
6
|
interface DecodableEvent {
|
|
@@ -157,6 +160,253 @@ interface BuilderCodeReceipt {
|
|
|
157
160
|
/** Null after unsetBuilderCode. */
|
|
158
161
|
builderCodeId: string | null;
|
|
159
162
|
}
|
|
163
|
+
/** The market's cash figures after the call, as the queue events report them. */
|
|
164
|
+
interface QueueCashFigures {
|
|
165
|
+
marketCash: bigint;
|
|
166
|
+
requiredCash: bigint;
|
|
167
|
+
waitingCashNeed: bigint;
|
|
168
|
+
}
|
|
169
|
+
/** `OrderEnqueued`: the trader's own receipt for a queued mint or sell. Drives "Placed". */
|
|
170
|
+
interface EnqueueReceipt {
|
|
171
|
+
type: 'enqueued';
|
|
172
|
+
marketId: string;
|
|
173
|
+
/** The record ID: what `read.order`, `quoteSell` and `enqueueSell` take. Persist it. */
|
|
174
|
+
recordId: bigint;
|
|
175
|
+
accountId: string;
|
|
176
|
+
kind: number;
|
|
177
|
+
kindName: OrderKindName;
|
|
178
|
+
side: 'mint' | 'sell' | 'unknown';
|
|
179
|
+
request: {
|
|
180
|
+
lowerTick: bigint;
|
|
181
|
+
higherTick: bigint;
|
|
182
|
+
quantity: bigint;
|
|
183
|
+
maxPremium: bigint;
|
|
184
|
+
minQuantity: bigint;
|
|
185
|
+
maxCost: bigint;
|
|
186
|
+
maxProbability: bigint;
|
|
187
|
+
minProbability: bigint;
|
|
188
|
+
minProceeds: bigint;
|
|
189
|
+
};
|
|
190
|
+
/** The position a sell moved into the record. Null for a mint. */
|
|
191
|
+
position: HeldPosition | null;
|
|
192
|
+
timing: {
|
|
193
|
+
placedAtMs: bigint;
|
|
194
|
+
earliestPriceMs: bigint;
|
|
195
|
+
tauMs: bigint;
|
|
196
|
+
deadlineMs: bigint;
|
|
197
|
+
cutoffMs: bigint;
|
|
198
|
+
pythChannel: number;
|
|
199
|
+
};
|
|
200
|
+
/** The Open record a sell took its position from. Null for a mint. */
|
|
201
|
+
sourceRecordId: bigint | null;
|
|
202
|
+
builderCodeId: string | null;
|
|
203
|
+
referrerAccountId: string | null;
|
|
204
|
+
/** USDC escrowed for the premium and fees (0 for a sell). */
|
|
205
|
+
budget: number;
|
|
206
|
+
orderFee: number;
|
|
207
|
+
cash: QueueCashFigures;
|
|
208
|
+
/** `onchain_timestamp_ms`: the placement transaction's clock. */
|
|
209
|
+
timestampMs: bigint;
|
|
210
|
+
raw: {
|
|
211
|
+
budget: bigint;
|
|
212
|
+
orderFee: bigint;
|
|
213
|
+
cashNeed: bigint;
|
|
214
|
+
subsidyBound: bigint;
|
|
215
|
+
};
|
|
216
|
+
/** The volatility snapshot the fill prices with, as the generated layout parses it. */
|
|
217
|
+
vol: (typeof OrderEnqueued)['$inferType']['vol'];
|
|
218
|
+
}
|
|
219
|
+
/** `CohortCommitted`: a price attached to the records `firstRecordId..=lastRecordId`. Drives "Priced". */
|
|
220
|
+
interface CohortCommitReceipt {
|
|
221
|
+
type: 'cohort-committed';
|
|
222
|
+
marketId: string;
|
|
223
|
+
tauMs: bigint;
|
|
224
|
+
/** The update's envelope: τ, or the backup tick one channel tick later. */
|
|
225
|
+
tickMs: bigint;
|
|
226
|
+
firstRecordId: bigint;
|
|
227
|
+
/** Inclusive. */
|
|
228
|
+
lastRecordId: bigint;
|
|
229
|
+
/** The committed price of the cohort's first order as a float: `spotRaw / 1e9`. */
|
|
230
|
+
price: number;
|
|
231
|
+
/** The committed price, normalized to 1e9. */
|
|
232
|
+
spotRaw: bigint;
|
|
233
|
+
/** That price's own update time, in µs. */
|
|
234
|
+
generationUs: bigint;
|
|
235
|
+
pythSourceId: number;
|
|
236
|
+
pythChannel: number;
|
|
237
|
+
/** Who committed: a keeper, or any third-party filler. */
|
|
238
|
+
sender: string;
|
|
239
|
+
/** `onchain_timestamp_ms`. */
|
|
240
|
+
timestampMs: bigint;
|
|
241
|
+
}
|
|
242
|
+
/** `QueuedOrderFilled`. Report "Filled" only from this event (or the record). */
|
|
243
|
+
interface QueuedFillReceipt {
|
|
244
|
+
type: 'filled';
|
|
245
|
+
marketId: string;
|
|
246
|
+
recordId: bigint;
|
|
247
|
+
accountId: string;
|
|
248
|
+
kind: number;
|
|
249
|
+
side: 'mint' | 'sell' | 'unknown';
|
|
250
|
+
/** Filled quantity (mint) or closed quantity (sell). */
|
|
251
|
+
quantity: number;
|
|
252
|
+
/** Cost paid (mint) or proceeds before the order fee (sell). */
|
|
253
|
+
amount: number;
|
|
254
|
+
fees: {
|
|
255
|
+
trading: number;
|
|
256
|
+
builder: number;
|
|
257
|
+
referral: number;
|
|
258
|
+
order: number;
|
|
259
|
+
subsidyUsed: number;
|
|
260
|
+
inventoryImpact: number;
|
|
261
|
+
};
|
|
262
|
+
tauMs: bigint;
|
|
263
|
+
tickMs: bigint;
|
|
264
|
+
/** The record's position now: a mint's new position, a partial sell's remainder, or null. */
|
|
265
|
+
position: HeldPosition | null;
|
|
266
|
+
sender: string;
|
|
267
|
+
timestampMs: bigint;
|
|
268
|
+
cash: QueueCashFigures;
|
|
269
|
+
raw: {
|
|
270
|
+
quantity: bigint;
|
|
271
|
+
amount: bigint;
|
|
272
|
+
tradingFee: bigint;
|
|
273
|
+
builderFee: bigint;
|
|
274
|
+
referralFee: bigint;
|
|
275
|
+
orderFee: bigint;
|
|
276
|
+
subsidyUsed: bigint;
|
|
277
|
+
inventoryImpact: bigint;
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* `QueuedOrderRefunded`, from whichever path refunded the order: resolve, a deadline refund, an
|
|
282
|
+
* admin refund, or the settlement drain (`settle_step`, reason 5). `sender` is always the
|
|
283
|
+
* transaction's sender.
|
|
284
|
+
*/
|
|
285
|
+
interface QueuedRefundReceipt {
|
|
286
|
+
type: 'refunded';
|
|
287
|
+
marketId: string;
|
|
288
|
+
recordId: bigint;
|
|
289
|
+
accountId: string;
|
|
290
|
+
kind: number;
|
|
291
|
+
side: 'mint' | 'sell' | 'unknown';
|
|
292
|
+
reason: RefundReasonInfo;
|
|
293
|
+
escrowReturned: number;
|
|
294
|
+
orderFeeReturned: number;
|
|
295
|
+
subsidyReturned: number;
|
|
296
|
+
/** True when a sell's record went back to Open holding its position. */
|
|
297
|
+
positionReturned: boolean;
|
|
298
|
+
sender: string;
|
|
299
|
+
timestampMs: bigint;
|
|
300
|
+
cash: QueueCashFigures;
|
|
301
|
+
raw: {
|
|
302
|
+
escrowReturned: bigint;
|
|
303
|
+
orderFeeReturned: bigint;
|
|
304
|
+
subsidyReturned: bigint;
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* `OpenRecordSettled` (paid, 0 for a loser) or `OpenRecordPayoutSkipped` (stays Open, for a later
|
|
309
|
+
* `pay_open`), from `settle_step`'s payout walk or `pay_open`.
|
|
310
|
+
*/
|
|
311
|
+
interface OpenRecordPayoutReceipt {
|
|
312
|
+
type: 'open-record-settled' | 'open-record-payout-skipped';
|
|
313
|
+
marketId: string;
|
|
314
|
+
recordId: bigint;
|
|
315
|
+
accountId: string;
|
|
316
|
+
orderId: bigint;
|
|
317
|
+
payout: number;
|
|
318
|
+
/** True for `OpenRecordPayoutSkipped`: the market couldn't pay it yet. */
|
|
319
|
+
skipped: boolean;
|
|
320
|
+
timestampMs: bigint;
|
|
321
|
+
raw: {
|
|
322
|
+
payout: bigint;
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
/** `MarketPayoutsCompleted`: the settlement payout walk is done. */
|
|
326
|
+
interface MarketPayoutsCompletedReceipt {
|
|
327
|
+
type: 'market-payouts-completed';
|
|
328
|
+
marketId: string;
|
|
329
|
+
timestampMs: bigint;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* `RecordFundsParked`: a record kept USDC it couldn't send to its receive address (on USDC's deny
|
|
333
|
+
* list, or USDC paused). `RecordFundsClaimed`: `claim_parked` sent a record's parked funds.
|
|
334
|
+
*/
|
|
335
|
+
interface RecordFundsReceipt {
|
|
336
|
+
type: 'record-funds-parked' | 'record-funds-claimed';
|
|
337
|
+
marketId: string;
|
|
338
|
+
recordId: bigint;
|
|
339
|
+
accountId: string;
|
|
340
|
+
receiveAddress: string;
|
|
341
|
+
/** Parked: this call's parked change or refund. Claimed: everything the record had parked. */
|
|
342
|
+
amount: number;
|
|
343
|
+
timestampMs: bigint;
|
|
344
|
+
raw: {
|
|
345
|
+
amount: bigint;
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/** Queue housekeeping events, for ops and alerts. */
|
|
349
|
+
type QueueOpsReceipt = {
|
|
350
|
+
type: 'queued-orders-cleaned';
|
|
351
|
+
marketId: string;
|
|
352
|
+
recordIds: bigint[];
|
|
353
|
+
timestampMs: bigint;
|
|
354
|
+
};
|
|
355
|
+
/** Delayed-execution admin events, for the multisig scripts and monitors. */
|
|
356
|
+
type PolicyUpdateReceipt = {
|
|
357
|
+
/**
|
|
358
|
+
* The companion desk's `DelayedExecutionPolicyUpdated`, from every policy setter with the
|
|
359
|
+
* full post-state. The desk's `init` at publish emits none: the launch policy is only the
|
|
360
|
+
* desk's state.
|
|
361
|
+
*/
|
|
362
|
+
type: 'policy-updated';
|
|
363
|
+
deskId: string;
|
|
364
|
+
policy: DelayedExecutionPolicy;
|
|
365
|
+
timestampMs: bigint;
|
|
366
|
+
} | {
|
|
367
|
+
type: 'flush-operator-updated';
|
|
368
|
+
operator: string;
|
|
369
|
+
added: boolean;
|
|
370
|
+
timestampMs: bigint;
|
|
371
|
+
} | {
|
|
372
|
+
/** Predict's `OrderFlowUpdated`: an order-flow witness allowlisted or removed. */type: 'order-flow-updated'; /** The witness type, as Move's `type_name` renders it (no `0x` prefix). */
|
|
373
|
+
orderFlow: string;
|
|
374
|
+
enabled: boolean;
|
|
375
|
+
timestampMs: bigint;
|
|
376
|
+
};
|
|
377
|
+
/** Every delayed-execution order event, tagged, in chain order. Feed it to `queue.reduceOrderEvents`. */
|
|
378
|
+
type QueueEvent = EnqueueReceipt | CohortCommitReceipt | QueuedFillReceipt | QueuedRefundReceipt | OpenRecordPayoutReceipt | MarketPayoutsCompletedReceipt | RecordFundsReceipt | QueueOpsReceipt;
|
|
379
|
+
/**
|
|
380
|
+
* `vault_events::ExpiryPnlRealized`: the change in the pool's gross realized result on one expiry
|
|
381
|
+
* since that expiry's previous emission, emitted with every `ExpiryPnl`. An expiry's first
|
|
382
|
+
* emission (its first settled sweep) carries the lifetime result, which can be a loss. A later
|
|
383
|
+
* one carries the extra cash a later sweep returned, always a profit. Gross: before the
|
|
384
|
+
* protocol/LP split, and including the sponsor fee subsidies mints moved into expiry cash.
|
|
385
|
+
*/
|
|
386
|
+
interface ExpiryPnlRealizedReceipt {
|
|
387
|
+
vaultId: string;
|
|
388
|
+
marketId: string;
|
|
389
|
+
propbookUnderlyingId: number;
|
|
390
|
+
expiryMs: bigint;
|
|
391
|
+
/** The settlement price, 1e9-scaled. */
|
|
392
|
+
settlementPriceRaw: bigint;
|
|
393
|
+
/** False only for a loss, which only an expiry's first emission reports. */
|
|
394
|
+
inProfit: boolean;
|
|
395
|
+
/** The change's magnitude, in USDC. */
|
|
396
|
+
amount: number;
|
|
397
|
+
/** The change with its sign: `+amount` for a profit, `−amount` for a loss. */
|
|
398
|
+
signedAmountRaw: bigint;
|
|
399
|
+
raw: {
|
|
400
|
+
amount: bigint;
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* The pool's gross realized P&L in raw USDC: the signed sum of `ExpiryPnlRealized` changes. Over
|
|
405
|
+
* every emission of every expiry it equals the sum of each expiry's latest `ExpiryPnl`, with no
|
|
406
|
+
* per-expiry dedup. Subtract the `OrderMinted.fee_incentive_subsidy` totals to isolate the
|
|
407
|
+
* trading result.
|
|
408
|
+
*/
|
|
409
|
+
declare function realizedPnlRaw(receipts: readonly Pick<ExpiryPnlRealizedReceipt, 'signedAmountRaw'>[]): bigint;
|
|
160
410
|
//#endregion
|
|
161
|
-
export { BalanceChangeReceipt, BuilderCodeReceipt, ClaimReceipt, CreateManagerReceipt, DecodableEvent, DecodableTransactionResult, MintReceipt, PlpCancelReceipt, PlpRequestReceipt, RedeemReceipt };
|
|
411
|
+
export { BalanceChangeReceipt, BuilderCodeReceipt, ClaimReceipt, CohortCommitReceipt, CreateManagerReceipt, DecodableEvent, DecodableTransactionResult, EnqueueReceipt, ExpiryPnlRealizedReceipt, MarketPayoutsCompletedReceipt, MintReceipt, OpenRecordPayoutReceipt, PlpCancelReceipt, PlpRequestReceipt, PolicyUpdateReceipt, QueueCashFigures, QueueEvent, QueueOpsReceipt, QueuedFillReceipt, QueuedRefundReceipt, RecordFundsReceipt, RedeemReceipt, realizedPnlRaw };
|
|
162
412
|
//# sourceMappingURL=decode.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decode.d.mts","names":[],"sources":["../../src/predict/decode.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"decode.d.mts","names":[],"sources":["../../src/predict/decode.ts"],"mappings":";;;;;UAyCiB,cAAA;EAAc;EAE9B,SAAA;EACA,IAAA;EACA,SAAA;EACA,MAAA;EADA;EAGA,IAAA;EAAA;EAEA,GAAA,GAAM,UAAA;AAAA;AAAA,UAGU,0BAAA;EAChB,MAAA,YAAkB,cAAA;AAAA;AAAA,UAoEF,WAAA;EAChB,QAAA;EACA,SAAA;EACA,KAAA;EAH2B;EAK3B,OAAA;EAL2B;EAO3B,cAAA;EACA,SAAA;EACA,UAAA;EAJA;EAMA,gBAAA;EAH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