@lightconexyz/lightcone-sdk 0.8.1 → 0.8.2
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/README.md +150 -3
- package/dist/auth/client.d.ts +17 -1
- package/dist/auth/client.d.ts.map +1 -1
- package/dist/auth/client.js +68 -0
- package/dist/auth/client.js.map +1 -1
- package/dist/auth/index.d.ts +57 -5
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +26 -5
- package/dist/auth/index.js.map +1 -1
- package/dist/client.d.ts +23 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +38 -2
- package/dist/client.js.map +1 -1
- package/dist/context.d.ts +23 -2
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +238 -17
- package/dist/context.js.map +1 -1
- package/dist/domain/market/outcome.d.ts +9 -3
- package/dist/domain/market/outcome.d.ts.map +1 -1
- package/dist/domain/market/outcome.js +10 -7
- package/dist/domain/market/outcome.js.map +1 -1
- package/dist/domain/market/wire.d.ts +3 -3
- package/dist/domain/market/wire.d.ts.map +1 -1
- package/dist/domain/market/wire.js.map +1 -1
- package/dist/domain/orderbook/wire.d.ts +5 -0
- package/dist/domain/orderbook/wire.d.ts.map +1 -1
- package/dist/domain/orderbook/wire.js.map +1 -1
- package/dist/domain/position/client.d.ts +160 -4
- package/dist/domain/position/client.d.ts.map +1 -1
- package/dist/domain/position/client.js +592 -4
- package/dist/domain/position/client.js.map +1 -1
- package/dist/domain/position/index.d.ts +54 -3
- package/dist/domain/position/index.d.ts.map +1 -1
- package/dist/domain/position/index.js +1 -0
- package/dist/domain/position/index.js.map +1 -1
- package/dist/domain/position/state.d.ts +118 -0
- package/dist/domain/position/state.d.ts.map +1 -0
- package/dist/domain/position/state.js +262 -0
- package/dist/domain/position/state.js.map +1 -0
- package/dist/error.d.ts +8 -2
- package/dist/error.d.ts.map +1 -1
- package/dist/error.js +14 -1
- package/dist/error.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/prelude.d.ts +6 -5
- package/dist/prelude.d.ts.map +1 -1
- package/dist/prelude.js +10 -1
- package/dist/prelude.js.map +1 -1
- package/dist/privy/client.d.ts +4 -0
- package/dist/privy/client.d.ts.map +1 -1
- package/dist/privy/client.js +4 -0
- package/dist/privy/client.js.map +1 -1
- package/dist/rpc.d.ts +46 -1
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +125 -0
- package/dist/rpc.js.map +1 -1
- package/dist/shared/api_response.d.ts +7 -0
- package/dist/shared/api_response.d.ts.map +1 -1
- package/dist/shared/api_response.js +16 -0
- package/dist/shared/api_response.js.map +1 -1
- package/dist/shared/index.d.ts +1 -1
- package/dist/shared/index.d.ts.map +1 -1
- package/dist/shared/index.js +2 -1
- package/dist/shared/index.js.map +1 -1
- package/dist/shared/signing.d.ts +17 -0
- package/dist/shared/signing.d.ts.map +1 -1
- package/dist/shared/signing.js +27 -0
- package/dist/shared/signing.js.map +1 -1
- package/dist/shared/types.d.ts +3 -1
- package/dist/shared/types.d.ts.map +1 -1
- package/dist/shared/types.js +12 -4
- package/dist/shared/types.js.map +1 -1
- package/dist/ws/client.browser.d.ts +4 -0
- package/dist/ws/client.browser.d.ts.map +1 -1
- package/dist/ws/client.browser.js +13 -1
- package/dist/ws/client.browser.js.map +1 -1
- package/dist/ws/client.node.d.ts +4 -0
- package/dist/ws/client.node.d.ts.map +1 -1
- package/dist/ws/client.node.js +13 -1
- package/dist/ws/client.node.js.map +1 -1
- package/dist/ws/index.d.ts +24 -0
- package/dist/ws/index.d.ts.map +1 -1
- package/dist/ws/index.js +162 -1
- package/dist/ws/index.js.map +1 -1
- package/dist/ws/subscriptions.d.ts +12 -1
- package/dist/ws/subscriptions.d.ts.map +1 -1
- package/dist/ws/subscriptions.js +11 -0
- package/dist/ws/subscriptions.js.map +1 -1
- package/dist/ws/types.d.ts +5 -0
- package/dist/ws/types.d.ts.map +1 -1
- package/dist/ws/types.js.map +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/domain/position/client.ts"],"names":[],"mappings":";;;AAAA,6CAAsF;AAEtF,2CAAkD;AAClD,qCAAyC;AACzC,6DAWoC;AACpC,2CAAmD;AACnD,qDAA2F;AAiB3F,yCAWoB;AAEpB,MAAa,SAAS;IACS;IAA7B,YAA6B,MAAqB;QAArB,WAAM,GAAN,MAAM,CAAe;IAAG,CAAC;IAEtD,wEAAwE;IAExE,GAAG,CAAC,KAAgB,EAAE,MAAiB;QACrC,OAAO,IAAA,oBAAc,EAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACjE,CAAC;IAED,wEAAwE;IAExE,KAAK,CAAC,GAAG,CAAC,UAAkB;QAC1B,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,kBAAkB,CAAC,UAAU,CAAC,YAAY,CAAC;QAClG,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAoB,GAAG,EAAE,kBAAW,CAAC,UAAU,CAAC,CAAC;IAC9E,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,UAAkB,EAAE,YAAoB;QACzD,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,kBAAkB,CAAC,UAAU,CAAC,YAAY,kBAAkB,CAAC,YAAY,CAAC,YAAY,CAAC;QAC9I,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAA0B,GAAG,EAAE,kBAAW,CAAC,UAAU,CAAC,CAAC;IACpF,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,SAAS;QACb,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,MAAM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CAAC,IAAc,CAAC,CAAC;IAChE,CAAC;CACF;AAxUD,8BAwUC","sourcesContent":["import { PublicKey, Transaction, type TransactionInstruction } from \"@solana/web3.js\";\nimport type { ClientContext } from \"../../context\";\nimport { requireConnection } from \"../../context\";\nimport { RetryPolicy } from \"../../http\";\nimport {\n buildRedeemWinningsIx,\n buildWithdrawConditionalFromPositionIx,\n buildInitPositionTokensIx,\n buildExtendPositionTokensIx,\n buildDepositToGlobalIx,\n buildDepositToGlobalIxWithAlt,\n buildGlobalToMarketDepositIx,\n buildWithdrawFromGlobalIx,\n buildClosePositionAltIx,\n buildClosePositionTokenAccountsIx,\n} from \"../../program/instructions\";\nimport { getPositionPda } from \"../../program/pda\";\nimport { deserializePosition as deserializeProgramPosition } from \"../../program/accounts\";\nimport type {\n Position as ProgramPosition,\n RedeemWinningsParams,\n WithdrawConditionalFromPositionParams,\n WithdrawFromPositionParams,\n InitPositionTokensParams,\n ExtendPositionTokensParams,\n DepositToGlobalParams,\n DepositToGlobalAltContext,\n GlobalToMarketDepositParams,\n WithdrawFromGlobalParams,\n ClosePositionAltParams,\n ClosePositionTokenAccountsParams,\n} from \"../../program/types\";\nimport type { DepositTokenBalancesSnapshot } from \"./index\";\nimport type { MarketPositionsResponse, PositionsResponse } from \"./wire\";\nimport {\n DepositBuilder,\n MergeBuilder,\n WithdrawBuilder,\n RedeemWinningsBuilder,\n WithdrawFromPositionBuilder,\n InitPositionTokensBuilder,\n ExtendPositionTokensBuilder,\n DepositToGlobalBuilder,\n WithdrawFromGlobalBuilder,\n GlobalToMarketDepositBuilder,\n} from \"./builders\";\n\nexport class Positions {\n constructor(private readonly client: ClientContext) {}\n\n // ── PDA helpers ──────────────────────────────────────────────────────\n\n pda(owner: PublicKey, market: PublicKey): PublicKey {\n return getPositionPda(owner, market, this.client.programId)[0];\n }\n\n // ── HTTP methods ─────────────────────────────────────────────────────\n\n async get(userPubkey: string): Promise<PositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/${encodeURIComponent(userPubkey)}/positions`;\n return this.client.http.get<PositionsResponse>(url, RetryPolicy.Idempotent);\n }\n\n async getForMarket(userPubkey: string, marketPubkey: string): Promise<MarketPositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/${encodeURIComponent(userPubkey)}/markets/${encodeURIComponent(marketPubkey)}/positions`;\n return this.client.http.get<MarketPositionsResponse>(url, RetryPolicy.Idempotent);\n }\n\n /**\n * Get all conditional-token positions for the authenticated user across\n * every market. The wallet is resolved server-side from the auth cookie,\n * so no parameter is required. Same response shape as `get()`.\n *\n * `GET /api/users/positions`\n */\n async positions(): Promise<PositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/positions`;\n return this.client.http.get<PositionsResponse>(url, RetryPolicy.Idempotent);\n }\n\n /**\n * Same as {@link positions}, but uses the supplied `cookieHeader` for this\n * call instead of the SDK's process-wide cookie store.\n *\n * Intended for server-side cookie forwarding (SSR / server functions)\n * where the per-request browser cookie can't propagate to the shared\n * client. In a browser context this is equivalent to {@link positions}\n * because the runtime is already attaching the cookie via\n * `credentials: \"include\"`.\n */\n async positionsWithCookies(cookieHeader: string): Promise<PositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/positions`;\n return this.client.http.getWithCookies<PositionsResponse>(\n url,\n RetryPolicy.Idempotent,\n cookieHeader,\n );\n }\n\n /**\n * Get the authenticated user's positions in a specific market. The wallet\n * is resolved server-side from the auth cookie.\n *\n * `GET /api/users/markets/{market_pubkey}/positions`\n */\n async positionsForMarket(marketPubkey: string): Promise<MarketPositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/markets/${encodeURIComponent(marketPubkey)}/positions`;\n return this.client.http.get<MarketPositionsResponse>(url, RetryPolicy.Idempotent);\n }\n\n /**\n * Same as {@link positionsForMarket}, but uses the supplied `cookieHeader`\n * for this call instead of the SDK's process-wide cookie store. For\n * server-side cookie forwarding (SSR / server functions).\n */\n async positionsForMarketWithCookies(\n marketPubkey: string,\n cookieHeader: string,\n ): Promise<MarketPositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/markets/${encodeURIComponent(marketPubkey)}/positions`;\n return this.client.http.getWithCookies<MarketPositionsResponse>(\n url,\n RetryPolicy.Idempotent,\n cookieHeader,\n );\n }\n\n /**\n * Get a confirmed-slot snapshot of the authenticated user's deposit-token\n * balances. When supplied, `minContextSlot` prevents an older cached\n * snapshot from satisfying the request.\n */\n async depositTokenBalances(\n minContextSlot?: number\n ): Promise<DepositTokenBalancesSnapshot> {\n const query =\n minContextSlot === undefined\n ? \"\"\n : `?min_context_slot=${encodeURIComponent(minContextSlot)}`;\n const url = `${this.client.http.baseUrl()}/api/users/deposit-token-balances${query}`;\n return this.client.http.get<DepositTokenBalancesSnapshot>(\n url,\n RetryPolicy.Idempotent,\n );\n }\n\n /**\n * Same as {@link depositTokenBalances}, but uses the supplied `cookieHeader`\n * for this call instead of the SDK's process-wide cookie store.\n *\n * Intended for server-side cookie forwarding (SSR / server functions)\n * where the per-request browser cookie can't propagate to the shared\n * client. In a browser context this is equivalent to\n * {@link depositTokenBalances} because the runtime is already attaching\n * the cookie via `credentials: \"include\"`.\n */\n async depositTokenBalancesWithCookies(\n minContextSlot: number | undefined,\n cookieHeader: string,\n ): Promise<DepositTokenBalancesSnapshot> {\n const query =\n minContextSlot === undefined\n ? \"\"\n : `?min_context_slot=${encodeURIComponent(minContextSlot)}`;\n const url = `${this.client.http.baseUrl()}/api/users/deposit-token-balances${query}`;\n return this.client.http.getWithCookies<DepositTokenBalancesSnapshot>(\n url,\n RetryPolicy.Idempotent,\n cookieHeader,\n );\n }\n\n // ── On-chain transaction builders ────────────────────────────────────\n\n redeemWinningsIx(\n params: RedeemWinningsParams,\n outcomeIndex: number\n ): TransactionInstruction {\n return buildRedeemWinningsIx(params, outcomeIndex, this.client.programId);\n }\n\n withdrawConditionalFromPositionIx(\n params: WithdrawConditionalFromPositionParams\n ): TransactionInstruction {\n return buildWithdrawConditionalFromPositionIx(params, this.client.programId);\n }\n\n withdrawFromPositionIx(\n params: WithdrawFromPositionParams\n ): TransactionInstruction {\n return this.withdrawConditionalFromPositionIx(params);\n }\n\n initPositionTokensIx(\n params: InitPositionTokensParams,\n numOutcomes: number\n ): TransactionInstruction {\n return buildInitPositionTokensIx(params, numOutcomes, this.client.programId);\n }\n\n extendPositionTokensIx(\n params: ExtendPositionTokensParams,\n numOutcomes: number\n ): TransactionInstruction {\n return buildExtendPositionTokensIx(params, numOutcomes, this.client.programId);\n }\n\n depositToGlobalIx(params: DepositToGlobalParams): TransactionInstruction {\n return buildDepositToGlobalIx(params, this.client.programId);\n }\n\n depositToGlobalIxWithAlt(\n params: DepositToGlobalParams,\n altContext: DepositToGlobalAltContext\n ): TransactionInstruction {\n return buildDepositToGlobalIxWithAlt(params, altContext, this.client.programId);\n }\n\n globalToMarketDepositIx(\n params: GlobalToMarketDepositParams,\n numOutcomes: number\n ): TransactionInstruction {\n return buildGlobalToMarketDepositIx(params, numOutcomes, this.client.programId);\n }\n\n withdrawFromGlobalIx(params: WithdrawFromGlobalParams): TransactionInstruction {\n return buildWithdrawFromGlobalIx(params, this.client.programId);\n }\n\n closePositionAltIx(params: ClosePositionAltParams): TransactionInstruction {\n return buildClosePositionAltIx(params, this.client.programId);\n }\n\n closePositionTokenAccountsIx(\n params: ClosePositionTokenAccountsParams,\n numOutcomes: number\n ): TransactionInstruction {\n return buildClosePositionTokenAccountsIx(\n params,\n numOutcomes,\n this.client.programId\n );\n }\n\n // ── Transaction builders (_tx convenience wrappers) ─────────────────\n\n redeemWinningsTx(\n params: RedeemWinningsParams,\n outcomeIndex: number\n ): Transaction {\n const ix = this.redeemWinningsIx(params, outcomeIndex);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n withdrawConditionalFromPositionTx(params: WithdrawConditionalFromPositionParams): Transaction {\n const ix = this.withdrawConditionalFromPositionIx(params);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n withdrawFromPositionTx(params: WithdrawFromPositionParams): Transaction {\n return this.withdrawConditionalFromPositionTx(params);\n }\n\n initPositionTokensTx(\n params: InitPositionTokensParams,\n numOutcomes: number\n ): Transaction {\n const ix = this.initPositionTokensIx(params, numOutcomes);\n return new Transaction({ feePayer: params.payer }).add(ix);\n }\n\n extendPositionTokensTx(\n params: ExtendPositionTokensParams,\n numOutcomes: number\n ): Transaction {\n const ix = this.extendPositionTokensIx(params, numOutcomes);\n return new Transaction({ feePayer: params.operator }).add(ix);\n }\n\n depositToGlobalTx(params: DepositToGlobalParams): Transaction {\n const ix = this.depositToGlobalIx(params);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n depositToGlobalTxWithAlt(\n params: DepositToGlobalParams,\n altContext: DepositToGlobalAltContext\n ): Transaction {\n const ix = this.depositToGlobalIxWithAlt(params, altContext);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n globalToMarketDepositTx(\n params: GlobalToMarketDepositParams,\n numOutcomes: number\n ): Transaction {\n const ix = this.globalToMarketDepositIx(params, numOutcomes);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n withdrawFromGlobalTx(params: WithdrawFromGlobalParams): Transaction {\n const ix = this.withdrawFromGlobalIx(params);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n closePositionAltTx(params: ClosePositionAltParams): Transaction {\n const ix = this.closePositionAltIx(params);\n return new Transaction({ feePayer: params.operator }).add(ix);\n }\n\n closePositionTokenAccountsTx(\n params: ClosePositionTokenAccountsParams,\n numOutcomes: number\n ): Transaction {\n const ix = this.closePositionTokenAccountsIx(params, numOutcomes);\n return new Transaction({ feePayer: params.operator }).add(ix);\n }\n\n // ── Builder factories ──────────────────────────────────────────────\n\n deposit(): DepositBuilder {\n return new DepositBuilder(this.client, this.client.depositSource);\n }\n\n merge(): MergeBuilder {\n return new MergeBuilder(this.client);\n }\n\n withdraw(): WithdrawBuilder {\n return new WithdrawBuilder(this.client, this.client.depositSource);\n }\n\n redeemWinnings(): RedeemWinningsBuilder {\n return new RedeemWinningsBuilder(this.client);\n }\n\n withdrawFromPosition(): WithdrawFromPositionBuilder {\n return new WithdrawFromPositionBuilder(this.client);\n }\n\n withdrawConditionalFromPosition(): WithdrawFromPositionBuilder {\n return new WithdrawFromPositionBuilder(this.client);\n }\n\n initPositionTokens(): InitPositionTokensBuilder {\n return new InitPositionTokensBuilder(this.client);\n }\n\n extendPositionTokens(): ExtendPositionTokensBuilder {\n return new ExtendPositionTokensBuilder(this.client);\n }\n\n depositToGlobal(): DepositToGlobalBuilder {\n return new DepositToGlobalBuilder(this.client);\n }\n\n withdrawFromGlobal(): WithdrawFromGlobalBuilder {\n return new WithdrawFromGlobalBuilder(this.client);\n }\n\n globalToMarketDeposit(): GlobalToMarketDepositBuilder {\n return new GlobalToMarketDepositBuilder(this.client);\n }\n\n // ── On-chain account fetchers (require Connection) ──────────────────\n\n async getOnchain(owner: PublicKey, market: PublicKey): Promise<ProgramPosition | null> {\n const connection = requireConnection(this.client);\n const positionPda = this.pda(owner, market);\n const accountInfo = await connection.getAccountInfo(positionPda);\n if (!accountInfo) {\n return null;\n }\n return deserializeProgramPosition(accountInfo.data as Buffer);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/domain/position/client.ts"],"names":[],"mappings":";;;;;;AA4JA,gDAmCC;AA/LD,6CAKyB;AACzB,iDAU2B;AAC3B,iDAA8C;AAC9C,gDAAwB;AACxB,qCAA6C;AAE7C,2CAGuB;AACvB,uCAAuC;AACvC,qCAAyC;AACzC,6DAaoC;AACpC,mCAAgC;AAChC,2CAAmD;AACnD,qDAA2F;AAC3F,+CAA6E;AAC7E,kDAG8B;AAiB9B,mCAOiB;AAEjB,yCAWoB;AAEpB,yEAAyE;AACzE,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,gFAAgF;AAChF,MAAM,OAAO,GAAG,mBAAsB,CAAC;AAuCvC,uFAAuF;AACvF,SAAS,qBAAqB,CAAC,cAAsB,EAAE,MAAc;IACnE,IAAI,OAAO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oBAAoB;QAClB,OAAO,IAAI,sCAA2B,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACtD,CAAC;IAED,+BAA+B;QAC7B,OAAO,IAAI,sCAA2B,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACtD,CAAC;IAED,kBAAkB;QAChB,OAAO,IAAI,oCAAyB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,CAAC;IAED,oBAAoB;QAClB,OAAO,IAAI,sCAA2B,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACtD,CAAC;IAED,eAAe;QACb,OAAO,IAAI,iCAAsB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACjD,CAAC;IAED,kBAAkB;QAChB,OAAO,IAAI,oCAAyB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,CAAC;IAED,qBAAqB;QACnB,OAAO,IAAI,uCAA4B,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvD,CAAC;IAED,uEAAuE;IAEvE,KAAK,CAAC,UAAU,CAAC,KAAgB,EAAE,MAAiB;QAClD,MAAM,UAAU,GAAG,IAAA,2BAAiB,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAClD,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC5C,MAAM,WAAW,GAAG,MAAM,UAAU,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC;QACjE,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAA,8BAA0B,EAAC,WAAW,CAAC,IAAc,CAAC,CAAC;IAChE,CAAC;CACF;AArlCD,8BAqlCC","sourcesContent":["import {\n PublicKey,\n SystemProgram,\n Transaction,\n type TransactionInstruction,\n} from \"@solana/web3.js\";\nimport {\n createAssociatedTokenAccountInstruction,\n createAssociatedTokenAccountIdempotentInstruction,\n createInitializeAccount3Instruction,\n createTransferInstruction,\n createCloseAccountInstruction,\n createSyncNativeInstruction,\n getAssociatedTokenAddressSync,\n NATIVE_MINT,\n TOKEN_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport bs58 from \"bs58\";\nimport { isAuthenticated } from \"../../auth\";\nimport type { ClientContext } from \"../../context\";\nimport {\n requireConnection,\n requireSigningStrategy,\n} from \"../../context\";\nimport { SdkError } from \"../../error\";\nimport { RetryPolicy } from \"../../http\";\nimport {\n buildDepositIx,\n buildMergeIx,\n buildRedeemWinningsIx,\n buildWithdrawConditionalFromPositionIx,\n buildInitPositionTokensIx,\n buildExtendPositionTokensIx,\n buildDepositToGlobalIx,\n buildDepositToGlobalIxWithAlt,\n buildGlobalToMarketDepositIx,\n buildWithdrawFromGlobalIx,\n buildClosePositionAltIx,\n buildClosePositionTokenAccountsIx,\n} from \"../../program/instructions\";\nimport { Rpc } from \"../../rpc\";\nimport { getPositionPda } from \"../../program/pda\";\nimport { deserializePosition as deserializeProgramPosition } from \"../../program/accounts\";\nimport { validateOutcomeIndex, validateOutcomes } from \"../../program/utils\";\nimport {\n requireNativeSigningStrategy,\n signingStrategyWalletAddress,\n} from \"../../shared/signing\";\nimport type {\n Position as ProgramPosition,\n RedeemWinningsParams,\n WithdrawConditionalFromPositionParams,\n WithdrawFromPositionParams,\n InitPositionTokensParams,\n ExtendPositionTokensParams,\n DepositToGlobalParams,\n DepositToGlobalAltContext,\n GlobalToMarketDepositParams,\n WithdrawFromGlobalParams,\n ClosePositionAltParams,\n ClosePositionTokenAccountsParams,\n} from \"../../program/types\";\nimport type { Market } from \"../market\";\nimport type { DepositTokenBalancesSnapshot } from \"./index\";\nimport {\n solBalanceAvailability,\n unwrapAllSolBalanceAvailability,\n type SolActionCosts,\n type SolBalanceAvailability,\n type SolBalanceComponents,\n type WalletDepositBalancesState,\n} from \"./state\";\nimport type { MarketPositionsResponse, PositionsResponse } from \"./wire\";\nimport {\n DepositBuilder,\n MergeBuilder,\n WithdrawBuilder,\n RedeemWinningsBuilder,\n WithdrawFromPositionBuilder,\n InitPositionTokensBuilder,\n ExtendPositionTokensBuilder,\n DepositToGlobalBuilder,\n WithdrawFromGlobalBuilder,\n GlobalToMarketDepositBuilder,\n} from \"./builders\";\n\n/** Byte allocation for a legacy SPL Token Program (Tokenkeg) account. */\nconst TOKEN_ACCOUNT_SPACE = 165;\n/** Largest exact lamport amount accepted by Solana transaction instructions. */\nconst MAX_U64 = 0xffff_ffff_ffff_ffffn;\n\n/**\n * Identifies the SOL-aware operation represented by an action plan.\n *\n * `wrap` and `unwrapAll` identify explicit native-keypair conversion plans.\n * Ordinary plan kinds do not call those planners or include canonical-account\n * closure.\n */\nexport type SolActionKind =\n | \"split\"\n | \"merge\"\n | \"redeem\"\n | \"nativeWithdraw\"\n | \"wrap\"\n | \"unwrapAll\";\n\n/** Expected changes to the separately authoritative SOL components. */\nexport interface SolComponentDelta {\n /** System-account change in lamports, including unsponsored costs. */\n nativeLamports: bigint;\n /** Persistent canonical WSOL ATA change in lamports. */\n canonicalWsolLamports: bigint;\n}\n\n/** Unsigned prepared transaction plus the exact preflight facts authorizing it. */\nexport interface SolActionPlan {\n /** Operation whose balance semantics produced this plan. */\n kind: SolActionKind;\n /** Fee-prepared message that submission must preserve exactly. */\n transaction: Transaction;\n /** Live fee/rent observations and explicit sponsorship capability. */\n costs: SolActionCosts;\n /** Component totals after action-specific native reserve. */\n availability: SolBalanceAvailability;\n /** Component-wise projection that does not replace authoritative state. */\n expectedDelta: SolComponentDelta;\n}\n\n/** Reject non-bigint, non-positive, or non-u64 lamports before any RPC side effect. */\nfunction assertSolActionAmount(amountLamports: bigint, action: string): void {\n if (typeof amountLamports !== \"bigint\") {\n throw SdkError.validation(`${action} amount must be exact bigint lamports`);\n }\n if (amountLamports <= 0n) {\n throw SdkError.validation(`${action} amount must be greater than zero`);\n }\n if (amountLamports > MAX_U64) {\n throw SdkError.validation(`${action} amount must fit u64`);\n }\n}\n\nfunction assertUnsponsoredPlan(sponsored: boolean): void {\n if (sponsored) {\n throw SdkError.validation(\"sponsored SOL action planning is not supported\");\n }\n}\n\n/**\n * Derive the cross-SDK temporary-account seed for native withdrawal.\n *\n * SHA-256 receives the ASCII domain `lightcone:wsol-withdraw:v1`, one zero byte,\n * raw 32-byte blockhash, wallet, and recipient keys, the amount as unsigned\n * eight-byte big-endian lamports, then the one-byte attempt. The first 16 digest\n * bytes become 32 lowercase hexadecimal ASCII characters for Solana's seed limit.\n */\nexport function nativeWithdrawSeed(\n recentBlockhash: string,\n wallet: PublicKey,\n recipient: PublicKey,\n amountLamports: bigint,\n attempt: number\n): string {\n if (!Number.isInteger(attempt) || attempt < 0 || attempt > 255) {\n throw SdkError.validation(\"temporary WSOL seed attempt must fit u8\");\n }\n if (amountLamports < 0n || amountLamports > MAX_U64) {\n throw SdkError.validation(\"withdraw amount must fit u64\");\n }\n const domain = new TextEncoder().encode(\"lightcone:wsol-withdraw:v1\");\n const blockhash = bs58.decode(recentBlockhash);\n if (blockhash.length !== 32) {\n throw SdkError.validation(\"recent blockhash must decode to 32 bytes\");\n }\n const preimage = new Uint8Array(domain.length + 1 + 32 + 32 + 32 + 8 + 1);\n let offset = 0;\n preimage.set(domain, offset);\n offset += domain.length;\n preimage[offset++] = 0;\n preimage.set(blockhash, offset);\n offset += 32;\n preimage.set(wallet.toBytes(), offset);\n offset += 32;\n preimage.set(recipient.toBytes(), offset);\n offset += 32;\n new DataView(preimage.buffer).setBigUint64(offset, amountLamports, false);\n offset += 8;\n preimage[offset] = attempt;\n return Array.from(sha256(preimage).slice(0, 16), (byte) =>\n byte.toString(16).padStart(2, \"0\")\n ).join(\"\");\n}\n\n/**\n * Plans position operations and explicit canonical WSOL conversions.\n *\n * Explicit conversion state flows as follows: complete matching wallet state and\n * native keypair -> live account and cost reads -> signer, account, reserve, and\n * amount guards -> fee-prepared plan -> unchanged prepared submission -> complete\n * snapshot covering the confirmed slot. An uncertain submission returns control\n * to the caller, which refreshes authoritative state before planning again.\n */\nexport class Positions {\n constructor(private readonly client: ClientContext) {}\n\n // ── PDA helpers ──────────────────────────────────────────────────────\n\n pda(owner: PublicKey, market: PublicKey): PublicKey {\n return getPositionPda(owner, market, this.client.programId)[0];\n }\n\n // ── HTTP methods ─────────────────────────────────────────────────────\n\n async get(userPubkey: string): Promise<PositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/${encodeURIComponent(userPubkey)}/positions`;\n return this.client.http.get<PositionsResponse>(url, RetryPolicy.Idempotent);\n }\n\n async getForMarket(userPubkey: string, marketPubkey: string): Promise<MarketPositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/${encodeURIComponent(userPubkey)}/markets/${encodeURIComponent(marketPubkey)}/positions`;\n return this.client.http.get<MarketPositionsResponse>(url, RetryPolicy.Idempotent);\n }\n\n /**\n * Get all conditional-token positions for the authenticated user across\n * every market. The wallet is resolved server-side from the auth cookie,\n * so no parameter is required. Same response shape as `get()`.\n *\n * `GET /api/users/positions`\n */\n async positions(): Promise<PositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/positions`;\n return this.client.http.get<PositionsResponse>(url, RetryPolicy.Idempotent);\n }\n\n /**\n * Same as {@link positions}, but uses the supplied `cookieHeader` for this\n * call instead of the SDK's process-wide cookie store.\n *\n * Intended for server-side cookie forwarding (SSR / server functions)\n * where the per-request browser cookie can't propagate to the shared\n * client. In a browser context this is equivalent to {@link positions}\n * because the runtime is already attaching the cookie via\n * `credentials: \"include\"`.\n */\n async positionsWithCookies(cookieHeader: string): Promise<PositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/positions`;\n return this.client.http.getWithCookies<PositionsResponse>(\n url,\n RetryPolicy.Idempotent,\n cookieHeader,\n );\n }\n\n /**\n * Get the authenticated user's positions in a specific market. The wallet\n * is resolved server-side from the auth cookie.\n *\n * `GET /api/users/markets/{market_pubkey}/positions`\n */\n async positionsForMarket(marketPubkey: string): Promise<MarketPositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/markets/${encodeURIComponent(marketPubkey)}/positions`;\n return this.client.http.get<MarketPositionsResponse>(url, RetryPolicy.Idempotent);\n }\n\n /**\n * Same as {@link positionsForMarket}, but uses the supplied `cookieHeader`\n * for this call instead of the SDK's process-wide cookie store. For\n * server-side cookie forwarding (SSR / server functions).\n */\n async positionsForMarketWithCookies(\n marketPubkey: string,\n cookieHeader: string,\n ): Promise<MarketPositionsResponse> {\n const url = `${this.client.http.baseUrl()}/api/users/markets/${encodeURIComponent(marketPubkey)}/positions`;\n return this.client.http.getWithCookies<MarketPositionsResponse>(\n url,\n RetryPolicy.Idempotent,\n cookieHeader,\n );\n }\n\n /**\n * Fetch a complete authenticated SPL and native-SOL balance snapshot.\n *\n * `minContextSlot` lower-bounds the cross-component snapshot. Native SOL is\n * required canonical nine-decimal text and remains outside the SPL map. The\n * generic HTTP layer trusts that shape at runtime; WebSocket frames are decoded\n * strictly, while malformed REST exact values fail later when state scales them.\n */\n async depositTokenBalances(\n minContextSlot?: number\n ): Promise<DepositTokenBalancesSnapshot> {\n const query =\n minContextSlot === undefined\n ? \"\"\n : `?min_context_slot=${encodeURIComponent(minContextSlot)}`;\n const url = `${this.client.http.baseUrl()}/api/users/deposit-token-balances${query}`;\n return this.client.http.get<DepositTokenBalancesSnapshot>(\n url,\n RetryPolicy.Idempotent,\n );\n }\n\n /**\n * Same as {@link depositTokenBalances}, but uses the supplied `cookieHeader`\n * for this call instead of the SDK's process-wide cookie store.\n *\n * Intended for server-side cookie forwarding (SSR / server functions)\n * where the per-request browser cookie can't propagate to the shared\n * client. The complete response has the same separate, exact native-SOL\n * contract as {@link depositTokenBalances}. In a browser this is equivalent to\n * {@link depositTokenBalances} because the runtime is already attaching\n * the cookie via `credentials: \"include\"`.\n */\n async depositTokenBalancesWithCookies(\n minContextSlot: number | undefined,\n cookieHeader: string,\n ): Promise<DepositTokenBalancesSnapshot> {\n const query =\n minContextSlot === undefined\n ? \"\"\n : `?min_context_slot=${encodeURIComponent(minContextSlot)}`;\n const url = `${this.client.http.baseUrl()}/api/users/deposit-token-balances${query}`;\n return this.client.http.getWithCookies<DepositTokenBalancesSnapshot>(\n url,\n RetryPolicy.Idempotent,\n cookieHeader,\n );\n }\n\n /**\n * Return a fee-prepared plan for an exact canonical WSOL wrap.\n *\n * The authenticated Trading Wallet must have a local native keypair and complete\n * balance state. Live canonical account data must match that state. An existing\n * account must have account lamports equal to its token amount plus native\n * reserve. Otherwise a later `SyncNative` instruction would recalculate the WSOL\n * token amount from account lamports and wrap donated excess beyond\n * `amountLamports`. The returned transaction contains strict Tokenkeg ATA\n * creation only when the account is absent. It then contains the exact transfer\n * and `SyncNative`. Availability uses the ordinary reserve floor.\n *\n * Callers rebuild immediately before prepared submission. They retain the\n * returned component projection until a complete snapshot covers the confirmed\n * slot. An uncertain outcome requires authoritative refresh before another plan.\n */\n async planWrapSol(\n amountLamports: bigint,\n state: WalletDepositBalancesState\n ): Promise<SolActionPlan> {\n assertSolActionAmount(amountLamports, \"wrap\");\n const wallet = this.conversionPlanningWallet(state);\n const components = state.solComponents();\n const rpc = new Rpc(this.client);\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n const account = await rpc.canonicalWsolAccountInfo(canonical, wallet);\n if (!account && components.canonicalWsolLamports > 0n) {\n throw SdkError.validation(\n \"canonical WSOL balance is positive but its account is unavailable\"\n );\n }\n if (\n account &&\n account.tokenAmountLamports !== components.canonicalWsolLamports\n ) {\n throw SdkError.validation(\n \"live canonical WSOL amount does not match wallet balance state\"\n );\n }\n if (\n account &&\n account.accountLamports !==\n account.tokenAmountLamports + account.nativeReserveLamports\n ) {\n throw SdkError.validation(\n \"canonical WSOL account has unsynchronized native lamports\"\n );\n }\n if (\n account &&\n (account.tokenAmountLamports + amountLamports > MAX_U64 ||\n account.accountLamports + amountLamports > MAX_U64)\n ) {\n throw SdkError.validation(\n \"wrap would exceed canonical WSOL token or account u64 range\"\n );\n }\n const createsCanonicalWsolAccount = account === null;\n const upfrontRentLamports = createsCanonicalWsolAccount\n ? await rpc.minimumBalanceForRentExemption(TOKEN_ACCOUNT_SPACE)\n : 0n;\n const transaction = this.buildWrapSolTransaction(\n wallet,\n amountLamports,\n createsCanonicalWsolAccount\n );\n const feeLamports = await rpc.prepareAndEstimateTransactionFee(transaction);\n const costs: SolActionCosts = {\n feeLamports,\n upfrontRentLamports,\n createsCanonicalWsolAccount,\n sponsored: false,\n };\n const availability = solBalanceAvailability(components, costs);\n const requiredNativeLamports =\n amountLamports + availability.reserveLamports;\n if (requiredNativeLamports > MAX_U64) {\n throw SdkError.validation(\n \"wrap amount and transaction reserve exceed u64 lamports\"\n );\n }\n if (components.nativeLamports < requiredNativeLamports) {\n throw SdkError.validation(\n \"native SOL cannot fund the wrap amount and transaction reserve\"\n );\n }\n return {\n kind: \"wrap\",\n transaction,\n costs,\n availability,\n expectedDelta: {\n nativeLamports:\n -amountLamports - feeLamports - upfrontRentLamports,\n canonicalWsolLamports: amountLamports,\n },\n };\n }\n\n /**\n * Return a fee-prepared plan for closing the complete canonical WSOL account.\n *\n * The Trading Wallet must have a local native keypair. Canonical WSOL in the\n * complete balance state must be positive and equal the live token amount. The\n * returned transaction contains one `CloseAccount` instruction whose authority,\n * destination, and fee payer are that wallet. If submitted successfully, the\n * instruction transfers the complete account balance, including rent and donated\n * lamports. The returned costs contain only the fresh fee. Availability requires\n * native SOL to fund that fee without relying on the later account transfer.\n *\n * Callers rebuild immediately before prepared submission. They retain the\n * returned component projection until a complete snapshot covers the confirmed\n * slot. Signing, submission, or confirmation uncertainty requires authoritative\n * refresh and does not authorize automatic resubmission.\n */\n async planUnwrapWsolAll(\n state: WalletDepositBalancesState\n ): Promise<SolActionPlan> {\n const wallet = this.conversionPlanningWallet(state);\n const components = state.solComponents();\n if (components.canonicalWsolLamports === 0n) {\n throw SdkError.validation(\n \"unwrap-all requires a positive canonical WSOL balance\"\n );\n }\n const rpc = new Rpc(this.client);\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n const account = await rpc.canonicalWsolAccountInfo(canonical, wallet);\n if (!account) {\n throw SdkError.validation(\n \"canonical WSOL account is required for unwrap-all\"\n );\n }\n if (account.tokenAmountLamports !== components.canonicalWsolLamports) {\n throw SdkError.validation(\n \"live canonical WSOL amount does not match wallet balance state\"\n );\n }\n const transaction = this.buildUnwrapWsolAllTransaction(wallet);\n const feeLamports = await rpc.prepareAndEstimateTransactionFee(transaction);\n const costs: SolActionCosts = {\n feeLamports,\n upfrontRentLamports: 0n,\n createsCanonicalWsolAccount: false,\n sponsored: false,\n };\n // Unwrap-all removes the persistent account, so its availability validates\n // SolActionCosts and reserves the fee without the ordinary account floor.\n const availability = unwrapAllSolBalanceAvailability(\n components,\n costs\n );\n const projectedNativeLamports =\n components.nativeLamports + account.accountLamports - feeLamports;\n if (projectedNativeLamports > MAX_U64) {\n throw SdkError.validation(\n \"unwrap-all projected native SOL exceeds the transaction u64 range\"\n );\n }\n return {\n kind: \"unwrapAll\",\n transaction,\n costs,\n availability,\n expectedDelta: {\n nativeLamports: account.accountLamports - feeLamports,\n canonicalWsolLamports: -components.canonicalWsolLamports,\n },\n };\n }\n\n /**\n * Plan one atomic split that consumes canonical WSOL before wrapping a shortfall.\n * Amounts and live costs are lamports; unavailable account, fee, or rent reads\n * fail closed, and sponsored planning is rejected until a sponsor owns costs.\n */\n async planSolSplit(\n market: Market,\n amountLamports: bigint,\n state: WalletDepositBalancesState,\n sponsored: boolean\n ): Promise<SolActionPlan> {\n assertUnsponsoredPlan(sponsored);\n assertSolActionAmount(amountLamports, \"split\");\n const wallet = this.planningWallet(state);\n const components = state.solComponents();\n const rpc = new Rpc(this.client);\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n const canonicalExists = await rpc.canonicalWsolAccountExists(canonical, wallet);\n if (components.canonicalWsolLamports > 0n && !canonicalExists) {\n throw SdkError.validation(\n \"canonical WSOL balance is positive but its account is unavailable\"\n );\n }\n const shortfall =\n amountLamports > components.canonicalWsolLamports\n ? amountLamports - components.canonicalWsolLamports\n : 0n;\n const upfrontRentLamports = canonicalExists\n ? 0n\n : await rpc.minimumBalanceForRentExemption(TOKEN_ACCOUNT_SPACE);\n const transaction = new Transaction({ feePayer: wallet });\n if (!canonicalExists) {\n transaction.add(\n createAssociatedTokenAccountIdempotentInstruction(\n wallet,\n canonical,\n wallet,\n NATIVE_MINT,\n TOKEN_PROGRAM_ID\n )\n );\n }\n if (shortfall > 0n) {\n transaction.add(\n SystemProgram.transfer({ fromPubkey: wallet, toPubkey: canonical, lamports: shortfall }),\n createSyncNativeInstruction(canonical, TOKEN_PROGRAM_ID)\n );\n }\n transaction.add(\n buildDepositIx(\n {\n user: wallet,\n market: new PublicKey(market.pubkey),\n depositMint: NATIVE_MINT,\n amount: amountLamports,\n },\n market.numOutcomes,\n this.client.programId\n )\n );\n const feeLamports = await rpc.prepareAndEstimateTransactionFee(transaction);\n const costs: SolActionCosts = {\n feeLamports,\n upfrontRentLamports,\n createsCanonicalWsolAccount: !canonicalExists,\n sponsored,\n };\n const availability = solBalanceAvailability(components, costs);\n if (amountLamports > availability.spendableLamports) {\n throw SdkError.validation(\n \"split amount exceeds spendable SOL after transaction reserve\"\n );\n }\n if (shortfall + availability.reserveLamports > components.nativeLamports) {\n throw SdkError.validation(\n \"native SOL cannot fund the wrap shortfall and transaction reserve\"\n );\n }\n const walletCosts = sponsored ? 0n : feeLamports + upfrontRentLamports;\n return {\n kind: \"split\",\n transaction,\n costs,\n availability,\n expectedDelta: {\n nativeLamports: -shortfall - walletCosts,\n canonicalWsolLamports: shortfall - amountLamports,\n },\n };\n }\n\n /**\n * Plan a merge that leaves returned WSOL in the persistent canonical ATA.\n * The prepared transaction does not mutate cached state; refresh authority\n * after confirmed submission.\n */\n async planSolMerge(\n market: Market,\n amountLamports: bigint,\n state: WalletDepositBalancesState,\n sponsored: boolean\n ): Promise<SolActionPlan> {\n assertUnsponsoredPlan(sponsored);\n assertSolActionAmount(amountLamports, \"merge\");\n const wallet = this.planningWallet(state);\n const transaction = new Transaction({ feePayer: wallet });\n const { rpc, components, canonicalExists, upfrontRentLamports } =\n await this.receivePlanContext(wallet, state);\n if (!canonicalExists) {\n transaction.add(this.createCanonicalWsolAccount(wallet));\n }\n transaction.add(\n buildMergeIx(\n {\n user: wallet,\n market: new PublicKey(market.pubkey),\n depositMint: NATIVE_MINT,\n amount: amountLamports,\n },\n market.numOutcomes,\n this.client.programId\n )\n );\n return this.finishReceivePlan(\n \"merge\",\n amountLamports,\n transaction,\n rpc,\n components,\n upfrontRentLamports,\n !canonicalExists,\n sponsored\n );\n }\n\n /**\n * Plan a redemption that leaves returned WSOL in the persistent canonical ATA.\n * `amountLamports` is exact collateral scale; `outcomeIndex` is validated\n * against the supplied authoritative `numOutcomes`.\n */\n async planSolRedeem(\n market: PublicKey,\n amountLamports: bigint,\n outcomeIndex: number,\n numOutcomes: number,\n state: WalletDepositBalancesState,\n sponsored: boolean\n ): Promise<SolActionPlan> {\n assertUnsponsoredPlan(sponsored);\n assertSolActionAmount(amountLamports, \"redeem\");\n validateOutcomes(numOutcomes);\n validateOutcomeIndex(outcomeIndex, numOutcomes);\n const wallet = this.planningWallet(state);\n const transaction = new Transaction({ feePayer: wallet });\n const { rpc, components, canonicalExists, upfrontRentLamports } =\n await this.receivePlanContext(wallet, state);\n if (!canonicalExists) {\n transaction.add(this.createCanonicalWsolAccount(wallet));\n }\n transaction.add(\n buildRedeemWinningsIx(\n {\n user: wallet,\n market,\n depositMint: NATIVE_MINT,\n amount: amountLamports,\n },\n outcomeIndex,\n this.client.programId\n )\n );\n return this.finishReceivePlan(\n \"redeem\",\n amountLamports,\n transaction,\n rpc,\n components,\n upfrontRentLamports,\n !canonicalExists,\n sponsored\n );\n }\n\n /**\n * Plan exact native SOL delivery without closing the canonical WSOL ATA.\n *\n * Native funds are preferred. A shortfall uses a bounded seeded Tokenkeg\n * account whose rent returns on close; all account, rent, and fee reads fail\n * closed. At most eight blockhash-scoped candidates bound RPC latency while\n * making accidental exhaustion negligible. The returned transaction already\n * carries its prepared message.\n */\n async planNativeSolWithdrawal(\n recipient: PublicKey,\n amountLamports: bigint,\n state: WalletDepositBalancesState,\n sponsored: boolean\n ): Promise<SolActionPlan> {\n assertUnsponsoredPlan(sponsored);\n assertSolActionAmount(amountLamports, \"withdraw\");\n const wallet = this.planningWallet(state);\n const components = state.solComponents();\n const rpc = new Rpc(this.client);\n const direct = new Transaction({ feePayer: wallet }).add(\n SystemProgram.transfer({ fromPubkey: wallet, toPubkey: recipient, lamports: amountLamports })\n );\n const directFee = await rpc.prepareAndEstimateTransactionFee(direct);\n const directCosts: SolActionCosts = {\n feeLamports: directFee,\n upfrontRentLamports: 0n,\n createsCanonicalWsolAccount: false,\n sponsored,\n };\n const directAvailability = solBalanceAvailability(components, directCosts);\n if (amountLamports > directAvailability.spendableLamports) {\n throw SdkError.validation(\n \"withdraw amount exceeds spendable SOL after transaction reserve\"\n );\n }\n if (\n components.nativeLamports >=\n amountLamports + directAvailability.reserveLamports\n ) {\n return {\n kind: \"nativeWithdraw\",\n transaction: direct,\n costs: directCosts,\n availability: directAvailability,\n expectedDelta: {\n nativeLamports: -amountLamports - (sponsored ? 0n : directFee),\n canonicalWsolLamports: 0n,\n },\n };\n }\n\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n if (!(await rpc.canonicalWsolAccountExists(canonical, wallet))) {\n throw SdkError.validation(\n \"canonical WSOL is required for this native withdrawal\"\n );\n }\n const temporaryRent = await rpc.minimumBalanceForRentExemption(TOKEN_ACCOUNT_SPACE);\n const { blockhash, lastValidBlockHeight } = await rpc.getLatestBlockhash();\n let seed: string | undefined;\n let temporary: PublicKey | undefined;\n // Bound account-existence RPCs; the blockhash and attempt byte make eight collisions remote.\n for (let attempt = 0; attempt <= 7; attempt++) {\n const candidateSeed = nativeWithdrawSeed(\n blockhash,\n wallet,\n recipient,\n amountLamports,\n attempt\n );\n const candidate = await PublicKey.createWithSeed(\n wallet,\n candidateSeed,\n TOKEN_PROGRAM_ID\n );\n if (!(await rpc.accountExists(candidate))) {\n seed = candidateSeed;\n temporary = candidate;\n break;\n }\n }\n if (!seed || !temporary) {\n throw SdkError.validation(\"temporary WSOL seed attempts are exhausted\");\n }\n\n let transaction = this.buildTemporaryNativeWithdrawal(\n wallet,\n recipient,\n amountLamports,\n 1n,\n temporaryRent,\n seed,\n temporary\n );\n transaction.recentBlockhash = blockhash;\n transaction.lastValidBlockHeight = lastValidBlockHeight;\n const initialFee = await rpc.estimatePreparedTransactionFee(transaction);\n const initialCosts: SolActionCosts = {\n feeLamports: initialFee,\n upfrontRentLamports: temporaryRent,\n createsCanonicalWsolAccount: false,\n sponsored,\n };\n const initialAvailability = solBalanceAvailability(components, initialCosts);\n const initialRequired = amountLamports + initialAvailability.reserveLamports;\n if (initialRequired < components.nativeLamports) {\n throw SdkError.validation(\"invalid temporary withdrawal requirement\");\n }\n const initialTransfer = initialRequired - components.nativeLamports;\n transaction = this.buildTemporaryNativeWithdrawal(\n wallet,\n recipient,\n amountLamports,\n initialTransfer,\n temporaryRent,\n seed,\n temporary\n );\n transaction.recentBlockhash = blockhash;\n transaction.lastValidBlockHeight = lastValidBlockHeight;\n const finalFee = await rpc.estimatePreparedTransactionFee(transaction);\n const costs: SolActionCosts = {\n feeLamports: finalFee,\n upfrontRentLamports: temporaryRent,\n createsCanonicalWsolAccount: false,\n sponsored,\n };\n const availability = solBalanceAvailability(components, costs);\n const finalRequired = amountLamports + availability.reserveLamports;\n if (finalRequired < components.nativeLamports) {\n throw SdkError.validation(\"invalid temporary withdrawal requirement\");\n }\n const canonicalTransfer = finalRequired - components.nativeLamports;\n if (canonicalTransfer > components.canonicalWsolLamports) {\n throw SdkError.validation(\n \"canonical WSOL cannot fund the native withdrawal shortfall\"\n );\n }\n if (canonicalTransfer !== initialTransfer) {\n transaction = this.buildTemporaryNativeWithdrawal(\n wallet,\n recipient,\n amountLamports,\n canonicalTransfer,\n temporaryRent,\n seed,\n temporary\n );\n transaction.recentBlockhash = blockhash;\n transaction.lastValidBlockHeight = lastValidBlockHeight;\n const stableFee = await rpc.estimatePreparedTransactionFee(transaction);\n if (stableFee !== finalFee) {\n throw SdkError.validation(\n \"transaction fee changed while rebuilding native withdrawal\"\n );\n }\n }\n return {\n kind: \"nativeWithdraw\",\n transaction,\n costs,\n availability,\n expectedDelta: {\n nativeLamports:\n canonicalTransfer - amountLamports - (sponsored ? 0n : finalFee),\n canonicalWsolLamports: -canonicalTransfer,\n },\n };\n }\n\n /** Resolve the authenticated wallet only from fresh matching cached authority. */\n private planningWallet(state: WalletDepositBalancesState): PublicKey {\n // Cached identity is a signing trust boundary: validate expiry, complete\n // state initialization, and wallet equality before constructing a transaction.\n const credentials = this.client.authCredentials;\n if (!credentials) {\n throw SdkError.validation(\"authenticated credentials are required\");\n }\n if (!isAuthenticated(credentials)) {\n throw SdkError.validation(\"authenticated credentials have expired\");\n }\n if (\n state.walletAddress === undefined ||\n state.contextSlot === undefined ||\n state.nativeSolBalance === undefined\n ) {\n throw SdkError.validation(\"wallet balance state is not initialized\");\n }\n if (state.walletAddress !== credentials.wallet_address) {\n throw SdkError.validation(\n \"authenticated wallet does not match wallet balance state\"\n );\n }\n let wallet: PublicKey;\n try {\n wallet = new PublicKey(credentials.wallet_address);\n } catch (error) {\n throw SdkError.validation(\n `authenticated wallet is invalid: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n const strategy = requireSigningStrategy(this.client);\n const signingAddress = signingStrategyWalletAddress(strategy);\n if (!signingAddress) {\n throw SdkError.validation(\"signing strategy wallet identity is required\");\n }\n let signingWallet: PublicKey;\n try {\n signingWallet = new PublicKey(signingAddress);\n } catch (error) {\n throw SdkError.validation(\n `signing strategy wallet is invalid: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n if (!signingWallet.equals(wallet)) {\n throw SdkError.validation(\n \"signing strategy does not control authenticated wallet\"\n );\n }\n return wallet;\n }\n\n /**\n * Return the authenticated Trading Wallet after native-keypair validation.\n *\n * Complete wallet state and identity are validated by `planningWallet`. This\n * additional guard rejects wallet-adapter and Privy strategies before conversion\n * RPC reads. Ordinary planners do not call this method.\n */\n private conversionPlanningWallet(\n state: WalletDepositBalancesState\n ): PublicKey {\n requireNativeSigningStrategy(requireSigningStrategy(this.client));\n return this.planningWallet(state);\n }\n\n /**\n * Return an unsigned wrap transaction with exact instruction ordering.\n *\n * When planning observed no canonical ATA, the first instruction is strict ATA\n * creation. A concurrently created ATA therefore makes execution fail instead of\n * using account state that was absent from the plan. The transfer and `SyncNative`\n * instructions follow. Fee preparation later attaches the live blockhash.\n */\n private buildWrapSolTransaction(\n wallet: PublicKey,\n amountLamports: bigint,\n createsCanonicalWsolAccount: boolean\n ): Transaction {\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n const transaction = new Transaction({ feePayer: wallet });\n if (createsCanonicalWsolAccount) {\n transaction.add(\n createAssociatedTokenAccountInstruction(\n wallet,\n canonical,\n wallet,\n NATIVE_MINT,\n TOKEN_PROGRAM_ID\n )\n );\n }\n return transaction.add(\n SystemProgram.transfer({\n fromPubkey: wallet,\n toPubkey: canonical,\n lamports: amountLamports,\n }),\n createSyncNativeInstruction(canonical, TOKEN_PROGRAM_ID)\n );\n }\n\n /**\n * Return an unsigned transaction containing one canonical `CloseAccount`.\n *\n * The Trading Wallet is the fee payer, close authority, and destination. A later\n * successful submission transfers the complete account balance to that wallet.\n */\n private buildUnwrapWsolAllTransaction(wallet: PublicKey): Transaction {\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n return new Transaction({ feePayer: wallet }).add(\n createCloseAccountInstruction(\n canonical,\n wallet,\n wallet,\n [],\n TOKEN_PROGRAM_ID\n )\n );\n }\n\n /**\n * Build idempotent creation of the persistent Tokenkeg WSOL ATA.\n * Tokenkeg is Solana's legacy SPL Token Program; canonical native-mint ATA\n * derivation is pinned to it rather than Token-2022 across the protocol.\n */\n private createCanonicalWsolAccount(wallet: PublicKey): TransactionInstruction {\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n return createAssociatedTokenAccountIdempotentInstruction(\n wallet,\n canonical,\n wallet,\n NATIVE_MINT,\n TOKEN_PROGRAM_ID\n );\n }\n\n /** Read canonical-account existence and upfront rent for merge/redeem plans. */\n private async receivePlanContext(\n wallet: PublicKey,\n state: WalletDepositBalancesState\n ): Promise<{\n rpc: Rpc;\n components: SolBalanceComponents;\n canonicalExists: boolean;\n upfrontRentLamports: bigint;\n }> {\n const rpc = new Rpc(this.client);\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n const canonicalExists = await rpc.canonicalWsolAccountExists(canonical, wallet);\n const components = state.solComponents();\n if (components.canonicalWsolLamports > 0n && !canonicalExists) {\n throw SdkError.validation(\n \"canonical WSOL balance is positive but its account is unavailable\"\n );\n }\n return {\n rpc,\n components,\n canonicalExists,\n upfrontRentLamports: canonicalExists\n ? 0n\n : await rpc.minimumBalanceForRentExemption(TOKEN_ACCOUNT_SPACE),\n };\n }\n\n /** Finish merge/redeem planning with live fee authority and component deltas. */\n private async finishReceivePlan(\n kind: \"merge\" | \"redeem\",\n amountLamports: bigint,\n transaction: Transaction,\n rpc: Rpc,\n components: SolBalanceComponents,\n upfrontRentLamports: bigint,\n createsCanonicalWsolAccount: boolean,\n sponsored: boolean\n ): Promise<SolActionPlan> {\n const feeLamports = await rpc.prepareAndEstimateTransactionFee(transaction);\n const costs: SolActionCosts = {\n feeLamports,\n upfrontRentLamports,\n createsCanonicalWsolAccount,\n sponsored,\n };\n const availability = solBalanceAvailability(components, costs);\n const walletCosts = sponsored ? 0n : feeLamports + upfrontRentLamports;\n return {\n kind,\n transaction,\n costs,\n availability,\n expectedDelta: {\n nativeLamports: -walletCosts,\n canonicalWsolLamports: amountLamports,\n },\n };\n }\n\n /**\n * Build the sole WSOL-to-native path without closing canonical authority.\n * The temporary Tokenkeg account is initialized, funded, and closed back to\n * the wallet before the exact recipient transfer in the same transaction.\n */\n private buildTemporaryNativeWithdrawal(\n wallet: PublicKey,\n recipient: PublicKey,\n amountLamports: bigint,\n canonicalTransfer: bigint,\n temporaryRent: bigint,\n seed: string,\n temporary: PublicKey\n ): Transaction {\n const canonical = getAssociatedTokenAddressSync(NATIVE_MINT, wallet);\n return new Transaction({ feePayer: wallet }).add(\n SystemProgram.createAccountWithSeed({\n fromPubkey: wallet,\n newAccountPubkey: temporary,\n basePubkey: wallet,\n seed,\n lamports: Number(temporaryRent),\n space: TOKEN_ACCOUNT_SPACE,\n programId: TOKEN_PROGRAM_ID,\n }),\n createInitializeAccount3Instruction(\n temporary,\n NATIVE_MINT,\n wallet,\n TOKEN_PROGRAM_ID\n ),\n createTransferInstruction(\n canonical,\n temporary,\n wallet,\n canonicalTransfer,\n [],\n TOKEN_PROGRAM_ID\n ),\n createCloseAccountInstruction(\n temporary,\n wallet,\n wallet,\n [],\n TOKEN_PROGRAM_ID\n ),\n SystemProgram.transfer({\n fromPubkey: wallet,\n toPubkey: recipient,\n lamports: amountLamports,\n })\n );\n }\n\n // ── On-chain transaction builders ────────────────────────────────────\n\n redeemWinningsIx(\n params: RedeemWinningsParams,\n outcomeIndex: number\n ): TransactionInstruction {\n return buildRedeemWinningsIx(params, outcomeIndex, this.client.programId);\n }\n\n withdrawConditionalFromPositionIx(\n params: WithdrawConditionalFromPositionParams\n ): TransactionInstruction {\n return buildWithdrawConditionalFromPositionIx(params, this.client.programId);\n }\n\n withdrawFromPositionIx(\n params: WithdrawFromPositionParams\n ): TransactionInstruction {\n return this.withdrawConditionalFromPositionIx(params);\n }\n\n initPositionTokensIx(\n params: InitPositionTokensParams,\n numOutcomes: number\n ): TransactionInstruction {\n return buildInitPositionTokensIx(params, numOutcomes, this.client.programId);\n }\n\n extendPositionTokensIx(\n params: ExtendPositionTokensParams,\n numOutcomes: number\n ): TransactionInstruction {\n return buildExtendPositionTokensIx(params, numOutcomes, this.client.programId);\n }\n\n depositToGlobalIx(params: DepositToGlobalParams): TransactionInstruction {\n return buildDepositToGlobalIx(params, this.client.programId);\n }\n\n depositToGlobalIxWithAlt(\n params: DepositToGlobalParams,\n altContext: DepositToGlobalAltContext\n ): TransactionInstruction {\n return buildDepositToGlobalIxWithAlt(params, altContext, this.client.programId);\n }\n\n globalToMarketDepositIx(\n params: GlobalToMarketDepositParams,\n numOutcomes: number\n ): TransactionInstruction {\n return buildGlobalToMarketDepositIx(params, numOutcomes, this.client.programId);\n }\n\n withdrawFromGlobalIx(params: WithdrawFromGlobalParams): TransactionInstruction {\n return buildWithdrawFromGlobalIx(params, this.client.programId);\n }\n\n closePositionAltIx(params: ClosePositionAltParams): TransactionInstruction {\n return buildClosePositionAltIx(params, this.client.programId);\n }\n\n closePositionTokenAccountsIx(\n params: ClosePositionTokenAccountsParams,\n numOutcomes: number\n ): TransactionInstruction {\n return buildClosePositionTokenAccountsIx(\n params,\n numOutcomes,\n this.client.programId\n );\n }\n\n // ── Transaction builders (_tx convenience wrappers) ─────────────────\n\n redeemWinningsTx(\n params: RedeemWinningsParams,\n outcomeIndex: number\n ): Transaction {\n const ix = this.redeemWinningsIx(params, outcomeIndex);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n withdrawConditionalFromPositionTx(params: WithdrawConditionalFromPositionParams): Transaction {\n const ix = this.withdrawConditionalFromPositionIx(params);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n withdrawFromPositionTx(params: WithdrawFromPositionParams): Transaction {\n return this.withdrawConditionalFromPositionTx(params);\n }\n\n initPositionTokensTx(\n params: InitPositionTokensParams,\n numOutcomes: number\n ): Transaction {\n const ix = this.initPositionTokensIx(params, numOutcomes);\n return new Transaction({ feePayer: params.payer }).add(ix);\n }\n\n extendPositionTokensTx(\n params: ExtendPositionTokensParams,\n numOutcomes: number\n ): Transaction {\n const ix = this.extendPositionTokensIx(params, numOutcomes);\n return new Transaction({ feePayer: params.operator }).add(ix);\n }\n\n depositToGlobalTx(params: DepositToGlobalParams): Transaction {\n const ix = this.depositToGlobalIx(params);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n depositToGlobalTxWithAlt(\n params: DepositToGlobalParams,\n altContext: DepositToGlobalAltContext\n ): Transaction {\n const ix = this.depositToGlobalIxWithAlt(params, altContext);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n globalToMarketDepositTx(\n params: GlobalToMarketDepositParams,\n numOutcomes: number\n ): Transaction {\n const ix = this.globalToMarketDepositIx(params, numOutcomes);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n withdrawFromGlobalTx(params: WithdrawFromGlobalParams): Transaction {\n const ix = this.withdrawFromGlobalIx(params);\n return new Transaction({ feePayer: params.user }).add(ix);\n }\n\n closePositionAltTx(params: ClosePositionAltParams): Transaction {\n const ix = this.closePositionAltIx(params);\n return new Transaction({ feePayer: params.operator }).add(ix);\n }\n\n closePositionTokenAccountsTx(\n params: ClosePositionTokenAccountsParams,\n numOutcomes: number\n ): Transaction {\n const ix = this.closePositionTokenAccountsIx(params, numOutcomes);\n return new Transaction({ feePayer: params.operator }).add(ix);\n }\n\n // ── Builder factories ──────────────────────────────────────────────\n\n deposit(): DepositBuilder {\n return new DepositBuilder(this.client, this.client.depositSource);\n }\n\n merge(): MergeBuilder {\n return new MergeBuilder(this.client);\n }\n\n withdraw(): WithdrawBuilder {\n return new WithdrawBuilder(this.client, this.client.depositSource);\n }\n\n redeemWinnings(): RedeemWinningsBuilder {\n return new RedeemWinningsBuilder(this.client);\n }\n\n withdrawFromPosition(): WithdrawFromPositionBuilder {\n return new WithdrawFromPositionBuilder(this.client);\n }\n\n withdrawConditionalFromPosition(): WithdrawFromPositionBuilder {\n return new WithdrawFromPositionBuilder(this.client);\n }\n\n initPositionTokens(): InitPositionTokensBuilder {\n return new InitPositionTokensBuilder(this.client);\n }\n\n extendPositionTokens(): ExtendPositionTokensBuilder {\n return new ExtendPositionTokensBuilder(this.client);\n }\n\n depositToGlobal(): DepositToGlobalBuilder {\n return new DepositToGlobalBuilder(this.client);\n }\n\n withdrawFromGlobal(): WithdrawFromGlobalBuilder {\n return new WithdrawFromGlobalBuilder(this.client);\n }\n\n globalToMarketDeposit(): GlobalToMarketDepositBuilder {\n return new GlobalToMarketDepositBuilder(this.client);\n }\n\n // ── On-chain account fetchers (require Connection) ──────────────────\n\n async getOnchain(owner: PublicKey, market: PublicKey): Promise<ProgramPosition | null> {\n const connection = requireConnection(this.client);\n const positionPda = this.pda(owner, market);\n const accountInfo = await connection.getAccountInfo(positionPda);\n if (!accountInfo) {\n return null;\n }\n return deserializeProgramPosition(accountInfo.data as Buffer);\n }\n}\n"]}
|
|
@@ -3,6 +3,7 @@ import type { OrderBookId, PubkeyStr } from "../../shared";
|
|
|
3
3
|
import type { UserMarketBalance, UserOutcomeBalance } from "../order/wire";
|
|
4
4
|
export * from "./builders";
|
|
5
5
|
export * from "./client";
|
|
6
|
+
export * from "./state";
|
|
6
7
|
export * from "./wire";
|
|
7
8
|
export interface Portfolio {
|
|
8
9
|
userAddress: PubkeyStr;
|
|
@@ -64,19 +65,69 @@ export interface DepositAssetMetadata {
|
|
|
64
65
|
description: string | null;
|
|
65
66
|
decimals: number;
|
|
66
67
|
}
|
|
68
|
+
/** One exact SPL balance plus display metadata from a complete wallet snapshot. */
|
|
67
69
|
export interface DepositTokenBalance {
|
|
68
70
|
mint: PubkeyStr;
|
|
71
|
+
/** Exact mint-denominated idle amount; precision is defined by the mint. */
|
|
69
72
|
idle: string;
|
|
70
73
|
symbol: string;
|
|
71
74
|
name: string;
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
+
/** Missing or null means metadata is currently unavailable. */
|
|
76
|
+
icon_url_low?: string | null;
|
|
77
|
+
/** Missing or null means metadata is currently unavailable. */
|
|
78
|
+
icon_url_medium?: string | null;
|
|
79
|
+
/** Missing or null means metadata is currently unavailable. */
|
|
80
|
+
icon_url_high?: string | null;
|
|
75
81
|
}
|
|
82
|
+
/** Complete REST snapshot with native SOL separate from the SPL mint map. */
|
|
76
83
|
export interface DepositTokenBalancesSnapshot {
|
|
84
|
+
/** Non-negative safe-integer lower slot valid for both observed components. */
|
|
77
85
|
context_slot: number;
|
|
86
|
+
/** Complete SPL map; native SOL never appears under a synthetic mint. */
|
|
78
87
|
balances: Record<PubkeyStr, DepositTokenBalance>;
|
|
88
|
+
/** Canonical non-negative SOL text with exactly nine fractional digits. */
|
|
89
|
+
native_sol_balance: string;
|
|
79
90
|
}
|
|
91
|
+
/** Recoverable stream conditions that retain the last accepted balance state. */
|
|
92
|
+
export type WalletDepositBalanceStatus = "reconnecting" | "metadata_unavailable";
|
|
93
|
+
/** Complete wallet-scoped event that authoritatively replaces all state. */
|
|
94
|
+
export interface WalletDepositBalanceSnapshot {
|
|
95
|
+
event_type: "wallet_deposit_balance_snapshot";
|
|
96
|
+
wallet_address: PubkeyStr;
|
|
97
|
+
/** Non-negative safe-integer lower slot; it may trail a component update. */
|
|
98
|
+
context_slot: number;
|
|
99
|
+
balances: Record<PubkeyStr, DepositTokenBalance>;
|
|
100
|
+
/** Exact non-negative native SOL with nine fractional digits. */
|
|
101
|
+
native_sol_balance: string;
|
|
102
|
+
}
|
|
103
|
+
/** Absolute single-mint replacement; zero is removed by the state reducer. */
|
|
104
|
+
export interface WalletDepositBalanceUpdate {
|
|
105
|
+
event_type: "wallet_deposit_balance_update";
|
|
106
|
+
wallet_address: PubkeyStr;
|
|
107
|
+
/** Non-negative JavaScript safe-integer component observation slot. */
|
|
108
|
+
context_slot: number;
|
|
109
|
+
/** Complete current balance for the mint, never a delta. */
|
|
110
|
+
balance: DepositTokenBalance;
|
|
111
|
+
}
|
|
112
|
+
/** Absolute native SOL replacement, never a delta. */
|
|
113
|
+
export interface WalletNativeSolBalanceUpdate {
|
|
114
|
+
event_type: "wallet_native_sol_balance_update";
|
|
115
|
+
wallet_address: PubkeyStr;
|
|
116
|
+
/** Non-negative JavaScript safe-integer component observation slot. */
|
|
117
|
+
context_slot: number;
|
|
118
|
+
/** Exact non-negative native SOL with nine fractional digits. */
|
|
119
|
+
native_sol_balance: string;
|
|
120
|
+
}
|
|
121
|
+
/** Informational wallet condition that does not advance slots or mutate balances. */
|
|
122
|
+
export interface WalletDepositBalanceStatusEvent {
|
|
123
|
+
event_type: "wallet_deposit_balance_status";
|
|
124
|
+
wallet_address: PubkeyStr;
|
|
125
|
+
status: WalletDepositBalanceStatus;
|
|
126
|
+
/** Stable machine-readable backend reason for logging or UX. */
|
|
127
|
+
code: string;
|
|
128
|
+
}
|
|
129
|
+
/** Nested discriminated payload of the outer `wallet_deposit_balances` channel. */
|
|
130
|
+
export type WalletDepositBalancesEvent = WalletDepositBalanceSnapshot | WalletDepositBalanceUpdate | WalletNativeSolBalanceUpdate | WalletDepositBalanceStatusEvent;
|
|
80
131
|
export declare function computedBase(balance: TokenBalance, conditionalPrice: Decimal): TokenBalanceComputedBase;
|
|
81
132
|
export declare function computedQuote(balance: TokenBalance): string;
|
|
82
133
|
/** An incremental change to a user's balance for one conditional token. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/domain/position/index.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAE3E,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC;AAEvB,MAAM,WAAW,SAAS;IACxB,WAAW,EAAE,SAAS,CAAC;IACvB,cAAc,EAAE,aAAa,EAAE,CAAC;IAChC,SAAS,EAAE,QAAQ,EAAE,CAAC;IACtB,gBAAgB,EAAE,MAAM,CAAC;IACzB,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,QAAQ;IACvB,WAAW,EAAE,SAAS,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAA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EAAE,wBAAwB,GAAG,IAAI;IAI5E,MAAM,CAAC,KAAK,EAAE,sBAAsB,GAAG,IAAI;IAa3C,MAAM,CAAC,YAAY,EAAE,SAAS,GAAG,IAAI;IAIrC,KAAK,IAAI,GAAG,CAAC,SAAS,EAAE,wBAAwB,CAAC;IAIjD,aAAa,IAAI,SAAS,EAAE;IAI5B,OAAO,IAAI,OAAO;IAIlB,MAAM,CAAC,qBAAqB,CAC1B,aAAa,EAAE,iBAAiB,GAC/B,sBAAsB,GAAG,SAAS;IAwBrC,MAAM,CAAC,sBAAsB,CAC3B,cAAc,EAAE,iBAAiB,EAAE,GAClC,sBAAsB;CAU1B"}
|
|
@@ -30,6 +30,7 @@ const decimal_1 = require("../../shared/fmt/decimal");
|
|
|
30
30
|
const wire_1 = require("../order/wire");
|
|
31
31
|
__exportStar(require("./builders"), exports);
|
|
32
32
|
__exportStar(require("./client"), exports);
|
|
33
|
+
__exportStar(require("./state"), exports);
|
|
33
34
|
__exportStar(require("./wire"), exports);
|
|
34
35
|
function computedBase(balance, conditionalPrice) {
|
|
35
36
|
const size = new decimal_js_1.default(balance.idle).plus(balance.onBook);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/domain/position/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AA8FA,oCAWC;AAED,sCAGC;AAeD,sDAEC;AAGD,wDAEC;AAED,wEAYC;AAED,4EAUC;AA9JD,4DAAiC;AACjC,yCAA6C;AAE7C,sDAAmD;AACnD,wCAAyD;AAGzD,6CAA2B;AAC3B,2CAAyB;AACzB,yCAAuB;AAqFvB,SAAgB,YAAY,CAC1B,OAAqB,EACrB,gBAAyB;IAEzB,MAAM,IAAI,GAAG,IAAI,oBAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5D,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,g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CAAC;YAC3C,MAAM,WAAW,GAAG,sBAAsB,CAAC,qBAAqB,CAAC,aAAa,CAAC,CAAC;YAChF,IAAI,WAAW,EAAE,CAAC;gBAChB,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAlFD,wDAkFC","sourcesContent":["import Decimal from \"decimal.js\";\nimport { asOrderBookId } from \"../../shared\";\nimport type { OrderBookId, PubkeyStr } from \"../../shared\";\nimport { display } from \"../../shared/fmt/decimal\";\nimport { userOutcomeBalanceIsZero } from \"../order/wire\";\nimport type { UserMarketBalance, UserOutcomeBalance } from \"../order/wire\";\n\nexport * from \"./builders\";\nexport * from \"./client\";\nexport * from \"./wire\";\n\nexport interface Portfolio {\n userAddress: PubkeyStr;\n walletHoldings: WalletHolding[];\n positions: Position[];\n totalWalletValue: string;\n totalPositionsValue: string;\n}\n\nexport interface Position {\n eventPubkey: PubkeyStr;\n eventName: string;\n eventImgSrc: string;\n outcomes: PositionOutcome[];\n totalValue: string;\n createdAt: Date;\n}\n\nexport interface PositionOutcome {\n conditionId: number;\n conditionName: string;\n tokenMint: PubkeyStr;\n amount: string;\n usdValue: string;\n}\n\nexport interface WalletHolding {\n tokenMint: PubkeyStr;\n symbol: string;\n amount: string;\n decimals: number;\n usdValue: string;\n imgSrc: string;\n}\n\nexport type TokenBalanceTokenType =\n | { kind: \"DepositAsset\" }\n | {\n kind: \"ConditionalToken\";\n orderbookId: OrderBookId;\n marketPubkey: PubkeyStr;\n outcomeIndex: number;\n };\n\nexport interface TokenBalance {\n mint: PubkeyStr;\n idle: string;\n onBook: string;\n tokenType: TokenBalanceTokenType;\n}\n\nexport interface TokenBalanceComputedBase {\n value: string;\n size: string;\n price: string;\n}\n\nexport interface DepositAssetMetadata {\n symbol: string;\n short_symbol: string;\n name: string;\n deposit_asset: PubkeyStr;\n icon_url_low: string;\n icon_url_medium: string;\n icon_url_high: string;\n description: string | null;\n decimals: number;\n}\n\nexport interface DepositTokenBalance {\n mint: PubkeyStr;\n idle: string;\n symbol: string;\n name: string;\n icon_url_low?: string;\n icon_url_medium?: string;\n icon_url_high?: string;\n}\n\nexport interface DepositTokenBalancesSnapshot {\n context_slot: number;\n balances: Record<PubkeyStr, DepositTokenBalance>;\n}\n\nexport function computedBase(\n balance: TokenBalance,\n conditionalPrice: Decimal\n): TokenBalanceComputedBase {\n const size = new Decimal(balance.idle).plus(balance.onBook);\n const value = size.mul(conditionalPrice);\n return {\n value: display(value),\n size: display(size),\n price: display(conditionalPrice),\n };\n}\n\nexport function computedQuote(balance: TokenBalance): string {\n const size = new Decimal(balance.idle).plus(balance.onBook);\n return display(size);\n}\n\n// ─── ConditionalBalanceDelta ─────────────────────────────────────────────────\n\n/** An incremental change to a user's balance for one conditional token. */\nexport interface ConditionalBalanceDelta {\n marketPubkey: PubkeyStr;\n orderbookId?: OrderBookId;\n outcomeIndex: number;\n conditionalToken: PubkeyStr;\n idle: string;\n onBook: string;\n}\n\n/** Full-precision sum of idle + on-book (mirrors the `balance` field). */\nexport function conditionalDeltaTotal(delta: ConditionalBalanceDelta): string {\n return new Decimal(delta.idle).plus(delta.onBook).toString();\n}\n\n/** True when the delta holds nothing idle and nothing resting on the book. */\nexport function conditionalDeltaIsZero(delta: ConditionalBalanceDelta): boolean {\n return !(new Decimal(delta.idle).gt(0) || new Decimal(delta.onBook).gt(0));\n}\n\nexport function conditionalDeltaToTokenBalance(delta: ConditionalBalanceDelta): TokenBalance {\n return {\n mint: delta.conditionalToken,\n idle: delta.idle,\n onBook: delta.onBook,\n tokenType: {\n kind: \"ConditionalToken\",\n orderbookId: delta.orderbookId ?? asOrderBookId(\"\"),\n marketPubkey: delta.marketPubkey,\n outcomeIndex: delta.outcomeIndex,\n },\n };\n}\n\nexport function conditionalDeltaToOutcomeBalance(\n delta: ConditionalBalanceDelta\n): UserOutcomeBalance {\n return {\n outcome_index: delta.outcomeIndex,\n conditional_token: delta.conditionalToken,\n balance: conditionalDeltaTotal(delta),\n balance_idle: delta.idle,\n balance_on_book: delta.onBook,\n };\n}\n\n// ─── UserMarketBalanceIndex ──────────────────────────────────────────────────\n\nexport type ConditionalTokenBalanceIndex = Map<PubkeyStr, UserOutcomeBalance>;\nexport type DepositAssetBalanceIndex = Map<PubkeyStr, ConditionalTokenBalanceIndex>;\n\n/**\n * Nested index of a user's conditional-token balances, keyed\n * `market → deposit_asset → conditional_token`. Zero balances are dropped when\n * building from wire records.\n */\nexport class UserMarketBalanceIndex {\n readonly index: Map<PubkeyStr, DepositAssetBalanceIndex>;\n\n constructor() {\n this.index = new Map();\n }\n\n get(marketPubkey: PubkeyStr): DepositAssetBalanceIndex | undefined {\n return this.index.get(marketPubkey);\n }\n\n insert(marketPubkey: PubkeyStr, marketEntry: DepositAssetBalanceIndex): void {\n this.index.set(marketPubkey, marketEntry);\n }\n\n extend(other: UserMarketBalanceIndex): void {\n for (const [marketPubkey, marketEntry] of other.index.entries()) {\n const existing = this.index.get(marketPubkey);\n if (!existing) {\n this.index.set(marketPubkey, marketEntry);\n continue;\n }\n for (const [depositAsset, outcomes] of marketEntry.entries()) {\n existing.set(depositAsset, outcomes);\n }\n }\n }\n\n remove(marketPubkey: PubkeyStr): void {\n this.index.delete(marketPubkey);\n }\n\n inner(): Map<PubkeyStr, DepositAssetBalanceIndex> {\n return this.index;\n }\n\n marketPubkeys(): PubkeyStr[] {\n return [...this.index.keys()].sort();\n }\n\n isEmpty(): boolean {\n return this.index.size === 0;\n }\n\n static fromUserMarketBalance(\n marketBalance: UserMarketBalance\n ): UserMarketBalanceIndex | undefined {\n const marketEntry: DepositAssetBalanceIndex = new Map();\n\n for (const depositAssetBalance of marketBalance.deposit_assets) {\n const outcomes: ConditionalTokenBalanceIndex = new Map();\n for (const outcome of depositAssetBalance.outcomes) {\n if (!userOutcomeBalanceIsZero(outcome)) {\n outcomes.set(outcome.conditional_token, outcome);\n }\n }\n if (outcomes.size > 0) {\n marketEntry.set(depositAssetBalance.deposit_asset, outcomes);\n }\n }\n\n if (marketEntry.size === 0) {\n return undefined;\n }\n\n const index = new UserMarketBalanceIndex();\n index.insert(marketBalance.market_pubkey, marketEntry);\n return index;\n }\n\n static fromUserMarketBalances(\n marketBalances: UserMarketBalance[]\n ): UserMarketBalanceIndex {\n const index = new UserMarketBalanceIndex();\n for (const marketBalance of marketBalances) {\n const marketIndex = UserMarketBalanceIndex.fromUserMarketBalance(marketBalance);\n if (marketIndex) {\n index.extend(marketIndex);\n }\n }\n return index;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/domain/position/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AA2JA,oCAWC;AAED,sCAGC;AAeD,sDAEC;AAGD,wDAEC;AAED,wEAYC;AAED,4EAUC;AA3ND,4DAAiC;AACjC,yCAA6C;AAE7C,sDAAmD;AACnD,wCAAyD;AAGzD,6CAA2B;AAC3B,2CAAyB;AACzB,0CAAwB;AACxB,yCAAuB;AAiJvB,SAAgB,YAAY,CAC1B,OAAqB,EACrB,gBAAyB;IAEzB,MAAM,IAAI,GAAG,IAAI,oBAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5D,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IACzC,OAAO;QACL,KAAK,EAAE,IAAA,iBAAO,EAAC,KAAK,CAAC;QACrB,IAAI,EAAE,IAAA,iBAAO,EAAC,IAAI,CAAC;QACnB,KAAK,EAAE,IAAA,iBAAO,EAAC,gBAAgB,CAAC;KACjC,CAAC;AACJ,CAAC;AAED,SAAgB,aAAa,CAAC,OAAqB;IACjD,MAAM,IAAI,GAAG,IAAI,oBAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5D,OAAO,IAAA,iBA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mB,IAAI,aAAa,CAAC,cAAc,EAAE,CAAC;YAC/D,MAAM,QAAQ,GAAiC,IAAI,GAAG,EAAE,CAAC;YACzD,KAAK,MAAM,OAAO,IAAI,mBAAmB,CAAC,QAAQ,EAAE,CAAC;gBACnD,IAAI,CAAC,IAAA,+BAAwB,EAAC,OAAO,CAAC,EAAE,CAAC;oBACvC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;gBACnD,CAAC;YACH,CAAC;YACD,IAAI,QAAQ,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;gBACtB,WAAW,CAAC,GAAG,CAAC,mBAAmB,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;QAED,IAAI,WAAW,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;YAC3B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,sBAAsB,EAAE,CAAC;QAC3C,KAAK,CAAC,MAAM,CAAC,aAAa,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC;QACvD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,CAAC,sBAAsB,CAC3B,cAAmC;QAEnC,MAAM,KAAK,GAAG,IAAI,sBAAsB,EAAE,CAAC;QAC3C,KAAK,MAAM,aAAa,IAAI,cAAc,EAAE,CAAC;YAC3C,MAAM,WAAW,GAAG,sBAAsB,CAAC,qBAAqB,CAAC,aAAa,CAAC,CAAC;YAChF,IAAI,WAAW,EAAE,CAAC;gBAChB,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAlFD,wDAkFC","sourcesContent":["import Decimal from \"decimal.js\";\nimport { asOrderBookId } from \"../../shared\";\nimport type { OrderBookId, PubkeyStr } from \"../../shared\";\nimport { display } from \"../../shared/fmt/decimal\";\nimport { userOutcomeBalanceIsZero } from \"../order/wire\";\nimport type { UserMarketBalance, UserOutcomeBalance } from \"../order/wire\";\n\nexport * from \"./builders\";\nexport * from \"./client\";\nexport * from \"./state\";\nexport * from \"./wire\";\n\nexport interface Portfolio {\n userAddress: PubkeyStr;\n walletHoldings: WalletHolding[];\n positions: Position[];\n totalWalletValue: string;\n totalPositionsValue: string;\n}\n\nexport interface Position {\n eventPubkey: PubkeyStr;\n eventName: string;\n eventImgSrc: string;\n outcomes: PositionOutcome[];\n totalValue: string;\n createdAt: Date;\n}\n\nexport interface PositionOutcome {\n conditionId: number;\n conditionName: string;\n tokenMint: PubkeyStr;\n amount: string;\n usdValue: string;\n}\n\nexport interface WalletHolding {\n tokenMint: PubkeyStr;\n symbol: string;\n amount: string;\n decimals: number;\n usdValue: string;\n imgSrc: string;\n}\n\nexport type TokenBalanceTokenType =\n | { kind: \"DepositAsset\" }\n | {\n kind: \"ConditionalToken\";\n orderbookId: OrderBookId;\n marketPubkey: PubkeyStr;\n outcomeIndex: number;\n };\n\nexport interface TokenBalance {\n mint: PubkeyStr;\n idle: string;\n onBook: string;\n tokenType: TokenBalanceTokenType;\n}\n\nexport interface TokenBalanceComputedBase {\n value: string;\n size: string;\n price: string;\n}\n\nexport interface DepositAssetMetadata {\n symbol: string;\n short_symbol: string;\n name: string;\n deposit_asset: PubkeyStr;\n icon_url_low: string;\n icon_url_medium: string;\n icon_url_high: string;\n description: string | null;\n decimals: number;\n}\n\n/** One exact SPL balance plus display metadata from a complete wallet snapshot. */\nexport interface DepositTokenBalance {\n mint: PubkeyStr;\n /** Exact mint-denominated idle amount; precision is defined by the mint. */\n idle: string;\n symbol: string;\n name: string;\n /** Missing or null means metadata is currently unavailable. */\n icon_url_low?: string | null;\n /** Missing or null means metadata is currently unavailable. */\n icon_url_medium?: string | null;\n /** Missing or null means metadata is currently unavailable. */\n icon_url_high?: string | null;\n}\n\n/** Complete REST snapshot with native SOL separate from the SPL mint map. */\nexport interface DepositTokenBalancesSnapshot {\n /** Non-negative safe-integer lower slot valid for both observed components. */\n context_slot: number;\n /** Complete SPL map; native SOL never appears under a synthetic mint. */\n balances: Record<PubkeyStr, DepositTokenBalance>;\n /** Canonical non-negative SOL text with exactly nine fractional digits. */\n native_sol_balance: string;\n}\n\n/** Recoverable stream conditions that retain the last accepted balance state. */\nexport type WalletDepositBalanceStatus = \"reconnecting\" | \"metadata_unavailable\";\n\n/** Complete wallet-scoped event that authoritatively replaces all state. */\nexport interface WalletDepositBalanceSnapshot {\n event_type: \"wallet_deposit_balance_snapshot\";\n wallet_address: PubkeyStr;\n /** Non-negative safe-integer lower slot; it may trail a component update. */\n context_slot: number;\n balances: Record<PubkeyStr, DepositTokenBalance>;\n /** Exact non-negative native SOL with nine fractional digits. */\n native_sol_balance: string;\n}\n\n/** Absolute single-mint replacement; zero is removed by the state reducer. */\nexport interface WalletDepositBalanceUpdate {\n event_type: \"wallet_deposit_balance_update\";\n wallet_address: PubkeyStr;\n /** Non-negative JavaScript safe-integer component observation slot. */\n context_slot: number;\n /** Complete current balance for the mint, never a delta. */\n balance: DepositTokenBalance;\n}\n\n/** Absolute native SOL replacement, never a delta. */\nexport interface WalletNativeSolBalanceUpdate {\n event_type: \"wallet_native_sol_balance_update\";\n wallet_address: PubkeyStr;\n /** Non-negative JavaScript safe-integer component observation slot. */\n context_slot: number;\n /** Exact non-negative native SOL with nine fractional digits. */\n native_sol_balance: string;\n}\n\n/** Informational wallet condition that does not advance slots or mutate balances. */\nexport interface WalletDepositBalanceStatusEvent {\n event_type: \"wallet_deposit_balance_status\";\n wallet_address: PubkeyStr;\n status: WalletDepositBalanceStatus;\n /** Stable machine-readable backend reason for logging or UX. */\n code: string;\n}\n\n/** Nested discriminated payload of the outer `wallet_deposit_balances` channel. */\nexport type WalletDepositBalancesEvent =\n | WalletDepositBalanceSnapshot\n | WalletDepositBalanceUpdate\n | WalletNativeSolBalanceUpdate\n | WalletDepositBalanceStatusEvent;\n\nexport function computedBase(\n balance: TokenBalance,\n conditionalPrice: Decimal\n): TokenBalanceComputedBase {\n const size = new Decimal(balance.idle).plus(balance.onBook);\n const value = size.mul(conditionalPrice);\n return {\n value: display(value),\n size: display(size),\n price: display(conditionalPrice),\n };\n}\n\nexport function computedQuote(balance: TokenBalance): string {\n const size = new Decimal(balance.idle).plus(balance.onBook);\n return display(size);\n}\n\n// ─── ConditionalBalanceDelta ─────────────────────────────────────────────────\n\n/** An incremental change to a user's balance for one conditional token. */\nexport interface ConditionalBalanceDelta {\n marketPubkey: PubkeyStr;\n orderbookId?: OrderBookId;\n outcomeIndex: number;\n conditionalToken: PubkeyStr;\n idle: string;\n onBook: string;\n}\n\n/** Full-precision sum of idle + on-book (mirrors the `balance` field). */\nexport function conditionalDeltaTotal(delta: ConditionalBalanceDelta): string {\n return new Decimal(delta.idle).plus(delta.onBook).toString();\n}\n\n/** True when the delta holds nothing idle and nothing resting on the book. */\nexport function conditionalDeltaIsZero(delta: ConditionalBalanceDelta): boolean {\n return !(new Decimal(delta.idle).gt(0) || new Decimal(delta.onBook).gt(0));\n}\n\nexport function conditionalDeltaToTokenBalance(delta: ConditionalBalanceDelta): TokenBalance {\n return {\n mint: delta.conditionalToken,\n idle: delta.idle,\n onBook: delta.onBook,\n tokenType: {\n kind: \"ConditionalToken\",\n orderbookId: delta.orderbookId ?? asOrderBookId(\"\"),\n marketPubkey: delta.marketPubkey,\n outcomeIndex: delta.outcomeIndex,\n },\n };\n}\n\nexport function conditionalDeltaToOutcomeBalance(\n delta: ConditionalBalanceDelta\n): UserOutcomeBalance {\n return {\n outcome_index: delta.outcomeIndex,\n conditional_token: delta.conditionalToken,\n balance: conditionalDeltaTotal(delta),\n balance_idle: delta.idle,\n balance_on_book: delta.onBook,\n };\n}\n\n// ─── UserMarketBalanceIndex ──────────────────────────────────────────────────\n\nexport type ConditionalTokenBalanceIndex = Map<PubkeyStr, UserOutcomeBalance>;\nexport type DepositAssetBalanceIndex = Map<PubkeyStr, ConditionalTokenBalanceIndex>;\n\n/**\n * Nested index of a user's conditional-token balances, keyed\n * `market → deposit_asset → conditional_token`. Zero balances are dropped when\n * building from wire records.\n */\nexport class UserMarketBalanceIndex {\n readonly index: Map<PubkeyStr, DepositAssetBalanceIndex>;\n\n constructor() {\n this.index = new Map();\n }\n\n get(marketPubkey: PubkeyStr): DepositAssetBalanceIndex | undefined {\n return this.index.get(marketPubkey);\n }\n\n insert(marketPubkey: PubkeyStr, marketEntry: DepositAssetBalanceIndex): void {\n this.index.set(marketPubkey, marketEntry);\n }\n\n extend(other: UserMarketBalanceIndex): void {\n for (const [marketPubkey, marketEntry] of other.index.entries()) {\n const existing = this.index.get(marketPubkey);\n if (!existing) {\n this.index.set(marketPubkey, marketEntry);\n continue;\n }\n for (const [depositAsset, outcomes] of marketEntry.entries()) {\n existing.set(depositAsset, outcomes);\n }\n }\n }\n\n remove(marketPubkey: PubkeyStr): void {\n this.index.delete(marketPubkey);\n }\n\n inner(): Map<PubkeyStr, DepositAssetBalanceIndex> {\n return this.index;\n }\n\n marketPubkeys(): PubkeyStr[] {\n return [...this.index.keys()].sort();\n }\n\n isEmpty(): boolean {\n return this.index.size === 0;\n }\n\n static fromUserMarketBalance(\n marketBalance: UserMarketBalance\n ): UserMarketBalanceIndex | undefined {\n const marketEntry: DepositAssetBalanceIndex = new Map();\n\n for (const depositAssetBalance of marketBalance.deposit_assets) {\n const outcomes: ConditionalTokenBalanceIndex = new Map();\n for (const outcome of depositAssetBalance.outcomes) {\n if (!userOutcomeBalanceIsZero(outcome)) {\n outcomes.set(outcome.conditional_token, outcome);\n }\n }\n if (outcomes.size > 0) {\n marketEntry.set(depositAssetBalance.deposit_asset, outcomes);\n }\n }\n\n if (marketEntry.size === 0) {\n return undefined;\n }\n\n const index = new UserMarketBalanceIndex();\n index.insert(marketBalance.market_pubkey, marketEntry);\n return index;\n }\n\n static fromUserMarketBalances(\n marketBalances: UserMarketBalance[]\n ): UserMarketBalanceIndex {\n const index = new UserMarketBalanceIndex();\n for (const marketBalance of marketBalances) {\n const marketIndex = UserMarketBalanceIndex.fromUserMarketBalance(marketBalance);\n if (marketIndex) {\n index.extend(marketIndex);\n }\n }\n return index;\n }\n}\n"]}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { PubkeyStr } from "../../shared";
|
|
2
|
+
import type { DepositTokenBalance, DepositTokenBalancesSnapshot, WalletDepositBalancesEvent } from "./index";
|
|
3
|
+
/**
|
|
4
|
+
* Canonical WSOL mint under Solana's legacy SPL Token Program (“Tokenkeg”).
|
|
5
|
+
* ATA derivation stays pinned to Tokenkeg rather than Token-2022 so state and
|
|
6
|
+
* transaction planning address the protocol's one canonical account.
|
|
7
|
+
*/
|
|
8
|
+
export declare const WRAPPED_SOL_MINT: PubkeyStr;
|
|
9
|
+
/** Unsponsored native reserve floor, in lamports, when canonical ATA creation is required. */
|
|
10
|
+
export declare const SOL_RESERVE_WITH_ACCOUNT_CREATION_LAMPORTS = 3500000n;
|
|
11
|
+
/** Unsponsored native reserve floor, in lamports, when canonical WSOL already exists. */
|
|
12
|
+
export declare const SOL_RESERVE_WITH_EXISTING_ACCOUNT_LAMPORTS = 1000000n;
|
|
13
|
+
/** Exact components behind the single displayed SOL asset. */
|
|
14
|
+
export interface SolBalanceComponents {
|
|
15
|
+
/** Lamports held by the Trading Wallet system account. */
|
|
16
|
+
nativeLamports: bigint;
|
|
17
|
+
/** Token amount in the Trading Wallet's persistent canonical WSOL ATA. */
|
|
18
|
+
canonicalWsolLamports: bigint;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Stores live chain costs used to derive transaction funding requirements.
|
|
22
|
+
*
|
|
23
|
+
* {@link solBalanceAvailability} applies ordinary safety floors.
|
|
24
|
+
* {@link unwrapAllSolBalanceAvailability} rejects account creation, upfront rent,
|
|
25
|
+
* and sponsorship, then uses only `feeLamports` as the unwrap-all reserve.
|
|
26
|
+
*/
|
|
27
|
+
export interface SolActionCosts {
|
|
28
|
+
/** Live `getFeeForMessage` result, in lamports. */
|
|
29
|
+
feeLamports: bigint;
|
|
30
|
+
/** Rent funded up front, even when a temporary account refunds it later. */
|
|
31
|
+
upfrontRentLamports: bigint;
|
|
32
|
+
/** Whether this transaction must create the persistent canonical WSOL ATA. */
|
|
33
|
+
createsCanonicalWsolAccount: boolean;
|
|
34
|
+
/** Exact public sponsorship capability supplied by the caller. */
|
|
35
|
+
sponsored: boolean;
|
|
36
|
+
}
|
|
37
|
+
/** Action-specific displayed, reserved, and spendable SOL values. */
|
|
38
|
+
export interface SolBalanceAvailability {
|
|
39
|
+
/** Separately authoritative native and canonical WSOL balances. */
|
|
40
|
+
components: SolBalanceComponents;
|
|
41
|
+
/** Sum of both components in lamports, before reserve. */
|
|
42
|
+
displayedLamports: bigint;
|
|
43
|
+
/** Native lamports withheld for live costs and any action-specific safety floor. */
|
|
44
|
+
reserveLamports: bigint;
|
|
45
|
+
/** Displayed lamports available to this action after reserve. */
|
|
46
|
+
spendableLamports: bigint;
|
|
47
|
+
}
|
|
48
|
+
/** Derive fail-closed availability and type an insufficient native reserve as fee funding. */
|
|
49
|
+
export declare function solBalanceAvailability(components: SolBalanceComponents, costs: SolActionCosts): SolBalanceAvailability;
|
|
50
|
+
/**
|
|
51
|
+
* Return unwrap-all availability with the live fee as its entire reserve.
|
|
52
|
+
*
|
|
53
|
+
* This function rejects costs that include sponsorship, account creation, or
|
|
54
|
+
* upfront rent. It rejects malformed or out-of-range components and costs. It
|
|
55
|
+
* rejects a displayed-balance sum outside Solana's unsigned 64-bit range. Native
|
|
56
|
+
* SOL must fund the fee without relying on lamports that a later `CloseAccount`
|
|
57
|
+
* instruction may transfer. The ordinary persistent-account floor does not apply
|
|
58
|
+
* because unwrap-all removes that account. An insufficient native fee balance
|
|
59
|
+
* returns the typed transaction-fee error.
|
|
60
|
+
*/
|
|
61
|
+
export declare function unwrapAllSolBalanceAvailability(components: SolBalanceComponents, costs: SolActionCosts): SolBalanceAvailability;
|
|
62
|
+
/** Whether an event was accepted by, or rejected by, its lifecycle guard. */
|
|
63
|
+
export type WalletDepositBalancesApplyResult = {
|
|
64
|
+
kind: "applied";
|
|
65
|
+
} | {
|
|
66
|
+
kind: "ignored";
|
|
67
|
+
} | {
|
|
68
|
+
kind: "rejected";
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Mutable application-owned wallet balance state.
|
|
72
|
+
*
|
|
73
|
+
* The default instance is uninitialized. A complete REST or WebSocket snapshot
|
|
74
|
+
* establishes its wallet baseline; later component events must match that wallet
|
|
75
|
+
* and carry absolute values. Native SOL never enters the sparse SPL mint map, and
|
|
76
|
+
* complete cross-component snapshots may replace `contextSlot` with a lower slot.
|
|
77
|
+
* Map containers are copied, but mutable balance objects are retained by reference;
|
|
78
|
+
* treat payload entries as immutable after applying them.
|
|
79
|
+
*/
|
|
80
|
+
export declare class WalletDepositBalancesState {
|
|
81
|
+
/** Wallet owning the current baseline, or `undefined` before initialization. */
|
|
82
|
+
walletAddress: PubkeyStr | undefined;
|
|
83
|
+
/** Slot of the last accepted event, not a globally monotonic stream version. */
|
|
84
|
+
contextSlot: number | undefined;
|
|
85
|
+
/** Sparse mint-keyed SPL balances; explicit zero updates remove their mint. */
|
|
86
|
+
readonly balances: Map<PubkeyStr, DepositTokenBalance>;
|
|
87
|
+
/** Exact nine-decimal native SOL, separate from `balances`. */
|
|
88
|
+
nativeSolBalance: string | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* Initialize or wholesale-replace state from a complete REST snapshot.
|
|
91
|
+
* The caller supplies the wallet omitted by REST; prior slots are not compared.
|
|
92
|
+
* Unlike WebSocket parsing, this TypeScript REST boundary performs no runtime
|
|
93
|
+
* shape validation. Malformed exact values fail when a derived method scales them.
|
|
94
|
+
*/
|
|
95
|
+
applyRestSnapshot(walletAddress: PubkeyStr, snapshot: DepositTokenBalancesSnapshot): WalletDepositBalancesApplyResult;
|
|
96
|
+
/**
|
|
97
|
+
* Apply the wallet event state machine.
|
|
98
|
+
*
|
|
99
|
+
* Complete snapshots always replace state. Matching component events replace
|
|
100
|
+
* one absolute value, zero SPL removes its mint, and status, pre-initialization,
|
|
101
|
+
* or wrong-wallet events return `ignored` without mutation.
|
|
102
|
+
*/
|
|
103
|
+
applyEvent(event: WalletDepositBalancesEvent): WalletDepositBalancesApplyResult;
|
|
104
|
+
/**
|
|
105
|
+
* Return exact native SOL plus canonical WSOL with nine fractional digits.
|
|
106
|
+
* Uses arbitrary-width integer arithmetic and never merges the stored assets.
|
|
107
|
+
*/
|
|
108
|
+
combinedSolBalance(): string;
|
|
109
|
+
/** Return exact native and canonical WSOL components for transaction planning. */
|
|
110
|
+
solComponents(): SolBalanceComponents;
|
|
111
|
+
/** Scale cached native SOL exactly to lamports; requires initialized state. */
|
|
112
|
+
nativeSolLamports(): bigint;
|
|
113
|
+
/** Scale the canonical WSOL idle balance exactly to lamports. */
|
|
114
|
+
canonicalWsolLamports(): bigint;
|
|
115
|
+
private matchesInitializedWallet;
|
|
116
|
+
private replace;
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=state.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../../src/domain/position/state.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,KAAK,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,0BAA0B,EAC3B,MAAM,SAAS,CAAC;AAEjB;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,EACsB,SAAS,CAAC;AAE7D,8FAA8F;AAC9F,eAAO,MAAM,0CAA0C,WAAa,CAAC;AACrE,yFAAyF;AACzF,eAAO,MAAM,0CAA0C,WAAa,CAAC;AAIrE,8DAA8D;AAC9D,MAAM,WAAW,oBAAoB;IACnC,0DAA0D;IAC1D,cAAc,EAAE,MAAM,CAAC;IACvB,0EAA0E;IAC1E,qBAAqB,EAAE,MAAM,CAAC;CAC/B;AAED;;;;;;GAMG;AACH,MAAM,WAAW,cAA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