@mysten/deepbook-v3 2.9.2 → 2.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/README.md +21 -0
- package/dist/account-bindings/account-registry.d.mts +109 -0
- package/dist/account-bindings/account-registry.d.mts.map +1 -0
- package/dist/account-bindings/account-registry.mjs +56 -0
- package/dist/account-bindings/account-registry.mjs.map +1 -0
- package/dist/account-bindings/account.d.mts +176 -0
- package/dist/account-bindings/account.d.mts.map +1 -0
- package/dist/account-bindings/account.mjs +94 -0
- package/dist/account-bindings/account.mjs.map +1 -0
- package/dist/account-bindings/latest.d.mts +12 -0
- package/dist/account-bindings/latest.d.mts.map +1 -0
- package/dist/account-bindings/latest.mjs +19 -0
- package/dist/account-bindings/latest.mjs.map +1 -0
- package/dist/account.d.mts +46 -3
- package/dist/account.d.mts.map +1 -1
- package/dist/account.mjs +51 -2
- package/dist/account.mjs.map +1 -1
- package/dist/contracts/account/account.d.mts +25 -97
- package/dist/contracts/account/account.d.mts.map +1 -1
- package/dist/contracts/account/account.mjs +43 -35
- package/dist/contracts/account/account.mjs.map +1 -1
- package/dist/contracts/account/account_events.d.mts +20 -20
- package/dist/contracts/account/account_registry.d.mts +7 -54
- package/dist/contracts/account/account_registry.d.mts.map +1 -1
- package/dist/contracts/account/account_registry.mjs +2 -22
- package/dist/contracts/account/account_registry.mjs.map +1 -1
- package/dist/contracts/deepbook/account.d.mts +18 -18
- package/dist/contracts/deepbook/balances.d.mts +4 -4
- package/dist/contracts/deepbook/deep_price.d.mts +3 -3
- package/dist/contracts/deepbook/order.d.mts +12 -12
- package/dist/contracts/deepbook_predict/admin.d.mts +4 -4
- package/dist/contracts/deepbook_predict/admin.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/builder_code.d.mts +60 -13
- package/dist/contracts/deepbook_predict/builder_code.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/builder_code.mjs +55 -1
- package/dist/contracts/deepbook_predict/builder_code.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/builder_code_events.d.mts +10 -10
- package/dist/contracts/deepbook_predict/config_events.d.mts +88 -84
- package/dist/contracts/deepbook_predict/config_events.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/config_events.mjs +8 -0
- package/dist/contracts/deepbook_predict/config_events.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/expiry_market.d.mts +262 -101
- package/dist/contracts/deepbook_predict/expiry_market.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/expiry_market.mjs +320 -41
- package/dist/contracts/deepbook_predict/expiry_market.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/market_lifecycle_cap.d.mts +5 -5
- package/dist/contracts/deepbook_predict/market_lifecycle_cap.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/market_manager.d.mts +27 -27
- package/dist/contracts/deepbook_predict/market_manager.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/order_events.d.mts +56 -54
- package/dist/contracts/deepbook_predict/order_events.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/order_events.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/pause_cap.d.mts +5 -5
- package/dist/contracts/deepbook_predict/pause_cap.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/plp.d.mts +74 -74
- package/dist/contracts/deepbook_predict/plp.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/pool_valuation_cap.d.mts +5 -5
- package/dist/contracts/deepbook_predict/pool_valuation_cap.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/predict_account.d.mts +22 -17
- package/dist/contracts/deepbook_predict/predict_account.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/predict_account.mjs +12 -6
- package/dist/contracts/deepbook_predict/predict_account.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/pricing.d.mts +67 -67
- package/dist/contracts/deepbook_predict/pricing.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/protocol_config.d.mts +127 -83
- package/dist/contracts/deepbook_predict/protocol_config.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/protocol_config.mjs +59 -1
- package/dist/contracts/deepbook_predict/protocol_config.mjs.map +1 -1
- package/dist/contracts/deepbook_predict/range_codec.d.mts +2 -2
- package/dist/contracts/deepbook_predict/range_codec.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/registry.d.mts +32 -32
- package/dist/contracts/deepbook_predict/registry.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict/vault_events.d.mts +131 -131
- package/dist/contracts/deepbook_predict_math/lazer_price.d.mts +13 -13
- package/dist/contracts/deepbook_predict_math/math.d.mts +14 -14
- package/dist/contracts/deepbook_predict_orders/delayed_execution_config.d.mts +30 -30
- package/dist/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.mjs +6 -0
- package/dist/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.mjs.map +1 -1
- package/dist/contracts/deepbook_predict_orders/desk.d.mts +28 -28
- package/dist/contracts/deepbook_predict_orders/desk.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict_orders/order_queue.d.mts +187 -187
- package/dist/contracts/deepbook_predict_orders/queue.d.mts +240 -62
- package/dist/contracts/deepbook_predict_orders/queue.d.mts.map +1 -1
- package/dist/contracts/deepbook_predict_orders/queue.mjs +306 -41
- package/dist/contracts/deepbook_predict_orders/queue.mjs.map +1 -1
- package/dist/contracts/deepbook_predict_orders/queue_events.d.mts +140 -140
- package/dist/contracts/deepbook_sessions/session_config.d.mts +8 -8
- package/dist/contracts/deepbook_sessions/sessions.d.mts +271 -31
- package/dist/contracts/deepbook_sessions/sessions.d.mts.map +1 -1
- package/dist/contracts/deepbook_sessions/sessions.mjs +363 -3
- package/dist/contracts/deepbook_sessions/sessions.mjs.map +1 -1
- package/dist/deployments/mainnet.mjs.map +1 -1
- package/dist/deployments/testnet.d.mts.map +1 -1
- package/dist/deployments/testnet.mjs +7 -4
- package/dist/deployments/testnet.mjs.map +1 -1
- package/dist/predict/bindings/expiry-market.d.mts +57 -7
- package/dist/predict/bindings/expiry-market.d.mts.map +1 -1
- package/dist/predict/bindings/expiry-market.mjs +48 -2
- package/dist/predict/bindings/expiry-market.mjs.map +1 -1
- package/dist/predict/bindings/protocol-config.d.mts +5 -5
- package/dist/predict/bindings/protocol-config.d.mts.map +1 -1
- package/dist/predict/bindings/protocol-config.mjs +4 -1
- package/dist/predict/bindings/protocol-config.mjs.map +1 -1
- package/dist/predict/bindings/queue.d.mts +30 -0
- package/dist/predict/bindings/queue.d.mts.map +1 -0
- package/dist/predict/bindings/queue.mjs +59 -0
- package/dist/predict/bindings/queue.mjs.map +1 -0
- package/dist/predict/bindings/rename.mjs +5 -1
- package/dist/predict/bindings/rename.mjs.map +1 -1
- package/dist/predict/client.d.mts.map +1 -1
- package/dist/predict/client.mjs +11 -5
- package/dist/predict/client.mjs.map +1 -1
- package/dist/predict/config/generated.d.mts +1 -1
- package/dist/predict/config/generated.d.mts.map +1 -1
- package/dist/predict/config/generated.mjs +1 -0
- package/dist/predict/config/generated.mjs.map +1 -1
- package/dist/predict/config/mainnet.mjs +3 -1
- package/dist/predict/config/mainnet.mjs.map +1 -1
- package/dist/predict/config/testnet.mjs +3 -1
- package/dist/predict/config/testnet.mjs.map +1 -1
- package/dist/predict/config/types.d.mts +23 -0
- package/dist/predict/config/types.d.mts.map +1 -1
- package/dist/predict/cost.d.mts +9 -1
- package/dist/predict/cost.d.mts.map +1 -1
- package/dist/predict/cost.mjs.map +1 -1
- package/dist/predict/errors.d.mts.map +1 -1
- package/dist/predict/errors.mjs +6 -2
- package/dist/predict/errors.mjs.map +1 -1
- package/dist/predict/index.d.mts +1 -1
- package/dist/predict/index.mjs +2 -2
- package/dist/predict/queue.d.mts +8 -4
- package/dist/predict/queue.d.mts.map +1 -1
- package/dist/predict/queue.mjs +8 -4
- package/dist/predict/queue.mjs.map +1 -1
- package/dist/predict/reads/balances.mjs +1 -1
- package/dist/predict/reads/queue.d.mts +3 -2
- package/dist/predict/reads/queue.d.mts.map +1 -1
- package/dist/predict/reads/queue.mjs +5 -4
- package/dist/predict/reads/queue.mjs.map +1 -1
- package/dist/predict/tx/authed.mjs +1 -1
- package/dist/predict/tx/common.d.mts.map +1 -1
- package/dist/predict/tx/common.mjs +3 -2
- package/dist/predict/tx/common.mjs.map +1 -1
- package/dist/predict/tx/trade.d.mts.map +1 -1
- package/dist/predict/tx/trade.mjs +3 -2
- package/dist/predict/tx/trade.mjs.map +1 -1
- package/dist/sessions.d.mts +10 -1
- package/dist/sessions.d.mts.map +1 -1
- package/dist/sessions.mjs.map +1 -1
- package/dist/transactions/balanceManager.d.mts +12 -12
- package/dist/transactions/balanceManager.d.mts.map +1 -1
- package/dist/transactions/deepbook.d.mts +20 -20
- package/dist/transactions/deepbook.d.mts.map +1 -1
- package/dist/transactions/deepbookAdmin.d.mts +4 -4
- package/dist/transactions/deepbookAdmin.d.mts.map +1 -1
- package/dist/transactions/marginAdmin.d.mts +7 -7
- package/dist/transactions/marginAdmin.d.mts.map +1 -1
- package/dist/transactions/marginLiquidations.d.mts +3 -3
- package/dist/transactions/marginMaintainer.d.mts +5 -5
- package/dist/transactions/marginMaintainer.d.mts.map +1 -1
- package/dist/transactions/marginManager.d.mts +32 -32
- package/dist/transactions/marginManager.d.mts.map +1 -1
- package/dist/transactions/marginPool.d.mts +18 -18
- package/dist/transactions/marginPool.d.mts.map +1 -1
- package/dist/transactions/marginRegistry.d.mts +16 -16
- package/dist/transactions/marginTPSL.d.mts +10 -10
- package/dist/transactions/marginTPSL.d.mts.map +1 -1
- package/dist/transactions/poolProxy.d.mts +8 -8
- package/dist/transactions/poolProxy.d.mts.map +1 -1
- package/dist/utils/constants.d.mts.map +1 -1
- package/dist/utils/constants.mjs +1 -1
- package/dist/utils/constants.mjs.map +1 -1
- package/package.json +1 -1
- package/src/account-bindings/account-registry.ts +39 -0
- package/src/account-bindings/account.ts +73 -0
- package/src/account-bindings/latest.ts +41 -0
- package/src/account.ts +89 -5
- package/src/contracts/account/account.ts +73 -4
- package/src/contracts/account/account_registry.ts +1 -1
- package/src/contracts/deepbook_predict/builder_code.ts +94 -2
- package/src/contracts/deepbook_predict/config_events.ts +7 -0
- package/src/contracts/deepbook_predict/expiry_market.ts +490 -44
- package/src/contracts/deepbook_predict/order_events.ts +6 -4
- package/src/contracts/deepbook_predict/predict_account.ts +12 -6
- package/src/contracts/deepbook_predict/protocol_config.ts +85 -0
- package/src/contracts/deepbook_predict_orders/deps/deepbook_predict/expiry_market.ts +14 -0
- package/src/contracts/deepbook_predict_orders/order_flow.ts +4 -0
- package/src/contracts/deepbook_predict_orders/queue.ts +495 -9
- package/src/contracts/deepbook_sessions/sessions.ts +538 -3
- package/src/deployments/mainnet.ts +4 -4
- package/src/deployments/testnet.ts +18 -7
- package/src/deployments/types.ts +14 -0
- package/src/predict/bindings/expiry-market.ts +87 -0
- package/src/predict/bindings/queue.ts +42 -0
- package/src/predict/bindings/rename.ts +5 -1
- package/src/predict/client.ts +25 -3
- package/src/predict/config/generated.ts +3 -0
- package/src/predict/config/mainnet.ts +4 -0
- package/src/predict/config/testnet.ts +4 -0
- package/src/predict/config/types.ts +23 -0
- package/src/predict/cost.ts +9 -1
- package/src/predict/errors.ts +11 -1
- package/src/predict/index.ts +1 -1
- package/src/predict/queue.ts +8 -4
- package/src/predict/reads/queue.ts +7 -4
- package/src/predict/tx/common.ts +2 -0
- package/src/predict/tx/trade.ts +3 -1
- package/src/sessions.ts +10 -1
- package/src/utils/constants.ts +5 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queue.mjs","names":["OrderViewBcs","expiryMarket.expiry","expiryMarket.mintPaused","expiryMarket.cashBalance","expiryMarket.requiredCash","expiryMarket.backingBufferLambda","expiryMarket.orderFlowState","queue.queueStuck","queue.waitingCohorts","queue.queueHeads","queue.pendingCounts","queue.payoutProgress","desk.policy","desk.versionWatermark","protocolConfig.noTradeWindowMs","protocolConfig.feeIncentiveSubsidyRate","protocolConfig.tradingPaused","protocolConfig.frozen","protocolConfig.versionWatermark","protocolConfig.isOrderFlow","queue.waitingOrders","account.loadAccount","account.balance","queue.order","cashBalance","requiredCash","DelayedExecutionPolicyBcs","balance","queue.quoteRedeemOpen","expiryMarket.quoteMintExactCostForAccount","expiryMarket.quoteMintForAccount","expiryMarket.quoteMint"],"sources":["../../../src/predict/reads/queue.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Delayed execution (DBU-885): chain reads for the order queue. A market's queue is a\n// `MarketQueue` in the order-flow companion (`deepbook_predict_orders`), at an ID derived from the\n// companion's `OrderDesk` and the market, so these reads take `OrdersGeneratedConfig` and the\n// facade gates them on the config recording the companion. The market's cash figures stay\n// Predict reads. A market whose queue doesn't exist yet can't be read: the facade checks that\n// first.\nimport type { ClientWithCoreApi } from '@mysten/sui/client';\nimport { bcs } from '@mysten/sui/bcs';\nimport { Transaction, type TransactionResult } from '@mysten/sui/transactions';\nimport { normalizeSuiAddress } from '@mysten/sui/utils';\nimport type { GeneratedConfig, OrdersGeneratedConfig } from '../config/generated.js';\nimport {\n\tDELAYED_EXECUTION_VERSION,\n\tPREDICT_PACKAGE_VERSION,\n\tpolicyFromBcs,\n\ttype DelayedExecutionPolicy,\n\ttype QueueHeads,\n\ttype QueuedOrder,\n} from '../queue.js';\nimport { deriveAccountIdFrom, deriveAccountWrapperIdFrom } from '../tx/common.js';\nimport { queueIdOf, type QueueTarget } from '../tx/queue.js';\nimport { loadLivePricer, type MarketFeeds } from '../tx/trade.js';\nimport { accountMoveCalls as account } from '../../account.js';\nimport * as expiryMarket from '../../contracts/deepbook_predict/expiry_market.js';\nimport * as protocolConfig from '../../contracts/deepbook_predict/protocol_config.js';\nimport { DelayedExecutionPolicy as DelayedExecutionPolicyBcs } from '../../contracts/deepbook_predict_orders/delayed_execution_config.js';\nimport * as desk from '../../contracts/deepbook_predict_orders/desk.js';\nimport { OrderView as OrderViewBcs } from '../../contracts/deepbook_predict_orders/order_queue.js';\nimport * as queue from '../../contracts/deepbook_predict_orders/queue.js';\nimport { inspectReturns, type ReadClient } from './inspect.js';\nimport { parseOptionalU64, parseU64LE } from './parse.js';\n\nconst parseBool = (bytes: Uint8Array): boolean => (bytes[0] ?? 0) !== 0;\nconst OptionalOrderView = bcs.option(OrderViewBcs);\n\n/** The companion's `order_flow::OrderFlow` witness type, which Predict's allowlist names. */\nexport function orderFlowWitnessType(\n\tconfig: Pick<OrdersGeneratedConfig, 'predictOrdersPackageIdV1'>,\n) {\n\treturn `${config.predictOrdersPackageIdV1}::order_flow::OrderFlow`;\n}\n\n/** Everything the queued-order preflight and the app's queue view read, from one simulate. */\nexport interface MarketQueueState {\n\tmarketId: string;\n\t/** The market's `MarketQueue`. */\n\tqueueId: string;\n\texpiryMs: bigint;\n\tmintPaused: boolean;\n\tcashBalance: bigint;\n\trequiredCash: bigint;\n\t/**\n\t * Cash above required cash, 0 when below: the largest cash need a new queued mint may have\n\t * now (Predict's admission refuses a larger one).\n\t */\n\tspareCash: bigint;\n\t/** Summed cash need of the admitted orders; `rebalance_expiry_cash` funds it. */\n\twaitingCashNeed: bigint;\n\t/** 1e9-scaled. The mint cash-need formulas take it. */\n\tminEntryProbability: bigint;\n\t/** 1e9-scaled λ. The sell cash-need formula takes it. */\n\tbackingBufferLambda: bigint;\n\t/** Sizes a filler's resolve batch. */\n\tpayoutTreeNodeCount: bigint;\n\t/** `queue_stuck`: enqueue would refuse as stuck right now (\"pricing delayed\"). */\n\tstuck: boolean;\n\tcohorts: {\n\t\tcount: bigint;\n\t\toldestUncommittedTauMs: bigint | null;\n\t\t/** The cohort the stuck gate's first rule watches. */\n\t\toldestUncommittedTauAboveCommittedMs: bigint | null;\n\t};\n\theads: QueueHeads;\n\t/** Unfinished mints and sells, against the policy capacities. */\n\tpending: { mints: bigint; sells: bigint };\n\t/**\n\t * The settlement payout walk (`settle_step`): it resumes at `cursor`, and `completed` is set\n\t * by the call that emits `MarketPayoutsCompleted`.\n\t */\n\tpayout: { cursor: bigint; nextId: bigint; completed: boolean };\n\t/** The companion's `OrderDesk`: the policy every queue runs under, and its version floor. */\n\tdesk: {\n\t\tid: string;\n\t\tpolicy: DelayedExecutionPolicy;\n\t\tversionWatermark: bigint;\n\t};\n\tprotocol: {\n\t\tnoTradeWindowMs: bigint;\n\t\t/** The admin-set mint fee subsidy rate, 1e9-scaled (20% when unset). */\n\t\tfeeIncentiveSubsidyRate: bigint;\n\t\ttradingPaused: boolean;\n\t\tfrozen: boolean;\n\t\t/** Predict's version floor. Enqueue needs it at `DELAYED_EXECUTION_VERSION`. */\n\t\tversionWatermark: bigint;\n\t\t/**\n\t\t * Whether Predict allowlists this companion's `OrderFlow` witness\n\t\t * (`protocol_config::set_order_flow`). Predict's admission, commit and fill refuse it until\n\t\t * then (`EOrderFlowNotAllowed`).\n\t\t */\n\t\torderFlowEnabled: boolean;\n\t};\n\t/** Present when an owner was given. */\n\taccount: {\n\t\taccountId: string;\n\t\t/**\n\t\t * Unfinished orders the account holds in this market, against `per_account_cap`. Stale\n\t\t * after expiry: the settlement drain refunds without lowering it.\n\t\t */\n\t\twaitingOrders: bigint;\n\t\t/** `account::balance<USDC>`, unsettled accumulator funds included. */\n\t\tavailableRaw: bigint;\n\t} | null;\n\t/** One entry per requested record ID: the record, or `null` when missing or deleted. */\n\trecords: (QueuedOrder | null)[];\n}\n\n/**\n * Read a market's queue state in one simulate: Predict's cash figures and gates, the queue's\n * stuck gate, cohorts, heads and counters, and the desk's policy. With `owner`, also the\n * account's waiting-order count and USDC balance (the owner must have an account: loading a\n * missing wrapper aborts the read). With `recordIds`, also those records. The queue must exist.\n */\nexport async function marketQueueState(\n\tclient: ReadClient,\n\tconfig: OrdersGeneratedConfig,\n\tmarketId: string,\n\topts: {\n\t\towner?: string;\n\t\tquoteCoinType?: string;\n\t\trecordIds?: readonly bigint[];\n\t\tqueueId?: string;\n\t} = {},\n): Promise<MarketQueueState> {\n\tconst queueId = queueIdOf(config, { expiryMarketId: marketId, queueId: opts.queueId });\n\tconst tx = new Transaction();\n\tlet next = 0;\n\tconst results: TransactionResult[] = [];\n\tconst add = (command: (tx: Transaction) => TransactionResult): number => {\n\t\tresults.push(tx.add(command));\n\t\treturn next++;\n\t};\n\tconst market = { market: marketId };\n\tconst onQueue = { queue: queueId };\n\tconst i = {\n\t\texpiry: add(expiryMarket.expiry({ config, arguments: market })),\n\t\tmintPaused: add(expiryMarket.mintPaused({ config, arguments: market })),\n\t\tcashBalance: add(expiryMarket.cashBalance({ config, arguments: market })),\n\t\trequiredCash: add(expiryMarket.requiredCash({ config, arguments: market })),\n\t\tbackingBufferLambda: add(expiryMarket.backingBufferLambda({ config, arguments: market })),\n\t\torderFlow: add(expiryMarket.orderFlowState({ config, arguments: market })),\n\t\tstuck: add(queue.queueStuck({ config, arguments: onQueue })),\n\t\tcohorts: add(queue.waitingCohorts({ config, arguments: onQueue })),\n\t\theads: add(queue.queueHeads({ config, arguments: onQueue })),\n\t\tpending: add(queue.pendingCounts({ config, arguments: onQueue })),\n\t\tpayout: add(queue.payoutProgress({ config, arguments: onQueue })),\n\t\tpolicy: add(desk.policy({ config })),\n\t\tdeskWatermark: add(desk.versionWatermark({ config })),\n\t\tnoTradeWindowMs: add(protocolConfig.noTradeWindowMs({ config })),\n\t\tsubsidyRate: add(protocolConfig.feeIncentiveSubsidyRate({ config })),\n\t\ttradingPaused: add(protocolConfig.tradingPaused({ config })),\n\t\tfrozen: add(protocolConfig.frozen({ config })),\n\t\twatermark: add(protocolConfig.versionWatermark({ config })),\n\t\torderFlowEnabled: add(\n\t\t\tprotocolConfig.isOrderFlow({ config, typeArguments: [orderFlowWitnessType(config)] }),\n\t\t),\n\t};\n\tlet accountIdx: { waiting: number; balance: number; accountId: string } | null = null;\n\tif (opts.owner) {\n\t\tif (!opts.quoteCoinType) throw new Error('marketQueueState: owner reads need quoteCoinType');\n\t\tconst accountId = deriveAccountIdFrom(config, opts.owner);\n\t\tconst waiting = add(queue.waitingOrders({ config, arguments: { ...onQueue, accountId } }));\n\t\tconst loaded = add(\n\t\t\taccount.loadAccount({\n\t\t\t\tconfig,\n\t\t\t\targuments: { self: deriveAccountWrapperIdFrom(config, opts.owner) },\n\t\t\t}),\n\t\t);\n\t\tconst balance = add(\n\t\t\taccount.balance({\n\t\t\t\tconfig,\n\t\t\t\ttypeArguments: [opts.quoteCoinType],\n\t\t\t\targuments: { self: results[loaded] },\n\t\t\t}),\n\t\t);\n\t\taccountIdx = { waiting, balance, accountId };\n\t}\n\tconst recordIdx = (opts.recordIds ?? []).map((recordId) =>\n\t\tadd(queue.order({ config, arguments: { ...onQueue, recordId } })),\n\t);\n\n\tconst cmds = await inspectReturns(client, tx);\n\tconst u64 = (idx: number, value = 0) => parseU64LE(cmds[idx][value]);\n\tconst cashBalance = u64(i.cashBalance);\n\tconst requiredCash = u64(i.requiredCash);\n\treturn {\n\t\tmarketId: normalizeSuiAddress(marketId),\n\t\tqueueId: normalizeSuiAddress(queueId),\n\t\texpiryMs: u64(i.expiry),\n\t\tmintPaused: parseBool(cmds[i.mintPaused][0]),\n\t\tcashBalance,\n\t\trequiredCash,\n\t\tspareCash: cashBalance > requiredCash ? cashBalance - requiredCash : 0n,\n\t\twaitingCashNeed: u64(i.orderFlow, 0),\n\t\tpayoutTreeNodeCount: u64(i.orderFlow, 1),\n\t\tminEntryProbability: u64(i.orderFlow, 2),\n\t\tbackingBufferLambda: u64(i.backingBufferLambda),\n\t\tstuck: parseBool(cmds[i.stuck][0]),\n\t\tcohorts: {\n\t\t\tcount: u64(i.cohorts, 0),\n\t\t\toldestUncommittedTauMs: parseOptionalU64(cmds[i.cohorts][1]),\n\t\t\toldestUncommittedTauAboveCommittedMs: parseOptionalU64(cmds[i.cohorts][2]),\n\t\t},\n\t\theads: {\n\t\t\tresolveHead: u64(i.heads, 0),\n\t\t\tnextId: u64(i.heads, 1),\n\t\t\tlastTauMs: u64(i.heads, 2),\n\t\t\tlastCommittedTauMs: u64(i.heads, 3),\n\t\t},\n\t\tpending: { mints: u64(i.pending, 0), sells: u64(i.pending, 1) },\n\t\tpayout: {\n\t\t\tcursor: u64(i.payout, 0),\n\t\t\tnextId: u64(i.payout, 1),\n\t\t\tcompleted: parseBool(cmds[i.payout][2]),\n\t\t},\n\t\tdesk: {\n\t\t\tid: normalizeSuiAddress(config.orderDesk),\n\t\t\tpolicy: policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[i.policy][0])),\n\t\t\tversionWatermark: u64(i.deskWatermark),\n\t\t},\n\t\tprotocol: {\n\t\t\tnoTradeWindowMs: u64(i.noTradeWindowMs),\n\t\t\tfeeIncentiveSubsidyRate: u64(i.subsidyRate),\n\t\t\ttradingPaused: parseBool(cmds[i.tradingPaused][0]),\n\t\t\tfrozen: parseBool(cmds[i.frozen][0]),\n\t\t\tversionWatermark: u64(i.watermark),\n\t\t\torderFlowEnabled: parseBool(cmds[i.orderFlowEnabled][0]),\n\t\t},\n\t\taccount: accountIdx\n\t\t\t? {\n\t\t\t\t\taccountId: accountIdx.accountId,\n\t\t\t\t\twaitingOrders: u64(accountIdx.waiting),\n\t\t\t\t\tavailableRaw: u64(accountIdx.balance),\n\t\t\t\t}\n\t\t\t: null,\n\t\trecords: recordIdx.map((idx) => OptionalOrderView.parse(cmds[idx][0]) ?? null),\n\t};\n}\n\n/** Queue records by record ID (`queue::order`), `null` for a missing or cleaned-up one. One simulate. */\nexport async function queuedOrders(\n\tclient: ReadClient,\n\tconfig: OrdersGeneratedConfig,\n\ttarget: QueueTarget,\n\trecordIds: readonly bigint[],\n): Promise<(QueuedOrder | null)[]> {\n\tif (recordIds.length === 0) return [];\n\tconst queueId = queueIdOf(config, target);\n\tconst tx = new Transaction();\n\tfor (const recordId of recordIds) {\n\t\ttx.add(queue.order({ config, arguments: { queue: queueId, recordId } }));\n\t}\n\tconst cmds = await inspectReturns(client, tx);\n\treturn cmds.map((rv) => OptionalOrderView.parse(rv[0]) ?? null);\n}\n\n/**\n * `ProtocolConfig.version_watermark`, read from the object's own BCS rather than a getter, so it\n * works against any package version: the getter only exists from the delayed-execution package\n * on, while the struct layout is frozen since v1.\n */\nexport async function versionWatermark(\n\tclient: ClientWithCoreApi,\n\tprotocolConfigId: string,\n): Promise<bigint> {\n\tconst { object } = await client.core.getObject({\n\t\tobjectId: protocolConfigId,\n\t\tinclude: { content: true },\n\t});\n\tif (!object.content) throw new Error(`ProtocolConfig ${protocolConfigId} returned no content`);\n\treturn protocolConfig.ProtocolConfig.parse(object.content).version_watermark;\n}\n\n/**\n * Which trade path a network is on:\n * - `'immediate'`: the watermark isn't raised and this SDK has no delayed-execution record, so\n * its call target is a pre-v4 Predict package. Use the immediate `mint*` / `redeem` builders.\n * - `'awaiting-cutover'`: the config records delayed execution but the watermark isn't raised.\n * Nothing trades: enqueue aborts `ECutoverNotReached`, and the immediate builders abort in the\n * v4 package the config calls (`EDelayedExecutionRequired`). Trading stays paused through the\n * cutover.\n * - `'delayed'`: the watermark is raised. Use the `enqueue*` builders; the immediate ones abort\n * `EDelayedExecutionRequired`.\n * - `'unsupported'`: the watermark is raised but this SDK's config has no delayed-execution\n * record for the network. Upgrade the SDK, or pass a config that records it.\n * - `'retired'`: the watermark is above the Predict code version this SDK calls\n * (`PREDICT_PACKAGE_VERSION`), so every version-gated call aborts `EPackageVersionDisabled`.\n * Upgrade the SDK.\n */\nexport type ExecutionMode =\n\t'immediate' | 'awaiting-cutover' | 'delayed' | 'unsupported' | 'retired';\n\n/**\n * The {@link ExecutionMode} for a watermark and what the config records.\n * `recordsDelayedExecution`: the Predict upgrade, the order-flow companion and its desk, which\n * queued orders need. `recordsPredictUpgrade`: the Predict upgrade alone\n * (`packages.predictDelayedExecution`), which makes the config's Predict call target the package\n * that retired the immediate trades. It defaults to `recordsDelayedExecution`.\n */\nexport function executionModeFor(\n\twatermark: bigint,\n\trecordsDelayedExecution: boolean,\n\trecordsPredictUpgrade: boolean = recordsDelayedExecution,\n): ExecutionMode {\n\tif (watermark >= DELAYED_EXECUTION_VERSION) {\n\t\tif (!recordsDelayedExecution) return 'unsupported';\n\t\treturn watermark > PREDICT_PACKAGE_VERSION ? 'retired' : 'delayed';\n\t}\n\treturn recordsDelayedExecution || recordsPredictUpgrade ? 'awaiting-cutover' : 'immediate';\n}\n\n/**\n * USDC sent to an account's wrapper address with `send_funds` that the account hasn't settled\n * yet: refunds, sell proceeds and settled payouts land here. `account::balance` already counts\n * them, so this is for display (\"pending funds\"), not for sizing.\n */\nexport async function pendingFunds(\n\tclient: ClientWithCoreApi,\n\twrapperId: string,\n\tcoinType: string,\n): Promise<bigint> {\n\tconst { balance } = await client.core.getBalance({ owner: wrapperId, coinType });\n\treturn BigInt(balance.addressBalance);\n}\n\n// The prefix of `pyth_lazer::state::State` up to the upgrade cap, identical in the testnet and\n// mainnet vendored sources. Parsing a prefix ignores the trailing `governance` field.\nconst LazerStatePrefix = bcs.struct('State', {\n\tid: bcs.Address,\n\ttrusted_signers: bcs.vector(\n\t\tbcs.struct('TrustedSignerInfo', { public_key: bcs.vector(bcs.u8()), expires_at: bcs.u64() }),\n\t),\n\tupgrade_cap: bcs.struct('UpgradeCap', {\n\t\tid: bcs.Address,\n\t\tpackage: bcs.Address,\n\t\tversion: bcs.u64(),\n\t\tpolicy: bcs.u8(),\n\t}),\n});\n\n/**\n * The current Pyth Lazer package (from `State.upgrade_cap.package`) and the original ID that\n * types `update::Update` (from the State's own type). Read it per filler batch and never cache\n * it: a Lazer upgrade retires the old package at once.\n */\nexport async function lazerPackages(\n\tclient: ClientWithCoreApi,\n\tstateId: string,\n): Promise<{ stateId: string; packageId: string; originalId: string }> {\n\tconst { object } = await client.core.getObject({ objectId: stateId, include: { content: true } });\n\tif (!object.content) throw new Error(`Lazer State ${stateId} returned no content`);\n\tconst [originalId, module, name] = object.type.split('::');\n\tif (module !== 'state' || name !== 'State') {\n\t\tthrow new Error(`${stateId} is a ${object.type}, not a Pyth Lazer State`);\n\t}\n\treturn {\n\t\tstateId: normalizeSuiAddress(stateId),\n\t\tpackageId: normalizeSuiAddress(LazerStatePrefix.parse(object.content).upgrade_cap.package),\n\t\toriginalId: normalizeSuiAddress(originalId),\n\t};\n}\n\n/** `expiry_market::RedeemQuote` with camelCase keys. `proceeds` is before the order fee. */\nexport interface RedeemOpenQuoteRaw {\n\tcloseQuantity: bigint;\n\tprobability: bigint;\n\tproceeds: bigint;\n\ttradingFee: bigint;\n\tbuilderFee: bigint;\n\tinventoryImpactRebate: bigint;\n}\n\n/**\n * Quote an early sell of an Open record at a fresh live pricer (`load_live_pricer`, then the\n * queue's `quote_redeem_open`, which prices through Predict's `quote_close`), and read the desk's\n * policy for the order fee. `proceeds` is before the order fee, with no congestion penalty.\n * Aborts `ERecordNotOpen` when the record isn't Open. It doesn't check that the wrapper's account\n * owns the record: the wrapper only supplies the builder code.\n */\nexport async function quoteRedeemOpen(\n\tclient: ReadClient,\n\tconfig: OrdersGeneratedConfig,\n\targs: QueueTarget & {\n\t\twrapperId: string;\n\t\trecordId: bigint;\n\t\tcloseQuantityRaw: bigint;\n\t} & MarketFeeds,\n): Promise<{ quote: RedeemOpenQuoteRaw; policy: DelayedExecutionPolicy }> {\n\tconst tx = new Transaction();\n\tconst pricer = tx.add(loadLivePricer(config, args));\n\ttx.add(\n\t\tqueue.quoteRedeemOpen({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tqueue: queueIdOf(config, args),\n\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\twrapper: args.wrapperId,\n\t\t\t\tpricer,\n\t\t\t\trecordId: args.recordId,\n\t\t\t\tcloseQuantity: args.closeQuantityRaw,\n\t\t\t},\n\t\t}),\n\t);\n\ttx.add(desk.policy({ config }));\n\tconst cmds = await inspectReturns(client, tx);\n\tconst q = expiryMarket.RedeemQuote.parse(cmds[1][0]);\n\treturn {\n\t\tquote: {\n\t\t\tcloseQuantity: q.close_quantity,\n\t\t\tprobability: q.probability,\n\t\t\tproceeds: q.proceeds,\n\t\t\ttradingFee: q.trading_fee,\n\t\t\tbuilderFee: q.builder_fee,\n\t\t\tinventoryImpactRebate: q.inventory_impact_rebate,\n\t\t},\n\t\tpolicy: policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[2][0])),\n\t};\n}\n\n/**\n * `expiry_market::MintQuote` with camelCase keys. `allInCost` includes `penaltyFee`, which the\n * delayed-execution package always quotes as 0: its quotes price like a queued fill.\n */\nexport interface MintQuoteRaw {\n\tquantity: bigint;\n\tentryProbability: bigint;\n\tpremium: bigint;\n\ttradingFee: bigint;\n\tfeeIncentiveSubsidy: bigint;\n\tbuilderFee: bigint;\n\tpenaltyFee: bigint;\n\tinventoryImpactCharge: bigint;\n\tallInCost: bigint;\n}\n\n/** What to quote: an exact quantity, a premium budget, or an all-in budget. */\nexport type MintQuoteRequest =\n\t| { shape: 'exact-quantity'; quantityRaw: bigint }\n\t| { shape: 'exact-amount'; maxPremiumRaw: bigint; minQuantityRaw: bigint }\n\t| { shape: 'exact-cost'; maxCostRaw: bigint; minQuantityRaw: bigint };\n\n/**\n * Quote a mint for one account without placing it: Predict's `quote_mint_for_account` (exact\n * quantity and premium budget) or `quote_mint_exact_cost_for_account` (all-in budget), at a fresh\n * live pricer. Both read the account's builder code and cap a budget at its balance. From the\n * delayed-execution package on they price like a queued fill at the clock: no congestion penalty,\n * and no trade-window or Pyth-staleness abort. They abort `EOrderFailsLimits` when the mint would\n * be refused at the clock. With `ordersConfig`, also reads the order desk's policy.\n */\nexport async function quoteMintForAccount(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\trequest: MintQuoteRequest;\n\t\t/** Also read the order desk's policy, in the same simulate. */\n\t\tordersConfig?: OrdersGeneratedConfig;\n\t} & MarketFeeds,\n): Promise<{ quote: MintQuoteRaw; policy: DelayedExecutionPolicy | null }> {\n\tconst tx = new Transaction();\n\tconst pricer = tx.add(loadLivePricer(config, args));\n\tconst base = {\n\t\tmarket: args.expiryMarketId,\n\t\twrapper: args.wrapperId,\n\t\tpricer,\n\t\tlowerTick: args.lowerTick,\n\t\thigherTick: args.higherTick,\n\t};\n\tconst r = args.request;\n\tif (r.shape === 'exact-cost') {\n\t\ttx.add(\n\t\t\texpiryMarket.quoteMintExactCostForAccount({\n\t\t\t\tconfig,\n\t\t\t\targuments: { ...base, maxCost: r.maxCostRaw, minQuantity: r.minQuantityRaw },\n\t\t\t}),\n\t\t);\n\t} else {\n\t\ttx.add(\n\t\t\texpiryMarket.quoteMintForAccount({\n\t\t\t\tconfig,\n\t\t\t\targuments:\n\t\t\t\t\tr.shape === 'exact-quantity'\n\t\t\t\t\t\t? { ...base, maxPremium: 0n, minQuantity: r.quantityRaw, exactQuantity: true }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\tmaxPremium: r.maxPremiumRaw,\n\t\t\t\t\t\t\t\tminQuantity: r.minQuantityRaw,\n\t\t\t\t\t\t\t\texactQuantity: false,\n\t\t\t\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\tif (args.ordersConfig) tx.add(desk.policy({ config: args.ordersConfig }));\n\tconst cmds = await inspectReturns(client, tx);\n\tconst q = expiryMarket.MintQuote.parse(cmds[1][0]);\n\tconst quote: MintQuoteRaw = {\n\t\tquantity: q.quantity,\n\t\tentryProbability: q.entry_probability,\n\t\tpremium: q.premium,\n\t\ttradingFee: q.trading_fee,\n\t\tfeeIncentiveSubsidy: q.fee_incentive_subsidy,\n\t\tbuilderFee: q.builder_fee,\n\t\tpenaltyFee: q.penalty_fee,\n\t\tinventoryImpactCharge: q.inventory_impact_charge,\n\t\tallInCost: q.all_in_cost,\n\t};\n\tconst policy = args.ordersConfig\n\t\t? policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[2][0]))\n\t\t: null;\n\treturn { quote, policy };\n}\n\n/** What `quote_mint` quotes: an exact quantity, or the largest quantity a premium budget buys. */\nexport type AnonymousMintQuoteRequest = Exclude<MintQuoteRequest, { shape: 'exact-cost' }>;\n\n/**\n * Quote a mint for no particular account: Predict's `quote_mint`, at a fresh live pricer. It\n * prices like a queued fill at the clock with no builder fee, so it previews a mint for a visitor\n * without an account or a funded balance. It has no all-in budget mode. It aborts\n * `EOrderFailsLimits` when the mint would be refused at the clock, for example below the 1 USDC\n * minimum premium. With `ordersConfig`, also reads the order desk's policy.\n */\nexport async function quoteMintAnonymous(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\trequest: AnonymousMintQuoteRequest;\n\t\tordersConfig?: OrdersGeneratedConfig;\n\t} & MarketFeeds,\n): Promise<{ quote: MintQuoteRaw; policy: DelayedExecutionPolicy | null }> {\n\tconst tx = new Transaction();\n\tconst pricer = tx.add(loadLivePricer(config, args));\n\tconst r = args.request;\n\ttx.add(\n\t\texpiryMarket.quoteMint({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\tpricer,\n\t\t\t\tlowerTick: args.lowerTick,\n\t\t\t\thigherTick: args.higherTick,\n\t\t\t\t...(r.shape === 'exact-quantity'\n\t\t\t\t\t? { maxPremium: 0n, minQuantity: r.quantityRaw, exactQuantity: true }\n\t\t\t\t\t: { maxPremium: r.maxPremiumRaw, minQuantity: r.minQuantityRaw, exactQuantity: false }),\n\t\t\t},\n\t\t}),\n\t);\n\tif (args.ordersConfig) tx.add(desk.policy({ config: args.ordersConfig }));\n\tconst cmds = await inspectReturns(client, tx);\n\tconst q = expiryMarket.MintQuote.parse(cmds[1][0]);\n\treturn {\n\t\tquote: {\n\t\t\tquantity: q.quantity,\n\t\t\tentryProbability: q.entry_probability,\n\t\t\tpremium: q.premium,\n\t\t\ttradingFee: q.trading_fee,\n\t\t\tfeeIncentiveSubsidy: q.fee_incentive_subsidy,\n\t\t\tbuilderFee: q.builder_fee,\n\t\t\tpenaltyFee: q.penalty_fee,\n\t\t\tinventoryImpactCharge: q.inventory_impact_charge,\n\t\t\tallInCost: q.all_in_cost,\n\t\t},\n\t\tpolicy: args.ordersConfig ? policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[2][0])) : null,\n\t};\n}\n\n/**\n * The order desk's policy and an owner's USDC balance, in one simulate. The queued exact-cost\n * quote needs both: enqueue escrows `min(max_cost, available − fee)`, while the chain quote caps\n * at the whole balance.\n */\nexport async function orderFeeAndBalance(\n\tclient: ReadClient,\n\tconfig: OrdersGeneratedConfig,\n\towner: string,\n\tcoinType: string,\n): Promise<{ policy: DelayedExecutionPolicy; availableRaw: bigint }> {\n\tconst tx = new Transaction();\n\ttx.add(desk.policy({ config }));\n\tconst loaded = tx.add(\n\t\taccount.loadAccount({ config, arguments: { self: deriveAccountWrapperIdFrom(config, owner) } }),\n\t);\n\ttx.add(account.balance({ config, typeArguments: [coinType], arguments: { self: loaded } }));\n\tconst cmds = await inspectReturns(client, tx);\n\treturn {\n\t\tpolicy: policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[0][0])),\n\t\tavailableRaw: parseU64LE(cmds[2][0]),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkCA,MAAM,aAAa,WAAgC,MAAM,MAAM,OAAO;AACtE,MAAM,oBAAoB,IAAI,OAAOA,UAAa;;AAGlD,SAAgB,qBACf,QACC;AACD,QAAO,GAAG,OAAO,yBAAyB;;;;;;;;AAmF3C,eAAsB,iBACrB,QACA,QACA,UACA,OAKI,EAAE,EACsB;CAC5B,MAAM,UAAU,UAAU,QAAQ;EAAE,gBAAgB;EAAU,SAAS,KAAK;EAAS,CAAC;CACtF,MAAM,KAAK,IAAI,aAAa;CAC5B,IAAI,OAAO;CACX,MAAM,UAA+B,EAAE;CACvC,MAAM,OAAO,YAA4D;AACxE,UAAQ,KAAK,GAAG,IAAI,QAAQ,CAAC;AAC7B,SAAO;;CAER,MAAM,SAAS,EAAE,QAAQ,U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,eAAe;IAAM,GACnE;IAAE,YAAY,EAAE;IAAe,aAAa,EAAE;IAAgB,eAAe;IAAO;GACvF;EACD,CAAC,CACF;AACD,KAAI,KAAK,aAAc,IAAG,IAAInB,OAAY,EAAE,QAAQ,KAAK,cAAc,CAAC,CAAC;CACzE,MAAM,OAAO,MAAM,eAAe,QAAQ,GAAG;CAC7C,MAAM,cAA2B,MAAM,KAAK,GAAG,GAAG;AAClD,QAAO;EACN,OAAO;GACN,UAAU,EAAE;GACZ,kBAAkB,EAAE;GACpB,SAAS,EAAE;GACX,YAAY,EAAE;GACd,qBAAqB,EAAE;GACvB,YAAY,EAAE;GACd,YAAY,EAAE;GACd,uBAAuB,EAAE;GACzB,WAAW,EAAE;GACb;EACD,QAAQ,KAAK,eAAe,cAAcc,uBAA0B,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG;EACzF;;;;;;;AAQF,eAAsB,mBACrB,QACA,QACA,OACA,UACoE;CACpE,MAAM,KAAK,IAAI,aAAa;AAC5B,IAAG,IAAId,OAAY,EAAE,QAAQ,CAAC,CAAC;CAC/B,MAAM,SAAS,GAAG,IACjBS,YAAoB;EAAE;EAAQ,WAAW,EAAE,MAAM,2BAA2B,QAAQ,MAAM,EAAE;EAAE,CAAC,CAC/F;AACD,IAAG,IAAIC,QAAgB;EAAE;EAAQ,eAAe,CAAC,SAAS;EAAE,WAAW,EAAE,MAAM,QAAQ;EAAE,CAAC,CAAC;CAC3F,MAAM,OAAO,MAAM,eAAe,QAAQ,GAAG;AAC7C,QAAO;EACN,QAAQ,cAAcI,uBAA0B,MAAM,KAAK,GAAG,GAAG,CAAC;EAClE,cAAc,WAAW,KAAK,GAAG,GAAG;EACpC"}
|
|
1
|
+
{"version":3,"file":"queue.mjs","names":["OrderViewBcs","expiryMarket.expiry","expiryMarket.mintPaused","expiryMarket.cashBalance","expiryMarket.requiredCash","expiryMarket.backingBufferLambda","expiryMarket.orderFlowState","queue.queueStuck","queue.waitingCohorts","queue.queueHeads","queue.pendingCounts","queue.payoutProgress","desk.policy","desk.versionWatermark","protocolConfig.noTradeWindowMs","protocolConfig.feeIncentiveSubsidyRate","protocolConfig.tradingPaused","protocolConfig.frozen","protocolConfig.versionWatermark","protocolConfig.isOrderFlow","queue.waitingOrders","account.loadAccount","account.balance","queue.order","cashBalance","requiredCash","DelayedExecutionPolicyBcs","balance","quoteRedeemOpenCall","expiryMarket.quoteMintExactCostForAccount","expiryMarket.quoteMintForAccount","expiryMarket.quoteMint"],"sources":["../../../src/predict/reads/queue.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Delayed execution (DBU-885): chain reads for the order queue. A market's queue is a\n// `MarketQueue` in the order-flow companion (`deepbook_predict_orders`), at an ID derived from the\n// companion's `OrderDesk` and the market, so these reads take `OrdersGeneratedConfig` and the\n// facade gates them on the config recording the companion. The market's cash figures stay\n// Predict reads. A market whose queue doesn't exist yet can't be read: the facade checks that\n// first.\nimport type { ClientWithCoreApi } from '@mysten/sui/client';\nimport { bcs } from '@mysten/sui/bcs';\nimport { Transaction, type TransactionResult } from '@mysten/sui/transactions';\nimport { normalizeSuiAddress } from '@mysten/sui/utils';\nimport type { GeneratedConfig, OrdersGeneratedConfig } from '../config/generated.js';\nimport {\n\tDELAYED_EXECUTION_VERSION,\n\tPREDICT_PACKAGE_VERSION,\n\tpolicyFromBcs,\n\ttype DelayedExecutionPolicy,\n\ttype QueueHeads,\n\ttype QueuedOrder,\n} from '../queue.js';\nimport { deriveAccountIdFrom, deriveAccountWrapperIdFrom } from '../tx/common.js';\nimport { queueIdOf, type QueueTarget } from '../tx/queue.js';\nimport { loadLivePricer, type MarketFeeds } from '../tx/trade.js';\nimport { accountMoveCalls as account } from '../../account.js';\nimport * as expiryMarket from '../../contracts/deepbook_predict/expiry_market.js';\nimport * as protocolConfig from '../../contracts/deepbook_predict/protocol_config.js';\nimport { DelayedExecutionPolicy as DelayedExecutionPolicyBcs } from '../../contracts/deepbook_predict_orders/delayed_execution_config.js';\nimport * as desk from '../../contracts/deepbook_predict_orders/desk.js';\nimport { OrderView as OrderViewBcs } from '../../contracts/deepbook_predict_orders/order_queue.js';\nimport * as queue from '../../contracts/deepbook_predict_orders/queue.js';\nimport { quoteRedeemOpen as quoteRedeemOpenCall } from '../bindings/queue.js';\nimport { inspectReturns, type ReadClient } from './inspect.js';\nimport { parseOptionalU64, parseU64LE } from './parse.js';\n\nconst parseBool = (bytes: Uint8Array): boolean => (bytes[0] ?? 0) !== 0;\nconst OptionalOrderView = bcs.option(OrderViewBcs);\n\n/** The companion's `order_flow::OrderFlow` witness type, which Predict's allowlist names. */\nexport function orderFlowWitnessType(\n\tconfig: Pick<OrdersGeneratedConfig, 'predictOrdersPackageIdV1'>,\n) {\n\treturn `${config.predictOrdersPackageIdV1}::order_flow::OrderFlow`;\n}\n\n/** Everything the queued-order preflight and the app's queue view read, from one simulate. */\nexport interface MarketQueueState {\n\tmarketId: string;\n\t/** The market's `MarketQueue`. */\n\tqueueId: string;\n\texpiryMs: bigint;\n\tmintPaused: boolean;\n\tcashBalance: bigint;\n\trequiredCash: bigint;\n\t/**\n\t * Cash above required cash, 0 when below: the largest cash need a new queued mint may have\n\t * now (Predict's admission refuses a larger one).\n\t */\n\tspareCash: bigint;\n\t/** Summed cash need of the admitted orders; `rebalance_expiry_cash` funds it. */\n\twaitingCashNeed: bigint;\n\t/** 1e9-scaled. The mint cash-need formulas take it. */\n\tminEntryProbability: bigint;\n\t/** 1e9-scaled λ. The sell cash-need formula takes it. */\n\tbackingBufferLambda: bigint;\n\t/** Sizes a filler's resolve batch. */\n\tpayoutTreeNodeCount: bigint;\n\t/** `queue_stuck`: enqueue would refuse as stuck right now (\"pricing delayed\"). */\n\tstuck: boolean;\n\tcohorts: {\n\t\tcount: bigint;\n\t\toldestUncommittedTauMs: bigint | null;\n\t\t/** The cohort the stuck gate's first rule watches. */\n\t\toldestUncommittedTauAboveCommittedMs: bigint | null;\n\t};\n\theads: QueueHeads;\n\t/** Unfinished mints and sells, against the policy capacities. */\n\tpending: { mints: bigint; sells: bigint };\n\t/**\n\t * The settlement payout walk (`settle_step`): it resumes at `cursor`, and `completed` is set\n\t * by the call that emits `MarketPayoutsCompleted`.\n\t */\n\tpayout: { cursor: bigint; nextId: bigint; completed: boolean };\n\t/** The companion's `OrderDesk`: the policy every queue runs under, and its version floor. */\n\tdesk: {\n\t\tid: string;\n\t\tpolicy: DelayedExecutionPolicy;\n\t\tversionWatermark: bigint;\n\t};\n\tprotocol: {\n\t\tnoTradeWindowMs: bigint;\n\t\t/** The admin-set mint fee subsidy rate, 1e9-scaled (20% when unset). */\n\t\tfeeIncentiveSubsidyRate: bigint;\n\t\ttradingPaused: boolean;\n\t\tfrozen: boolean;\n\t\t/** Predict's version floor. Enqueue needs it at `DELAYED_EXECUTION_VERSION`. */\n\t\tversionWatermark: bigint;\n\t\t/**\n\t\t * Whether Predict allowlists this companion's `OrderFlow` witness\n\t\t * (`protocol_config::set_order_flow`). Predict's admission, commit and fill refuse it until\n\t\t * then (`EOrderFlowNotAllowed`).\n\t\t */\n\t\torderFlowEnabled: boolean;\n\t};\n\t/** Present when an owner was given. */\n\taccount: {\n\t\taccountId: string;\n\t\t/**\n\t\t * Unfinished orders the account holds in this market, against `per_account_cap`. Stale\n\t\t * after expiry: the settlement drain refunds without lowering it.\n\t\t */\n\t\twaitingOrders: bigint;\n\t\t/** `account::balance<USDC>`, unsettled accumulator funds included. */\n\t\tavailableRaw: bigint;\n\t} | null;\n\t/** One entry per requested record ID: the record, or `null` when missing or deleted. */\n\trecords: (QueuedOrder | null)[];\n}\n\n/**\n * Read a market's queue state in one simulate: Predict's cash figures and gates, the queue's\n * stuck gate, cohorts, heads and counters, and the desk's policy. With `owner`, also the\n * account's waiting-order count and USDC balance (the owner must have an account: loading a\n * missing wrapper aborts the read). With `recordIds`, also those records. The queue must exist.\n */\nexport async function marketQueueState(\n\tclient: ReadClient,\n\tconfig: OrdersGeneratedConfig,\n\tmarketId: string,\n\topts: {\n\t\towner?: string;\n\t\tquoteCoinType?: string;\n\t\trecordIds?: readonly bigint[];\n\t\tqueueId?: string;\n\t} = {},\n): Promise<MarketQueueState> {\n\tconst queueId = queueIdOf(config, { expiryMarketId: marketId, queueId: opts.queueId });\n\tconst tx = new Transaction();\n\tlet next = 0;\n\tconst results: TransactionResult[] = [];\n\tconst add = (command: (tx: Transaction) => TransactionResult): number => {\n\t\tresults.push(tx.add(command));\n\t\treturn next++;\n\t};\n\tconst market = { market: marketId };\n\tconst onQueue = { queue: queueId };\n\tconst i = {\n\t\texpiry: add(expiryMarket.expiry({ config, arguments: market })),\n\t\tmintPaused: add(expiryMarket.mintPaused({ config, arguments: market })),\n\t\tcashBalance: add(expiryMarket.cashBalance({ config, arguments: market })),\n\t\trequiredCash: add(expiryMarket.requiredCash({ config, arguments: market })),\n\t\tbackingBufferLambda: add(expiryMarket.backingBufferLambda({ config, arguments: market })),\n\t\torderFlow: add(expiryMarket.orderFlowState({ config, arguments: market })),\n\t\tstuck: add(queue.queueStuck({ config, arguments: onQueue })),\n\t\tcohorts: add(queue.waitingCohorts({ config, arguments: onQueue })),\n\t\theads: add(queue.queueHeads({ config, arguments: onQueue })),\n\t\tpending: add(queue.pendingCounts({ config, arguments: onQueue })),\n\t\tpayout: add(queue.payoutProgress({ config, arguments: onQueue })),\n\t\tpolicy: add(desk.policy({ config })),\n\t\tdeskWatermark: add(desk.versionWatermark({ config })),\n\t\tnoTradeWindowMs: add(protocolConfig.noTradeWindowMs({ config })),\n\t\tsubsidyRate: add(protocolConfig.feeIncentiveSubsidyRate({ config })),\n\t\ttradingPaused: add(protocolConfig.tradingPaused({ config })),\n\t\tfrozen: add(protocolConfig.frozen({ config })),\n\t\twatermark: add(protocolConfig.versionWatermark({ config })),\n\t\torderFlowEnabled: add(\n\t\t\tprotocolConfig.isOrderFlow({ config, typeArguments: [orderFlowWitnessType(config)] }),\n\t\t),\n\t};\n\tlet accountIdx: { waiting: number; balance: number; accountId: string } | null = null;\n\tif (opts.owner) {\n\t\tif (!opts.quoteCoinType) throw new Error('marketQueueState: owner reads need quoteCoinType');\n\t\tconst accountId = deriveAccountIdFrom(config, opts.owner);\n\t\tconst waiting = add(queue.waitingOrders({ config, arguments: { ...onQueue, accountId } }));\n\t\tconst loaded = add(\n\t\t\taccount.loadAccount({\n\t\t\t\tconfig,\n\t\t\t\targuments: { self: deriveAccountWrapperIdFrom(config, opts.owner) },\n\t\t\t}),\n\t\t);\n\t\tconst balance = add(\n\t\t\taccount.balance({\n\t\t\t\tconfig,\n\t\t\t\ttypeArguments: [opts.quoteCoinType],\n\t\t\t\targuments: { self: results[loaded] },\n\t\t\t}),\n\t\t);\n\t\taccountIdx = { waiting, balance, accountId };\n\t}\n\tconst recordIdx = (opts.recordIds ?? []).map((recordId) =>\n\t\tadd(queue.order({ config, arguments: { ...onQueue, recordId } })),\n\t);\n\n\tconst cmds = await inspectReturns(client, tx);\n\tconst u64 = (idx: number, value = 0) => parseU64LE(cmds[idx][value]);\n\tconst cashBalance = u64(i.cashBalance);\n\tconst requiredCash = u64(i.requiredCash);\n\treturn {\n\t\tmarketId: normalizeSuiAddress(marketId),\n\t\tqueueId: normalizeSuiAddress(queueId),\n\t\texpiryMs: u64(i.expiry),\n\t\tmintPaused: parseBool(cmds[i.mintPaused][0]),\n\t\tcashBalance,\n\t\trequiredCash,\n\t\tspareCash: cashBalance > requiredCash ? cashBalance - requiredCash : 0n,\n\t\twaitingCashNeed: u64(i.orderFlow, 0),\n\t\tpayoutTreeNodeCount: u64(i.orderFlow, 1),\n\t\tminEntryProbability: u64(i.orderFlow, 2),\n\t\tbackingBufferLambda: u64(i.backingBufferLambda),\n\t\tstuck: parseBool(cmds[i.stuck][0]),\n\t\tcohorts: {\n\t\t\tcount: u64(i.cohorts, 0),\n\t\t\toldestUncommittedTauMs: parseOptionalU64(cmds[i.cohorts][1]),\n\t\t\toldestUncommittedTauAboveCommittedMs: parseOptionalU64(cmds[i.cohorts][2]),\n\t\t},\n\t\theads: {\n\t\t\tresolveHead: u64(i.heads, 0),\n\t\t\tnextId: u64(i.heads, 1),\n\t\t\tlastTauMs: u64(i.heads, 2),\n\t\t\tlastCommittedTauMs: u64(i.heads, 3),\n\t\t},\n\t\tpending: { mints: u64(i.pending, 0), sells: u64(i.pending, 1) },\n\t\tpayout: {\n\t\t\tcursor: u64(i.payout, 0),\n\t\t\tnextId: u64(i.payout, 1),\n\t\t\tcompleted: parseBool(cmds[i.payout][2]),\n\t\t},\n\t\tdesk: {\n\t\t\tid: normalizeSuiAddress(config.orderDesk),\n\t\t\tpolicy: policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[i.policy][0])),\n\t\t\tversionWatermark: u64(i.deskWatermark),\n\t\t},\n\t\tprotocol: {\n\t\t\tnoTradeWindowMs: u64(i.noTradeWindowMs),\n\t\t\tfeeIncentiveSubsidyRate: u64(i.subsidyRate),\n\t\t\ttradingPaused: parseBool(cmds[i.tradingPaused][0]),\n\t\t\tfrozen: parseBool(cmds[i.frozen][0]),\n\t\t\tversionWatermark: u64(i.watermark),\n\t\t\torderFlowEnabled: parseBool(cmds[i.orderFlowEnabled][0]),\n\t\t},\n\t\taccount: accountIdx\n\t\t\t? {\n\t\t\t\t\taccountId: accountIdx.accountId,\n\t\t\t\t\twaitingOrders: u64(accountIdx.waiting),\n\t\t\t\t\tavailableRaw: u64(accountIdx.balance),\n\t\t\t\t}\n\t\t\t: null,\n\t\trecords: recordIdx.map((idx) => OptionalOrderView.parse(cmds[idx][0]) ?? null),\n\t};\n}\n\n/** Queue records by record ID (`queue::order`), `null` for a missing or cleaned-up one. One simulate. */\nexport async function queuedOrders(\n\tclient: ReadClient,\n\tconfig: OrdersGeneratedConfig,\n\ttarget: QueueTarget,\n\trecordIds: readonly bigint[],\n): Promise<(QueuedOrder | null)[]> {\n\tif (recordIds.length === 0) return [];\n\tconst queueId = queueIdOf(config, target);\n\tconst tx = new Transaction();\n\tfor (const recordId of recordIds) {\n\t\ttx.add(queue.order({ config, arguments: { queue: queueId, recordId } }));\n\t}\n\tconst cmds = await inspectReturns(client, tx);\n\treturn cmds.map((rv) => OptionalOrderView.parse(rv[0]) ?? null);\n}\n\n/**\n * `ProtocolConfig.version_watermark`, read from the object's own BCS rather than a getter, so it\n * works against any package version: the getter only exists from the delayed-execution package\n * on, while the struct layout is frozen since v1.\n */\nexport async function versionWatermark(\n\tclient: ClientWithCoreApi,\n\tprotocolConfigId: string,\n): Promise<bigint> {\n\tconst { object } = await client.core.getObject({\n\t\tobjectId: protocolConfigId,\n\t\tinclude: { content: true },\n\t});\n\tif (!object.content) throw new Error(`ProtocolConfig ${protocolConfigId} returned no content`);\n\treturn protocolConfig.ProtocolConfig.parse(object.content).version_watermark;\n}\n\n/**\n * Which trade path a network is on:\n * - `'immediate'`: the watermark isn't raised and this SDK has no delayed-execution record, so\n * its call target is a pre-v4 Predict package. Use the immediate `mint*` / `redeem` builders.\n * - `'awaiting-cutover'`: the config records delayed execution but the watermark isn't raised.\n * Nothing trades: enqueue aborts `ECutoverNotReached`, and the immediate builders abort in the\n * v4 package the config calls (`EDelayedExecutionRequired`). Trading stays paused through the\n * cutover.\n * - `'delayed'`: the watermark is raised. Use the `enqueue*` builders; the immediate ones abort\n * `EDelayedExecutionRequired`.\n * - `'unsupported'`: the watermark is raised but this SDK's config has no delayed-execution\n * record for the network. Upgrade the SDK, or pass a config that records it.\n * - `'retired'`: the watermark is above the Predict code version the config calls\n * (`packages.predictCurrentVersion`, else `PREDICT_PACKAGE_VERSION`), so every version-gated\n * call aborts `EPackageVersionDisabled`.\n * Upgrade the SDK.\n */\nexport type ExecutionMode =\n\t'immediate' | 'awaiting-cutover' | 'delayed' | 'unsupported' | 'retired';\n\n/**\n * The {@link ExecutionMode} for a watermark and what the config records.\n * `recordsDelayedExecution`: the Predict upgrade, the order-flow companion and its desk, which\n * queued orders need. `recordsPredictUpgrade`: the Predict upgrade alone\n * (`packages.predictDelayedExecution`), which makes the config's Predict call target the package\n * that retired the immediate trades. It defaults to `recordsDelayedExecution`.\n */\nexport function executionModeFor(\n\twatermark: bigint,\n\trecordsDelayedExecution: boolean,\n\trecordsPredictUpgrade: boolean = recordsDelayedExecution,\n\tpredictCurrentVersion: bigint = PREDICT_PACKAGE_VERSION,\n): ExecutionMode {\n\tif (watermark >= DELAYED_EXECUTION_VERSION) {\n\t\tif (!recordsDelayedExecution) return 'unsupported';\n\t\treturn watermark > predictCurrentVersion ? 'retired' : 'delayed';\n\t}\n\treturn recordsDelayedExecution || recordsPredictUpgrade ? 'awaiting-cutover' : 'immediate';\n}\n\n/**\n * USDC sent to an account's wrapper address with `send_funds` that the account hasn't settled\n * yet: refunds, sell proceeds and settled payouts land here. `account::balance` already counts\n * them, so this is for display (\"pending funds\"), not for sizing.\n */\nexport async function pendingFunds(\n\tclient: ClientWithCoreApi,\n\twrapperId: string,\n\tcoinType: string,\n): Promise<bigint> {\n\tconst { balance } = await client.core.getBalance({ owner: wrapperId, coinType });\n\treturn BigInt(balance.addressBalance);\n}\n\n// The prefix of `pyth_lazer::state::State` up to the upgrade cap, identical in the testnet and\n// mainnet vendored sources. Parsing a prefix ignores the trailing `governance` field.\nconst LazerStatePrefix = bcs.struct('State', {\n\tid: bcs.Address,\n\ttrusted_signers: bcs.vector(\n\t\tbcs.struct('TrustedSignerInfo', { public_key: bcs.vector(bcs.u8()), expires_at: bcs.u64() }),\n\t),\n\tupgrade_cap: bcs.struct('UpgradeCap', {\n\t\tid: bcs.Address,\n\t\tpackage: bcs.Address,\n\t\tversion: bcs.u64(),\n\t\tpolicy: bcs.u8(),\n\t}),\n});\n\n/**\n * The current Pyth Lazer package (from `State.upgrade_cap.package`) and the original ID that\n * types `update::Update` (from the State's own type). Read it per filler batch and never cache\n * it: a Lazer upgrade retires the old package at once.\n */\nexport async function lazerPackages(\n\tclient: ClientWithCoreApi,\n\tstateId: string,\n): Promise<{ stateId: string; packageId: string; originalId: string }> {\n\tconst { object } = await client.core.getObject({ objectId: stateId, include: { content: true } });\n\tif (!object.content) throw new Error(`Lazer State ${stateId} returned no content`);\n\tconst [originalId, module, name] = object.type.split('::');\n\tif (module !== 'state' || name !== 'State') {\n\t\tthrow new Error(`${stateId} is a ${object.type}, not a Pyth Lazer State`);\n\t}\n\treturn {\n\t\tstateId: normalizeSuiAddress(stateId),\n\t\tpackageId: normalizeSuiAddress(LazerStatePrefix.parse(object.content).upgrade_cap.package),\n\t\toriginalId: normalizeSuiAddress(originalId),\n\t};\n}\n\n/** `expiry_market::RedeemQuote` with camelCase keys. `proceeds` is before the order fee. */\nexport interface RedeemOpenQuoteRaw {\n\tcloseQuantity: bigint;\n\tprobability: bigint;\n\tproceeds: bigint;\n\ttradingFee: bigint;\n\tbuilderFee: bigint;\n\tinventoryImpactRebate: bigint;\n}\n\n/**\n * Quote an early sell of an Open record at a fresh live pricer (`load_live_pricer`, then the\n * queue's `quote_redeem_open`, which prices through Predict's `quote_close`), and read the desk's\n * policy for the order fee. `proceeds` is before the order fee, with no congestion penalty.\n * Aborts `ERecordNotOpen` when the record isn't Open. It doesn't check that the wrapper's account\n * owns the record: the wrapper only supplies the builder code.\n */\nexport async function quoteRedeemOpen(\n\tclient: ReadClient,\n\tconfig: OrdersGeneratedConfig,\n\targs: QueueTarget & {\n\t\twrapperId: string;\n\t\trecordId: bigint;\n\t\tcloseQuantityRaw: bigint;\n\t} & MarketFeeds,\n): Promise<{ quote: RedeemOpenQuoteRaw; policy: DelayedExecutionPolicy }> {\n\tconst tx = new Transaction();\n\tconst pricer = tx.add(loadLivePricer(config, args));\n\ttx.add(\n\t\tquoteRedeemOpenCall({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tqueue: queueIdOf(config, args),\n\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\twrapper: args.wrapperId,\n\t\t\t\tpricer,\n\t\t\t\trecordId: args.recordId,\n\t\t\t\tcloseQuantity: args.closeQuantityRaw,\n\t\t\t},\n\t\t}),\n\t);\n\ttx.add(desk.policy({ config }));\n\tconst cmds = await inspectReturns(client, tx);\n\tconst q = expiryMarket.RedeemQuote.parse(cmds[1][0]);\n\treturn {\n\t\tquote: {\n\t\t\tcloseQuantity: q.close_quantity,\n\t\t\tprobability: q.probability,\n\t\t\tproceeds: q.proceeds,\n\t\t\ttradingFee: q.trading_fee,\n\t\t\tbuilderFee: q.builder_fee,\n\t\t\tinventoryImpactRebate: q.inventory_impact_rebate,\n\t\t},\n\t\tpolicy: policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[2][0])),\n\t};\n}\n\n/**\n * `expiry_market::MintQuote` with camelCase keys. `allInCost` includes `penaltyFee`, which the\n * delayed-execution package always quotes as 0: its quotes price like a queued fill.\n */\nexport interface MintQuoteRaw {\n\tquantity: bigint;\n\tentryProbability: bigint;\n\tpremium: bigint;\n\ttradingFee: bigint;\n\tfeeIncentiveSubsidy: bigint;\n\tbuilderFee: bigint;\n\tpenaltyFee: bigint;\n\tinventoryImpactCharge: bigint;\n\tallInCost: bigint;\n}\n\n/** What to quote: an exact quantity, a premium budget, or an all-in budget. */\nexport type MintQuoteRequest =\n\t| { shape: 'exact-quantity'; quantityRaw: bigint }\n\t| { shape: 'exact-amount'; maxPremiumRaw: bigint; minQuantityRaw: bigint }\n\t| { shape: 'exact-cost'; maxCostRaw: bigint; minQuantityRaw: bigint };\n\n/**\n * Quote a mint for one account without placing it: Predict's `quote_mint_for_account` (exact\n * quantity and premium budget) or `quote_mint_exact_cost_for_account` (all-in budget), at a fresh\n * live pricer. Both read the account's builder code and cap a budget at its balance. From the\n * delayed-execution package on they price like a queued fill at the clock: no congestion penalty,\n * and no trade-window or Pyth-staleness abort. They abort `EOrderFailsLimits` when the mint would\n * be refused at the clock. With `ordersConfig`, also reads the order desk's policy.\n */\nexport async function quoteMintForAccount(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\trequest: MintQuoteRequest;\n\t\t/** Also read the order desk's policy, in the same simulate. */\n\t\tordersConfig?: OrdersGeneratedConfig;\n\t} & MarketFeeds,\n): Promise<{ quote: MintQuoteRaw; policy: DelayedExecutionPolicy | null }> {\n\tconst tx = new Transaction();\n\tconst pricer = tx.add(loadLivePricer(config, args));\n\tconst base = {\n\t\tmarket: args.expiryMarketId,\n\t\twrapper: args.wrapperId,\n\t\tpricer,\n\t\tlowerTick: args.lowerTick,\n\t\thigherTick: args.higherTick,\n\t};\n\tconst r = args.request;\n\tif (r.shape === 'exact-cost') {\n\t\ttx.add(\n\t\t\texpiryMarket.quoteMintExactCostForAccount({\n\t\t\t\tconfig,\n\t\t\t\targuments: { ...base, maxCost: r.maxCostRaw, minQuantity: r.minQuantityRaw },\n\t\t\t}),\n\t\t);\n\t} else {\n\t\ttx.add(\n\t\t\texpiryMarket.quoteMintForAccount({\n\t\t\t\tconfig,\n\t\t\t\targuments:\n\t\t\t\t\tr.shape === 'exact-quantity'\n\t\t\t\t\t\t? { ...base, maxPremium: 0n, minQuantity: r.quantityRaw, exactQuantity: true }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\tmaxPremium: r.maxPremiumRaw,\n\t\t\t\t\t\t\t\tminQuantity: r.minQuantityRaw,\n\t\t\t\t\t\t\t\texactQuantity: false,\n\t\t\t\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\tif (args.ordersConfig) tx.add(desk.policy({ config: args.ordersConfig }));\n\tconst cmds = await inspectReturns(client, tx);\n\tconst q = expiryMarket.MintQuote.parse(cmds[1][0]);\n\tconst quote: MintQuoteRaw = {\n\t\tquantity: q.quantity,\n\t\tentryProbability: q.entry_probability,\n\t\tpremium: q.premium,\n\t\ttradingFee: q.trading_fee,\n\t\tfeeIncentiveSubsidy: q.fee_incentive_subsidy,\n\t\tbuilderFee: q.builder_fee,\n\t\tpenaltyFee: q.penalty_fee,\n\t\tinventoryImpactCharge: q.inventory_impact_charge,\n\t\tallInCost: q.all_in_cost,\n\t};\n\tconst policy = args.ordersConfig\n\t\t? policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[2][0]))\n\t\t: null;\n\treturn { quote, policy };\n}\n\n/** What `quote_mint` quotes: an exact quantity, or the largest quantity a premium budget buys. */\nexport type AnonymousMintQuoteRequest = Exclude<MintQuoteRequest, { shape: 'exact-cost' }>;\n\n/**\n * Quote a mint for no particular account: Predict's `quote_mint`, at a fresh live pricer. It\n * prices like a queued fill at the clock with no builder fee, so it previews a mint for a visitor\n * without an account or a funded balance. It has no all-in budget mode. It aborts\n * `EOrderFailsLimits` when the mint would be refused at the clock, for example below the 1 USDC\n * minimum premium. With `ordersConfig`, also reads the order desk's policy.\n */\nexport async function quoteMintAnonymous(\n\tclient: ReadClient,\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\trequest: AnonymousMintQuoteRequest;\n\t\tordersConfig?: OrdersGeneratedConfig;\n\t} & MarketFeeds,\n): Promise<{ quote: MintQuoteRaw; policy: DelayedExecutionPolicy | null }> {\n\tconst tx = new Transaction();\n\tconst pricer = tx.add(loadLivePricer(config, args));\n\tconst r = args.request;\n\ttx.add(\n\t\texpiryMarket.quoteMint({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\tpricer,\n\t\t\t\tlowerTick: args.lowerTick,\n\t\t\t\thigherTick: args.higherTick,\n\t\t\t\t...(r.shape === 'exact-quantity'\n\t\t\t\t\t? { maxPremium: 0n, minQuantity: r.quantityRaw, exactQuantity: true }\n\t\t\t\t\t: { maxPremium: r.maxPremiumRaw, minQuantity: r.minQuantityRaw, exactQuantity: false }),\n\t\t\t},\n\t\t}),\n\t);\n\tif (args.ordersConfig) tx.add(desk.policy({ config: args.ordersConfig }));\n\tconst cmds = await inspectReturns(client, tx);\n\tconst q = expiryMarket.MintQuote.parse(cmds[1][0]);\n\treturn {\n\t\tquote: {\n\t\t\tquantity: q.quantity,\n\t\t\tentryProbability: q.entry_probability,\n\t\t\tpremium: q.premium,\n\t\t\ttradingFee: q.trading_fee,\n\t\t\tfeeIncentiveSubsidy: q.fee_incentive_subsidy,\n\t\t\tbuilderFee: q.builder_fee,\n\t\t\tpenaltyFee: q.penalty_fee,\n\t\t\tinventoryImpactCharge: q.inventory_impact_charge,\n\t\t\tallInCost: q.all_in_cost,\n\t\t},\n\t\tpolicy: args.ordersConfig ? policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[2][0])) : null,\n\t};\n}\n\n/**\n * The order desk's policy and an owner's USDC balance, in one simulate. The queued exact-cost\n * quote needs both: enqueue escrows `min(max_cost, available − fee)`, while the chain quote caps\n * at the whole balance.\n */\nexport async function orderFeeAndBalance(\n\tclient: ReadClient,\n\tconfig: OrdersGeneratedConfig,\n\towner: string,\n\tcoinType: string,\n): Promise<{ policy: DelayedExecutionPolicy; availableRaw: bigint }> {\n\tconst tx = new Transaction();\n\ttx.add(desk.policy({ config }));\n\tconst loaded = tx.add(\n\t\taccount.loadAccount({ config, arguments: { self: deriveAccountWrapperIdFrom(config, owner) } }),\n\t);\n\ttx.add(account.balance({ config, typeArguments: [coinType], arguments: { self: loaded } }));\n\tconst cmds = await inspectReturns(client, tx);\n\treturn {\n\t\tpolicy: policyFromBcs(DelayedExecutionPolicyBcs.parse(cmds[0][0])),\n\t\tavailableRaw: parseU64LE(cmds[2][0]),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,MAAM,aAAa,WAAgC,MAAM,MAAM,OAAO;AACtE,MAAM,oBAAoB,IAAI,OAAOA,UAAa;;AAGlD,SAAgB,qBACf,QACC;AACD,QAAO,GAAG,OAAO,yBAAyB;;;;;;;;AAmF3C,eAAsB,iBACrB,QACA,QACA,UACA,OAKI,EAAE,EACsB;CAC5B,MAAM,UAAU,UAAU,QAAQ;EAAE,gBAAgB;EAAU,SAAS,KAAK;EAAS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,KAAK,GAAG,GAAG;EACpC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { depositFunds as depositFunds$1, withdrawFunds as withdrawFunds$1 } from "../../
|
|
1
|
+
import { depositFunds as depositFunds$1, withdrawFunds as withdrawFunds$1 } from "../../account-bindings/account.mjs";
|
|
2
2
|
import { withAuth } from "./common.mjs";
|
|
3
3
|
import { cancelSupplyRequest as cancelSupplyRequest$1, cancelWithdrawRequest as cancelWithdrawRequest$1, requestSupply as requestSupply$1, requestWithdraw as requestWithdraw$1 } from "../../contracts/deepbook_predict/plp.mjs";
|
|
4
4
|
import { setBuilderCode as setBuilderCode$1, unsetBuilderCode as unsetBuilderCode$1 } from "../../contracts/deepbook_predict/predict_account.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.d.mts","names":[],"sources":["../../../src/predict/tx/common.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"common.d.mts","names":[],"sources":["../../../src/predict/tx/common.ts"],"mappings":";;;;;;;AA2BA;;;;;iBAAgB,YAAA,CAAa,GAAA,EAAK,aAAA,IAAiB,EAAA,EAAI,WAAA,KAAgB,iBAAA;;iBAoEvD,sBAAA,CAAuB,GAAA,EAAK,aAAA,EAAe,KAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { generateAuth as generateAuth$1 } from "../../
|
|
1
|
+
import { generateAuth as generateAuth$1 } from "../../account-bindings/account.mjs";
|
|
2
2
|
import { AccountContract } from "../../account.mjs";
|
|
3
3
|
import { toGeneratedConfig } from "../config/generated.mjs";
|
|
4
4
|
import { bcs } from "@mysten/sui/bcs";
|
|
@@ -8,7 +8,8 @@ import { deriveObjectID } from "@mysten/sui/utils";
|
|
|
8
8
|
function accountContract(cfg) {
|
|
9
9
|
return new AccountContract({
|
|
10
10
|
accountPackageId: cfg.packages.account,
|
|
11
|
-
accountRegistry: cfg.objects.accountRegistry
|
|
11
|
+
accountRegistry: cfg.objects.accountRegistry,
|
|
12
|
+
accountPackageIdLatest: cfg.packages.accountLatest
|
|
12
13
|
});
|
|
13
14
|
}
|
|
14
15
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.mjs","names":["account.generateAuth"],"sources":["../../../src/predict/tx/common.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs } from '@mysten/sui/bcs';\nimport type { Transaction, TransactionArgument, TransactionResult } from '@mysten/sui/transactions';\nimport { deriveObjectID } from '@mysten/sui/utils';\nimport { toGeneratedConfig, type GeneratedConfig } from '../config/generated.js';\nimport type { PredictConfig } from '../config/index.js';\nimport { AccountContract, accountMoveCalls as account } from '../../account.js';\n\n// Predict's accounts ARE the shared on-chain account primitive (`packages/account`), so the\n// builders live in `@mysten/deepbook-v3/account` and this is the thin adapter that drives them with\n// Predict's deployed ids. The generated thunks are still used directly by `withAuth` below, which\n// wraps Predict's own entrypoints too — those take the same `Auth` hot potato.\nexport function accountContract(cfg: PredictConfig): AccountContract {\n\treturn new AccountContract({\n\t\taccountPackageId: cfg.packages.account,\n\t\taccountRegistry: cfg.objects.accountRegistry,\n\t});\n}\n\n/**\n * Owner authority is a hot-potato `Auth` minted from the tx sender (`ctx` is implicit in a PTB)\n * and consumed by the very next account-loading call (`load_account_mut` inside `deposit_funds` /\n * `withdraw_funds` / `mint` / …). It resolves to owner auth for whoever signs the transaction.\n * See `packages/account/sources/account.move`.\n */\nexport function generateAuth(cfg: PredictConfig): (tx: Transaction) => TransactionResult {\n\treturn account.generateAuth({ config: toGeneratedConfig(cfg) });\n}\n\n// The shape every generated binding shares: options in, one PTB command out.\ntype GeneratedCall<Options> = (options: Options) => (tx: Transaction) => TransactionResult;\n\n// The generated options of a call that consumes the hot-potato `Auth`. Codegen types\n// `arguments` as the named form OR a positional tuple; only the named form is used here.\ninterface AuthCallOptions {\n\targuments: { auth: TransactionArgument } | readonly unknown[];\n\tconfig?: object;\n\tpackage?: string;\n}\n\n// The named-`arguments` arm of such an options type (the tuple arm has no `auth` property).\ntype NamedArguments<Options extends AuthCallOptions> = Extract<\n\tOptions['arguments'],\n\t{ auth: TransactionArgument }\n>;\n\n/**\n * The options {@link withAuth} leaves to the caller: the generated ones, minus the `auth`\n * argument it supplies itself, with the projected config required (it is what mints the auth).\n * The config must also carry every key the wrapped call resolves, so a call into the order-flow\n * companion can't be handed a slice without its desk.\n */\nexport type WithAuthOptions<Options extends AuthCallOptions> = Omit<\n\tOptions,\n\t'arguments' | 'config'\n> & {\n\tconfig: GeneratedConfig & NonNullable<Options['config']>;\n\targuments: Omit<NamedArguments<Options>, 'auth'>;\n};\n\n/**\n * Every owner-authorized call in this SDK is the same two commands — mint the hot-potato `Auth`,\n * then make the generated call that consumes it. This lifts a generated binding into that pair,\n * so such a builder is declared rather than written: `withAuth(account.depositFunds)` takes\n * `deposit_funds`'s own options with the `auth` slot already filled.\n */\nexport function withAuth<Options extends AuthCallOptions>(\n\tcall: GeneratedCall<Options>,\n): (options: WithAuthOptions<Options>) => (tx: Transaction) => TransactionResult {\n\treturn (options) => (tx) => {\n\t\tconst auth = tx.add(account.generateAuth({ config: options.config }));\n\t\t// The one unchecked step: with `Options` still generic, TS cannot see that putting `auth`\n\t\t// back makes the arguments whole again. Callers get the fully checked type above.\n\t\treturn tx.add(\n\t\t\tcall({ ...options, arguments: { ...options.arguments, auth } } as unknown as Options),\n\t\t);\n\t};\n}\n\n// The derivation must agree with on-chain `derive_address`, so it is owned in one place:\n// `@mysten/deepbook-v3/account`. This projects Predict's config onto that contract.\nexport function deriveAccountWrapperIdFrom(\n\tconfig: Pick<GeneratedConfig, 'accountRegistry' | 'accountPackageId'>,\n\towner: string,\n): string {\n\treturn new AccountContract({\n\t\taccountPackageId: config.accountPackageId,\n\t\taccountRegistry: config.accountRegistry,\n\t}).deriveAccountWrapperId(owner);\n}\n\n/** The deterministic id of an owner's canonical account wrapper — no chain read needed. */\nexport function deriveAccountWrapperId(cfg: PredictConfig, owner: string): string {\n\treturn deriveAccountWrapperIdFrom(toGeneratedConfig(cfg), owner);\n}\n\n// `account_registry::AccountKey(owner)`: a one-field positional struct, so its BCS is the bare\n// 32-byte address.\nconst AccountKey = bcs.struct('AccountKey', { pos0: bcs.Address });\n\n/**\n * The owner's canonical ACCOUNT id (`Account.account_id`), a different derived object from the\n * wrapper: `derive_address(registry, AccountKey(owner))`. Queue records and events name accounts\n * by it, and `queue::waiting_orders` takes it.\n */\nexport function deriveAccountIdFrom(\n\tconfig: Pick<GeneratedConfig, 'accountRegistry' | 'accountPackageId'>,\n\towner: string,\n): string {\n\treturn deriveObjectID(\n\t\tconfig.accountRegistry,\n\t\t`${config.accountPackageId}::account_registry::AccountKey`,\n\t\tAccountKey.serialize({ pos0: owner }).toBytes(),\n\t);\n}\n"],"mappings":";;;;;;;AAaA,SAAgB,gBAAgB,KAAqC;AACpE,QAAO,IAAI,gBAAgB;EAC1B,kBAAkB,IAAI,SAAS;EAC/B,iBAAiB,IAAI,QAAQ;EAC7B,CAAC;;;;;;;;AASH,SAAgB,aAAa,KAA4D;AACxF,QAAOA,eAAqB,EAAE,QAAQ,kBAAkB,IAAI,EAAE,CAAC;;;;;;;;AAwChE,SAAgB,SACf,MACgF;AAChF,SAAQ,aAAa,OAAO;EAC3B,MAAM,OAAO,GAAG,IAAIA,eAAqB,EAAE,QAAQ,QAAQ,QAAQ,CAAC,CAAC;AAGrE,SAAO,GAAG,IACT,KAAK;GAAE,GAAG;GAAS,WAAW;IAAE,GAAG,QAAQ;IAAW;IAAM;GAAE,CAAuB,CACrF;;;AAMH,SAAgB,2BACf,QACA,OACS;
|
|
1
|
+
{"version":3,"file":"common.mjs","names":["account.generateAuth"],"sources":["../../../src/predict/tx/common.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs } from '@mysten/sui/bcs';\nimport type { Transaction, TransactionArgument, TransactionResult } from '@mysten/sui/transactions';\nimport { deriveObjectID } from '@mysten/sui/utils';\nimport { toGeneratedConfig, type GeneratedConfig } from '../config/generated.js';\nimport type { PredictConfig } from '../config/index.js';\nimport { AccountContract, accountMoveCalls as account } from '../../account.js';\n\n// Predict's accounts ARE the shared on-chain account primitive (`packages/account`), so the\n// builders live in `@mysten/deepbook-v3/account` and this is the thin adapter that drives them with\n// Predict's deployed ids. The generated thunks are still used directly by `withAuth` below, which\n// wraps Predict's own entrypoints too — those take the same `Auth` hot potato.\nexport function accountContract(cfg: PredictConfig): AccountContract {\n\treturn new AccountContract({\n\t\taccountPackageId: cfg.packages.account,\n\t\taccountRegistry: cfg.objects.accountRegistry,\n\t\taccountPackageIdLatest: cfg.packages.accountLatest,\n\t});\n}\n\n/**\n * Owner authority is a hot-potato `Auth` minted from the tx sender (`ctx` is implicit in a PTB)\n * and consumed by the very next account-loading call (`load_account_mut` inside `deposit_funds` /\n * `withdraw_funds` / `mint` / …). It resolves to owner auth for whoever signs the transaction.\n * See `packages/account/sources/account.move`.\n */\nexport function generateAuth(cfg: PredictConfig): (tx: Transaction) => TransactionResult {\n\treturn account.generateAuth({ config: toGeneratedConfig(cfg) });\n}\n\n// The shape every generated binding shares: options in, one PTB command out.\ntype GeneratedCall<Options> = (options: Options) => (tx: Transaction) => TransactionResult;\n\n// The generated options of a call that consumes the hot-potato `Auth`. Codegen types\n// `arguments` as the named form OR a positional tuple; only the named form is used here.\ninterface AuthCallOptions {\n\targuments: { auth: TransactionArgument } | readonly unknown[];\n\tconfig?: object;\n\tpackage?: string;\n}\n\n// The named-`arguments` arm of such an options type (the tuple arm has no `auth` property).\ntype NamedArguments<Options extends AuthCallOptions> = Extract<\n\tOptions['arguments'],\n\t{ auth: TransactionArgument }\n>;\n\n/**\n * The options {@link withAuth} leaves to the caller: the generated ones, minus the `auth`\n * argument it supplies itself, with the projected config required (it is what mints the auth).\n * The config must also carry every key the wrapped call resolves, so a call into the order-flow\n * companion can't be handed a slice without its desk.\n */\nexport type WithAuthOptions<Options extends AuthCallOptions> = Omit<\n\tOptions,\n\t'arguments' | 'config'\n> & {\n\tconfig: GeneratedConfig & NonNullable<Options['config']>;\n\targuments: Omit<NamedArguments<Options>, 'auth'>;\n};\n\n/**\n * Every owner-authorized call in this SDK is the same two commands — mint the hot-potato `Auth`,\n * then make the generated call that consumes it. This lifts a generated binding into that pair,\n * so such a builder is declared rather than written: `withAuth(account.depositFunds)` takes\n * `deposit_funds`'s own options with the `auth` slot already filled.\n */\nexport function withAuth<Options extends AuthCallOptions>(\n\tcall: GeneratedCall<Options>,\n): (options: WithAuthOptions<Options>) => (tx: Transaction) => TransactionResult {\n\treturn (options) => (tx) => {\n\t\tconst auth = tx.add(account.generateAuth({ config: options.config }));\n\t\t// The one unchecked step: with `Options` still generic, TS cannot see that putting `auth`\n\t\t// back makes the arguments whole again. Callers get the fully checked type above.\n\t\treturn tx.add(\n\t\t\tcall({ ...options, arguments: { ...options.arguments, auth } } as unknown as Options),\n\t\t);\n\t};\n}\n\n// The derivation must agree with on-chain `derive_address`, so it is owned in one place:\n// `@mysten/deepbook-v3/account`. This projects Predict's config onto that contract.\nexport function deriveAccountWrapperIdFrom(\n\tconfig: Pick<GeneratedConfig, 'accountRegistry' | 'accountPackageId'>,\n\towner: string,\n): string {\n\t// The original ID: the key type's defining package, whatever account version runs.\n\treturn new AccountContract({\n\t\taccountPackageId: config.accountPackageId,\n\t\taccountRegistry: config.accountRegistry,\n\t}).deriveAccountWrapperId(owner);\n}\n\n/** The deterministic id of an owner's canonical account wrapper — no chain read needed. */\nexport function deriveAccountWrapperId(cfg: PredictConfig, owner: string): string {\n\treturn deriveAccountWrapperIdFrom(toGeneratedConfig(cfg), owner);\n}\n\n// `account_registry::AccountKey(owner)`: a one-field positional struct, so its BCS is the bare\n// 32-byte address.\nconst AccountKey = bcs.struct('AccountKey', { pos0: bcs.Address });\n\n/**\n * The owner's canonical ACCOUNT id (`Account.account_id`), a different derived object from the\n * wrapper: `derive_address(registry, AccountKey(owner))`. Queue records and events name accounts\n * by it, and `queue::waiting_orders` takes it.\n */\nexport function deriveAccountIdFrom(\n\tconfig: Pick<GeneratedConfig, 'accountRegistry' | 'accountPackageId'>,\n\towner: string,\n): string {\n\treturn deriveObjectID(\n\t\tconfig.accountRegistry,\n\t\t`${config.accountPackageId}::account_registry::AccountKey`,\n\t\tAccountKey.serialize({ pos0: owner }).toBytes(),\n\t);\n}\n"],"mappings":";;;;;;;AAaA,SAAgB,gBAAgB,KAAqC;AACpE,QAAO,IAAI,gBAAgB;EAC1B,kBAAkB,IAAI,SAAS;EAC/B,iBAAiB,IAAI,QAAQ;EAC7B,wBAAwB,IAAI,SAAS;EACrC,CAAC;;;;;;;;AASH,SAAgB,aAAa,KAA4D;AACxF,QAAOA,eAAqB,EAAE,QAAQ,kBAAkB,IAAI,EAAE,CAAC;;;;;;;;AAwChE,SAAgB,SACf,MACgF;AAChF,SAAQ,aAAa,OAAO;EAC3B,MAAM,OAAO,GAAG,IAAIA,eAAqB,EAAE,QAAQ,QAAQ,QAAQ,CAAC,CAAC;AAGrE,SAAO,GAAG,IACT,KAAK;GAAE,GAAG;GAAS,WAAW;IAAE,GAAG,QAAQ;IAAW;IAAM;GAAE,CAAuB,CACrF;;;AAMH,SAAgB,2BACf,QACA,OACS;AAET,QAAO,IAAI,gBAAgB;EAC1B,kBAAkB,OAAO;EACzB,iBAAiB,OAAO;EACxB,CAAC,CAAC,uBAAuB,MAAM;;;AAIjC,SAAgB,uBAAuB,KAAoB,OAAuB;AACjF,QAAO,2BAA2B,kBAAkB,IAAI,EAAE,MAAM;;AAKjE,MAAM,aAAa,IAAI,OAAO,cAAc,EAAE,MAAM,IAAI,SAAS,CAAC;;;;;;AAOlE,SAAgB,oBACf,QACA,OACS;AACT,QAAO,eACN,OAAO,iBACP,GAAG,OAAO,iBAAiB,iCAC3B,WAAW,UAAU,EAAE,MAAM,OAAO,CAAC,CAAC,SAAS,CAC/C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trade.d.mts","names":[],"sources":["../../../src/predict/tx/trade.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"trade.d.mts","names":[],"sources":["../../../src/predict/tx/trade.ts"],"mappings":";;;;UAoBiB,WAAA;EAChB,QAAA;EACA,sBAAA;EACA,oBAAA;AAAA;AAAA,iBASe,cAAA,CACf,MAAA,EAAQ,eAAA,EACR,IAAA;EAAQ,cAAA;AAAA,IAA2B,WAAA,IAChC,EAAA,EAAI,WAAA,KAAgB,iBAAA"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { generateAuth } from "../../
|
|
1
|
+
import { generateAuth } from "../../account-bindings/account.mjs";
|
|
2
2
|
import { U64_MAX } from "../units.mjs";
|
|
3
3
|
import { withAuth } from "./common.mjs";
|
|
4
|
-
import { loadLivePricer as loadLivePricer$1, mintExactAmount as mintExactAmount$1, mintExactCost as mintExactCost$1, mintExactQuantity as mintExactQuantity$1, redeemLive as redeemLive$1
|
|
4
|
+
import { loadLivePricer as loadLivePricer$1, mintExactAmount as mintExactAmount$1, mintExactCost as mintExactCost$1, mintExactQuantity as mintExactQuantity$1, redeemLive as redeemLive$1 } from "../../contracts/deepbook_predict/expiry_market.mjs";
|
|
5
|
+
import { redeemSettled as redeemSettled$1 } from "../bindings/expiry-market.mjs";
|
|
5
6
|
|
|
6
7
|
//#region src/predict/tx/trade.ts
|
|
7
8
|
const authed = { redeemSettled: withAuth(redeemSettled$1) };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trade.mjs","names":["expiryMarket.redeemSettled","expiryMarket.loadLivePricer","account.generateAuth","expiryMarket.mintExactQuantity","expiryMarket.mintExactAmount","expiryMarket.mintExactCost","expiryMarket.redeemLive"],"sources":["../../../src/predict/tx/trade.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport type { Transaction, TransactionResult } from '@mysten/sui/transactions';\nimport type { GeneratedConfig } from '../config/generated.js';\nimport { U64_MAX } from '../units.js';\nimport { accountMoveCalls as account } from '../../account.js';\nimport * as expiryMarket from '../../contracts/deepbook_predict/expiry_market.js';\nimport { withAuth } from './common.js';\n\n// The trade calls with their `auth` argument already supplied (see `withAuth`): each\n// takes its generated options minus that slot and expands to auth → call.\nconst authed = {\n\tredeemSettled: withAuth(expiryMarket.redeemSettled),\n};\n\n// The oracle feed object ids a live market's pricer reads. Grouped so callers pass one\n// bundle; the deployment's per-underlying ids live in `cfg.underlyings[symbol]` (see\n// `src/config/testnet.ts`), named to match `deployment.testnet.json`.\nexport interface MarketFeeds {\n\tpythFeed: string;\n\tblockScholesValueStore: string;\n\tblockScholesSviStore: string;\n}\n\n// Load a fresh `Pricer` from the live oracle feeds. Every live-flow trade call\n// (`mint_*`, `redeem_live`) and every live quote (`quote_mint*`, the queue's `quote_redeem_open`) borrows\n// this `&Pricer` and it must be loaded first in the PTB. Queued orders (`enqueue_*`) don't take\n// one: they read the oracle objects directly. Deployed sig `load_live_pricer` (expiry_market.move): market, config,\n// propbook_registry (&OracleRegistry), pyth, bs_values, bs_svi, clock (auto-injected).\n// `config` and `propbook_registry` are supplied by the config slice, not named here.\nexport function loadLivePricer(\n\tconfig: GeneratedConfig,\n\targs: { expiryMarketId: string } & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn (tx) =>\n\t\ttx.add(\n\t\t\texpiryMarket.loadLivePricer({\n\t\t\t\tconfig,\n\t\t\t\targuments: {\n\t\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\t\tpyth: args.pythFeed,\n\t\t\t\t\tbsValues: args.blockScholesValueStore,\n\t\t\t\t\tbsSvi: args.blockScholesSviStore,\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n}\n\n// The three commands every live-flow trade is: load a fresh market-bound `Pricer`, mint\n// owner auth, then the one `expiry_market::*` call that consumes both.\n//\n// The live trades are retired: Predict v4 keeps their published signatures but names every\n// parameter with a leading underscore, which codegen renders as a capitalized key (`_market` →\n// `Market`). So the auth is minted here and passed as `Auth`, rather than through `withAuth`.\n// The emitted commands are unchanged, and still reach a pre-v4 package.\nfunction liveTrade(\n\tconfig: GeneratedConfig,\n\targs: { expiryMarketId: string } & MarketFeeds,\n\tbuild: (\n\t\tpricer: TransactionResult,\n\t\tauth: TransactionResult,\n\t) => (tx: Transaction) => TransactionResult,\n): (tx: Transaction) => TransactionResult {\n\treturn (tx) => {\n\t\tconst pricer = tx.add(loadLivePricer(config, args));\n\t\tconst auth = tx.add(account.generateAuth({ config }));\n\t\treturn tx.add(build(pricer, auth));\n\t};\n}\n\n// Mint a position of an exact `quantityRaw`, capped by cost/probability ceilings,\n// returning the new order id (u256). Command order is pricer → auth → mint (auth is a\n// hot potato consumed by this call). `maxCostRaw`/`maxProbabilityRaw` default to\n// `U64_MAX` (no slippage cap). Deployed sig `mint_exact_quantity`.\n/**\n * @deprecated Retired by delayed execution (DBU-885): Predict v4's `mint_exact_quantity` always\n * aborts `EDelayedExecutionRequired`, so this works only while the config's call target is a\n * pre-v4 package. Use `enqueueExactQuantity` from `tx/queue.ts`.\n */\nexport function mintExactQuantity(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tquantityRaw: bigint;\n\t\tmaxCostRaw?: bigint;\n\t\tmaxProbabilityRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer, auth) =>\n\t\texpiryMarket.mintExactQuantity({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tMarket: args.expiryMarketId,\n\t\t\t\tWrapper: args.wrapperId,\n\t\t\t\tAuth: auth,\n\t\t\t\tPricer: pricer,\n\t\t\t\tLowerTick: args.lowerTick,\n\t\t\t\tHigherTick: args.higherTick,\n\t\t\t\tQuantity: args.quantityRaw,\n\t\t\t\tMaxCost: args.maxCostRaw ?? U64_MAX,\n\t\t\t\tMaxProbability: args.maxProbabilityRaw ?? U64_MAX,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Mint by spending up to `maxPremiumRaw` (raw quote units), enforcing a `minQuantityRaw`\n// floor on the position received and a `maxCostRaw` all-in ceiling, returning the new\n// order id (u256). Command order is pricer → auth → mint. Deployed sig\n// `mint_exact_amount`: …, max_premium, min_quantity, max_cost, root.\n/**\n * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n * (`EDelayedExecutionRequired`). Use `enqueueExactAmount`.\n */\nexport function mintExactAmount(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tmaxPremiumRaw: bigint;\n\t\tminQuantityRaw: bigint;\n\t\tmaxCostRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer, auth) =>\n\t\texpiryMarket.mintExactAmount({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tMarket: args.expiryMarketId,\n\t\t\t\tWrapper: args.wrapperId,\n\t\t\t\tAuth: auth,\n\t\t\t\tPricer: pricer,\n\t\t\t\tLowerTick: args.lowerTick,\n\t\t\t\tHigherTick: args.higherTick,\n\t\t\t\tMaxPremium: args.maxPremiumRaw,\n\t\t\t\tMinQuantity: args.minQuantityRaw,\n\t\t\t\tMaxCost: args.maxCostRaw ?? U64_MAX,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/**\n * Mint within an all-in budget, including fees, using the v2 entrypoint.\n * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n * (`EDelayedExecutionRequired`). Use `enqueueExactCost`.\n */\nexport function mintExactCost(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tmaxCostRaw: bigint;\n\t\tminQuantityRaw: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer, auth) =>\n\t\texpiryMarket.mintExactCost({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tMarket: args.expiryMarketId,\n\t\t\t\tWrapper: args.wrapperId,\n\t\t\t\tAuth: auth,\n\t\t\t\tPricer: pricer,\n\t\t\t\tLowerTick: args.lowerTick,\n\t\t\t\tHigherTick: args.higherTick,\n\t\t\t\tMaxCost: args.maxCostRaw,\n\t\t\t\tMinQuantity: args.minQuantityRaw,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Owner-authorized redeem of a live (not-yet-settled) position: close `closeQuantityRaw`\n// of `orderId` at the live pricer's mark, enforcing close-side slippage floors\n// (`minProbabilityRaw`/`minProceedsRaw`, default 0 = uncapped). Returns `Option<u256>`:\n// the replacement order id when a partial close leaves quantity open, else none. Command\n// order is pricer → auth → redeem. Deployed sig `redeem_live`.\n/**\n * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n * (`EDelayedExecutionRequired`). Account positions then have no early exit; queued fills are Open\n * records sold with `enqueueRedeemOpen`.\n */\nexport function redeemLive(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\torderId: bigint;\n\t\tcloseQuantityRaw: bigint;\n\t\tminProbabilityRaw?: bigint;\n\t\tminProceedsRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer, auth) =>\n\t\texpiryMarket.redeemLive({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tMarket: args.expiryMarketId,\n\t\t\t\tWrapper: args.wrapperId,\n\t\t\t\tAuth: auth,\n\t\t\t\tPricer: pricer,\n\t\t\t\tOrderId: args.orderId,\n\t\t\t\tCloseQuantity: args.closeQuantityRaw,\n\t\t\t\tMinProbability: args.minProbabilityRaw ?? 0n,\n\t\t\t\tMinProceeds: args.minProceedsRaw ?? 0n,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Unchanged by delayed execution: still pays settled positions held in the account. It doesn't\n// pay Open queue records, which the queue's `settle_step` pays at settlement.\n//\n// Owner-authorized redeem of a settled position: closes `orderId` IN FULL against the\n// recorded settlement price (the deployed entrypoint takes no quantity — a settled claim\n// is all-or-nothing). No live pricer (settlement price is fixed); auth is consumed by the\n// call. Deployed sig `redeem_settled` (owner-auth form). The keeper-facing\n// `redeem_settled_permissionless` is a separate entrypoint, out of scope for this SDK.\nexport function redeemSettled(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\torderId: bigint;\n\t},\n): (tx: Transaction) => TransactionResult {\n\treturn authed.redeemSettled({\n\t\tconfig,\n\t\targuments: {\n\t\t\tmarket: args.expiryMarketId,\n\t\t\twrapper: args.wrapperId,\n\t\t\torderId: args.orderId,\n\t\t},\n\t});\n}\n"],"mappings":";;;;;;AAWA,MAAM,SAAS,EACd,eAAe,SAASA,gBAA2B,EACnD;AAiBD,SAAgB,eACf,QACA,MACyC;AACzC,SAAQ,OACP,GAAG,IACFC,iBAA4B;EAC3B;EACA,WAAW;GACV,QAAQ,KAAK;GACb,MAAM,KAAK;GACX,UAAU,KAAK;GACf,OAAO,KAAK;GACZ;EACD,CAAC,CACF;;AAUH,SAAS,UACR,QACA,MACA,OAIyC;AACzC,SAAQ,OAAO;EACd,MAAM,SAAS,GAAG,IAAI,eAAe,QAAQ,KAAK,CAAC;EACnD,MAAM,OAAO,GAAG,IAAIC,aAAqB,EAAE,QAAQ,CAAC,CAAC;AACrD,SAAO,GAAG,IAAI,MAAM,QAAQ,KAAK,CAAC;;;;;;;;AAapC,SAAgB,kBACf,QACA,MASyC;AACzC,QAAO,UAAU,QAAQ,OAAO,QAAQ,SACvCC,oBAA+B;EAC9B;EACA,WAAW;GACV,QAAQ,KAAK;GACb,SAAS,KAAK;GACd,MAAM;GACN,QAAQ;GACR,WAAW,KAAK;GAChB,YAAY,KAAK;GACjB,UAAU,KAAK;GACf,SAAS,KAAK,cAAc;GAC5B,gBAAgB,KAAK,qBAAqB;GAC1C;EACD,CAAC,CACF;;;;;;AAWF,SAAgB,gBACf,QACA,MASyC;AACzC,QAAO,UAAU,QAAQ,OAAO,QAAQ,SACvCC,kBAA6B;EAC5B;EACA,WAAW;GACV,QAAQ,KAAK;GACb,SAAS,KAAK;GACd,MAAM;GACN,QAAQ;GACR,WAAW,KAAK;GAChB,YAAY,KAAK;GACjB,YAAY,KAAK;GACjB,aAAa,KAAK;GAClB,SAAS,KAAK,cAAc;GAC5B;EACD,CAAC,CACF;;;;;;;AAQF,SAAgB,cACf,QACA,MAQyC;AACzC,QAAO,UAAU,QAAQ,OAAO,QAAQ,SACvCC,gBAA2B;EAC1B;EACA,WAAW;GACV,QAAQ,KAAK;GACb,SAAS,KAAK;GACd,MAAM;GACN,QAAQ;GACR,WAAW,KAAK;GAChB,YAAY,KAAK;GACjB,SAAS,KAAK;GACd,aAAa,KAAK;GAClB;EACD,CAAC,CACF;;;;;;;AAaF,SAAgB,WACf,QACA,MAQyC;AACzC,QAAO,UAAU,QAAQ,OAAO,QAAQ,SACvCC,aAAwB;EACvB;EACA,WAAW;GACV,QAAQ,KAAK;GACb,SAAS,KAAK;GACd,MAAM;GACN,QAAQ;GACR,SAAS,KAAK;GACd,eAAe,KAAK;GACpB,gBAAgB,KAAK,qBAAqB;GAC1C,aAAa,KAAK,kBAAkB;GACpC;EACD,CAAC,CACF;;AAWF,SAAgB,cACf,QACA,MAKyC;AACzC,QAAO,OAAO,cAAc;EAC3B;EACA,WAAW;GACV,QAAQ,KAAK;GACb,SAAS,KAAK;GACd,SAAS,KAAK;GACd;EACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"trade.mjs","names":["expiryMarketBindings.redeemSettled","expiryMarket.loadLivePricer","account.generateAuth","expiryMarket.mintExactQuantity","expiryMarket.mintExactAmount","expiryMarket.mintExactCost","expiryMarket.redeemLive"],"sources":["../../../src/predict/tx/trade.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport type { Transaction, TransactionResult } from '@mysten/sui/transactions';\nimport type { GeneratedConfig } from '../config/generated.js';\nimport { U64_MAX } from '../units.js';\nimport { accountMoveCalls as account } from '../../account.js';\nimport * as expiryMarket from '../../contracts/deepbook_predict/expiry_market.js';\nimport * as expiryMarketBindings from '../bindings/expiry-market.js';\nimport { withAuth } from './common.js';\n\n// The trade calls with their `auth` argument already supplied (see `withAuth`): each\n// takes its generated options minus that slot and expands to auth → call.\nconst authed = {\n\t// The shipped argument keys: Predict v5 underscore-prefixed the retired call's parameters.\n\tredeemSettled: withAuth(expiryMarketBindings.redeemSettled),\n};\n\n// The oracle feed object ids a live market's pricer reads. Grouped so callers pass one\n// bundle; the deployment's per-underlying ids live in `cfg.underlyings[symbol]` (see\n// `src/config/testnet.ts`), named to match `deployment.testnet.json`.\nexport interface MarketFeeds {\n\tpythFeed: string;\n\tblockScholesValueStore: string;\n\tblockScholesSviStore: string;\n}\n\n// Load a fresh `Pricer` from the live oracle feeds. Every live-flow trade call\n// (`mint_*`, `redeem_live`) and every live quote (`quote_mint*`, the queue's `quote_redeem_open`) borrows\n// this `&Pricer` and it must be loaded first in the PTB. Queued orders (`enqueue_*`) don't take\n// one: they read the oracle objects directly. Deployed sig `load_live_pricer` (expiry_market.move): market, config,\n// propbook_registry (&OracleRegistry), pyth, bs_values, bs_svi, clock (auto-injected).\n// `config` and `propbook_registry` are supplied by the config slice, not named here.\nexport function loadLivePricer(\n\tconfig: GeneratedConfig,\n\targs: { expiryMarketId: string } & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn (tx) =>\n\t\ttx.add(\n\t\t\texpiryMarket.loadLivePricer({\n\t\t\t\tconfig,\n\t\t\t\targuments: {\n\t\t\t\t\tmarket: args.expiryMarketId,\n\t\t\t\t\tpyth: args.pythFeed,\n\t\t\t\t\tbsValues: args.blockScholesValueStore,\n\t\t\t\t\tbsSvi: args.blockScholesSviStore,\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n}\n\n// The three commands every live-flow trade is: load a fresh market-bound `Pricer`, mint\n// owner auth, then the one `expiry_market::*` call that consumes both.\n//\n// The live trades are retired: Predict v4 keeps their published signatures but names every\n// parameter with a leading underscore, which codegen renders as a capitalized key (`_market` →\n// `Market`). So the auth is minted here and passed as `Auth`, rather than through `withAuth`.\n// The emitted commands are unchanged, and still reach a pre-v4 package.\nfunction liveTrade(\n\tconfig: GeneratedConfig,\n\targs: { expiryMarketId: string } & MarketFeeds,\n\tbuild: (\n\t\tpricer: TransactionResult,\n\t\tauth: TransactionResult,\n\t) => (tx: Transaction) => TransactionResult,\n): (tx: Transaction) => TransactionResult {\n\treturn (tx) => {\n\t\tconst pricer = tx.add(loadLivePricer(config, args));\n\t\tconst auth = tx.add(account.generateAuth({ config }));\n\t\treturn tx.add(build(pricer, auth));\n\t};\n}\n\n// Mint a position of an exact `quantityRaw`, capped by cost/probability ceilings,\n// returning the new order id (u256). Command order is pricer → auth → mint (auth is a\n// hot potato consumed by this call). `maxCostRaw`/`maxProbabilityRaw` default to\n// `U64_MAX` (no slippage cap). Deployed sig `mint_exact_quantity`.\n/**\n * @deprecated Retired by delayed execution (DBU-885): Predict v4's `mint_exact_quantity` always\n * aborts `EDelayedExecutionRequired`, so this works only while the config's call target is a\n * pre-v4 package. Use `enqueueExactQuantity` from `tx/queue.ts`.\n */\nexport function mintExactQuantity(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tquantityRaw: bigint;\n\t\tmaxCostRaw?: bigint;\n\t\tmaxProbabilityRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer, auth) =>\n\t\texpiryMarket.mintExactQuantity({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tMarket: args.expiryMarketId,\n\t\t\t\tWrapper: args.wrapperId,\n\t\t\t\tAuth: auth,\n\t\t\t\tPricer: pricer,\n\t\t\t\tLowerTick: args.lowerTick,\n\t\t\t\tHigherTick: args.higherTick,\n\t\t\t\tQuantity: args.quantityRaw,\n\t\t\t\tMaxCost: args.maxCostRaw ?? U64_MAX,\n\t\t\t\tMaxProbability: args.maxProbabilityRaw ?? U64_MAX,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Mint by spending up to `maxPremiumRaw` (raw quote units), enforcing a `minQuantityRaw`\n// floor on the position received and a `maxCostRaw` all-in ceiling, returning the new\n// order id (u256). Command order is pricer → auth → mint. Deployed sig\n// `mint_exact_amount`: …, max_premium, min_quantity, max_cost, root.\n/**\n * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n * (`EDelayedExecutionRequired`). Use `enqueueExactAmount`.\n */\nexport function mintExactAmount(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tmaxPremiumRaw: bigint;\n\t\tminQuantityRaw: bigint;\n\t\tmaxCostRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer, auth) =>\n\t\texpiryMarket.mintExactAmount({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tMarket: args.expiryMarketId,\n\t\t\t\tWrapper: args.wrapperId,\n\t\t\t\tAuth: auth,\n\t\t\t\tPricer: pricer,\n\t\t\t\tLowerTick: args.lowerTick,\n\t\t\t\tHigherTick: args.higherTick,\n\t\t\t\tMaxPremium: args.maxPremiumRaw,\n\t\t\t\tMinQuantity: args.minQuantityRaw,\n\t\t\t\tMaxCost: args.maxCostRaw ?? U64_MAX,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/**\n * Mint within an all-in budget, including fees, using the v2 entrypoint.\n * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n * (`EDelayedExecutionRequired`). Use `enqueueExactCost`.\n */\nexport function mintExactCost(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tlowerTick: bigint;\n\t\thigherTick: bigint;\n\t\tmaxCostRaw: bigint;\n\t\tminQuantityRaw: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer, auth) =>\n\t\texpiryMarket.mintExactCost({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tMarket: args.expiryMarketId,\n\t\t\t\tWrapper: args.wrapperId,\n\t\t\t\tAuth: auth,\n\t\t\t\tPricer: pricer,\n\t\t\t\tLowerTick: args.lowerTick,\n\t\t\t\tHigherTick: args.higherTick,\n\t\t\t\tMaxCost: args.maxCostRaw,\n\t\t\t\tMinQuantity: args.minQuantityRaw,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Owner-authorized redeem of a live (not-yet-settled) position: close `closeQuantityRaw`\n// of `orderId` at the live pricer's mark, enforcing close-side slippage floors\n// (`minProbabilityRaw`/`minProceedsRaw`, default 0 = uncapped). Returns `Option<u256>`:\n// the replacement order id when a partial close leaves quantity open, else none. Command\n// order is pricer → auth → redeem. Deployed sig `redeem_live`.\n/**\n * @deprecated Retired by delayed execution (DBU-885): Predict v4 always aborts it\n * (`EDelayedExecutionRequired`). Account positions then have no early exit; queued fills are Open\n * records sold with `enqueueRedeemOpen`.\n */\nexport function redeemLive(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\torderId: bigint;\n\t\tcloseQuantityRaw: bigint;\n\t\tminProbabilityRaw?: bigint;\n\t\tminProceedsRaw?: bigint;\n\t} & MarketFeeds,\n): (tx: Transaction) => TransactionResult {\n\treturn liveTrade(config, args, (pricer, auth) =>\n\t\texpiryMarket.redeemLive({\n\t\t\tconfig,\n\t\t\targuments: {\n\t\t\t\tMarket: args.expiryMarketId,\n\t\t\t\tWrapper: args.wrapperId,\n\t\t\t\tAuth: auth,\n\t\t\t\tPricer: pricer,\n\t\t\t\tOrderId: args.orderId,\n\t\t\t\tCloseQuantity: args.closeQuantityRaw,\n\t\t\t\tMinProbability: args.minProbabilityRaw ?? 0n,\n\t\t\t\tMinProceeds: args.minProceedsRaw ?? 0n,\n\t\t\t},\n\t\t}),\n\t);\n}\n\n// Unchanged by delayed execution: still pays settled positions held in the account. It doesn't\n// pay Open queue records, which the queue's `settle_step` pays at settlement.\n//\n// Owner-authorized redeem of a settled position: closes `orderId` IN FULL against the\n// recorded settlement price (the deployed entrypoint takes no quantity — a settled claim\n// is all-or-nothing). No live pricer (settlement price is fixed); auth is consumed by the\n// call. Deployed sig `redeem_settled` (owner-auth form). The keeper-facing\n// `redeem_settled_permissionless` is a separate entrypoint, out of scope for this SDK.\nexport function redeemSettled(\n\tconfig: GeneratedConfig,\n\targs: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\torderId: bigint;\n\t},\n): (tx: Transaction) => TransactionResult {\n\treturn authed.redeemSettled({\n\t\tconfig,\n\t\targuments: {\n\t\t\tmarket: args.expiryMarketId,\n\t\t\twrapper: args.wrapperId,\n\t\t\torderId: args.orderId,\n\t\t},\n\t});\n}\n"],"mappings":";;;;;;;AAYA,MAAM,SAAS,EAEd,eAAe,SAASA,gBAAmC,EAC3D;AAiBD,SAAgB,eACf,QACA,MACyC;AACzC,SAAQ,OACP,GAAG,IACFC,iBAA4B;EAC3B;EACA,WAAW;GACV,QAAQ,KAAK;GACb,MAAM,KAAK;GACX,UAAU,KAAK;GACf,OAAO,KAAK;GACZ;EACD,CAAC,CACF;;AAUH,SAAS,UACR,QACA,MACA,OAIyC;AACzC,SAAQ,OAAO;EACd,MAAM,SAAS,GAAG,IAAI,eAAe,QAAQ,KAAK,CAAC;EACnD,MAAM,OAAO,GAAG,IAAIC,aAAqB,EAAE,QAAQ,CAAC,CAAC;AACrD,SAAO,GAAG,IAAI,MA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ACb,SAAS,KAAK;GACd,SAAS,KAAK;GACd;EACD,CAAC"}
|
package/dist/sessions.d.mts
CHANGED
|
@@ -20,10 +20,19 @@ interface SessionsConfig extends DeepbookSessionsConfig {
|
|
|
20
20
|
sessionsPackageIdV1?: string;
|
|
21
21
|
/** The shared `SessionsConfig` object id. */
|
|
22
22
|
sessionsConfig: string;
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* The ORIGINAL shared `account` package id. The derived account and wrapper ids and the
|
|
25
|
+
* session data key's type are built from it, so it never moves to an upgraded package.
|
|
26
|
+
*/
|
|
24
27
|
accountPackageId: string;
|
|
25
28
|
/** The shared `AccountRegistry` object id. */
|
|
26
29
|
accountRegistry: string;
|
|
30
|
+
/**
|
|
31
|
+
* The latest `account` package once the network has upgraded it: the call target for any
|
|
32
|
+
* account call composed into the same PTB as these sessions calls, which link it. A PTB can't
|
|
33
|
+
* call account at an older version (`InvalidLinkage`). Absent while the network runs v1.
|
|
34
|
+
*/
|
|
35
|
+
accountPackageIdLatest?: string;
|
|
27
36
|
}
|
|
28
37
|
/**
|
|
29
38
|
* Ids the DeepBook **spot** session wrappers need on top of {@link SessionsConfig}. The
|
package/dist/sessions.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessions.d.mts","names":[],"sources":["../src/sessions.ts"],"mappings":";;;;;;;;;;;AA4BA;;;;UAAiB,cAAA,SAAuB,sBAAA;EAEvC;EAAA,iBAAA;EAIA;EAFA,mBAAA;
|
|
1
|
+
{"version":3,"file":"sessions.d.mts","names":[],"sources":["../src/sessions.ts"],"mappings":";;;;;;;;;;;AA4BA;;;;UAAiB,cAAA,SAAuB,sBAAA;EAEvC;EAAA,iBAAA;EAIA;EAFA,mBAAA;EASA;EAPA,cAAA;EAasB;;AAQvB;;EAhBC,gBAAA;EAkBA;EAhBA,eAAA;EAsBgB;;;;;EAhBhB,sBAAA;AAAA;;;;;;UAQgB,eAAA;EAyBuC;EAvBvD,g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;;;;;;;;;;;;;SA+CpB,cAAA,CAAe,QAAA,EAAU,UAAA,GAAa,YAAA;;SAqBtC,cAAA,CAAe,MAAA,WAAiB,YAAA,IAAgB,KAAA,oBAAyB,YAAA;;;;;;;SAYzE,eAAA,CAAgB,MAAA,WAAiB,YAAA,IAAgB,KAAA,oBAAyB,YAAA;AAAA"}
|
package/dist/sessions.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessions.mjs","names":["#config","#generatedConfig","sessions.authorizeSession","sessions.revokeSession","sessions.sessionExpirationMs","sessions.mintExactQuantity","sessions.mintExactAmount","sessions.mintExactCost","sessions.redeemLive","sessions.redeemSettled","sessions.enqueueExactQuantity","#queuedTarget","sessions.enqueueExactAmount","sessions.enqueueExactCost","sessions.enqueueRedeemOpen"],"sources":["../src/sessions.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs } from '@mysten/sui/bcs';\nimport type { Transaction, TransactionArgument, TransactionResult } from '@mysten/sui/transactions';\nimport { deriveDynamicFieldID, deriveObjectID } from '@mysten/sui/utils';\n\nimport { MAINNET_SESSIONS } from './deployments/mainnet.js';\nimport { TESTNET_SESSIONS } from './deployments/testnet.js';\nimport type { NetworkArg } from './deployments/index.js';\n\n// Provenance and scale constants, so a sessions-only consumer can answer \"which deployment\n// is this pinned to?\" and format a custody balance without importing another subpath.\nexport { getDeployment, getUnits, TESTNET_DEPLOYMENT, TESTNET_UNITS } from './deployments/index.js';\nexport type { DeployedNetwork, NetworkArg } from './deployments/index.js';\n\nimport { AccountContract } from './account.js';\nimport { deriveQueueId } from './predict/queue-id.js';\nimport type { DeepbookSessionsConfig } from './contracts/deepbook_sessions/config-arguments.js';\nimport * as sessions from './contracts/deepbook_sessions/sessions.js';\nimport { SessionsData } from './contracts/deepbook_sessions/sessions.js';\n\n/**\n * Deployed ids the sessions builders address.\n *\n * `accountPackageId` / `accountRegistry` are the same shared-account ids\n * {@link AccountContract} takes — sessions is an Account app, so it addresses the same\n * registry. `sessionsPackageId` and `sessionsConfig` come from the sessions deployment.\n */\nexport interface SessionsConfig extends DeepbookSessionsConfig {\n\t/** The latest `deepbook_sessions` Move-call package id. */\n\tsessionsPackageId: string;\n\t/** Original ID for v1 structs. Omit only for an unupgraded custom deployment. */\n\tsessionsPackageIdV1?: string;\n\t/** The shared `SessionsConfig` object id. */\n\tsessionsConfig: string;\n\t/** The shared `account` Move package id. */\n\taccountPackageId: string;\n\t/** The shared `AccountRegistry` object id. */\n\taccountRegistry: string;\n}\n\n/**\n * Ids the DeepBook **spot** session wrappers need on top of {@link SessionsConfig}. The\n * Predict wrappers never take these, so they are kept off the main config rather than made\n * optional there.\n */\nexport interface SessionsSpotIds {\n\t/** DeepBook's shared `Registry` — `deepbook_registry` on the spot entrypoints. */\n\tdeepbookRegistry: string;\n\t/** The `deepbook_core_account` Move package id. */\n\tdeepbookCoreAccountPackageId: string;\n}\n\n/** Ids the Predict session wrappers need beyond {@link SessionsConfig}. */\nexport interface SessionsPredictIds {\n\t/** Every Predict wrapper takes `config: &ProtocolConfig`. */\n\tprotocolConfig: string;\n}\n\n/**\n * @description The deployed sessions ids for `network`, so a caller does not transcribe\n * them. Generated from the deploy manifest — see `src/deployments/`. The returned object\n * also carries {@link SessionsSpotIds} for the generated spot wrappers.\n * @throws if the network has no recorded deployment, rather than returning placeholder ids.\n *\n * ```ts\n * const sessions = new SessionsContract(getSessionsConfig('testnet'));\n * ```\n */\nexport function getSessionsConfig(\n\tnetwork: NetworkArg,\n): SessionsConfig & SessionsSpotIds & SessionsPredictIds {\n\t// The frozen record itself, matching `/account` — returning a spread here would have\n\t// quietly exempted this subpath from the immutability the others guarantee.\n\tif (network === 'testnet') return TESTNET_SESSIONS;\n\tif (network === 'mainnet') return MAINNET_SESSIONS;\n\tthrow new Error(\n\t\t`@mysten/deepbook-v3/sessions: no sessions deployment recorded for network '${network}'. ` +\n\t\t\t'Sessions is recorded for testnet and mainnet; for your own deployment construct a ' +\n\t\t\t'`SessionsConfig` ' +\n\t\t\t'and pass it to SessionsContract directly.',\n\t);\n}\n\n/** The market, queue, account and oracle objects every queued Predict session wrapper names. */\nexport interface SessionsQueuedOrderTarget {\n\texpiryMarketId: string;\n\twrapperId: string;\n\t/**\n\t * The order-flow companion's shared `OrderDesk` (`deepbook_predict_orders`). Predict's\n\t * `PredictConfig.objects.orderDesk`.\n\t */\n\torderDesk: string;\n\t/**\n\t * The order-flow companion's shared `QueueRegistry`, which every market's queue ID derives\n\t * from. Predict's `PredictConfig.objects.queueRegistry`.\n\t */\n\tqueueRegistry: string;\n\t/**\n\t * The market's `MarketQueue`. Defaults to the ID derived from `queueRegistry` and the market\n\t * (`deriveQueueId`), which is where `queue::create_and_share` puts it.\n\t */\n\tqueueId?: string;\n\t/** Predict's `ProtocolConfig`. */\n\tprotocolConfig: string;\n\t/** Predict's `OracleRegistry` (the propbook registry). */\n\toracleRegistry: string;\n\t/** The market's `PythFeed`. */\n\tpythFeed: string;\n\t/** The market's `BlockScholesValueStore`. */\n\tblockScholesValueStore: string;\n\t/** The market's `BlockScholesSVIStore`. */\n\tblockScholesSviStore: string;\n}\n\nconst U64_MAX = (1n << 64n) - 1n;\n\n// The chain refuses a zero or \"unlimited\" cap on every queued mint (`EMintCostCapRequired`).\nfunction assertQueuedMaxCost(maxCost: number | bigint): void {\n\tconst value = BigInt(maxCost);\n\tif (value <= 0n || value >= U64_MAX) {\n\t\tthrow new Error(\n\t\t\t`maxCost must be above 0 and below u64::MAX on a queued mint (EMintCostCapRequired), got ${value}`,\n\t\t);\n\t}\n}\n\n/** The maximum session duration the contract accepts: 30 days, in milliseconds. */\nexport const MAX_SESSION_DURATION_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** The maximum number of distinct session addresses one Account may store. */\nexport const MAX_SESSIONS_PER_ACCOUNT = 20;\n\n// `sui::dynamic_field::Field<DataKey<SessionsApp>, SessionsData>` — what a core `getObject`\n// on the grant field actually returns. `DataKey` is source-empty, but Move inserts a\n// hidden `dummy_field: bool` into empty structs, so the name occupies ONE zero byte\n// between the id and the value. Decoding the value alone would read the field id's first\n// byte as the VecMap length: garbage grants, or a silent empty list.\nconst SessionsDataField = bcs.struct('Field<DataKey,SessionsData>', {\n\tid: bcs.Address,\n\tname: bcs.bool(), // DataKey's hidden dummy_field\n\tvalue: SessionsData,\n});\n\n// `AccountKey(owner)` — the canonical ACCOUNT identity, a different derived object from\n// the wrapper. Grant data hangs off this one.\nconst AccountKey = bcs.struct('AccountKey', { pos0: bcs.Address });\n\n/** One stored session grant. */\nexport interface SessionGrant {\n\t/** The authorized ephemeral address. */\n\tsession: string;\n\t/** Absolute expiry, ms since epoch. The grant is dead AT this timestamp (strict `<`). */\n\texpiresAtMs: bigint;\n}\n\n/**\n * SessionsContract — time-limited trading sessions over a canonical Account.\n *\n * An Account owner authorizes an ephemeral address to submit a bounded set of\n * transactions on the Account's behalf until a fixed expiry. The session key never\n * receives a reusable `Auth`: each wrapper mints app authorization internally and\n * consumes it in the same call.\n *\n * WHAT A SESSION KEY CAN DO. It cannot withdraw to an address, cannot grant or revoke\n * sessions, and cannot outlive its expiry — those all require owner auth. It CAN trade\n * the Account's full balance: the spot wrappers take a caller-chosen `Pool` and, through\n * `deepbook_core_account`, pull the account's entire Base, Quote and DEEP balance\n * (stored plus unsettled) into the embedded manager for the duration of the call, with\n * `price_limit` supplied by the caller. Nothing caps notional, restricts which pools are\n * reachable, or bounds loss to adverse pricing. Treat a session key as authority over\n * everything the Account holds, and fund an ephemeral-session Account accordingly.\n *\n * Operational precondition: an admin must have authorized `SessionsApp` on the account\n * registry. Until then — or after a `deauthorize_app` — the TRADING wrappers abort with\n * `EAppNotAuthorized`; `authorizeSession`, `revokeSession` and `sessionExpirationMs` use\n * owner auth or no auth and keep working. Note that `deauthorize_app` does not clear\n * `SessionsData`, so re-authorizing makes every still-unexpired grant live again at once\n * — it is a pause, not a kill switch. Revoking, and reading expirations, also keep\n * working if the sessions package is later version-gated.\n *\n * This class wraps the session lifecycle and the **Predict** entrypoints. The DeepBook\n * spot session wrappers are generated (see `sessionsMoveCalls`) but are not wrapped here\n * — note `placeLimitOrder` and `placeMarketOrder` put `accountRegistry` at index 2 and\n * `sessionsConfig` at 4, because `deepbookRegistry` sits between them; the other three\n * (`cancelLiveOrder`, `cancelLiveOrders`, `withdrawSettledAmounts`) take no\n * `deepbookRegistry` and so keep 1 and 3 like the Predict wrappers:\n * the surrounding spot-over-Account workflow — discovering the embedded balance manager,\n * reading resting orders and locked balances — is not modelled yet, so a wrapped builder\n * would be hard to use well. They are reachable from the generated bindings meanwhile.\n */\nexport class SessionsContract {\n\t#config: SessionsConfig;\n\n\tconstructor(config: SessionsConfig) {\n\t\tthis.#config = config;\n\t}\n\n\t// The generated thunks resolve the package address and auto-inject the shared\n\t// `SessionsConfig` from this object. `accountRegistry` stays an explicit argument —\n\t// it belongs to the account package, which is a separate codegen entry.\n\tget #generatedConfig() {\n\t\treturn {\n\t\t\tsessionsPackageId: this.#config.sessionsPackageId,\n\t\t\tsessionsConfig: this.#config.sessionsConfig,\n\t\t};\n\t}\n\n\t/**\n\t * @description The owner's canonical `AccountWrapper` id — derived off-chain, no read.\n\t * Every builder here takes that id.\n\t */\n\tderiveAccountWrapperId(owner: string): string {\n\t\treturn new AccountContract({\n\t\t\taccountPackageId: this.#config.accountPackageId,\n\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t}).deriveAccountWrapperId(owner);\n\t}\n\n\t/**\n\t * @description The owner's canonical ACCOUNT id — a different derived object from the\n\t * wrapper. The session grants hang off this one, so this is what\n\t * {@link deriveSessionsFieldId} and {@link decodeSessions} work from.\n\t */\n\tderiveAccountId(owner: string): string {\n\t\treturn deriveObjectID(\n\t\t\tthis.#config.accountRegistry,\n\t\t\t`${this.#config.accountPackageId}::account_registry::AccountKey`,\n\t\t\tAccountKey.serialize({ pos0: owner }).toBytes(),\n\t\t);\n\t}\n\n\t/**\n\t * @description The object id of the owner's `DataKey<SessionsApp>` dynamic field —\n\t * fetch this object and pass its BCS contents to {@link decodeSessions}. There is no\n\t * bulk on-chain read, so this is the route to enumerating grants.\n\t */\n\tderiveSessionsFieldId(owner: string): string {\n\t\t// A PLAIN dynamic field, not a derived object: `account::attach` writes it with\n\t\t// `df::add` (`use fun df::add as UID.add`), whereas the account and wrapper ids are\n\t\t// claimed through `derived_object::claim`. `deriveObjectID` would wrap the tag in\n\t\t// `0x2::derived_object::DerivedObjectKey<..>` and yield an id that points at nothing.\n\t\treturn deriveDynamicFieldID(\n\t\t\tthis.deriveAccountId(owner),\n\t\t\t`${this.#config.accountPackageId}::account::DataKey<${this.#config.sessionsPackageIdV1 ?? this.#config.sessionsPackageId}::sessions::SessionsApp>`,\n\t\t\t// DataKey is source-empty; Move's hidden `dummy_field: bool` is the key's one byte.\n\t\t\tnew Uint8Array([0]),\n\t\t);\n\t}\n\n\t/**\n\t * @description Grant `session` authority over the Account until `now + durationMs`.\n\t * Authority is derived from the transaction SENDER, so the owner must sign this.\n\t * `durationMs` must be > 0 and <= {@link MAX_SESSION_DURATION_MS}; an Account holds at\n\t * most {@link MAX_SESSIONS_PER_ACCOUNT} distinct addresses. Re-authorizing an address\n\t * replaces its expiry in place and consumes no additional slot.\n\t * @returns A function that takes a Transaction object\n\t */\n\tauthorizeSession(params: { wrapperId: string; session: string; durationMs: number | bigint }) {\n\t\treturn (tx: Transaction): void => {\n\t\t\ttx.add(\n\t\t\t\tsessions.authorizeSession({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tsession: params.session,\n\t\t\t\t\t\tdurationMs: params.durationMs,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\t}\n\n\t/**\n\t * @description Remove `session`'s grant. Owner-signed, like `authorizeSession`.\n\t * Deliberately takes no `SessionsConfig`: revocation is not version-gated, so it keeps\n\t * working after the package is retired. Revoking an address that holds no grant is a\n\t * silent no-op — it neither aborts nor emits, so read before and after if you need to\n\t * distinguish \"revoked\" from \"was never granted\".\n\t * @returns A function that takes a Transaction object\n\t */\n\trevokeSession(params: { wrapperId: string; session: string }) {\n\t\treturn (tx: Transaction): void => {\n\t\t\ttx.add(\n\t\t\t\tsessions.revokeSession({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: { wrapper: params.wrapperId, session: params.session },\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\t}\n\n\t/**\n\t * @description Read one session's absolute expiry as `Option<u64>`. Compose in a\n\t * dev-inspect/simulate PTB and decode the returned BCS. Not version-gated.\n\t * @returns A function that takes a Transaction object\n\t */\n\tsessionExpirationMs(params: { wrapperId: string; session: string }) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.sessionExpirationMs({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: { wrapper: params.wrapperId, session: params.session },\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t// === Predict wrappers ===\n\t//\n\t// Each mirrors the Predict entrypoint of the same name, with two differences: the\n\t// caller supplies NO `Auth` (the wrapper mints and consumes app authorization\n\t// internally), and `accountRegistry` + `sessionsConfig` are threaded in. `pricer` is a\n\t// PTB RESULT, not an object — it comes from a preceding `expiry_market::load_live_pricer`\n\t// command in the same transaction. Everything else matches Predict exactly, and Predict\n\t// still performs all parameter validation.\n\n\t/**\n\t * @description Mint a position of an exact payout quantity, as `session`. Pass\n\t * `u64::MAX` for `maxCost` / `maxProbability` to leave either slippage cap\n\t * effectively unbounded — the chain asserts `value <= cap`, so the max value can never\n\t * trip. Both are required; there is no default.\n\t * @returns A function that takes a Transaction object and returns the new order id (u256)\n\t * @deprecated Retired by delayed execution (DBU-885): always aborts through Predict v4\n\t * (`EDelayedExecutionRequired`). Use {@link SessionsContract.enqueueExactQuantity}.\n\t */\n\tmintExactQuantity(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\tpricer: TransactionArgument;\n\t\tlowerTick: number | bigint;\n\t\thigherTick: number | bigint;\n\t\tquantity: number | bigint;\n\t\tmaxCost: number | bigint;\n\t\tmaxProbability: number | bigint;\n\t}) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.mintExactQuantity({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\tpricer: params.pricer,\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tquantity: params.quantity,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t\tmaxProbability: params.maxProbability,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Mint by spending up to a premium budget, flooring the quantity received.\n\t * The chain requires `maxCost > 0`.\n\t * @returns A function that takes a Transaction object and returns the new order id (u256)\n\t * @deprecated Retired by delayed execution (DBU-885): always aborts through Predict v4.\n\t * Use {@link SessionsContract.enqueueExactAmount}.\n\t */\n\tmintExactAmount(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\tpricer: TransactionArgument;\n\t\tlowerTick: number | bigint;\n\t\thigherTick: number | bigint;\n\t\tmaxPremium: number | bigint;\n\t\tminQuantity: number | bigint;\n\t\tmaxCost: number | bigint;\n\t}) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.mintExactAmount({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\tpricer: params.pricer,\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tmaxPremium: params.maxPremium,\n\t\t\t\t\t\tminQuantity: params.minQuantity,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * Mint within an all-in budget as a session. Amounts are raw Move units.\n\t * Requires Sessions/Predict v2 or later.\n\t * @deprecated Retired by delayed execution (DBU-885): always aborts through Predict v4.\n\t * Use {@link SessionsContract.enqueueExactCost}.\n\t */\n\tmintExactCost(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\tpricer: TransactionArgument;\n\t\tlowerTick: number | bigint;\n\t\thigherTick: number | bigint;\n\t\tmaxCost: number | bigint;\n\t\tminQuantity: number | bigint;\n\t}) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.mintExactCost({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\tpricer: params.pricer,\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t\tminQuantity: params.minQuantity,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Close part or all of a live position at the pricer's mark, as `session`.\n\t * `minProbability` / `minProceeds` are close-side slippage floors; `0` disables either,\n\t * and OMITTING them is `0` — unlike the mint caps, which are required. On a delegated\n\t * key this is the direction that closes a position at any price, so pass real floors\n\t * unless you mean to accept whatever the mark gives you.\n\t * @returns A function that takes a Transaction object and returns `Option<u256>` — the\n\t * replacement order id when a partial close leaves quantity open\n\t * @deprecated Retired by delayed execution (DBU-885): always aborts through Predict v4.\n\t * Account positions then have no early exit; queued fills are Open records sold with\n\t * {@link SessionsContract.enqueueRedeemOpen}.\n\t */\n\tredeemLive(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\tpricer: TransactionArgument;\n\t\torderId: bigint;\n\t\tcloseQuantity: number | bigint;\n\t\tminProbability?: number | bigint;\n\t\tminProceeds?: number | bigint;\n\t}) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.redeemLive({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\tpricer: params.pricer,\n\t\t\t\t\t\torderId: params.orderId,\n\t\t\t\t\t\tcloseQuantity: params.closeQuantity,\n\t\t\t\t\t\tminProbability: params.minProbability ?? 0,\n\t\t\t\t\t\tminProceeds: params.minProceeds ?? 0,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Claim a settled position in full, as `session`. Takes no pricer — the\n\t * settlement price is fixed — and no quantity: a settled claim is all-or-nothing.\n\t * @returns A function that takes a Transaction object\n\t */\n\tredeemSettled(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\torderId: bigint;\n\t}) {\n\t\treturn (tx: Transaction): void => {\n\t\t\ttx.add(\n\t\t\t\tsessions.redeemSettled({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\torderId: params.orderId,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\t}\n\n\t// === Queued Predict wrappers (delayed execution, DBU-885) ===\n\t//\n\t// The session form of the order-flow companion's `queue::enqueue_*`, in Sessions v3. Each\n\t// wrapper names the market's `MarketQueue` and the companion's `OrderDesk` next to the market.\n\t// Placement takes no pricer: it reads the oracle objects directly, so each wrapper takes the\n\t// market's three feed ids plus Predict's `OracleRegistry` (the propbook registry). Amounts are\n\t// raw Move units. Each returns the new queue record ID (u64). The queue and Predict perform\n\t// every check; the caps below are only the ones a session key should never send by accident.\n\t//\n\t// They need a config whose `sessionsPackageId` is a Sessions v3 publication, which both\n\t// network records are. Sessions v1 and v2 have none of them.\n\n\t/**\n\t * @description Queue a mint of an exact payout quantity, as `session`. `maxCost` (all-in cap)\n\t * and `maxProbability` (at most 1e9) are required, and the chain refuses an \"unlimited\"\n\t * `maxCost`.\n\t * @returns A function that takes a Transaction object and returns the record id (u64)\n\t */\n\tenqueueExactQuantity(\n\t\tparams: SessionsQueuedOrderTarget & {\n\t\t\tlowerTick: number | bigint;\n\t\t\thigherTick: number | bigint;\n\t\t\tquantity: number | bigint;\n\t\t\tmaxCost: number | bigint;\n\t\t\tmaxProbability: number | bigint;\n\t\t},\n\t) {\n\t\tassertQueuedMaxCost(params.maxCost);\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.enqueueExactQuantity({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\t...this.#queuedTarget(params),\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tquantity: params.quantity,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t\tmaxProbability: params.maxProbability,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Queue a premium-budget mint, as `session`: sized at τ under `maxPremium`, at\n\t * least `minQuantity`, with the all-in debit capped by the required `maxCost`.\n\t * @returns A function that takes a Transaction object and returns the record id (u64)\n\t */\n\tenqueueExactAmount(\n\t\tparams: SessionsQueuedOrderTarget & {\n\t\t\tlowerTick: number | bigint;\n\t\t\thigherTick: number | bigint;\n\t\t\tmaxPremium: number | bigint;\n\t\t\tminQuantity: number | bigint;\n\t\t\tmaxCost: number | bigint;\n\t\t},\n\t) {\n\t\tassertQueuedMaxCost(params.maxCost);\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.enqueueExactAmount({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\t...this.#queuedTarget(params),\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tmaxPremium: params.maxPremium,\n\t\t\t\t\t\tminQuantity: params.minQuantity,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Queue an all-in-budget mint, as `session`: sized at τ so the all-in cost fits\n\t * `maxCost`, at least `minQuantity`.\n\t * @returns A function that takes a Transaction object and returns the record id (u64)\n\t */\n\tenqueueExactCost(\n\t\tparams: SessionsQueuedOrderTarget & {\n\t\t\tlowerTick: number | bigint;\n\t\t\thigherTick: number | bigint;\n\t\t\tmaxCost: number | bigint;\n\t\t\tminQuantity: number | bigint;\n\t\t},\n\t) {\n\t\tassertQueuedMaxCost(params.maxCost);\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.enqueueExactCost({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\t...this.#queuedTarget(params),\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t\tminQuantity: params.minQuantity,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Queue an early sell of the Open record `recordId` (its queue record ID, not\n\t * the position's order ID), as `session`. `minProbability` and `minProceeds` are the close\n\t * floors at τ and are required: on a delegated key, `0` closes at any price, so pass it only\n\t * on purpose.\n\t * @returns A function that takes a Transaction object and returns the new record id (u64)\n\t */\n\tenqueueRedeemOpen(\n\t\tparams: SessionsQueuedOrderTarget & {\n\t\t\trecordId: number | bigint;\n\t\t\tcloseQuantity: number | bigint;\n\t\t\tminProbability: number | bigint;\n\t\t\tminProceeds: number | bigint;\n\t\t},\n\t) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.enqueueRedeemOpen({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\t...this.#queuedTarget(params),\n\t\t\t\t\t\trecordId: params.recordId,\n\t\t\t\t\t\tcloseQuantity: params.closeQuantity,\n\t\t\t\t\t\tminProbability: params.minProbability,\n\t\t\t\t\t\tminProceeds: params.minProceeds,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t// The leading arguments every queued wrapper shares, in the Move order: `(queue, market,\n\t// account_registry, wrapper, sessions_config, desk, config, propbook_registry, pyth, bs_values,\n\t// bs_svi, …)`. `sessions_config` comes from the generated config.\n\t#queuedTarget(params: SessionsQueuedOrderTarget) {\n\t\treturn {\n\t\t\tqueue: params.queueId ?? deriveQueueId(params.queueRegistry, params.expiryMarketId),\n\t\t\tmarket: params.expiryMarketId,\n\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\twrapper: params.wrapperId,\n\t\t\tdesk: params.orderDesk,\n\t\t\tconfig: params.protocolConfig,\n\t\t\tpropbookRegistry: params.oracleRegistry,\n\t\t\tpyth: params.pythFeed,\n\t\t\tbsValues: params.blockScholesValueStore,\n\t\t\tbsSvi: params.blockScholesSviStore,\n\t\t};\n\t}\n\n\t/**\n\t * @description Decode an Account's stored grants from the raw BCS content of its\n\t * `DataKey<SessionsApp>` dynamic FIELD object — the whole\n\t * `Field<DataKey<SessionsApp>, SessionsData>`, as the core API returns it, not the\n\t * inner `SessionsData`. Get the id from {@link deriveSessionsFieldId}.\n\t *\n\t * There is no bulk on-chain read — `sessionExpirationMs` answers one address at a time —\n\t * so listing grants means fetching that field and decoding it here. Note the field hangs\n\t * off the DERIVED ACCOUNT address, not the wrapper address; they are different objects.\n\t *\n\t * Expired grants are never pruned automatically and keep occupying slots, so callers\n\t * managing the {@link MAX_SESSIONS_PER_ACCOUNT} cap should list, drop anything already\n\t * expired, and revoke before granting again.\n\t */\n\tstatic decodeSessions(contents: Uint8Array): SessionGrant[] {\n\t\t// Assert full consumption. `@mysten/bcs`'s ULEB reader indexes the underlying\n\t\t// ArrayBuffer rather than the view, so a truncated SUBARRAY — which is exactly what a\n\t\t// gRPC `content` field is — can read past its bound and decode to `[]` with no error.\n\t\t// Re-serializing and comparing lengths turns both truncation and trailing junk into a\n\t\t// throw, so \"no grants\" can only ever mean no grants.\n\t\tconst field = SessionsDataField.parse(contents);\n\t\tconst reencoded = SessionsDataField.serialize(field).toBytes();\n\t\tif (reencoded.length !== contents.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`sessions field is ${contents.length} bytes but its contents encode to ${reencoded.length}; ` +\n\t\t\t\t\t'the bytes are truncated or carry trailing data',\n\t\t\t);\n\t\t}\n\t\treturn field.value.sessions.contents.map((entry) => ({\n\t\t\tsession: entry.key,\n\t\t\texpiresAtMs: BigInt(entry.value),\n\t\t}));\n\t}\n\n\t/** Grants from {@link decodeSessions} that are still live at `nowMs`. */\n\tstatic activeSessions(grants: readonly SessionGrant[], nowMs: number | bigint): SessionGrant[] {\n\t\tconst now = BigInt(nowMs);\n\t\t// The chain asserts `now < expiresAtMs`, so a grant is dead AT its expiry.\n\t\treturn grants.filter((g) => now < g.expiresAtMs);\n\t}\n\n\t/**\n\t * @description Grants that are already dead at `nowMs` — the complement of\n\t * {@link activeSessions}, and the list to revoke when reclaiming slots. Use this rather\n\t * than filtering by hand: `nowMs > expiresAtMs` looks equivalent but leaves the grant\n\t * expiring exactly at `nowMs` occupying a slot forever.\n\t */\n\tstatic expiredSessions(grants: readonly SessionGrant[], nowMs: number | bigint): SessionGrant[] {\n\t\tconst now = BigInt(nowMs);\n\t\treturn grants.filter((g) => now >= g.expiresAtMs);\n\t}\n}\n\n// === Generated bindings ===\n// NOTE: this namespace carries the DeepBook spot session calls too\n// (`placeLimitOrder`, `placeMarketOrder`, `cancelLiveOrder(s)`, `withdrawSettledAmounts`).\n// They are generated and callable; they are simply not wrapped on `SessionsContract`.\nexport * as sessionsMoveCalls from './contracts/deepbook_sessions/sessions.js';\nexport * as sessionConfigMoveCalls from './contracts/deepbook_sessions/session_config.js';\nexport {\n\tSessionsApp,\n\tSessionsData,\n\tSessionAuthorized,\n\tSessionRevoked,\n} from './contracts/deepbook_sessions/sessions.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,kBACf,SACwD;AAGxD,KAAI,YAAY,UAAW,QAAO;AAClC,KAAI,YAAY,UAAW,QAAO;AAClC,OAAM,IAAI,MACT,8EAA8E,QAAQ,mJAItF;;AAkCF,MAAM,WAAW,MAAM,OAAO;AAG9B,SAAS,oBAAoB,SAAgC;CAC5D,MAAM,QAAQ,OAAO,QAAQ;AAC7B,KAAI,SAAS,MAAM,SAAS,QAC3B,OAAM,IAAI,MACT,2FAA2F,QAC3F;;;AAKH,MAAa,0BAA0B,MAAU,KAAK,KAAK;;AAG3D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;AACD,UAAQ,OACP,GAAG,IACFG,kBAA2B;GAC1B,QAAQ,MAAKb;GACb,WAAW;IACV,GAAG,MAAKU,aAAc,OAAO;IAC7B,UAAU,OAAO;IACjB,eAAe,OAAO;IACtB,gBAAgB,OAAO;IACvB,aAAa,OAAO;IACpB;GACD,CAAC,CACF;;CAMH,cAAc,QAAmC;AAChD,SAAO;GACN,OAAO,OAAO,WAAW,cAAc,OAAO,eAAe,OAAO,eAAe;GACnF,QAAQ,OAAO;GACf,iBAAiB,MAAKX,OAAQ;GAC9B,SAAS,OAAO;GAChB,MAAM,OAAO;GACb,QAAQ,OAAO;GACf,kBAAkB,OAAO;GACzB,MAAM,OAAO;GACb,UAAU,OAAO;GACjB,OAAO,OAAO;GACd;;;;;;;;;;;;;;;;CAiBF,OAAO,eAAe,UAAsC;EAM3D,MAAM,QAAQ,kBAAkB,MAAM,SAAS;EAC/C,MAAM,YAAY,kBAAkB,UAAU,MAAM,CAAC,SAAS;AAC9D,MAAI,UAAU,WAAW,SAAS,OACjC,OAAM,IAAI,MACT,qBAAqB,SAAS,OAAO,oCAAoC,UAAU,OAAO,kDAE1F;AAEF,SAAO,MAAM,MAAM,SAAS,SAAS,KAAK,WAAW;GACpD,SAAS,MAAM;GACf,aAAa,OAAO,MAAM,MAAM;GAChC,EAAE;;;CAIJ,OAAO,eAAe,QAAiC,OAAwC;EAC9F,MAAM,MAAM,OAAO,MAAM;AAEzB,SAAO,OAAO,QAAQ,MAAM,MAAM,EAAE,YAAY;;;;;;;;CASjD,OAAO,gBAAgB,QAAiC,OAAwC;EAC/F,MAAM,MAAM,OAAO,MAAM;AACzB,SAAO,OAAO,QAAQ,MAAM,OAAO,EAAE,YAAY"}
|
|
1
|
+
{"version":3,"file":"sessions.mjs","names":["#config","#generatedConfig","sessions.authorizeSession","sessions.revokeSession","sessions.sessionExpirationMs","sessions.mintExactQuantity","sessions.mintExactAmount","sessions.mintExactCost","sessions.redeemLive","sessions.redeemSettled","sessions.enqueueExactQuantity","#queuedTarget","sessions.enqueueExactAmount","sessions.enqueueExactCost","sessions.enqueueRedeemOpen"],"sources":["../src/sessions.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs } from '@mysten/sui/bcs';\nimport type { Transaction, TransactionArgument, TransactionResult } from '@mysten/sui/transactions';\nimport { deriveDynamicFieldID, deriveObjectID } from '@mysten/sui/utils';\n\nimport { MAINNET_SESSIONS } from './deployments/mainnet.js';\nimport { TESTNET_SESSIONS } from './deployments/testnet.js';\nimport type { NetworkArg } from './deployments/index.js';\n\n// Provenance and scale constants, so a sessions-only consumer can answer \"which deployment\n// is this pinned to?\" and format a custody balance without importing another subpath.\nexport { getDeployment, getUnits, TESTNET_DEPLOYMENT, TESTNET_UNITS } from './deployments/index.js';\nexport type { DeployedNetwork, NetworkArg } from './deployments/index.js';\n\nimport { AccountContract } from './account.js';\nimport { deriveQueueId } from './predict/queue-id.js';\nimport type { DeepbookSessionsConfig } from './contracts/deepbook_sessions/config-arguments.js';\nimport * as sessions from './contracts/deepbook_sessions/sessions.js';\nimport { SessionsData } from './contracts/deepbook_sessions/sessions.js';\n\n/**\n * Deployed ids the sessions builders address.\n *\n * `accountPackageId` / `accountRegistry` are the same shared-account ids\n * {@link AccountContract} takes — sessions is an Account app, so it addresses the same\n * registry. `sessionsPackageId` and `sessionsConfig` come from the sessions deployment.\n */\nexport interface SessionsConfig extends DeepbookSessionsConfig {\n\t/** The latest `deepbook_sessions` Move-call package id. */\n\tsessionsPackageId: string;\n\t/** Original ID for v1 structs. Omit only for an unupgraded custom deployment. */\n\tsessionsPackageIdV1?: string;\n\t/** The shared `SessionsConfig` object id. */\n\tsessionsConfig: string;\n\t/**\n\t * The ORIGINAL shared `account` package id. The derived account and wrapper ids and the\n\t * session data key's type are built from it, so it never moves to an upgraded package.\n\t */\n\taccountPackageId: string;\n\t/** The shared `AccountRegistry` object id. */\n\taccountRegistry: string;\n\t/**\n\t * The latest `account` package once the network has upgraded it: the call target for any\n\t * account call composed into the same PTB as these sessions calls, which link it. A PTB can't\n\t * call account at an older version (`InvalidLinkage`). Absent while the network runs v1.\n\t */\n\taccountPackageIdLatest?: string;\n}\n\n/**\n * Ids the DeepBook **spot** session wrappers need on top of {@link SessionsConfig}. The\n * Predict wrappers never take these, so they are kept off the main config rather than made\n * optional there.\n */\nexport interface SessionsSpotIds {\n\t/** DeepBook's shared `Registry` — `deepbook_registry` on the spot entrypoints. */\n\tdeepbookRegistry: string;\n\t/** The `deepbook_core_account` Move package id. */\n\tdeepbookCoreAccountPackageId: string;\n}\n\n/** Ids the Predict session wrappers need beyond {@link SessionsConfig}. */\nexport interface SessionsPredictIds {\n\t/** Every Predict wrapper takes `config: &ProtocolConfig`. */\n\tprotocolConfig: string;\n}\n\n/**\n * @description The deployed sessions ids for `network`, so a caller does not transcribe\n * them. Generated from the deploy manifest — see `src/deployments/`. The returned object\n * also carries {@link SessionsSpotIds} for the generated spot wrappers.\n * @throws if the network has no recorded deployment, rather than returning placeholder ids.\n *\n * ```ts\n * const sessions = new SessionsContract(getSessionsConfig('testnet'));\n * ```\n */\nexport function getSessionsConfig(\n\tnetwork: NetworkArg,\n): SessionsConfig & SessionsSpotIds & SessionsPredictIds {\n\t// The frozen record itself, matching `/account` — returning a spread here would have\n\t// quietly exempted this subpath from the immutability the others guarantee.\n\tif (network === 'testnet') return TESTNET_SESSIONS;\n\tif (network === 'mainnet') return MAINNET_SESSIONS;\n\tthrow new Error(\n\t\t`@mysten/deepbook-v3/sessions: no sessions deployment recorded for network '${network}'. ` +\n\t\t\t'Sessions is recorded for testnet and mainnet; for your own deployment construct a ' +\n\t\t\t'`SessionsConfig` ' +\n\t\t\t'and pass it to SessionsContract directly.',\n\t);\n}\n\n/** The market, queue, account and oracle objects every queued Predict session wrapper names. */\nexport interface SessionsQueuedOrderTarget {\n\texpiryMarketId: string;\n\twrapperId: string;\n\t/**\n\t * The order-flow companion's shared `OrderDesk` (`deepbook_predict_orders`). Predict's\n\t * `PredictConfig.objects.orderDesk`.\n\t */\n\torderDesk: string;\n\t/**\n\t * The order-flow companion's shared `QueueRegistry`, which every market's queue ID derives\n\t * from. Predict's `PredictConfig.objects.queueRegistry`.\n\t */\n\tqueueRegistry: string;\n\t/**\n\t * The market's `MarketQueue`. Defaults to the ID derived from `queueRegistry` and the market\n\t * (`deriveQueueId`), which is where `queue::create_and_share` puts it.\n\t */\n\tqueueId?: string;\n\t/** Predict's `ProtocolConfig`. */\n\tprotocolConfig: string;\n\t/** Predict's `OracleRegistry` (the propbook registry). */\n\toracleRegistry: string;\n\t/** The market's `PythFeed`. */\n\tpythFeed: string;\n\t/** The market's `BlockScholesValueStore`. */\n\tblockScholesValueStore: string;\n\t/** The market's `BlockScholesSVIStore`. */\n\tblockScholesSviStore: string;\n}\n\nconst U64_MAX = (1n << 64n) - 1n;\n\n// The chain refuses a zero or \"unlimited\" cap on every queued mint (`EMintCostCapRequired`).\nfunction assertQueuedMaxCost(maxCost: number | bigint): void {\n\tconst value = BigInt(maxCost);\n\tif (value <= 0n || value >= U64_MAX) {\n\t\tthrow new Error(\n\t\t\t`maxCost must be above 0 and below u64::MAX on a queued mint (EMintCostCapRequired), got ${value}`,\n\t\t);\n\t}\n}\n\n/** The maximum session duration the contract accepts: 30 days, in milliseconds. */\nexport const MAX_SESSION_DURATION_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** The maximum number of distinct session addresses one Account may store. */\nexport const MAX_SESSIONS_PER_ACCOUNT = 20;\n\n// `sui::dynamic_field::Field<DataKey<SessionsApp>, SessionsData>` — what a core `getObject`\n// on the grant field actually returns. `DataKey` is source-empty, but Move inserts a\n// hidden `dummy_field: bool` into empty structs, so the name occupies ONE zero byte\n// between the id and the value. Decoding the value alone would read the field id's first\n// byte as the VecMap length: garbage grants, or a silent empty list.\nconst SessionsDataField = bcs.struct('Field<DataKey,SessionsData>', {\n\tid: bcs.Address,\n\tname: bcs.bool(), // DataKey's hidden dummy_field\n\tvalue: SessionsData,\n});\n\n// `AccountKey(owner)` — the canonical ACCOUNT identity, a different derived object from\n// the wrapper. Grant data hangs off this one.\nconst AccountKey = bcs.struct('AccountKey', { pos0: bcs.Address });\n\n/** One stored session grant. */\nexport interface SessionGrant {\n\t/** The authorized ephemeral address. */\n\tsession: string;\n\t/** Absolute expiry, ms since epoch. The grant is dead AT this timestamp (strict `<`). */\n\texpiresAtMs: bigint;\n}\n\n/**\n * SessionsContract — time-limited trading sessions over a canonical Account.\n *\n * An Account owner authorizes an ephemeral address to submit a bounded set of\n * transactions on the Account's behalf until a fixed expiry. The session key never\n * receives a reusable `Auth`: each wrapper mints app authorization internally and\n * consumes it in the same call.\n *\n * WHAT A SESSION KEY CAN DO. It cannot withdraw to an address, cannot grant or revoke\n * sessions, and cannot outlive its expiry — those all require owner auth. It CAN trade\n * the Account's full balance: the spot wrappers take a caller-chosen `Pool` and, through\n * `deepbook_core_account`, pull the account's entire Base, Quote and DEEP balance\n * (stored plus unsettled) into the embedded manager for the duration of the call, with\n * `price_limit` supplied by the caller. Nothing caps notional, restricts which pools are\n * reachable, or bounds loss to adverse pricing. Treat a session key as authority over\n * everything the Account holds, and fund an ephemeral-session Account accordingly.\n *\n * Operational precondition: an admin must have authorized `SessionsApp` on the account\n * registry. Until then — or after a `deauthorize_app` — the TRADING wrappers abort with\n * `EAppNotAuthorized`; `authorizeSession`, `revokeSession` and `sessionExpirationMs` use\n * owner auth or no auth and keep working. Note that `deauthorize_app` does not clear\n * `SessionsData`, so re-authorizing makes every still-unexpired grant live again at once\n * — it is a pause, not a kill switch. Revoking, and reading expirations, also keep\n * working if the sessions package is later version-gated.\n *\n * This class wraps the session lifecycle and the **Predict** entrypoints. The DeepBook\n * spot session wrappers are generated (see `sessionsMoveCalls`) but are not wrapped here\n * — note `placeLimitOrder` and `placeMarketOrder` put `accountRegistry` at index 2 and\n * `sessionsConfig` at 4, because `deepbookRegistry` sits between them; the other three\n * (`cancelLiveOrder`, `cancelLiveOrders`, `withdrawSettledAmounts`) take no\n * `deepbookRegistry` and so keep 1 and 3 like the Predict wrappers:\n * the surrounding spot-over-Account workflow — discovering the embedded balance manager,\n * reading resting orders and locked balances — is not modelled yet, so a wrapped builder\n * would be hard to use well. They are reachable from the generated bindings meanwhile.\n */\nexport class SessionsContract {\n\t#config: SessionsConfig;\n\n\tconstructor(config: SessionsConfig) {\n\t\tthis.#config = config;\n\t}\n\n\t// The generated thunks resolve the package address and auto-inject the shared\n\t// `SessionsConfig` from this object. `accountRegistry` stays an explicit argument —\n\t// it belongs to the account package, which is a separate codegen entry.\n\tget #generatedConfig() {\n\t\treturn {\n\t\t\tsessionsPackageId: this.#config.sessionsPackageId,\n\t\t\tsessionsConfig: this.#config.sessionsConfig,\n\t\t};\n\t}\n\n\t/**\n\t * @description The owner's canonical `AccountWrapper` id — derived off-chain, no read.\n\t * Every builder here takes that id.\n\t */\n\tderiveAccountWrapperId(owner: string): string {\n\t\treturn new AccountContract({\n\t\t\taccountPackageId: this.#config.accountPackageId,\n\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t}).deriveAccountWrapperId(owner);\n\t}\n\n\t/**\n\t * @description The owner's canonical ACCOUNT id — a different derived object from the\n\t * wrapper. The session grants hang off this one, so this is what\n\t * {@link deriveSessionsFieldId} and {@link decodeSessions} work from.\n\t */\n\tderiveAccountId(owner: string): string {\n\t\treturn deriveObjectID(\n\t\t\tthis.#config.accountRegistry,\n\t\t\t`${this.#config.accountPackageId}::account_registry::AccountKey`,\n\t\t\tAccountKey.serialize({ pos0: owner }).toBytes(),\n\t\t);\n\t}\n\n\t/**\n\t * @description The object id of the owner's `DataKey<SessionsApp>` dynamic field —\n\t * fetch this object and pass its BCS contents to {@link decodeSessions}. There is no\n\t * bulk on-chain read, so this is the route to enumerating grants.\n\t */\n\tderiveSessionsFieldId(owner: string): string {\n\t\t// A PLAIN dynamic field, not a derived object: `account::attach` writes it with\n\t\t// `df::add` (`use fun df::add as UID.add`), whereas the account and wrapper ids are\n\t\t// claimed through `derived_object::claim`. `deriveObjectID` would wrap the tag in\n\t\t// `0x2::derived_object::DerivedObjectKey<..>` and yield an id that points at nothing.\n\t\treturn deriveDynamicFieldID(\n\t\t\tthis.deriveAccountId(owner),\n\t\t\t`${this.#config.accountPackageId}::account::DataKey<${this.#config.sessionsPackageIdV1 ?? this.#config.sessionsPackageId}::sessions::SessionsApp>`,\n\t\t\t// DataKey is source-empty; Move's hidden `dummy_field: bool` is the key's one byte.\n\t\t\tnew Uint8Array([0]),\n\t\t);\n\t}\n\n\t/**\n\t * @description Grant `session` authority over the Account until `now + durationMs`.\n\t * Authority is derived from the transaction SENDER, so the owner must sign this.\n\t * `durationMs` must be > 0 and <= {@link MAX_SESSION_DURATION_MS}; an Account holds at\n\t * most {@link MAX_SESSIONS_PER_ACCOUNT} distinct addresses. Re-authorizing an address\n\t * replaces its expiry in place and consumes no additional slot.\n\t * @returns A function that takes a Transaction object\n\t */\n\tauthorizeSession(params: { wrapperId: string; session: string; durationMs: number | bigint }) {\n\t\treturn (tx: Transaction): void => {\n\t\t\ttx.add(\n\t\t\t\tsessions.authorizeSession({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tsession: params.session,\n\t\t\t\t\t\tdurationMs: params.durationMs,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\t}\n\n\t/**\n\t * @description Remove `session`'s grant. Owner-signed, like `authorizeSession`.\n\t * Deliberately takes no `SessionsConfig`: revocation is not version-gated, so it keeps\n\t * working after the package is retired. Revoking an address that holds no grant is a\n\t * silent no-op — it neither aborts nor emits, so read before and after if you need to\n\t * distinguish \"revoked\" from \"was never granted\".\n\t * @returns A function that takes a Transaction object\n\t */\n\trevokeSession(params: { wrapperId: string; session: string }) {\n\t\treturn (tx: Transaction): void => {\n\t\t\ttx.add(\n\t\t\t\tsessions.revokeSession({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: { wrapper: params.wrapperId, session: params.session },\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\t}\n\n\t/**\n\t * @description Read one session's absolute expiry as `Option<u64>`. Compose in a\n\t * dev-inspect/simulate PTB and decode the returned BCS. Not version-gated.\n\t * @returns A function that takes a Transaction object\n\t */\n\tsessionExpirationMs(params: { wrapperId: string; session: string }) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.sessionExpirationMs({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: { wrapper: params.wrapperId, session: params.session },\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t// === Predict wrappers ===\n\t//\n\t// Each mirrors the Predict entrypoint of the same name, with two differences: the\n\t// caller supplies NO `Auth` (the wrapper mints and consumes app authorization\n\t// internally), and `accountRegistry` + `sessionsConfig` are threaded in. `pricer` is a\n\t// PTB RESULT, not an object — it comes from a preceding `expiry_market::load_live_pricer`\n\t// command in the same transaction. Everything else matches Predict exactly, and Predict\n\t// still performs all parameter validation.\n\n\t/**\n\t * @description Mint a position of an exact payout quantity, as `session`. Pass\n\t * `u64::MAX` for `maxCost` / `maxProbability` to leave either slippage cap\n\t * effectively unbounded — the chain asserts `value <= cap`, so the max value can never\n\t * trip. Both are required; there is no default.\n\t * @returns A function that takes a Transaction object and returns the new order id (u256)\n\t * @deprecated Retired by delayed execution (DBU-885): always aborts through Predict v4\n\t * (`EDelayedExecutionRequired`). Use {@link SessionsContract.enqueueExactQuantity}.\n\t */\n\tmintExactQuantity(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\tpricer: TransactionArgument;\n\t\tlowerTick: number | bigint;\n\t\thigherTick: number | bigint;\n\t\tquantity: number | bigint;\n\t\tmaxCost: number | bigint;\n\t\tmaxProbability: number | bigint;\n\t}) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.mintExactQuantity({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\tpricer: params.pricer,\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tquantity: params.quantity,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t\tmaxProbability: params.maxProbability,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Mint by spending up to a premium budget, flooring the quantity received.\n\t * The chain requires `maxCost > 0`.\n\t * @returns A function that takes a Transaction object and returns the new order id (u256)\n\t * @deprecated Retired by delayed execution (DBU-885): always aborts through Predict v4.\n\t * Use {@link SessionsContract.enqueueExactAmount}.\n\t */\n\tmintExactAmount(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\tpricer: TransactionArgument;\n\t\tlowerTick: number | bigint;\n\t\thigherTick: number | bigint;\n\t\tmaxPremium: number | bigint;\n\t\tminQuantity: number | bigint;\n\t\tmaxCost: number | bigint;\n\t}) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.mintExactAmount({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\tpricer: params.pricer,\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tmaxPremium: params.maxPremium,\n\t\t\t\t\t\tminQuantity: params.minQuantity,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * Mint within an all-in budget as a session. Amounts are raw Move units.\n\t * Requires Sessions/Predict v2 or later.\n\t * @deprecated Retired by delayed execution (DBU-885): always aborts through Predict v4.\n\t * Use {@link SessionsContract.enqueueExactCost}.\n\t */\n\tmintExactCost(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\tpricer: TransactionArgument;\n\t\tlowerTick: number | bigint;\n\t\thigherTick: number | bigint;\n\t\tmaxCost: number | bigint;\n\t\tminQuantity: number | bigint;\n\t}) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.mintExactCost({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\tpricer: params.pricer,\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t\tminQuantity: params.minQuantity,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Close part or all of a live position at the pricer's mark, as `session`.\n\t * `minProbability` / `minProceeds` are close-side slippage floors; `0` disables either,\n\t * and OMITTING them is `0` — unlike the mint caps, which are required. On a delegated\n\t * key this is the direction that closes a position at any price, so pass real floors\n\t * unless you mean to accept whatever the mark gives you.\n\t * @returns A function that takes a Transaction object and returns `Option<u256>` — the\n\t * replacement order id when a partial close leaves quantity open\n\t * @deprecated Retired by delayed execution (DBU-885): always aborts through Predict v4.\n\t * Account positions then have no early exit; queued fills are Open records sold with\n\t * {@link SessionsContract.enqueueRedeemOpen}.\n\t */\n\tredeemLive(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\tpricer: TransactionArgument;\n\t\torderId: bigint;\n\t\tcloseQuantity: number | bigint;\n\t\tminProbability?: number | bigint;\n\t\tminProceeds?: number | bigint;\n\t}) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.redeemLive({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\tpricer: params.pricer,\n\t\t\t\t\t\torderId: params.orderId,\n\t\t\t\t\t\tcloseQuantity: params.closeQuantity,\n\t\t\t\t\t\tminProbability: params.minProbability ?? 0,\n\t\t\t\t\t\tminProceeds: params.minProceeds ?? 0,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Claim a settled position in full, as `session`. Takes no pricer — the\n\t * settlement price is fixed — and no quantity: a settled claim is all-or-nothing.\n\t * @returns A function that takes a Transaction object\n\t */\n\tredeemSettled(params: {\n\t\texpiryMarketId: string;\n\t\twrapperId: string;\n\t\tprotocolConfig: string;\n\t\torderId: bigint;\n\t}) {\n\t\treturn (tx: Transaction): void => {\n\t\t\ttx.add(\n\t\t\t\tsessions.redeemSettled({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tmarket: params.expiryMarketId,\n\t\t\t\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\t\t\t\twrapper: params.wrapperId,\n\t\t\t\t\t\tconfig: params.protocolConfig,\n\t\t\t\t\t\torderId: params.orderId,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\t}\n\n\t// === Queued Predict wrappers (delayed execution, DBU-885) ===\n\t//\n\t// The session form of the order-flow companion's `queue::enqueue_*`, in Sessions v3. Each\n\t// wrapper names the market's `MarketQueue` and the companion's `OrderDesk` next to the market.\n\t// Placement takes no pricer: it reads the oracle objects directly, so each wrapper takes the\n\t// market's three feed ids plus Predict's `OracleRegistry` (the propbook registry). Amounts are\n\t// raw Move units. Each returns the new queue record ID (u64). The queue and Predict perform\n\t// every check; the caps below are only the ones a session key should never send by accident.\n\t//\n\t// They need a config whose `sessionsPackageId` is a Sessions v3 publication, which both\n\t// network records are. Sessions v1 and v2 have none of them.\n\n\t/**\n\t * @description Queue a mint of an exact payout quantity, as `session`. `maxCost` (all-in cap)\n\t * and `maxProbability` (at most 1e9) are required, and the chain refuses an \"unlimited\"\n\t * `maxCost`.\n\t * @returns A function that takes a Transaction object and returns the record id (u64)\n\t */\n\tenqueueExactQuantity(\n\t\tparams: SessionsQueuedOrderTarget & {\n\t\t\tlowerTick: number | bigint;\n\t\t\thigherTick: number | bigint;\n\t\t\tquantity: number | bigint;\n\t\t\tmaxCost: number | bigint;\n\t\t\tmaxProbability: number | bigint;\n\t\t},\n\t) {\n\t\tassertQueuedMaxCost(params.maxCost);\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.enqueueExactQuantity({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\t...this.#queuedTarget(params),\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tquantity: params.quantity,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t\tmaxProbability: params.maxProbability,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Queue a premium-budget mint, as `session`: sized at τ under `maxPremium`, at\n\t * least `minQuantity`, with the all-in debit capped by the required `maxCost`.\n\t * @returns A function that takes a Transaction object and returns the record id (u64)\n\t */\n\tenqueueExactAmount(\n\t\tparams: SessionsQueuedOrderTarget & {\n\t\t\tlowerTick: number | bigint;\n\t\t\thigherTick: number | bigint;\n\t\t\tmaxPremium: number | bigint;\n\t\t\tminQuantity: number | bigint;\n\t\t\tmaxCost: number | bigint;\n\t\t},\n\t) {\n\t\tassertQueuedMaxCost(params.maxCost);\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.enqueueExactAmount({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\t...this.#queuedTarget(params),\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tmaxPremium: params.maxPremium,\n\t\t\t\t\t\tminQuantity: params.minQuantity,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Queue an all-in-budget mint, as `session`: sized at τ so the all-in cost fits\n\t * `maxCost`, at least `minQuantity`.\n\t * @returns A function that takes a Transaction object and returns the record id (u64)\n\t */\n\tenqueueExactCost(\n\t\tparams: SessionsQueuedOrderTarget & {\n\t\t\tlowerTick: number | bigint;\n\t\t\thigherTick: number | bigint;\n\t\t\tmaxCost: number | bigint;\n\t\t\tminQuantity: number | bigint;\n\t\t},\n\t) {\n\t\tassertQueuedMaxCost(params.maxCost);\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.enqueueExactCost({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\t...this.#queuedTarget(params),\n\t\t\t\t\t\tlowerTick: params.lowerTick,\n\t\t\t\t\t\thigherTick: params.higherTick,\n\t\t\t\t\t\tmaxCost: params.maxCost,\n\t\t\t\t\t\tminQuantity: params.minQuantity,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t/**\n\t * @description Queue an early sell of the Open record `recordId` (its queue record ID, not\n\t * the position's order ID), as `session`. `minProbability` and `minProceeds` are the close\n\t * floors at τ and are required: on a delegated key, `0` closes at any price, so pass it only\n\t * on purpose.\n\t * @returns A function that takes a Transaction object and returns the new record id (u64)\n\t */\n\tenqueueRedeemOpen(\n\t\tparams: SessionsQueuedOrderTarget & {\n\t\t\trecordId: number | bigint;\n\t\t\tcloseQuantity: number | bigint;\n\t\t\tminProbability: number | bigint;\n\t\t\tminProceeds: number | bigint;\n\t\t},\n\t) {\n\t\treturn (tx: Transaction): TransactionResult =>\n\t\t\ttx.add(\n\t\t\t\tsessions.enqueueRedeemOpen({\n\t\t\t\t\tconfig: this.#generatedConfig,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\t...this.#queuedTarget(params),\n\t\t\t\t\t\trecordId: params.recordId,\n\t\t\t\t\t\tcloseQuantity: params.closeQuantity,\n\t\t\t\t\t\tminProbability: params.minProbability,\n\t\t\t\t\t\tminProceeds: params.minProceeds,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t}\n\n\t// The leading arguments every queued wrapper shares, in the Move order: `(queue, market,\n\t// account_registry, wrapper, sessions_config, desk, config, propbook_registry, pyth, bs_values,\n\t// bs_svi, …)`. `sessions_config` comes from the generated config.\n\t#queuedTarget(params: SessionsQueuedOrderTarget) {\n\t\treturn {\n\t\t\tqueue: params.queueId ?? deriveQueueId(params.queueRegistry, params.expiryMarketId),\n\t\t\tmarket: params.expiryMarketId,\n\t\t\taccountRegistry: this.#config.accountRegistry,\n\t\t\twrapper: params.wrapperId,\n\t\t\tdesk: params.orderDesk,\n\t\t\tconfig: params.protocolConfig,\n\t\t\tpropbookRegistry: params.oracleRegistry,\n\t\t\tpyth: params.pythFeed,\n\t\t\tbsValues: params.blockScholesValueStore,\n\t\t\tbsSvi: params.blockScholesSviStore,\n\t\t};\n\t}\n\n\t/**\n\t * @description Decode an Account's stored grants from the raw BCS content of its\n\t * `DataKey<SessionsApp>` dynamic FIELD object — the whole\n\t * `Field<DataKey<SessionsApp>, SessionsData>`, as the core API returns it, not the\n\t * inner `SessionsData`. Get the id from {@link deriveSessionsFieldId}.\n\t *\n\t * There is no bulk on-chain read — `sessionExpirationMs` answers one address at a time —\n\t * so listing grants means fetching that field and decoding it here. Note the field hangs\n\t * off the DERIVED ACCOUNT address, not the wrapper address; they are different objects.\n\t *\n\t * Expired grants are never pruned automatically and keep occupying slots, so callers\n\t * managing the {@link MAX_SESSIONS_PER_ACCOUNT} cap should list, drop anything already\n\t * expired, and revoke before granting again.\n\t */\n\tstatic decodeSessions(contents: Uint8Array): SessionGrant[] {\n\t\t// Assert full consumption. `@mysten/bcs`'s ULEB reader indexes the underlying\n\t\t// ArrayBuffer rather than the view, so a truncated SUBARRAY — which is exactly what a\n\t\t// gRPC `content` field is — can read past its bound and decode to `[]` with no error.\n\t\t// Re-serializing and comparing lengths turns both truncation and trailing junk into a\n\t\t// throw, so \"no grants\" can only ever mean no grants.\n\t\tconst field = SessionsDataField.parse(contents);\n\t\tconst reencoded = SessionsDataField.serialize(field).toBytes();\n\t\tif (reencoded.length !== contents.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`sessions field is ${contents.length} bytes but its contents encode to ${reencoded.length}; ` +\n\t\t\t\t\t'the bytes are truncated or carry trailing data',\n\t\t\t);\n\t\t}\n\t\treturn field.value.sessions.contents.map((entry) => ({\n\t\t\tsession: entry.key,\n\t\t\texpiresAtMs: BigInt(entry.value),\n\t\t}));\n\t}\n\n\t/** Grants from {@link decodeSessions} that are still live at `nowMs`. */\n\tstatic activeSessions(grants: readonly SessionGrant[], nowMs: number | bigint): SessionGrant[] {\n\t\tconst now = BigInt(nowMs);\n\t\t// The chain asserts `now < expiresAtMs`, so a grant is dead AT its expiry.\n\t\treturn grants.filter((g) => now < g.expiresAtMs);\n\t}\n\n\t/**\n\t * @description Grants that are already dead at `nowMs` — the complement of\n\t * {@link activeSessions}, and the list to revoke when reclaiming slots. Use this rather\n\t * than filtering by hand: `nowMs > expiresAtMs` looks equivalent but leaves the grant\n\t * expiring exactly at `nowMs` occupying a slot forever.\n\t */\n\tstatic expiredSessions(grants: readonly SessionGrant[], nowMs: number | bigint): SessionGrant[] {\n\t\tconst now = BigInt(nowMs);\n\t\treturn grants.filter((g) => now >= g.expiresAtMs);\n\t}\n}\n\n// === Generated bindings ===\n// NOTE: this namespace carries the DeepBook spot session calls too\n// (`placeLimitOrder`, `placeMarketOrder`, `cancelLiveOrder(s)`, `withdrawSettledAmounts`).\n// They are generated and callable; they are simply not wrapped on `SessionsContract`.\nexport * as sessionsMoveCalls from './contracts/deepbook_sessions/sessions.js';\nexport * as sessionConfigMoveCalls from './contracts/deepbook_sessions/session_config.js';\nexport {\n\tSessionsApp,\n\tSessionsData,\n\tSessionAuthorized,\n\tSessionRevoked,\n} from './contracts/deepbook_sessions/sessions.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8EA,SAAgB,kBACf,SACwD;AAGxD,KAAI,YAAY,UAAW,QAAO;AAClC,KAAI,YAAY,UAAW,QAAO;AAClC,OAAM,IAAI,MACT,8EAA8E,QAAQ,mJAItF;;AAkCF,MAAM,WAAW,MAAM,OAAO;AAG9B,SAAS,oBAAoB,SAAgC;CAC5D,MAAM,QAAQ,OAAO,QAAQ;AAC7B,KAAI,SAAS,MAAM,SAAS,QAC3B,OAAM,IAAI,MACT,2FAA2F,QAC3F;;;AAKH,MAAa,0BAA0B,MAAU,KAAK,KAAK;;AAG3D,MAAa,2BAA2B;AAOxC,MAAM,oBAAoB,IAAI,OAAO,+BAA+B;CACnE,IAAI,IAAI;CACR,MAAM,IAAI,MAAM;CAChB,OAAO;CACP,CAAC;AAIF,MAAM,aAAa,IAAI,OAAO,cAAc,EAAE,MAAM,IAAI,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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