@mysten/deepbook-v3 2.5.0 → 2.6.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 +31 -0
- package/PREDICT.md +160 -12
- 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 +19 -19
- package/dist/contracts/account/account_registry.d.mts.map +1 -1
- 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_predict/admin.d.mts +4 -4
- package/dist/contracts/deepbook_predict/builder_code.d.mts +11 -11
- package/dist/contracts/deepbook_predict/builder_code.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/builder_code_events.d.mts +10 -10
- package/dist/contracts/deepbook_predict/config_events.d.mts +67 -67
- package/dist/contracts/deepbook_predict/config_events.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/expiry_market.d.mts +176 -96
- package/dist/contracts/deepbook_predict/expiry_market.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/expiry_market.mjs +114 -1
- package/dist/contracts/deepbook_predict/expiry_market.mjs.map +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/market_manager.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/order_events.d.mts +50 -50
- package/dist/contracts/deepbook_predict/pause_cap.d.mts +5 -5
- package/dist/contracts/deepbook_predict/plp.d.mts +72 -72
- package/dist/contracts/deepbook_predict/plp.d.mts.map +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 +53 -53
- package/dist/contracts/deepbook_predict/protocol_config.d.mts +64 -64
- 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 +12 -0
- package/dist/contracts/deepbook_predict/strike_exposure.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/vault_events.d.mts +105 -105
- package/dist/contracts/deepbook_sessions/session_config.d.mts +8 -8
- package/dist/contracts/deepbook_sessions/session_config.d.mts.map +1 -1
- package/dist/contracts/deepbook_sessions/sessions.d.mts +48 -23
- package/dist/contracts/deepbook_sessions/sessions.d.mts.map +1 -1
- package/dist/contracts/deepbook_sessions/sessions.mjs +44 -1
- package/dist/contracts/deepbook_sessions/sessions.mjs.map +1 -1
- package/dist/deployments/mainnet.d.mts.map +1 -1
- package/dist/deployments/mainnet.mjs +2 -0
- package/dist/deployments/mainnet.mjs.map +1 -1
- package/dist/deployments/testnet.d.mts.map +1 -1
- package/dist/deployments/testnet.mjs +4 -2
- package/dist/deployments/testnet.mjs.map +1 -1
- package/dist/deployments/types.d.mts +1 -1
- package/dist/predict/client.d.mts +12 -3
- package/dist/predict/client.d.mts.map +1 -1
- package/dist/predict/client.mjs +39 -18
- package/dist/predict/client.mjs.map +1 -1
- package/dist/predict/config/generated.d.mts +3 -2
- package/dist/predict/config/generated.d.mts.map +1 -1
- package/dist/predict/config/generated.mjs +1 -0
- package/dist/predict/config/generated.mjs.map +1 -1
- package/dist/predict/config/types.d.mts +3 -0
- package/dist/predict/config/types.d.mts.map +1 -1
- package/dist/predict/cost.d.mts +353 -0
- package/dist/predict/cost.d.mts.map +1 -0
- package/dist/predict/cost.mjs +555 -0
- package/dist/predict/cost.mjs.map +1 -0
- package/dist/predict/decode.mjs +6 -7
- package/dist/predict/decode.mjs.map +1 -1
- package/dist/predict/index.d.mts +3 -2
- package/dist/predict/index.mjs +2 -1
- package/dist/predict/pricing.mjs +1 -1
- package/dist/predict/reads/positions.mjs +1 -1
- package/dist/predict/reads/positions.mjs.map +1 -1
- package/dist/predict/tx/trade.d.mts.map +1 -1
- package/dist/predict/tx/trade.mjs +18 -2
- package/dist/predict/tx/trade.mjs.map +1 -1
- package/dist/sessions.d.mts +17 -1
- package/dist/sessions.d.mts.map +1 -1
- package/dist/sessions.mjs +22 -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/deepbookAdmin.d.mts +4 -4
- package/dist/transactions/marginAdmin.d.mts +7 -7
- package/dist/transactions/marginLiquidations.d.mts +3 -3
- package/dist/transactions/marginMaintainer.d.mts +5 -5
- package/dist/transactions/marginManager.d.mts +32 -32
- package/dist/transactions/marginPool.d.mts +18 -18
- package/dist/transactions/marginPool.d.mts.map +1 -1
- 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 +2 -2
- package/src/contracts/deepbook_predict/expiry_market.ts +160 -0
- package/src/contracts/deepbook_predict/strike_exposure.ts +14 -0
- package/src/contracts/deepbook_sessions/sessions.ts +68 -0
- package/src/deployments/mainnet.ts +4 -1
- package/src/deployments/testnet.ts +6 -3
- package/src/deployments/types.ts +4 -2
- package/src/predict/client.ts +80 -27
- package/src/predict/config/generated.ts +4 -2
- package/src/predict/config/types.ts +3 -0
- package/src/predict/cost.ts +1022 -0
- package/src/predict/decode.ts +8 -8
- package/src/predict/index.ts +9 -0
- package/src/predict/reads/positions.ts +1 -1
- package/src/predict/tx/trade.ts +30 -1
- package/src/sessions.ts +37 -2
|
@@ -0,0 +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,UAAU,SAAS,UAAU,IAAU;AACvF,KAAI,OAAO,UAAU,YAAY,QAAQ,WAAW,QAAQ,QAC3D,OAAM,IAAI,kBACT,GAAG,KAAK,0BAA0B,QAAQ,IAAI,QAAQ,SAAS,QAC/D;;AAKH,SAAS,iBAAiB,GAAmB;CAC5C,IAAI,OAAO;CACX,IAAI,MAAM;AACV,KAAI,OAAO,MAAM,KAAK;AACrB,UAAQ;AACR,UAAQ;;AAET,KAAI,OAAO,MAAM,KAAK;AACrB,UAAQ;AACR,UAAQ;;AAET,KAAI,OAAO,MAAM,KAAK;AACrB,UAAQ;AACR,UAAQ;;AAET,KAAI,OAAO,MAAM,IAAI;AACpB,UAAQ;AACR,UAAQ;;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AsB;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"}
|
package/dist/predict/decode.mjs
CHANGED
|
@@ -39,7 +39,7 @@ function exactlyOne(items, what) {
|
|
|
39
39
|
}
|
|
40
40
|
const optId = (v) => v == null ? null : normalizeSuiAddress(v);
|
|
41
41
|
function decodeMints(cfg, result) {
|
|
42
|
-
return decodeAll(result, cfg.packages.predict, "order_events", "OrderMinted", OrderMinted).map((e) => ({
|
|
42
|
+
return decodeAll(result, cfg.packages.predictV1 ?? cfg.packages.predict, "order_events", "OrderMinted", OrderMinted).map((e) => ({
|
|
43
43
|
marketId: normalizeSuiAddress(e.expiry_market_id),
|
|
44
44
|
accountId: normalizeSuiAddress(e.account_id),
|
|
45
45
|
owner: normalizeSuiAddress(e.owner),
|
|
@@ -73,8 +73,7 @@ function decodeMints(cfg, result) {
|
|
|
73
73
|
}));
|
|
74
74
|
}
|
|
75
75
|
function decodeRedeems(cfg, result) {
|
|
76
|
-
|
|
77
|
-
return decodeAll(result, pkg, "order_events", "LiveOrderRedeemed", LiveOrderRedeemed).map((e) => ({
|
|
76
|
+
return decodeAll(result, cfg.packages.predictV1 ?? cfg.packages.predict, "order_events", "LiveOrderRedeemed", LiveOrderRedeemed).map((e) => ({
|
|
78
77
|
marketId: normalizeSuiAddress(e.expiry_market_id),
|
|
79
78
|
accountId: normalizeSuiAddress(e.account_id),
|
|
80
79
|
owner: normalizeSuiAddress(e.owner),
|
|
@@ -105,7 +104,7 @@ function decodeRedeems(cfg, result) {
|
|
|
105
104
|
}));
|
|
106
105
|
}
|
|
107
106
|
function decodeClaims(cfg, result) {
|
|
108
|
-
return decodeAll(result, cfg.packages.predict, "order_events", "SettledOrderRedeemed", SettledOrderRedeemed).map((e) => ({
|
|
107
|
+
return decodeAll(result, cfg.packages.predictV1 ?? cfg.packages.predict, "order_events", "SettledOrderRedeemed", SettledOrderRedeemed).map((e) => ({
|
|
109
108
|
marketId: normalizeSuiAddress(e.expiry_market_id),
|
|
110
109
|
accountId: normalizeSuiAddress(e.account_id),
|
|
111
110
|
owner: normalizeSuiAddress(e.owner),
|
|
@@ -139,7 +138,7 @@ function decodeBalanceChanges(cfg, result, name) {
|
|
|
139
138
|
const decodeDeposits = (cfg, result) => decodeBalanceChanges(cfg, result, "Deposited");
|
|
140
139
|
const decodeWithdrawals = (cfg, result) => decodeBalanceChanges(cfg, result, "Withdrawn");
|
|
141
140
|
function decodePlpRequests(cfg, result) {
|
|
142
|
-
const pkg = cfg.packages.predict;
|
|
141
|
+
const pkg = cfg.packages.predictV1 ?? cfg.packages.predict;
|
|
143
142
|
const make = (kind) => (e) => ({
|
|
144
143
|
kind,
|
|
145
144
|
vaultId: normalizeSuiAddress(e.pool_vault_id),
|
|
@@ -152,7 +151,7 @@ function decodePlpRequests(cfg, result) {
|
|
|
152
151
|
return [...decodeAll(result, pkg, "vault_events", "SupplyRequested", SupplyRequested).map(make("supply")), ...decodeAll(result, pkg, "vault_events", "WithdrawRequested", WithdrawRequested).map(make("withdraw"))];
|
|
153
152
|
}
|
|
154
153
|
function decodePlpCancels(cfg, result) {
|
|
155
|
-
return decodeAll(result, cfg.packages.predict, "vault_events", "RequestCancelled", RequestCancelled).map((e) => ({
|
|
154
|
+
return decodeAll(result, cfg.packages.predictV1 ?? cfg.packages.predict, "vault_events", "RequestCancelled", RequestCancelled).map((e) => ({
|
|
156
155
|
vaultId: normalizeSuiAddress(e.pool_vault_id),
|
|
157
156
|
accountId: normalizeSuiAddress(e.account_id),
|
|
158
157
|
recipient: normalizeSuiAddress(e.recipient),
|
|
@@ -163,7 +162,7 @@ function decodePlpCancels(cfg, result) {
|
|
|
163
162
|
}));
|
|
164
163
|
}
|
|
165
164
|
function decodeBuilderCodeSets(cfg, result) {
|
|
166
|
-
return decodeAll(result, cfg.packages.predict, "builder_code_events", "BuilderCodeSet", BuilderCodeSet).map((e) => ({
|
|
165
|
+
return decodeAll(result, cfg.packages.predictV1 ?? cfg.packages.predict, "builder_code_events", "BuilderCodeSet", BuilderCodeSet).map((e) => ({
|
|
167
166
|
accountId: normalizeSuiAddress(e.account_id),
|
|
168
167
|
owner: normalizeSuiAddress(e.owner),
|
|
169
168
|
builderCodeId: optId(e.builder_code_id)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decode.mjs","names":["orderEvents.OrderMinted","orderEvents.LiveOrderRedeemed","orderEvents.SettledOrderRedeemed","accountEvents.AccountCreated","accountEvents.Deposited","accountEvents.Withdrawn","vaultEvents.SupplyRequested","vaultEvents.WithdrawRequested","vaultEvents.RequestCancelled","builderCodeEvents.BuilderCodeSet"],"sources":["../../src/predict/decode.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromBase64, normalizeSuiAddress } from '@mysten/sui/utils';\nimport type { PredictConfig } from './config/index.js';\nimport { accountEvents } from '../account.js';\nimport * as builderCodeEvents from '../contracts/deepbook_predict/builder_code_events.js';\nimport * as orderEvents from '../contracts/deepbook_predict/order_events.js';\nimport * as vaultEvents from '../contracts/deepbook_predict/vault_events.js';\nimport { PredictInputError } from './errors.js';\nimport { fromRaw } from './units.js';\n\n// ============================================================================\n// Execution-result decoders.\n//\n// Every tx.* builder returns a Transaction; after the app executes it (with\n// events included), the deployed contracts emit typed events carrying the full\n// receipt — order ids, fills, fees, queue indexes, new balances. These pure\n// functions turn that result into typed receipts. No network, no client.\n//\n// Decoding uses each event's BCS bytes, not its `json`: the client typings\n// warn the JSON rendering varies across transports (JSON-RPC/gRPC/GraphQL),\n// while BCS is canonical. Layouts come from the GENERATED event MoveStructs\n// (src/contracts/{deepbook_predict,account}/*_events.ts), whose field order\n// mirrors the deployed Move — regenerate the bindings if the package changes.\n// ============================================================================\n\n/** The slice of an executed/simulated transaction result the decoders need. */\nexport interface DecodableEvent {\n\t/** Full type tag `0xpkg::module::Name` (gRPC `eventType`, legacy `type`). */\n\teventType?: string;\n\ttype?: string;\n\tpackageId?: string;\n\tmodule?: string;\n\t/** Struct name, when the transport supplies it separately from a full type tag. */\n\tname?: string;\n\t/** Canonical BCS payload; some transports deliver it base64-encoded. */\n\tbcs?: Uint8Array | string;\n}\n\nexport interface DecodableTransactionResult {\n\tevents?: readonly DecodableEvent[] | null;\n}\n\n// --- matching + plumbing ----------------------------------------------------\n\nfunction eventBytes(e: DecodableEvent): Uint8Array | null {\n\tif (e.bcs instanceof Uint8Array) return e.bcs;\n\tif (typeof e.bcs === 'string') return fromBase64(e.bcs);\n\treturn null;\n}\n\n// Match by defining package + module + struct name. Events are typed by the\n// ORIGINAL package id; for the current v1 deployments that equals the config\n// package id.\nfunction matches(e: DecodableEvent, pkg: string, module: string, name: string): boolean {\n\tconst tag = e.eventType ?? e.type;\n\tif (tag) {\n\t\tconst parts = tag.split('::');\n\t\tif (parts.length !== 3) return false;\n\t\treturn (\n\t\t\tnormalizeSuiAddress(parts[0]) === normalizeSuiAddress(pkg) &&\n\t\t\tparts[1] === module &&\n\t\t\tparts[2] === name\n\t\t);\n\t}\n\t// No type tag. Match on what the transport did give us — and on `name` when it is\n\t// present, because module+package alone matches EVERY struct in the module, so one\n\t// decoder would happily take another's event and fail deep inside BCS.\n\tif (e.module !== module || e.packageId == null) return false;\n\tif (normalizeSuiAddress(e.packageId) !== normalizeSuiAddress(pkg)) return false;\n\treturn e.name == null || e.name === name;\n}\n\nfunction decodeAll<T>(\n\tresult: DecodableTransactionResult,\n\tpkg: string,\n\tmodule: string,\n\tname: string,\n\tlayout: { parse(bytes: Uint8Array): T },\n): T[] {\n\tconst out: T[] = [];\n\tfor (const e of result.events ?? []) {\n\t\tif (!matches(e, pkg, module, name)) continue;\n\t\tconst bytes = eventBytes(e);\n\t\tif (!bytes) {\n\t\t\tthrow new PredictInputError(\n\t\t\t\t`${module}::${name} event has no BCS payload — execute/simulate with events included`,\n\t\t\t);\n\t\t}\n\t\tout.push(layout.parse(bytes));\n\t}\n\treturn out;\n}\n\nfunction exactlyOne<T>(items: T[], what: string): T {\n\tif (items.length !== 1) {\n\t\tthrow new PredictInputError(`expected exactly one ${what} event, found ${items.length}`);\n\t}\n\treturn items[0];\n}\n\nconst optId = (v: string | null | undefined): string | null =>\n\tv == null ? null : normalizeSuiAddress(v);\n\n// --- receipts ---------------------------------------------------------------\n\nexport interface MintReceipt {\n\tmarketId: string;\n\taccountId: string;\n\towner: string;\n\t/** Persist this: required to redeem/claim the position later. */\n\torderId: bigint;\n\t/** Stable across partial-close replacements; equals orderId at mint. */\n\tpositionRootId: bigint;\n\tlowerTick: bigint;\n\thigherTick: bigint;\n\t/** 0..1 range probability quoted at entry (your fill price per $1 payout). */\n\tentryProbability: number;\n\t/** Max payout actually minted, in quote units (mintAmount: chain-floored). */\n\tquantity: number;\n\t/** Premium paid into LP backing, in quote units. */\n\tpremium: number;\n\t/**\n\t * Fee breakdown. `referral` is the slice of the trader-paid trading fee and\n\t * congestion surcharge delivered to the referrer; `inventoryImpact` is the\n\t * path-independent inventory-impact charge assessed on the mint.\n\t */\n\tfees: {\n\t\ttrading: number;\n\t\tsubsidy: number;\n\t\tbuilder: number;\n\t\tpenalty: number;\n\t\treferral: number;\n\t\tinventoryImpact: number;\n\t};\n\tbuilderCodeId: string | null;\n\traw: {\n\t\tquantity: bigint;\n\t\tpremium: bigint;\n\t\ttradingFee: bigint;\n\t\tfeeIncentiveSubsidy: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\treferralFee: bigint;\n\t\tinventoryImpactCharge: bigint;\n\t\tentryProbability: bigint;\n\t};\n}\n\nexport interface RedeemReceipt {\n\tmarketId: string;\n\taccountId: string;\n\towner: string;\n\torderId: bigint;\n\tpositionRootId: bigint;\n\tquantityClosed: number;\n\tremaining: number;\n\t/**\n\t * A partial close RETIRES the old order id and issues this replacement for\n\t * the remaining quantity — update your stored id or it goes silently stale.\n\t */\n\treplacementOrderId: bigint | null;\n\t/** NET quote credited to the account: gross + inventoryImpactRebate − trading −\n\t * builder − penalty — the same expression the chain asserts `min_proceeds`\n\t * against, and what `settle_live_redeem_payment` actually deposits. */\n\tproceeds: number;\n\t/** Gross close value before fees (the event's redeem_amount). */\n\tgross: number;\n\t/**\n\t * Fee breakdown. `inventoryImpactRebate` is the path-independent\n\t * inventory-impact rebate credited back on the close.\n\t */\n\tfees: { trading: number; builder: number; penalty: number; inventoryImpactRebate: number };\n\tbuilderCodeId: string | null;\n\traw: {\n\t\tquantityClosed: bigint;\n\t\tremaining: bigint;\n\t\tproceeds: bigint;\n\t\tgross: bigint;\n\t\ttradingFee: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\tinventoryImpactRebate: bigint;\n\t};\n}\n\nexport interface ClaimReceipt {\n\tmarketId: string;\n\taccountId: string;\n\towner: string;\n\torderId: bigint;\n\tpositionRootId: bigint;\n\t/** Quote units paid out. A settled claim closes the order in full. */\n\tpayout: number;\n\traw: { payout: bigint };\n}\n\nexport interface CreateManagerReceipt {\n\taccountId: string;\n\twrapperId: string;\n\towner: string;\n\tselfOwned: boolean;\n}\n\nexport interface BalanceChangeReceipt {\n\taccountId: string;\n\tcoinType: string;\n\t/** Display value assuming a 6-decimal coin (quote + PLP both are). */\n\tamount: number;\n\tnewBalance: number;\n\traw: { amount: bigint; newBalance: bigint };\n}\n\nexport interface PlpRequestReceipt {\n\tkind: 'supply' | 'withdraw';\n\tvaultId: string;\n\taccountId: string;\n\trecipient: string;\n\t/** Feed straight into cancelSupplyPlp / cancelWithdrawPlp. */\n\tindex: bigint;\n\t/** Quote units for supply; PLP shares (6-dec) for withdraw. */\n\tamount: number;\n\traw: { amount: bigint };\n}\n\nexport interface PlpCancelReceipt {\n\tvaultId: string;\n\taccountId: string;\n\trecipient: string;\n\tindex: bigint;\n\tisSupply: boolean;\n\t/** Refund returned to the account (quote for supply, PLP for withdraw). */\n\tamount: number;\n\traw: { amount: bigint };\n}\n\nexport interface BuilderCodeReceipt {\n\taccountId: string;\n\towner: string;\n\t/** Null after unsetBuilderCode. */\n\tbuilderCodeId: string | null;\n}\n\n// --- decoders (plural = all matching events, in event order) ----------------\n\nexport function decodeMints(cfg: PredictConfig, result: DecodableTransactionResult): MintReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.predict,\n\t\t'order_events',\n\t\t'OrderMinted',\n\t\torderEvents.OrderMinted,\n\t).map((e) => ({\n\t\tmarketId: normalizeSuiAddress(e.expiry_market_id),\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\torderId: e.order_id,\n\t\tpositionRootId: e.position_root_id,\n\t\tlowerTick: e.lower_tick,\n\t\thigherTick: e.higher_tick,\n\t\tentryProbability: fromRaw(e.entry_probability, 9),\n\t\tquantity: fromRaw(e.quantity, 6),\n\t\tpremium: fromRaw(e.premium, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(e.trading_fee, 6),\n\t\t\tsubsidy: fromRaw(e.fee_incentive_subsidy, 6),\n\t\t\tbuilder: fromRaw(e.builder_fee, 6),\n\t\t\tpenalty: fromRaw(e.penalty_fee, 6),\n\t\t\treferral: fromRaw(e.referral_fee, 6),\n\t\t\tinventoryImpact: fromRaw(e.inventory_impact_charge, 6),\n\t\t},\n\t\tbuilderCodeId: optId(e.builder_code_id),\n\t\traw: {\n\t\t\tquantity: e.quantity,\n\t\t\tpremium: e.premium,\n\t\t\ttradingFee: e.trading_fee,\n\t\t\tfeeIncentiveSubsidy: e.fee_incentive_subsidy,\n\t\t\tbuilderFee: e.builder_fee,\n\t\t\tpenaltyFee: e.penalty_fee,\n\t\t\treferralFee: e.referral_fee,\n\t\t\tinventoryImpactCharge: e.inventory_impact_charge,\n\t\t\tentryProbability: e.entry_probability,\n\t\t},\n\t}));\n}\n\nexport function decodeRedeems(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): RedeemReceipt[] {\n\tconst pkg = cfg.packages.predict;\n\tconst live = decodeAll(\n\t\tresult,\n\t\tpkg,\n\t\t'order_events',\n\t\t'LiveOrderRedeemed',\n\t\torderEvents.LiveOrderRedeemed,\n\t).map((e): RedeemReceipt => ({\n\t\tmarketId: normalizeSuiAddress(e.expiry_market_id),\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\torderId: e.order_id,\n\t\tpositionRootId: e.position_root_id,\n\t\tquantityClosed: fromRaw(e.quantity_closed, 6),\n\t\tremaining: fromRaw(e.remaining_quantity, 6),\n\t\treplacementOrderId: e.replacement_order_id,\n\t\t// Mirrors the deployed close-side accounting exactly (the same expression\n\t\t// `min_proceeds` is asserted against): the net credited to the account is\n\t\t// redeem_amount PLUS the inventory-impact rebate, minus trading, builder and\n\t\t// penalty fees. The event's redeem_amount is GROSS.\n\t\tproceeds: fromRaw(\n\t\t\te.redeem_amount + e.inventory_impact_rebate - e.trading_fee - e.builder_fee - e.penalty_fee,\n\t\t\t6,\n\t\t),\n\t\tgross: fromRaw(e.redeem_amount, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(e.trading_fee, 6),\n\t\t\tbuilder: fromRaw(e.builder_fee, 6),\n\t\t\tpenalty: fromRaw(e.penalty_fee, 6),\n\t\t\tinventoryImpactRebate: fromRaw(e.inventory_impact_rebate, 6),\n\t\t},\n\t\tbuilderCodeId: optId(e.builder_code_id),\n\t\traw: {\n\t\t\tquantityClosed: e.quantity_closed,\n\t\t\tremaining: e.remaining_quantity,\n\t\t\tproceeds:\n\t\t\t\te.redeem_amount + e.inventory_impact_rebate - e.trading_fee - e.builder_fee - e.penalty_fee,\n\t\t\tgross: e.redeem_amount,\n\t\t\ttradingFee: e.trading_fee,\n\t\t\tbuilderFee: e.builder_fee,\n\t\t\tpenaltyFee: e.penalty_fee,\n\t\t\tinventoryImpactRebate: e.inventory_impact_rebate,\n\t\t},\n\t}));\n\treturn live;\n}\n\nexport function decodeClaims(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): ClaimReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.predict,\n\t\t'order_events',\n\t\t'SettledOrderRedeemed',\n\t\torderEvents.SettledOrderRedeemed,\n\t).map((e) => ({\n\t\tmarketId: normalizeSuiAddress(e.expiry_market_id),\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\torderId: e.order_id,\n\t\tpositionRootId: e.position_root_id,\n\t\tpayout: fromRaw(e.payout_amount, 6),\n\t\traw: { payout: e.payout_amount },\n\t}));\n}\n\nexport function decodeAccountsCreated(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): CreateManagerReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.account,\n\t\t'account_events',\n\t\t'AccountCreated',\n\t\taccountEvents.AccountCreated,\n\t).map((e) => ({\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\twrapperId: normalizeSuiAddress(e.wrapper_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\tselfOwned: e.self_owned,\n\t}));\n}\n\nfunction decodeBalanceChanges(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n\tname: 'Deposited' | 'Withdrawn',\n): BalanceChangeReceipt[] {\n\tconst layout = name === 'Deposited' ? accountEvents.Deposited : accountEvents.Withdrawn;\n\treturn decodeAll(result, cfg.packages.account, 'account_events', name, layout).map((e) => ({\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\tcoinType: e.coin_type,\n\t\tamount: fromRaw(e.amount, 6),\n\t\tnewBalance: fromRaw(e.new_balance, 6),\n\t\traw: { amount: e.amount, newBalance: e.new_balance },\n\t}));\n}\n\nexport const decodeDeposits = (\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): BalanceChangeReceipt[] => decodeBalanceChanges(cfg, result, 'Deposited');\n\nexport const decodeWithdrawals = (\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): BalanceChangeReceipt[] => decodeBalanceChanges(cfg, result, 'Withdrawn');\n\nexport function decodePlpRequests(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): PlpRequestReceipt[] {\n\tconst pkg = cfg.packages.predict;\n\t// Supply/WithdrawRequested differ only in their min-out field (unused here);\n\t// pick the fields both share so either generated struct's parse feeds `make`.\n\ttype RequestedCommon = Pick<\n\t\t(typeof vaultEvents.SupplyRequested)['$inferType'],\n\t\t'pool_vault_id' | 'account_id' | 'recipient' | 'index' | 'amount'\n\t>;\n\tconst make =\n\t\t(kind: 'supply' | 'withdraw') =>\n\t\t(e: RequestedCommon): PlpRequestReceipt => ({\n\t\t\tkind,\n\t\t\tvaultId: normalizeSuiAddress(e.pool_vault_id),\n\t\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\t\trecipient: normalizeSuiAddress(e.recipient),\n\t\t\tindex: e.index,\n\t\t\tamount: fromRaw(e.amount, 6),\n\t\t\traw: { amount: e.amount },\n\t\t});\n\treturn [\n\t\t...decodeAll(result, pkg, 'vault_events', 'SupplyRequested', vaultEvents.SupplyRequested).map(\n\t\t\tmake('supply'),\n\t\t),\n\t\t...decodeAll(\n\t\t\tresult,\n\t\t\tpkg,\n\t\t\t'vault_events',\n\t\t\t'WithdrawRequested',\n\t\t\tvaultEvents.WithdrawRequested,\n\t\t).map(make('withdraw')),\n\t];\n}\n\nexport function decodePlpCancels(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): PlpCancelReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.predict,\n\t\t'vault_events',\n\t\t'RequestCancelled',\n\t\tvaultEvents.RequestCancelled,\n\t).map((e) => ({\n\t\tvaultId: normalizeSuiAddress(e.pool_vault_id),\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\trecipient: normalizeSuiAddress(e.recipient),\n\t\tindex: e.index,\n\t\tisSupply: e.is_supply,\n\t\tamount: fromRaw(e.amount, 6),\n\t\traw: { amount: e.amount },\n\t}));\n}\n\nexport function decodeBuilderCodeSets(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): BuilderCodeReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.predict,\n\t\t'builder_code_events',\n\t\t'BuilderCodeSet',\n\t\tbuilderCodeEvents.BuilderCodeSet,\n\t).map((e) => ({\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\tbuilderCodeId: optId(e.builder_code_id),\n\t}));\n}\n\nexport { exactlyOne };\n"],"mappings":";;;;;;;;;AA6CA,SAAS,WAAW,GAAsC;AACzD,KAAI,EAAE,eAAe,WAAY,QAAO,EAAE;AAC1C,KAAI,OAAO,EAAE,QAAQ,SAAU,QAAO,WAAW,EAAE,IAAI;AACvD,QAAO;;AAMR,SAAS,QAAQ,GAAmB,KAAa,QAAgB,MAAuB;CACvF,MAAM,MAAM,EAAE,aAAa,EAAE;AAC7B,KAAI,KAAK;EACR,MAAM,QAAQ,IAAI,MAAM,KAAK;AAC7B,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,SACC,oBAAoB,MAAM,GAAG,KAAK,oBAAoB,IAAI,IAC1D,MAAM,OAAO,UACb,MAAM,OAAO;;AAMf,KAAI,EAAE,WAAW,UAAU,EAAE,aAAa,KAAM,QAAO;AACvD,KAAI,oBAAoB,EAAE,UAAU,KAAK,oBAAoB,IAAI,CAAE,QAAO;AAC1E,QAAO,EAAE,QAAQ,QAAQ,EAAE,SAAS;;AAGrC,SAAS,UACR,QACA,KACA,QACA,MACA,QACM;CACN,MAAM,MAAW,EAAE;AACnB,MAAK,MAAM,KAAK,OAAO,UAAU,EAAE,EAAE;AACpC,MAAI,CAAC,QAAQ,GAAG,KAAK,QAAQ,KA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SAAgB,iBACf,KACA,QACqB;AACrB,QAAO,UACN,QACA,IAAI,SAAS,SACb,gBACA,oBACAC,iBACA,CAAC,KAAK,OAAO;EACb,SAAS,oBAAoB,EAAE,cAAc;EAC7C,WAAW,oBAAoB,EAAE,WAAW;EAC5C,WAAW,oBAAoB,EAAE,UAAU;EAC3C,OAAO,EAAE;EACT,UAAU,EAAE;EACZ,QAAQ,QAAQ,EAAE,QAAQ,EAAE;EAC5B,KAAK,EAAE,QAAQ,EAAE,QAAQ;EACzB,EAAE;;AAGJ,SAAgB,sBACf,KACA,QACuB;AACvB,QAAO,UACN,QACA,IAAI,SAAS,SACb,uBACA,kBACAC,eACA,CAAC,KAAK,OAAO;EACb,WAAW,oBAAoB,EAAE,WAAW;EAC5C,OAAO,oBAAoB,EAAE,MAAM;EACnC,eAAe,MAAM,EAAE,gBAAgB;EACvC,EAAE"}
|
|
1
|
+
{"version":3,"file":"decode.mjs","names":["orderEvents.OrderMinted","orderEvents.LiveOrderRedeemed","orderEvents.SettledOrderRedeemed","accountEvents.AccountCreated","accountEvents.Deposited","accountEvents.Withdrawn","vaultEvents.SupplyRequested","vaultEvents.WithdrawRequested","vaultEvents.RequestCancelled","builderCodeEvents.BuilderCodeSet"],"sources":["../../src/predict/decode.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromBase64, normalizeSuiAddress } from '@mysten/sui/utils';\nimport type { PredictConfig } from './config/index.js';\nimport { accountEvents } from '../account.js';\nimport * as builderCodeEvents from '../contracts/deepbook_predict/builder_code_events.js';\nimport * as orderEvents from '../contracts/deepbook_predict/order_events.js';\nimport * as vaultEvents from '../contracts/deepbook_predict/vault_events.js';\nimport { PredictInputError } from './errors.js';\nimport { fromRaw } from './units.js';\n\n// ============================================================================\n// Execution-result decoders.\n//\n// Every tx.* builder returns a Transaction; after the app executes it (with\n// events included), the deployed contracts emit typed events carrying the full\n// receipt — order ids, fills, fees, queue indexes, new balances. These pure\n// functions turn that result into typed receipts. No network, no client.\n//\n// Decoding uses each event's BCS bytes, not its `json`: the client typings\n// warn the JSON rendering varies across transports (JSON-RPC/gRPC/GraphQL),\n// while BCS is canonical. Layouts come from the GENERATED event MoveStructs\n// (src/contracts/{deepbook_predict,account}/*_events.ts), whose field order\n// mirrors the deployed Move — regenerate the bindings if the package changes.\n// ============================================================================\n\n/** The slice of an executed/simulated transaction result the decoders need. */\nexport interface DecodableEvent {\n\t/** Full type tag `0xpkg::module::Name` (gRPC `eventType`, legacy `type`). */\n\teventType?: string;\n\ttype?: string;\n\tpackageId?: string;\n\tmodule?: string;\n\t/** Struct name, when the transport supplies it separately from a full type tag. */\n\tname?: string;\n\t/** Canonical BCS payload; some transports deliver it base64-encoded. */\n\tbcs?: Uint8Array | string;\n}\n\nexport interface DecodableTransactionResult {\n\tevents?: readonly DecodableEvent[] | null;\n}\n\n// --- matching + plumbing ----------------------------------------------------\n\nfunction eventBytes(e: DecodableEvent): Uint8Array | null {\n\tif (e.bcs instanceof Uint8Array) return e.bcs;\n\tif (typeof e.bcs === 'string') return fromBase64(e.bcs);\n\treturn null;\n}\n\n// Match by defining package + module + struct name. Events are typed by the\n// package version that introduced their struct, not the latest Move-call target.\n// All events decoded here were introduced in v1.\nfunction matches(e: DecodableEvent, pkg: string, module: string, name: string): boolean {\n\tconst tag = e.eventType ?? e.type;\n\tif (tag) {\n\t\tconst parts = tag.split('::');\n\t\tif (parts.length !== 3) return false;\n\t\treturn (\n\t\t\tnormalizeSuiAddress(parts[0]) === normalizeSuiAddress(pkg) &&\n\t\t\tparts[1] === module &&\n\t\t\tparts[2] === name\n\t\t);\n\t}\n\t// No type tag. Match on what the transport did give us — and on `name` when it is\n\t// present, because module+package alone matches EVERY struct in the module, so one\n\t// decoder would happily take another's event and fail deep inside BCS.\n\tif (e.module !== module || e.packageId == null) return false;\n\tif (normalizeSuiAddress(e.packageId) !== normalizeSuiAddress(pkg)) return false;\n\treturn e.name == null || e.name === name;\n}\n\nfunction decodeAll<T>(\n\tresult: DecodableTransactionResult,\n\tpkg: string,\n\tmodule: string,\n\tname: string,\n\tlayout: { parse(bytes: Uint8Array): T },\n): T[] {\n\tconst out: T[] = [];\n\tfor (const e of result.events ?? []) {\n\t\tif (!matches(e, pkg, module, name)) continue;\n\t\tconst bytes = eventBytes(e);\n\t\tif (!bytes) {\n\t\t\tthrow new PredictInputError(\n\t\t\t\t`${module}::${name} event has no BCS payload — execute/simulate with events included`,\n\t\t\t);\n\t\t}\n\t\tout.push(layout.parse(bytes));\n\t}\n\treturn out;\n}\n\nfunction exactlyOne<T>(items: T[], what: string): T {\n\tif (items.length !== 1) {\n\t\tthrow new PredictInputError(`expected exactly one ${what} event, found ${items.length}`);\n\t}\n\treturn items[0];\n}\n\nconst optId = (v: string | null | undefined): string | null =>\n\tv == null ? null : normalizeSuiAddress(v);\n\n// --- receipts ---------------------------------------------------------------\n\nexport interface MintReceipt {\n\tmarketId: string;\n\taccountId: string;\n\towner: string;\n\t/** Persist this: required to redeem/claim the position later. */\n\torderId: bigint;\n\t/** Stable across partial-close replacements; equals orderId at mint. */\n\tpositionRootId: bigint;\n\tlowerTick: bigint;\n\thigherTick: bigint;\n\t/** 0..1 range probability quoted at entry (your fill price per $1 payout). */\n\tentryProbability: number;\n\t/** Max payout actually minted, in quote units (mintAmount: chain-floored). */\n\tquantity: number;\n\t/** Premium paid into LP backing, in quote units. */\n\tpremium: number;\n\t/**\n\t * Fee breakdown. `referral` is the slice of the trader-paid trading fee and\n\t * congestion surcharge delivered to the referrer; `inventoryImpact` is the\n\t * path-independent inventory-impact charge assessed on the mint.\n\t */\n\tfees: {\n\t\ttrading: number;\n\t\tsubsidy: number;\n\t\tbuilder: number;\n\t\tpenalty: number;\n\t\treferral: number;\n\t\tinventoryImpact: number;\n\t};\n\tbuilderCodeId: string | null;\n\traw: {\n\t\tquantity: bigint;\n\t\tpremium: bigint;\n\t\ttradingFee: bigint;\n\t\tfeeIncentiveSubsidy: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\treferralFee: bigint;\n\t\tinventoryImpactCharge: bigint;\n\t\tentryProbability: bigint;\n\t};\n}\n\nexport interface RedeemReceipt {\n\tmarketId: string;\n\taccountId: string;\n\towner: string;\n\torderId: bigint;\n\tpositionRootId: bigint;\n\tquantityClosed: number;\n\tremaining: number;\n\t/**\n\t * A partial close RETIRES the old order id and issues this replacement for\n\t * the remaining quantity — update your stored id or it goes silently stale.\n\t */\n\treplacementOrderId: bigint | null;\n\t/** NET quote credited to the account: gross + inventoryImpactRebate − trading −\n\t * builder − penalty — the same expression the chain asserts `min_proceeds`\n\t * against, and what `settle_live_redeem_payment` actually deposits. */\n\tproceeds: number;\n\t/** Gross close value before fees (the event's redeem_amount). */\n\tgross: number;\n\t/**\n\t * Fee breakdown. `inventoryImpactRebate` is the path-independent\n\t * inventory-impact rebate credited back on the close.\n\t */\n\tfees: { trading: number; builder: number; penalty: number; inventoryImpactRebate: number };\n\tbuilderCodeId: string | null;\n\traw: {\n\t\tquantityClosed: bigint;\n\t\tremaining: bigint;\n\t\tproceeds: bigint;\n\t\tgross: bigint;\n\t\ttradingFee: bigint;\n\t\tbuilderFee: bigint;\n\t\tpenaltyFee: bigint;\n\t\tinventoryImpactRebate: bigint;\n\t};\n}\n\nexport interface ClaimReceipt {\n\tmarketId: string;\n\taccountId: string;\n\towner: string;\n\torderId: bigint;\n\tpositionRootId: bigint;\n\t/** Quote units paid out. A settled claim closes the order in full. */\n\tpayout: number;\n\traw: { payout: bigint };\n}\n\nexport interface CreateManagerReceipt {\n\taccountId: string;\n\twrapperId: string;\n\towner: string;\n\tselfOwned: boolean;\n}\n\nexport interface BalanceChangeReceipt {\n\taccountId: string;\n\tcoinType: string;\n\t/** Display value assuming a 6-decimal coin (quote + PLP both are). */\n\tamount: number;\n\tnewBalance: number;\n\traw: { amount: bigint; newBalance: bigint };\n}\n\nexport interface PlpRequestReceipt {\n\tkind: 'supply' | 'withdraw';\n\tvaultId: string;\n\taccountId: string;\n\trecipient: string;\n\t/** Feed straight into cancelSupplyPlp / cancelWithdrawPlp. */\n\tindex: bigint;\n\t/** Quote units for supply; PLP shares (6-dec) for withdraw. */\n\tamount: number;\n\traw: { amount: bigint };\n}\n\nexport interface PlpCancelReceipt {\n\tvaultId: string;\n\taccountId: string;\n\trecipient: string;\n\tindex: bigint;\n\tisSupply: boolean;\n\t/** Refund returned to the account (quote for supply, PLP for withdraw). */\n\tamount: number;\n\traw: { amount: bigint };\n}\n\nexport interface BuilderCodeReceipt {\n\taccountId: string;\n\towner: string;\n\t/** Null after unsetBuilderCode. */\n\tbuilderCodeId: string | null;\n}\n\n// --- decoders (plural = all matching events, in event order) ----------------\n\nexport function decodeMints(cfg: PredictConfig, result: DecodableTransactionResult): MintReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.predictV1 ?? cfg.packages.predict,\n\t\t'order_events',\n\t\t'OrderMinted',\n\t\torderEvents.OrderMinted,\n\t).map((e) => ({\n\t\tmarketId: normalizeSuiAddress(e.expiry_market_id),\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\torderId: e.order_id,\n\t\tpositionRootId: e.position_root_id,\n\t\tlowerTick: e.lower_tick,\n\t\thigherTick: e.higher_tick,\n\t\tentryProbability: fromRaw(e.entry_probability, 9),\n\t\tquantity: fromRaw(e.quantity, 6),\n\t\tpremium: fromRaw(e.premium, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(e.trading_fee, 6),\n\t\t\tsubsidy: fromRaw(e.fee_incentive_subsidy, 6),\n\t\t\tbuilder: fromRaw(e.builder_fee, 6),\n\t\t\tpenalty: fromRaw(e.penalty_fee, 6),\n\t\t\treferral: fromRaw(e.referral_fee, 6),\n\t\t\tinventoryImpact: fromRaw(e.inventory_impact_charge, 6),\n\t\t},\n\t\tbuilderCodeId: optId(e.builder_code_id),\n\t\traw: {\n\t\t\tquantity: e.quantity,\n\t\t\tpremium: e.premium,\n\t\t\ttradingFee: e.trading_fee,\n\t\t\tfeeIncentiveSubsidy: e.fee_incentive_subsidy,\n\t\t\tbuilderFee: e.builder_fee,\n\t\t\tpenaltyFee: e.penalty_fee,\n\t\t\treferralFee: e.referral_fee,\n\t\t\tinventoryImpactCharge: e.inventory_impact_charge,\n\t\t\tentryProbability: e.entry_probability,\n\t\t},\n\t}));\n}\n\nexport function decodeRedeems(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): RedeemReceipt[] {\n\tconst pkg = cfg.packages.predictV1 ?? cfg.packages.predict;\n\tconst live = decodeAll(\n\t\tresult,\n\t\tpkg,\n\t\t'order_events',\n\t\t'LiveOrderRedeemed',\n\t\torderEvents.LiveOrderRedeemed,\n\t).map((e): RedeemReceipt => ({\n\t\tmarketId: normalizeSuiAddress(e.expiry_market_id),\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\torderId: e.order_id,\n\t\tpositionRootId: e.position_root_id,\n\t\tquantityClosed: fromRaw(e.quantity_closed, 6),\n\t\tremaining: fromRaw(e.remaining_quantity, 6),\n\t\treplacementOrderId: e.replacement_order_id,\n\t\t// Mirrors the deployed close-side accounting exactly (the same expression\n\t\t// `min_proceeds` is asserted against): the net credited to the account is\n\t\t// redeem_amount PLUS the inventory-impact rebate, minus trading, builder and\n\t\t// penalty fees. The event's redeem_amount is GROSS.\n\t\tproceeds: fromRaw(\n\t\t\te.redeem_amount + e.inventory_impact_rebate - e.trading_fee - e.builder_fee - e.penalty_fee,\n\t\t\t6,\n\t\t),\n\t\tgross: fromRaw(e.redeem_amount, 6),\n\t\tfees: {\n\t\t\ttrading: fromRaw(e.trading_fee, 6),\n\t\t\tbuilder: fromRaw(e.builder_fee, 6),\n\t\t\tpenalty: fromRaw(e.penalty_fee, 6),\n\t\t\tinventoryImpactRebate: fromRaw(e.inventory_impact_rebate, 6),\n\t\t},\n\t\tbuilderCodeId: optId(e.builder_code_id),\n\t\traw: {\n\t\t\tquantityClosed: e.quantity_closed,\n\t\t\tremaining: e.remaining_quantity,\n\t\t\tproceeds:\n\t\t\t\te.redeem_amount + e.inventory_impact_rebate - e.trading_fee - e.builder_fee - e.penalty_fee,\n\t\t\tgross: e.redeem_amount,\n\t\t\ttradingFee: e.trading_fee,\n\t\t\tbuilderFee: e.builder_fee,\n\t\t\tpenaltyFee: e.penalty_fee,\n\t\t\tinventoryImpactRebate: e.inventory_impact_rebate,\n\t\t},\n\t}));\n\treturn live;\n}\n\nexport function decodeClaims(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): ClaimReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.predictV1 ?? cfg.packages.predict,\n\t\t'order_events',\n\t\t'SettledOrderRedeemed',\n\t\torderEvents.SettledOrderRedeemed,\n\t).map((e) => ({\n\t\tmarketId: normalizeSuiAddress(e.expiry_market_id),\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\torderId: e.order_id,\n\t\tpositionRootId: e.position_root_id,\n\t\tpayout: fromRaw(e.payout_amount, 6),\n\t\traw: { payout: e.payout_amount },\n\t}));\n}\n\nexport function decodeAccountsCreated(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): CreateManagerReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.account,\n\t\t'account_events',\n\t\t'AccountCreated',\n\t\taccountEvents.AccountCreated,\n\t).map((e) => ({\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\twrapperId: normalizeSuiAddress(e.wrapper_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\tselfOwned: e.self_owned,\n\t}));\n}\n\nfunction decodeBalanceChanges(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n\tname: 'Deposited' | 'Withdrawn',\n): BalanceChangeReceipt[] {\n\tconst layout = name === 'Deposited' ? accountEvents.Deposited : accountEvents.Withdrawn;\n\treturn decodeAll(result, cfg.packages.account, 'account_events', name, layout).map((e) => ({\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\tcoinType: e.coin_type,\n\t\tamount: fromRaw(e.amount, 6),\n\t\tnewBalance: fromRaw(e.new_balance, 6),\n\t\traw: { amount: e.amount, newBalance: e.new_balance },\n\t}));\n}\n\nexport const decodeDeposits = (\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): BalanceChangeReceipt[] => decodeBalanceChanges(cfg, result, 'Deposited');\n\nexport const decodeWithdrawals = (\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): BalanceChangeReceipt[] => decodeBalanceChanges(cfg, result, 'Withdrawn');\n\nexport function decodePlpRequests(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): PlpRequestReceipt[] {\n\tconst pkg = cfg.packages.predictV1 ?? cfg.packages.predict;\n\t// Supply/WithdrawRequested differ only in their min-out field (unused here);\n\t// pick the fields both share so either generated struct's parse feeds `make`.\n\ttype RequestedCommon = Pick<\n\t\t(typeof vaultEvents.SupplyRequested)['$inferType'],\n\t\t'pool_vault_id' | 'account_id' | 'recipient' | 'index' | 'amount'\n\t>;\n\tconst make =\n\t\t(kind: 'supply' | 'withdraw') =>\n\t\t(e: RequestedCommon): PlpRequestReceipt => ({\n\t\t\tkind,\n\t\t\tvaultId: normalizeSuiAddress(e.pool_vault_id),\n\t\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\t\trecipient: normalizeSuiAddress(e.recipient),\n\t\t\tindex: e.index,\n\t\t\tamount: fromRaw(e.amount, 6),\n\t\t\traw: { amount: e.amount },\n\t\t});\n\treturn [\n\t\t...decodeAll(result, pkg, 'vault_events', 'SupplyRequested', vaultEvents.SupplyRequested).map(\n\t\t\tmake('supply'),\n\t\t),\n\t\t...decodeAll(\n\t\t\tresult,\n\t\t\tpkg,\n\t\t\t'vault_events',\n\t\t\t'WithdrawRequested',\n\t\t\tvaultEvents.WithdrawRequested,\n\t\t).map(make('withdraw')),\n\t];\n}\n\nexport function decodePlpCancels(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): PlpCancelReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.predictV1 ?? cfg.packages.predict,\n\t\t'vault_events',\n\t\t'RequestCancelled',\n\t\tvaultEvents.RequestCancelled,\n\t).map((e) => ({\n\t\tvaultId: normalizeSuiAddress(e.pool_vault_id),\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\trecipient: normalizeSuiAddress(e.recipient),\n\t\tindex: e.index,\n\t\tisSupply: e.is_supply,\n\t\tamount: fromRaw(e.amount, 6),\n\t\traw: { amount: e.amount },\n\t}));\n}\n\nexport function decodeBuilderCodeSets(\n\tcfg: PredictConfig,\n\tresult: DecodableTransactionResult,\n): BuilderCodeReceipt[] {\n\treturn decodeAll(\n\t\tresult,\n\t\tcfg.packages.predictV1 ?? cfg.packages.predict,\n\t\t'builder_code_events',\n\t\t'BuilderCodeSet',\n\t\tbuilderCodeEvents.BuilderCodeSet,\n\t).map((e) => ({\n\t\taccountId: normalizeSuiAddress(e.account_id),\n\t\towner: normalizeSuiAddress(e.owner),\n\t\tbuilderCodeId: optId(e.builder_code_id),\n\t}));\n}\n\nexport { exactlyOne };\n"],"mappings":";;;;;;;;;AA6CA,SAAS,WAAW,GAAsC;AACzD,KAAI,EAAE,eAAe,WAAY,QAAO,EAAE;AAC1C,KAAI,OAAO,EAAE,QAAQ,SAAU,QAAO,WAAW,EAAE,IAAI;AACvD,QAAO;;AAMR,SAAS,QAAQ,GAAmB,KAAa,QAAgB,MAAuB;CACvF,MAAM,MAAM,EAAE,aAAa,EAAE;AAC7B,KAAI,KAAK;EACR,MAAM,QAAQ,IAAI,MAAM,KAAK;AAC7B,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,SACC,oBAAoB,MAAM,GAAG,KAAK,oBAAoB,IAAI,IAC1D,MAAM,OAAO,UACb,MAAM,OAAO;;AAM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,SAAS,oBAAoB,EAAE,cAAc;EAC7C,WAAW,oBAAoB,EAAE,WAAW;EAC5C,WAAW,oBAAoB,EAAE,UAAU;EAC3C,OAAO,EAAE;EACT,QAAQ,QAAQ,EAAE,QAAQ,EAAE;EAC5B,KAAK,EAAE,QAAQ,EAAE,QAAQ;EACzB;AACF,QAAO,CACN,GAAG,UAAU,QAAQ,KAAK,gBAAgB,mBAAmBC,gBAA4B,CAAC,IACzF,KAAK,SAAS,CACd,EACD,GAAG,UACF,QACA,KACA,gBACA,qBACAC,kBACA,CAAC,IAAI,KAAK,WAAW,CAAC,CACvB;;AAGF,SAAgB,iBACf,KACA,QACqB;AACrB,QAAO,UACN,QACA,IAAI,SAAS,aAAa,IAAI,SAAS,SACvC,gBACA,oBACAC,iBACA,CAAC,KAAK,OAAO;EACb,SAAS,oBAAoB,EAAE,cAAc;EAC7C,WAAW,oBAAoB,EAAE,WAAW;EAC5C,WAAW,oBAAoB,EAAE,UAAU;EAC3C,OAAO,EAAE;EACT,UAAU,EAAE;EACZ,QAAQ,QAAQ,EAAE,QAAQ,EAAE;EAC5B,KAAK,EAAE,QAAQ,EAAE,QAAQ;EACzB,EAAE;;AAGJ,SAAgB,sBACf,KACA,QACuB;AACvB,QAAO,UACN,QACA,IAAI,SAAS,aAAa,IAAI,SAAS,SACvC,uBACA,kBACAC,eACA,CAAC,KAAK,OAAO;EACb,WAAW,oBAAoB,EAAE,WAAW;EAC5C,OAAO,oBAAoB,EAAE,MAAM;EACnC,eAAe,MAAM,EAAE,gBAAgB;EACvC,EAAE"}
|
package/dist/predict/index.d.mts
CHANGED
|
@@ -13,7 +13,7 @@ import { MarketFeeds, loadLivePricer } from "./tx/trade.mjs";
|
|
|
13
13
|
import { ReadClient } from "./reads/inspect.mjs";
|
|
14
14
|
import { PricerSnapshot } from "./reads/pricing.mjs";
|
|
15
15
|
import { POS_INF_TICK, Side, binaryRangeTicks } from "./ticks.mjs";
|
|
16
|
-
import { ActiveMarket, CloseOptions, MarketDescriptor, MarketSummary, MintAmountOptions, MintOptions, MintQuote, POSITION_LOT_SIZE, PlpSupplyOptions, PlpWithdrawOptions, PoolSummary, PredictClient, PredictCompatibleClient, RedeemQuote, predict } from "./client.mjs";
|
|
16
|
+
import { ActiveMarket, CloseOptions, MarketDescriptor, MarketSummary, MintAmountOptions, MintCostOptions, MintOptions, MintQuote, POSITION_LOT_SIZE, PlpSupplyOptions, PlpWithdrawOptions, PoolSummary, PredictClient, PredictCompatibleClient, RedeemQuote, predict } from "./client.mjs";
|
|
17
17
|
import { deriveAccountWrapperId, generateAuth } from "./tx/common.mjs";
|
|
18
18
|
import { admin_d_exports } from "../contracts/deepbook_predict/admin.mjs";
|
|
19
19
|
import { builder_code_d_exports } from "../contracts/deepbook_predict/builder_code.mjs";
|
|
@@ -33,5 +33,6 @@ import { config_events_d_exports } from "../contracts/deepbook_predict/config_ev
|
|
|
33
33
|
import { order_events_d_exports } from "../contracts/deepbook_predict/order_events.mjs";
|
|
34
34
|
import { vault_events_d_exports } from "../contracts/deepbook_predict/vault_events.mjs";
|
|
35
35
|
import { U64_MAX, priceToRaw, probabilityToRaw, rawToPrice, rawToProbability, rawToUsdc, usdcToRaw } from "./units.mjs";
|
|
36
|
+
import { cost_d_exports } from "./cost.mjs";
|
|
36
37
|
import { MoveAbortError, PredictInputError, PredictMoveError, decodeMoveAbort } from "./errors.mjs";
|
|
37
|
-
export { type ActiveMarket, type BalanceChangeReceipt, type BuilderCodeReceipt, type ClaimReceipt, type CloseOptions, type CreateManagerReceipt, type DecodableEvent, type DecodableTransactionResult, type GeneratedConfig, MAINNET_CONFIG, MAINNET_DEPLOYMENT, MAINNET_UNITS, type MarketDescriptor, type MarketFeeds, type MarketSummary, type MintAmountOptions, type MintOptions, type MintQuote, type MintReceipt, type MoveAbortError, type OpenPosition, POSITION_LOT_SIZE, POS_INF_TICK, type PlpCancelReceipt, type PlpRequestReceipt, type PlpSupplyOptions, type PlpWithdrawOptions, type PoolSummary, PredictClient, type PredictCompatibleClient, type PredictConfig, PredictInputError, PredictMoveError, type PredictPackages, type PricerSnapshot, type ReadClient, type RedeemQuote, type RedeemReceipt, type Side, TESTNET_CONFIG, TESTNET_DEPLOYMENT, TESTNET_UNITS, U64_MAX, type UnderlyingConfig, admin_d_exports as adminMoveCalls, binaryRangeTicks, builder_code_events_d_exports as builderCodeEvents, builder_code_d_exports as builderCodeMoveCalls, config_events_d_exports as configEvents, decodeMoveAbort, deriveAccountWrapperId, expiry_market_d_exports as expiryMarketMoveCalls, generateAuth, getConfig, getDeployment, getUnits, loadLivePricer, market_lifecycle_cap_d_exports as marketLifecycleCapMoveCalls, market_manager_d_exports as marketManagerMoveCalls, order_events_d_exports as orderEvents, pause_cap_d_exports as pauseCapMoveCalls, plp_d_exports as plpMoveCalls, pool_valuation_cap_d_exports as poolValuationCapMoveCalls, predict, predict_account_d_exports as predictAccountMoveCalls, priceToRaw, pricing_d_exports as pricing, pricing_d_exports$1 as pricingMoveCalls, probabilityToRaw, protocol_config_d_exports as protocolConfigMoveCalls, range_codec_d_exports as rangeCodecMoveCalls, rawToPrice, rawToProbability, rawToUsdc, registry_d_exports as registryMoveCalls, toGeneratedConfig, usdcToRaw, vault_events_d_exports as vaultEvents };
|
|
38
|
+
export { type ActiveMarket, type BalanceChangeReceipt, type BuilderCodeReceipt, type ClaimReceipt, type CloseOptions, type CreateManagerReceipt, type DecodableEvent, type DecodableTransactionResult, type GeneratedConfig, MAINNET_CONFIG, MAINNET_DEPLOYMENT, MAINNET_UNITS, type MarketDescriptor, type MarketFeeds, type MarketSummary, type MintAmountOptions, type MintCostOptions, type MintOptions, type MintQuote, type MintReceipt, type MoveAbortError, type OpenPosition, POSITION_LOT_SIZE, POS_INF_TICK, type PlpCancelReceipt, type PlpRequestReceipt, type PlpSupplyOptions, type PlpWithdrawOptions, type PoolSummary, PredictClient, type PredictCompatibleClient, type PredictConfig, PredictInputError, PredictMoveError, type PredictPackages, type PricerSnapshot, type ReadClient, type RedeemQuote, type RedeemReceipt, type Side, TESTNET_CONFIG, TESTNET_DEPLOYMENT, TESTNET_UNITS, U64_MAX, type UnderlyingConfig, admin_d_exports as adminMoveCalls, binaryRangeTicks, builder_code_events_d_exports as builderCodeEvents, builder_code_d_exports as builderCodeMoveCalls, config_events_d_exports as configEvents, cost_d_exports as cost, decodeMoveAbort, deriveAccountWrapperId, expiry_market_d_exports as expiryMarketMoveCalls, generateAuth, getConfig, getDeployment, getUnits, loadLivePricer, market_lifecycle_cap_d_exports as marketLifecycleCapMoveCalls, market_manager_d_exports as marketManagerMoveCalls, order_events_d_exports as orderEvents, pause_cap_d_exports as pauseCapMoveCalls, plp_d_exports as plpMoveCalls, pool_valuation_cap_d_exports as poolValuationCapMoveCalls, predict, predict_account_d_exports as predictAccountMoveCalls, priceToRaw, pricing_d_exports as pricing, pricing_d_exports$1 as pricingMoveCalls, probabilityToRaw, protocol_config_d_exports as protocolConfigMoveCalls, range_codec_d_exports as rangeCodecMoveCalls, rawToPrice, rawToProbability, rawToUsdc, registry_d_exports as registryMoveCalls, toGeneratedConfig, usdcToRaw, vault_events_d_exports as vaultEvents };
|
package/dist/predict/index.mjs
CHANGED
|
@@ -29,5 +29,6 @@ import { pause_cap_exports } from "../contracts/deepbook_predict/pause_cap.mjs";
|
|
|
29
29
|
import { pool_valuation_cap_exports } from "../contracts/deepbook_predict/pool_valuation_cap.mjs";
|
|
30
30
|
import { protocol_config_exports } from "../contracts/deepbook_predict/protocol_config.mjs";
|
|
31
31
|
import { config_events_exports } from "../contracts/deepbook_predict/config_events.mjs";
|
|
32
|
+
import { cost_exports } from "./cost.mjs";
|
|
32
33
|
|
|
33
|
-
export { MAINNET_CONFIG, MAINNET_DEPLOYMENT, MAINNET_UNITS, POSITION_LOT_SIZE, POS_INF_TICK, PredictClient, PredictInputError, PredictMoveError, TESTNET_CONFIG, TESTNET_DEPLOYMENT, TESTNET_UNITS, U64_MAX, admin_exports as adminMoveCalls, binaryRangeTicks, builder_code_events_exports as builderCodeEvents, builder_code_exports as builderCodeMoveCalls, config_events_exports as configEvents, decodeMoveAbort, deriveAccountWrapperId, expiry_market_exports as expiryMarketMoveCalls, generateAuth, getConfig, getDeployment, getUnits, loadLivePricer, market_lifecycle_cap_exports as marketLifecycleCapMoveCalls, market_manager_exports as marketManagerMoveCalls, order_events_exports as orderEvents, pause_cap_exports as pauseCapMoveCalls, plp_exports as plpMoveCalls, pool_valuation_cap_exports as poolValuationCapMoveCalls, predict, predict_account_exports as predictAccountMoveCalls, priceToRaw, pricing_exports as pricing, pricing_exports$1 as pricingMoveCalls, probabilityToRaw, protocol_config_exports as protocolConfigMoveCalls, range_codec_exports as rangeCodecMoveCalls, rawToPrice, rawToProbability, rawToUsdc, registry_exports as registryMoveCalls, toGeneratedConfig, usdcToRaw, vault_events_exports as vaultEvents };
|
|
34
|
+
export { MAINNET_CONFIG, MAINNET_DEPLOYMENT, MAINNET_UNITS, POSITION_LOT_SIZE, POS_INF_TICK, PredictClient, PredictInputError, PredictMoveError, TESTNET_CONFIG, TESTNET_DEPLOYMENT, TESTNET_UNITS, U64_MAX, admin_exports as adminMoveCalls, binaryRangeTicks, builder_code_events_exports as builderCodeEvents, builder_code_exports as builderCodeMoveCalls, config_events_exports as configEvents, cost_exports as cost, decodeMoveAbort, deriveAccountWrapperId, expiry_market_exports as expiryMarketMoveCalls, generateAuth, getConfig, getDeployment, getUnits, loadLivePricer, market_lifecycle_cap_exports as marketLifecycleCapMoveCalls, market_manager_exports as marketManagerMoveCalls, order_events_exports as orderEvents, pause_cap_exports as pauseCapMoveCalls, plp_exports as plpMoveCalls, pool_valuation_cap_exports as poolValuationCapMoveCalls, predict, predict_account_exports as predictAccountMoveCalls, priceToRaw, pricing_exports as pricing, pricing_exports$1 as pricingMoveCalls, probabilityToRaw, protocol_config_exports as protocolConfigMoveCalls, range_codec_exports as rangeCodecMoveCalls, rawToPrice, rawToProbability, rawToUsdc, registry_exports as registryMoveCalls, toGeneratedConfig, usdcToRaw, vault_events_exports as vaultEvents };
|
package/dist/predict/pricing.mjs
CHANGED
|
@@ -31,7 +31,7 @@ async function resolvePositionsTable(client, config, owner) {
|
|
|
31
31
|
const wrapperContent = await contentOf(client, deriveAccountWrapperIdFrom(config, owner));
|
|
32
32
|
if (!wrapperContent) return null;
|
|
33
33
|
const accountUid = normalizeSuiAddress(AccountWrapper.parse(wrapperContent).account.account_id);
|
|
34
|
-
const fieldContent = await contentOf(client, deriveDynamicFieldID(accountUid, `${config.accountPackageId}::account::DataKey<${config.
|
|
34
|
+
const fieldContent = await contentOf(client, deriveDynamicFieldID(accountUid, `${config.accountPackageId}::account::DataKey<${config.predictPackageIdV1}::predict_account::PredictApp>`, new Uint8Array([0])));
|
|
35
35
|
if (!fieldContent) return {
|
|
36
36
|
accountUid,
|
|
37
37
|
positionsTableId: null,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"positions.mjs","names":[],"sources":["../../../src/predict/reads/positions.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs } from '@mysten/sui/bcs';\nimport type { ClientWithCoreApi } from '@mysten/sui/client';\nimport { deriveDynamicFieldID, normalizeSuiAddress } from '@mysten/sui/utils';\nimport { type GeneratedConfig } from '../config/generated.js';\nimport { deriveAccountWrapperIdFrom } from '../tx/common.js';\nimport { AccountWrapper } from '../../account.js';\nimport { PositionKey, PredictData } from '../../contracts/deepbook_predict/predict_account.js';\n\n// ============================================================================\n// Chain-only position enumeration.\n//\n// Every open position is tracked under the owner's account:\n// `predict_account::PredictData.positions` is a\n// `Table<PositionKey{expiry_market_id, order_id}, Position>` — and Table\n// entries are dynamic fields, so the KEYS (everything redeem/claim need)\n// arrive directly from a dynamic-field listing. No indexer, no simulation.\n//\n// The walk (all parsing is exact BCS via `include: {content: true}`; the account\n// and PredictData struct layouts come from the generated `contracts/*` MoveStructs\n// so they can't drift from the deployed `account`/`predict_account` sources):\n// 1. wrapper object (id derived client-side) → account UID\n// 2. derived DataKey<PredictApp> field object → positions Table id\n// 3. listDynamicFields(table) → PositionKey per entry\n// Steps 1-2 resolve ids that are immutable once created — cache them per\n// owner (the facade does) and steady state is ONE call per page of positions.\n// ============================================================================\n\n// sui::dynamic_field::Field<DataKey<PredictApp>, PredictData>. DataKey is\n// source-empty, but Move inserts a hidden `dummy_field: bool` into empty\n// structs — so the name occupies ONE zero byte between id and value (and the\n// same byte is the derived-field key, below). The `value` uses the generated\n// `PredictData` layout so it tracks the deployed struct.\nconst PredictDataFieldBcs = bcs.struct('Field<DataKey,PredictData>', {\n\tid: bcs.Address,\n\tname: bcs.bool(), // DataKey's hidden dummy_field\n\tvalue: PredictData,\n});\n\n/** One open position — the coordinates redeem/claim/hasPosition take. */\nexport interface OpenPosition {\n\tmarketId: string;\n\torderId: bigint;\n}\n\n/** Resolved-once ids for an owner's position store (cache these). */\nexport interface PositionsHandle {\n\taccountUid: string;\n\t/** Null until the account's Predict data exists (first trade/builder-code). */\n\tpositionsTableId: string | null;\n\t/** Open-position count at resolution time (from the Table's size). */\n\tpositionCount: bigint;\n}\n\nasync function contentOf(client: ClientWithCoreApi, objectId: string): Promise<Uint8Array | null> {\n\ttry {\n\t\tconst { object } = await client.core.getObject({ objectId, include: { content: true } });\n\t\treturn object.content ?? null;\n\t} catch (e) {\n\t\t// Only a genuinely absent object means \"no positions\" (never-onboarded\n\t\t// owner, or no Predict data yet). Anything else — transport failures,\n\t\t// rate limits — must surface, not silently read as an empty portfolio.\n\t\tif (/not.?found|does not exist|deleted|NOT_FOUND/i.test(String(e))) return null;\n\t\tthrow e;\n\t}\n}\n\n/**\n * Resolve the immutable id chain for an owner's positions: wrapper → account\n * UID → PredictData → positions Table. Returns null when the owner has never\n * created a Predict account.\n */\nexport async function resolvePositionsTable(\n\tclient: ClientWithCoreApi,\n\tconfig: GeneratedConfig,\n\towner: string,\n): Promise<PositionsHandle | null> {\n\tconst wrapperContent = await contentOf(client, deriveAccountWrapperIdFrom(config, owner));\n\tif (!wrapperContent) return null;\n\tconst accountUid = normalizeSuiAddress(AccountWrapper.parse(wrapperContent).account.account_id);\n\n\t// The PredictData field id is derivable — no listing needed for this hop.\n\tconst dataFieldId = deriveDynamicFieldID(\n\t\taccountUid,\n\t\t`${config.accountPackageId}::account::DataKey<${config.
|
|
1
|
+
{"version":3,"file":"positions.mjs","names":[],"sources":["../../../src/predict/reads/positions.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs } from '@mysten/sui/bcs';\nimport type { ClientWithCoreApi } from '@mysten/sui/client';\nimport { deriveDynamicFieldID, normalizeSuiAddress } from '@mysten/sui/utils';\nimport { type GeneratedConfig } from '../config/generated.js';\nimport { deriveAccountWrapperIdFrom } from '../tx/common.js';\nimport { AccountWrapper } from '../../account.js';\nimport { PositionKey, PredictData } from '../../contracts/deepbook_predict/predict_account.js';\n\n// ============================================================================\n// Chain-only position enumeration.\n//\n// Every open position is tracked under the owner's account:\n// `predict_account::PredictData.positions` is a\n// `Table<PositionKey{expiry_market_id, order_id}, Position>` — and Table\n// entries are dynamic fields, so the KEYS (everything redeem/claim need)\n// arrive directly from a dynamic-field listing. No indexer, no simulation.\n//\n// The walk (all parsing is exact BCS via `include: {content: true}`; the account\n// and PredictData struct layouts come from the generated `contracts/*` MoveStructs\n// so they can't drift from the deployed `account`/`predict_account` sources):\n// 1. wrapper object (id derived client-side) → account UID\n// 2. derived DataKey<PredictApp> field object → positions Table id\n// 3. listDynamicFields(table) → PositionKey per entry\n// Steps 1-2 resolve ids that are immutable once created — cache them per\n// owner (the facade does) and steady state is ONE call per page of positions.\n// ============================================================================\n\n// sui::dynamic_field::Field<DataKey<PredictApp>, PredictData>. DataKey is\n// source-empty, but Move inserts a hidden `dummy_field: bool` into empty\n// structs — so the name occupies ONE zero byte between id and value (and the\n// same byte is the derived-field key, below). The `value` uses the generated\n// `PredictData` layout so it tracks the deployed struct.\nconst PredictDataFieldBcs = bcs.struct('Field<DataKey,PredictData>', {\n\tid: bcs.Address,\n\tname: bcs.bool(), // DataKey's hidden dummy_field\n\tvalue: PredictData,\n});\n\n/** One open position — the coordinates redeem/claim/hasPosition take. */\nexport interface OpenPosition {\n\tmarketId: string;\n\torderId: bigint;\n}\n\n/** Resolved-once ids for an owner's position store (cache these). */\nexport interface PositionsHandle {\n\taccountUid: string;\n\t/** Null until the account's Predict data exists (first trade/builder-code). */\n\tpositionsTableId: string | null;\n\t/** Open-position count at resolution time (from the Table's size). */\n\tpositionCount: bigint;\n}\n\nasync function contentOf(client: ClientWithCoreApi, objectId: string): Promise<Uint8Array | null> {\n\ttry {\n\t\tconst { object } = await client.core.getObject({ objectId, include: { content: true } });\n\t\treturn object.content ?? null;\n\t} catch (e) {\n\t\t// Only a genuinely absent object means \"no positions\" (never-onboarded\n\t\t// owner, or no Predict data yet). Anything else — transport failures,\n\t\t// rate limits — must surface, not silently read as an empty portfolio.\n\t\tif (/not.?found|does not exist|deleted|NOT_FOUND/i.test(String(e))) return null;\n\t\tthrow e;\n\t}\n}\n\n/**\n * Resolve the immutable id chain for an owner's positions: wrapper → account\n * UID → PredictData → positions Table. Returns null when the owner has never\n * created a Predict account.\n */\nexport async function resolvePositionsTable(\n\tclient: ClientWithCoreApi,\n\tconfig: GeneratedConfig,\n\towner: string,\n): Promise<PositionsHandle | null> {\n\tconst wrapperContent = await contentOf(client, deriveAccountWrapperIdFrom(config, owner));\n\tif (!wrapperContent) return null;\n\tconst accountUid = normalizeSuiAddress(AccountWrapper.parse(wrapperContent).account.account_id);\n\n\t// The PredictData field id is derivable — no listing needed for this hop.\n\tconst dataFieldId = deriveDynamicFieldID(\n\t\taccountUid,\n\t\t`${config.accountPackageId}::account::DataKey<${config.predictPackageIdV1}::predict_account::PredictApp>`,\n\t\tnew Uint8Array([0]), // DataKey's hidden dummy_field: bool = false\n\t);\n\tconst fieldContent = await contentOf(client, dataFieldId);\n\tif (!fieldContent) return { accountUid, positionsTableId: null, positionCount: 0n };\n\n\tconst data = PredictDataFieldBcs.parse(fieldContent).value;\n\treturn {\n\t\taccountUid,\n\t\tpositionsTableId: normalizeSuiAddress(data.positions.id),\n\t\tpositionCount: data.positions.size,\n\t};\n}\n\n/**\n * List open positions from a resolved positions Table: one call per page,\n * keys parsed from the dynamic-field NAMES (no per-entry fetches).\n */\nexport async function positionsFromTable(\n\tclient: ClientWithCoreApi,\n\tpositionsTableId: string,\n\topts: { limit?: number; maxPages?: number } = {},\n): Promise<OpenPosition[]> {\n\tconst limit = opts.limit ?? 1000;\n\tconst maxPages = opts.maxPages ?? 10;\n\tconst out: OpenPosition[] = [];\n\tlet cursor: string | undefined = undefined;\n\tfor (let page = 0; page < maxPages; page++) {\n\t\tconst res = await client.core.listDynamicFields({\n\t\t\tparentId: positionsTableId,\n\t\t\tlimit,\n\t\t\tcursor,\n\t\t});\n\t\tfor (const entry of res.dynamicFields) {\n\t\t\tconst key = PositionKey.parse(entry.name.bcs);\n\t\t\tout.push({\n\t\t\t\tmarketId: normalizeSuiAddress(key.expiry_market_id),\n\t\t\t\torderId: key.order_id,\n\t\t\t});\n\t\t}\n\t\tif (!res.hasNextPage || !res.cursor) return out;\n\t\tcursor = res.cursor;\n\t}\n\tthrow new Error(\n\t\t`positions listing exceeded ${maxPages} pages (${out.length} so far) — raise maxPages`,\n\t);\n}\n\n/** Convenience: resolve + list in one call (uncached; the facade caches). */\nexport async function positions(\n\tclient: ClientWithCoreApi,\n\tconfig: GeneratedConfig,\n\towner: string,\n\topts: { limit?: number; maxPages?: number } = {},\n): Promise<OpenPosition[]> {\n\tconst handle = await resolvePositionsTable(client, config, owner);\n\tif (!handle?.positionsTableId) return [];\n\treturn positionsFromTable(client, handle.positionsTableId, opts);\n}\n"],"mappings":";;;;;;;AAkCA,MAAM,sBAAsB,IAAI,OAAO,8BAA8B;CACpE,IAAI,IAAI;CACR,MAAM,IAAI,MAAM;CAChB,OAAO;CACP,CAAC;AAiBF,eAAe,UAAU,QAA2B,UAA8C;AACjG,KAAI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C,IAAI,eAAe,CAAC,IAAI,OAAQ,QAAO;AAC5C,WAAS,IAAI;;AAEd,OAAM,IAAI,MACT,8BAA8B,SAAS,UAAU,IAAI,OAAO,2BAC5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trade.d.mts","names":[],"sources":["../../../src/predict/tx/trade.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"trade.d.mts","names":[],"sources":["../../../src/predict/tx/trade.ts"],"mappings":";;;;UAqBiB,WAAA;EAChB,QAAA;EACA,sBAAA;EACA,oBAAA;AAAA;AAAA,iBAQe,cAAA,CACf,MAAA,EAAQ,eAAA,EACR,IAAA;EAAQ,cAAA;AAAA,IAA2B,WAAA,IAChC,EAAA,EAAI,WAAA,KAAgB,iBAAA"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { U64_MAX } from "../units.mjs";
|
|
2
2
|
import { withAuth } from "./common.mjs";
|
|
3
|
-
import { loadLivePricer as loadLivePricer$1, mintExactAmount as mintExactAmount$1, mintExactQuantity as mintExactQuantity$1, redeemLive as redeemLive$1, redeemSettled as redeemSettled$1 } from "../../contracts/deepbook_predict/expiry_market.mjs";
|
|
3
|
+
import { loadLivePricer as loadLivePricer$1, mintExactAmount as mintExactAmount$1, mintExactCost as mintExactCost$1, mintExactQuantity as mintExactQuantity$1, redeemLive as redeemLive$1, redeemSettled as redeemSettled$1 } from "../../contracts/deepbook_predict/expiry_market.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/predict/tx/trade.ts
|
|
6
6
|
const authed = {
|
|
7
7
|
mintExactQuantity: withAuth(mintExactQuantity$1),
|
|
8
8
|
mintExactAmount: withAuth(mintExactAmount$1),
|
|
9
|
+
mintExactCost: withAuth(mintExactCost$1),
|
|
9
10
|
redeemLive: withAuth(redeemLive$1),
|
|
10
11
|
redeemSettled: withAuth(redeemSettled$1)
|
|
11
12
|
};
|
|
@@ -56,6 +57,21 @@ function mintExactAmount(config, args) {
|
|
|
56
57
|
}
|
|
57
58
|
}));
|
|
58
59
|
}
|
|
60
|
+
/** Mint within an all-in budget, including fees, using the v2 entrypoint. */
|
|
61
|
+
function mintExactCost(config, args) {
|
|
62
|
+
return liveTrade(config, args, (pricer) => authed.mintExactCost({
|
|
63
|
+
config,
|
|
64
|
+
arguments: {
|
|
65
|
+
market: args.expiryMarketId,
|
|
66
|
+
wrapper: args.wrapperId,
|
|
67
|
+
pricer,
|
|
68
|
+
lowerTick: args.lowerTick,
|
|
69
|
+
higherTick: args.higherTick,
|
|
70
|
+
maxCost: args.maxCostRaw,
|
|
71
|
+
minQuantity: args.minQuantityRaw
|
|
72
|
+
}
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
59
75
|
function redeemLive(config, args) {
|
|
60
76
|
return liveTrade(config, args, (pricer) => authed.redeemLive({
|
|
61
77
|
config,
|
|
@@ -82,5 +98,5 @@ function redeemSettled(config, args) {
|
|
|
82
98
|
}
|
|
83
99
|
|
|
84
100
|
//#endregion
|
|
85
|
-
export { loadLivePricer, mintExactAmount, mintExactQuantity, redeemLive, redeemSettled };
|
|
101
|
+
export { loadLivePricer, mintExactAmount, mintExactCost, mintExactQuantity, redeemLive, redeemSettled };
|
|
86
102
|
//# sourceMappingURL=trade.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trade.mjs","names":["expiryMarket.mintExactQuantity","expiryMarket.mintExactAmount","expiryMarket.redeemLive","expiryMarket.redeemSettled","expiryMarket.loadLivePricer"],"sources":["../../../src/predict/tx/trade.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport type { Transaction, TransactionResult } from '@mysten/sui/transactions';\nimport type { GeneratedConfig } from '../config/generated.js';\nimport { U64_MAX } from '../units.js';\nimport * as expiryMarket from '../../contracts/deepbook_predict/expiry_market.js';\nimport { withAuth } from './common.js';\n\n// The
|
|
1
|
+
{"version":3,"file":"trade.mjs","names":["expiryMarket.mintExactQuantity","expiryMarket.mintExactAmount","expiryMarket.mintExactCost","expiryMarket.redeemLive","expiryMarket.redeemSettled","expiryMarket.loadLivePricer"],"sources":["../../../src/predict/tx/trade.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport type { Transaction, TransactionResult } from '@mysten/sui/transactions';\nimport type { GeneratedConfig } from '../config/generated.js';\nimport { U64_MAX } from '../units.js';\nimport * as expiryMarket from '../../contracts/deepbook_predict/expiry_market.js';\nimport { withAuth } from './common.js';\n\n// The trade calls with their `auth` argument already supplied (see `withAuth`): each\n// takes its generated options minus that slot and expands to auth → call.\nconst authed = {\n\tmintExactQuantity: withAuth(expiryMarket.mintExactQuantity),\n\tmintExactAmount: withAuth(expiryMarket.mintExactAmount),\n\tmintExactCost: withAuth(expiryMarket.mintExactCost),\n\tredeemLive: withAuth(expiryMarket.redeemLive),\n\tredeemSettled: withAuth(expiryMarket.redeemSettled),\n};\n\n// The oracle feed object ids a live market's pricer reads. Grouped so callers pass one\n// bundle; the deployment's per-underlying ids live in `cfg.underlyings[symbol]` (see\n// `src/config/testnet.ts`), named to match `deployment.testnet.json`.\nexport interface MarketFeeds {\n\tpythFeed: string;\n\tblockScholesValueStore: string;\n\tblockScholesSviStore: string;\n}\n\n// Load a fresh `Pricer` from the live oracle feeds. Every live-flow trade call\n// (`mint_*`, `redeem_live`) borrows this `&Pricer` and it must be loaded first in the\n// PTB. Deployed sig `load_live_pricer` (expiry_market.move): market, config,\n// propbook_registry (&OracleRegistry), pyth, bs_values, bs_svi, clock (auto-injected).\n// `config` and `propbook_registry` are supplied by the config slice, not named here.\nexport function loadLivePricer(\n\tconfig: GeneratedConfig,\n\targs: { expiryMarketId: string } & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn (tx) =>\n\t\ttx.add(\n\t\t\texpiryMarket.loadLivePricer({\n\t\t\t\tconfig,\n\t\t\t\targuments: {\n\t\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\t\tpyth: args.pythFeed,\n\t\t\t\t\tbsValues: args.blockScholesValueStore,\n\t\t\t\t\tbsSvi: args.blockScholesSviStore,\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n}\n\n// The three commands every live-flow trade is: load a fresh market-bound `Pricer`, mint\n// owner auth, then the one `expiry_market::*` call that consumes both. Only the pricer is\n// composed here — `build` returns an `authed.*` call, which is the other two commands.\nfunction liveTrade(\n\tconfig: GeneratedConfig,\n\targs: { expiryMarketId: string } & MarketFeeds,\n\tbuild: (pricer: TransactionResult) => (tx: Transaction) => TransactionResult,\n): (tx: Transaction) => TransactionResult {\n\treturn (tx) => {\n\t\tconst pricer = tx.add(loadLivePricer(config, args));\n\t\treturn tx.add(build(pricer));\n\t};\n}\n\n// Mint a position of an exact `quantityRaw`, capped by cost/probability ceilings,\n// returning the new order id (u256). Command order is pricer → auth → mint (auth is a\n// hot potato consumed by this call). `maxCostRaw`/`maxProbabilityRaw` default to\n// `U64_MAX` (no slippage cap). Deployed sig `mint_exact_quantity`.\nexport function mintExactQuantity(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tquantityRaw: bigint;\n\t\tmaxCostRaw?: bigint;\n\t\tmaxProbabilityRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer) =>\n\t\tauthed.mintExactQuantity({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\twrapper: args.wrapperId,\n\t\t\t\tpricer,\n\t\t\t\tlowerTick: args.lowerTick,\n\t\t\t\thigherTick: args.higherTick,\n\t\t\t\tquantity: args.quantityRaw,\n\t\t\t\tmaxCost: args.maxCostRaw ?? U64_MAX,\n\t\t\t\tmaxProbability: args.maxProbabilityRaw ?? U64_MAX,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Mint by spending up to `maxPremiumRaw` (raw quote units), enforcing a `minQuantityRaw`\n// floor on the position received and a `maxCostRaw` all-in ceiling, returning the new\n// order id (u256). Command order is pricer → auth → mint. Deployed sig\n// `mint_exact_amount`: …, max_premium, min_quantity, max_cost, root.\nexport function mintExactAmount(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tmaxPremiumRaw: bigint;\n\t\tminQuantityRaw: bigint;\n\t\tmaxCostRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer) =>\n\t\tauthed.mintExactAmount({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\twrapper: args.wrapperId,\n\t\t\t\tpricer,\n\t\t\t\tlowerTick: args.lowerTick,\n\t\t\t\thigherTick: args.higherTick,\n\t\t\t\tmaxPremium: args.maxPremiumRaw,\n\t\t\t\tminQuantity: args.minQuantityRaw,\n\t\t\t\tmaxCost: args.maxCostRaw ?? U64_MAX,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/** Mint within an all-in budget, including fees, using the v2 entrypoint. */\nexport function mintExactCost(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tmaxCostRaw: bigint;\n\t\tminQuantityRaw: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer) =>\n\t\tauthed.mintExactCost({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\twrapper: args.wrapperId,\n\t\t\t\tpricer,\n\t\t\t\tlowerTick: args.lowerTick,\n\t\t\t\thigherTick: args.higherTick,\n\t\t\t\tmaxCost: args.maxCostRaw,\n\t\t\t\tminQuantity: args.minQuantityRaw,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Owner-authorized redeem of a live (not-yet-settled) position: close `closeQuantityRaw`\n// of `orderId` at the live pricer's mark, enforcing close-side slippage floors\n// (`minProbabilityRaw`/`minProceedsRaw`, default 0 = uncapped). Returns `Option<u256>`:\n// the replacement order id when a partial close leaves quantity open, else none. Command\n// order is pricer → auth → redeem. Deployed sig `redeem_live`.\nexport function redeemLive(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\torderId: bigint;\n\t\tcloseQuantityRaw: bigint;\n\t\tminProbabilityRaw?: bigint;\n\t\tminProceedsRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer) =>\n\t\tauthed.redeemLive({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\twrapper: args.wrapperId,\n\t\t\t\tpricer,\n\t\t\t\torderId: args.orderId,\n\t\t\t\tcloseQuantity: args.closeQuantityRaw,\n\t\t\t\tminProbability: args.minProbabilityRaw ?? 0n,\n\t\t\t\tminProceeds: args.minProceedsRaw ?? 0n,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Owner-authorized redeem of a settled position: closes `orderId` IN FULL against the\n// recorded settlement price (the deployed entrypoint takes no quantity — a settled claim\n// is all-or-nothing). No live pricer (settlement price is fixed); auth is consumed by the\n// call. Deployed sig `redeem_settled` (owner-auth form). The keeper-facing\n// `redeem_settled_permissionless` is a separate entrypoint, out of scope for this SDK.\nexport function redeemSettled(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\torderId: bigint;\n\t},\n): (tx: Transaction) => TransactionResult {\n\treturn authed.redeemSettled({\n\t\tconfig,\n\t\targuments: {\n\t\t\tmarket: args.expiryMarketId,\n\t\t\twrapper: args.wrapperId,\n\t\t\torderId: args.orderId,\n\t\t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,KAAK;GACd,aAAa,KAAK;GAClB;EACD,CAAC,CACF;;AAQF,SAAgB,WACf,QACA,MAQyC;AACzC,QAAO,UAAU,QAAQ,OAAO,WAC/B,OAAO,WAAW;EACjB;EACA,WAAW;GACV,QAAQ,KAAK;GACb,SAAS,KAAK;GACd;GACA,SAAS,KAAK;GACd,eAAe,KAAK;GACpB,gBAAgB,KAAK,qBAAqB;GAC1C,aAAa,KAAK,kBAAkB;GACpC;EACD,CAAC,CACF;;AAQF,SAAgB,cACf,QACA,MAKyC;AACzC,QAAO,OAAO,cAAc;EAC3B;EACA,WAAW;GACV,QAAQ,KAAK;GACb,SAAS,KAAK;GACd,SAAS,KAAK;GACd;EACD,CAAC"}
|
package/dist/sessions.d.mts
CHANGED
|
@@ -14,8 +14,10 @@ import { Transaction, TransactionArgument, TransactionResult } from "@mysten/sui
|
|
|
14
14
|
* registry. `sessionsPackageId` and `sessionsConfig` come from the sessions deployment.
|
|
15
15
|
*/
|
|
16
16
|
interface SessionsConfig extends DeepbookSessionsConfig {
|
|
17
|
-
/** The `deepbook_sessions` Move package id. */
|
|
17
|
+
/** The latest `deepbook_sessions` Move-call package id. */
|
|
18
18
|
sessionsPackageId: string;
|
|
19
|
+
/** Original ID for v1 structs. Omit only for an unupgraded custom deployment. */
|
|
20
|
+
sessionsPackageIdV1?: string;
|
|
19
21
|
/** The shared `SessionsConfig` object id. */
|
|
20
22
|
sessionsConfig: string;
|
|
21
23
|
/** The shared `account` Move package id. */
|
|
@@ -184,6 +186,20 @@ declare class SessionsContract {
|
|
|
184
186
|
minQuantity: number | bigint;
|
|
185
187
|
maxCost: number | bigint;
|
|
186
188
|
}): (tx: Transaction) => TransactionResult;
|
|
189
|
+
/**
|
|
190
|
+
* Mint within an all-in budget as a session. Amounts are raw Move units.
|
|
191
|
+
* Requires Sessions/Predict v2 (currently Testnet; Mainnet is still v1).
|
|
192
|
+
*/
|
|
193
|
+
mintExactCost(params: {
|
|
194
|
+
expiryMarketId: string;
|
|
195
|
+
wrapperId: string;
|
|
196
|
+
protocolConfig: string;
|
|
197
|
+
pricer: TransactionArgument;
|
|
198
|
+
lowerTick: number | bigint;
|
|
199
|
+
higherTick: number | bigint;
|
|
200
|
+
maxCost: number | bigint;
|
|
201
|
+
minQuantity: number | bigint;
|
|
202
|
+
}): (tx: Transaction) => TransactionResult;
|
|
187
203
|
/**
|
|
188
204
|
* @description Close part or all of a live position at the pricer's mark, as `session`.
|
|
189
205
|
* `minProbability` / `minProceeds` are close-side slippage floors; `0` disables either,
|
package/dist/sessions.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessions.d.mts","names":[],"sources":["../src/sessions.ts"],"mappings":";;;;;;;;;;;AA2BA;;;;UAAiB,cAAA,SAAuB,sBAAA;EAEvC;EAAA,iBAAA;EAIA;EAFA,cAAA;EAIe;EAFf,gBAAA;
|
|
1
|
+
{"version":3,"file":"sessions.d.mts","names":[],"sources":["../src/sessions.ts"],"mappings":";;;;;;;;;;;AA2BA;;;;UAAiB,cAAA,SAAuB,sBAAA;EAEvC;EAAA,iBAAA;EAIA;EAFA,mBAAA;EAMA;EAJA,cAAA;EAIe;EAFf,gBAAA;EAU+B;EAR/B,eAAA;AAAA;;AAgBD;;;;UARiB,eAAA;EAuBD;EArBf,gBAAA;;EAEA,4BAAA;AAAA;;UAIgB,kBAAA;EAiBuC;EAfvD,cAAA;AAAA;;;;;;;AA6BD;;;;iBAhBgB,iBAAA,CACf,OAAA,EAAS,UAAA,GACP,cAAA,GAAiB,eAAA,GAAkB,kBAAA;AAiBtC;AAAA,cAHa,uBAAA;;cAGA,wBAAA;;UAkBI,YAAA;EAAY;EAE5B,OAAA;EAAA;EAEA,WAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAsCY,gBAAA;EAAA;cAGA,MAAA,EAAQ,cAAA;EAgEpB;;;;EA9CA,sBAAA,CAAuB,KAAA;EA+CV;;;;;EAnCb,eAAA,CAAgB,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,WAAA;;;;;;;;;;;;;;;SA8BN,cAAA,CAAe,QAAA,EAAU,UAAA,GAAa,YAAA;;SAqBtC,cAAA,CAAe,MAAA,WAAiB,YAAA,IAAgB,KAAA,oBAAyB,YAAA;;;;;;;SAYzE,eAAA,CAAgB,MAAA,WAAiB,YAAA,IAAgB,KAAA,oBAAyB,YAAA;AAAA"}
|
package/dist/sessions.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { MAINNET_SESSIONS } from "./deployments/mainnet.mjs";
|
|
|
2
2
|
import { TESTNET_DEPLOYMENT, TESTNET_SESSIONS, TESTNET_UNITS } from "./deployments/testnet.mjs";
|
|
3
3
|
import { getDeployment, getUnits } from "./deployments/index.mjs";
|
|
4
4
|
import { AccountContract } from "./account.mjs";
|
|
5
|
-
import { SessionAuthorized, SessionRevoked, SessionsApp, SessionsData, authorizeSession, mintExactAmount, mintExactQuantity, redeemLive, redeemSettled, revokeSession, sessionExpirationMs, sessions_exports } from "./contracts/deepbook_sessions/sessions.mjs";
|
|
5
|
+
import { SessionAuthorized, SessionRevoked, SessionsApp, SessionsData, authorizeSession, mintExactAmount, mintExactCost, mintExactQuantity, redeemLive, redeemSettled, revokeSession, sessionExpirationMs, sessions_exports } from "./contracts/deepbook_sessions/sessions.mjs";
|
|
6
6
|
import { session_config_exports } from "./contracts/deepbook_sessions/session_config.mjs";
|
|
7
7
|
import { bcs } from "@mysten/sui/bcs";
|
|
8
8
|
import { deriveDynamicFieldID, deriveObjectID } from "@mysten/sui/utils";
|
|
@@ -103,7 +103,7 @@ var SessionsContract = class {
|
|
|
103
103
|
* bulk on-chain read, so this is the route to enumerating grants.
|
|
104
104
|
*/
|
|
105
105
|
deriveSessionsFieldId(owner) {
|
|
106
|
-
return deriveDynamicFieldID(this.deriveAccountId(owner), `${this.#config.accountPackageId}::account::DataKey<${this.#config.sessionsPackageId}::sessions::SessionsApp>`, new Uint8Array([0]));
|
|
106
|
+
return deriveDynamicFieldID(this.deriveAccountId(owner), `${this.#config.accountPackageId}::account::DataKey<${this.#config.sessionsPackageIdV1 ?? this.#config.sessionsPackageId}::sessions::SessionsApp>`, new Uint8Array([0]));
|
|
107
107
|
}
|
|
108
108
|
/**
|
|
109
109
|
* @description Grant `session` authority over the Account until `now + durationMs`.
|
|
@@ -205,6 +205,26 @@ var SessionsContract = class {
|
|
|
205
205
|
}));
|
|
206
206
|
}
|
|
207
207
|
/**
|
|
208
|
+
* Mint within an all-in budget as a session. Amounts are raw Move units.
|
|
209
|
+
* Requires Sessions/Predict v2 (currently Testnet; Mainnet is still v1).
|
|
210
|
+
*/
|
|
211
|
+
mintExactCost(params) {
|
|
212
|
+
return (tx) => tx.add(mintExactCost({
|
|
213
|
+
config: this.#generatedConfig,
|
|
214
|
+
arguments: {
|
|
215
|
+
market: params.expiryMarketId,
|
|
216
|
+
accountRegistry: this.#config.accountRegistry,
|
|
217
|
+
wrapper: params.wrapperId,
|
|
218
|
+
config: params.protocolConfig,
|
|
219
|
+
pricer: params.pricer,
|
|
220
|
+
lowerTick: params.lowerTick,
|
|
221
|
+
higherTick: params.higherTick,
|
|
222
|
+
maxCost: params.maxCost,
|
|
223
|
+
minQuantity: params.minQuantity
|
|
224
|
+
}
|
|
225
|
+
}));
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
208
228
|
* @description Close part or all of a live position at the pricer's mark, as `session`.
|
|
209
229
|
* `minProbability` / `minProceeds` are close-side slippage floors; `0` disables either,
|
|
210
230
|
* and OMITTING them is `0` — unlike the mint caps, which are required. On a delegated
|