{"version":3,"file":"cost.mjs","names":["quantity"],"sources":["../../src/predict/cost.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Client-side ALL-IN cost math for Predict trades — the fee layer `pricing.ts` stops short of.\n// `pricing.*` answers \"what is this contract worth?\" (the probability); this module answers\n// \"what does the chain debit me for it?\" and \"what does closing it credit me?\", with NO chain\n// call: no `devInspect`, no dry run, no simulate.\n//\n// It is an EXACT integer port of the deployed cost path, function for function:\n//\n//   mint     `expiry_market::mint_quote_at` / `compute_mint_quote`\n//              -> premium + (trading_fee - fee_incentive_subsidy) + builder_fee + penalty_fee\n//                 + inventory_impact_charge\n//   budget   `expiry_market::quote_exact_cost_terms` (the `mint_exact_cost` lot search)\n//   redeem   `expiry_market::redeem_live`'s payment decomposition\n//              -> gross + inventory_impact_rebate - trading_fee - builder_fee - penalty\n//   fees     `strike_exposure_config::trading_fee` (per-boundary Bernoulli fee + expiry ramp),\n//            `expiry_market::builder_fee_amount`, `ewma::penalty_fee`,\n//            `strike_exposure::mint_range_inventory_impact` / `live_close_inventory_impact`\n//\n// Every rounding step is the chain's: `mul_down`, `mul_div_down` and a bit-identical\n// `sqrt_down` (same Newton schedule as `fixed_math::math`), all on bigints. So given the same\n// inputs the chain uses, these return the chain's numbers to the raw unit — the fee layer\n// carries no approximation of its own.\n//\n// Local float probabilities (`pricing.upProbability`, ~1e-4) introduce approximation.\n// With raw probabilities AND the same fee, account, book and clock inputs as execution,\n// the arithmetic matches the chain. `exactProbabilities` only identifies the probability\n// input format; it does not certify the source or freshness of any state. A nonzero\n// inventory-impact policy requires book data. Congestion defaults to a zero rate; supply\n// the actual rate when enabled. Use `read.quoteMint` / `read.quoteRedeem` for a simulation\n// against current account and market state, including the execution gates these previews\n// do not check (ownership, pauses, trade window, oracle freshness and cash backing).\n//\n// The fee POLICY is a per-market snapshot taken at creation (`StrikeExposureConfig`). The\n// chain exposes no getter for `base_fee`/`min_fee`, so `read.feePolicy(market)` decodes it from\n// the `ExpiryMarket` object. The market's `MarketCreated` event carries it too.\n\nimport { PredictInputError } from './errors.js';\nimport type { PricerInputs } from './pricing.js';\nimport { upProbability } from './pricing.js';\nimport { POS_INF_TICK } from './ticks.js';\nimport { fromRaw, U64_MAX, usdcToRaw } from './units.js';\n\n// === Protocol constants (mirrors of `deepbook_predict::constants` / `fixed_math::math`) ===\n\n/** `math::float_scaling` — 1e9 is 1.0 for every rate and probability here. */\nexport const FLOAT_SCALING = 1_000_000_000n;\n/** `constants::position_lot_size` — quantity is an integer number of these. */\nexport const POSITION_LOT_SIZE = 10_000n;\n/** `constants::min_premium` — a mint below this premium aborts `EPremiumBelowMinimum`. */\nexport const MIN_PREMIUM = 1_000_000n;\n/** `constants::builder_fee_multiplier` — the builder's cut of the trading fee (10%). */\nexport const BUILDER_FEE_MULTIPLIER = 100_000_000n;\n/** `constants::max_builder_fee_rate` — cap on the builder fee as a share of quantity (0.5%). */\nexport const MAX_BUILDER_FEE_RATE = 5_000_000n;\n/**\n * The default sponsor share of a trader's mint fee (20%), and the rate the chain reads while the\n * admin hasn't set one.\n * @deprecated From delayed execution (DBU-885) the rate is admin-set: read it with\n * `protocol_config::fee_incentive_subsidy_rate` (`read.queue(...).protocol.feeIncentiveSubsidyRate`)\n * and pass it as `feeIncentiveSubsidyRate`. A hardcoded 20% underquotes every mint once the rate\n * moves.\n */\nexport const FEE_INCENTIVE_SUBSIDY_RATE = 200_000_000n;\n/** `order::max_quantity_lots` — the order ID's 32-bit lot field. */\nexport const MAX_QUANTITY_LOTS = (1n << 32n) - 1n;\n\n// === Fixed-point primitives (mirrors of `fixed_math::math`) ===\n\nconst mulDown = (x: bigint, y: bigint): bigint => (x * y) / FLOAT_SCALING;\nconst divDown = (x: bigint, y: bigint): bigint => (x * FLOAT_SCALING) / y;\nconst mulDivDown = (x: bigint, y: bigint, denominator: bigint): bigint => (x * y) / denominator;\nconst min = (a: bigint, b: bigint): bigint => (a < b ? a : b);\nconst max = (a: bigint, b: bigint): bigint => (a > b ? a : b);\n\n// Move's unsigned types enforce these domains before arithmetic. JS bigint does not.\nfunction assertUint(value: bigint, name: string, maximum = U64_MAX, minimum = 0n): void {\n\tif (typeof value !== 'bigint' || value < minimum || value > maximum) {\n\t\tthrow new PredictInputError(\n\t\t\t`${name} must be an integer in [${minimum}, ${maximum}], got ${value}`,\n\t\t);\n\t}\n}\n\n// `math::sqrt_initial_guess_u128` — power-of-two seed for the Newton iteration.\nfunction sqrtInitialGuess(x: bigint): bigint {\n\tlet bits = 0n;\n\tlet val = x;\n\tif (val >= 1n << 64n) {\n\t\tval >>= 64n;\n\t\tbits += 64n;\n\t}\n\tif (val >= 1n << 32n) {\n\t\tval >>= 32n;\n\t\tbits += 32n;\n\t}\n\tif (val >= 1n << 16n) {\n\t\tval >>= 16n;\n\t\tbits += 16n;\n\t}\n\tif (val >= 1n << 8n) {\n\t\tval >>= 8n;\n\t\tbits += 8n;\n\t}\n\tif (val >= 1n << 4n) {\n\t\tval >>= 4n;\n\t\tbits += 4n;\n\t}\n\tif (val >= 1n << 2n) {\n\t\tval >>= 2n;\n\t\tbits += 2n;\n\t}\n\tif (val >= 1n << 1n) bits += 1n;\n\treturn 1n << ((bits + 1n) / 2n);\n}\n\n// `math::sqrt_u128_down` — seven Newton steps then one correcting decrement, exactly as the\n// chain runs them, so this agrees with the contract raw unit for raw unit rather than merely\n// to within a rounding step.\nfunction sqrtU128Down(x: bigint): bigint {\n\tif (x === 0n) return 0n;\n\tif (x < 4n) return 1n;\n\tlet g = sqrtInitialGuess(x);\n\tfor (let i = 0; i < 7; i++) g = (g + x / g) / 2n;\n\tif (g > x / g) g -= 1n;\n\treturn g;\n}\n\n/** `math::sqrt_down` — square root of a 1e9-scaled value, 1e9-scaled, rounded down. */\nexport function sqrtDown(x: bigint): bigint {\n\tassertUint(x, 'sqrt input');\n\treturn sqrtU128Down(x * FLOAT_SCALING);\n}\n\n// === Policy and state inputs ===\n\n/**\n * One market's fee policy: the `StrikeExposureConfig` it snapshotted at creation, in raw 1e9\n * rates. Snapshotted means later admin changes do NOT reprice a market already trading, so\n * read it per market with `read.feePolicy(market)` (the `MarketCreated` event carries every field\n * too) rather than assuming the template. The last three are the inventory-impact parameters, inert while\n * `inventoryImpactMaxRate` is `0n` (the shipped value).\n */\nexport interface FeePolicy {\n\t/** `base_fee` — multiplies `sqrt(p·(1−p))`. */\n\tbaseFee: bigint;\n\t/** `min_fee` — per-unit floor, applied per boundary leg before the ramp. */\n\tminFee: bigint;\n\t/** `expiry_fee_window_ms` — window before expiry over which the fee ramps. */\n\texpiryFeeWindowMs: bigint;\n\t/** `expiry_fee_max_multiplier` — multiplier reached at expiry; 1e9 disables the ramp. */\n\texpiryFeeMaxMultiplier: bigint;\n\t/** `min_entry_probability` — mint admission floor on the entry probability. */\n\tminEntryProbability: bigint;\n\t/** `max_entry_probability` — mint admission ceiling on the entry probability. */\n\tmaxEntryProbability: bigint;\n\t/** `inventory_impact_max_rate` — maximum marginal impact rate; `0n` disables impact. */\n\tinventoryImpactMaxRate: bigint;\n\t/** `inventory_impact_scale` — the market's `max_expiry_allocation`, the curve's `B`. */\n\tinventoryImpactScale: bigint;\n\t/** `backing_buffer_lambda` — the buffer on non-peak payout in the liability formula. */\n\tbackingBufferLambda: bigint;\n}\n\n/**\n * The shipped template (`config_constants` defaults): 10% Bernoulli fee, a 2.2% per-leg floor,\n * a one-day ramp window that is inert at a 1.0 multiplier, a 1%–99% entry band, and inventory\n * impact disabled. Neither recorded deployment's template matches it any more: both charge a\n * 20.4% Bernoulli fee, ramp it to 3× over the last 60 s and admit entries in 25%–75% (checked\n * 2026-10-09), so a live market's costs from this policy come out low. Pass\n * `read.feePolicy(market)` instead. This stays for tests and for a deployment still on the\n * defaults.\n */\nexport const SHIPPED_FEE_POLICY: FeePolicy = Object.freeze({\n\tbaseFee: 100_000_000n,\n\tminFee: 22_000_000n,\n\texpiryFeeWindowMs: 86_400_000n,\n\texpiryFeeMaxMultiplier: FLOAT_SCALING,\n\tminEntryProbability: 10_000_000n,\n\tmaxEntryProbability: 990_000_000n,\n\tinventoryImpactMaxRate: 0n,\n\tinventoryImpactScale: 0n,\n\tbackingBufferLambda: 310_000_000n,\n});\n\n/** A range's two boundary UP probabilities, raw 1e9. `null` is an infinite boundary — the\n * −∞ lower of a DOWN order and the +∞ higher of an UP order — which is priced at the digital\n * limit and pays no fee leg. */\nexport interface Boundaries {\n\t/** `P(settle > lower)`, or `null` for the −∞ lower bound. */\n\tlowerUp: bigint | null;\n\t/** `P(settle > higher)`, or `null` for the +∞ higher bound. */\n\thigherUp: bigint | null;\n}\n\n/** Where a quote's probabilities come from: boundary probabilities you already hold (raw 1e9,\n * e.g. `probabilityToRaw((await read.price(...)).up)`) or a local pricer snapshot plus\n * the range's strikes in USD (`null` for an infinite side). */\nexport type ProbabilitySource =\n\tBoundaries | { pricer: PricerInputs; lower: number | null; upper: number | null };\n\n/** The market's gas-price EWMA (`ewma::EwmaState`), both fields 1e9-scaled. */\nexport interface CongestionState {\n\tmean: bigint;\n\tvariance: bigint;\n}\n\n/** The protocol's congestion knobs (`EwmaConfig`). Shipped disabled. */\nexport interface CongestionPolicy {\n\tenabled: boolean;\n\t/** `penalty_rate` — per-unit surcharge charged when the z-score fires. */\n\tpenaltyRate: bigint;\n\t/** `z_score_threshold` — how many standard deviations above the mean gas must sit. */\n\tzScoreThreshold: bigint;\n}\n\n/** Pre-trade payout-tree reads a mint's inventory-impact charge is evaluated against\n * (`strike_exposure::quote_mint_range`). All in quote units. */\nexport interface MintBookTerms {\n\t/** `M` — largest summed net payout at any one settlement price. */\n\tmaxPayout: bigint;\n\t/** `T` — sum of every live order's payout. */\n\ttotalPayout: bigint;\n\t/** The payout peak inside the mint's own `(lower, higher]`. */\n\trangeMaxPayout: bigint;\n}\n\n/** The same reads for a live close, which also needs the peak OUTSIDE the order's range\n * (`strike_exposure::live_close_inventory_impact`). */\nexport interface CloseBookTerms extends MintBookTerms {\n\t/** The payout peak in the complement of the order's range. */\n\tcomplementMaxPayout: bigint;\n}\n\nfunction assertFeePolicy(policy: FeePolicy): void {\n\tassertUint(policy.baseFee, 'baseFee', FLOAT_SCALING);\n\tassertUint(policy.minFee, 'minFee', FLOAT_SCALING);\n\tassertUint(policy.expiryFeeWindowMs, 'expiryFeeWindowMs', U64_MAX, 1n);\n\tassertUint(\n\t\tpolicy.expiryFeeMaxMultiplier,\n\t\t'expiryFeeMaxMultiplier',\n\t\t10n * FLOAT_SCALING,\n\t\tFLOAT_SCALING,\n\t);\n\tassertUint(policy.minEntryProbability, 'minEntryProbability', FLOAT_SCALING);\n\tassertUint(policy.maxEntryProbability, 'maxEntryProbability', FLOAT_SCALING);\n\tif (policy.minEntryProbability >= policy.maxEntryProbability) {\n\t\tthrow new PredictInputError('minEntryProbability must be below maxEntryProbability');\n\t}\n\tassertUint(policy.inventoryImpactMaxRate, 'inventoryImpactMaxRate', FLOAT_SCALING);\n\tassertUint(policy.backingBufferLambda, 'backingBufferLambda', FLOAT_SCALING);\n\tassertUint(\n\t\tpolicy.inventoryImpactScale,\n\t\t'inventoryImpactScale',\n\t\tU64_MAX,\n\t\tpolicy.inventoryImpactMaxRate === 0n ? 0n : 1n,\n\t);\n}\n\nfunction assertBoundaries(boundaries: Boundaries): void {\n\tif (boundaries.lowerUp !== null) assertUint(boundaries.lowerUp, 'lowerUp', FLOAT_SCALING);\n\tif (boundaries.higherUp !== null) assertUint(boundaries.higherUp, 'higherUp', FLOAT_SCALING);\n}\n\nfunction assertBook(book: MintBookTerms): void {\n\tassertUint(book.totalPayout, 'totalPayout');\n\tassertUint(book.maxPayout, 'maxPayout', book.totalPayout);\n\tassertUint(book.rangeMaxPayout, 'rangeMaxPayout', book.maxPayout);\n}\n\nfunction assertCostInputs(\n\tinputs: Pick<MintInputsBase, 'fees' | 'book' | 'penaltyRate' | 'lotSize'>,\n): void {\n\tassertFeePolicy(inputs.fees);\n\tassertUint(inputs.penaltyRate ?? 0n, 'penaltyRate', FLOAT_SCALING);\n\tassertUint(inputs.lotSize ?? POSITION_LOT_SIZE, 'lotSize', U64_MAX / MAX_QUANTITY_LOTS, 1n);\n\tif (inputs.fees.inventoryImpactMaxRate > 0n && !inputs.book) {\n\t\tthrow new PredictInputError('book is required when inventory impact is enabled');\n\t}\n\tif (inputs.book) assertBook(inputs.book);\n}\n\n// === Fee components ===\n\n/** `strike_exposure_config::raw_bernoulli_fee_rate` — `base_fee · sqrt(p·(1−p))`, the fee rate\n * before the `min_fee` floor and the expiry ramp. Zero at the certain ends. */\nexport function bernoulliFeeRate(baseFee: bigint, probability: bigint): bigint {\n\tassertUint(baseFee, 'baseFee', FLOAT_SCALING);\n\tassertUint(probability, 'probability (EInvalidFeeProbability)', FLOAT_SCALING);\n\tif (probability === 0n || probability === FLOAT_SCALING) return 0n;\n\treturn mulDown(baseFee, sqrtDown(mulDown(probability, FLOAT_SCALING - probability)));\n}\n\n/** `strike_exposure_config::expiry_fee_multiplier` — 1.0 outside the window, rising linearly\n * to `expiry_fee_max_multiplier` at expiry. */\nexport function expiryFeeMultiplier(policy: FeePolicy, timeToExpiryMs: bigint): bigint {\n\tassertFeePolicy(policy);\n\tassertUint(timeToExpiryMs, 'timeToExpiryMs');\n\tif (timeToExpiryMs >= policy.expiryFeeWindowMs) return FLOAT_SCALING;\n\treturn (\n\t\tFLOAT_SCALING +\n\t\tmulDivDown(\n\t\t\tpolicy.expiryFeeMaxMultiplier - FLOAT_SCALING,\n\t\t\tpolicy.expiryFeeWindowMs - timeToExpiryMs,\n\t\t\tpolicy.expiryFeeWindowMs,\n\t\t)\n\t);\n}\n\n// `strike_exposure_config::leg_trading_fee` — one finite boundary's fee, floored then ramped,\n// rounded down at each step.\nfunction legTradingFee(\n\tpolicy: FeePolicy,\n\tprobability: bigint,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): bigint {\n\tconst base = max(bernoulliFeeRate(policy.baseFee, probability), policy.minFee);\n\treturn mulDown(mulDown(base, expiryFeeMultiplier(policy, timeToExpiryMs)), quantity);\n}\n\n/**\n * `strike_exposure_config::trading_fee` — the fee for a whole range, charged PER FINITE\n * BOUNDARY with each leg floored and ramped independently. A binary order has one finite\n * boundary and pays one leg; a two-sided range pays two, so it is not the same fee as the\n * range's own probability would suggest.\n */\nexport function tradingFee(\n\tpolicy: FeePolicy,\n\tboundaries: Boundaries,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBoundaries(boundaries);\n\tassertUint(quantity, 'quantity');\n\tassertUint(timeToExpiryMs, 'timeToExpiryMs');\n\tconst lower =\n\t\tboundaries.lowerUp === null\n\t\t\t? 0n\n\t\t\t: legTradingFee(policy, boundaries.lowerUp, quantity, timeToExpiryMs);\n\tconst higher =\n\t\tboundaries.higherUp === null\n\t\t\t? 0n\n\t\t\t: legTradingFee(policy, boundaries.higherUp, quantity, timeToExpiryMs);\n\treturn lower + higher;\n}\n\n/** `expiry_market::builder_fee_amount` — an account carrying a builder code pays the builder a\n * multiple of its trading fee, capped as a share of quantity. */\nexport function builderFee(fee: bigint, quantity: bigint, hasBuilderCode: boolean): bigint {\n\tassertUint(fee, 'fee');\n\tassertUint(quantity, 'quantity');\n\tif (!hasBuilderCode) return 0n;\n\treturn min(mulDown(fee, BUILDER_FEE_MULTIPLIER), mulDown(quantity, MAX_BUILDER_FEE_RATE));\n}\n\n/** `expiry_market::fee_incentive_subsidy_amount` — a sponsor pays part of the trader's MINT\n * fee, bounded by the expiry's remaining sponsored balance. Mints only; redeems pay in full.\n * `rate` is the protocol's `fee_incentive_subsidy_rate` (1e9-scaled), 20% when omitted. */\nexport function feeIncentiveSubsidy(\n\tfee: bigint,\n\tfeeIncentiveBalance: bigint,\n\trate: bigint = FEE_INCENTIVE_SUBSIDY_RATE,\n): bigint {\n\tassertUint(fee, 'fee');\n\tassertUint(feeIncentiveBalance, 'feeIncentiveBalance');\n\tassertUint(rate, 'feeIncentiveSubsidyRate', FLOAT_SCALING);\n\treturn min(mulDown(fee, rate), feeIncentiveBalance);\n}\n\n/**\n * `ewma::penalty_fee`'s firing test, as a per-unit RATE: `penalty_rate` when the transaction's\n * gas price is a high outlier against the market's pre-trade EWMA, else zero. It is a rate and\n * not an amount because the surcharge is `rate · quantity`, and a budget search has to reprice\n * it at every candidate quantity. `gasPrice` is the raw reference gas price (not 1e9-scaled),\n * as `tx_context::gas_price` reports it.\n */\nexport function congestionPenaltyRate(\n\tpolicy: CongestionPolicy,\n\tstate: CongestionState,\n\tgasPrice: bigint,\n): bigint {\n\tassertUint(policy.penaltyRate, 'penaltyRate', FLOAT_SCALING);\n\tassertUint(policy.zScoreThreshold, 'zScoreThreshold');\n\tassertUint(state.mean, 'mean');\n\tassertUint(state.variance, 'variance');\n\tassertUint(gasPrice, 'gasPrice', U64_MAX / FLOAT_SCALING);\n\tif (!policy.enabled || state.variance === 0n) return 0n;\n\tconst scaled = gasPrice * FLOAT_SCALING;\n\tif (scaled <= state.mean) return 0n;\n\tconst zScore = divDown(scaled - state.mean, sqrtDown(state.variance));\n\tif (zScore <= policy.zScoreThreshold) return 0n;\n\treturn policy.penaltyRate;\n}\n\n// `strike_exposure::live_payout_liability_from_terms` — `M + lambda·(T − M)`.\nfunction payoutLiability(policy: FeePolicy, maxPayout: bigint, totalPayout: bigint): bigint {\n\treturn maxPayout + mulDown(policy.backingBufferLambda, totalPayout - maxPayout);\n}\n\n/**\n * `strike_exposure::inventory_impact_potential_for_liability` — the book-level potential\n * `phi(L)`: marginal rate rising linearly to `inventory_impact_max_rate` over the scale `B`,\n * flat at the cap above it. Trades are charged the DIFFERENCE of two evaluations, which is\n * what makes inventory cycles telescope to zero.\n */\nexport function inventoryImpactPotential(policy: FeePolicy, liability: bigint): bigint {\n\tassertFeePolicy(policy);\n\tassertUint(liability, 'liability');\n\tif (policy.inventoryImpactMaxRate === 0n || liability === 0n) return 0n;\n\tconst scale = policy.inventoryImpactScale;\n\tconst capped = min(liability, scale);\n\tconst utilization = mulDivDown(capped, FLOAT_SCALING, scale);\n\tconst marginalRate = mulDown(policy.inventoryImpactMaxRate, utilization);\n\tconst potentialAtCapped = mulDown(marginalRate, capped) / 2n;\n\tif (liability <= scale) return potentialAtCapped;\n\treturn potentialAtCapped + mulDown(policy.inventoryImpactMaxRate, liability - scale);\n}\n\n/** `strike_exposure::mint_range_inventory_impact` — the charge a mint of `quantity` over a\n * range pays: the exact rise in the book potential. Zero at the shipped rate of `0n`. */\nexport function mintInventoryImpact(\n\tpolicy: FeePolicy,\n\tbook: MintBookTerms,\n\tquantity: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBook(book);\n\tassertUint(quantity, 'quantity', U64_MAX - book.totalPayout);\n\tif (policy.inventoryImpactMaxRate === 0n || quantity === 0n) return 0n;\n\tconst before = payoutLiability(policy, book.maxPayout, book.totalPayout);\n\tconst after = payoutLiability(\n\t\tpolicy,\n\t\tmax(book.maxPayout, book.rangeMaxPayout + quantity),\n\t\tbook.totalPayout + quantity,\n\t);\n\treturn inventoryImpactPotential(policy, after) - inventoryImpactPotential(policy, before);\n}\n\n/** `strike_exposure::live_close_inventory_impact` — the rebate a live close of `payout`\n * receives: the exact fall in the same potential. Zero at the shipped rate of `0n`. */\nexport function closeInventoryImpact(\n\tpolicy: FeePolicy,\n\tbook: CloseBookTerms,\n\tpayout: bigint,\n): bigint {\n\tassertFeePolicy(policy);\n\tassertBook(book);\n\tassertUint(book.complementMaxPayout, 'complementMaxPayout', book.maxPayout);\n\tif (max(book.rangeMaxPayout, book.complementMaxPayout) !== book.maxPayout) {\n\t\tthrow new PredictInputError('maxPayout must equal the larger range or complement payout');\n\t}\n\tassertUint(payout, 'close payout', book.rangeMaxPayout);\n\tif (policy.inventoryImpactMaxRate === 0n || payout === 0n) return 0n;\n\tconst before = payoutLiability(policy, book.maxPayout, book.totalPayout);\n\tconst after = payoutLiability(\n\t\tpolicy,\n\t\tmax(book.rangeMaxPayout - payout, book.complementMaxPayout),\n\t\tbook.totalPayout - payout,\n\t);\n\treturn inventoryImpactPotential(policy, before) - inventoryImpactPotential(policy, after);\n}\n\n// === Probabilities ===\n\n/** `pricing::probability` — the range's own probability, `up(lower) − up(higher)` with the\n * chain's saturating subtraction and its infinite-boundary defaults. */\nexport function rangeProbability(boundaries: Boundaries): bigint {\n\tassertBoundaries(boundaries);\n\tconst lower = boundaries.lowerUp ?? FLOAT_SCALING;\n\tconst higher = boundaries.higherUp ?? 0n;\n\treturn lower > higher ? lower - higher : 0n;\n}\n\n// Float probability -> the chain's raw 1e9 domain, clamped like `compute_nd2`'s own clamp.\nfunction toRawProbability(p: number): bigint {\n\tif (!Number.isFinite(p)) throw new PredictInputError(`probability is not finite: ${p}`);\n\tconst raw = BigInt(Math.round(p * Number(FLOAT_SCALING)));\n\treturn raw < 0n ? 0n : raw > FLOAT_SCALING ? FLOAT_SCALING : raw;\n}\n\n/** Price a range's two boundaries with the local float pricer. `lower`/`upper` are strikes in\n * USD; pass `null` for an infinite side (`{ lower: strike, upper: null }` is an UP order,\n * `{ lower: null, upper: strike }` a DOWN order). Carries the pricer's ~1e-4 approximation. */\nexport function boundaryProbabilities(\n\tpricer: PricerInputs,\n\tlower: number | null,\n\tupper: number | null,\n): Boundaries {\n\treturn {\n\t\tlowerUp: lower === null ? null : toRawProbability(upProbability(pricer, lower)),\n\t\thigherUp: upper === null ? null : toRawProbability(upProbability(pricer, upper)),\n\t};\n}\n\nfunction resolveBoundaries(source: ProbabilitySource): { boundaries: Boundaries; exact: boolean } {\n\tlet boundaries: Boundaries;\n\tlet exact: boolean;\n\tif ('pricer' in source) {\n\t\tconst { lower, upper } = source;\n\t\tif (lower !== null && upper !== null && lower >= upper) {\n\t\t\tthrow new PredictInputError(`lower strike ${lower} must be below ${upper} (EInvalidRange)`);\n\t\t}\n\t\tboundaries = boundaryProbabilities(source.pricer, lower, upper);\n\t\texact = false;\n\t} else {\n\t\tboundaries = source;\n\t\texact = true;\n\t}\n\tassertBoundaries(boundaries);\n\t// `(-inf, +inf]` is the whole outcome space; `order::assert_valid_order_shape` rejects it.\n\tif (boundaries.lowerUp === null && boundaries.higherUp === null) {\n\t\tthrow new PredictInputError('a range cannot be infinite on both sides (EInvalidRange)');\n\t}\n\treturn { boundaries, exact };\n}\n\n// `number` is a human amount in USDC decimals, `bigint` is already raw — the SDK-wide\n// convention for every financial parameter.\nfunction rawAmount(value: number | bigint): bigint {\n\tconst raw = typeof value === 'bigint' ? value : usdcToRaw(value);\n\tassertUint(raw, 'amount');\n\treturn raw;\n}\n\nfunction rawMs(value: number | bigint): bigint {\n\tif (typeof value === 'number' && !Number.isSafeInteger(value)) {\n\t\tthrow new PredictInputError(`timestamp must be a safe integer in milliseconds, got ${value}`);\n\t}\n\tconst raw = typeof value === 'bigint' ? value : BigInt(value);\n\tassertUint(raw, 'timestamp');\n\treturn raw;\n}\n\n// === Mint ===\n\n/** Inputs shared by the exact-quantity mint quote and the budget-sized one. */\ninterface MintInputsBase {\n\t/** The market's snapshotted fee policy. */\n\tfees: FeePolicy;\n\t/** Market expiry, ms since epoch. */\n\texpiryMs: number | bigint;\n\t/** The clock the trade will price against, ms since epoch. Defaults to `Date.now()`. */\n\tnowMs?: number | bigint;\n\t/** Boundary probabilities, or a pricer snapshot plus the range's strikes. */\n\tprobabilities: ProbabilitySource;\n\t/**\n\t * Whether the minting account carries a builder code and pays the account-attached builder fee:\n\t * Predict v4 semantics. From Predict Version 5 an attached code charges nothing (a builder fee\n\t * is passed on each trade instead), so leave this `false` on a network running Version 5.\n\t */\n\tbuilderCode?: boolean;\n\t/** The expiry's remaining sponsored fee balance (`fee_incentive_balance`). Default `0n`. */\n\tfeeIncentiveBalance?: number | bigint;\n\t/**\n\t * The protocol's admin-set mint fee subsidy rate (`protocol_config::fee_incentive_subsidy_rate`),\n\t * 1e9-scaled. Defaults to the 20% the chain reads while unset.\n\t */\n\tfeeIncentiveSubsidyRate?: bigint;\n\t/**\n\t * Per-unit congestion surcharge rate — see {@link congestionPenaltyRate}. Default `0n`. A\n\t * queued (delayed-execution) fill pays no congestion penalty, so queued previews keep it 0.\n\t */\n\tpenaltyRate?: bigint;\n\t/** Pre-trade payout-tree terms. Required when inventory impact is enabled. */\n\tbook?: MintBookTerms;\n\t/** The deployment's `position_lot_size`. Defaults to the Move constant, `10_000n`. */\n\tlotSize?: bigint;\n}\n\n/** Inputs for {@link mintCost}: an exact payout quantity. */\nexport interface MintCostInputs extends MintInputsBase {\n\t/** Maximum payout bought, in quote units — `number` is human USD, `bigint` is raw. */\n\tquantity: number | bigint;\n}\n\n/** Inputs for {@link mintCostForBudget}: an all-in budget, the `mint_exact_cost` shape. */\nexport interface MintBudgetInputs extends MintInputsBase {\n\t/** The total to spend, fees included. */\n\tbudget: number | bigint;\n\t/** Floor on the fill; a smaller result aborts, as `mint_exact_cost` does. Default one lot. */\n\tminQuantity?: number | bigint;\n\t/** The account's settled USDC. The chain caps the budget at it before sizing; pass it to\n\t * reproduce that cap (and to let `U64_MAX` mean \"my whole balance\"). */\n\taccountBalance?: number | bigint;\n}\n\n/** One mint's cost decomposition — the fields of the chain's `MintQuote`, in human units with\n * the exact integers alongside. `cost` is the account debit. */\nexport interface MintCost {\n\t/** Maximum payout bought (human quote units). */\n\tquantity: number;\n\t/** Fill price, 0..1 per $1 of payout, before fees. */\n\tentryProbability: number;\n\t/** Premium into LP backing. */\n\tpremium: number;\n\t/** `referral` is not here: it is a split of protocol proceeds, not a trader debit. */\n\tfees: { trading: number; subsidy: number; builder: number; penalty: number; impact: number };\n\t/** All-in account debit: `premium + (trading − subsidy) + builder + penalty + impact`. */\n\tcost: number;\n\t/** All-in price per $1 of payout — `cost / quantity`, the number to compare across venues. */\n\tcostPerContract: number;\n\t/** Maximum payout divided by the all-in debit, including fees. */\n\tpayoutMultiple: number;\n\traw: {\n\t\tquantity: bigint;\n\t\tentryProbability: bigint;\n\t\tpremium: bigint;\n\t\ttradingFee: bigint;\n\t\tsubsidy: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\timpactCharge: bigint;\n\t\tcost: bigint;\n\t};\n\t/** True when boundary probabilities were supplied as raw integers rather than priced\n\t * locally in float. Does not verify their source, freshness or the other quote inputs. */\n\texactProbabilities: boolean;\n}\n\n/** Budget-sized mint plus the budget information needed to render an order preview. */\nexport interface MintBudgetCost extends Omit<MintCost, 'raw'> {\n\t/** Requested all-in budget, before the optional account-balance cap. */\n\tbudget: number;\n\t/** Budget after the optional account-balance cap. */\n\teffectiveBudget: number;\n\t/** Requested budget minus actual cost, including any balance-cap shortfall. */\n\tunspentBudget: number;\n\traw: MintCost['raw'] & {\n\t\tbudget: bigint;\n\t\teffectiveBudget: bigint;\n\t\tunspentBudget: bigint;\n\t};\n}\n\n// `strike_exposure_config::assert_mint_probability_policy`, applied where\n// `assert_range_mint_probability_policy` applies it: each finite leg and the range itself.\nfunction assertProbabilityPolicy(policy: FeePolicy, probability: bigint): void {\n\tif (probability < policy.minEntryProbability || probability > policy.maxEntryProbability) {\n\t\tthrow new PredictInputError(\n\t\t\t`entry probability ${probability} outside the market's [${policy.minEntryProbability}, ` +\n\t\t\t\t`${policy.maxEntryProbability}] admission band (EEntryProbabilityOutOfBounds)`,\n\t\t);\n\t}\n}\n\nfunction assertRangeMintPolicy(policy: FeePolicy, boundaries: Boundaries): void {\n\tif (boundaries.lowerUp !== null) assertProbabilityPolicy(policy, boundaries.lowerUp);\n\tif (boundaries.higherUp !== null) {\n\t\tassertProbabilityPolicy(policy, FLOAT_SCALING - boundaries.higherUp);\n\t}\n\tassertProbabilityPolicy(policy, rangeProbability(boundaries));\n}\n\nfunction assertValidQuantity(quantity: bigint, lotSize: bigint): void {\n\tif (quantity <= 0n || quantity % lotSize !== 0n || quantity / lotSize > MAX_QUANTITY_LOTS) {\n\t\tthrow new PredictInputError(\n\t\t\t`quantity ${quantity} must be a positive multiple of the ${lotSize} lot size, at most ` +\n\t\t\t\t`${MAX_QUANTITY_LOTS} lots (EInvalidQuantity)`,\n\t\t);\n\t}\n}\n\nfunction timeToExpiry(expiryMs: bigint, nowMs: bigint): bigint {\n\tif (nowMs >= expiryMs) {\n\t\tthrow new PredictInputError(\n\t\t\t`market expired at ${expiryMs}; a live trade at ${nowMs} aborts (ELivePricingExpired)`,\n\t\t);\n\t}\n\treturn expiryMs - nowMs;\n}\n\n// The all-in sum, `expiry_market::mint_quote_at`, with no admission checks — the one place the\n// cost is assembled, shared by the quote and the budget search exactly as the contract shares\n// it. Rounding order is the chain's: every component is floored before it is summed.\nfunction mintQuoteAt(\n\tinputs: MintInputsBase,\n\tboundaries: Boundaries,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): {\n\tpremium: bigint;\n\tfee: bigint;\n\tsubsidy: bigint;\n\tbuilder: bigint;\n\tpenalty: bigint;\n\timpact: bigint;\n\tcost: bigint;\n} {\n\tconst premium = mulDown(rangeProbability(boundaries), quantity);\n\tconst fee = tradingFee(inputs.fees, boundaries, quantity, timeToExpiryMs);\n\tconst subsidy = feeIncentiveSubsidy(\n\t\tfee,\n\t\trawAmount(inputs.feeIncentiveBalance ?? 0n),\n\t\tinputs.feeIncentiveSubsidyRate,\n\t);\n\tconst builder = builderFee(fee, quantity, inputs.builderCode ?? false);\n\tconst penalty = mulDown(inputs.penaltyRate ?? 0n, quantity);\n\tconst impact = inputs.book ? mintInventoryImpact(inputs.fees, inputs.book, quantity) : 0n;\n\treturn {\n\t\tpremium,\n\t\tfee,\n\t\tsubsidy,\n\t\tbuilder,\n\t\tpenalty,\n\t\timpact,\n\t\tcost: premium + (fee - subsidy) + builder + penalty + impact,\n\t};\n}\n\nfunction mintCostFrom(\n\tinputs: MintInputsBase,\n\tboundaries: Boundaries,\n\texact: boolean,\n\tquantity: bigint,\n\ttimeToExpiryMs: bigint,\n): MintCost {\n\tconst q = mintQuoteAt(inputs, boundaries, quantity, timeToExpiryMs);\n\tconst probability = rangeProbability(boundaries);\n\treturn {\n\t\tquantity: fromRaw(quantity, 6),\n\t\tentryProbability: fromRaw(probability, 9),\n\t\tpremium: fromRaw(q.premium, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(q.fee, 6),\n\t\t\tsubsidy: fromRaw(q.subsidy, 6),\n\t\t\tbuilder: fromRaw(q.builder, 6),\n\t\t\tpenalty: fromRaw(q.penalty, 6),\n\t\t\timpact: fromRaw(q.impact, 6),\n\t\t},\n\t\tcost: fromRaw(q.cost, 6),\n\t\tcostPerContract: quantity === 0n ? 0 : Number(q.cost) / Number(quantity),\n\t\tpayoutMultiple: Number(quantity) / Number(q.cost),\n\t\traw: {\n\t\t\tquantity,\n\t\t\tentryProbability: probability,\n\t\t\tpremium: q.premium,\n\t\t\ttradingFee: q.fee,\n\t\t\tsubsidy: q.subsidy,\n\t\t\tbuilderFee: q.builder,\n\t\t\tpenaltyFee: q.penalty,\n\t\t\timpactCharge: q.impact,\n\t\t\tcost: q.cost,\n\t\t},\n\t\texactProbabilities: exact,\n\t};\n}\n\n/**\n * All-in cost of minting an exact payout quantity — the `mint_exact_quantity` shape, priced\n * entirely client-side. Mirrors `compute_mint_quote`, including its admission checks: the\n * entry-probability band on each finite leg and on the range, the `min_premium` floor, the lot\n * grid, and the `all_in_cost <= quantity` bound (a contract may never cost more than it can\n * pay out). Each violation throws the `PredictInputError` naming the abort the chain would\n * have raised.\n */\nexport function mintCost(inputs: MintCostInputs): MintCost {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst quantity = rawAmount(inputs.quantity);\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\n\tassertRangeMintPolicy(inputs.fees, boundaries);\n\tconst premium = mulDown(rangeProbability(boundaries), quantity);\n\tif (premium < MIN_PREMIUM) {\n\t\tthrow new PredictInputError(\n\t\t\t`premium ${premium} is below the ${MIN_PREMIUM} minimum (EPremiumBelowMinimum)`,\n\t\t);\n\t}\n\tassertValidQuantity(quantity, lotSize);\n\n\tconst quote = mintCostFrom(inputs, boundaries, exact, quantity, ttl);\n\tif (quote.raw.cost > quantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`all-in cost ${quote.raw.cost} exceeds the maximum payout ${quantity} ` +\n\t\t\t\t`(EMintCostAboveMaxPayout)`,\n\t\t);\n\t}\n\treturn quote;\n}\n\n/**\n * A fill whose ALL-IN cost fits a budget — `expiry_market::mint_exact_cost` computed\n * client-side, with the same lot search over the same cost function, so the answer is the\n * quantity that entrypoint would size and the cost it would debit.\n *\n * Without it a \"spend exactly $X\" flow has to guess: every fee is charged ON TOP of the\n * premium, so the caller subtracts an estimated fee load, pads it against an abort, and\n * systematically underspends. Here the whole search runs locally; submit the all-in budget\n * through `tx.mintCost` on deployments carrying `mint_exact_cost`.\n *\n * Sizing also respects the fill's maximum payout and the 32-bit lot cap; either can leave\n * substantial budget unspent. When only the budget binds, one more lot would exceed it.\n * If the budget fill exceeds its maximum payout, the contract's step-down is best effort:\n * rounding can make it miss a larger admissible fill, including one meeting `minQuantity`.\n * The chain caps the budget at the account balance first ({@link MintBudgetInputs.accountBalance}).\n */\nexport function mintCostForBudget(inputs: MintBudgetInputs): MintBudgetCost {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\tconst minQuantity = inputs.minQuantity === undefined ? lotSize : rawAmount(inputs.minQuantity);\n\tconst requestedBudget = rawAmount(inputs.budget);\n\tlet budget = requestedBudget;\n\tif (inputs.accountBalance !== undefined) budget = min(budget, rawAmount(inputs.accountBalance));\n\n\tassertRangeMintPolicy(inputs.fees, boundaries);\n\n\t// `strike_exposure::max_quantity_for_premium` — the premium-only fit bounds the all-in\n\t// fit from above, because every other term is non-negative.\n\tconst probability = rangeProbability(boundaries);\n\tlet lo = 0n;\n\tlet hi = MAX_QUANTITY_LOTS;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi + 1n) / 2n;\n\t\tif (mulDown(probability, mid * lotSize) <= budget) lo = mid;\n\t\telse hi = mid - 1n;\n\t}\n\n\t// `expiry_market::quote_exact_cost_terms`, first half: the budget search proper. Exact,\n\t// because every all-in term is nondecreasing in quantity for fixed pre-trade state.\n\tconst allInCostAt = (quantity: bigint) => mintQuoteAt(inputs, boundaries, quantity, ttl).cost;\n\thi = lo;\n\tlo = 0n;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi + 1n) / 2n;\n\t\tif (allInCostAt(mid * lotSize) <= budget) lo = mid;\n\t\telse hi = mid - 1n;\n\t}\n\tconst budgetLots = lo;\n\tconst budgetQuantity = budgetLots * lotSize;\n\n\t// Second half: the maximum-payout bound (`cost <= quantity`) is deliberately NOT part of\n\t// that search. It is not monotone — cost and quantity both rise, and the independent floors\n\t// in each cost term let `cost(q) <= q` flip back to true at a larger lot wherever unit cost\n\t// sits within rounding of one — so binary-searching it would discard admissible fills. It is\n\t// consulted only when the budget fill breaches it, and the step-down runs strictly below\n\t// that fill, so every candidate already fits the budget.\n\t// This fallback mirrors Move's best-effort search; its nonmonotone predicate means it\n\t// can miss larger admissible fills, including one satisfying minQuantity.\n\tlet lots = budgetLots;\n\tif (budgetLots > 0n && allInCostAt(budgetQuantity) > budgetQuantity) {\n\t\tlet stepLo = 0n;\n\t\tlet stepHi = budgetLots - 1n;\n\t\twhile (stepLo < stepHi) {\n\t\t\tconst mid = (stepLo + stepHi + 1n) / 2n;\n\t\t\tconst candidate = mid * lotSize;\n\t\t\tif (allInCostAt(candidate) <= candidate) stepLo = mid;\n\t\t\telse stepHi = mid - 1n;\n\t\t}\n\t\t// No admissible smaller fill: fall back to the budget fill, which then fails the\n\t\t// maximum-payout bound below exactly as the chain's own quote aborts on it.\n\t\tlots = stepLo === 0n ? budgetLots : stepLo;\n\t}\n\n\tconst quantity = lots * lotSize;\n\tif (quantity < minQuantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`budget ${budget} sizes ${quantity}, below the ${minQuantity} minimum ` +\n\t\t\t\t`(EMintQuantityBelowMin)`,\n\t\t);\n\t}\n\tconst premium = mulDown(probability, quantity);\n\tif (premium < MIN_PREMIUM) {\n\t\tthrow new PredictInputError(\n\t\t\t`budget ${budget} sizes a premium of ${premium}, below the ${MIN_PREMIUM} minimum ` +\n\t\t\t\t`(EPremiumBelowMinimum)`,\n\t\t);\n\t}\n\tassertValidQuantity(quantity, lotSize);\n\tconst quote = mintCostFrom(inputs, boundaries, exact, quantity, ttl);\n\tif (quote.raw.cost > quantity) {\n\t\tthrow new PredictInputError(\n\t\t\t`sized fill inside budget ${budget} costs more than it can pay out: ${quote.raw.cost} ` +\n\t\t\t\t`exceeds ${quantity} (EMintCostAboveMaxPayout)`,\n\t\t);\n\t}\n\treturn {\n\t\t...quote,\n\t\tbudget: fromRaw(requestedBudget, 6),\n\t\teffectiveBudget: fromRaw(budget, 6),\n\t\tunspentBudget: fromRaw(requestedBudget - quote.raw.cost, 6),\n\t\traw: {\n\t\t\t...quote.raw,\n\t\t\tbudget: requestedBudget,\n\t\t\teffectiveBudget: budget,\n\t\t\tunspentBudget: requestedBudget - quote.raw.cost,\n\t\t},\n\t};\n}\n\n// === Live redeem ===\n\n/** Inputs for {@link redeemLiveProceeds}. The range is the ORDER's own range — the same two\n * boundaries it was minted over, which is what `redeem_live` reprices. */\nexport interface RedeemLiveInputs {\n\tfees: FeePolicy;\n\texpiryMs: number | bigint;\n\tnowMs?: number | bigint;\n\t/** The order's boundary probabilities now, or a pricer snapshot plus the order's strikes. */\n\tprobabilities: ProbabilitySource;\n\t/** Payout being closed — the whole order, or part of it. */\n\tcloseQuantity: number | bigint;\n\t/** Current position payout quantity, when known. Validates the close and returns the remainder. */\n\tpositionQuantity?: number | bigint;\n\t/**\n\t * Whether the selling account pays the account-attached builder fee: Predict v4 semantics.\n\t * Leave it `false` on a network running Version 5, where an attached code charges nothing.\n\t */\n\tbuilderCode?: boolean;\n\tpenaltyRate?: bigint;\n\t/** Pre-trade payout-tree terms. Required when inventory impact is enabled. */\n\tbook?: CloseBookTerms;\n\tlotSize?: bigint;\n}\n\n/** What a live close credits the account, decomposed. */\nexport interface RedeemLiveProceeds {\n\t/** NET credited to the account. */\n\tproceeds: number;\n\t/** Close value before fees: the range's current probability times the closed payout. */\n\tgross: number;\n\tfees: { trading: number; builder: number; penalty: number; impactRebate: number };\n\tquantityClosed: number;\n\t/** Unclosed payout quantity, or null when positionQuantity was not supplied. */\n\tremainingQuantity: number | null;\n\t/** Net credited per $1 of closed payout; includes fees and the inventory rebate. */\n\tproceedsPerContract: number;\n\t/** Current range probability, 0..1, before amount rounding and fees. */\n\tprobability: number;\n\traw: {\n\t\tproceeds: bigint;\n\t\tgross: bigint;\n\t\ttradingFee: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\timpactRebate: bigint;\n\t\tquantityClosed: bigint;\n\t\tremainingQuantity: bigint | null;\n\t\t/** 1e9-scaled range probability; locally priced inputs remain approximate. */\n\t\tprobability: bigint;\n\t};\n\t/** Identifies raw probability inputs; does not verify their source or state freshness. */\n\texactProbabilities: boolean;\n}\n\n/**\n * Net proceeds of closing a live position — `expiry_market::redeem_live`'s payment\n * decomposition, client-side. The mirror of {@link mintCost}: the same per-boundary trading\n * fee and builder fee, the same congestion surcharge, and the inventory-impact term as a\n * REBATE rather than a charge. There is no sponsor subsidy on a close (incentives subsidise\n * mints only), and each deduction is clamped at the payout remaining after the ones before it,\n * exactly as the contract clamps them, so a close can never cost more than it releases.\n *\n * Use this for a local UI preview from a supplied snapshot. `read.quoteRedeem` simulates\n * the actual close and remains the pre-trade check for ownership, remaining position size,\n * live-market gates and current fees. `proceeds` is what `min_proceeds` is compared against\n * on the real call; this preview does not guarantee execution at that amount.\n */\nexport function redeemLiveProceeds(inputs: RedeemLiveInputs): RedeemLiveProceeds {\n\tassertCostInputs(inputs);\n\tconst { boundaries, exact } = resolveBoundaries(inputs.probabilities);\n\tconst lotSize = inputs.lotSize ?? POSITION_LOT_SIZE;\n\tconst quantity = rawAmount(inputs.closeQuantity);\n\tconst ttl = timeToExpiry(rawMs(inputs.expiryMs), rawMs(inputs.nowMs ?? Date.now()));\n\tassertValidQuantity(quantity, lotSize);\n\n\tconst positionQuantity =\n\t\tinputs.positionQuantity === undefined ? null : rawAmount(inputs.positionQuantity);\n\tif (positionQuantity !== null) {\n\t\tassertValidQuantity(positionQuantity, lotSize);\n\t\tif (quantity > positionQuantity)\n\t\t\tthrow new PredictInputError('closeQuantity exceeds positionQuantity');\n\t}\n\tconst remainingQuantity = positionQuantity === null ? null : positionQuantity - quantity;\n\tconst probability = rangeProbability(boundaries);\n\tconst gross = mulDown(probability, quantity);\n\tconst fee = min(tradingFee(inputs.fees, boundaries, quantity, ttl), gross);\n\tconst builder = min(builderFee(fee, quantity, inputs.builderCode ?? false), gross - fee);\n\tconst penalty = min(mulDown(inputs.penaltyRate ?? 0n, quantity), gross - fee - builder);\n\tconst rebate = inputs.book ? closeInventoryImpact(inputs.fees, inputs.book, quantity) : 0n;\n\tconst proceeds = gross + rebate - fee - builder - penalty;\n\n\treturn {\n\t\tproceeds: fromRaw(proceeds, 6),\n\t\tgross: fromRaw(gross, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(fee, 6),\n\t\t\tbuilder: fromRaw(builder, 6),\n\t\t\tpenalty: fromRaw(penalty, 6),\n\t\t\timpactRebate: fromRaw(rebate, 6),\n\t\t},\n\t\tquantityClosed: fromRaw(quantity, 6),\n\t\tremainingQuantity: remainingQuantity === null ? null : fromRaw(remainingQuantity, 6),\n\t\tproceedsPerContract: Number(proceeds) / Number(quantity),\n\t\tprobability: fromRaw(probability, 9),\n\t\traw: {\n\t\t\tproceeds,\n\t\t\tgross,\n\t\t\ttradingFee: fee,\n\t\t\tbuilderFee: builder,\n\t\t\tpenaltyFee: penalty,\n\t\t\timpactRebate: rebate,\n\t\t\tquantityClosed: quantity,\n\t\t\tremainingQuantity,\n\t\t\tprobability,\n\t\t},\n\t\texactProbabilities: exact,\n\t};\n}\n\n// === Order IDs ===\n\nconst QUANTITY_LOTS_OFFSET = 100n;\nconst LOWER_TICK_OFFSET = 70n;\nconst HIGHER_TICK_OFFSET = 40n;\nconst TICK_MASK = POS_INF_TICK; // `constants::pos_inf_tick` is the full 30-bit mask\n/** `constants::pos_inf_tick` — the +∞ sentinel in an order's higher-tick field. */\nexport { POS_INF_TICK };\nconst U32_MASK = (1n << 32n) - 1n;\n\n/** The contract terms packed into an order ID (`deepbook_predict::order`). Tick `0` as the\n * lower bound is −∞ and {@link POS_INF_TICK} as the higher is +∞; multiply a finite tick by\n * the market's `tickSize` for its raw strike. Use it to feed a position from `read.positions`\n * into {@link redeemLiveProceeds}. */\nexport interface OrderRange {\n\tlowerTick: bigint;\n\thigherTick: bigint;\n\t/** Minted payout: `quantity_lots · position_lot_size`. */\n\tquantity: bigint;\n}\n\n/** Decode an order ID's range and quantity — the TypeScript mirror of `order::lower_tick` /\n * `higher_tick` / `quantity`. */\nexport function decodeOrderRange(orderId: bigint, lotSize: bigint = POSITION_LOT_SIZE): OrderRange {\n\treturn {\n\t\tlowerTick: (orderId >> LOWER_TICK_OFFSET) & TICK_MASK,\n\t\thigherTick: (orderId >> HIGHER_TICK_OFFSET) & TICK_MASK,\n\t\tquantity: ((orderId >> QUANTITY_LOTS_OFFSET) & U32_MASK) * lotSize,\n\t};\n}\n\n/**\n * What an order pays at settlement, raw USDC: its full quantity when the settlement price lies\n * in `(lower, higher]`, else 0. The mirror of `strike_exposure::settled_order_payout`, which\n * rounds the settlement price up to the market's tick grid (`range_codec::limit_tick`) before\n * comparing it with the order's ticks, so a price inside a tick counts as that tick's upper edge.\n * Pass `read.settlement`'s `settlementPriceRaw` and `tickSizeRaw`, and the config's\n * `units.positionLotSize` when it isn't the default.\n */\nexport function settledPayout(\n\torderId: bigint,\n\tsettlementPriceRaw: bigint,\n\ttickSizeRaw: bigint,\n\tlotSize: bigint = POSITION_LOT_SIZE,\n): bigint {\n\tif (tickSizeRaw <= 0n) throw new PredictInputError('tickSizeRaw must be positive');\n\tconst { lowerTick, higherTick, quantity } = decodeOrderRange(orderId, lotSize);\n\tconst limit = (settlementPriceRaw + tickSizeRaw - 1n) / tickSizeRaw;\n\tconst inRange = lowerTick < limit && (higherTick === POS_INF_TICK || limit <= higherTick);\n\treturn inRange ? quantity : 0n;\n}\n\n/** The strikes an {@link OrderRange} prices against, in USD, with `null` for each infinite\n * side — the shape {@link boundaryProbabilities} takes. `tickSize` is the market's raw tick\n * size (`ActiveMarket.tickSize` in USD, or the raw value from the deployment). */\nexport function orderStrikes(\n\trange: OrderRange,\n\ttickSizeRaw: bigint,\n): { lower: number | null; upper: number | null } {\n\treturn {\n\t\tlower: range.lowerTick === 0n ? null : fromRaw(range.lowerTick * tickSizeRaw, 9),\n\t\tupper: range.higherTick === POS_INF_TICK ? null : fromRaw(range.higherTick * tickSizeRaw, 9),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,gBAAgB;;AAE7B,MAAa,oBAAoB;;AAEjC,MAAa,cAAc;;AAE3B,MAAa,yBAAyB;;AAEtC,MAAa,uBAAuB;;;;;;;;;AASpC,MAAa,6BAA6B;;AAE1C,MAAa,qBAAqB,MAAM,OAAO;AAI/C,MAAM,WAAW,GAAW,MAAuB,IAAI,IAAK;AAC5D,MAAM,WAAW,GAAW,MAAuB,IAAI,gBAAiB;AACxE,MAAM,cAAc,GAAW,GAAW,gBAAiC,IAAI,IAAK;AACpF,MAAM,OAAO,GAAW,MAAuB,IAAI,IAAI,IAAI;AAC3D,MAAM,OAAO,GAAW,MAAuB,IAAI,IAAI,IAAI;AAG3D,SAAS,WAAW,OAAe,MAAc,UAAU,SAAS,UAAU,IAAU;AACvF,KAAI,OAAO,UAAU,YAAY,QAAQ,WAAW,QAAQ,QAC3D,OAAM,IAAI,kBACT,GAAG,KAAK,0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