{"version":3,"file":"client.mjs","names":["#config","opts","#buildMint","#buildMintCost","#feeds","#resolveMarket","#strikeTicks","#buildRedeem","#assertLot","#planMint","#planSell","marketState","#requireDelayedExecution","#existingQueueId","#client","#referencePriceOf","#positionsCache","#strikeRawFor","#queuedMintQuote","#quoteMintTransaction","#recordsDelayedExecution","#predictCurrentVersion","#queueState","#assertQueueOpen","#hasAccount","#searchBudgetQuote","#entryBandRefusal","#quoteRefusal","#appliedSlippage","#admittedFloor","#refusal","#assertMintOrder","#assertRecordOpen","#assertSellQuantity","#assertSellOrder","#underlying","#marketCache","resolved","#assertAdmittedTick","#gridTick","raw","quote","#knownQueues","#ordersCurrentVersion","#preview"],"sources":["../../src/predict/client.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport type { ClientWithCoreApi, SuiClientRegistration } from '@mysten/sui/client';\nimport { Transaction, coinWithBalance, type TransactionResult } from '@mysten/sui/transactions';\nimport { isValidSuiObjectId, normalizeSuiAddress } from '@mysten/sui/utils';\nimport { TESTNET_PREDICT } from '../deployments/testnet.js';\nimport { getConfig, type PredictConfig, type UnderlyingConfig } from './config/index.js';\nimport {\n\ttoGeneratedConfig,\n\ttoOrdersConfig,\n\ttype GeneratedConfig,\n\ttype OrdersGeneratedConfig,\n} from './config/generated.js';\nimport { MIN_PREMIUM, decodeOrderRange, type FeePolicy } from './cost.js';\nimport {\n\tdecodeAccountsCreated,\n\tdecodeBuilderCodeSets,\n\tdecodeClaims,\n\tdecodeCohortCommits,\n\tdecodeDeposits,\n\tdecodeEnqueues,\n\tdecodeExpiryPnlRealized,\n\tdecodeMarketPayoutsCompleted,\n\tdecodeMints,\n\tdecodeOpenRecordPayouts,\n\tdecodePlpCancels,\n\tdecodePlpRequests,\n\tdecodePolicyUpdates,\n\tdecodeQueueEvents,\n\tdecodeQueueOps,\n\tdecodeQueuedFills,\n\tdecodeQueuedRefunds,\n\tdecodeRecordFunds,\n\tdecodeRedeems,\n\tdecodeWithdrawals,\n\texactlyOne,\n\ttype DecodableTransactionResult,\n} from './decode.js';\nimport {\n\tPredictInputError,\n\tPredictMoveError,\n\tPredictPreflightError,\n\ttype PredictPreflightCode,\n} from './errors.js';\nimport {\n\tORDER_FLOW_PACKAGE_VERSION,\n\tPREDICT_PACKAGE_VERSION,\n\tORDER_KIND,\n\tORDER_STATUS,\n\tbudgetMintLimits,\n\tcashNeedSell,\n\tchannelTickMs,\n\texactMintLimits,\n\tfeeCovered,\n\tmaxMintNow,\n\tmintBudget,\n\tmintCashNeed,\n\torderKindName,\n\torderView,\n\tpreviewTiming,\n\tsellLimits,\n\tslippageBand,\n\ttype DelayedExecutionPolicy,\n\ttype MaxMintNow,\n\ttype OrderKindName,\n\ttype OrderView,\n\ttype QueuedOrder,\n\ttype TimingPreview,\n} from './queue.js';\nimport { deriveQueueId } from './queue-id.js';\nimport { simulateWithEvents } from './reads/inspect.js';\nimport {\n\texecutionModeFor,\n\tlazerPackages,\n\tmarketQueueState,\n\torderFeeAndBalance,\n\tpendingFunds,\n\tqueuedOrders,\n\tquoteMintAnonymous,\n\tquoteMintForAccount,\n\tquoteRedeemOpen,\n\tversionWatermark,\n\ttype AnonymousMintQuoteRequest,\n\ttype ExecutionMode,\n\ttype MarketQueueState,\n\ttype MintQuoteRaw,\n\ttype MintQuoteRequest,\n} from './reads/queue.js';\nimport {\n\tpositionsFromTable,\n\tresolvePositionsTable,\n\ttype OpenPosition,\n\ttype PositionsHandle,\n} from './reads/positions.js';\nimport { accountBalance, hasPosition } from './reads/balances.js';\nimport {\n\tactiveMarketIds,\n\tcurrentNav,\n\texpiryMarketId,\n\tmarketFeePolicy,\n\tmarketState,\n\tmarketStates,\n\trangePrices,\n\treferenceTick,\n\tsettlementPrice,\n\ttype MarketState,\n} from './reads/markets.js';\nimport { poolStats } from './reads/pool.js';\nimport { readPricerSnapshot, type PricerSnapshot } from './reads/pricing.js';\nimport { boardPricer, type BoardPricer } from './pricing.js';\nimport { POS_INF_TICK, binaryRangeTicks, type Side } from './ticks.js';\nimport {\n\tcancelSupplyRequest,\n\tcancelWithdrawRequest,\n\tdepositFunds,\n\trequestSupply,\n\trequestWithdraw,\n\tsetBuilderCode,\n\tunsetBuilderCode,\n\twithdrawFunds,\n} from './tx/authed.js';\n\nimport { accountContract, deriveAccountWrapperIdFrom } from './tx/common.js';\nimport {\n\tassertOrderFeeAtMost,\n\tclaimParked,\n\tenqueueExactAmount,\n\tenqueueExactCost,\n\tenqueueExactQuantity,\n\tenqueueRedeemOpen,\n\tfill,\n\tpayOpen,\n\trebalanceExpiryCash,\n\trefund,\n\ttype LazerPackages,\n} from './tx/queue.js';\nimport type { MarketFeeds } from './tx/trade.js';\nimport {\n\tmintExactAmount,\n\tmintExactCost,\n\tmintExactQuantity,\n\tredeemLive,\n\tredeemSettled,\n} from './tx/trade.js';\nimport {\n\tpriceToRaw,\n\tprobabilityToRaw,\n\trawToProbability,\n\trawToUsdc,\n\tusdcToRaw,\n\tfromRaw,\n} from './units.js';\n\n// `position_lot_size` — a position quantity must be a whole multiple of this many\n// raw payout units ($0.01 lots). See packages/predict/sources/constants.move.\n/**\n * Testnet's `position_lot_size`, read from the deployment record. Validation uses the lot\n * size of the config actually in play; this is the convenience constant for testnet callers.\n */\nexport const POSITION_LOT_SIZE = BigInt(TESTNET_PREDICT.units.positionLotSize);\n\n// An unsubsidized price per contract (1e9 = $1) below which a budget fill's cost can't be above\n// its payout, so an admission refusal there is the entry band, not the payout bound.\nconst NEAR_DOLLAR_PER_CONTRACT = 950_000_000n;\n\n// Most `tx.*` builders are one builder's worth of commands in a fresh PTB.\nfunction txOf(command: (tx: Transaction) => TransactionResult | void): Transaction {\n\tconst tx = new Transaction();\n\ttx.add(command);\n\treturn tx;\n}\n\n/** A live/settled market addressed by its human coordinates: a binary position\n * (single strike + side) or a two-strike range position. */\nexport type MarketDescriptor = {\n\tunderlying: string;\n\texpiryMs: number | bigint;\n\t/**\n\t * Pin resolution to this exact `ExpiryMarket` object, skipping the\n\t * underlying+expiry lookup — a caller that reviewed a specific market object\n\t * mints against exactly that object, not whatever resolves at submit time.\n\t */\n\tmarketId?: string;\n} & (\n\t| {\n\t\t\tside: Side;\n\t\t\t/**\n\t\t\t * Strike in USD, or \"reference\" to trade at the market's on-chain reference\n\t\t\t * price (the Polymarket-style anchor: derived from the exact previous-window\n\t\t\t * oracle observation, so consecutive windows chain settlement → next strike).\n\t\t\t */\n\t\t\tstrike: number | 'reference';\n\t  }\n\t| {\n\t\t\t/** A range position: pays out when settlement lands inside `(lower, upper]`\n\t\t\t * (left-open, right-closed — same convention as the on-chain range key). */\n\t\t\tside: 'range';\n\t\t\t/** Lower strike bound in USD — finite, on the tick grid. */\n\t\t\tlower: number;\n\t\t\t/** Upper strike bound in USD — finite, on the tick grid, above `lower`. */\n\t\t\tupper: number;\n\t  }\n);\n\n/** Options for the friendly `mint` (exact payout quantity). */\nexport interface MintOptions {\n\tquantity: number;\n\tmaxCost?: number;\n\tmaxProbability?: number;\n}\n\n/** Options for `mintAmount` (spend up to a premium budget, floor the quantity received). */\nexport interface MintAmountOptions {\n\t/** Premium budget in quote units — the max premium paid (chain also caps it at the account balance). */\n\tspend: number;\n\tminQuantity: number;\n\t/** All-in cost ceiling in quote units (premium + fees). Omitted → uncapped. */\n\tmaxCost?: number;\n}\n\n/** Options for `mintCost`: all-in budget. Requires Predict v2 or later. */\nexport interface MintCostOptions {\n\t/** All-in USDC budget; the chain also caps it at the account balance. */\n\tspend: number;\n\t/** Minimum payout received. Zero disables this slippage floor. */\n\tminQuantity: number;\n}\n\n/** Options for `redeem`: which order and how much to close. `claimSettled` takes only\n * `orderId` — a settled claim closes the order in full. */\nexport interface CloseOptions {\n\torderId: bigint;\n\tquantity: number;\n}\n\n/** Options for `supplyPlp`. */\nexport interface PlpSupplyOptions {\n\t/**\n\t * Floor on the PLP minted for the whole request, as raw `bigint` shares — PLP is raw\n\t * everywhere in this SDK. It is a floor on the MARK, not a share count: a flush quoting\n\t * less does not fill smaller, it declines. Omitted → `0n`, no floor.\n\t *\n\t * How a miss is handled is the deployment's `lp_request_limit_flush_attempts`: at the\n\t * shipped count of one the first flush below the floor cancels and refunds the request.\n\t */\n\tminPlpOut?: bigint;\n}\n\n/** Options for `withdrawPlp`. */\nexport interface PlpWithdrawOptions {\n\t/**\n\t * Floor on the USDC paid for the whole request, in USD decimals like every other amount\n\t * here. A floor on the MARK, not an amount: a flush quoting less declines rather than\n\t * paying out smaller. Omitted → no floor. Measured after the protocol's withdraw fee.\n\t */\n\tminUsdcOut?: number | string;\n}\n\n/** One tradeable market as returned by read.markets(). */\nexport interface ActiveMarket {\n\tid: string;\n\texpiryMs: bigint;\n\t/** Strike granularity in USD (e.g. 0.01). */\n\ttickSize: number;\n\t/**\n\t * Coarser step new mint strikes must align to. A numeric strike must be a whole\n\t * multiple of this (the market's `referencePrice` is the one exception the chain\n\t * admits off-grid); otherwise the mint aborts `EInvalidAdmissionTick`.\n\t */\n\tadmissionTickSize: number;\n\tmintPaused: boolean;\n\t/** The window's anchor strike in USD, or null until the keeper seeds it. */\n\treferencePrice: number | null;\n}\n\n/** A resolved live market: its on-chain state summary for the caller. */\nexport interface MarketSummary {\n\tid: string;\n\texpiryMs: bigint;\n\ttickSize: number;\n\t/**\n\t * Coarser step new mint strikes must align to. A numeric strike must be a whole\n\t * multiple of this (the market's `referencePrice` is the one exception the chain\n\t * admits off-grid); otherwise the mint aborts `EInvalidAdmissionTick`.\n\t */\n\tadmissionTickSize: number;\n\tmintPaused: boolean;\n\tnav: number;\n\t/** The window's anchor strike in USD, or null until the keeper seeds it. */\n\treferencePrice: number | null;\n}\n\n/**\n * A market's settlement, from `read.settlement`. Pass `settlementPriceRaw` and `tickSizeRaw` to\n * `cost.settledPayout` to show what a position paid.\n */\nexport interface MarketSettlement {\n\tmarketId: string;\n\texpiryMs: bigint;\n\t/** Whether Predict has recorded the settlement price. */\n\tsettled: boolean;\n\t/** The settlement price in USD, or null until the market settles. */\n\tsettlementPrice: number | null;\n\t/** The settlement price at the 1e9 price scale, or null until the market settles. */\n\tsettlementPriceRaw: bigint | null;\n\t/** The market's raw tick size, which `cost.settledPayout` rounds the price against. */\n\ttickSizeRaw: bigint;\n}\n\n/** Aggregate pool figures. Balances in human units (shares raw); the pending fields\n * are request COUNTS, not amounts — the on-chain getters expose queue lengths, and\n * the escrowed USDC/PLP behind them is tracked separately. */\nexport interface PoolSummary {\n\tplpTotalSupply: bigint;\n\tidleUsdc: number;\n\t/** Number of LP supply requests queued for the next flush. */\n\tsupplyRequestsPending: number;\n\t/** Number of LP withdraw requests queued for the next flush. */\n\twithdrawRequestsPending: number;\n}\n\n/** Exact pre-trade quote: the dry-run receipt of the mint you are about to send. */\nexport interface MintQuote {\n\t/** Fill price, 0..1 per $1 payout. */\n\tentryProbability: number;\n\t/** Premium paid into LP backing (quote units). */\n\tpremium: number;\n\t/**\n\t * Fee breakdown. `referral` is a PORTION of the trader-paid trading fee and\n\t * congestion surcharge routed to the referrer — it is already inside those\n\t * numbers and is NOT an extra debit. `inventoryImpact` is a separate charge and\n\t * IS part of `cost`.\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\t/**\n\t * All-in account debit: premium + (trading − subsidy) + builder + penalty +\n\t * inventoryImpact — exactly what the chain withdraws (the deployed\n\t * `compute_mint_quote`'s `all_in_cost`); pass this (plus your buffer) as maxCost.\n\t */\n\tcost: number;\n\tquantity: number;\n\traw: { premium: bigint; cost: bigint; quantity: bigint; entryProbability: bigint };\n\t/** True: computed by the real mint code path against real account state. */\n\tfeesExact: true;\n\t/**\n\t * True when this previews a queued (delayed-execution) fill: read from the chain's\n\t * `quote_*` functions with the congestion penalty removed, since a queued fill pays none.\n\t * Set when the network's config records delayed execution.\n\t */\n\tqueued?: boolean;\n\t/**\n\t * Queued previews only: the flat order fee, charged once at enqueue on top of `cost`. Show\n\t * it once per order, not per contract.\n\t */\n\torderFee?: number;\n}\n\n/** Exact pre-close quote: the dry-run receipt of the redeem you are about to send. */\nexport interface RedeemQuote {\n\t/** NET quote credited to the account. */\n\tproceeds: number;\n\t/** Gross close value before fees. */\n\tgross: number;\n\t/** `inventoryImpactRebate` is credited back on the close, so `proceeds` is\n\t * gross + rebate − trading − builder − penalty. */\n\tfees: { trading: number; builder: number; penalty: number; inventoryImpactRebate: number };\n\tquantityClosed: number;\n\tremaining: number;\n\traw: { proceeds: bigint; gross: bigint; quantityClosed: bigint };\n\tfeesExact: true;\n}\n\ninterface ResolvedMarket {\n\tid: string;\n\tstate: MarketState;\n}\n\n/** A market by its underlying and expiry, optionally pinned to an exact object. */\nexport type MarketCoordinates = Pick<MarketDescriptor, 'underlying' | 'expiryMs' | 'marketId'>;\n\n/** Options for `enqueueMint`: a queued mint of an exact payout quantity. */\nexport interface EnqueueMintOptions {\n\tquantity: number;\n\t/** All-in USDC cap (premium + fees). Required: a queued mint has no \"unlimited\" cap. */\n\tmaxCost: number;\n\t/** Entry-probability cap at τ, in (0, 1]. Required. See `queue.slippageBand`. */\n\tmaxProbability: number;\n}\n\n/** Options for `enqueueMintAmount`: a queued premium-budget mint. */\nexport interface EnqueueMintAmountOptions {\n\t/** Premium budget in USDC. */\n\tspend: number;\n\t/** Floor on the payout received. */\n\tminQuantity: number;\n\t/** All-in USDC cap (premium + fees). Required. */\n\tmaxCost: number;\n}\n\n/** Options for `enqueueMintCost`: a queued all-in-budget mint. */\nexport interface EnqueueMintCostOptions {\n\t/** All-in USDC budget, fees included. Escrowed at enqueue, less what the fill doesn't use. */\n\tspend: number;\n\t/** Floor on the payout received. Zero disables this slippage floor. */\n\tminQuantity: number;\n}\n\n/** Options for `enqueueSell`: a queued early sell of an Open record. */\nexport interface EnqueueSellOptions {\n\t/** The Open record to sell from: its queue record ID, not the position's order ID. */\n\trecordId: bigint;\n\t/** Payout quantity to close. A partial sell must leave at least the policy minimum. */\n\tquantity: number;\n\t/** Close-side probability floor at τ, in [0, 1]. Pass 0 on purpose to disable it. */\n\tminProbability: number;\n\t/** Floor on the proceeds before the order fee, in USDC. Pass 0 on purpose to disable it. */\n\tminProceeds: number;\n\t/**\n\t * Add `rebalance_expiry_cash` after the enqueue so the market is funded for this sell at once.\n\t * `'auto'` (default) adds it only when the sell's cash need is above spare cash, `'always'`\n\t * always, `'never'` never. It takes the hot `PoolVault`, so keep it conditional.\n\t */\n\tfundMarket?: 'auto' | 'always' | 'never';\n}\n\n/** What a queued order builder previews alongside the transaction. Display only. */\nexport interface QueuedOrderPreview {\n\tmarketId: string;\n\tkind: number;\n\tkindName: OrderKindName;\n\t/** τ, deadline and cutoff for an order placed now, from the local clock. */\n\ttiming: TimingPreview;\n\t/** The flat order fee, charged once at enqueue. */\n\torderFee: number;\n\t/** USDC escrowed for the premium and fees; 0 for a sell. Unused budget returns at the fill. */\n\tbudget: number;\n\t/** What enqueue debits: budget + order fee. */\n\ttotalDebit: number;\n\t/** The order's worst-case cash need against the market's spare cash. */\n\tcashNeedRaw: bigint;\n\tspareCashRaw: bigint;\n\t/**\n\t * Sells only: the cash need is above spare cash, so the sell may be refunded in full\n\t * (reason 8) unless the market is funded before the fill.\n\t */\n\tneedsFunding: boolean;\n\t/** Whether the builder added `rebalance_expiry_cash` after the enqueue. */\n\tfundedInTransaction: boolean;\n\traw: { orderFee: bigint; budget: bigint; totalDebit: bigint };\n}\n\n/** A queued order's transaction and its preview. */\nexport interface QueuedOrderPlan {\n\ttransaction: Transaction;\n\tpreview: QueuedOrderPreview;\n}\n\n/**\n * How much the price may move against a queued order between its quote and its fill, in cents per\n * contract. A contract pays $1, so its price in cents is its probability: 10¢ of slippage lets\n * a 42¢ contract fill at up to 52¢, fees included. It is never a percentage.\n */\nexport interface SlippageOptions {\n\t/**\n\t * Cents per contract: `10` is 10¢. `'auto'` (the default) sizes it with `queue.slippageBand`\n\t * from the time to expiry and the policy's delay.\n\t */\n\tslippageCents?: number | 'auto';\n\t/** Standard deviations of movement for `'auto'`. Default 2. */\n\tk?: number;\n}\n\n/**\n * Options for `read.planMint`. `amount` plans a purchase form's spend (an all-in budget mint),\n * and `quantity` plans an exact payout.\n */\nexport type PlanMintOptions = SlippageOptions &\n\t(\n\t\t| {\n\t\t\t\t/** The purchase amount in USDC. */\n\t\t\t\tamount: number;\n\t\t\t\t/**\n\t\t\t\t * Whether `amount` is the whole debit, order fee included (`'inclusive'`, the default),\n\t\t\t\t * or the order fee is charged on top (`'exclusive'`).\n\t\t\t\t */\n\t\t\t\torderFee?: 'inclusive' | 'exclusive';\n\t\t  }\n\t\t| { quantity: number }\n\t);\n\n/** The slippage a plan applied. */\nexport interface AppliedSlippage {\n\t/** Cents per contract. */\n\tcents: number;\n\tsource: 'input' | 'auto';\n\t/** The model band when `source` is `'auto'`. */\n\tband: ReturnType<typeof slippageBand> | null;\n}\n\n/**\n * `read.planMint`: everything a purchase form shows, and the enqueue options that carry its\n * slippage. Display only: the fill prices at τ, within the limits in `order`.\n */\nexport interface MintPlan {\n\tshape: 'budget' | 'exact-quantity';\n\t/** The owner, market and strike range the plan was quoted for. */\n\ttarget: PlanTarget;\n\t/** The quote at the current price. */\n\tquote: MintQuote;\n\t/**\n\t * Whether the quote is the account's own (`quote_mint_*_for_account`, with its builder fee). A\n\t * visitor without an account, or a balance below the order, gets `quote_mint`'s quote instead,\n\t * with a budget's quantity found by a short search.\n\t */\n\tquoteForAccount: boolean;\n\tslippage: AppliedSlippage;\n\t/** The payout if it wins, at the current price (\"Potential payout\"). */\n\tpotentialPayout: number;\n\t/** The smallest payout the order accepts, at the worst price. A smaller fill is refunded. */\n\tminPayout: number;\n\t/** `potentialPayout / expectedDebit` (\"Payout multiple\"), order fee included. */\n\tpayoutMultiple: number;\n\t/** `minPayout / totalDebit`: the multiple at the worst price. */\n\tminPayoutMultiple: number;\n\t/** All-in price per contract now in USDC (0.42 is 42¢), after the fee subsidy, order fee excluded. */\n\tpricePerContract: number;\n\t/**\n\t * The worst price the limits admit: the price per contract without the fee subsidy, plus the\n\t * slippage. Enqueue admission checks the order without the subsidy, and the subsidy can run out\n\t * before the fill, so the limits never count on it.\n\t */\n\tworstPricePerContract: number;\n\t/** The flat order fee, read from the order desk, charged once per order. */\n\torderFee: number;\n\t/** USDC escrowed for the premium and fees. Unused budget comes back at the fill. */\n\tbudget: number;\n\t/** `budget + orderFee`: what enqueue debits. */\n\ttotalDebit: number;\n\t/** `quote.cost + orderFee`: what the order costs if it fills at the current price. */\n\texpectedDebit: number;\n\tbalance: {\n\t\t/** Whether the owner has a Predict account yet. */\n\t\thasAccount: boolean;\n\t\t/** The account's USDC, or null without an account. */\n\t\tavailable: number | null;\n\t\t/** Whether the balance covers `totalDebit`, or null without an account. */\n\t\tcovers: boolean | null;\n\t};\n\t/**\n\t * The largest `amount` (budget plans) or `quantity` (exact plans) the market's spare cash and,\n\t * with an account, the balance allow now. An exact plan's balance bound prices each contract\n\t * at the plan's `worstPricePerContract`. Null when neither binds.\n\t */\n\tmaxNow: number | null;\n\t/** τ, deadline and cutoff for an order placed now, from the local clock. */\n\ttiming: TimingPreview;\n\t/**\n\t * Whether `tx.enqueuePlan` would build the order now and admission would take it at the current\n\t * price: the builder's preflight (the queue gates, the order fee, the minimum premium and the\n\t * market's cash), the balance against `totalDebit`, the payout bound and, for a budget, the\n\t * floor admission buys without the fee subsidy. Two admission conditions are checked only on\n\t * chain, at placement: the market's SVI age under the order desk's `svi_max_age_ms`, and room in\n\t * the payout tree for a new strike's boundary nodes.\n\t */\n\taccepting: boolean;\n\t/**\n\t * The `PredictPreflightError` code the order would get now, or null. `'fee'` also covers a\n\t * missing account or a balance below `totalDebit`.\n\t */\n\trefusal: PredictPreflightCode | null;\n\t/** Pass `order.options` to `tx[order.builder]`. */\n\torder:\n\t\t| { builder: 'enqueueMintCost'; options: EnqueueMintCostOptions }\n\t\t| { builder: 'enqueueMint'; options: EnqueueMintOptions };\n\traw: {\n\t\tbudget: bigint;\n\t\torderFee: bigint;\n\t\ttotalDebit: bigint;\n\t\tslippage: bigint;\n\t\tminQuantity: bigint;\n\t\tmaxCost: bigint | null;\n\t\tmaxProbability: bigint | null;\n\t\tpricePerContract: bigint;\n\t\tworstPricePerContract: bigint;\n\t};\n}\n\n/**\n * What a plan was quoted for. Its limits are sized for that one order, so `tx.enqueuePlan` refuses\n * the plan for any other owner, market, strike or record.\n */\nexport interface PlanTarget {\n\towner: string;\n\texpiryMarketId: string;\n\t/** A mint's strike range, as the market's admission ticks. */\n\tlowerTick?: bigint;\n\thigherTick?: bigint;\n\t/** A sell's Open record. Record IDs restart in every market. */\n\trecordId?: bigint;\n}\n\n/** Options for `read.planSell`. */\nexport type PlanSellOptions = SlippageOptions & {\n\t/** The Open record to sell from. */\n\trecordId: bigint;\n\t/** Payout quantity to close. */\n\tquantity: number;\n};\n\n/** `read.planSell`: what an early sell shows, and the enqueue options that carry its slippage. */\nexport interface SellPlan {\n\t/** The owner, market and record the plan was quoted for. */\n\ttarget: PlanTarget;\n\t/** The quote at the current price. */\n\tquote: SellQuote;\n\tslippage: AppliedSlippage;\n\t/** Proceeds at the current price, before the order fee. */\n\tproceeds: number;\n\t/** `proceeds − orderFee`. */\n\tnet: number;\n\t/** The proceeds floor the order carries, before the order fee. A smaller fill is refunded. */\n\tminProceeds: number;\n\t/**\n\t * `minProceeds − orderFee`: the worst the sell nets if it fills. Negative when the order fee is\n\t * above the proceeds floor.\n\t */\n\tminNet: number;\n\torderFee: number;\n\ttiming: TimingPreview;\n\t/**\n\t * Whether `tx.enqueuePlan` would build the sell now: the builder's preflight, which checks the\n\t * queue gates, that the record is Open and the owner's, the order fee and the minimum sell. The\n\t * market's SVI age under the order desk's `svi_max_age_ms` is checked only on chain, at\n\t * placement.\n\t */\n\taccepting: boolean;\n\t/** The `PredictPreflightError` code the sell would get now, or null. */\n\trefusal: PredictPreflightCode | null;\n\t/** Pass `order.options` to `tx.enqueueSell`. */\n\torder: { builder: 'enqueueSell'; options: EnqueueSellOptions };\n\traw: { slippage: bigint; minProceeds: bigint; minProbability: bigint; orderFee: bigint };\n}\n\n/** `read.queue`: a market's queue state plus the derived figures the app shows. */\nexport interface MarketQueueView extends MarketQueueState {\n\tmode: ExecutionMode;\n\t/** τ, deadline and cutoff for an order placed now, from the local clock. */\n\ttiming: TimingPreview;\n\t/**\n\t * Whether a new mint would pass the queue gates now: the same gates `enqueueMint*` checks\n\t * before its fee and cash checks (the order-flow allowlist, the cutover, pauses, stuck, mint\n\t * capacity, the cutoff, and the account cap when an owner was given). One side can be full\n\t * while the other is open.\n\t */\n\tacceptingMints: boolean;\n\t/** Whether a new sell would pass the queue gates now (sells skip the mint pauses). */\n\tacceptingSells: boolean;\n\t/**\n\t * Why each side refuses now, or null: the `PredictPreflightError` code the builder would\n\t * throw for the queue gates.\n\t */\n\trefusal: { mint: PredictPreflightCode | null; sell: PredictPreflightCode | null };\n\t/** The largest mint the market's spare cash admits now. */\n\tmaxMint: { exactQuantity: MaxMintNow; budget: MaxMintNow };\n}\n\n/** A queue record and its display state. */\nexport interface QueuedOrderView {\n\trecordId: bigint;\n\trecord: QueuedOrder;\n\tview: OrderView;\n}\n\n/** How `read.waitForOutcome` ended. */\nexport interface QueuedOrderOutcome {\n\t/** `'gone'`: the record is missing (cleaned up, or not landed). `'timeout'`: still waiting. */\n\toutcome: 'filled' | 'refunded' | 'closed' | 'gone' | 'timeout';\n\torder: QueuedOrderView | null;\n}\n\n/** A quote for selling an Open record early (`quote_redeem_open`). */\nexport interface SellQuote {\n\t/** The live per-contract probability. */\n\tprobability: number;\n\t/** Proceeds before the order fee, with no congestion penalty. */\n\tproceeds: number;\n\t/**\n\t * `proceeds − orderFee`: what the account nets. Negative when the order fee is above the\n\t * proceeds, since the fee is charged at enqueue whatever the sell returns.\n\t */\n\tnet: number;\n\tfees: { trading: number; builder: number; inventoryImpactRebate: number; order: number };\n\tquantityClosed: number;\n\traw: { probability: bigint; proceeds: bigint; orderFee: bigint; quantityClosed: bigint };\n}\n\n// The strike-bearing (binary) arm of MarketDescriptor, for read.price and its\n// seam — anonymous board pricing has no range semantics.\ntype BinaryMarketCoordinates = Pick<MarketDescriptor, 'underlying' | 'expiryMs' | 'marketId'> & {\n\tstrike: number | 'reference';\n};\n\n/** The Sui client surface PredictClient reads through: any `ClientWithCoreApi`\n * (gRPC or GraphQL) provides both the `simulateTransaction` the reads/quotes\n * sit on and the `core` object methods position enumeration needs. */\nexport interface PredictCompatibleClient extends ClientWithCoreApi {}\n\n/**\n * Register PredictClient as a `client.predict` extension, mirroring\n * `@mysten/deepbook-v3`'s `deepbook(...)`: `client.$extend(predict({ network }))`.\n */\nexport function predict<Name extends string = 'predict'>({\n\tname = 'predict' as Name,\n\tnetwork,\n\tconfig,\n}: {\n\tname?: Name;\n\tnetwork: 'testnet' | 'mainnet';\n\tconfig?: PredictConfig;\n}): SuiClientRegistration<PredictCompatibleClient, Name, PredictClient> {\n\treturn {\n\t\tname,\n\t\tregister: (client) => new PredictClient({ client, network, config }),\n\t};\n}\n\n/**\n * The one object an app constructs. Wraps the config, a client for reads, and\n * a derived-account model so callers pass owner addresses, decimal amounts, and\n * human market coordinates — the facade converts to raw units, resolves markets\n * (cached), and delegates to the internal tx primitives / reads. Each `tx.*` builder\n * returns a finished `Transaction`; callers composing their own PTBs use the generated\n * move-call bindings this subpath exports (`plpMoveCalls`, `expiryMarketMoveCalls`, …).\n */\n// The chain refused a quote or order on its own limits at the current price.\nfunction isOrderFailsLimits(error: unknown): boolean {\n\treturn error instanceof PredictMoveError && error.abortName === 'EOrderFailsLimits';\n}\n\n// The chain refused to price a live trade because the market reached its expiry.\nfunction isPastExpiry(error: unknown): boolean {\n\treturn error instanceof PredictMoveError && error.abortName === 'ELivePricingExpired';\n}\n\nexport class PredictClient {\n\treadonly cfg: PredictConfig;\n\t// The flat slice every generated call resolves `options.config` against.\n\tget #config(): GeneratedConfig {\n\t\treturn toGeneratedConfig(this.cfg);\n\t}\n\t#client: PredictCompatibleClient;\n\t// underlying:expiryMs → resolved market. The id and tickSizeRaw — the only\n\t// state tx building depends on — are immutable per (underlying, expiry), so\n\t// one resolution per market per client suffices. (mintPaused IS mutable; the\n\t// cached copy is never consulted for a tx decision — the chain enforces it.)\n\t#marketCache = new Map<string, ResolvedMarket>();\n\t// owner → resolved position-store ids. accountUid and the table id are\n\t// immutable once created, so cache-forever; a missing table (no Predict\n\t// data yet) is NOT cached — it appears after the owner's first trade.\n\t#positionsCache = new Map<string, PositionsHandle>();\n\t// Queue IDs confirmed to exist. A `MarketQueue` is shared and never deleted, so a confirmed\n\t// queue is cached forever; a missing one is not cached, since the keeper creates it later.\n\t#knownQueues = new Set<string>();\n\n\tconstructor(opts: {\n\t\tnetwork: 'testnet' | 'mainnet';\n\t\tclient: PredictCompatibleClient;\n\t\tconfig?: PredictConfig;\n\t}) {\n\t\tthis.cfg = opts.config ?? getConfig(opts.network);\n\t\tthis.#client = opts.client;\n\t}\n\n\t/** The deterministic id of an owner's canonical account wrapper — no chain read. */\n\twrapperIdFor(owner: string): string {\n\t\treturn deriveAccountWrapperIdFrom(this.#config, owner);\n\t}\n\n\t/**\n\t * The deterministic id of a market's `MarketQueue` under the config's queue registry, whether\n\t * or not it exists yet — no chain read. Throws `PredictInputError` while the config doesn't\n\t * record delayed execution.\n\t */\n\tqueueIdFor(marketId: string): string {\n\t\treturn deriveQueueId(this.#requireDelayedExecution().queueRegistry, marketId);\n\t}\n\n\t// The deployment's wiring for a symbol; throws a typed error on an unknown symbol.\n\t// Per-underlying ids are the one thing the flat config slice does not carry.\n\t#underlying(underlying: string): UnderlyingConfig {\n\t\tconst u = this.cfg.underlyings[underlying];\n\t\tif (!u) throw new PredictInputError(`unknown underlying: ${underlying}`);\n\t\treturn u;\n\t}\n\n\t// The oracle feed ids for a symbol; throws a typed error on an unknown symbol.\n\t#feeds(underlying: string): MarketFeeds {\n\t\tconst u = this.#underlying(underlying);\n\t\treturn {\n\t\t\tpythFeed: u.pythFeed,\n\t\t\tblockScholesValueStore: u.blockScholesValueStore,\n\t\t\tblockScholesSviStore: u.blockScholesSviStore,\n\t\t};\n\t}\n\n\t// Resolve (and cache) a market's id + state from its human coordinates. An\n\t// explicit `marketId` pin skips the underlying+expiry lookup but still reads\n\t// that market's state — tx building depends on tickSizeRaw.\n\tasync #resolveMarket(\n\t\tm: Pick<MarketDescriptor, 'underlying' | 'expiryMs' | 'marketId'>,\n\t): Promise<ResolvedMarket> {\n\t\tif (m.marketId != null) {\n\t\t\tif (!isValidSuiObjectId(m.marketId)) {\n\t\t\t\tthrow new PredictInputError(`invalid marketId: ${JSON.stringify(m.marketId)}`);\n\t\t\t}\n\t\t\tconst resolved: ResolvedMarket = this.#marketCache.get(m.marketId) ?? {\n\t\t\t\tid: m.marketId,\n\t\t\t\tstate: await marketState(this.#client, this.#config, m.marketId),\n\t\t\t};\n\t\t\t// The pin must agree with the descriptor's coordinates: catching a stale or\n\t\t\t// wrong-market id here beats minting against mismatched oracle feeds. (The\n\t\t\t// underlying cannot be cross-checked — market state does not carry it.)\n\t\t\tif (resolved.state.expiryMs !== BigInt(m.expiryMs)) {\n\t\t\t\tthrow new PredictInputError(\n\t\t\t\t\t`pinned market ${m.marketId} expires at ${resolved.state.expiryMs}, descriptor says ${BigInt(m.expiryMs)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.#marketCache.set(m.marketId, resolved);\n\t\t\treturn resolved;\n\t\t}\n\t\tconst expiryMs = BigInt(m.expiryMs);\n\t\tconst key = `${m.underlying}:${expiryMs}`;\n\t\tconst hit = this.#marketCache.get(key);\n\t\tif (hit) return hit;\n\t\tconst u = this.#underlying(m.underlying);\n\t\tconst id = await expiryMarketId(this.#client, this.#config, u, expiryMs);\n\t\tif (!id) throw new PredictInputError(`no market for ${m.underlying} at expiry ${expiryMs}`);\n\t\tconst state = await marketState(this.#client, this.#config, id);\n\t\tconst resolved: ResolvedMarket = { id, state };\n\t\tthis.#marketCache.set(key, resolved);\n\t\treturn resolved;\n\t}\n\n\t// Reference PRICE in USD from a state (tick index × tick size), or null.\n\tstatic #referencePriceOf(state: MarketState): number | null {\n\t\treturn state.referenceTickRaw == null\n\t\t\t? null\n\t\t\t: fromRaw(state.referenceTickRaw * state.tickSizeRaw, 9);\n\t}\n\n\t// A finite tick from a USD strike, validated exactly like binaryRangeTicks:\n\t// whole-tick multiple, inside the finite domain (1..POS_INF_TICK-1).\n\t#gridTick(strike: number, tickSizeRaw: bigint): bigint {\n\t\tconst raw = priceToRaw(strike);\n\t\tconst tick = raw / tickSizeRaw;\n\t\tif (tick * tickSizeRaw !== raw) {\n\t\t\tthrow new PredictInputError(\n\t\t\t\t`strike ${strike} is not on the ${fromRaw(tickSizeRaw, 9)} tick grid`,\n\t\t\t);\n\t\t}\n\t\tif (tick <= 0n || tick >= POS_INF_TICK) {\n\t\t\tthrow new PredictInputError(\n\t\t\t\t`strike tick ${tick} outside the finite tick domain (1..POS_INF_TICK-1)`,\n\t\t\t);\n\t\t}\n\t\treturn tick;\n\t}\n\n\t// New finite MINT boundaries must land on the market's coarser ADMISSION grid,\n\t// not merely the fine tick grid — the chain asserts exactly this\n\t// (`assert_admitted_mint_ticks`, `EInvalidAdmissionTick`). The ±inf sentinels are\n\t// exempt, and the market's reference tick is the one finite boundary allowed to\n\t// bypass the grid, so an off-grid tick is only rejected after confirming it is not\n\t// the reference (one extra read, and only on the failing path).\n\tasync #assertAdmittedTick(tick: bigint, marketId: string, state: MarketState): Promise<void> {\n\t\tif (tick === 0n || tick === POS_INF_TICK) return;\n\t\tconst multiple = state.admissionTickSizeRaw / state.tickSizeRaw;\n\t\tif (multiple > 0n && tick % multiple === 0n) return;\n\t\tconst reference = await referenceTick(this.#client, this.#config, marketId);\n\t\tif (reference != null && reference === tick) return;\n\t\tconst admission = fromRaw(state.admissionTickSizeRaw, 9);\n\t\tthrow new PredictInputError(\n\t\t\t`strike ${fromRaw(tick * state.tickSizeRaw, 9)} is not on the ${admission} admission grid ` +\n\t\t\t\t`(mint boundaries must be a multiple of ${admission}, or the market's reference strike)`,\n\t\t);\n\t}\n\n\t// Resolve a descriptor's strike(s) to the (lower, higher) tick pair. A binary\n\t// numeric strike converts and validates against the tick grid; \"reference\"\n\t// reads the market's reference tick FRESH (never cached — it is unset early in\n\t// a window) and uses it directly: it is on the tick grid by construction. A\n\t// range descriptor converts both bounds to finite grid ticks (\"reference\" is\n\t// binary-only: a range has no single reference strike).\n\tasync #strikeTicks(\n\t\tm: MarketDescriptor,\n\t\tmarketId: string,\n\t\tstate: MarketState,\n\t): Promise<{ lowerTick: bigint; higherTick: bigint }> {\n\t\tif (m.side === 'range') {\n\t\t\tif (!(m.lower < m.upper)) {\n\t\t\t\tthrow new PredictInputError(`range lower ${m.lower} must be below upper ${m.upper}`);\n\t\t\t}\n\t\t\tconst lowerTick = this.#gridTick(m.lower, state.tickSizeRaw);\n\t\t\tconst higherTick = this.#gridTick(m.upper, state.tickSizeRaw);\n\t\t\tawait this.#assertAdmittedTick(lowerTick, marketId, state);\n\t\t\tawait this.#assertAdmittedTick(higherTick, marketId, state);\n\t\t\treturn { lowerTick, higherTick };\n\t\t}\n\t\tif (m.strike !== 'reference') {\n\t\t\tconst ticks = binaryRangeTicks(priceToRaw(m.strike), m.side, state.tickSizeRaw);\n\t\t\tawait this.#assertAdmittedTick(ticks.lowerTick, marketId, state);\n\t\t\tawait this.#assertAdmittedTick(ticks.higherTick, marketId, state);\n\t\t\treturn ticks;\n\t\t}\n\t\tconst tick = await referenceTick(this.#client, this.#config, marketId);\n\t\tif (tick == null) {\n\t\t\tthrow new PredictInputError(\n\t\t\t\t`reference price not set yet for ${m.underlying} @ ${m.expiryMs} — retry shortly or pass a numeric strike`,\n\t\t\t);\n\t\t}\n\t\treturn m.side === 'up'\n\t\t\t? { lowerTick: tick, higherTick: POS_INF_TICK }\n\t\t\t: { lowerTick: 0n, higherTick: tick };\n\t}\n\n\t// Raw payout quantity must land on a lot boundary — the chain rejects otherwise.\n\t#assertLot(quantityRaw: bigint): void {\n\t\t// From the config in play, not the exported testnet constant — a deployment with a\n\t\t// different `position_lot_size` must not be validated against testnet's.\n\t\tconst lot = BigInt(this.cfg.units.positionLotSize);\n\t\tif (quantityRaw % lot !== 0n) {\n\t\t\tthrow new PredictInputError(\n\t\t\t\t`quantity ${quantityRaw} raw is not a whole ${lot}-unit lot (position_lot_size)`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Whether the owner's account wrapper exists. A visitor without an account still gets a plan.\n\tasync #hasAccount(owner: string): Promise<boolean> {\n\t\tconst {\n\t\t\tobjects: [wrapper],\n\t\t} = await this.#client.core.getObjects({ objectIds: [this.wrapperIdFor(owner)] });\n\t\treturn !(wrapper instanceof Error);\n\t}\n\n\t// The slippage a plan applies, per $1 of payout, 1e9-scaled: the caller's, or the model band at\n\t// the quote's probability.\n\tstatic #appliedSlippage(\n\t\topts: SlippageOptions,\n\t\tprobabilityRaw: bigint,\n\t\tstate: MarketQueueState,\n\t\tnowMs: bigint,\n\t): { raw: bigint; applied: AppliedSlippage } {\n\t\tconst cents = opts.slippageCents ?? 'auto';\n\t\tif (cents !== 'auto') {\n\t\t\tif (!(Number.isFinite(cents) && cents >= 0 && cents <= 100)) {\n\t\t\t\tthrow new PredictInputError(\n\t\t\t\t\t`slippageCents must be in [0, 100] cents per contract, got ${cents}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// A cent is 1e7 in the 1e9-scaled price per $1 of payout.\n\t\t\tconst raw = BigInt(Math.round(cents * 1e7));\n\t\t\treturn { raw, applied: { cents: Number(raw) / 1e7, source: 'input', band: null } };\n\t\t}\n\t\tconst policy = state.desk.policy;\n\t\tconst band = slippageBand({\n\t\t\t// The band is undefined at the certain ends, where a queued mint is refused anyway.\n\t\t\tprobability: Math.min(Math.max(rawToProbability(probabilityRaw), 1e-6), 1 - 1e-6),\n\t\t\ttimeToExpiryMs: Number(state.expiryMs > nowMs ? state.expiryMs - nowMs : 0n),\n\t\t\tdelayMs: Number(policy.delayMs),\n\t\t\ttickMs: Number(channelTickMs(policy.pythChannel)),\n\t\t\tk: opts.k,\n\t\t});\n\t\tconst raw = BigInt(Math.ceil(band.deltaProbability * 1e9));\n\t\treturn { raw, applied: { cents: Number(raw) / 1e7, source: 'auto', band } };\n\t}\n\n\t// Why the chain refused a plan's quote, as a typed refusal, or the chain's own error when it\n\t// can't tell. A market past its expiry has no live price (`ELivePricingExpired`). A mint the\n\t// chain refuses at the current price (`EOrderFailsLimits`) is diagnosed by `#entryBandRefusal`.\n\tasync #quoteRefusal(\n\t\terror: unknown,\n\t\tmint?: { m: MarketDescriptor; quantityRaw?: bigint },\n\t): Promise<unknown> {\n\t\tif (isPastExpiry(error)) {\n\t\t\treturn new PredictPreflightError(\n\t\t\t\t'past-cutoff',\n\t\t\t\t'the market reached its expiry, so it has no live price and takes no orders',\n\t\t\t);\n\t\t}\n\t\tif (mint != null && isOrderFailsLimits(error)) {\n\t\t\treturn (await this.#entryBandRefusal(mint.m, mint.quantityRaw)) ?? error;\n\t\t}\n\t\treturn error;\n\t}\n\n\t// Why the chain refused to quote a mint at the current price (`EOrderFailsLimits`), as a typed\n\t// refusal: a binary strike outside the market's entry band, or an exact quantity whose premium\n\t// is below the minimum. Null when neither explains it, or the diagnosis can't be read, so the\n\t// caller rethrows the chain's error.\n\tasync #entryBandRefusal(\n\t\tm: MarketDescriptor,\n\t\tquantityRaw?: bigint,\n\t): Promise<PredictPreflightError | null> {\n\t\tif (m.side === 'range') return null;\n\t\t// Best effort: a failed diagnosis read leaves the chain's own error to the caller.\n\t\tconst read = await Promise.all([this.read.price(m), this.read.feePolicy(m)]).catch(() => null);\n\t\tif (read == null) return null;\n\t\tconst [prices, policy] = read;\n\t\tconst probability = probabilityToRaw(m.side === 'up' ? prices.up : prices.down);\n\t\tif (probability < policy.minEntryProbability || probability > policy.maxEntryProbability) {\n\t\t\treturn new PredictPreflightError(\n\t\t\t\t'entry-band',\n\t\t\t\t`the ${m.side} probability ${rawToProbability(probability)} is outside the market's entry band [${rawToProbability(policy.minEntryProbability)}, ${rawToProbability(policy.maxEntryProbability)}]: pick a strike nearer the money`,\n\t\t\t);\n\t\t}\n\t\tif (quantityRaw != null && (quantityRaw * probability) / 1_000_000_000n < MIN_PREMIUM) {\n\t\t\treturn new PredictPreflightError(\n\t\t\t\t'min-premium',\n\t\t\t\t`${rawToUsdc(quantityRaw)} contracts cost a premium below the ${rawToUsdc(MIN_PREMIUM)} USDC minimum`,\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t}\n\n\t// A payout floor admission buys at least, for an all-in budget: the largest lot multiple up to\n\t// `startRaw` whose cost without the fee subsidy, by an exact chain quote, fits the budget.\n\t// Admission (`cost_qty_at`, no subsidy) first finds the largest quantity whose cost fits, and\n\t// cost rises with quantity, so that is at least this. A probe below the minimum premium\n\t// (`EOrderFailsLimits`) is retried once at the smallest quantity that clears it. Admission\n\t// searches again only when its fill costs more than its payout, a search rounding makes\n\t// non-monotone, so a floor whose payout is below the budget, about $1 a contract, is refused.\n\tasync #admittedFloor(\n\t\tquoteAt: (quantityRaw: bigint) => Promise<MintQuoteRaw>,\n\t\tbudgetRaw: bigint,\n\t\tstartRaw: bigint,\n\t\tlot: bigint,\n\t\tentryProbabilityRaw: bigint,\n\t\tunsubsidizedPricePerContractRaw: bigint,\n\t): Promise<\n\t\t{ quantity: bigint } | { refusal: 'min-premium' | 'cost-above-payout' | 'entry-band' }\n\t> {\n\t\tconst ceilLot = (x: bigint) => ((x + lot - 1n) / lot) * lot;\n\t\tconst minPremiumQuantity =\n\t\t\tentryProbabilityRaw === 0n\n\t\t\t\t? 0n\n\t\t\t\t: ceilLot((MIN_PREMIUM * 1_000_000_000n + entryProbabilityRaw - 1n) / entryProbabilityRaw);\n\t\tlet quantity = startRaw;\n\t\tlet raised = false;\n\t\tfor (let probe = 0; probe < 5 && quantity > 0n; probe++) {\n\t\t\tlet quote: MintQuoteRaw;\n\t\t\ttry {\n\t\t\t\tquote = await quoteAt(quantity);\n\t\t\t} catch (e) {\n\t\t\t\tif (!isOrderFailsLimits(e)) throw e;\n\t\t\t\tif (!raised && quantity < minPremiumQuantity) {\n\t\t\t\t\traised = true;\n\t\t\t\t\tquantity = minPremiumQuantity;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// The raise sized the minimum-premium quantity from the budget quote's entry\n\t\t\t\t// probability. When the raised probe still fails, the probability moved down between\n\t\t\t\t// the two quotes and the premium is still short, so the minimum premium refused it.\n\t\t\t\tif (raised || quantity < minPremiumQuantity) return { refusal: 'min-premium' };\n\t\t\t\t// At or above the minimum premium, admission refuses a cost above the payout or an entry\n\t\t\t\t// probability outside the band. Well below $1 a contract the cost can't reach the payout,\n\t\t\t\t// so the probability left the band between the budget quote and this probe.\n\t\t\t\treturn {\n\t\t\t\t\trefusal:\n\t\t\t\t\t\tunsubsidizedPricePerContractRaw < NEAR_DOLLAR_PER_CONTRACT\n\t\t\t\t\t\t\t? 'entry-band'\n\t\t\t\t\t\t\t: 'cost-above-payout',\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst unsubsidized = quote.allInCost - quote.penaltyFee + quote.feeIncentiveSubsidy;\n\t\t\tif (unsubsidized <= budgetRaw) {\n\t\t\t\treturn quantity >= budgetRaw ? { quantity } : { refusal: 'cost-above-payout' };\n\t\t\t}\n\t\t\t// The smallest quantity that clears the minimum premium doesn't fit.\n\t\t\tif (raised) return { refusal: 'min-premium' };\n\t\t\tconst next = ((quantity * budgetRaw) / unsubsidized / lot) * lot;\n\t\t\tquantity = next < quantity ? next : quantity - lot;\n\t\t}\n\t\treturn { refusal: 'min-premium' };\n\t}\n\n\t// A budget mint's quote for no particular account. `quote_mint` has no all-in budget mode, so\n\t// this searches for the largest lot multiple whose all-in cost fits the budget. The first probe\n\t// is its premium-budget mode with the whole budget as the premium, whose premium clears the\n\t// 1 USDC minimum whenever the purchase can. Each next probe divides the budget by the last price\n\t// per contract. The price barely moves with size, so a few quotes settle it. A probe the chain\n\t// refuses (`EOrderFailsLimits`) ends the search with the best fit so far. With no fit, the\n\t// refusal is `min-premium`, unless the chain priced no probe and the budget is at least the\n\t// minimum premium plus a lot: the first probe's premium is above `budget − lot` (a lot costs\n\t// under $1), so the minimum premium didn't refuse it, and the chain's own refusal stands.\n\tasync #searchBudgetQuote(\n\t\tticks: { expiryMarketId: string; lowerTick: bigint; higherTick: bigint } & MarketFeeds,\n\t\tbudgetRaw: bigint,\n\t\tlot: bigint,\n\t): Promise<MintQuoteRaw> {\n\t\tconst floorLot = (x: bigint) => (x / lot) * lot;\n\t\tlet refusal: unknown = null;\n\t\tlet priced = false;\n\t\tconst probeQuote = async (request: AnonymousMintQuoteRequest) => {\n\t\t\ttry {\n\t\t\t\tconst { quote } = await quoteMintAnonymous(this.#client, this.#config, {\n\t\t\t\t\t...ticks,\n\t\t\t\t\trequest,\n\t\t\t\t});\n\t\t\t\tpriced = true;\n\t\t\t\treturn quote;\n\t\t\t} catch (e) {\n\t\t\t\tif (!isOrderFailsLimits(e)) throw e;\n\t\t\t\trefusal ??= e;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t};\n\t\tlet best: MintQuoteRaw | null = null;\n\t\tlet quote = await probeQuote({\n\t\t\tshape: 'exact-amount',\n\t\t\tmaxPremiumRaw: budgetRaw,\n\t\t\tminQuantityRaw: lot,\n\t\t});\n\t\tfor (let probe = 1; quote != null; probe++) {\n\t\t\tconst cost = quote.allInCost - quote.penaltyFee;\n\t\t\tif (cost <= budgetRaw && (best == null || quote.quantity > best.quantity)) best = quote;\n\t\t\tif (probe === 4) break;\n\t\t\tconst next = cost === 0n ? quote.quantity : floorLot((budgetRaw * quote.quantity) / cost);\n\t\t\tif (next === 0n || next === quote.quantity) break;\n\t\t\tquote = await probeQuote({ shape: 'exact-quantity', quantityRaw: next });\n\t\t}\n\t\tif (best == null) {\n\t\t\tif (!priced && refusal != null && budgetRaw >= MIN_PREMIUM + lot) throw refusal;\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'min-premium',\n\t\t\t\t`a budget of ${rawToUsdc(budgetRaw)} buys no payout at the current price (a mint's premium must be at least ${rawToUsdc(MIN_PREMIUM)} USDC)`,\n\t\t\t);\n\t\t}\n\t\treturn best;\n\t}\n\n\t// The PredictPreflightError code a check throws, or null when it passes.\n\tstatic #refusal(check: () => void): PredictPreflightCode | null {\n\t\ttry {\n\t\t\tcheck();\n\t\t\treturn null;\n\t\t} catch (e) {\n\t\t\tif (e instanceof PredictPreflightError) return e.code;\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// Shared construction for tx.mint and read.quoteMint. The quote dry-runs the\n\t// same mint the trade sends; quoteMint omits the caller's cost/probability caps\n\t// (they only gate via abort and don't change the receipt numbers).\n\tasync #buildMint(owner: string, m: MarketDescriptor, opts: MintOptions): Promise<Transaction> {\n\t\tconst feeds = this.#feeds(m.underlying);\n\t\tconst { id, state } = await this.#resolveMarket(m);\n\t\tconst quantityRaw = usdcToRaw(opts.quantity);\n\t\tthis.#assertLot(quantityRaw);\n\t\tconst { lowerTick, higherTick } = await this.#strikeTicks(m, id, state);\n\t\treturn txOf(\n\t\t\tmintExactQuantity(this.#config, {\n\t\t\t\texpiryMarketId: id,\n\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\tlowerTick,\n\t\t\t\thigherTick,\n\t\t\t\tquantityRaw,\n\t\t\t\tmaxCostRaw: opts.maxCost != null ? usdcToRaw(opts.maxCost) : undefined,\n\t\t\t\tmaxProbabilityRaw:\n\t\t\t\t\topts.maxProbability != null ? probabilityToRaw(opts.maxProbability) : undefined,\n\t\t\t\t...feeds,\n\t\t\t}),\n\t\t);\n\t}\n\n\tasync #buildMintCost(\n\t\towner: string,\n\t\tm: MarketDescriptor,\n\t\topts: MintCostOptions,\n\t): Promise<Transaction> {\n\t\tconst feeds = this.#feeds(m.underlying);\n\t\tconst maxCostRaw = usdcToRaw(opts.spend);\n\t\tconst minQuantityRaw = usdcToRaw(opts.minQuantity);\n\t\tconst { id, state } = await this.#resolveMarket(m);\n\t\tconst { lowerTick, higherTick } = await this.#strikeTicks(m, id, state);\n\t\treturn txOf(\n\t\t\tmintExactCost(this.#config, {\n\t\t\t\texpiryMarketId: id,\n\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\tlowerTick,\n\t\t\t\thigherTick,\n\t\t\t\tmaxCostRaw,\n\t\t\t\tminQuantityRaw,\n\t\t\t\t...feeds,\n\t\t\t}),\n\t\t);\n\t}\n\n\tasync #quoteMintTransaction(owner: string, tx: Transaction): Promise<MintQuote> {\n\t\tconst events = await simulateWithEvents(this.#client, tx, owner);\n\t\tconst r = exactlyOne(decodeMints(this.cfg, { events }), 'OrderMinted');\n\t\t// Mirrors the deployed `compute_mint_quote`'s all_in_cost exactly:\n\t\t// premium + (trading − subsidy) + builder + penalty + inventory-impact.\n\t\t// `referral_fee` is deliberately NOT added — it is a portion OF the\n\t\t// trader-paid trading fee and congestion surcharge, not an extra debit.\n\t\tconst costRaw =\n\t\t\tr.raw.premium +\n\t\t\t(r.raw.tradingFee - r.raw.feeIncentiveSubsidy) +\n\t\t\tr.raw.builderFee +\n\t\t\tr.raw.penaltyFee +\n\t\t\tr.raw.inventoryImpactCharge;\n\t\treturn {\n\t\t\tentryProbability: r.entryProbability,\n\t\t\tpremium: r.premium,\n\t\t\tfees: r.fees,\n\t\t\tcost: rawToUsdc(costRaw),\n\t\t\tquantity: r.quantity,\n\t\t\traw: {\n\t\t\t\tpremium: r.raw.premium,\n\t\t\t\tcost: costRaw,\n\t\t\t\tquantity: r.raw.quantity,\n\t\t\t\tentryProbability: r.raw.entryProbability,\n\t\t\t},\n\t\t\tfeesExact: true,\n\t\t};\n\t}\n\n\t// Shared construction for tx.redeem and read.quoteRedeem.\n\tasync #buildRedeem(owner: string, m: MarketDescriptor, opts: CloseOptions): Promise<Transaction> {\n\t\tconst feeds = this.#feeds(m.underlying);\n\t\tconst { id } = await this.#resolveMarket(m);\n\t\tconst closeQuantityRaw = usdcToRaw(opts.quantity);\n\t\tthis.#assertLot(closeQuantityRaw);\n\t\treturn txOf(\n\t\t\tredeemLive(this.#config, {\n\t\t\t\texpiryMarketId: id,\n\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\torderId: opts.orderId,\n\t\t\t\tcloseQuantityRaw,\n\t\t\t\t...feeds,\n\t\t\t}),\n\t\t);\n\t}\n\n\t// Raw strike for anonymous pricing: numeric strikes validate against the tick\n\t// grid; \"reference\" reads the market's reference tick fresh (unset → typed error).\n\tasync #strikeRawFor(\n\t\tm: BinaryMarketCoordinates,\n\t\tmarketId: string,\n\t\tstate: MarketState,\n\t): Promise<bigint> {\n\t\tif (m.strike !== 'reference') {\n\t\t\t// Same validation as the mint path: on the grid AND inside the finite tick\n\t\t\t// domain (0 / POS_INF are the ±inf sentinels, not quotable strikes).\n\t\t\treturn this.#gridTick(m.strike, state.tickSizeRaw) * state.tickSizeRaw;\n\t\t}\n\t\tconst tick = await referenceTick(this.#client, this.#config, marketId);\n\t\tif (tick == null) {\n\t\t\tthrow new PredictInputError(\n\t\t\t\t`reference price not set yet for ${m.underlying} @ ${m.expiryMs} — retry shortly or pass a numeric strike`,\n\t\t\t);\n\t\t}\n\t\treturn tick * state.tickSizeRaw;\n\t}\n\n\t// === delayed execution (DBU-885) ===\n\n\t// The config slice the queue calls take, or a typed refusal: without the Predict upgrade, the\n\t// order-flow companion and its desk, this SDK version has no record of delayed execution on the\n\t// network, and the queue calls would address the wrong package or decode nothing.\n\t#requireDelayedExecution(): OrdersGeneratedConfig {\n\t\treturn toOrdersConfig(this.cfg);\n\t}\n\n\t// Whether the config records delayed execution, without throwing.\n\t#recordsDelayedExecution(): boolean {\n\t\tconst { predictDelayedExecution, predictOrders } = this.cfg.packages;\n\t\tconst { orderDesk, queueRegistry } = this.cfg.objects;\n\t\treturn Boolean(predictDelayedExecution && predictOrders && orderDesk && queueRegistry);\n\t}\n\n\t// The version constants the configured call targets compile: the network's own pins, else the\n\t// versions these bindings were generated from. A watermark above one retires that code.\n\t#predictCurrentVersion(): bigint {\n\t\treturn this.cfg.packages.predictCurrentVersion ?? PREDICT_PACKAGE_VERSION;\n\t}\n\n\t#ordersCurrentVersion(): bigint {\n\t\treturn this.cfg.packages.predictOrdersCurrentVersion ?? ORDER_FLOW_PACKAGE_VERSION;\n\t}\n\n\t// The market's queue ID, once its `MarketQueue` is known to exist. A missing queue would abort\n\t// every read and order with an opaque error, so it is refused here with a typed one.\n\tasync #existingQueueId(orders: OrdersGeneratedConfig, marketId: string): Promise<string> {\n\t\tconst queueId = deriveQueueId(orders.queueRegistry, marketId);\n\t\tif (this.#knownQueues.has(queueId)) return queueId;\n\t\tconst {\n\t\t\tobjects: [queue],\n\t\t} = await this.#client.core.getObjects({ objectIds: [queueId] });\n\t\tif (queue instanceof Error) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'no-queue',\n\t\t\t\t`market ${marketId} has no order queue yet (\\`queue::create_and_share\\` hasn't run for it)`,\n\t\t\t);\n\t\t}\n\t\tthis.#knownQueues.add(queueId);\n\t\treturn queueId;\n\t}\n\n\tasync #queueState(\n\t\torders: OrdersGeneratedConfig,\n\t\tmarketId: string,\n\t\topts: { owner?: string; recordIds?: bigint[] } = {},\n\t): Promise<MarketQueueState> {\n\t\tconst queueId = await this.#existingQueueId(orders, marketId);\n\t\treturn marketQueueState(this.#client, orders, marketId, {\n\t\t\towner: opts.owner,\n\t\t\tquoteCoinType: this.cfg.quoteCoinType,\n\t\t\trecordIds: opts.recordIds,\n\t\t\tqueueId,\n\t\t});\n\t}\n\n\t// The queue gates every enqueue passes: Predict's order-flow allowlist and cutover, the\n\t// pauses, then the queue's own (`begin_enqueue`): the stuck gate, capacity, the per-account\n\t// cap, and the cutoff on the previewed τ. Throws the matching PredictPreflightError.\n\t#assertQueueOpen(\n\t\tstate: MarketQueueState,\n\t\tside: 'mint' | 'sell',\n\t\tnowMs: bigint,\n\t): { policy: DelayedExecutionPolicy; timing: TimingPreview } {\n\t\tconst policy = state.desk.policy;\n\t\tif (!state.protocol.orderFlowEnabled) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'not-live',\n\t\t\t\t\"queued orders aren't live yet: the protocol hasn't enabled the order-flow package\",\n\t\t\t);\n\t\t}\n\t\tconst mode = executionModeFor(\n\t\t\tstate.protocol.versionWatermark,\n\t\t\ttrue,\n\t\t\ttrue,\n\t\t\tthis.#predictCurrentVersion(),\n\t\t);\n\t\tif (mode === 'retired') {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'retired',\n\t\t\t\t'the Predict package version this SDK calls is retired: update the SDK',\n\t\t\t);\n\t\t}\n\t\tif (mode !== 'delayed') {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'not-live',\n\t\t\t\t\"queued orders aren't live yet: the protocol's version watermark hasn't been raised\",\n\t\t\t);\n\t\t}\n\t\tif (state.desk.versionWatermark > this.#ordersCurrentVersion()) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'retired',\n\t\t\t\t'the order-flow package version this SDK calls is retired: update the SDK',\n\t\t\t);\n\t\t}\n\t\tif (state.protocol.frozen) throw new PredictPreflightError('paused', 'the protocol is frozen');\n\t\tif (side === 'mint' && (state.protocol.tradingPaused || state.mintPaused)) {\n\t\t\tthrow new PredictPreflightError('paused', 'minting is paused on this market');\n\t\t}\n\t\tif (state.stuck) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'stuck',\n\t\t\t\t'pricing is delayed for this market, try again shortly',\n\t\t\t);\n\t\t}\n\t\tconst [pending, capacity] =\n\t\t\tside === 'mint'\n\t\t\t\t? [state.pending.mints, policy.mintCapacity]\n\t\t\t\t: [state.pending.sells, policy.sellCapacity];\n\t\tif (pending >= capacity) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'queue-full',\n\t\t\t\t`the market has ${pending} waiting ${side}s, its maximum`,\n\t\t\t);\n\t\t}\n\t\tif (state.account && state.account.waitingOrders >= policy.perAccountCap) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'account-cap',\n\t\t\t\t`the account already has ${state.account.waitingOrders} waiting orders in this market, its maximum`,\n\t\t\t);\n\t\t}\n\t\tconst timing = previewTiming({\n\t\t\tnowMs,\n\t\t\tpolicy,\n\t\t\theads: state.heads,\n\t\t\texpiryMs: state.expiryMs,\n\t\t\tnoTradeWindowMs: state.protocol.noTradeWindowMs,\n\t\t});\n\t\tif (!timing.beforeCutoff) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'past-cutoff',\n\t\t\t\t'this market no longer takes orders before its expiry',\n\t\t\t);\n\t\t}\n\t\treturn { policy, timing };\n\t}\n\n\t#preview(\n\t\tmarketId: string,\n\t\tkind: number,\n\t\ttiming: TimingPreview,\n\t\tpolicy: DelayedExecutionPolicy,\n\t\tbudget: bigint,\n\t\tcashNeedRaw: bigint,\n\t\tspareCashRaw: bigint,\n\t\tfunding: { needsFunding: boolean; fundedInTransaction: boolean },\n\t): QueuedOrderPreview {\n\t\tconst totalDebit = budget + policy.orderFee;\n\t\treturn {\n\t\t\tmarketId,\n\t\t\tkind,\n\t\t\tkindName: orderKindName(kind),\n\t\t\ttiming,\n\t\t\torderFee: rawToUsdc(policy.orderFee),\n\t\t\tbudget: rawToUsdc(budget),\n\t\t\ttotalDebit: rawToUsdc(totalDebit),\n\t\t\tcashNeedRaw,\n\t\t\tspareCashRaw,\n\t\t\t...funding,\n\t\t\traw: { orderFee: policy.orderFee, budget, totalDebit },\n\t\t};\n\t}\n\n\t// Shared by the three queued mints: resolve the market and ticks, build the enqueue (its static\n\t// checks run first), then one read for the preflight: queue gates, fee, budget, cash need.\n\tasync #planMint(\n\t\towner: string,\n\t\tm: MarketDescriptor,\n\t\torder: { kind: number; maxCostRaw: bigint; quantityRaw?: bigint; maxPremiumRaw?: bigint },\n\t\tbuild: (\n\t\t\torders: OrdersGeneratedConfig,\n\t\t\ttarget: {\n\t\t\t\texpiryMarketId: string;\n\t\t\t\twrapperId: string;\n\t\t\t\tlowerTick: bigint;\n\t\t\t\thigherTick: bigint;\n\t\t\t} & MarketFeeds,\n\t\t) => (tx: Transaction) => TransactionResult,\n\t): Promise<QueuedOrderPlan> {\n\t\tconst orders = this.#requireDelayedExecution();\n\t\tconst feeds = this.#feeds(m.underlying);\n\t\tconst { id, state: market } = await this.#resolveMarket(m);\n\t\tconst { lowerTick, higherTick } = await this.#strikeTicks(m, id, market);\n\t\tconst thunk = build(orders, {\n\t\t\texpiryMarketId: id,\n\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\tlowerTick,\n\t\t\thigherTick,\n\t\t\t...feeds,\n\t\t});\n\t\tconst state = await this.#queueState(orders, id, { owner });\n\t\tconst { policy, timing } = this.#assertQueueOpen(state, 'mint', BigInt(Date.now()));\n\t\tconst { budget, cashNeed } = PredictClient.#assertMintOrder(state, policy, order);\n\t\t// The enqueue charges the desk's fee at execution, so hold it to the previewed one.\n\t\tconst tx = new Transaction();\n\t\ttx.add(assertOrderFeeAtMost(orders, policy.orderFee));\n\t\ttx.add(thunk);\n\t\treturn {\n\t\t\ttransaction: tx,\n\t\t\tpreview: this.#preview(id, order.kind, timing, policy, budget, cashNeed, state.spareCash, {\n\t\t\t\tneedsFunding: false,\n\t\t\t\tfundedInTransaction: false,\n\t\t\t}),\n\t\t};\n\t}\n\n\t// A mint's own checks after the queue gates, shared by the mint builders and `read.planMint`:\n\t// the order fee, the escrowed budget against the minimum premium, and the market's cash.\n\tstatic #assertMintOrder(\n\t\tstate: MarketQueueState,\n\t\tpolicy: DelayedExecutionPolicy,\n\t\torder: { kind: number; maxCostRaw: bigint; quantityRaw?: bigint; maxPremiumRaw?: bigint },\n\t): { budget: bigint; cashNeed: bigint } {\n\t\tconst available = state.account?.availableRaw ?? 0n;\n\t\tconst budget = mintBudget({\n\t\t\tkind: order.kind,\n\t\t\tmaxCostRaw: order.maxCostRaw,\n\t\t\tavailableRaw: available,\n\t\t\torderFeeRaw: policy.orderFee,\n\t\t\tquantityRaw: order.quantityRaw,\n\t\t});\n\t\tif (budget == null) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'fee',\n\t\t\t\t`the balance (${rawToUsdc(available)}) doesn't cover the ${rawToUsdc(policy.orderFee)} order fee`,\n\t\t\t);\n\t\t}\n\t\tif (budget < MIN_PREMIUM) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'min-premium',\n\t\t\t\t`the escrowed budget ${rawToUsdc(budget)} is below the ${rawToUsdc(MIN_PREMIUM)} minimum premium`,\n\t\t\t);\n\t\t}\n\t\tif (order.kind !== ORDER_KIND.EXACT_QUANTITY && state.minEntryProbability === 0n) {\n\t\t\tthrow new PredictPreflightError('market-cash', 'this market takes no budget mints');\n\t\t}\n\t\tconst cashNeed = mintCashNeed({\n\t\t\tkind: order.kind,\n\t\t\tbudgetRaw: budget,\n\t\t\tminEntryProbability: state.minEntryProbability,\n\t\t\tquantityRaw: order.quantityRaw,\n\t\t\tmaxPremiumRaw: order.maxPremiumRaw,\n\t\t});\n\t\tif (cashNeed > state.spareCash) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'market-cash',\n\t\t\t\t\"this market can't take an order this size right now\",\n\t\t\t);\n\t\t}\n\t\treturn { budget, cashNeed };\n\t}\n\n\t// The record a sell names is Open. The chain can't even quote one that isn't (`ERecordNotOpen`).\n\tstatic #assertRecordOpen(state: MarketQueueState, recordId: bigint): QueuedOrder {\n\t\tconst record = state.records[0];\n\t\tif (!record || record.status !== ORDER_STATUS.OPEN || record.position.order_id === 0n) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'record-not-open',\n\t\t\t\t`record ${recordId} isn't an Open position`,\n\t\t\t);\n\t\t}\n\t\treturn record;\n\t}\n\n\t// The quantity an Open record holds, refusing a sell of more than that.\n\t#assertSellQuantity(record: QueuedOrder, closeQuantityRaw: bigint): bigint {\n\t\tconst held = decodeOrderRange(\n\t\t\trecord.position.order_id,\n\t\t\tBigInt(this.cfg.units.positionLotSize),\n\t\t).quantity;\n\t\tif (closeQuantityRaw > held) {\n\t\t\tthrow new PredictInputError(\n\t\t\t\t`quantity ${rawToUsdc(closeQuantityRaw)} is above the record's ${rawToUsdc(held)}`,\n\t\t\t);\n\t\t}\n\t\treturn held;\n\t}\n\n\t// A sell's own checks after the queue gates, shared by `tx.enqueueSell` and `read.planSell`: the\n\t// record is Open and the owner's, the order fee, the record's quantity and the minimum sell. A\n\t// sell is never refused for market cash.\n\t#assertSellOrder(\n\t\tstate: MarketQueueState,\n\t\tpolicy: DelayedExecutionPolicy,\n\t\trecordId: bigint,\n\t\tcloseQuantityRaw: bigint,\n\t): void {\n\t\tconst record = PredictClient.#assertRecordOpen(state, recordId);\n\t\tif (\n\t\t\t!state.account ||\n\t\t\tnormalizeSuiAddress(record.account_id) !== normalizeSuiAddress(state.account.accountId)\n\t\t) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'not-record-owner',\n\t\t\t\t`record ${recordId} belongs to another account`,\n\t\t\t);\n\t\t}\n\t\tif (!feeCovered('sell', state.account.availableRaw, policy.orderFee)) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'fee',\n\t\t\t\t`the balance doesn't cover the ${rawToUsdc(policy.orderFee)} order fee`,\n\t\t\t);\n\t\t}\n\t\tconst held = this.#assertSellQuantity(record, closeQuantityRaw);\n\t\tconst min = policy.minSellQuantity;\n\t\tif (closeQuantityRaw < min || (closeQuantityRaw < held && held - closeQuantityRaw < min)) {\n\t\t\tthrow new PredictPreflightError(\n\t\t\t\t'below-min-sell',\n\t\t\t\t`a sell must close at least ${rawToUsdc(min)} and leave either nothing or at least that much`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync #planSell(\n\t\towner: string,\n\t\tm: MarketCoordinates,\n\t\topts: EnqueueSellOptions,\n\t): Promise<QueuedOrderPlan> {\n\t\tconst orders = this.#requireDelayedExecution();\n\t\tconst feeds = this.#feeds(m.underlying);\n\t\tconst { id } = await this.#resolveMarket(m);\n\t\tconst closeQuantityRaw = usdcToRaw(opts.quantity);\n\t\tthis.#assertLot(closeQuantityRaw);\n\t\tconst thunk = enqueueRedeemOpen(orders, {\n\t\t\texpiryMarketId: id,\n\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\trecordId: opts.recordId,\n\t\t\tcloseQuantityRaw,\n\t\t\tminProbabilityRaw: probabilityToRaw(opts.minProbability),\n\t\t\tminProceedsRaw: usdcToRaw(opts.minProceeds),\n\t\t\t...feeds,\n\t\t});\n\t\tconst state = await this.#queueState(orders, id, { owner, recordIds: [opts.recordId] });\n\t\tconst { policy, timing } = this.#assertQueueOpen(state, 'sell', BigInt(Date.now()));\n\t\tthis.#assertSellOrder(state, policy, opts.recordId, closeQuantityRaw);\n\t\tconst cashNeed = cashNeedSell(closeQuantityRaw, state.backingBufferLambda);\n\t\tconst needsFunding = cashNeed > state.spareCash;\n\t\tconst fund = opts.fundMarket ?? 'auto';\n\t\tconst funded = fund === 'always' || (fund === 'auto' && needsFunding);\n\t\tconst tx = new Transaction();\n\t\t// The enqueue charges the desk's fee at execution, so hold it to the previewed one.\n\t\ttx.add(assertOrderFeeAtMost(orders, policy.orderFee));\n\t\ttx.add(thunk);\n\t\t// After the enqueue: its cash need is then in `waiting_cash_need`, which the rebalance funds.\n\t\tif (funded) tx.add(rebalanceExpiryCash(this.#config, { expiryMarketId: id }));\n\t\treturn {\n\t\t\ttransaction: tx,\n\t\t\tpreview: this.#preview(\n\t\t\t\tid,\n\t\t\t\tORDER_KIND.REDEEM_OPEN,\n\t\t\t\ttiming,\n\t\t\t\tpolicy,\n\t\t\t\t0n,\n\t\t\t\tcashNeed,\n\t\t\t\tstate.spareCash,\n\t\t\t\t{\n\t\t\t\t\tneedsFunding,\n\t\t\t\t\tfundedInTransaction: funded,\n\t\t\t\t},\n\t\t\t),\n\t\t};\n\t}\n\n\t// A chain mint quote as a queued-fill preview: the congestion penalty comes out of the cost\n\t// (a queued fill pays none) and the order fee is reported separately.\n\tstatic #queuedMintQuote(q: MintQuoteRaw, policy: DelayedExecutionPolicy | null): MintQuote {\n\t\tconst costRaw = q.allInCost - q.penaltyFee;\n\t\treturn {\n\t\t\tentryProbability: rawToProbability(q.entryProbability),\n\t\t\tpremium: rawToUsdc(q.premium),\n\t\t\tfees: {\n\t\t\t\ttrading: rawToUsdc(q.tradingFee),\n\t\t\t\tsubsidy: rawToUsdc(q.feeIncentiveSubsidy),\n\t\t\t\tbuilder: rawToUsdc(q.builderFee),\n\t\t\t\tpenalty: 0,\n\t\t\t\t// The chain quote doesn't split it out. It is part of `trading`, never extra.\n\t\t\t\treferral: 0,\n\t\t\t\tinventoryImpact: rawToUsdc(q.inventoryImpactCharge),\n\t\t\t},\n\t\t\tcost: rawToUsdc(costRaw),\n\t\t\tquantity: rawToUsdc(q.quantity),\n\t\t\traw: {\n\t\t\t\tpremium: q.premium,\n\t\t\t\tcost: costRaw,\n\t\t\t\tquantity: q.quantity,\n\t\t\t\tentryProbability: q.entryProbability,\n\t\t\t},\n\t\t\tfeesExact: true,\n\t\t\tqueued: true,\n\t\t\torderFee: policy ? rawToUsdc(policy.orderFee) : undefined,\n\t\t};\n\t}\n\n\t// === tx builders ===\n\t// Each returns a ready-to-sign Transaction. Market-resolving builders are async.\n\treadonly tx = {\n\t\tcreateManager: (): Transaction => txOf(accountContract(this.cfg).createAccount()),\n\n\t\t// `create: true` composes first-time funding into ONE PTB: create the account\n\t\t// wrapper, deposit into it through the fresh handle, and `share` it LAST (once\n\t\t// shared, by-value use of the handle is over). The wrapper is derived from the\n\t\t// transaction SENDER (`account_registry::new` takes no owner), so `owner` MUST\n\t\t// be the address that signs this transaction — a sponsored/backend signer would\n\t\t// silently fund its own fresh account instead. The caller also asserts the\n\t\t// account does not exist yet: `new` ABORTS at the deterministic address if it\n\t\t// already exists — no chain read is done here. Gate on your own existence check\n\t\t// (`wrapperIdFor(owner)` + a getObject), or retry without the flag on that abort.\n\t\t//\n\t\t// Without `create`, the sourced coin goes into the existing account's stored\n\t\t// balance via the PTB-callable `deposit_funds` (folds settle → authorize → load →\n\t\t// deposit; clock auto-injected). Command order is auth → deposit (auth is a hot\n\t\t// potato consumed by the deposit). See\n\t\t// `packages/account/sources/account.move` (`deposit_funds`).\n\t\tdeposit: (\n\t\t\towner: string,\n\t\t\tamountUsdc: number | string,\n\t\t\topts?: { create?: boolean },\n\t\t): Transaction => {\n\t\t\tconst tx = new Transaction();\n\t\t\tconst coin = tx.add(\n\t\t\t\tcoinWithBalance({\n\t\t\t\t\ttype: this.cfg.quoteCoinType,\n\t\t\t\t\tbalance: usdcToRaw(amountUsdc),\n\t\t\t\t\tuseGasCoin: false,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (opts?.create) {\n\t\t\t\ttx.add(\n\t\t\t\t\taccountContract(this.cfg).createAccountAndDeposit({\n\t\t\t\t\t\tcoin,\n\t\t\t\t\t\tcoinType: this.cfg.quoteCoinType,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\ttx.add(\n\t\t\t\t\tdepositFunds({\n\t\t\t\t\t\tconfig: this.#config,\n\t\t\t\t\t\targuments: { wrapper: this.wrapperIdFor(owner), coin },\n\t\t\t\t\t\ttypeArguments: [this.cfg.quoteCoinType],\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn tx;\n\t\t},\n\n\t\t// Withdraw `amountUsdc` from the account back to `owner`. By default the funds land\n\t\t// in the owner's USDC *address balance* (the versionless accumulator) via\n\t\t// `0x2::coin::send_funds` — no coin-object churn, and they merge into the same\n\t\t// balance `deposit` draws from, closing the loop. Pass `{ toCoinObject: true }` to\n\t\t// instead receive a discrete `Coin<T>` object (for wallets/explorers that only\n\t\t// render coin objects, or to compose the coin further in your own PTB). Either way\n\t\t// the underlying `withdraw_funds` returns the raw `Coin<T>` — the PTB-callable form\n\t\t// that folds settle → authorize → load → withdraw (clock auto-injected, `ctx`\n\t\t// implicit); command order is auth → withdraw. See\n\t\t// `packages/account/sources/account.move` (`withdraw_funds`).\n\t\twithdraw: (\n\t\t\towner: string,\n\t\t\tamountUsdc: number | string,\n\t\t\topts?: { toCoinObject?: boolean },\n\t\t): Transaction => {\n\t\t\tconst tx = new Transaction();\n\t\t\tconst coin = tx.add(\n\t\t\t\twithdrawFunds({\n\t\t\t\t\tconfig: this.#config,\n\t\t\t\t\targuments: { wrapper: this.wrapperIdFor(owner), amount: usdcToRaw(amountUsdc) },\n\t\t\t\t\ttypeArguments: [this.cfg.quoteCoinType],\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (opts?.toCoinObject) {\n\t\t\t\ttx.transferObjects([coin], owner);\n\t\t\t} else {\n\t\t\t\ttx.moveCall({\n\t\t\t\t\ttarget: '0x2::coin::send_funds',\n\t\t\t\t\ttypeArguments: [this.cfg.quoteCoinType],\n\t\t\t\t\targuments: [coin, tx.pure.address(owner)],\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn tx;\n\t\t},\n\n\t\t/**\n\t\t * Immediate exact-quantity mint (`mint_exact_quantity`).\n\t\t * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n\t\t * (`EDelayedExecutionRequired`), so it works only while the config calls a pre-v4 package.\n\t\t * Use {@link PredictClient.tx.enqueueMint}, and `read.executionMode()` to know which path a\n\t\t * network is on.\n\t\t */\n\t\tmint: (owner: string, m: MarketDescriptor, opts: MintOptions): Promise<Transaction> =>\n\t\t\tthis.#buildMint(owner, m, opts),\n\n\t\t/**\n\t\t * V2 all-in budget mint; use minQuantity to protect the fill against slippage.\n\t\t * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n\t\t * (`EDelayedExecutionRequired`). Use `tx.enqueueMintCost`.\n\t\t */\n\t\tmintCost: (owner: string, m: MarketDescriptor, opts: MintCostOptions): Promise<Transaction> =>\n\t\t\tthis.#buildMintCost(owner, m, opts),\n\n\t\t/**\n\t\t * Immediate premium-budget mint (`mint_exact_amount`).\n\t\t * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n\t\t * (`EDelayedExecutionRequired`). Use `tx.enqueueMintAmount`.\n\t\t */\n\t\tmintAmount: async (\n\t\t\towner: string,\n\t\t\tm: MarketDescriptor,\n\t\t\topts: MintAmountOptions,\n\t\t): Promise<Transaction> => {\n\t\t\tconst feeds = this.#feeds(m.underlying);\n\t\t\t// The chain requires a positive all-in cost cap (EMintCostCapRequired);\n\t\t\t// reject a zero cap pre-flight rather than surface a cryptic Move abort.\n\t\t\tif (opts.maxCost != null && opts.maxCost <= 0) {\n\t\t\t\tthrow new PredictInputError('maxCost must be > 0');\n\t\t\t}\n\t\t\tconst { id, state } = await this.#resolveMarket(m);\n\t\t\t// No lot check: min_quantity is a floor the chain compares against an\n\t\t\t// already-lot-floored minted quantity, so any floor value is legal.\n\t\t\tconst minQuantityRaw = usdcToRaw(opts.minQuantity);\n\t\t\tconst { lowerTick, higherTick } = await this.#strikeTicks(m, id, state);\n\t\t\treturn txOf(\n\t\t\t\tmintExactAmount(this.#config, {\n\t\t\t\t\texpiryMarketId: id,\n\t\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\t\tlowerTick,\n\t\t\t\t\thigherTick,\n\t\t\t\t\tmaxPremiumRaw: usdcToRaw(opts.spend),\n\t\t\t\t\tminQuantityRaw,\n\t\t\t\t\tmaxCostRaw: opts.maxCost != null ? usdcToRaw(opts.maxCost) : undefined,\n\t\t\t\t\t...feeds,\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\n\t\t/**\n\t\t * Immediate close of an account position (`redeem_live`).\n\t\t * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n\t\t * (`EDelayedExecutionRequired`). A position held in the account then has no early exit and\n\t\t * is paid at settlement with `claimSettled`. Queued fills are Open records in the market's\n\t\t * queue, sold with `tx.enqueueSell`.\n\t\t */\n\t\tredeem: (owner: string, m: MarketDescriptor, opts: CloseOptions): Promise<Transaction> =>\n\t\t\tthis.#buildRedeem(owner, m, opts),\n\n\t\t/**\n\t\t * Pay a settled position held in the ACCOUNT (`redeem_settled`), in full. Unchanged by delayed\n\t\t * execution, for positions minted before it. It doesn't pay Open queue records: the queue's\n\t\t * settlement walk (`settle_step`) pays those to the account's wrapper address.\n\t\t */\n\t\tclaimSettled: async (\n\t\t\towner: string,\n\t\t\tm: Pick<MarketDescriptor, 'underlying' | 'expiryMs' | 'marketId'>,\n\t\t\topts: Pick<CloseOptions, 'orderId'>,\n\t\t): Promise<Transaction> => {\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\treturn txOf(\n\t\t\t\tredeemSettled(this.#config, {\n\t\t\t\t\texpiryMarketId: id,\n\t\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\t\torderId: opts.orderId,\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\n\t\t// --- delayed execution (DBU-885) ---\n\t\t// Each queued-order builder reads the market once and refuses, with a typed\n\t\t// PredictPreflightError, an order the queue or protocol gates would abort, so a refused order\n\t\t// never fails a larger transaction. The order's own limits at the current price are checked\n\t\t// only on chain. It returns the transaction and a display preview. Every builder throws\n\t\t// PredictInputError while the network's config doesn't record delayed execution.\n\n\t\t/**\n\t\t * Queue a mint of an exact payout quantity, filled at Pyth's price for its τ. Escrows\n\t\t * `min(maxCost, quantity, available − fee)` plus the order fee. `maxCost` and\n\t\t * `maxProbability` are required caps (see `queue.slippageBand`). Size against\n\t\t * `read.queue(...).maxMint`. The record ID is in the enqueue's `OrderEnqueued`\n\t\t * (`decode.enqueue`).\n\t\t */\n\t\tenqueueMint: async (\n\t\t\towner: string,\n\t\t\tm: MarketDescriptor,\n\t\t\topts: EnqueueMintOptions,\n\t\t): Promise<QueuedOrderPlan> => {\n\t\t\tconst quantityRaw = usdcToRaw(opts.quantity);\n\t\t\tthis.#assertLot(quantityRaw);\n\t\t\tconst maxCostRaw = usdcToRaw(opts.maxCost);\n\t\t\tconst maxProbabilityRaw = probabilityToRaw(opts.maxProbability);\n\t\t\treturn this.#planMint(\n\t\t\t\towner,\n\t\t\t\tm,\n\t\t\t\t{ kind: ORDER_KIND.EXACT_QUANTITY, maxCostRaw, quantityRaw },\n\t\t\t\t(orders, target) =>\n\t\t\t\t\tenqueueExactQuantity(orders, {\n\t\t\t\t\t\t...target,\n\t\t\t\t\t\tquantityRaw,\n\t\t\t\t\t\tmaxCostRaw,\n\t\t\t\t\t\tmaxProbabilityRaw,\n\t\t\t\t\t}),\n\t\t\t);\n\t\t},\n\n\t\t/**\n\t\t * Queue a premium-budget mint: sized at τ under `spend`, at least `minQuantity`, with the\n\t\t * all-in debit capped by the required `maxCost`.\n\t\t */\n\t\tenqueueMintAmount: async (\n\t\t\towner: string,\n\t\t\tm: MarketDescriptor,\n\t\t\topts: EnqueueMintAmountOptions,\n\t\t): Promise<QueuedOrderPlan> => {\n\t\t\tconst maxPremiumRaw = usdcToRaw(opts.spend);\n\t\t\tconst minQuantityRaw = usdcToRaw(opts.minQuantity);\n\t\t\tconst maxCostRaw = usdcToRaw(opts.maxCost);\n\t\t\t// The fill buys at most `spend` of premium, so a spend below the minimum premium fails\n\t\t\t// the chain's placement dry run whatever the budget. Refused before any read.\n\t\t\tif (maxPremiumRaw < MIN_PREMIUM) {\n\t\t\t\tthrow new PredictPreflightError(\n\t\t\t\t\t'min-premium',\n\t\t\t\t\t`spend ${rawToUsdc(maxPremiumRaw)} is below the ${rawToUsdc(MIN_PREMIUM)} minimum premium`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn this.#planMint(\n\t\t\t\towner,\n\t\t\t\tm,\n\t\t\t\t{ kind: ORDER_KIND.EXACT_AMOUNT, maxCostRaw, maxPremiumRaw },\n\t\t\t\t(orders, target) =>\n\t\t\t\t\tenqueueExactAmount(orders, {\n\t\t\t\t\t\t...target,\n\t\t\t\t\t\tmaxPremiumRaw,\n\t\t\t\t\t\tminQuantityRaw,\n\t\t\t\t\t\tmaxCostRaw,\n\t\t\t\t\t}),\n\t\t\t);\n\t\t},\n\n\t\t/**\n\t\t * Queue an all-in-budget mint (the default mint): sized at τ so the all-in cost fits\n\t\t * `spend`, at least `minQuantity`. Escrows `min(spend, available − fee)` plus the order fee.\n\t\t */\n\t\tenqueueMintCost: async (\n\t\t\towner: string,\n\t\t\tm: MarketDescriptor,\n\t\t\topts: EnqueueMintCostOptions,\n\t\t): Promise<QueuedOrderPlan> => {\n\t\t\tconst maxCostRaw = usdcToRaw(opts.spend);\n\t\t\tconst minQuantityRaw = usdcToRaw(opts.minQuantity);\n\t\t\treturn this.#planMint(\n\t\t\t\towner,\n\t\t\t\tm,\n\t\t\t\t{ kind: ORDER_KIND.EXACT_COST, maxCostRaw },\n\t\t\t\t(orders, target) => enqueueExactCost(orders, { ...target, maxCostRaw, minQuantityRaw }),\n\t\t\t);\n\t\t},\n\n\t\t/**\n\t\t * Queue an early sell of an Open record (`enqueue_redeem_open`), the only early sell in v4.\n\t\t * The record must be Open and the owner's. Sells are never refused for market cash: when the\n\t\t * sell's cash need is above spare cash the preview sets `needsFunding`, and by default the\n\t\t * builder adds `rebalance_expiry_cash` after the enqueue (see `fundMarket`). A sell the market\n\t\t * still can't cover at the fill is refunded in full (reason 8) and the position returns to an\n\t\t * Open record.\n\t\t */\n\t\tenqueueSell: (\n\t\t\towner: string,\n\t\t\tm: MarketCoordinates,\n\t\t\topts: EnqueueSellOptions,\n\t\t): Promise<QueuedOrderPlan> => this.#planSell(owner, m, opts),\n\n\t\t/**\n\t\t * Queue the order a `read.planMint` or `read.planSell` plan describes, with its limits:\n\t\t * `enqueueMintCost`, `enqueueMint` or `enqueueSell`, by `plan.order.builder`. Pass the\n\t\t * market the plan was made for: the descriptor a mint plan was planned with, or the\n\t\t * coordinates `read.planSell` took for a sell plan. Throws the plan's `refusal` as a\n\t\t * `PredictPreflightError`, and `'fee'` when the balance now escrows less than the plan's\n\t\t * budget.\n\t\t */\n\t\tenqueuePlan: async <P extends MintPlan | SellPlan>(\n\t\t\towner: string,\n\t\t\tm: P extends SellPlan ? MarketCoordinates : MarketDescriptor,\n\t\t\tplan: P,\n\t\t): Promise<QueuedOrderPlan> => {\n\t\t\t// A plan that reported a refusal is refused the same way, so the two never disagree.\n\t\t\t// Plan again once the reason clears.\n\t\t\tif (plan.refusal != null) {\n\t\t\t\tthrow new PredictPreflightError(plan.refusal, `the plan was refused (${plan.refusal})`);\n\t\t\t}\n\t\t\t// A plan's limits fit one order. Queued for another owner, market, strike or record, they\n\t\t\t// would buy or sell a different contract, so plan that order instead.\n\t\t\tconst target = plan.target;\n\t\t\tconst { id, state: marketState } = await this.#resolveMarket(m);\n\t\t\tif (normalizeSuiAddress(owner) !== normalizeSuiAddress(target.owner)) {\n\t\t\t\tthrow new PredictInputError(`the plan was made for owner ${target.owner}, not ${owner}`);\n\t\t\t}\n\t\t\tif (normalizeSuiAddress(id) !== normalizeSuiAddress(target.expiryMarketId)) {\n\t\t\t\tthrow new PredictInputError(\n\t\t\t\t\t`the plan was made for market ${target.expiryMarketId}, not ${id}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst order = plan.order;\n\t\t\t// A mint needs the descriptor's strike and side. A plan typed only as\n\t\t\t// `MintPlan | SellPlan` can pass bare coordinates, so check.\n\t\t\tconst descriptor = 'side' in m ? (m as MarketDescriptor) : null;\n\t\t\tlet placed: QueuedOrderPlan;\n\t\t\tif (order.builder === 'enqueueSell') {\n\t\t\t\tif (order.options.recordId !== target.recordId) {\n\t\t\t\t\tthrow new PredictInputError(\n\t\t\t\t\t\t`the plan was made for record ${target.recordId}, not ${order.options.recordId}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tplaced = await this.tx.enqueueSell(owner, m, order.options);\n\t\t\t} else {\n\t\t\t\tif (descriptor == null) {\n\t\t\t\t\tthrow new PredictInputError(\n\t\t\t\t\t\t'a mint plan needs the market descriptor it was planned with (its strike and side)',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst { lowerTick, higherTick } = await this.#strikeTicks(descriptor, id, marketState);\n\t\t\t\tif (lowerTick !== target.lowerTick || higherTick !== target.higherTick) {\n\t\t\t\t\tthrow new PredictInputError(\n\t\t\t\t\t\t'the market descriptor names a different strike or side than the plan, or its reference strike moved: plan again',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tplaced =\n\t\t\t\t\torder.builder === 'enqueueMintCost'\n\t\t\t\t\t\t? await this.tx.enqueueMintCost(owner, descriptor, order.options)\n\t\t\t\t\t\t: await this.tx.enqueueMint(owner, descriptor, order.options);\n\t\t\t}\n\t\t\t// The plan's debit, and a sell's net, assume the order fee it was quoted with. The builders\n\t\t\t// read the desk's fee again, and no order argument bounds it on chain, so refuse a fee\n\t\t\t// that rose since the plan.\n\t\t\tif (placed.preview.raw.orderFee > plan.raw.orderFee) {\n\t\t\t\tthrow new PredictInputError(\n\t\t\t\t\t`the order fee rose from ${rawToUsdc(plan.raw.orderFee)} to ${placed.preview.orderFee} since the plan: plan again`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (order.builder === 'enqueueSell') return placed;\n\t\t\t// The limits assume the plan's whole budget. The builders escrow less when the balance\n\t\t\t// fell since the plan, so refuse that instead.\n\t\t\tconst planned = (plan as MintPlan).raw.budget;\n\t\t\tif (placed.preview.raw.budget < planned) {\n\t\t\t\tthrow new PredictPreflightError(\n\t\t\t\t\t'fee',\n\t\t\t\t\t`the balance now escrows ${placed.preview.budget}, below the plan's ${rawToUsdc(planned)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn placed;\n\t\t},\n\n\t\t/**\n\t\t * Refund this market's orders past their deadline. For the app's \"Refund my order\" button\n\t\t * only (`OrderView.canRequestRefund`), never prepended to other transactions: keepers\n\t\t * refund on their own. Needs no account, session or Pyth key, and works during a freeze.\n\t\t * `maxOrders` (default 100) bounds the records visited.\n\t\t */\n\t\trefund: async (\n\t\t\tm: MarketCoordinates,\n\t\t\topts: { maxOrders?: number } = {},\n\t\t): Promise<Transaction> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst queueId = await this.#existingQueueId(orders, id);\n\t\t\treturn txOf(\n\t\t\t\trefund(orders, {\n\t\t\t\t\texpiryMarketId: id,\n\t\t\t\t\tqueueId,\n\t\t\t\t\tmaxOrders: BigInt(opts.maxOrders ?? 100),\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\n\t\t/**\n\t\t * Send a finished record's parked funds to its receive address (`queue::claim_parked`): a\n\t\t * refund or change the address couldn't take while it was on USDC's deny list or USDC was\n\t\t * paused (`OrderView` `parkedRaw`). A skipped settlement payout isn't parked: pay it with\n\t\t * `payOpen`. Permissionless, and a no-op returning 0 while\n\t\t * the address is still denied. Needs no account, session or Pyth key.\n\t\t */\n\t\tclaimParked: async (m: MarketCoordinates, recordId: bigint): Promise<Transaction> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst queueId = await this.#existingQueueId(orders, id);\n\t\t\treturn txOf(claimParked(orders, { expiryMarketId: id, queueId, recordId }));\n\t\t},\n\n\t\t/**\n\t\t * Pay a settled market's Open record that the payout walk skipped (`queue::pay_open`), for\n\t\t * example while its receive address was denied. Permissionless: the payout goes only to the\n\t\t * record's own receive address. Aborts `EMarketNotSettled` before settlement.\n\t\t */\n\t\tpayOpen: async (m: MarketCoordinates, recordId: bigint): Promise<Transaction> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst queueId = await this.#existingQueueId(orders, id);\n\t\t\treturn txOf(payOpen(orders, { expiryMarketId: id, queueId, recordId }));\n\t\t},\n\n\t\t/**\n\t\t * The open filler: verify signed Pyth Lazer payloads, commit them to the market's waiting\n\t\t * cohorts, then resolve up to `maxOrders` (default 15) records. Reads the current Lazer\n\t\t * package from Lazer's `State` first (`lazerStateId`, or `config.oracle.pythLazerState`).\n\t\t */\n\t\tfill: async (\n\t\t\tm: MarketCoordinates,\n\t\t\topts: {\n\t\t\t\tpayloads: readonly Uint8Array[];\n\t\t\t\tmaxOrders?: number;\n\t\t\t\trefundOverdue?: boolean;\n\t\t\t\tlazerStateId?: string;\n\t\t\t},\n\t\t): Promise<Transaction> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst stateId = opts.lazerStateId ?? this.cfg.oracle?.pythLazerState;\n\t\t\tif (!stateId) {\n\t\t\t\tthrow new PredictInputError('fill needs the Pyth Lazer State: pass `lazerStateId`');\n\t\t\t}\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst queueId = await this.#existingQueueId(orders, id);\n\t\t\tconst lazer = await lazerPackages(this.#client, stateId);\n\t\t\treturn txOf(\n\t\t\t\tfill(orders, {\n\t\t\t\t\texpiryMarketId: id,\n\t\t\t\t\tqueueId,\n\t\t\t\t\tpayloads: opts.payloads,\n\t\t\t\t\tlazer,\n\t\t\t\t\tmaxOrders: BigInt(opts.maxOrders ?? 15),\n\t\t\t\t\trefundOverdue: opts.refundOverdue,\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\n\t\t// Queue a supply request pulling `amountUsdc` from the account's existing custody\n\t\t// balance. `request_supply` auto-settles USDC then `account.withdraw`s the payment\n\t\t// into queue escrow; the PLP fill is delivered at the next flush, not returned here.\n\t\t// Command order is auth → request (auth is a hot potato consumed by this call). The\n\t\t// `minPlpOut` slot is the per-request floor on PLP minted at flush — `options.minPlpOut`\n\t\t// when given, otherwise 0 (no floor). At the shipped attempt count of one, the first\n\t\t// flush whose mark quotes less cancels and refunds the request; three is the\n\t\t// configurable maximum, not the default.\n\t\tsupplyPlp: (\n\t\t\towner: string,\n\t\t\tamountUsdc: number | string,\n\t\t\toptions: PlpSupplyOptions = {},\n\t\t): Transaction =>\n\t\t\ttxOf(\n\t\t\t\trequestSupply({\n\t\t\t\t\tconfig: this.#config,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\twrapper: this.wrapperIdFor(owner),\n\t\t\t\t\t\tamount: usdcToRaw(amountUsdc),\n\t\t\t\t\t\tminPlpOut: options.minPlpOut ?? 0n,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t),\n\n\t\t// Queue a withdraw request pulling `shares` (raw PLP u64) from account custody into\n\t\t// queue escrow — the Move parameter is named `amount`, but on `request_withdraw` it\n\t\t// counts PLP SHARES, not USDC. Auto-settles flush-delivered PLP first; the USDC\n\t\t// fill lands on the account at the next flush (no `withdraw_settled` entrypoint).\n\t\t// Command order is auth → request. The `minUsdcOut` slot is the per-request floor\n\t\t// on USDC paid at flush — `options.minUsdcOut` when given, otherwise 0 (no floor).\n\t\t// At the shipped attempt count of one, the first flush whose mark quotes less\n\t\t// cancels and refunds the request; three is the configurable maximum, not the\n\t\t// default.\n\t\twithdrawPlp: (owner: string, shares: bigint, options: PlpWithdrawOptions = {}): Transaction =>\n\t\t\ttxOf(\n\t\t\t\trequestWithdraw({\n\t\t\t\t\tconfig: this.#config,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\twrapper: this.wrapperIdFor(owner),\n\t\t\t\t\t\tamount: shares,\n\t\t\t\t\t\tminUsdcOut: options.minUsdcOut === undefined ? 0n : usdcToRaw(options.minUsdcOut),\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t),\n\n\t\t// Cancel a still-pending supply request by queue `index`, refunding its escrowed\n\t\t// USDC straight back into the requesting account. Command order is auth → cancel.\n\t\tcancelSupplyPlp: (owner: string, index: bigint): Transaction =>\n\t\t\ttxOf(\n\t\t\t\tcancelSupplyRequest({\n\t\t\t\t\tconfig: this.#config,\n\t\t\t\t\targuments: { wrapper: this.wrapperIdFor(owner), index },\n\t\t\t\t}),\n\t\t\t),\n\n\t\t// Cancel a still-pending withdraw request by queue `index`, refunding its escrowed\n\t\t// PLP straight back into the requesting account. Command order is auth → cancel.\n\t\tcancelWithdrawPlp: (owner: string, index: bigint): Transaction =>\n\t\t\ttxOf(\n\t\t\t\tcancelWithdrawRequest({\n\t\t\t\t\tconfig: this.#config,\n\t\t\t\t\targuments: { wrapper: this.wrapperIdFor(owner), index },\n\t\t\t\t}),\n\t\t\t),\n\n\t\t// Set the account's sticky builder-code attribution to `builderCodeId`, an existing\n\t\t// `BuilderCode` object borrowed as `&BuilderCode`. Command order is auth → set (auth\n\t\t// is a hot potato consumed by this call). Lives in the PREDICT package's\n\t\t// `predict_account` module, NOT the account package. Deployed sig\n\t\t// `packages/predict/sources/predict_account.move:134` — 3 moveCall args\n\t\t// (wrapper, auth, code; ctx implicit).\n\t\tsetBuilderCode: (owner: string, builderCodeId: string): Transaction =>\n\t\t\ttxOf(\n\t\t\t\tsetBuilderCode({\n\t\t\t\t\tconfig: this.#config,\n\t\t\t\t\targuments: { wrapper: this.wrapperIdFor(owner), code: builderCodeId },\n\t\t\t\t}),\n\t\t\t),\n\n\t\t// Clear the account's sticky builder-code attribution. Command order is auth → unset.\n\t\t// Deployed sig `.../predict_account.move:151` — 2 moveCall args (wrapper, auth; ctx\n\t\t// implicit).\n\t\tunsetBuilderCode: (owner: string): Transaction =>\n\t\t\ttxOf(\n\t\t\t\tunsetBuilderCode({\n\t\t\t\t\tconfig: this.#config,\n\t\t\t\t\targuments: { wrapper: this.wrapperIdFor(owner) },\n\t\t\t\t}),\n\t\t\t),\n\t};\n\n\t// === reads ===\n\treadonly read = {\n\t\t// All tradeable (active) markets with the state a frontend needs to render\n\t\t// and mint: one chain read for ids + one batched PTB for the states.\n\t\tmarkets: async (): Promise<ActiveMarket[]> => {\n\t\t\tconst ids = await activeMarketIds(this.#client, this.#config);\n\t\t\tconst states = await marketStates(this.#client, this.#config, ids);\n\t\t\treturn ids.map((id, i) => ({\n\t\t\t\tid,\n\t\t\t\texpiryMs: states[i].expiryMs,\n\t\t\t\ttickSize: fromRaw(states[i].tickSizeRaw, 9),\n\t\t\t\tadmissionTickSize: fromRaw(states[i].admissionTickSizeRaw, 9),\n\t\t\t\tmintPaused: states[i].mintPaused,\n\t\t\t\treferencePrice: PredictClient.#referencePriceOf(states[i]),\n\t\t\t}));\n\t\t},\n\n\t\t// Validate an app-stored order id against the chain (stale after full\n\t\t// close or partial-close replacement — see RedeemReceipt.replacementOrderId).\n\t\thasPosition: (owner: string, marketId: string, orderId: bigint): Promise<boolean> =>\n\t\t\thasPosition(this.#client, this.#config, owner, marketId, orderId),\n\n\t\t// All open positions for an owner, enumerated from the chain (the\n\t\t// account's positions Table): 1 call per page warm, +2 resolution calls\n\t\t// once per owner. Returns [] for owners with no Predict account.\n\t\tpositions: async (owner: string): Promise<OpenPosition[]> => {\n\t\t\tlet handle = this.#positionsCache.get(owner);\n\t\t\tif (!handle?.positionsTableId) {\n\t\t\t\tconst resolved = await resolvePositionsTable(this.#client, this.#config, owner);\n\t\t\t\tif (!resolved) return []; // never onboarded — do not cache\n\t\t\t\tif (resolved.positionsTableId) this.#positionsCache.set(owner, resolved);\n\t\t\t\thandle = resolved;\n\t\t\t}\n\t\t\tif (!handle.positionsTableId) return [];\n\t\t\treturn positionsFromTable(this.#client, handle.positionsTableId);\n\t\t},\n\n\t\t// Anonymous board pricing: the chain's probability for both sides of a\n\t\t// strike, from one fresh pricer (no account needed). This is the ↑/↓\n\t\t// button price before a user has onboarded.\n\t\tprice: async (m: BinaryMarketCoordinates): Promise<{ up: number; down: number }> => {\n\t\t\tconst feeds = this.#feeds(m.underlying);\n\t\t\tconst { id, state } = await this.#resolveMarket(m);\n\t\t\tconst strikeRaw = await this.#strikeRawFor(m, id, state);\n\t\t\tconst { upRaw, downRaw } = await rangePrices(\n\t\t\t\tthis.#client,\n\t\t\t\tthis.#config,\n\t\t\t\tid,\n\t\t\t\tfeeds,\n\t\t\t\tstrikeRaw,\n\t\t\t\tstate.tickSizeRaw,\n\t\t\t);\n\t\t\treturn { up: rawToProbability(upRaw), down: rawToProbability(downRaw) };\n\t\t},\n\n\t\t// A client-side board pricer for one market: ONE simulate reads the chain's\n\t\t// resolved pricer (already forward-selected + rolled to now), then prices every\n\t\t// strike LOCALLY with no further chain calls — `pricer.up(strike)`,\n\t\t// `.down(strike)`, `.range(lo,hi)`, `.strikeAtProbability(p)`. Use this to paint a\n\t\t// whole board instantly; `read.price` / `read.quoteMint` stay the authoritative\n\t\t// per-strike quote at trade time. Throws the same typed stale-oracle/expired\n\t\t// PredictMoveError `read.price` would when the chain itself cannot quote.\n\t\tpricer: async (\n\t\t\tm: Pick<MarketDescriptor, 'underlying' | 'expiryMs'>,\n\t\t): Promise<BoardPricer & { asOf: PricerSnapshot['sources'] }> => {\n\t\t\tconst feeds = this.#feeds(m.underlying);\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst snap = await readPricerSnapshot(this.#client, this.#config, id, feeds);\n\t\t\treturn { ...boardPricer(snap), asOf: snap.sources };\n\t\t},\n\n\t\t/**\n\t\t * Exact pre-trade quote for an exact-quantity mint. Requires a funded account.\n\t\t *\n\t\t * Where the config records the delayed-execution upgrade (`packages.predictDelayedExecution`),\n\t\t * this reads Predict's own `quote_mint_for_account` (the immediate mint is retired there) and\n\t\t * the order desk's fee, and previews a QUEUED fill at the clock: `queued: true`, no\n\t\t * congestion penalty in `cost`, and the order fee in `orderFee`. The fill itself prices at\n\t\t * its committed Pyth tick. It throws `PredictInputError` when that config lacks the\n\t\t * order-flow package or its desk. Elsewhere it dry-runs the immediate mint and decodes its\n\t\t * receipt, as before.\n\t\t */\n\t\tquoteMint: async (\n\t\t\towner: string,\n\t\t\tm: MarketDescriptor,\n\t\t\topts: Pick<MintOptions, 'quantity'>,\n\t\t): Promise<MintQuote> => {\n\t\t\tif (this.cfg.packages.predictDelayedExecution) {\n\t\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\t\tconst feeds = this.#feeds(m.underlying);\n\t\t\t\tconst { id, state } = await this.#resolveMarket(m);\n\t\t\t\tconst quantityRaw = usdcToRaw(opts.quantity);\n\t\t\t\tthis.#assertLot(quantityRaw);\n\t\t\t\tconst { lowerTick, higherTick } = await this.#strikeTicks(m, id, state);\n\t\t\t\tconst { quote, policy } = await quoteMintForAccount(this.#client, this.#config, {\n\t\t\t\t\texpiryMarketId: id,\n\t\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\t\tlowerTick,\n\t\t\t\t\thigherTick,\n\t\t\t\t\trequest: { shape: 'exact-quantity', quantityRaw },\n\t\t\t\t\tordersConfig: orders,\n\t\t\t\t\t...feeds,\n\t\t\t\t});\n\t\t\t\treturn PredictClient.#queuedMintQuote(quote, policy);\n\t\t\t}\n\t\t\tconst tx = await this.#buildMint(owner, m, opts);\n\t\t\treturn this.#quoteMintTransaction(owner, tx);\n\t\t},\n\n\t\t/**\n\t\t * Quote the all-in budget mint against current account and market state. Where the config\n\t\t * records the delayed-execution upgrade, it reads `quote_mint_exact_cost_for_account` at\n\t\t * `min(spend, available − fee)`, the budget enqueue escrows, and previews a queued fill as\n\t\t * `quoteMint` does (and throws as it does on a partial config). Elsewhere it simulates the\n\t\t * immediate v2 mint.\n\t\t */\n\t\tquoteMintCost: async (\n\t\t\towner: string,\n\t\t\tm: MarketDescriptor,\n\t\t\topts: MintCostOptions,\n\t\t): Promise<MintQuote> => {\n\t\t\tif (this.cfg.packages.predictDelayedExecution) {\n\t\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\t\tconst feeds = this.#feeds(m.underlying);\n\t\t\t\tconst { id, state } = await this.#resolveMarket(m);\n\t\t\t\tconst { lowerTick, higherTick } = await this.#strikeTicks(m, id, state);\n\t\t\t\tconst { policy, availableRaw } = await orderFeeAndBalance(\n\t\t\t\t\tthis.#client,\n\t\t\t\t\torders,\n\t\t\t\t\towner,\n\t\t\t\t\tthis.cfg.quoteCoinType,\n\t\t\t\t);\n\t\t\t\tconst fee = policy.orderFee;\n\t\t\t\tconst spendRaw = usdcToRaw(opts.spend);\n\t\t\t\tconst escrowable = availableRaw > fee ? availableRaw - fee : 0n;\n\t\t\t\tconst { quote } = await quoteMintForAccount(this.#client, this.#config, {\n\t\t\t\t\texpiryMarketId: id,\n\t\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\t\tlowerTick,\n\t\t\t\t\thigherTick,\n\t\t\t\t\trequest: {\n\t\t\t\t\t\tshape: 'exact-cost',\n\t\t\t\t\t\tmaxCostRaw: spendRaw < escrowable ? spendRaw : escrowable,\n\t\t\t\t\t\tminQuantityRaw: usdcToRaw(opts.minQuantity),\n\t\t\t\t\t},\n\t\t\t\t\t...feeds,\n\t\t\t\t});\n\t\t\t\treturn PredictClient.#queuedMintQuote(quote, policy);\n\t\t\t}\n\t\t\treturn this.#quoteMintTransaction(owner, await this.#buildMintCost(owner, m, opts));\n\t\t},\n\n\t\t/**\n\t\t * Quote an early sell of an Open record (the queue's `quote_redeem_open`) at a fresh live\n\t\t * pricer. `proceeds` is before the order fee, with no congestion penalty, and `net` takes the\n\t\t * fee off. Throws `ERecordNotOpen` when the record isn't Open.\n\t\t */\n\t\tquoteSell: async (\n\t\t\towner: string,\n\t\t\tm: MarketCoordinates,\n\t\t\topts: { recordId: bigint; quantity: number },\n\t\t): Promise<SellQuote> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst feeds = this.#feeds(m.underlying);\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst closeQuantityRaw = usdcToRaw(opts.quantity);\n\t\t\tthis.#assertLot(closeQuantityRaw);\n\t\t\tconst queueId = await this.#existingQueueId(orders, id);\n\t\t\tconst { quote, policy } = await quoteRedeemOpen(this.#client, orders, {\n\t\t\t\texpiryMarketId: id,\n\t\t\t\tqueueId,\n\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\trecordId: opts.recordId,\n\t\t\t\tcloseQuantityRaw,\n\t\t\t\t...feeds,\n\t\t\t});\n\t\t\tconst orderFee = policy.orderFee;\n\t\t\treturn {\n\t\t\t\tprobability: rawToProbability(quote.probability),\n\t\t\t\tproceeds: rawToUsdc(quote.proceeds),\n\t\t\t\tnet: rawToUsdc(quote.proceeds - orderFee),\n\t\t\t\tfees: {\n\t\t\t\t\ttrading: rawToUsdc(quote.tradingFee),\n\t\t\t\t\tbuilder: rawToUsdc(quote.builderFee),\n\t\t\t\t\tinventoryImpactRebate: rawToUsdc(quote.inventoryImpactRebate),\n\t\t\t\t\torder: rawToUsdc(orderFee),\n\t\t\t\t},\n\t\t\t\tquantityClosed: rawToUsdc(quote.closeQuantity),\n\t\t\t\traw: {\n\t\t\t\t\tprobability: quote.probability,\n\t\t\t\t\tproceeds: quote.proceeds,\n\t\t\t\t\torderFee,\n\t\t\t\t\tquantityClosed: quote.closeQuantity,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\n\t\t/**\n\t\t * Which trade path the network is on, from `ProtocolConfig.version_watermark` and whether\n\t\t * this config records delayed execution (the Predict upgrade, the order-flow companion and\n\t\t * its desk). Flip the app between `mint*` and `enqueue*` on it, without a redeploy at the\n\t\t * watermark bump.\n\t\t */\n\t\texecutionMode: async (): Promise<ExecutionMode> =>\n\t\t\texecutionModeFor(\n\t\t\t\tawait versionWatermark(this.#client, this.cfg.objects.protocolConfig),\n\t\t\t\tthis.#recordsDelayedExecution(),\n\t\t\t\tthis.cfg.packages.predictDelayedExecution != null,\n\t\t\t\tthis.#predictCurrentVersion(),\n\t\t\t),\n\n\t\t/**\n\t\t * A market's queue in one read: cash, the stuck gate (\"pricing delayed\"), cohorts, counters\n\t\t * against capacity, the desk's policy, a τ/deadline/cutoff preview, and the largest mint\n\t\t * spare cash admits now. With `owner` (who must have an account), also the account's\n\t\t * waiting orders and balance. Throws `PredictPreflightError` `'no-queue'` while the market\n\t\t * has no `MarketQueue`.\n\t\t */\n\t\tqueue: async (m: MarketCoordinates, owner?: string): Promise<MarketQueueView> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst state = await this.#queueState(orders, id, { owner });\n\t\t\tconst nowMs = BigInt(Date.now());\n\t\t\tconst policy = state.desk.policy;\n\t\t\tconst mode = executionModeFor(\n\t\t\t\tstate.protocol.versionWatermark,\n\t\t\t\ttrue,\n\t\t\t\ttrue,\n\t\t\t\tthis.#predictCurrentVersion(),\n\t\t\t);\n\t\t\tconst timing = previewTiming({\n\t\t\t\tnowMs,\n\t\t\t\tpolicy,\n\t\t\t\theads: state.heads,\n\t\t\t\texpiryMs: state.expiryMs,\n\t\t\t\tnoTradeWindowMs: state.protocol.noTradeWindowMs,\n\t\t\t});\n\t\t\t// The builders' own gate, so the flags can never disagree with their preflight.\n\t\t\tconst refusalFor = (side: 'mint' | 'sell'): PredictPreflightCode | null => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.#assertQueueOpen(state, side, nowMs);\n\t\t\t\t\treturn null;\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (e instanceof PredictPreflightError) return e.code;\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst refusal = { mint: refusalFor('mint'), sell: refusalFor('sell') };\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tmode,\n\t\t\t\ttiming,\n\t\t\t\tacceptingMints: refusal.mint == null,\n\t\t\t\tacceptingSells: refusal.sell == null,\n\t\t\t\trefusal,\n\t\t\t\tmaxMint: {\n\t\t\t\t\texactQuantity: maxMintNow({\n\t\t\t\t\t\tshape: 'exact-quantity',\n\t\t\t\t\t\tspareCashRaw: state.spareCash,\n\t\t\t\t\t\tminEntryProbability: state.minEntryProbability,\n\t\t\t\t\t\tlotSize: BigInt(this.cfg.units.positionLotSize),\n\t\t\t\t\t\tasOfMs: nowMs,\n\t\t\t\t\t}),\n\t\t\t\t\tbudget: maxMintNow({\n\t\t\t\t\t\tshape: 'budget',\n\t\t\t\t\t\tspareCashRaw: state.spareCash,\n\t\t\t\t\t\tminEntryProbability: state.minEntryProbability,\n\t\t\t\t\t\tavailableRaw: state.account?.availableRaw,\n\t\t\t\t\t\torderFeeRaw: policy.orderFee,\n\t\t\t\t\t\tasOfMs: nowMs,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\n\t\t/**\n\t\t * Plan a queued mint for a purchase form: the quote at the current price, the payout and\n\t\t * multiple, the order fee read from the desk, the escrow and debit, the balance, the most\n\t\t * the market takes now, the timing and the queue gates, plus the enqueue options that carry\n\t\t * the slippage. `amount` plans an all-in spend (`enqueueMintCost`, refunded below the payout\n\t\t * floor), and `quantity` an exact payout (`enqueueMint`, capped by probability and cost).\n\t\t * Works for a visitor without an account: the quote then comes from `quote_mint`.\n\t\t *\n\t\t * `slippageCents` is cents per contract, never a percentage: a 10¢ limit fills while the\n\t\t * all-in price per contract stays within 10¢ of the quote's price without its fee subsidy.\n\t\t */\n\t\tplanMint: async (\n\t\t\towner: string,\n\t\t\tm: MarketDescriptor,\n\t\t\topts: PlanMintOptions,\n\t\t): Promise<MintPlan> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst feeds = this.#feeds(m.underlying);\n\t\t\tconst { id, state: market } = await this.#resolveMarket(m);\n\t\t\tconst { lowerTick, higherTick } = await this.#strikeTicks(m, id, market);\n\t\t\tconst hasAccount = await this.#hasAccount(owner);\n\t\t\tconst state = await this.#queueState(orders, id, hasAccount ? { owner } : {});\n\t\t\tconst nowMs = BigInt(Date.now());\n\t\t\tconst policy = state.desk.policy;\n\t\t\tconst fee = policy.orderFee;\n\t\t\tconst availableRaw = state.account?.availableRaw ?? null;\n\t\t\tconst lot = BigInt(this.cfg.units.positionLotSize);\n\t\t\tconst ticks = { expiryMarketId: id, lowerTick, higherTick, ...feeds };\n\t\t\tconst forAccount = (request: MintQuoteRequest) =>\n\t\t\t\tquoteMintForAccount(this.#client, this.#config, {\n\t\t\t\t\t...ticks,\n\t\t\t\t\twrapperId: this.wrapperIdFor(owner),\n\t\t\t\t\trequest,\n\t\t\t\t}).then((r) => r.quote);\n\n\t\t\tlet quote: MintQuoteRaw;\n\t\t\tlet quoteForAccount: boolean;\n\t\t\tlet budgetRequested: bigint | null = null;\n\t\t\tif ('amount' in opts) {\n\t\t\t\tconst amountRaw = usdcToRaw(opts.amount);\n\t\t\t\tbudgetRequested =\n\t\t\t\t\t(opts.orderFee ?? 'inclusive') === 'inclusive'\n\t\t\t\t\t\t? amountRaw > fee\n\t\t\t\t\t\t\t? amountRaw - fee\n\t\t\t\t\t\t\t: 0n\n\t\t\t\t\t\t: amountRaw;\n\t\t\t\t// No budget below the minimum premium can be admitted, and the account's quote\n\t\t\t\t// aborts `EOrderFailsLimits` on one, so refuse it as a visitor's search does. An\n\t\t\t\t// amount the order fee takes whole buys nothing either.\n\t\t\t\tif (budgetRequested === 0n) {\n\t\t\t\t\tthrow new PredictPreflightError(\n\t\t\t\t\t\t'min-premium',\n\t\t\t\t\t\t`${opts.amount} doesn't cover the ${rawToUsdc(fee)} order fee, so it buys no premium`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (budgetRequested < MIN_PREMIUM) {\n\t\t\t\t\tthrow new PredictPreflightError(\n\t\t\t\t\t\t'min-premium',\n\t\t\t\t\t\t`a budget of ${rawToUsdc(budgetRequested)} is below the minimum premium (a mint's premium must be at least ${rawToUsdc(MIN_PREMIUM)} USDC)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// The account's own quote caps the budget at its balance, so it only previews an\n\t\t\t\t// order the balance covers.\n\t\t\t\tquoteForAccount =\n\t\t\t\t\tavailableRaw != null && availableRaw > fee && availableRaw - fee >= budgetRequested;\n\t\t\t\tconst budget = budgetRequested;\n\t\t\t\tconst search = () =>\n\t\t\t\t\tthis.#searchBudgetQuote(ticks, budget, lot).catch(async (error: unknown) => {\n\t\t\t\t\t\t// Every probe refused ends the search in 'min-premium', which a strike outside\n\t\t\t\t\t\t// the entry band also explains.\n\t\t\t\t\t\tif (error instanceof PredictPreflightError && error.code === 'min-premium') {\n\t\t\t\t\t\t\tthrow (await this.#entryBandRefusal(m)) ?? error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow await this.#quoteRefusal(error, { m });\n\t\t\t\t\t});\n\t\t\t\tif (quoteForAccount) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tquote = await forAccount({\n\t\t\t\t\t\t\tshape: 'exact-cost',\n\t\t\t\t\t\t\tmaxCostRaw: budget,\n\t\t\t\t\t\t\tminQuantityRaw: 0n,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!isOrderFailsLimits(error)) throw await this.#quoteRefusal(error);\n\t\t\t\t\t\t// The chain refused the budget at the account's own pricing, its builder fee\n\t\t\t\t\t\t// included. The account-free search only diagnoses the refusal: a strike outside\n\t\t\t\t\t\t// the entry band, or a budget too small for the minimum premium, throws its typed\n\t\t\t\t\t\t// refusal. It leaves the builder fee out, so a budget only it can size is never\n\t\t\t\t\t\t// planned, and keeps the chain's own error. (Near $1 a contract, admission's\n\t\t\t\t\t\t// payout-bound step-down isn't monotone, so a slightly smaller budget can pass\n\t\t\t\t\t\t// where this one is refused. That is a false refusal, never a bad order.)\n\t\t\t\t\t\tawait search();\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tquote = await search();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst quantityRaw = usdcToRaw(opts.quantity);\n\t\t\t\tthis.#assertLot(quantityRaw);\n\t\t\t\tquoteForAccount = hasAccount;\n\t\t\t\ttry {\n\t\t\t\t\tquote = hasAccount\n\t\t\t\t\t\t? await forAccount({ shape: 'exact-quantity', quantityRaw })\n\t\t\t\t\t\t: (\n\t\t\t\t\t\t\t\tawait quoteMintAnonymous(this.#client, this.#config, {\n\t\t\t\t\t\t\t\t\t...ticks,\n\t\t\t\t\t\t\t\t\trequest: { shape: 'exact-quantity', quantityRaw },\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t).quote;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow await this.#quoteRefusal(error, { m, quantityRaw });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// The expected cost, after the fee subsidy. The limits add the subsidy back, because\n\t\t\t// admission checks the order without it (`EOrderFailsLimits`).\n\t\t\tconst costRaw = quote.allInCost - quote.penaltyFee;\n\t\t\tconst slippage = PredictClient.#appliedSlippage(opts, quote.entryProbability, state, nowMs);\n\t\t\tconst limitsIn = {\n\t\t\t\tquoteCostRaw: costRaw,\n\t\t\t\tquoteQuantityRaw: quote.quantity,\n\t\t\t\tentryProbabilityRaw: quote.entryProbability,\n\t\t\t\tslippageRaw: slippage.raw,\n\t\t\t\tfeeIncentiveSubsidyRaw: quote.feeIncentiveSubsidy,\n\t\t\t\tlotSize: lot,\n\t\t\t};\n\t\t\tlet budgetRaw: bigint;\n\t\t\tlet minQuantityRaw: bigint;\n\t\t\t// What admission buys at least, for a budget plan, or why it buys nothing the plan can\n\t\t\t// preview.\n\t\t\tlet admitted:\n\t\t\t\t| { quantity: bigint }\n\t\t\t\t| { refusal: 'min-premium' | 'cost-above-payout' | 'entry-band' }\n\t\t\t\t| null = null;\n\t\t\tlet maxCostRaw: bigint | null = null;\n\t\t\tlet maxProbabilityRaw: bigint | null = null;\n\t\t\tlet price: { nowRaw: bigint; worstRaw: bigint };\n\t\t\tlet order: MintPlan['order'];\n\t\t\tif (budgetRequested != null) {\n\t\t\t\tconst limits = budgetMintLimits({ ...limitsIn, budgetRaw: budgetRequested });\n\t\t\t\tbudgetRaw = budgetRequested;\n\t\t\t\t// Admission sizes the fill without the subsidy by Move's exact arithmetic, whose\n\t\t\t\t// per-component rounding (inventory impact included) an average price can't bound.\n\t\t\t\t// So the floor's ceiling is checked with exact quotes. It also never exceeds the\n\t\t\t\t// quote's own quantity, since a searched quote can leave part of the budget unspent.\n\t\t\t\t// The first probe divides the budget by the quote's unsubsidized price, with no rounding\n\t\t\t\t// allowance, so a minimum-sized purchase isn't probed one lot short.\n\t\t\t\tconst unsubsidizedCost = costRaw + quote.feeIncentiveSubsidy;\n\t\t\t\tconst start =\n\t\t\t\t\tunsubsidizedCost === 0n\n\t\t\t\t\t\t? quote.quantity\n\t\t\t\t\t\t: ((budgetRaw * quote.quantity) / unsubsidizedCost / lot) * lot;\n\t\t\t\tadmitted = await this.#admittedFloor(\n\t\t\t\t\t(quantityRaw) =>\n\t\t\t\t\t\tquoteForAccount\n\t\t\t\t\t\t\t? forAccount({ shape: 'exact-quantity', quantityRaw })\n\t\t\t\t\t\t\t: quoteMintAnonymous(this.#client, this.#config, {\n\t\t\t\t\t\t\t\t\t...ticks,\n\t\t\t\t\t\t\t\t\trequest: { shape: 'exact-quantity', quantityRaw },\n\t\t\t\t\t\t\t\t}).then((r) => r.quote),\n\t\t\t\t\tbudgetRaw,\n\t\t\t\t\tstart < quote.quantity ? start : quote.quantity,\n\t\t\t\t\tlot,\n\t\t\t\t\tquote.entryProbability,\n\t\t\t\t\tquote.quantity === 0n ? 0n : (unsubsidizedCost * 1_000_000_000n) / quote.quantity,\n\t\t\t\t);\n\t\t\t\tconst ceiling = 'quantity' in admitted ? admitted.quantity : 0n;\n\t\t\t\tminQuantityRaw = limits.minQuantityRaw < ceiling ? limits.minQuantityRaw : ceiling;\n\t\t\t\tprice = limits.pricePerContract;\n\t\t\t\torder = {\n\t\t\t\t\tbuilder: 'enqueueMintCost',\n\t\t\t\t\toptions: { spend: rawToUsdc(budgetRaw), minQuantity: rawToUsdc(minQuantityRaw) },\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tconst limits = exactMintLimits(limitsIn);\n\t\t\t\tmaxCostRaw = limits.maxCostRaw;\n\t\t\t\tmaxProbabilityRaw = limits.maxProbabilityRaw;\n\t\t\t\t// Enqueue escrows `min(max_cost, quantity, available − fee)`.\n\t\t\t\tbudgetRaw = maxCostRaw < quote.quantity ? maxCostRaw : quote.quantity;\n\t\t\t\tminQuantityRaw = quote.quantity;\n\t\t\t\tprice = limits.pricePerContract;\n\t\t\t\torder = {\n\t\t\t\t\tbuilder: 'enqueueMint',\n\t\t\t\t\toptions: {\n\t\t\t\t\t\tquantity: rawToUsdc(quote.quantity),\n\t\t\t\t\t\tmaxCost: rawToUsdc(maxCostRaw),\n\t\t\t\t\t\tmaxProbability: rawToProbability(maxProbabilityRaw),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst totalDebitRaw = budgetRaw + fee;\n\t\t\tconst expectedDebitRaw = costRaw + fee;\n\t\t\tconst inclusive = 'amount' in opts && (opts.orderFee ?? 'inclusive') === 'inclusive';\n\t\t\t// The builder's own preflight on the plan's order, plus what only the quote shows: the\n\t\t\t// balance against the whole debit the limits assume, the payout bound, and the premium a\n\t\t\t// budget buys at admission, which prices without the fee subsidy.\n\t\t\tconst refusal = PredictClient.#refusal(() => {\n\t\t\t\tthis.#assertQueueOpen(state, 'mint', nowMs);\n\t\t\t\tif (availableRaw == null || availableRaw < totalDebitRaw) {\n\t\t\t\t\tthrow new PredictPreflightError(\n\t\t\t\t\t\t'fee',\n\t\t\t\t\t\t`the balance doesn't cover the plan's ${rawToUsdc(totalDebitRaw)} debit`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tPredictClient.#assertMintOrder(\n\t\t\t\t\tstate,\n\t\t\t\t\tpolicy,\n\t\t\t\t\tbudgetRequested != null\n\t\t\t\t\t\t? { kind: ORDER_KIND.EXACT_COST, maxCostRaw: budgetRaw }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tkind: ORDER_KIND.EXACT_QUANTITY,\n\t\t\t\t\t\t\t\tmaxCostRaw: maxCostRaw ?? budgetRaw,\n\t\t\t\t\t\t\t\tquantityRaw: quote.quantity,\n\t\t\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (costRaw + quote.feeIncentiveSubsidy > quote.quantity) {\n\t\t\t\t\tthrow new PredictPreflightError(\n\t\t\t\t\t\t'cost-above-payout',\n\t\t\t\t\t\t'the all-in cost without the fee subsidy is above the payout',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (admitted != null && 'refusal' in admitted) {\n\t\t\t\t\tthrow new PredictPreflightError(\n\t\t\t\t\t\tadmitted.refusal,\n\t\t\t\t\t\tadmitted.refusal === 'min-premium'\n\t\t\t\t\t\t\t? `without the fee subsidy, ${rawToUsdc(budgetRaw)} buys no fill that clears the ${rawToUsdc(MIN_PREMIUM)} minimum premium`\n\t\t\t\t\t\t\t: admitted.refusal === 'entry-band'\n\t\t\t\t\t\t\t\t? \"the entry probability left the market's entry band while the order was sized: plan again, or pick a strike nearer the money\"\n\t\t\t\t\t\t\t\t: `without the fee subsidy, ${rawToUsdc(budgetRaw)} buys a fill near $1 a contract, whose admission sizing can't be previewed`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst cashOrBudgetMax = maxMintNow(\n\t\t\t\tbudgetRequested != null\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tshape: 'budget',\n\t\t\t\t\t\t\tspareCashRaw: state.spareCash,\n\t\t\t\t\t\t\tminEntryProbability: state.minEntryProbability,\n\t\t\t\t\t\t\tavailableRaw: availableRaw ?? undefined,\n\t\t\t\t\t\t\torderFeeRaw: fee,\n\t\t\t\t\t\t\tasOfMs: nowMs,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tshape: 'exact-quantity',\n\t\t\t\t\t\t\tspareCashRaw: state.spareCash,\n\t\t\t\t\t\t\tminEntryProbability: state.minEntryProbability,\n\t\t\t\t\t\t\tlotSize: lot,\n\t\t\t\t\t\t\tasOfMs: nowMs,\n\t\t\t\t\t\t},\n\t\t\t).maxRaw;\n\t\t\t// `maxMintNow` bounds an exact quantity by spare cash only. Enqueue escrows the quantity\n\t\t\t// at the plan's worst price per contract, capped at the $1 payout, so the balance bounds\n\t\t\t// it too.\n\t\t\tlet max = cashOrBudgetMax;\n\t\t\tif (budgetRequested == null && availableRaw != null && price.worstRaw > 0n) {\n\t\t\t\tconst spendable = availableRaw > fee ? availableRaw - fee : 0n;\n\t\t\t\tconst perContract = price.worstRaw < 1_000_000_000n ? price.worstRaw : 1_000_000_000n;\n\t\t\t\tconst byBalance = ((spendable * 1_000_000_000n) / perContract / lot) * lot;\n\t\t\t\tif (max == null || byBalance < max) max = byBalance;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tshape: budgetRequested != null ? 'budget' : 'exact-quantity',\n\t\t\t\ttarget: { owner: normalizeSuiAddress(owner), expiryMarketId: id, lowerTick, higherTick },\n\t\t\t\tquote: PredictClient.#queuedMintQuote(quote, policy),\n\t\t\t\tquoteForAccount,\n\t\t\t\tslippage: slippage.applied,\n\t\t\t\tpotentialPayout: rawToUsdc(quote.quantity),\n\t\t\t\tminPayout: rawToUsdc(minQuantityRaw),\n\t\t\t\tpayoutMultiple: Number(quote.quantity) / Number(expectedDebitRaw),\n\t\t\t\tminPayoutMultiple: Number(minQuantityRaw) / Number(totalDebitRaw),\n\t\t\t\tpricePerContract: rawToProbability(price.nowRaw),\n\t\t\t\tworstPricePerContract: rawToProbability(price.worstRaw),\n\t\t\t\torderFee: rawToUsdc(fee),\n\t\t\t\tbudget: rawToUsdc(budgetRaw),\n\t\t\t\ttotalDebit: rawToUsdc(totalDebitRaw),\n\t\t\t\texpectedDebit: rawToUsdc(expectedDebitRaw),\n\t\t\t\tbalance: {\n\t\t\t\t\thasAccount,\n\t\t\t\t\tavailable: availableRaw == null ? null : rawToUsdc(availableRaw),\n\t\t\t\t\tcovers: availableRaw == null ? null : availableRaw >= totalDebitRaw,\n\t\t\t\t},\n\t\t\t\tmaxNow: max == null ? null : rawToUsdc(inclusive ? max + fee : max),\n\t\t\t\ttiming: previewTiming({\n\t\t\t\t\tnowMs,\n\t\t\t\t\tpolicy,\n\t\t\t\t\theads: state.heads,\n\t\t\t\t\texpiryMs: state.expiryMs,\n\t\t\t\t\tnoTradeWindowMs: state.protocol.noTradeWindowMs,\n\t\t\t\t}),\n\t\t\t\taccepting: refusal == null,\n\t\t\t\trefusal,\n\t\t\t\torder,\n\t\t\t\traw: {\n\t\t\t\t\tbudget: budgetRaw,\n\t\t\t\t\torderFee: fee,\n\t\t\t\t\ttotalDebit: totalDebitRaw,\n\t\t\t\t\tslippage: slippage.raw,\n\t\t\t\t\tminQuantity: minQuantityRaw,\n\t\t\t\t\tmaxCost: maxCostRaw,\n\t\t\t\t\tmaxProbability: maxProbabilityRaw,\n\t\t\t\t\tpricePerContract: price.nowRaw,\n\t\t\t\t\tworstPricePerContract: price.worstRaw,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\n\t\t/**\n\t\t * Plan a queued early sell of an Open record: the quote at the current price, net of the\n\t\t * order fee, the floors at the worst price the slippage allows, the timing and the\n\t\t * builder's preflight, plus the `enqueueSell` options that carry the floors. A record that\n\t\t * isn't Open has no quote, so it throws `PredictPreflightError` `'record-not-open'` instead.\n\t\t */\n\t\tplanSell: async (\n\t\t\towner: string,\n\t\t\tm: MarketCoordinates,\n\t\t\topts: PlanSellOptions,\n\t\t): Promise<SellPlan> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst state = await this.#queueState(orders, id, { owner, recordIds: [opts.recordId] });\n\t\t\t// No quote exists for a record that isn't Open, or for more than it holds, so those\n\t\t\t// refusals throw.\n\t\t\tconst record = PredictClient.#assertRecordOpen(state, opts.recordId);\n\t\t\tthis.#assertSellQuantity(record, usdcToRaw(opts.quantity));\n\t\t\tconst quote = await this.read\n\t\t\t\t.quoteSell(owner, m, { recordId: opts.recordId, quantity: opts.quantity })\n\t\t\t\t.catch(async (error: unknown) => {\n\t\t\t\t\tthrow await this.#quoteRefusal(error);\n\t\t\t\t});\n\t\t\tconst nowMs = BigInt(Date.now());\n\t\t\tconst slippage = PredictClient.#appliedSlippage(opts, quote.raw.probability, state, nowMs);\n\t\t\tconst limits = sellLimits({\n\t\t\t\tproceedsRaw: quote.raw.proceeds,\n\t\t\t\tcloseQuantityRaw: quote.raw.quantityClosed,\n\t\t\t\tprobabilityRaw: quote.raw.probability,\n\t\t\t\tslippageRaw: slippage.raw,\n\t\t\t});\n\t\t\tconst fee = quote.raw.orderFee;\n\t\t\t// The builder's own preflight on the sell.\n\t\t\tconst refusal = PredictClient.#refusal(() => {\n\t\t\t\tconst { policy } = this.#assertQueueOpen(state, 'sell', nowMs);\n\t\t\t\tthis.#assertSellOrder(state, policy, opts.recordId, usdcToRaw(opts.quantity));\n\t\t\t});\n\t\t\treturn {\n\t\t\t\ttarget: { owner: normalizeSuiAddress(owner), expiryMarketId: id, recordId: opts.recordId },\n\t\t\t\tquote,\n\t\t\t\tslippage: slippage.applied,\n\t\t\t\tproceeds: quote.proceeds,\n\t\t\t\tnet: quote.net,\n\t\t\t\tminProceeds: rawToUsdc(limits.minProceedsRaw),\n\t\t\t\tminNet: rawToUsdc(limits.minProceedsRaw - fee),\n\t\t\t\torderFee: rawToUsdc(fee),\n\t\t\t\ttiming: previewTiming({\n\t\t\t\t\tnowMs,\n\t\t\t\t\tpolicy: state.desk.policy,\n\t\t\t\t\theads: state.heads,\n\t\t\t\t\texpiryMs: state.expiryMs,\n\t\t\t\t\tnoTradeWindowMs: state.protocol.noTradeWindowMs,\n\t\t\t\t}),\n\t\t\t\taccepting: refusal == null,\n\t\t\t\trefusal,\n\t\t\t\torder: {\n\t\t\t\t\tbuilder: 'enqueueSell',\n\t\t\t\t\toptions: {\n\t\t\t\t\t\trecordId: opts.recordId,\n\t\t\t\t\t\tquantity: opts.quantity,\n\t\t\t\t\t\tminProbability: rawToProbability(limits.minProbabilityRaw),\n\t\t\t\t\t\tminProceeds: rawToUsdc(limits.minProceedsRaw),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\traw: {\n\t\t\t\t\tslippage: slippage.raw,\n\t\t\t\t\tminProceeds: limits.minProceedsRaw,\n\t\t\t\t\tminProbability: limits.minProbabilityRaw,\n\t\t\t\t\torderFee: fee,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\n\t\t/** One queue record and its display state, or null when missing or cleaned up. */\n\t\torder: async (m: MarketCoordinates, recordId: bigint): Promise<QueuedOrderView | null> =>\n\t\t\t(await this.read.orders(m, [recordId]))[0],\n\n\t\t/**\n\t\t * Queue records by record ID, with their display states. The SDK has no indexer: the app\n\t\t * supplies record IDs from its enqueue receipts or its indexer.\n\t\t */\n\t\torders: async (\n\t\t\tm: MarketCoordinates,\n\t\t\trecordIds: readonly bigint[],\n\t\t): Promise<(QueuedOrderView | null)[]> => {\n\t\t\tconst orders = this.#requireDelayedExecution();\n\t\t\tconst { id } = await this.#resolveMarket(m);\n\t\t\tconst queueId = await this.#existingQueueId(orders, id);\n\t\t\tconst records = await queuedOrders(\n\t\t\t\tthis.#client,\n\t\t\t\torders,\n\t\t\t\t{ expiryMarketId: id, queueId },\n\t\t\t\trecordIds,\n\t\t\t);\n\t\t\tconst nowMs = BigInt(Date.now());\n\t\t\treturn records.map((record, i) =>\n\t\t\t\trecord\n\t\t\t\t\t? {\n\t\t\t\t\t\t\trecordId: recordIds[i],\n\t\t\t\t\t\t\trecord,\n\t\t\t\t\t\t\tview: orderView(record, nowMs, {\n\t\t\t\t\t\t\t\tlotSize: BigInt(this.cfg.units.positionLotSize),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t);\n\t\t},\n\n\t\t/**\n\t\t * Poll a record until it is filled, refunded or closed (`pollMs`, default 250), or until\n\t\t * `timeoutMs` (default 30 s). The fullnode a client reads can trail the enqueue's\n\t\t * execution, so a record not seen yet is polled again until the timeout, and ends as\n\t\t * `'gone'` only then. A record that disappears after it was seen ends as `'gone'` at once.\n\t\t * The record's result is enough for the UI; the fee breakdown is in the\n\t\t * `QueuedOrderFilled` event.\n\t\t */\n\t\twaitForOutcome: async (\n\t\t\tm: MarketCoordinates,\n\t\t\trecordId: bigint,\n\t\t\topts: { pollMs?: number; timeoutMs?: number; signal?: AbortSignal } = {},\n\t\t): Promise<QueuedOrderOutcome> => {\n\t\t\tconst pollMs = opts.pollMs ?? 250;\n\t\t\tconst deadline = Date.now() + (opts.timeoutMs ?? 30_000);\n\t\t\tlet seen = false;\n\t\t\tfor (;;) {\n\t\t\t\tconst order = await this.read.order(m, recordId);\n\t\t\t\tconst timedOut = Date.now() + pollMs > deadline;\n\t\t\t\tif (!order) {\n\t\t\t\t\tif (seen || timedOut) return { outcome: 'gone', order: null };\n\t\t\t\t} else {\n\t\t\t\t\tseen = true;\n\t\t\t\t\tconst state = order.view.state;\n\t\t\t\t\tif (state === 'filled' || state === 'refunded' || state === 'closed') {\n\t\t\t\t\t\treturn { outcome: state, order };\n\t\t\t\t\t}\n\t\t\t\t\tif (timedOut) return { outcome: 'timeout', order };\n\t\t\t\t}\n\t\t\t\tawait sleep(pollMs, opts.signal);\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * USDC sent to the owner's account wrapper that the account hasn't settled yet: refunds,\n\t\t * sell proceeds and settled payouts of Open records. Already counted in `read.balance`; for\n\t\t * display.\n\t\t */\n\t\tpendingFunds: async (owner: string): Promise<number> =>\n\t\t\trawToUsdc(await pendingFunds(this.#client, this.wrapperIdFor(owner), this.cfg.quoteCoinType)),\n\n\t\t/** The current Pyth Lazer package, for a filler. Read it per batch and never cache it. */\n\t\tlazerPackages: (stateId?: string): Promise<LazerPackages> => {\n\t\t\tconst id = stateId ?? this.cfg.oracle?.pythLazerState;\n\t\t\tif (!id) throw new PredictInputError('pass the Pyth Lazer State id');\n\t\t\treturn lazerPackages(this.#client, id);\n\t\t},\n\n\t\t/**\n\t\t * Exact pre-close quote for an ACCOUNT position: dry-runs the immediate redeem and decodes\n\t\t * the receipt.\n\t\t * @deprecated `redeem_live` is retired by delayed execution (DBU-885): Predict v4 always\n\t\t * aborts it. Queued fills are Open records: quote them with `read.quoteSell`.\n\t\t */\n\t\tquoteRedeem: async (\n\t\t\towner: string,\n\t\t\tm: MarketDescriptor,\n\t\t\topts: CloseOptions,\n\t\t): Promise<RedeemQuote> => {\n\t\t\tconst tx = await this.#buildRedeem(owner, m, opts);\n\t\t\tconst events = await simulateWithEvents(this.#client, tx, owner);\n\t\t\tconst r = exactlyOne(decodeRedeems(this.cfg, { events }), 'order-redeemed');\n\t\t\treturn {\n\t\t\t\tproceeds: r.proceeds,\n\t\t\t\tgross: r.gross,\n\t\t\t\tfees: r.fees,\n\t\t\t\tquantityClosed: r.quantityClosed,\n\t\t\t\tremaining: r.remaining,\n\t\t\t\traw: {\n\t\t\t\t\tproceeds: r.raw.proceeds,\n\t\t\t\t\tgross: r.raw.gross,\n\t\t\t\t\tquantityClosed: r.raw.quantityClosed,\n\t\t\t\t},\n\t\t\t\tfeesExact: true,\n\t\t\t};\n\t\t},\n\n\t\tmarket: async (\n\t\t\tm: Pick<MarketDescriptor, 'underlying' | 'expiryMs'>,\n\t\t): Promise<MarketSummary | null> => {\n\t\t\tconst expiryMs = BigInt(m.expiryMs);\n\t\t\t// Deliberately re-queries and overwrites the cache instead of reading\n\t\t\t// through it: this read must return live state (nav, mintPaused), and\n\t\t\t// refreshing the cache on the way keeps later tx builds consistent.\n\t\t\tconst u = this.#underlying(m.underlying);\n\t\t\tconst id = await expiryMarketId(this.#client, this.#config, u, expiryMs);\n\t\t\tif (!id) return null;\n\t\t\tconst state = await marketState(this.#client, this.#config, id);\n\t\t\tthis.#marketCache.set(`${m.underlying}:${expiryMs}`, { id, state });\n\t\t\tconst navRaw = await currentNav(this.#client, this.#config, id, u);\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\texpiryMs: state.expiryMs,\n\t\t\t\ttickSize: fromRaw(state.tickSizeRaw, 9), // strike/price scale\n\t\t\t\tadmissionTickSize: fromRaw(state.admissionTickSizeRaw, 9),\n\t\t\t\tmintPaused: state.mintPaused,\n\t\t\t\tnav: rawToUsdc(navRaw),\n\t\t\t\treferencePrice: PredictClient.#referencePriceOf(state),\n\t\t\t};\n\t\t},\n\n\t\t/**\n\t\t * The market's settlement price, or `null` until a keeper settles it. Unlike `market`,\n\t\t * `price` and the quotes, which abort `ELivePricingExpired` once the market expires, it\n\t\t * keeps working after expiry, when an app shows results. With delayed execution the\n\t\t * keeper settles a market, pays its Open records and cleans them up within about a second\n\t\t * of expiry, so `read.order` returns `null` by then. Keep each filled record's\n\t\t * `position.orderId` and pass it to `cost.settledPayout` with this price.\n\t\t */\n\t\tsettlement: async (m: MarketCoordinates): Promise<MarketSettlement> => {\n\t\t\tconst { id, state } = await this.#resolveMarket(m);\n\t\t\tconst raw = await settlementPrice(this.#client, this.#config, id);\n\t\t\treturn {\n\t\t\t\tmarketId: id,\n\t\t\t\texpiryMs: state.expiryMs,\n\t\t\t\tsettled: raw != null,\n\t\t\t\tsettlementPrice: raw == null ? null : fromRaw(raw, 9),\n\t\t\t\tsettlementPriceRaw: raw,\n\t\t\t\ttickSizeRaw: state.tickSizeRaw,\n\t\t\t};\n\t\t},\n\n\t\t/**\n\t\t * The fee and exposure policy the market snapshotted at creation, ready to pass to the\n\t\t * `cost` functions as `fees`. A market keeps it for its whole life, so it can differ from\n\t\t * the protocol's current template, and neither recorded deployment's template matches\n\t\t * `cost.SHIPPED_FEE_POLICY` any more. One object read.\n\t\t */\n\t\tfeePolicy: async (m: MarketCoordinates): Promise<FeePolicy> =>\n\t\t\tmarketFeePolicy(this.#client, (await this.#resolveMarket(m)).id),\n\n\t\tbalance: async (owner: string): Promise<number> =>\n\t\t\trawToUsdc(await accountBalance(this.#client, this.#config, owner, this.cfg.quoteCoinType)),\n\n\t\t// PLP shares held in the owner's account custody (raw u64, 6-decimal PLP coin).\n\t\tplpBalance: (owner: string): Promise<bigint> =>\n\t\t\taccountBalance(this.#client, this.#config, owner, this.cfg.coinTypes.plp),\n\n\t\tpool: async (): Promise<PoolSummary> => {\n\t\t\tconst s = await poolStats(this.#client, this.#config);\n\t\t\treturn {\n\t\t\t\tplpTotalSupply: s.plpTotalSupply, // shares raw (6-decimal)\n\t\t\t\tidleUsdc: rawToUsdc(s.idleBalance),\n\t\t\t\t// These are queue LENGTHS (counts of pending requests), not token amounts.\n\t\t\t\tsupplyRequestsPending: Number(s.supplyRequestsPending),\n\t\t\t\twithdrawRequestsPending: Number(s.withdrawRequestsPending),\n\t\t\t};\n\t\t},\n\t};\n\n\t// === execution-result decoders ===\n\t// Pure event parsing (no network): pass the executed/simulated transaction\n\t// result (with events included) and get a typed receipt back. Singular forms\n\t// throw unless exactly one matching event exists; plural forms return all\n\t// (an integrator batching N actions in one PTB gets N receipts).\n\treadonly decode = {\n\t\tmint: (r: DecodableTransactionResult) => exactlyOne(decodeMints(this.cfg, r), 'OrderMinted'),\n\t\tmints: (r: DecodableTransactionResult) => decodeMints(this.cfg, r),\n\t\tredeem: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodeRedeems(this.cfg, r), 'order-redeemed'),\n\t\tredeems: (r: DecodableTransactionResult) => decodeRedeems(this.cfg, r),\n\t\tclaim: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodeClaims(this.cfg, r), 'SettledOrderRedeemed'),\n\t\tclaims: (r: DecodableTransactionResult) => decodeClaims(this.cfg, r),\n\t\tcreateManager: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodeAccountsCreated(this.cfg, r), 'AccountCreated'),\n\t\tdeposit: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodeDeposits(this.cfg, r), 'Deposited'),\n\t\twithdraw: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodeWithdrawals(this.cfg, r), 'Withdrawn'),\n\t\tplpRequest: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodePlpRequests(this.cfg, r), 'supply/withdraw-requested'),\n\t\tplpCancel: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodePlpCancels(this.cfg, r), 'RequestCancelled'),\n\t\tbuilderCode: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodeBuilderCodeSets(this.cfg, r), 'BuilderCodeSet'),\n\n\t\t// --- delayed execution (DBU-885) --- the queue events are matched against the order-flow\n\t\t// companion's original ID (`packages.predictOrdersV1 ?? predictOrders`), the Predict events\n\t\t// the upgrade added against `packages.predictDelayedExecution`. Each throws\n\t\t// PredictInputError while the config doesn't record the package it needs.\n\n\t\t/** The trader's `OrderEnqueued` receipt: the record ID, τ, deadline, escrow and fee. */\n\t\tenqueue: (r: DecodableTransactionResult) =>\n\t\t\texactlyOne(decodeEnqueues(this.cfg, r), 'OrderEnqueued'),\n\t\tenqueues: (r: DecodableTransactionResult) => decodeEnqueues(this.cfg, r),\n\t\t/** Every queue event, tagged, in chain order: feed it to `queue.reduceOrderEvents`. */\n\t\tqueueEvents: (r: DecodableTransactionResult) => decodeQueueEvents(this.cfg, r),\n\t\tcohortCommits: (r: DecodableTransactionResult) => decodeCohortCommits(this.cfg, r),\n\t\tqueuedFills: (r: DecodableTransactionResult) => decodeQueuedFills(this.cfg, r),\n\t\tqueuedRefunds: (r: DecodableTransactionResult) => decodeQueuedRefunds(this.cfg, r),\n\t\topenRecordPayouts: (r: DecodableTransactionResult) => decodeOpenRecordPayouts(this.cfg, r),\n\t\tmarketPayoutsCompleted: (r: DecodableTransactionResult) =>\n\t\t\tdecodeMarketPayoutsCompleted(this.cfg, r),\n\t\tqueueOps: (r: DecodableTransactionResult) => decodeQueueOps(this.cfg, r),\n\t\t/** `RecordFundsParked` and `RecordFundsClaimed`: USDC a record keeps until it can be sent. */\n\t\trecordFunds: (r: DecodableTransactionResult) => decodeRecordFunds(this.cfg, r),\n\t\tpolicyUpdates: (r: DecodableTransactionResult) => decodePolicyUpdates(this.cfg, r),\n\t\t/**\n\t\t * `ExpiryPnlRealized` changes in the pool's gross realized result, for P&L reporting. Sum\n\t\t * them with `realizedPnlRaw`.\n\t\t */\n\t\texpiryPnlRealized: (r: DecodableTransactionResult) => decodeExpiryPnlRealized(this.cfg, r),\n\t};\n}\n\n// Resolve after `ms`, or reject with the signal's reason once it aborts.\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(signal.reason);\n\t\t\treturn;\n\t\t}\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(signal?.reason);\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener('abort', on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