import { PricerInputs } from "./pricing.mjs"; import { POS_INF_TICK } from "./ticks.mjs"; //#region src/predict/cost.d.ts declare namespace cost_d_exports { export { BUILDER_FEE_MULTIPLIER, Boundaries, CloseBookTerms, CongestionPolicy, CongestionState, FEE_INCENTIVE_SUBSIDY_RATE, FLOAT_SCALING, FeePolicy, MAX_BUILDER_FEE_RATE, MAX_QUANTITY_LOTS, MIN_PREMIUM, MintBookTerms, MintBudgetCost, MintBudgetInputs, MintCost, MintCostInputs, OrderRange, POSITION_LOT_SIZE, POS_INF_TICK, ProbabilitySource, RedeemLiveInputs, RedeemLiveProceeds, SHIPPED_FEE_POLICY, bernoulliFeeRate, boundaryProbabilities, builderFee, closeInventoryImpact, congestionPenaltyRate, decodeOrderRange, expiryFeeMultiplier, feeIncentiveSubsidy, inventoryImpactPotential, mintCost, mintCostForBudget, mintInventoryImpact, orderStrikes, rangeProbability, redeemLiveProceeds, settledPayout, sqrtDown, tradingFee }; } /** `math::float_scaling` — 1e9 is 1.0 for every rate and probability here. */ declare const FLOAT_SCALING = 1000000000n; /** `constants::position_lot_size` — quantity is an integer number of these. */ declare const POSITION_LOT_SIZE = 10000n; /** `constants::min_premium` — a mint below this premium aborts `EPremiumBelowMinimum`. */ declare const MIN_PREMIUM = 1000000n; /** `constants::builder_fee_multiplier` — the builder's cut of the trading fee (10%). */ declare const BUILDER_FEE_MULTIPLIER = 100000000n; /** `constants::max_builder_fee_rate` — cap on the builder fee as a share of quantity (0.5%). */ declare const MAX_BUILDER_FEE_RATE = 5000000n; /** * The default sponsor share of a trader's mint fee (20%), and the rate the chain reads while the * admin hasn't set one. * @deprecated From delayed execution (DBU-885) the rate is admin-set: read it with * `protocol_config::fee_incentive_subsidy_rate` (`read.queue(...).protocol.feeIncentiveSubsidyRate`) * and pass it as `feeIncentiveSubsidyRate`. A hardcoded 20% underquotes every mint once the rate * moves. */ declare const FEE_INCENTIVE_SUBSIDY_RATE = 200000000n; /** `order::max_quantity_lots` — the order ID's 32-bit lot field. */ declare const MAX_QUANTITY_LOTS: bigint; /** `math::sqrt_down` — square root of a 1e9-scaled value, 1e9-scaled, rounded down. */ declare function sqrtDown(x: bigint): bigint; /** * One market's fee policy: the `StrikeExposureConfig` it snapshotted at creation, in raw 1e9 * rates. Snapshotted means later admin changes do NOT reprice a market already trading, so * read it per market with `read.feePolicy(market)` (the `MarketCreated` event carries every field * too) rather than assuming the template. The last three are the inventory-impact parameters, inert while * `inventoryImpactMaxRate` is `0n` (the shipped value). */ interface FeePolicy { /** `base_fee` — multiplies `sqrt(p·(1−p))`. */ baseFee: bigint; /** `min_fee` — per-unit floor, applied per boundary leg before the ramp. */ minFee: bigint; /** `expiry_fee_window_ms` — window before expiry over which the fee ramps. */ expiryFeeWindowMs: bigint; /** `expiry_fee_max_multiplier` — multiplier reached at expiry; 1e9 disables the ramp. */ expiryFeeMaxMultiplier: bigint; /** `min_entry_probability` — mint admission floor on the entry probability. */ minEntryProbability: bigint; /** `max_entry_probability` — mint admission ceiling on the entry probability. */ maxEntryProbability: bigint; /** `inventory_impact_max_rate` — maximum marginal impact rate; `0n` disables impact. */ inventoryImpactMaxRate: bigint; /** `inventory_impact_scale` — the market's `max_expiry_allocation`, the curve's `B`. */ inventoryImpactScale: bigint; /** `backing_buffer_lambda` — the buffer on non-peak payout in the liability formula. */ backingBufferLambda: bigint; } /** * The shipped template (`config_constants` defaults): 10% Bernoulli fee, a 2.2% per-leg floor, * a one-day ramp window that is inert at a 1.0 multiplier, a 1%–99% entry band, and inventory * impact disabled. Neither recorded deployment's template matches it any more: both charge a * 20.4% Bernoulli fee, ramp it to 3× over the last 60 s and admit entries in 25%–75% (checked * 2026-10-09), so a live market's costs from this policy come out low. Pass * `read.feePolicy(market)` instead. This stays for tests and for a deployment still on the * defaults. */ declare const SHIPPED_FEE_POLICY: FeePolicy; /** A range's two boundary UP probabilities, raw 1e9. `null` is an infinite boundary — the * −∞ lower of a DOWN order and the +∞ higher of an UP order — which is priced at the digital * limit and pays no fee leg. */ interface Boundaries { /** `P(settle > lower)`, or `null` for the −∞ lower bound. */ lowerUp: bigint | null; /** `P(settle > higher)`, or `null` for the +∞ higher bound. */ higherUp: bigint | null; } /** Where a quote's probabilities come from: boundary probabilities you already hold (raw 1e9, * e.g. `probabilityToRaw((await read.price(...)).up)`) or a local pricer snapshot plus * the range's strikes in USD (`null` for an infinite side). */ type ProbabilitySource = Boundaries | { pricer: PricerInputs; lower: number | null; upper: number | null; }; /** The market's gas-price EWMA (`ewma::EwmaState`), both fields 1e9-scaled. */ interface CongestionState { mean: bigint; variance: bigint; } /** The protocol's congestion knobs (`EwmaConfig`). Shipped disabled. */ interface CongestionPolicy { enabled: boolean; /** `penalty_rate` — per-unit surcharge charged when the z-score fires. */ penaltyRate: bigint; /** `z_score_threshold` — how many standard deviations above the mean gas must sit. */ zScoreThreshold: bigint; } /** Pre-trade payout-tree reads a mint's inventory-impact charge is evaluated against * (`strike_exposure::quote_mint_range`). All in quote units. */ interface MintBookTerms { /** `M` — largest summed net payout at any one settlement price. */ maxPayout: bigint; /** `T` — sum of every live order's payout. */ totalPayout: bigint; /** The payout peak inside the mint's own `(lower, higher]`. */ rangeMaxPayout: bigint; } /** The same reads for a live close, which also needs the peak OUTSIDE the order's range * (`strike_exposure::live_close_inventory_impact`). */ interface CloseBookTerms extends MintBookTerms { /** The payout peak in the complement of the order's range. */ complementMaxPayout: bigint; } /** `strike_exposure_config::raw_bernoulli_fee_rate` — `base_fee · sqrt(p·(1−p))`, the fee rate * before the `min_fee` floor and the expiry ramp. Zero at the certain ends. */ declare function bernoulliFeeRate(baseFee: bigint, probability: bigint): bigint; /** `strike_exposure_config::expiry_fee_multiplier` — 1.0 outside the window, rising linearly * to `expiry_fee_max_multiplier` at expiry. */ declare function expiryFeeMultiplier(policy: FeePolicy, timeToExpiryMs: bigint): bigint; /** * `strike_exposure_config::trading_fee` — the fee for a whole range, charged PER FINITE * BOUNDARY with each leg floored and ramped independently. A binary order has one finite * boundary and pays one leg; a two-sided range pays two, so it is not the same fee as the * range's own probability would suggest. */ declare function tradingFee(policy: FeePolicy, boundaries: Boundaries, quantity: bigint, timeToExpiryMs: bigint): bigint; /** `expiry_market::builder_fee_amount` — an account carrying a builder code pays the builder a * multiple of its trading fee, capped as a share of quantity. */ declare function builderFee(fee: bigint, quantity: bigint, hasBuilderCode: boolean): bigint; /** `expiry_market::fee_incentive_subsidy_amount` — a sponsor pays part of the trader's MINT * fee, bounded by the expiry's remaining sponsored balance. Mints only; redeems pay in full. * `rate` is the protocol's `fee_incentive_subsidy_rate` (1e9-scaled), 20% when omitted. */ declare function feeIncentiveSubsidy(fee: bigint, feeIncentiveBalance: bigint, rate?: bigint): bigint; /** * `ewma::penalty_fee`'s firing test, as a per-unit RATE: `penalty_rate` when the transaction's * gas price is a high outlier against the market's pre-trade EWMA, else zero. It is a rate and * not an amount because the surcharge is `rate · quantity`, and a budget search has to reprice * it at every candidate quantity. `gasPrice` is the raw reference gas price (not 1e9-scaled), * as `tx_context::gas_price` reports it. */ declare function congestionPenaltyRate(policy: CongestionPolicy, state: CongestionState, gasPrice: bigint): bigint; /** * `strike_exposure::inventory_impact_potential_for_liability` — the book-level potential * `phi(L)`: marginal rate rising linearly to `inventory_impact_max_rate` over the scale `B`, * flat at the cap above it. Trades are charged the DIFFERENCE of two evaluations, which is * what makes inventory cycles telescope to zero. */ declare function inventoryImpactPotential(policy: FeePolicy, liability: bigint): bigint; /** `strike_exposure::mint_range_inventory_impact` — the charge a mint of `quantity` over a * range pays: the exact rise in the book potential. Zero at the shipped rate of `0n`. */ declare function mintInventoryImpact(policy: FeePolicy, book: MintBookTerms, quantity: bigint): bigint; /** `strike_exposure::live_close_inventory_impact` — the rebate a live close of `payout` * receives: the exact fall in the same potential. Zero at the shipped rate of `0n`. */ declare function closeInventoryImpact(policy: FeePolicy, book: CloseBookTerms, payout: bigint): bigint; /** `pricing::probability` — the range's own probability, `up(lower) − up(higher)` with the * chain's saturating subtraction and its infinite-boundary defaults. */ declare function rangeProbability(boundaries: Boundaries): bigint; /** Price a range's two boundaries with the local float pricer. `lower`/`upper` are strikes in * USD; pass `null` for an infinite side (`{ lower: strike, upper: null }` is an UP order, * `{ lower: null, upper: strike }` a DOWN order). Carries the pricer's ~1e-4 approximation. */ declare function boundaryProbabilities(pricer: PricerInputs, lower: number | null, upper: number | null): Boundaries; /** Inputs shared by the exact-quantity mint quote and the budget-sized one. */ interface MintInputsBase { /** The market's snapshotted fee policy. */ fees: FeePolicy; /** Market expiry, ms since epoch. */ expiryMs: number | bigint; /** The clock the trade will price against, ms since epoch. Defaults to `Date.now()`. */ nowMs?: number | bigint; /** Boundary probabilities, or a pricer snapshot plus the range's strikes. */ probabilities: ProbabilitySource; /** * Whether the minting account carries a builder code and pays the account-attached builder fee: * Predict v4 semantics. From Predict Version 5 an attached code charges nothing (a builder fee * is passed on each trade instead), so leave this `false` on a network running Version 5. */ builderCode?: boolean; /** The expiry's remaining sponsored fee balance (`fee_incentive_balance`). Default `0n`. */ feeIncentiveBalance?: number | bigint; /** * The protocol's admin-set mint fee subsidy rate (`protocol_config::fee_incentive_subsidy_rate`), * 1e9-scaled. Defaults to the 20% the chain reads while unset. */ feeIncentiveSubsidyRate?: bigint; /** * Per-unit congestion surcharge rate — see {@link congestionPenaltyRate}. Default `0n`. A * queued (delayed-execution) fill pays no congestion penalty, so queued previews keep it 0. */ penaltyRate?: bigint; /** Pre-trade payout-tree terms. Required when inventory impact is enabled. */ book?: MintBookTerms; /** The deployment's `position_lot_size`. Defaults to the Move constant, `10_000n`. */ lotSize?: bigint; } /** Inputs for {@link mintCost}: an exact payout quantity. */ interface MintCostInputs extends MintInputsBase { /** Maximum payout bought, in quote units — `number` is human USD, `bigint` is raw. */ quantity: number | bigint; } /** Inputs for {@link mintCostForBudget}: an all-in budget, the `mint_exact_cost` shape. */ interface MintBudgetInputs extends MintInputsBase { /** The total to spend, fees included. */ budget: number | bigint; /** Floor on the fill; a smaller result aborts, as `mint_exact_cost` does. Default one lot. */ minQuantity?: number | bigint; /** The account's settled USDC. The chain caps the budget at it before sizing; pass it to * reproduce that cap (and to let `U64_MAX` mean "my whole balance"). */ accountBalance?: number | bigint; } /** One mint's cost decomposition — the fields of the chain's `MintQuote`, in human units with * the exact integers alongside. `cost` is the account debit. */ interface MintCost { /** Maximum payout bought (human quote units). */ quantity: number; /** Fill price, 0..1 per $1 of payout, before fees. */ entryProbability: number; /** Premium into LP backing. */ premium: number; /** `referral` is not here: it is a split of protocol proceeds, not a trader debit. */ fees: { trading: number; subsidy: number; builder: number; penalty: number; impact: number; }; /** All-in account debit: `premium + (trading − subsidy) + builder + penalty + impact`. */ cost: number; /** All-in price per $1 of payout — `cost / quantity`, the number to compare across venues. */ costPerContract: number; /** Maximum payout divided by the all-in debit, including fees. */ payoutMultiple: number; raw: { quantity: bigint; entryProbability: bigint; premium: bigint; tradingFee: bigint; subsidy: bigint; builderFee: bigint; penaltyFee: bigint; impactCharge: bigint; cost: bigint; }; /** True when boundary probabilities were supplied as raw integers rather than priced * locally in float. Does not verify their source, freshness or the other quote inputs. */ exactProbabilities: boolean; } /** Budget-sized mint plus the budget information needed to render an order preview. */ interface MintBudgetCost extends Omit { /** Requested all-in budget, before the optional account-balance cap. */ budget: number; /** Budget after the optional account-balance cap. */ effectiveBudget: number; /** Requested budget minus actual cost, including any balance-cap shortfall. */ unspentBudget: number; raw: MintCost['raw'] & { budget: bigint; effectiveBudget: bigint; unspentBudget: bigint; }; } /** * All-in cost of minting an exact payout quantity — the `mint_exact_quantity` shape, priced * entirely client-side. Mirrors `compute_mint_quote`, including its admission checks: the * entry-probability band on each finite leg and on the range, the `min_premium` floor, the lot * grid, and the `all_in_cost <= quantity` bound (a contract may never cost more than it can * pay out). Each violation throws the `PredictInputError` naming the abort the chain would * have raised. */ declare function mintCost(inputs: MintCostInputs): MintCost; /** * A fill whose ALL-IN cost fits a budget — `expiry_market::mint_exact_cost` computed * client-side, with the same lot search over the same cost function, so the answer is the * quantity that entrypoint would size and the cost it would debit. * * Without it a "spend exactly $X" flow has to guess: every fee is charged ON TOP of the * premium, so the caller subtracts an estimated fee load, pads it against an abort, and * systematically underspends. Here the whole search runs locally; submit the all-in budget * through `tx.mintCost` on deployments carrying `mint_exact_cost`. * * Sizing also respects the fill's maximum payout and the 32-bit lot cap; either can leave * substantial budget unspent. When only the budget binds, one more lot would exceed it. * If the budget fill exceeds its maximum payout, the contract's step-down is best effort: * rounding can make it miss a larger admissible fill, including one meeting `minQuantity`. * The chain caps the budget at the account balance first ({@link MintBudgetInputs.accountBalance}). */ declare function mintCostForBudget(inputs: MintBudgetInputs): MintBudgetCost; /** Inputs for {@link redeemLiveProceeds}. The range is the ORDER's own range — the same two * boundaries it was minted over, which is what `redeem_live` reprices. */ interface RedeemLiveInputs { fees: FeePolicy; expiryMs: number | bigint; nowMs?: number | bigint; /** The order's boundary probabilities now, or a pricer snapshot plus the order's strikes. */ probabilities: ProbabilitySource; /** Payout being closed — the whole order, or part of it. */ closeQuantity: number | bigint; /** Current position payout quantity, when known. Validates the close and returns the remainder. */ positionQuantity?: number | bigint; /** * Whether the selling account pays the account-attached builder fee: Predict v4 semantics. * Leave it `false` on a network running Version 5, where an attached code charges nothing. */ builderCode?: boolean; penaltyRate?: bigint; /** Pre-trade payout-tree terms. Required when inventory impact is enabled. */ book?: CloseBookTerms; lotSize?: bigint; } /** What a live close credits the account, decomposed. */ interface RedeemLiveProceeds { /** NET credited to the account. */ proceeds: number; /** Close value before fees: the range's current probability times the closed payout. */ gross: number; fees: { trading: number; builder: number; penalty: number; impactRebate: number; }; quantityClosed: number; /** Unclosed payout quantity, or null when positionQuantity was not supplied. */ remainingQuantity: number | null; /** Net credited per $1 of closed payout; includes fees and the inventory rebate. */ proceedsPerContract: number; /** Current range probability, 0..1, before amount rounding and fees. */ probability: number; raw: { proceeds: bigint; gross: bigint; tradingFee: bigint; builderFee: bigint; penaltyFee: bigint; impactRebate: bigint; quantityClosed: bigint; remainingQuantity: bigint | null; /** 1e9-scaled range probability; locally priced inputs remain approximate. */ probability: bigint; }; /** Identifies raw probability inputs; does not verify their source or state freshness. */ exactProbabilities: boolean; } /** * Net proceeds of closing a live position — `expiry_market::redeem_live`'s payment * decomposition, client-side. The mirror of {@link mintCost}: the same per-boundary trading * fee and builder fee, the same congestion surcharge, and the inventory-impact term as a * REBATE rather than a charge. There is no sponsor subsidy on a close (incentives subsidise * mints only), and each deduction is clamped at the payout remaining after the ones before it, * exactly as the contract clamps them, so a close can never cost more than it releases. * * Use this for a local UI preview from a supplied snapshot. `read.quoteRedeem` simulates * the actual close and remains the pre-trade check for ownership, remaining position size, * live-market gates and current fees. `proceeds` is what `min_proceeds` is compared against * on the real call; this preview does not guarantee execution at that amount. */ declare function redeemLiveProceeds(inputs: RedeemLiveInputs): RedeemLiveProceeds; /** The contract terms packed into an order ID (`deepbook_predict::order`). Tick `0` as the * lower bound is −∞ and {@link POS_INF_TICK} as the higher is +∞; multiply a finite tick by * the market's `tickSize` for its raw strike. Use it to feed a position from `read.positions` * into {@link redeemLiveProceeds}. */ interface OrderRange { lowerTick: bigint; higherTick: bigint; /** Minted payout: `quantity_lots · position_lot_size`. */ quantity: bigint; } /** Decode an order ID's range and quantity — the TypeScript mirror of `order::lower_tick` / * `higher_tick` / `quantity`. */ declare function decodeOrderRange(orderId: bigint, lotSize?: bigint): OrderRange; /** * What an order pays at settlement, raw USDC: its full quantity when the settlement price lies * in `(lower, higher]`, else 0. The mirror of `strike_exposure::settled_order_payout`, which * rounds the settlement price up to the market's tick grid (`range_codec::limit_tick`) before * comparing it with the order's ticks, so a price inside a tick counts as that tick's upper edge. * Pass `read.settlement`'s `settlementPriceRaw` and `tickSizeRaw`, and the config's * `units.positionLotSize` when it isn't the default. */ declare function settledPayout(orderId: bigint, settlementPriceRaw: bigint, tickSizeRaw: bigint, lotSize?: bigint): bigint; /** The strikes an {@link OrderRange} prices against, in USD, with `null` for each infinite * side — the shape {@link boundaryProbabilities} takes. `tickSize` is the market's raw tick * size (`ActiveMarket.tickSize` in USD, or the raw value from the deployment). */ declare function orderStrikes(range: OrderRange, tickSizeRaw: bigint): { lower: number | null; upper: number | null; }; //#endregion export { FeePolicy, cost_d_exports }; //# sourceMappingURL=cost.d.mts.map