{"version":3,"file":"markets.mjs","names":["plp.activeExpiryMarkets","registry.expiryMarketId","expiryMarket.expiry","expiryMarket.tickSize","expiryMarket.admissionTickSize","expiryMarket.mintPaused","expiryMarket.referenceTick","rangeCodec.strikeFromTick","pricing.rangePrice","pricing.probability","expiryMarket.settlementPrice","expiryMarket.currentNav"],"sources":["../../../src/predict/reads/markets.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { Transaction } from '@mysten/sui/transactions';\nimport { type GeneratedConfig } from '../config/generated.js';\nimport { type UnderlyingConfig } from '../config/index.js';\nimport { type FeePolicy } from '../cost.js';\nimport { PredictMoveError } from '../errors.js';\nimport { POS_INF_TICK } from '../ticks.js';\nimport { loadLivePricer, type MarketFeeds } from '../tx/trade.js';\nimport * as expiryMarket from '../../contracts/deepbook_predict/expiry_market.js';\nimport * as plp from '../../contracts/deepbook_predict/plp.js';\nimport * as pricing from '../../contracts/deepbook_predict/pricing.js';\nimport * as rangeCodec from '../../contracts/deepbook_predict/range_codec.js';\nimport * as registry from '../../contracts/deepbook_predict/registry.js';\nimport { inspectReturns, type ReadClient } from './inspect.js';\nimport { parseOptionalId, parseOptionalU64, parseU64LE, parseVectorOfIds } from './parse.js';\n\n// On-chain ids of the pool's active (live, not-yet-settled) expiry markets.\n// `plp::active_expiry_markets(vault)` — see packages/predict/sources/plp/plp.move:179.\nexport async function activeMarketIds(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n): Promise<string[]> {\n\tconst tx = new Transaction();\n\ttx.add(plp.activeExpiryMarkets({ config }));\n\tconst [cmd0] = await inspectReturns(client, tx);\n\treturn parseVectorOfIds(cmd0[0]);\n}\n\n// The expiry market id for one underlying at one expiry, or null if none exists.\n// `registry::expiry_market_id(registry, propbook_underlying_id: u32, expiry: u64):\n// Option<ID>` — see packages/predict/sources/registry/registry.move:58.\nexport async function expiryMarketId(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\tunderlying: UnderlyingConfig,\n\texpiryMs: bigint,\n): Promise<string | null> {\n\tconst tx = new Transaction();\n\ttx.add(\n\t\tregistry.expiryMarketId({\n\t\t\tconfig,\n\t\t\targuments: { propbookUnderlyingId: underlying.propbookUnderlyingId, expiry: expiryMs },\n\t\t}),\n\t);\n\tconst [cmd0] = await inspectReturns(client, tx);\n\treturn parseOptionalId(cmd0[0]);\n}\n\nexport interface MarketState {\n\texpiryMs: bigint;\n\ttickSizeRaw: bigint;\n\t/**\n\t * The COARSER raw-price step new finite mint boundaries must align to\n\t * (`expiry_market::admission_tick_size`). A numeric strike must be a whole\n\t * multiple of this — the fine `tickSizeRaw` grid alone is not sufficient — or\n\t * the chain aborts `EInvalidAdmissionTick`. The market's reference tick is the\n\t * one finite boundary allowed to bypass it.\n\t */\n\tadmissionTickSizeRaw: bigint;\n\tmintPaused: boolean;\n\t/**\n\t * The reference fine-grid tick (Polymarket-style anchor strike: derived\n\t * on-chain from the exact previous-window oracle observation), or null while\n\t * the keeper has not seeded it. Reference PRICE raw = tick * tickSizeRaw.\n\t */\n\treferenceTickRaw: bigint | null;\n}\n\n// The per-market state getters, in fixed order. `expiry_market::{expiry,\n// tick_size, mint_paused, reference_tick}` — see\n// packages/predict/sources/expiry_market.move:{101,177,259,187}. reference_tick\n// returns Option (no abort risk). settlement is read separately via\n// `settlementPrice` (its own non-batched getter below).\nconst STATE_FNS = [\n\texpiryMarket.expiry,\n\texpiryMarket.tickSize,\n\texpiryMarket.admissionTickSize,\n\texpiryMarket.mintPaused,\n\texpiryMarket.referenceTick,\n] as const;\n\nfunction parseStateAt(cmds: Uint8Array[][], base: number): MarketState {\n\treturn {\n\t\texpiryMs: parseU64LE(cmds[base][0]),\n\t\ttickSizeRaw: parseU64LE(cmds[base + 1][0]),\n\t\tadmissionTickSizeRaw: parseU64LE(cmds[base + 2][0]),\n\t\tmintPaused: (cmds[base + 3][0][0] ?? 0) !== 0, // BCS bool: 1 byte\n\t\treferenceTickRaw: parseOptionalU64(cmds[base + 4][0]),\n\t};\n}\n\nexport async function marketState(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\tmarketId: string,\n): Promise<MarketState> {\n\tconst [state] = await marketStates(client, config, [marketId]);\n\treturn state;\n}\n\n// Batched marketState for N markets in ONE PTB (STATE_FNS.length commands per\n// market, same order). Returns states aligned with `marketIds`.\nexport async function marketStates(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\tmarketIds: readonly string[],\n): Promise<MarketState[]> {\n\tif (marketIds.length === 0) return [];\n\tconst tx = new Transaction();\n\tfor (const id of marketIds) {\n\t\tfor (const fn of STATE_FNS) {\n\t\t\ttx.add(fn({ config, arguments: { market: id } }));\n\t\t}\n\t}\n\tconst cmds = await inspectReturns(client, tx);\n\treturn marketIds.map((_, i) => parseStateAt(cmds, STATE_FNS.length * i));\n}\n\n// Anonymous both-sides pricing for one strike: the chain's own probability for\n// (strike, +inf] and (-inf, strike]. Deployed `pricing::range_price` takes typed\n// `range_codec::Strike`s (NOT raw u64) — each boundary is built via\n// `range_codec::strike_from_tick(tick, tick_size)`, which maps tick 0 → -inf,\n// POS_INF_TICK → +inf, and any finite tick → tick*tick_size. `range_price` is a\n// public fun on the deployed package. Both sides read the SAME pricer in one PTB, so\n// `down` is the chain's number, not 1 − up.\n//\n// `range_price` now returns a `RangePrice` carrying both boundary probabilities so the\n// fee can charge each leg separately; `probability()` is the combined range number this\n// function has always returned (`lower_up.saturating_sub(higher_up)`, unchanged). The\n// extra call per side is what keeps the u64 parse below reading a u64 rather than the\n// struct's BCS.\nexport async function rangePrices(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\tmarketId: string,\n\tfeeds: MarketFeeds,\n\tstrikeRaw: bigint,\n\ttickSizeRaw: bigint,\n): Promise<{ upRaw: bigint; downRaw: bigint }> {\n\tconst tx = new Transaction();\n\tconst pricer = tx.add(loadLivePricer(config, { expiryMarketId: marketId, ...feeds }));\n\t// strikeRaw is a whole tick multiple (the caller validates divisibility), so the\n\t// finite boundary is `strike_from_tick(strikeRaw / tickSize, tickSize)`.\n\tconst strikeTick = strikeRaw / tickSizeRaw;\n\tconst mkStrike = (tick: bigint) =>\n\t\ttx.add(rangeCodec.strikeFromTick({ config, arguments: { tick, tickSize: tickSizeRaw } }));\n\tconst strike = mkStrike(strikeTick);\n\tconst posInf = mkStrike(POS_INF_TICK);\n\tconst negInf = mkStrike(0n);\n\t// UP: (strike, +inf], then DOWN: (-inf, strike]. The two `probability` reductions are\n\t// the last two commands, which is what the tail-relative parse below indexes.\n\tconst up = tx.add(\n\t\tpricing.rangePrice({ config, arguments: { pricer, lower: strike, higher: posInf } }),\n\t);\n\tconst down = tx.add(\n\t\tpricing.rangePrice({ config, arguments: { pricer, lower: negInf, higher: strike } }),\n\t);\n\ttx.add(pricing.probability({ config, arguments: { price: up } }));\n\ttx.add(pricing.probability({ config, arguments: { price: down } }));\n\tconst cmds = await inspectReturns(client, tx);\n\treturn {\n\t\tupRaw: parseU64LE(cmds[cmds.length - 2][0]),\n\t\tdownRaw: parseU64LE(cmds[cmds.length - 1][0]),\n\t};\n}\n\n// Fresh single read of the reference tick — used by mint-at-reference, which\n// must not trust a cached state (the reference is unset early in a window\n// until the keeper seeds it).\nexport async function referenceTick(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\tmarketId: string,\n): Promise<bigint | null> {\n\tconst tx = new Transaction();\n\ttx.add(expiryMarket.referenceTick({ config, arguments: { market: marketId } }));\n\tconst [cmd0] = await inspectReturns(client, tx);\n\treturn parseOptionalU64(cmd0[0]);\n}\n\n// The recorded settlement price, or null while the market is unsettled.\n//\n// On the deployed package `expiry_market::settlement_price` is public and\n// `destroy_some`s the stored Option — callable here only because simulate runs with\n// checksEnabled:false, and it aborts in std::option (EOPTION_NOT_SET) when the\n// market has not settled; we map exactly that abort (and the public\n// EMarketNotSettled variant, should a future package guard it directly) to null.\n// (A non-aborting `try_settlement_price` also exists on-chain if this ever wants to\n// drop the abort-catch.)\nexport async function settlementPrice(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\tmarketId: string,\n): Promise<bigint | null> {\n\tconst tx = new Transaction();\n\ttx.add(expiryMarket.settlementPrice({ config, arguments: { market: marketId } }));\n\ttry {\n\t\tconst [cmd0] = await inspectReturns(client, tx);\n\t\treturn parseU64LE(cmd0[0]);\n\t} catch (e) {\n\t\tif (\n\t\t\te instanceof PredictMoveError &&\n\t\t\t(e.module === 'option' ||\n\t\t\t\t(e.module === 'expiry_market' && e.abortName === 'EMarketNotSettled'))\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\tthrow e;\n\t}\n}\n\n// A market's current NAV mark (the per-expiry recoverable value the flush prices\n// against). Loads a fresh live pricer, then reads `current_nav(market, &pricer)` —\n// see packages/predict/sources/expiry_market.move:236. `Pricer` has copy+drop, so\n// the unconsumed borrow is fine in a read-only inspect.\nexport async function currentNav(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\tmarketId: string,\n\tunderlying: UnderlyingConfig,\n): Promise<bigint> {\n\tconst tx = new Transaction();\n\tconst pricer = tx.add(\n\t\tloadLivePricer(config, {\n\t\t\texpiryMarketId: marketId,\n\t\t\tpythFeed: underlying.pythFeed,\n\t\t\tblockScholesValueStore: underlying.blockScholesValueStore,\n\t\t\tblockScholesSviStore: underlying.blockScholesSviStore,\n\t\t}),\n\t);\n\ttx.add(expiryMarket.currentNav({ config, arguments: { market: marketId, pricer } }));\n\tconst cmds = await inspectReturns(client, tx);\n\t// current_nav is the last command; load_live_pricer precedes it.\n\treturn parseU64LE(cmds[cmds.length - 1][0]);\n}\n\n/**\n * The fee and exposure policy a market snapshotted at creation, from its `ExpiryMarket` object:\n * `strike_exposure.config` and `strike_exposure.inventory_impact_scale`. It is the policy the\n * market charges for its whole life, whatever the protocol template says now, and the `cost`\n * functions take it as `fees`. One object read, no simulate. The struct layout is fixed across\n * package upgrades, so the v1 binding decodes every version's markets.\n */\nexport async function marketFeePolicy(client: ReadClient, marketId: string): Promise<FeePolicy> {\n\tconst { object } = await client.core.getObject({\n\t\tobjectId: marketId,\n\t\tinclude: { content: true },\n\t});\n\tif (!object.content) throw new Error(`ExpiryMarket ${marketId} returned no content`);\n\tconst { config, inventory_impact_scale } = expiryMarket.ExpiryMarket.parse(\n\t\tobject.content,\n\t).strike_exposure;\n\treturn {\n\t\tbaseFee: BigInt(config.base_fee),\n\t\tminFee: BigInt(config.min_fee),\n\t\texpiryFeeWindowMs: BigInt(config.expiry_fee_window_ms),\n\t\texpiryFeeMaxMultiplier: BigInt(config.expiry_fee_max_multiplier),\n\t\tminEntryProbability: BigInt(config.min_entry_probability),\n\t\tmaxEntryProbability: BigInt(config.max_entry_probability),\n\t\tinventoryImpactMaxRate: BigInt(config.inventory_impact_max_rate),\n\t\tinventoryImpactScale: BigInt(inventory_impact_scale),\n\t\tbackingBufferLambda: BigInt(config.backing_buffer_lambda),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,eAAsB,gBACrB,QACA,QACoB;CACpB,MAAM,KAAK,IAAI,aAAa;AAC5B,IAAG,IAAIA,oBAAwB,EAAE,QAAQ,CAAC,CAAC;CAC3C,MAAM,CAAC,QAAQ,MAAM,eAAe,QAAQ,GAAG;AAC/C,QAAO,iBAAiB,KAAK,GAAG;;AAMjC,eAAsB,eACrB,QACA,QACA,YACA,UACyB;CACzB,MAAM,KAAK,IAAI,aAAa;AAC5B,IAAG,IACFC,iBAAwB;EACvB;EACA,WAAW;GAAE,sBAAsB,WAAW;GAAsB,QAAQ;GAAU;EACtF,CAAC,CACF;CACD,MAAM,CAAC,QAAQ,MAAM,eAAe,QAAQ,GAAG;AAC/C,QAAO,gBAAgB,KAAK,GAAG;;AA4BhC,MAAM,YAAY;CACjBC;CACAC;CACAC;CACAC;CACAC;CACA;AAED,SAAS,aAAa,MAAsB,MAA2B;AACtE,QAAO;EACN,UAAU,WAAW,KAAK,MAAM,GAAG;EACnC,aAAa,WAAW,KAAK,OAAO,GAAG,GAAG;EAC1C,sB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