{"version":3,"file":"positions.mjs","names":[],"sources":["../../../src/predict/reads/positions.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs } from '@mysten/sui/bcs';\nimport type { ClientWithCoreApi, SuiClientTypes } from '@mysten/sui/client';\nimport { deriveDynamicFieldID, normalizeSuiAddress } from '@mysten/sui/utils';\nimport { type GeneratedConfig } from '../config/generated.js';\nimport { deriveAccountWrapperIdFrom } from '../tx/common.js';\nimport { AccountWrapper } from '../../account.js';\nimport { PositionKey, PredictData } from '../../contracts/deepbook_predict/predict_account.js';\n\n// ============================================================================\n// Chain-only position enumeration.\n//\n// Every open position is tracked under the owner's account:\n// `predict_account::PredictData.positions` is a\n// `Table<PositionKey{expiry_market_id, order_id}, Position>` — and Table\n// entries are dynamic fields, so the KEYS (everything redeem/claim need)\n// arrive directly from a dynamic-field listing. No indexer, no simulation.\n//\n// The walk (all parsing is exact BCS via `include: {content: true}`; the account\n// and PredictData struct layouts come from the generated `contracts/*` MoveStructs\n// so they can't drift from the deployed `account`/`predict_account` sources):\n//   1. wrapper object (id derived client-side)     → account UID\n//   2. derived DataKey<PredictApp> field object     → positions Table id\n//   3. listDynamicFields(table)                    → PositionKey per entry\n// Steps 1-2 resolve ids that are immutable once created — cache them per\n// owner (the facade does) and steady state is ONE call per page of positions.\n// ============================================================================\n\n// sui::dynamic_field::Field<DataKey<PredictApp>, PredictData>. DataKey is\n// source-empty, but Move inserts a hidden `dummy_field: bool` into empty\n// structs — so the name occupies ONE zero byte between id and value (and the\n// same byte is the derived-field key, below). The `value` uses the generated\n// `PredictData` layout so it tracks the deployed struct.\nconst PredictDataFieldBcs = bcs.struct('Field<DataKey,PredictData>', {\n\tid: bcs.Address,\n\tname: bcs.bool(), // DataKey's hidden dummy_field\n\tvalue: PredictData,\n});\n\n/** One open position — the coordinates redeem/claim/hasPosition take. */\nexport interface OpenPosition {\n\tmarketId: string;\n\torderId: bigint;\n}\n\n/** Resolved-once ids for an owner's position store (cache these). */\nexport interface PositionsHandle {\n\taccountUid: string;\n\t/** Null until the account's Predict data exists (first trade/builder-code). */\n\tpositionsTableId: string | null;\n\t/** Open-position count at resolution time (from the Table's size). */\n\tpositionCount: bigint;\n}\n\nasync function contentOf(client: ClientWithCoreApi, objectId: string): Promise<Uint8Array | null> {\n\ttry {\n\t\tconst { object } = await client.core.getObject({ objectId, include: { content: true } });\n\t\treturn object.content ?? null;\n\t} catch (e) {\n\t\t// Only a genuinely absent object means \"no positions\" (never-onboarded\n\t\t// owner, or no Predict data yet). Anything else — transport failures,\n\t\t// rate limits — must surface, not silently read as an empty portfolio.\n\t\tif (/not.?found|does not exist|deleted|NOT_FOUND/i.test(String(e))) return null;\n\t\tthrow e;\n\t}\n}\n\n/**\n * Resolve the immutable id chain for an owner's positions: wrapper → account\n * UID → PredictData → positions Table. Returns null when the owner has never\n * created a Predict account.\n */\nexport async function resolvePositionsTable(\n\tclient: ClientWithCoreApi,\n\tconfig: GeneratedConfig,\n\towner: string,\n): Promise<PositionsHandle | null> {\n\tconst wrapperContent = await contentOf(client, deriveAccountWrapperIdFrom(config, owner));\n\tif (!wrapperContent) return null;\n\tconst accountUid = normalizeSuiAddress(AccountWrapper.parse(wrapperContent).account.account_id);\n\n\t// The PredictData field id is derivable — no listing needed for this hop.\n\tconst dataFieldId = deriveDynamicFieldID(\n\t\taccountUid,\n\t\t`${config.accountPackageId}::account::DataKey<${config.predictPackageIdV1}::predict_account::PredictApp>`,\n\t\tnew Uint8Array([0]), // DataKey's hidden dummy_field: bool = false\n\t);\n\tconst fieldContent = await contentOf(client, dataFieldId);\n\tif (!fieldContent) return { accountUid, positionsTableId: null, positionCount: 0n };\n\n\tconst data = PredictDataFieldBcs.parse(fieldContent).value;\n\treturn {\n\t\taccountUid,\n\t\tpositionsTableId: normalizeSuiAddress(data.positions.id),\n\t\tpositionCount: data.positions.size,\n\t};\n}\n\n/**\n * List open positions from a resolved positions Table: one call per page,\n * keys parsed from the dynamic-field NAMES (no per-entry fetches).\n */\nexport async function positionsFromTable(\n\tclient: ClientWithCoreApi,\n\tpositionsTableId: string,\n\topts: { limit?: number; maxPages?: number } = {},\n): Promise<OpenPosition[]> {\n\tconst limit = opts.limit ?? 1000;\n\tconst maxPages = opts.maxPages ?? 10;\n\tconst out: OpenPosition[] = [];\n\tlet cursor: string | undefined = undefined;\n\tfor (let page = 0; page < maxPages; page++) {\n\t\tconst res: SuiClientTypes.ListDynamicFieldsResponse = await client.core.listDynamicFields({\n\t\t\tparentId: positionsTableId,\n\t\t\tlimit,\n\t\t\tcursor,\n\t\t});\n\t\tfor (const entry of res.dynamicFields) {\n\t\t\tconst key = PositionKey.parse(entry.name.bcs);\n\t\t\tout.push({\n\t\t\t\tmarketId: normalizeSuiAddress(key.expiry_market_id),\n\t\t\t\torderId: key.order_id,\n\t\t\t});\n\t\t}\n\t\tif (!res.hasNextPage || !res.cursor) return out;\n\t\tcursor = res.cursor;\n\t}\n\tthrow new Error(\n\t\t`positions listing exceeded ${maxPages} pages (${out.length} so far) — raise maxPages`,\n\t);\n}\n\n/** Convenience: resolve + list in one call (uncached; the facade caches). */\nexport async function positions(\n\tclient: ClientWithCoreApi,\n\tconfig: GeneratedConfig,\n\towner: string,\n\topts: { limit?: number; maxPages?: number } = {},\n): Promise<OpenPosition[]> {\n\tconst handle = await resolvePositionsTable(client, config, owner);\n\tif (!handle?.positionsTableId) return [];\n\treturn positionsFromTable(client, handle.positionsTableId, opts);\n}\n"],"mappings":";;;;;;;AAkCA,MAAM,sBAAsB,IAAI,OAAO,8BAA8B;CACpE,IAAI,IAAI;CACR,MAAM,IAAI,MAAM;CAChB,OAAO;CACP,CAAC;AAiBF,eAAe,UAAU,QAA2B,UAA8C;AACjG,KAAI;EACH,MAAM,EAAE,WAAW,MAAM,OAAO,KAAK,UAAU;GAAE;GAAU,SAAS,EAAE,SAAS,MAAM;GAAE,CAAC;AACxF,SAAO,OAAO,WAAW;UACjB,GAAG;AAIX,MAAI,+C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