@invisible-labs/sdk 0.6.0-devnet.2 → 0.6.0-devnet.4
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 +186 -70
- package/dist/.invisible-sdk-build-target.json +7 -0
- package/dist/{chunk-TQNNTV5F.js → chunk-4X5OCCQW.js} +3 -3
- package/dist/{chunk-TQNNTV5F.js.map → chunk-4X5OCCQW.js.map} +1 -1
- package/dist/{chunk-7DSVN3MV.js → chunk-5NNEO7IK.js} +41 -36
- package/dist/chunk-5NNEO7IK.js.map +1 -0
- package/dist/chunk-BRDLLGCZ.js +59 -0
- package/dist/chunk-BRDLLGCZ.js.map +1 -0
- package/dist/{chunk-NCY4FCYU.js → chunk-DIA6U2CV.js} +19 -3
- package/dist/chunk-DIA6U2CV.js.map +1 -0
- package/dist/{chunk-LBC7ALYO.js → chunk-E4DCEDAG.js} +177 -12
- package/dist/chunk-E4DCEDAG.js.map +1 -0
- package/dist/{chunk-OHIM2YWU.js → chunk-GHBQF3A7.js} +2 -2
- package/dist/chunk-GHBQF3A7.js.map +1 -0
- package/dist/{chunk-SZAYO2L5.js → chunk-NHEHCUS5.js} +3 -3
- package/dist/{chunk-SZAYO2L5.js.map → chunk-NHEHCUS5.js.map} +1 -1
- package/dist/{chunk-XUWBGET5.js → chunk-UADJCUPK.js} +125 -18
- package/dist/chunk-UADJCUPK.js.map +1 -0
- package/dist/{chunk-JRMKCE3S.js → chunk-V5HXJRBW.js} +3 -3
- package/dist/{chunk-JRMKCE3S.js.map → chunk-V5HXJRBW.js.map} +1 -1
- package/dist/{coordinator-7Y45MCCZ.js → coordinator-ZNLGAYXD.js} +3 -3
- package/dist/{coordinator-7Y45MCCZ.js.map → coordinator-ZNLGAYXD.js.map} +1 -1
- package/dist/events.js +3 -3
- package/dist/index.d.ts +62 -300
- package/dist/index.js +98 -43
- package/dist/index.js.map +1 -1
- package/dist/lp.d.ts +51 -10
- package/dist/lp.js +313 -86
- package/dist/lp.js.map +1 -1
- package/dist/presets.d.ts +5 -42
- package/dist/presets.js +11 -62
- package/dist/presets.js.map +1 -1
- package/dist/stats.js +1 -1
- package/dist/storage.js +1 -1
- package/dist/{createSession-D3ym-Ira.d.ts → types.generated-DJBTjLpP.d.ts} +37 -53
- package/dist/user.d.ts +94 -112
- package/dist/user.js +649 -248
- package/dist/user.js.map +1 -1
- package/package.json +2 -28
- package/dist/chunk-7DSVN3MV.js.map +0 -1
- package/dist/chunk-LBC7ALYO.js.map +0 -1
- package/dist/chunk-NCY4FCYU.js.map +0 -1
- package/dist/chunk-OHIM2YWU.js.map +0 -1
- package/dist/chunk-XUWBGET5.js.map +0 -1
- package/dist/types.generated-CHGSbmLp.d.ts +0 -67
package/dist/lp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lp/positionCode.ts","../src/lp/withdrawalValidation.ts","../src/lp/coordinatorClient.ts","../src/lp/dkgBatch.ts","../src/lp/lifecycle.ts","../src/lp/index.ts"],"names":["lpPositionId","secretHex","publicKey","encoder","request","addresses","LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS","sleep","refreshPosition","completeDkgBatch","isLpDkgActiveSessionError","execution","redemption","randomBytes","prepareTopUp","reconcileFunding"],"mappings":";;;;;;;;AAeA,IAAM,kBAAA,GAAqB,MAAA;AAC3B,IAAM,WAAA,GAAc,MAAA;AACpB,IAAM,iBAAA,GAAoB,EAAA;AAC1B,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAEhC,eAAsB,uBAAuB,YAAA,EAAmD;AAC9F,EAAA,oBAAA,CAAqB,YAAY,CAAA;AACjC,EAAA,MAAM,MAAA,GAAS,IAAI,UAAA,CAAW,EAAE,CAAA;AAChC,EAAA,SAAA,EAAU,CAAE,gBAAgB,MAAM,CAAA;AAClC,EAAA,MAAM,OAAA,GAAU,MAAM,SAAA,EAAU,CAAE,MAAA,CAAO,YAAY,EAAE,IAAA,EAAM,SAAA,EA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AAA;AACxE;AAEO,SAASC,iBAAAA,CACd,SACA,UAAA,EAC8C;AAC9C,EAAA,OAAO,wBAAA,CAAyB,OAAO,CAAA,CAAE,gBAAA,CAAiB,UAAU,CAAA;AACtE;AAEO,SAAS,gBAAA,CACd,OAAA,EACA,UAAA,EACA,IAAA,EACiC;AACjC,EAAA,OAAO,wBAAA,CAAyB,OAAO,CAAA,CAAE,gBAAA,CAAiB,YAAY,IAAI,CAAA;AAC5E;AAEO,SAAS,8BACd,OAAA,EACA,UAAA,EACA,SAAA,EACA,OAAA,GAAgD,EAAC,EAChB;AACjC,EAAA,OAAO,wBAAA,CAAyB,OAAO,CAAA,CAAE,6BAAA;AAAA,IACvC,UAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;AACF;AAMA,eAAsB,YAAA,CACpB,OAAA,EACA,UAAA,EACA,IAAA,EACgB;AAChB,EAAA,SAAA,CAAU,KAAK,WAAW,CAAA;AAC1B,EAAA,cAAA,CAAe,OAAO,CAAA;AACtB,EAAA,OAAO,MAAM,wBAAA,CAAyB,OAAO,CAAA,CAAE,YAAA,CAAa,YAAY,IAAI,CAAA;AAC9E;AAEO,SAAS,cAAc,OAAA,EAAkE;AAC9F,EAAA,OAAO,wBAAA,CAAyB,OAAO,CAAA,CAAE,aAAA,EAAc;AACzD","file":"lp.js","sourcesContent":["import { isValidLpPositionId } from \"@invisible/shared\";\n\ndeclare const lpPositionCodeBrand: unique symbol;\n\nexport type LpPositionCode = string & { readonly [lpPositionCodeBrand]: \"LpPositionCode\" };\n\nexport type LpPositionCodeAuth = {\n readonly code: LpPositionCode;\n readonly lpPositionId: string;\n readonly authPublicKey: Uint8Array;\n readonly authPrivateKeyPkcs8: Uint8Array;\n readonly refillPublicKey: Uint8Array;\n readonly withdrawalCommitment: Uint8Array;\n};\n\nconst LEGACY_CODE_PREFIX = \"ilp1\";\nconst CODE_PREFIX = \"ilp2\";\nconst SECRET_HEX_LENGTH = 64;\nconst encoder = new TextEncoder();\n\nexport async function generateLpPositionCode(lpPositionId: string): Promise<LpPositionCodeAuth> {\n validateLpPositionId(lpPositionId);\n const secret = new Uint8Array(32);\n getCrypto().getRandomValues(secret);\n const keyPair = await getCrypto().subtle.generateKey({ name: \"Ed25519\" }, true, [\n \"sign\",\n \"verify\",\n ]);\n const [privatePkcs8, publicRaw] = await Promise.all([\n getCrypto().subtle.exportKey(\"pkcs8\", keyPair.privateKey),\n getCrypto().subtle.exportKey(\"raw\", keyPair.publicKey),\n ]);\n const code = encodeCode(\n lpPositionId,\n bytesToHex(secret),\n bytesToHex(new Uint8Array(privatePkcs8)),\n bytesToHex(new Uint8Array(publicRaw)),\n );\n secret.fill(0);\n return deriveLpPositionCodeAuth(code);\n}\n\nexport async function deriveLpPositionCodeAuth(input: string): Promise<LpPositionCodeAuth> {\n const code = normalizeLpPositionCode(input);\n const parsed = parseCode(code);\n const secret = hexToBytes(parsed.secretHex);\n try {\n const authPublicKey = parsed.authPublicKeyHex\n ? hexToBytes(parsed.authPublicKeyHex)\n : new Uint8Array();\n const authPrivateKeyPkcs8 = parsed.authPrivateKeyPkcs8Hex\n ? hexToBytes(parsed.authPrivateKeyPkcs8Hex)\n : new Uint8Array();\n if (authPublicKey.length > 0 || authPrivateKeyPkcs8.length > 0) {\n await assertAuthKeyPair(authPrivateKeyPkcs8, authPublicKey);\n }\n const refillPublicKey = await deriveBytes(\n \"invisible-lp-refill-public-key-v0\",\n parsed.lpPositionId,\n secret,\n );\n const withdrawalCommitment = await deriveBytes(\n \"invisible-lp-redemption-commitment-v0\",\n parsed.lpPositionId,\n secret,\n );\n return {\n code,\n lpPositionId: parsed.lpPositionId,\n authPublicKey,\n authPrivateKeyPkcs8,\n refillPublicKey,\n withdrawalCommitment,\n };\n } finally {\n secret.fill(0);\n }\n}\n\nexport function normalizeLpPositionCode(input: string): LpPositionCode {\n return input.trim() as LpPositionCode;\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport async function signLpCommandBytes(\n auth: LpPositionCodeAuth,\n bytes: Uint8Array,\n): Promise<Uint8Array> {\n if (auth.authPrivateKeyPkcs8.length === 0 || auth.authPublicKey.length === 0) {\n throw new Error(\"LP Position Code cannot sign owner commands; create a new ilp2 code\");\n }\n const privateKey = await getCrypto().subtle.importKey(\n \"pkcs8\",\n bufferSource(auth.authPrivateKeyPkcs8),\n { name: \"Ed25519\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(\n await getCrypto().subtle.sign({ name: \"Ed25519\" }, privateKey, bufferSource(bytes)),\n );\n}\n\nfunction encodeCode(\n lpPositionId: string,\n secretHex: string,\n authPrivateKeyPkcs8Hex: string,\n authPublicKeyHex: string,\n): LpPositionCode {\n return `${CODE_PREFIX}:${lpPositionId}:${secretHex}:${authPrivateKeyPkcs8Hex}:${authPublicKeyHex}` as LpPositionCode;\n}\n\nfunction parseCode(code: LpPositionCode): {\n readonly lpPositionId: string;\n readonly secretHex: string;\n readonly authPrivateKeyPkcs8Hex?: string;\n readonly authPublicKeyHex?: string;\n} {\n const parts = code.split(\":\");\n if (parts.length === 3 && parts[0] === LEGACY_CODE_PREFIX) {\n const [, lpPositionId, secretHex] = parts;\n validateLpPositionId(lpPositionId);\n if (!new RegExp(`^[0-9a-fA-F]{${SECRET_HEX_LENGTH}}$`).test(secretHex)) {\n throw new Error(\"LP Position Code secret must be 32 bytes hex\");\n }\n return { lpPositionId, secretHex: secretHex.toLowerCase() };\n }\n if (parts.length !== 5 || parts[0] !== CODE_PREFIX) {\n throw new Error(\"LP Position Code must use the ilp2 format\");\n }\n const [, lpPositionId, secretHex, authPrivateKeyPkcs8Hex, authPublicKeyHex] = parts;\n validateLpPositionId(lpPositionId);\n if (!new RegExp(`^[0-9a-fA-F]{${SECRET_HEX_LENGTH}}$`).test(secretHex)) {\n throw new Error(\"LP Position Code secret must be 32 bytes hex\");\n }\n if (!/^[0-9a-fA-F]+$/.test(authPrivateKeyPkcs8Hex) || authPrivateKeyPkcs8Hex.length < 64) {\n throw new Error(\"LP Position Code auth private key must be pkcs8 hex\");\n }\n if (!new RegExp(`^[0-9a-fA-F]{${SECRET_HEX_LENGTH}}$`).test(authPublicKeyHex)) {\n throw new Error(\"LP Position Code auth public key must be 32 bytes hex\");\n }\n return {\n lpPositionId,\n secretHex: secretHex.toLowerCase(),\n authPrivateKeyPkcs8Hex: authPrivateKeyPkcs8Hex.toLowerCase(),\n authPublicKeyHex: authPublicKeyHex.toLowerCase(),\n };\n}\n\nfunction validateLpPositionId(lpPositionId: string): void {\n if (!isValidLpPositionId(lpPositionId)) {\n throw new Error(\"LP Position Code has an invalid position id\");\n }\n}\n\nasync function deriveBytes(\n domain: string,\n lpPositionId: string,\n secret: Uint8Array,\n): Promise<Uint8Array> {\n const domainBytes = encoder.encode(`${domain}:${lpPositionId}:`);\n const material = new Uint8Array(domainBytes.length + secret.length);\n material.set(domainBytes);\n material.set(secret, domainBytes.length);\n const digest = await getCrypto().subtle.digest(\"SHA-256\", material);\n material.fill(0);\n return new Uint8Array(digest);\n}\n\nasync function assertAuthKeyPair(privatePkcs8: Uint8Array, publicRaw: Uint8Array): Promise<void> {\n if (publicRaw.length !== 32) {\n throw new Error(\"LP Position Code auth public key must be 32 bytes\");\n }\n const [privateKey, publicKey] = await Promise.all([\n getCrypto().subtle.importKey(\"pkcs8\", bufferSource(privatePkcs8), { name: \"Ed25519\" }, false, [\n \"sign\",\n ]),\n getCrypto().subtle.importKey(\"raw\", bufferSource(publicRaw), { name: \"Ed25519\" }, false, [\n \"verify\",\n ]),\n ]);\n const challenge = encoder.encode(\"invisible-lp-auth-self-test\");\n const signature = await getCrypto().subtle.sign({ name: \"Ed25519\" }, privateKey, challenge);\n const ok = await getCrypto().subtle.verify({ name: \"Ed25519\" }, publicKey, signature, challenge);\n if (!ok) {\n throw new Error(\"LP Position Code auth key pair is invalid\");\n }\n}\n\nfunction bufferSource(bytes: Uint8Array): ArrayBuffer {\n return new Uint8Array(bytes).buffer;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction getCrypto(): Crypto {\n if (globalThis.crypto === undefined || globalThis.crypto.subtle === undefined) {\n throw new Error(\"Web Crypto is required for LP Position Code handling\");\n }\n return globalThis.crypto;\n}\n","import { lamports, publicKey } from \"../core/brands.js\";\nimport { PolicyValidationError } from \"../core/errors.js\";\n\nexport interface LpWithdrawalPlanValidationInput {\n readonly depositPrincipalLamports: number;\n readonly earnedFeeLamports: number;\n readonly destinationAddresses: readonly string[];\n readonly allowManyToOne?: boolean;\n readonly sourceCount?: number;\n}\n\nconst SINGLE_DESTINATION_WITHDRAWAL_MESSAGE =\n \"single-destination withdrawal is privacy-degrading; pass allowManyToOne: true to acknowledge\";\nconst DESTINATION_SOURCE_COUNT_MESSAGE =\n \"LP withdrawal requires one destination per withdrawable source unless allowManyToOne is true\";\nconst SOURCE_COUNT_MESSAGE = \"LP withdrawal source count must be a positive integer\";\n\nexport function validateLpWithdrawalPlan(input: LpWithdrawalPlanValidationInput): void {\n const {\n depositPrincipalLamports,\n earnedFeeLamports,\n destinationAddresses,\n allowManyToOne,\n sourceCount,\n } = input;\n lamports(depositPrincipalLamports);\n lamports(earnedFeeLamports);\n if (depositPrincipalLamports === 0 && earnedFeeLamports === 0) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n \"LP withdrawal requires a non-zero principal or earned-fee claim\",\n );\n }\n validateDestinationAddresses(destinationAddresses);\n if (sourceCount !== undefined && (!Number.isInteger(sourceCount) || sourceCount < 1)) {\n throw new PolicyValidationError(\"INVALID_WITHDRAWAL_PLAN\", SOURCE_COUNT_MESSAGE);\n }\n if (\n sourceCount !== undefined &&\n allowManyToOne !== true &&\n destinationAddresses.length !== sourceCount\n ) {\n throw new PolicyValidationError(\"INVALID_WITHDRAWAL_PLAN\", DESTINATION_SOURCE_COUNT_MESSAGE);\n }\n if (destinationAddresses.length === 1 && sourceCount !== 1 && allowManyToOne !== true) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n SINGLE_DESTINATION_WITHDRAWAL_MESSAGE,\n );\n }\n}\n\nfunction validateDestinationAddresses(destinationAddresses: readonly string[]): void {\n if (destinationAddresses.length === 0) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n \"at least one destination address is required\",\n );\n }\n const seen = new Set<string>();\n for (const address of destinationAddresses) {\n publicKey(address);\n if (seen.has(address)) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n `duplicate withdrawal destination: ${address}`,\n );\n }\n seen.add(address);\n }\n}\n","import type { Session } from \"../core/session.js\";\nimport { CommandError, PolicyValidationError } from \"../core/errors.js\";\nimport { getSessionState } from \"../session/state.js\";\nimport {\n CoordinatorMessageType,\n requestEnvelope,\n type Envelope,\n} from \"../coordinator/protocolClient.js\";\nimport { bytesToHex, signLpCommandBytes, type LpPositionCodeAuth } from \"./positionCode.js\";\nimport { validateLpWithdrawalPlan } from \"./withdrawalValidation.js\";\nimport type {\n FinalizeLpDkgBatchInput,\n FundingConfirmationInput,\n LpActorSyncView,\n LpCoordinatorClient,\n LpInventoryShard,\n LpPositionView,\n LpRedemptionHistoryView,\n LpTopUpRequest,\n LpWithdrawalExecutionView,\n OpenLpPositionInput,\n RefillLpPositionInput,\n} from \"./types.js\";\n\ntype LpCommandAction =\n | \"dkg_init\"\n | \"dkg_round1\"\n | \"dkg_round2\"\n | \"position_open\"\n | \"position_get\"\n | \"dkg_finalize\"\n | \"refill\"\n | \"reconcile_funding\"\n | \"funding_plan\"\n | \"funding_confirmation\"\n | \"make_available\"\n | \"withdraw_request\"\n | \"prepare_top_up\"\n | \"top_up_status\";\n\ntype LpCommandBody = { readonly case: string; readonly value: Record<string, unknown> };\n\ntype ProtocolLpModule = {\n readonly encodeLpCommandForSigning: (command: unknown) => Uint8Array;\n readonly lpSignedCommandEnvelope: (\n command: unknown,\n signature: Uint8Array,\n ) => { readonly type: CoordinatorMessageType; readonly payload: Record<string, unknown> };\n readonly asLpCommandResponsePayload: (envelope: Envelope) => LpCommandResponsePayload;\n};\n\ntype LpCommandResponsePayload =\n | { readonly case: \"dkgInit\"; readonly value: { readonly session_id: string } }\n | {\n readonly case: \"dkgRound1\";\n readonly value: { readonly package: Uint8Array; readonly round2_for_lp: Uint8Array };\n }\n | {\n readonly case: \"dkgRound2\";\n readonly value: {\n readonly address: string;\n readonly joint_pubkey: Uint8Array;\n readonly shard_id: string;\n readonly index: number;\n };\n }\n | { readonly case: \"position\"; readonly value: LpPositionViewPayload }\n | { readonly case: \"shards\"; readonly value: LpShardViewPayload[] }\n | { readonly case: \"shard\"; readonly value: LpShardViewPayload }\n | { readonly case: \"topUpRequest\"; readonly value: LpTopUpRequestPayload }\n | {\n readonly case: \"withdrawalExecution\";\n readonly value: { readonly withdrawal_id: string; readonly tx_signatures: string[] };\n };\n\ntype LpPositionViewPayload = {\n readonly lp_position_id: string;\n readonly status: LpPositionView[\"status\"];\n readonly target_shard_count: number;\n readonly auth_public_key: Uint8Array;\n readonly refill_public_key: Uint8Array;\n readonly redemption_commitment: Uint8Array;\n readonly committed_lamports: number;\n readonly earned_lamports: number;\n readonly refill_threshold: number;\n readonly shards: LpShardViewPayload[];\n readonly created_at_ms: number;\n readonly actor_sync?: {\n readonly lp_position_id: string;\n readonly status: LpActorSyncView[\"status\"];\n readonly source_liquidity_use: LpActorSyncView[\"sourceLiquidityUse\"];\n readonly redeemable_principal_lamports?: number;\n readonly redeemable_fee_lamports?: number;\n readonly lifetime_earned_lamports?: number;\n readonly redeemable_principal_source_count?: number;\n readonly redeemable_fee_source_count?: number;\n readonly pending_reservation_count: number;\n readonly reserved_payout_lamports: number;\n readonly estimated_network_fee_lamports: number;\n readonly reimbursement_due_count: number;\n readonly reimbursement_due_source_count: number;\n readonly reimbursement_due_payout_lamports: number;\n readonly reimbursement_due_network_fee_lamports: number;\n readonly withdrawal_requested_lamports: number;\n readonly withdrawal_landed_lamports: number;\n readonly withdrawal_landed_fee_lamports: number;\n readonly withdrawal_canceled_lamports: number;\n readonly withdrawal_network_fee_loss_lamports: number;\n readonly withdrawal_tx_hashes: string[];\n readonly redemption_history?: LpRedemptionHistoryPayload[];\n readonly redemption_history_has_more?: boolean;\n readonly redemption_history_next_cursor?: string;\n readonly state_version: number;\n readonly updated_at_ms: number;\n };\n};\n\ntype LpRedemptionHistoryPayload = {\n readonly redemption_id: string;\n readonly state: LpRedemptionHistoryView[\"state\"];\n readonly accepted_lamports: number;\n readonly accepted_deposit_principal_lamports: number;\n readonly accepted_earned_fee_lamports: number;\n readonly landed_lamports: number;\n readonly landed_deposit_principal_lamports: number;\n readonly landed_earned_fee_lamports: number;\n readonly canceled_lamports: number;\n readonly canceled_deposit_principal_lamports: number;\n readonly canceled_earned_fee_lamports: number;\n readonly network_fee_lamports: number;\n readonly network_fee_loss_lamports: number;\n readonly failed_attempts: number;\n readonly destination_addresses: string[];\n readonly destination_count: number;\n readonly tx_signatures: string[];\n readonly tx_signature_count: number;\n readonly details_truncated: boolean;\n readonly state_version: number;\n readonly created_at_ms: number;\n readonly updated_at_ms: number;\n};\n\ntype LpShardViewPayload = {\n readonly lp_position_id: string;\n readonly shard_id: string;\n readonly index: number;\n readonly address: string;\n readonly amount_lamports: number;\n readonly required_lamports?: number;\n readonly status:\n | \"pregenerated\"\n | \"funding_queued\"\n | \"funded\"\n | \"cooling\"\n | \"available\"\n | \"reserved\"\n | \"retired\"\n | \"redeemed\";\n readonly funding_tx_signature?: string;\n readonly payout_tx_signature?: string;\n readonly cooling_until_ms?: number;\n};\n\ntype LpTopUpRequestPayload = {\n readonly top_up_id: string;\n readonly lp_position_id: string;\n readonly deposit_address: string;\n readonly expires_at_ms: number;\n readonly status: LpTopUpRequest[\"status\"];\n};\n\nconst COMMAND_TTL_MS = 30_000;\nexport const LP_COMMAND_REQUEST_TIMEOUT_MS = 120_000;\nconst encoder = new TextEncoder();\nlet protocolPromise: Promise<ProtocolLpModule> | null = null;\n\nexport function createLpCoordinatorClient(session: Session): LpCoordinatorClient {\n return {\n initDkg(input, auth) {\n return initDkg(session, input, auth);\n },\n dkgRound1(input, auth) {\n return dkgRound1(session, input, auth);\n },\n dkgRound2(input, auth) {\n return dkgRound2(session, input, auth);\n },\n openPosition(input, auth) {\n return openPosition(session, input, auth);\n },\n getPosition(lpPositionId, auth) {\n return getPosition(session, lpPositionId, auth);\n },\n finalizeDkgBatch(input, auth) {\n return finalizeDkgBatch(session, input, auth);\n },\n refillPosition(input, auth) {\n return refillPosition(session, input, auth);\n },\n reconcileFunding(lpPositionId, auth) {\n return reconcileFunding(session, lpPositionId, auth);\n },\n planFunding(input, auth) {\n return planFunding(session, input, auth);\n },\n confirmFunding(input, auth) {\n return confirmFunding(session, input, auth);\n },\n prepareTopUp(lpPositionId, auth) {\n return prepareTopUp(session, lpPositionId, auth);\n },\n getTopUpStatus(input, auth) {\n return getTopUpStatus(session, input, auth);\n },\n makeAvailable(input, auth) {\n return makeAvailable(session, input, auth);\n },\n executeWithdrawal(input, auth) {\n return executeWithdrawal(session, input, auth);\n },\n };\n}\n\nasync function initDkg(\n session: Session,\n input: { lpPositionId: string; index: number },\n auth: LpPositionCodeAuth,\n): Promise<{ sessionId: string }> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"dkg_init\", {\n case: \"dkgInit\",\n value: { index: input.index },\n });\n if (response.case !== \"dkgInit\") throw new Error(\"Unexpected LP DKG init response\");\n return { sessionId: response.value.session_id };\n}\n\nasync function dkgRound1(\n session: Session,\n input: { sessionId: string; package: number[] },\n auth: LpPositionCodeAuth,\n): Promise<{ package: Uint8Array; round2ForLp: Uint8Array }> {\n const response = await request(session, auth, \"dkg_round1\", {\n case: \"dkgRound1\",\n value: {\n session_id: input.sessionId,\n package: Uint8Array.from(input.package),\n },\n });\n if (response.case !== \"dkgRound1\") throw new Error(\"Unexpected LP DKG round1 response\");\n return {\n package: response.value.package,\n round2ForLp: response.value.round2_for_lp,\n };\n}\n\nasync function dkgRound2(\n session: Session,\n input: { sessionId: string; package: number[]; delegatedShare: number[] },\n auth: LpPositionCodeAuth,\n): Promise<{ address: string; jointPubkey: Uint8Array; shardId: string; index: number }> {\n const response = await request(session, auth, \"dkg_round2\", {\n case: \"dkgRound2\",\n value: {\n session_id: input.sessionId,\n package: Uint8Array.from(input.package),\n delegated_share: Uint8Array.from(input.delegatedShare),\n },\n });\n if (response.case !== \"dkgRound2\") throw new Error(\"Unexpected LP DKG round2 response\");\n return {\n address: response.value.address,\n jointPubkey: response.value.joint_pubkey,\n shardId: response.value.shard_id,\n index: response.value.index,\n };\n}\n\nasync function openPosition(\n session: Session,\n input: OpenLpPositionInput,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"position_open\", {\n case: \"positionOpen\",\n value: {\n auth_public_key: Uint8Array.from(input.authPublicKey),\n refill_public_key: Uint8Array.from(input.refillPublicKey),\n redemption_commitment: Uint8Array.from(input.withdrawalCommitment),\n committed_lamports: input.committedLamports,\n shard_count: input.shardCount,\n shard_amount_lamports: input.shardAmountLamports,\n refill_threshold: input.refillThreshold,\n addresses: input.addresses,\n created_at_ms: input.createdAtMs,\n },\n });\n return expectPosition(response);\n}\n\nasync function getPosition(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n let cursor: string | undefined;\n let position: LpPositionView | undefined;\n const seenCursors = new Set<string>();\n for (;;) {\n const response = await requestForPosition(session, lpPositionId, auth, \"position_get\", {\n case: \"positionGet\",\n value: cursor === undefined ? {} : { redemption_history_cursor: cursor },\n });\n const page = expectPosition(response);\n const mergedPosition =\n position === undefined ? page : mergePositionHistoryPages(position, page);\n position = mergedPosition;\n const actorSync = page.actorSync;\n if (actorSync?.redemptionHistoryHasMore !== true) return mergedPosition;\n const nextCursor = actorSync.redemptionHistoryNextCursor;\n if (nextCursor === undefined || seenCursors.has(nextCursor)) {\n throw new CommandError(\n \"REJECTED_STATE\",\n \"coordinator LP actor sync returned an invalid redemption history cursor\",\n );\n }\n seenCursors.add(nextCursor);\n cursor = nextCursor;\n }\n}\n\nasync function finalizeDkgBatch(\n session: Session,\n input: FinalizeLpDkgBatchInput,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"dkg_finalize\", {\n case: \"dkgFinalize\",\n value: {\n start_index: input.startIndex,\n addresses: input.addresses,\n finalized_at_ms: input.finalizedAtMs,\n },\n });\n return expectPosition(response);\n}\n\nasync function refillPosition(\n session: Session,\n input: RefillLpPositionInput,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"refill\", {\n case: \"refill\",\n value: {\n shard_count: input.shardCount,\n shard_amount_lamports: input.shardAmountLamports,\n addresses: input.addresses,\n authorized_at_ms: input.authorizedAtMs,\n },\n });\n return expectPosition(response);\n}\n\nasync function reconcileFunding(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n const response = await requestForPosition(session, lpPositionId, auth, \"reconcile_funding\", {\n case: \"reconcileFunding\",\n value: {},\n });\n return expectPosition(response);\n}\n\nasync function planFunding(\n session: Session,\n input: { lpPositionId: string; shardCount: number; nowMs: number },\n auth: LpPositionCodeAuth,\n): Promise<LpInventoryShard[]> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"funding_plan\", {\n case: \"fundingPlan\",\n value: {\n shard_count: input.shardCount,\n planned_at_ms: input.nowMs,\n },\n });\n if (response.case !== \"shards\") throw new Error(\"Unexpected LP funding plan response\");\n return response.value.map(mapShard);\n}\n\nasync function confirmFunding(\n session: Session,\n input: FundingConfirmationInput,\n auth: LpPositionCodeAuth,\n): Promise<LpInventoryShard> {\n const response = await requestForPosition(\n session,\n input.lpPositionId,\n auth,\n \"funding_confirmation\",\n {\n case: \"fundingConfirmation\",\n value: {\n shard_id: input.shardId,\n amount_lamports: input.amountLamports,\n funding_tx_signature: input.fundingTxSignature,\n },\n },\n );\n if (response.case !== \"shard\") throw new Error(\"Unexpected LP funding confirmation response\");\n return mapShard(response.value);\n}\n\nasync function prepareTopUp(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n): Promise<LpTopUpRequest> {\n const response = await requestForPosition(session, lpPositionId, auth, \"prepare_top_up\", {\n case: \"prepareTopUp\",\n value: {},\n });\n if (response.case !== \"topUpRequest\") throw new Error(\"Unexpected LP top-up response\");\n return mapTopUpRequest(response.value);\n}\n\nasync function getTopUpStatus(\n session: Session,\n input: { lpPositionId: string; topUpId: string },\n auth: LpPositionCodeAuth,\n): Promise<LpTopUpRequest> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"top_up_status\", {\n case: \"topUpStatus\",\n value: { top_up_id: input.topUpId },\n });\n if (response.case !== \"topUpRequest\") throw new Error(\"Unexpected LP top-up response\");\n return mapTopUpRequest(response.value);\n}\n\nasync function makeAvailable(\n session: Session,\n input: { lpPositionId: string; shardId: string },\n auth: LpPositionCodeAuth,\n): Promise<LpInventoryShard> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"make_available\", {\n case: \"makeAvailable\",\n value: {\n shard_id: input.shardId,\n },\n });\n if (response.case !== \"shard\") throw new Error(\"Unexpected LP availability response\");\n return mapShard(response.value);\n}\n\nasync function executeWithdrawal(\n session: Session,\n input: {\n lpPositionId: string;\n destinationAddresses: string[];\n depositPrincipalLamports: number;\n earnedFeeLamports: number;\n requestedAtMs: number;\n allowManyToOne?: boolean;\n },\n auth: LpPositionCodeAuth,\n): Promise<LpWithdrawalExecutionView> {\n validateLpWithdrawalPlan({\n destinationAddresses: input.destinationAddresses,\n depositPrincipalLamports: input.depositPrincipalLamports,\n earnedFeeLamports: input.earnedFeeLamports,\n allowManyToOne: input.allowManyToOne,\n });\n const response = await requestForPosition(session, input.lpPositionId, auth, \"withdraw_request\", {\n case: \"withdrawRequest\",\n value: {\n destination_addresses: input.destinationAddresses,\n deposit_principal_lamports: input.depositPrincipalLamports,\n earned_fee_lamports: input.earnedFeeLamports,\n requested_at_ms: input.requestedAtMs,\n },\n });\n if (response.case !== \"withdrawalExecution\") {\n throw new Error(\"Unexpected LP withdrawal execution response\");\n }\n return {\n withdrawalId: response.value.withdrawal_id,\n txSignatures: [...response.value.tx_signatures],\n };\n}\n\nfunction request(\n session: Session,\n auth: LpPositionCodeAuth,\n action: LpCommandAction,\n payload: LpCommandBody,\n): Promise<LpCommandResponsePayload> {\n return requestForPosition(session, auth.lpPositionId, auth, action, payload);\n}\n\nasync function requestForPosition(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n action: LpCommandAction,\n payload: LpCommandBody,\n): Promise<LpCommandResponsePayload> {\n assertAuthMatchesPosition(lpPositionId, auth);\n const protocol = await loadProtocol();\n const state = getSessionState(session);\n const attestation = state.channel?.attestation;\n if (!attestation) throw new Error(\"LP coordinator attestation is not available\");\n\n const command = {\n lp_position_id: lpPositionId,\n action,\n nonce: randomBytes(32),\n expires_at_ms: Date.now() + COMMAND_TTL_MS,\n coordinator_attestation_hash: await coordinatorAttestationHash(\n attestation.binaryHash,\n attestation.pubkeyHex,\n ),\n payload,\n };\n const signature = await signLpCommandBytes(auth, protocol.encodeLpCommandForSigning(command));\n const { type, payload: envelopePayload } = protocol.lpSignedCommandEnvelope(command, signature);\n const envelope = await requestEnvelope(session, type, envelopePayload, {\n timeoutMs: LP_COMMAND_REQUEST_TIMEOUT_MS,\n });\n return protocol.asLpCommandResponsePayload(envelope);\n}\n\nfunction assertAuthMatchesPosition(lpPositionId: string, auth: LpPositionCodeAuth): void {\n if (lpPositionId === auth.lpPositionId) return;\n throw new PolicyValidationError(\n \"INVALID_POSITION_AUTH\",\n \"LP Position Code does not match the target LP position\",\n );\n}\n\nfunction expectPosition(response: LpCommandResponsePayload): LpPositionView {\n if (response.case !== \"position\") throw new Error(\"Unexpected LP position response\");\n return mapPosition(response.value);\n}\n\nfunction mapPosition(position: LpPositionViewPayload): LpPositionView {\n return {\n id: position.lp_position_id,\n status: position.status,\n targetShardCount: position.target_shard_count,\n authPublicKey: bytesToHex(position.auth_public_key),\n refillPublicKey: bytesToHex(position.refill_public_key),\n withdrawalCommitment: bytesToHex(position.redemption_commitment),\n committedLamports: position.committed_lamports,\n earnedLamports: position.earned_lamports,\n refillThreshold: position.refill_threshold,\n shards: position.shards.map(mapShard),\n createdAt: position.created_at_ms,\n ...(position.actor_sync === undefined\n ? {}\n : { actorSync: mapLpActorSync(position.actor_sync) }),\n };\n}\n\nfunction mapLpActorSync(\n actorSync: NonNullable<LpPositionViewPayload[\"actor_sync\"]>,\n): LpActorSyncView {\n const redeemableBucketValues = [\n actorSync.redeemable_principal_lamports,\n actorSync.redeemable_fee_lamports,\n actorSync.lifetime_earned_lamports,\n actorSync.redeemable_principal_source_count,\n actorSync.redeemable_fee_source_count,\n ];\n const redeemableBucketCount = redeemableBucketValues.filter(\n (value) => value !== undefined,\n ).length;\n if (redeemableBucketCount > 0 && redeemableBucketCount < redeemableBucketValues.length) {\n throw new CommandError(\n \"REJECTED_STATE\",\n \"coordinator LP actor sync redeemable buckets must be all-or-none\",\n );\n }\n const redeemableProjectionAvailable = redeemableBucketCount === redeemableBucketValues.length;\n return {\n lpPositionId: actorSync.lp_position_id,\n status: actorSync.status,\n sourceLiquidityUse: actorSync.source_liquidity_use,\n redeemableProjectionAvailable,\n redeemablePrincipalLamports: actorSync.redeemable_principal_lamports ?? 0,\n redeemableFeeLamports: actorSync.redeemable_fee_lamports ?? 0,\n lifetimeEarnedLamports: actorSync.lifetime_earned_lamports ?? 0,\n redeemablePrincipalSourceCount: actorSync.redeemable_principal_source_count ?? 0,\n redeemableFeeSourceCount: actorSync.redeemable_fee_source_count ?? 0,\n pendingReservationCount: actorSync.pending_reservation_count,\n reservedPayoutLamports: actorSync.reserved_payout_lamports,\n estimatedNetworkFeeLamports: actorSync.estimated_network_fee_lamports,\n reimbursementDueCount: actorSync.reimbursement_due_count,\n reimbursementDueSourceCount: actorSync.reimbursement_due_source_count,\n reimbursementDuePayoutLamports: actorSync.reimbursement_due_payout_lamports,\n reimbursementDueNetworkFeeLamports: actorSync.reimbursement_due_network_fee_lamports,\n withdrawalRequestedLamports: actorSync.withdrawal_requested_lamports,\n withdrawalLandedLamports: actorSync.withdrawal_landed_lamports,\n withdrawalLandedFeeLamports: actorSync.withdrawal_landed_fee_lamports,\n withdrawalCanceledLamports: actorSync.withdrawal_canceled_lamports,\n withdrawalNetworkFeeLossLamports: actorSync.withdrawal_network_fee_loss_lamports,\n withdrawalTxHashes: [...actorSync.withdrawal_tx_hashes],\n redemptionHistory: (actorSync.redemption_history ?? []).map(mapLpRedemptionHistory),\n redemptionHistoryHasMore: actorSync.redemption_history_has_more ?? false,\n ...(actorSync.redemption_history_next_cursor === undefined\n ? {}\n : { redemptionHistoryNextCursor: actorSync.redemption_history_next_cursor }),\n stateVersion: actorSync.state_version,\n updatedAtMs: actorSync.updated_at_ms,\n };\n}\n\nfunction mergePositionHistoryPages(first: LpPositionView, next: LpPositionView): LpPositionView {\n if (first.actorSync === undefined) return next;\n if (next.actorSync === undefined) return first;\n const historyByRedemptionId = new Map<string, LpRedemptionHistoryView>();\n for (const history of first.actorSync.redemptionHistory ?? []) {\n historyByRedemptionId.set(history.redemptionId, history);\n }\n for (const history of next.actorSync.redemptionHistory ?? []) {\n historyByRedemptionId.set(history.redemptionId, history);\n }\n return {\n ...first,\n actorSync: {\n ...first.actorSync,\n ...next.actorSync,\n redemptionHistory: [...historyByRedemptionId.values()],\n },\n };\n}\n\nfunction mapLpRedemptionHistory(history: LpRedemptionHistoryPayload): LpRedemptionHistoryView {\n return {\n redemptionId: history.redemption_id,\n state: history.state,\n acceptedLamports: history.accepted_lamports,\n acceptedDepositPrincipalLamports: history.accepted_deposit_principal_lamports,\n acceptedEarnedFeeLamports: history.accepted_earned_fee_lamports,\n landedLamports: history.landed_lamports,\n landedDepositPrincipalLamports: history.landed_deposit_principal_lamports,\n landedEarnedFeeLamports: history.landed_earned_fee_lamports,\n canceledLamports: history.canceled_lamports,\n canceledDepositPrincipalLamports: history.canceled_deposit_principal_lamports,\n canceledEarnedFeeLamports: history.canceled_earned_fee_lamports,\n networkFeeLamports: history.network_fee_lamports,\n networkFeeLossLamports: history.network_fee_loss_lamports,\n failedAttempts: history.failed_attempts,\n destinationAddresses: [...history.destination_addresses],\n destinationCount: history.destination_count,\n txSignatures: [...history.tx_signatures],\n txSignatureCount: history.tx_signature_count,\n detailsTruncated: history.details_truncated,\n stateVersion: history.state_version,\n createdAtMs: history.created_at_ms,\n updatedAtMs: history.updated_at_ms,\n };\n}\n\nfunction mapShard(shard: LpShardViewPayload): LpInventoryShard {\n return {\n kind: \"lp\",\n lpPositionId: shard.lp_position_id,\n shardId: shard.shard_id,\n index: shard.index,\n address: shard.address,\n amountLamports: shard.amount_lamports,\n ...(shard.required_lamports === undefined ? {} : { requiredLamports: shard.required_lamports }),\n status: mapStatus(shard.status),\n fundingTxSignature: shard.funding_tx_signature,\n payoutTxSignature: shard.payout_tx_signature,\n coolingUntilMs: shard.cooling_until_ms,\n };\n}\n\nfunction mapTopUpRequest(request: LpTopUpRequestPayload): LpTopUpRequest {\n return {\n topUpId: request.top_up_id,\n positionId: request.lp_position_id,\n depositAddress: request.deposit_address,\n expiresAtMs: request.expires_at_ms,\n status: request.status,\n };\n}\n\nfunction mapStatus(status: LpShardViewPayload[\"status\"]): LpInventoryShard[\"status\"] {\n switch (status) {\n case \"pregenerated\":\n return \"PREGENERATED\";\n case \"funding_queued\":\n return \"FUNDING_QUEUED\";\n case \"funded\":\n return \"FUNDED\";\n case \"cooling\":\n return \"COOLING\";\n case \"available\":\n return \"AVAILABLE\";\n case \"reserved\":\n return \"RESERVED\";\n case \"retired\":\n return \"RETIRED\";\n case \"redeemed\":\n return \"REDEEMED\";\n }\n}\n\nasync function coordinatorAttestationHash(\n binaryHash: string,\n pubkeyHex: string,\n): Promise<Uint8Array> {\n const material = encoder.encode(\n `invisible-lp-attestation-v1\\0${binaryHash.toLowerCase()}\\0${pubkeyHex.toLowerCase()}`,\n );\n return new Uint8Array(await crypto.subtle.digest(\"SHA-256\", material));\n}\n\nfunction randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n\nfunction loadProtocol(): Promise<ProtocolLpModule> {\n protocolPromise ??= import(\"protocol/coordinator\") as Promise<ProtocolLpModule>;\n return protocolPromise;\n}\n","import type { LpPositionCodeAuth } from \"./positionCode.js\";\nimport type { LpCoordinatorClient } from \"./types.js\";\n\ntype LpDkgWorkerRequest =\n | {\n id: string;\n type: \"round1\";\n }\n | {\n id: string;\n type: \"round2\";\n teeRound1: number[];\n teeRound2ForLp: number[];\n };\n\ntype LpDkgWorkerResponse =\n | {\n id: string;\n type: \"round1\";\n package: number[];\n }\n | {\n id: string;\n type: \"round2\";\n package: number[];\n delegatedShare: number[];\n jointPubkey: number[];\n }\n | {\n id: string;\n type: \"error\";\n error: string;\n };\n\nexport type LpDkgProgress = {\n completed: number;\n total: number;\n address: string;\n};\n\nexport type CreateLpDkgBatchInput = {\n lpPositionId: string;\n startIndex: number;\n count: number;\n auth: LpPositionCodeAuth;\n client: LpCoordinatorClient;\n concurrency?: number;\n workerFactory?: () => Worker;\n useDeterministicTestAddresses?: boolean;\n onProgress?: (progress: LpDkgProgress) => void;\n};\n\nconst MAX_LP_DKG_CONCURRENCY = 8;\nconst DEFAULT_LP_DKG_CONCURRENCY = MAX_LP_DKG_CONCURRENCY;\nconst LP_DKG_COMPLETED_SHARD_POLL_INTERVAL_MS = 500;\nconst LP_DKG_COMPLETED_SHARD_POLL_TIMEOUT_MS = 5 * 60_000 + 15_000;\nconst LP_DKG_ACTIVE_SESSION_RETRY_INTERVAL_MS = 2_000;\nconst LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS = LP_DKG_COMPLETED_SHARD_POLL_TIMEOUT_MS;\n\nexport async function createLpDkgBatch(input: CreateLpDkgBatchInput): Promise<string[]> {\n if (input.useDeterministicTestAddresses === true) {\n const addresses = Array.from({ length: input.count }, (_, offset) =>\n testAddress(input.lpPositionId, input.startIndex + offset),\n );\n for (const [offset, address] of addresses.entries()) {\n input.onProgress?.({\n completed: offset + 1,\n total: input.count,\n address,\n });\n }\n return addresses;\n }\n\n const workerCount = resolveConcurrency(input.count, input.concurrency);\n const workers = Array.from({ length: workerCount }, () => createWorker(input.workerFactory));\n const addresses = new Array<string>(input.count);\n let completed = 0;\n let nextOffset = 0;\n try {\n await Promise.all(\n workers.map(async (worker) => {\n for (;;) {\n const offset = nextOffset;\n nextOffset += 1;\n if (offset >= input.count) return;\n\n const index = input.startIndex + offset;\n const address = await createLpDkgShard(input, worker, index);\n addresses[offset] = address;\n completed += 1;\n input.onProgress?.({\n completed,\n total: input.count,\n address,\n });\n }\n }),\n );\n return addresses;\n } finally {\n workers.forEach((worker) => worker.terminate());\n }\n}\n\nasync function createLpDkgShard(\n input: CreateLpDkgBatchInput,\n worker: Worker,\n index: number,\n): Promise<string> {\n const deadline = Date.now() + LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS;\n let sawActiveSession = false;\n\n for (;;) {\n if (sawActiveSession) {\n const completedAddress = await getCompletedShardAddress(input, index);\n if (completedAddress !== null) return completedAddress;\n }\n\n try {\n return await runLpDkgShard(input, worker, index);\n } catch (error) {\n if (isLpDkgCompletedOrVisibleError(error)) {\n return waitForCompletedShardAddress(input, index);\n }\n if (!isLpDkgActiveSessionError(error)) throw error;\n\n sawActiveSession = true;\n const completedAddress = await getCompletedShardAddress(input, index);\n if (completedAddress !== null) return completedAddress;\n if (Date.now() >= deadline) throw error;\n await sleep(LP_DKG_ACTIVE_SESSION_RETRY_INTERVAL_MS);\n }\n }\n}\n\nasync function runLpDkgShard(\n input: CreateLpDkgBatchInput,\n worker: Worker,\n index: number,\n): Promise<string> {\n const roundId = `lp_dkg_${Date.now()}_${index}_${Math.random().toString(16).slice(2)}`;\n const initResponse = await input.client.initDkg(\n { lpPositionId: input.lpPositionId, index },\n input.auth,\n );\n\n const round1 = await workerRequest(worker, {\n id: roundId,\n type: \"round1\",\n });\n if (round1.type !== \"round1\") throw new Error(\"LP DKG worker returned wrong round1 type\");\n\n const round1Response = await input.client.dkgRound1(\n {\n sessionId: initResponse.sessionId,\n package: round1.package,\n },\n input.auth,\n );\n const round2 = await workerRequest(worker, {\n id: roundId,\n type: \"round2\",\n teeRound1: Array.from(round1Response.package),\n teeRound2ForLp: Array.from(round1Response.round2ForLp),\n });\n if (round2.type !== \"round2\") throw new Error(\"LP DKG worker returned wrong round2 type\");\n\n const round2Response = await input.client.dkgRound2(\n {\n sessionId: initResponse.sessionId,\n package: round2.package,\n delegatedShare: round2.delegatedShare,\n },\n input.auth,\n );\n if (!bytesEqual(Uint8Array.from(round2.jointPubkey), round2Response.jointPubkey)) {\n throw new Error(`LP DKG joint pubkey mismatch at index ${index}`);\n }\n if (round2Response.index !== index) {\n throw new Error(`LP DKG index mismatch: expected ${index}, got ${round2Response.index}`);\n }\n\n return round2Response.address;\n}\n\nasync function waitForCompletedShardAddress(\n input: CreateLpDkgBatchInput,\n index: number,\n): Promise<string> {\n const deadline = Date.now() + LP_DKG_COMPLETED_SHARD_POLL_TIMEOUT_MS;\n for (;;) {\n const address = await getCompletedShardAddress(input, index);\n if (address !== null) return address;\n if (Date.now() >= deadline) {\n throw new Error(`LP DKG completed shard ${index} did not become visible`);\n }\n await sleep(LP_DKG_COMPLETED_SHARD_POLL_INTERVAL_MS);\n }\n}\n\nasync function getCompletedShardAddress(\n input: CreateLpDkgBatchInput,\n index: number,\n): Promise<string | null> {\n const position = await input.client.getPosition(input.lpPositionId, input.auth);\n return position.shards.find((candidate) => candidate.index === index)?.address ?? null;\n}\n\nfunction workerRequest(worker: Worker, request: LpDkgWorkerRequest): Promise<LpDkgWorkerResponse> {\n return new Promise((resolve, reject) => {\n const onMessage = (event: MessageEvent<LpDkgWorkerResponse>) => {\n const message = event.data;\n if (message.id !== request.id) return;\n cleanup();\n if (message.type === \"error\") {\n reject(new Error(message.error));\n } else {\n resolve(message);\n }\n };\n const onError = (event: ErrorEvent) => {\n cleanup();\n reject(new Error(event.message));\n };\n const cleanup = () => {\n worker.removeEventListener(\"message\", onMessage);\n worker.removeEventListener(\"error\", onError);\n };\n worker.addEventListener(\"message\", onMessage);\n worker.addEventListener(\"error\", onError);\n worker.postMessage(request);\n });\n}\n\nfunction createWorker(workerFactory: (() => Worker) | undefined): Worker {\n if (workerFactory !== undefined) return workerFactory();\n return new Worker(new URL(\"./dkgWorker.js\", import.meta.url), { type: \"module\" });\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n let diff = 0;\n for (let index = 0; index < a.byteLength; index += 1) {\n diff |= a[index]! ^ b[index]!;\n }\n return diff === 0;\n}\n\nfunction isLpDkgCompletedOrVisibleError(error: unknown): boolean {\n if (!(error instanceof Error) || !error.message.includes(\"LP DKG index\")) return false;\n return (\n error.message.includes(\"already completed for position\") ||\n error.message.includes(\"already exists for position\")\n );\n}\n\nfunction isLpDkgActiveSessionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.includes(\"LP DKG session already active for position index\")\n );\n}\n\nfunction resolveConcurrency(count: number, requested: number | undefined): number {\n if (count <= 0) return 0;\n const concurrency = requested ?? DEFAULT_LP_DKG_CONCURRENCY;\n if (!Number.isFinite(concurrency)) return Math.min(count, DEFAULT_LP_DKG_CONCURRENCY);\n return Math.max(1, Math.min(count, MAX_LP_DKG_CONCURRENCY, Math.floor(concurrency)));\n}\n\nfunction sleep(delayMs: number): Promise<void> {\n return new Promise((resolve) => {\n globalThis.setTimeout(resolve, delayMs);\n });\n}\n\nfunction testAddress(lpPositionId: string, index: number): string {\n return `${lpPositionId}Shard${String(index).padStart(5, \"0\")}11111111111111111111`;\n}\n","import {\n LP_DEFAULT_REFILL_BATCH_SIZE,\n LP_DEFAULT_TARGET_SHARDS,\n LP_MAX_REFILL_BATCH_SIZE,\n LP_MAX_TARGET_SHARDS,\n} from \"@invisible/shared\";\nimport { LpLifecycleError, PolicyValidationError, RoutingError } from \"../core/errors.js\";\nimport type { Session } from \"../core/session.js\";\nimport { publicKey } from \"../core/brands.js\";\nimport { assertAttested } from \"../session/guards.js\";\nimport { createLpCoordinatorClient } from \"./coordinatorClient.js\";\nimport { createLpDkgBatch } from \"./dkgBatch.js\";\nimport {\n bytesToHex,\n deriveLpPositionCodeAuth,\n generateLpPositionCode,\n type LpPositionCodeAuth,\n} from \"./positionCode.js\";\nimport { validateLpWithdrawalPlan } from \"./withdrawalValidation.js\";\nimport type {\n LpCoordinatorClient,\n LpInventoryShard,\n LpPositionView,\n LpRedemptionHistoryView,\n LpWithdrawalExecutionView,\n} from \"./types.js\";\n\nconst LP_ID_PREFIX = \"lp\";\nconst DEFAULT_SHARD_FUNDING_LAMPORTS = 101_000_000;\nconst DEFAULT_REFILL_THRESHOLD_RATIO = 0.2;\nconst LP_DKG_ACTIVE_SESSION_RETRY_DELAY_MS = 2_000;\nconst LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS = 5 * 60_000 + 15_000;\nconst LP_WITHDRAWAL_CONFIRMATION_POLL_INTERVAL_MS = 3_000;\nconst LP_WITHDRAWAL_CONFIRMATION_TIMEOUT_MS = 15 * 60_000;\nconst LP_TOP_UP_WAIT_POLL_INTERVAL_MS = 1_000;\nconst LP_REDEMPTION_HISTORY_OPEN_STATES: ReadonlySet<LpRedemptionHistoryView[\"state\"]> = new Set([\n \"requested\",\n \"match_requested\",\n \"reserved\",\n \"pending\",\n]);\nexport const LP_REDEMPTION_RECONCILING_MESSAGE =\n \"LP redemption is still settling on the coordinator; it will reconcile from sync\";\nexport const LP_MISSING_POSITION_CODE_MESSAGE =\n \"Save or recover the LP Position Code before using LP funds\";\nconst POSITION_CODE_MISMATCH_MESSAGE = \"LP Position Code does not match this TEE position\";\nconst FUNDING_PLAN_EMPTY_MESSAGE = \"TEE returned an empty LP funding plan\";\nconst WITHDRAWAL_MISSING_RECORD_MESSAGE = \"LP withdrawal record is missing\";\nconst WITHDRAWAL_RECORD_MISMATCH_MESSAGE =\n \"LP withdrawal record does not match this confirmation request\";\nconst WITHDRAWAL_NO_LAMPORTS_MESSAGE = \"LP redemption did not land any lamports on-chain\";\nconst WITHDRAWAL_HISTORY_MISMATCH_MESSAGE = \"LP redemption history does not match this request\";\nconst UNSUPPORTED_FEE_POLICY_MESSAGE =\n \"LP fee policy overrides are not advertised by the coordinator\";\nconst FEE_SOURCE_COUNT_UNAVAILABLE_MESSAGE =\n \"LP earned-fee source count is not available; pass allowManyToOne: true to acknowledge many-to-one withdrawal risk\";\n\nexport type LpLifecycleDkgProgress = {\n readonly phase: \"dkg\";\n readonly lpPositionId: string;\n readonly startIndex: number;\n readonly targetShardCount: number;\n readonly completed: number;\n readonly total: number;\n};\n\nexport interface CreatePositionArgs {\n readonly committedLamports?: number;\n readonly shardCount?: number;\n readonly refillThreshold?: number;\n readonly feePolicy?: unknown;\n /**\n * Called after SDK-owned code generation and before the coordinator open call.\n * Use this to show/save the code if coordinator intake fails.\n */\n readonly onPositionCode?: (code: LpGeneratedPositionCode) => void;\n}\n\nexport interface LpGeneratedPositionCode {\n readonly positionId: string;\n readonly lpPositionCode: string;\n}\n\nexport interface CreatePositionResult {\n readonly positionId: string;\n /** Shown once at onboarding; treat like a seed phrase. */\n readonly lpPositionCode: string;\n readonly position: LpPositionView;\n}\n\nexport interface CompleteDkgBatchOptions {\n readonly onProgress?: (progress: LpLifecycleDkgProgress) => void;\n readonly onPosition?: (position: LpPositionView) => void;\n readonly concurrency?: number;\n readonly workerFactory?: () => Worker;\n}\n\nexport interface InitialFundingPlan {\n readonly address: string;\n readonly requiredLamports: number;\n readonly qrPayload: string;\n readonly position: LpPositionView;\n}\n\nexport interface LpTopUpRequest {\n readonly topUpId: string;\n readonly positionId: string;\n readonly depositAddress: string;\n readonly expiresAtMs: number;\n readonly status: \"watching\" | \"funded\" | \"expired\";\n}\n\nexport interface WithdrawPositionArgs {\n /** Accepted LP deposit-principal bucket claim. Computed from the position when omitted. */\n readonly depositPrincipalLamports?: number;\n /** Accepted earned-fee bucket claim. Computed from the position when omitted. */\n readonly earnedFeeLamports?: number;\n readonly destinationAddresses: string[];\n /** Required to accept a privacy-degrading single-destination withdrawal. */\n readonly allowManyToOne?: boolean;\n}\n\nexport interface RefillArgs {\n readonly shardCount?: number;\n readonly onProgress?: (progress: LpLifecycleDkgProgress) => void;\n readonly onPosition?: (position: LpPositionView) => void;\n readonly workerFactory?: () => Worker;\n}\n\nexport interface WithdrawalExecution {\n readonly withdrawalId: string;\n readonly txSignatures: string[];\n}\n\nexport interface LpWithdrawalRecord {\n readonly redemptionId: string;\n readonly lpPositionId: string;\n readonly requestedAt: number;\n readonly status: \"pending\" | \"reconciling\" | \"confirmed\" | \"failed\";\n readonly destinationAddresses: string[];\n readonly destinationCount?: number;\n readonly txSignatureCount?: number;\n readonly detailsTruncated?: boolean;\n readonly acceptedLamports?: number;\n readonly requestedTargetLamports: number;\n readonly landedBaselineLamports: number;\n readonly landedFeeBaselineLamports?: number;\n readonly redeemedLamports: number;\n readonly txSignatures: string[];\n readonly txSignatureBaseline: string[];\n readonly coordinatorStateVersion?: number;\n readonly error?: string;\n}\n\nexport interface WithdrawPositionResult {\n readonly execution: WithdrawalExecution;\n readonly position: LpPositionView;\n readonly redemption: LpWithdrawalRecord;\n}\n\nexport interface WithdrawalConfirmation {\n readonly withdrawalId: string;\n readonly txSignatures: string[];\n readonly redeemedLamports: number;\n}\n\nexport interface LpLifecycleRuntime {\n readonly coordinatorClient?: LpCoordinatorClient;\n readonly workerFactory?: () => Worker;\n readonly useDeterministicTestAddresses?: boolean;\n readonly nowMs?: () => number;\n readonly idFactory?: () => string;\n readonly sleep?: (delayMs: number) => Promise<void>;\n readonly dkgConcurrency?: number;\n readonly withdrawalConfirmationPollIntervalMs?: number;\n readonly withdrawalConfirmationTimeoutMs?: number;\n}\n\nexport interface WaitForWithdrawalConfirmationOptions {\n readonly onPosition?: (position: LpPositionView) => void;\n readonly onRedemptionUpdate?: (record: LpWithdrawalRecord) => void;\n readonly redemptionRecord?: LpWithdrawalRecord;\n}\n\nexport interface WaitForTopUpOptions {\n readonly signal?: AbortSignal;\n readonly pollIntervalMs?: number;\n readonly positionId?: string;\n}\n\nclass LpRedemptionReconcilingError extends LpLifecycleError {\n constructor() {\n super(\"LP_REDEMPTION_RECONCILING\", LP_REDEMPTION_RECONCILING_MESSAGE);\n this.name = \"LpRedemptionReconcilingError\";\n }\n}\n\nclass LpPositionAuthMissingError extends LpLifecycleError {\n constructor() {\n super(\"LP_POSITION_AUTH_MISSING\", LP_MISSING_POSITION_CODE_MESSAGE);\n this.name = \"LpPositionAuthMissingError\";\n }\n}\n\nexport function isLpRedemptionReconcilingError(error: unknown): boolean {\n return (\n error instanceof LpRedemptionReconcilingError ||\n (error instanceof Error && error.message === LP_REDEMPTION_RECONCILING_MESSAGE)\n );\n}\n\nexport function isLpPositionAuthMissingError(error: unknown): boolean {\n return (\n error instanceof LpPositionAuthMissingError ||\n (error instanceof Error && error.message === LP_MISSING_POSITION_CODE_MESSAGE)\n );\n}\n\nexport interface LpLifecycleClient {\n createPosition(args?: CreatePositionArgs): Promise<CreatePositionResult>;\n recoverPosition(args: { readonly code: string }): Promise<LpPositionView>;\n confirmPositionCodeSaved(positionId: string): void;\n completeDkgBatch(positionId: string, options?: CompleteDkgBatchOptions): Promise<LpPositionView>;\n refreshPosition(positionId: string): Promise<LpPositionView>;\n refill(positionId: string, args?: RefillArgs): Promise<LpPositionView>;\n prepareInitialFunding(positionId: string): Promise<InitialFundingPlan | null>;\n prepareTopUp(positionId: string): Promise<LpTopUpRequest>;\n waitForTopUp(topUpId: string, options?: WaitForTopUpOptions): Promise<LpTopUpRequest>;\n reconcileFunding(positionId: string): Promise<LpPositionView>;\n withdrawPosition(positionId: string, args: WithdrawPositionArgs): Promise<WithdrawPositionResult>;\n waitForWithdrawalConfirmation(\n positionId: string,\n execution: WithdrawalExecution,\n options?: WaitForWithdrawalConfirmationOptions,\n ): Promise<WithdrawalConfirmation>;\n withdrawFees(positionId: string, args: { readonly destination: string }): Promise<never>;\n listPositions(): Promise<LpPositionView[]>;\n}\n\ntype LpLifecycleState = {\n readonly authByPosition: Map<string, LpPositionCodeAuth>;\n readonly positions: Map<string, LpPositionView>;\n readonly redemptions: Map<string, LpWithdrawalRecord>;\n readonly topUps: Map<string, LpTopUpRequest>;\n};\n\nconst lifecycleClients = new WeakMap<Session, LpLifecycleClient>();\n\nexport function createLpLifecycleClient(\n session: Session,\n runtime: LpLifecycleRuntime = {},\n): LpLifecycleClient {\n const state: LpLifecycleState = {\n authByPosition: new Map(),\n positions: new Map(),\n redemptions: new Map(),\n topUps: new Map(),\n };\n const client = runtime.coordinatorClient ?? createLpCoordinatorClient(session);\n const nowMs = runtime.nowMs ?? Date.now;\n const sleep = runtime.sleep ?? defaultSleep;\n\n const requireAuth = (positionId: string): LpPositionCodeAuth => {\n const auth = state.authByPosition.get(positionId);\n if (auth === undefined) throw new LpPositionAuthMissingError();\n return auth;\n };\n\n const rememberPosition = (position: LpPositionView): LpPositionView => {\n const snapshot = clonePosition(position);\n state.positions.set(snapshot.id, snapshot);\n hydrateLpRedemptionsFromPosition(state, snapshot);\n return position;\n };\n\n const rememberAuth = (auth: LpPositionCodeAuth): void => {\n state.authByPosition.set(auth.lpPositionId, auth);\n };\n\n const refreshPosition = async (positionId: string): Promise<LpPositionView> => {\n const auth = requireAuth(positionId);\n return rememberPosition(await client.getPosition(positionId, auth));\n };\n\n const completeDkgBatch = async (\n positionId: string,\n options: CompleteDkgBatchOptions = {},\n ): Promise<LpPositionView> => {\n assertAttested(session);\n const auth = requireAuth(positionId);\n let activeSessionRetryStartedAtMs: number | null = null;\n\n for (;;) {\n const current = rememberPosition(await client.getPosition(positionId, auth));\n options.onPosition?.(current);\n const startIndex = current.shards.length;\n const remaining = current.targetShardCount - startIndex;\n if (remaining <= 0) return current;\n\n emitDkgProgress(options, current, startIndex, remaining, 0);\n let expectedAddresses: string[] | null = null;\n try {\n const addresses = await createLpDkgBatch({\n lpPositionId: positionId,\n startIndex,\n count: remaining,\n auth,\n client,\n concurrency: options.concurrency ?? runtime.dkgConcurrency,\n workerFactory: options.workerFactory ?? runtime.workerFactory,\n useDeterministicTestAddresses: runtime.useDeterministicTestAddresses,\n onProgress: (progress) => {\n emitDkgProgress(options, current, startIndex, remaining, progress.completed);\n },\n });\n expectedAddresses = addresses;\n const position = await client.finalizeDkgBatch(\n {\n lpPositionId: positionId,\n startIndex,\n addresses,\n finalizedAtMs: nowMs(),\n },\n auth,\n );\n options.onPosition?.(position);\n emitDkgProgress(options, position, startIndex, remaining, remaining);\n return rememberPosition(position);\n } catch (error) {\n const reconciled = await tryRefreshCompletedDkgWindow({\n client,\n positionId,\n auth,\n startIndex,\n total: remaining,\n expectedAddresses,\n state,\n });\n if (reconciled !== null) return reconciled;\n if (isLpDkgIndexDriftError(error)) {\n activeSessionRetryStartedAtMs = null;\n continue;\n }\n if (!isLpDkgActiveSessionError(error)) throw error;\n\n const currentTime = nowMs();\n activeSessionRetryStartedAtMs ??= currentTime;\n if (currentTime - activeSessionRetryStartedAtMs >= LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS) {\n throw error;\n }\n await sleep(LP_DKG_ACTIVE_SESSION_RETRY_DELAY_MS);\n }\n }\n };\n\n return {\n async createPosition(args = {}) {\n assertNoUnsupportedFeePolicy(args.feePolicy);\n const shardCount = args.shardCount ?? LP_DEFAULT_TARGET_SHARDS;\n assertShardCount(shardCount, LP_MAX_TARGET_SHARDS, \"shardCount\");\n assertAttested(session);\n const positionId = runtime.idFactory?.() ?? generateId(LP_ID_PREFIX);\n const auth = await generateLpPositionCode(positionId);\n rememberAuth(auth);\n args.onPositionCode?.({ positionId, lpPositionCode: auth.code });\n const committedLamports = args.committedLamports ?? DEFAULT_SHARD_FUNDING_LAMPORTS;\n const position = rememberPosition(\n await client.openPosition(\n {\n lpPositionId: positionId,\n authPublicKey: Array.from(auth.authPublicKey),\n refillPublicKey: Array.from(auth.refillPublicKey),\n withdrawalCommitment: Array.from(auth.withdrawalCommitment),\n committedLamports,\n shardCount,\n shardAmountLamports: DEFAULT_SHARD_FUNDING_LAMPORTS,\n refillThreshold:\n args.refillThreshold ?? Math.ceil(shardCount * DEFAULT_REFILL_THRESHOLD_RATIO),\n addresses: [],\n createdAtMs: nowMs(),\n },\n auth,\n ),\n );\n return { positionId, lpPositionCode: auth.code, position };\n },\n\n async recoverPosition(args) {\n const auth = await deriveLpPositionCodeAuth(args.code);\n rememberAuth(auth);\n const position = rememberPosition(await client.getPosition(auth.lpPositionId, auth));\n assertPositionMatchesAuth(position, auth);\n return position;\n },\n\n confirmPositionCodeSaved(_positionId) {\n return;\n },\n\n completeDkgBatch,\n\n refreshPosition,\n\n async refill(positionId, args = {}) {\n const requestedShardCount = args.shardCount ?? LP_DEFAULT_REFILL_BATCH_SIZE;\n assertShardCount(requestedShardCount, LP_MAX_REFILL_BATCH_SIZE, \"shardCount\");\n assertAttested(session);\n const auth = requireAuth(positionId);\n const current = await refreshPosition(positionId);\n args.onPosition?.(current);\n const refillShardCount = resolveLpRefillShardCount(\n current,\n requestedShardCount,\n args.shardCount === undefined,\n );\n const authorizedPosition = rememberPosition(\n await client.refillPosition(\n {\n lpPositionId: positionId,\n shardCount: refillShardCount,\n shardAmountLamports: DEFAULT_SHARD_FUNDING_LAMPORTS,\n addresses: [],\n authorizedAtMs: nowMs(),\n },\n auth,\n ),\n );\n args.onPosition?.(authorizedPosition);\n if (authorizedPosition.shards.length >= authorizedPosition.targetShardCount) {\n return authorizedPosition;\n }\n return completeDkgBatch(positionId, {\n onProgress: args.onProgress,\n onPosition: args.onPosition,\n workerFactory: args.workerFactory,\n });\n },\n\n async prepareInitialFunding(positionId) {\n assertAttested(session);\n const auth = requireAuth(positionId);\n const currentPosition = rememberPosition(await client.getPosition(positionId, auth));\n if (!isLpPositionReadyForInitialFunding(currentPosition)) return null;\n\n const initialShard = currentPosition.shards.find((shard) => shard.index === 0);\n if (initialShard === undefined) return null;\n if (initialShard.status === \"FUNDING_QUEUED\") {\n return fundingPlanFromShard(currentPosition, initialShard);\n }\n if (initialShard.status !== \"PREGENERATED\") return null;\n\n const existingQueuedShard = currentPosition.shards.find(\n (shard) => shard.status === \"FUNDING_QUEUED\",\n );\n if (existingQueuedShard !== undefined) return null;\n\n const [plannedShard] = await client.planFunding(\n { lpPositionId: positionId, shardCount: 1, nowMs: nowMs() },\n auth,\n );\n if (plannedShard === undefined) throw new Error(FUNDING_PLAN_EMPTY_MESSAGE);\n if (plannedShard.index !== 0) {\n throw new PolicyValidationError(\n \"INVALID_POSITION_AUTH\",\n \"Coordinator funding plan did not select LP_DKG_0\",\n );\n }\n const position = rememberPosition(await client.getPosition(positionId, auth));\n return fundingPlanFromShard(position, plannedShard);\n },\n\n async prepareTopUp(positionId) {\n assertAttested(session);\n const auth = requireAuth(positionId);\n const request = await client.prepareTopUp(positionId, auth);\n state.topUps.set(request.topUpId, request);\n return request;\n },\n\n async waitForTopUp(topUpId, options = {}) {\n const cached = state.topUps.get(topUpId);\n if (\n cached !== undefined &&\n options.positionId !== undefined &&\n cached.positionId !== options.positionId\n ) {\n throw new PolicyValidationError(\n \"INVALID_POSITION_AUTH\",\n \"Top-up request does not belong to the requested LP position\",\n );\n }\n const initial =\n cached ??\n (options.positionId === undefined\n ? undefined\n : await client.getTopUpStatus(\n { lpPositionId: options.positionId, topUpId },\n requireAuth(options.positionId),\n ));\n if (initial === undefined) {\n throw new PolicyValidationError(\n \"INVALID_POSITION_AUTH\",\n \"Top-up request is not known to this LP session\",\n );\n }\n const pollIntervalMs = options.pollIntervalMs ?? LP_TOP_UP_WAIT_POLL_INTERVAL_MS;\n let current = initial;\n for (;;) {\n throwIfTopUpWaitAborted(options.signal);\n if (current.status !== \"watching\") return current;\n const auth = requireAuth(current.positionId);\n current = await client.getTopUpStatus({ lpPositionId: current.positionId, topUpId }, auth);\n state.topUps.set(topUpId, current);\n if (current.status !== \"watching\") return current;\n if (nowMs() >= current.expiresAtMs) {\n current = await client.getTopUpStatus(\n { lpPositionId: current.positionId, topUpId },\n auth,\n );\n state.topUps.set(topUpId, current);\n if (current.status !== \"watching\") return current;\n current = { ...current, status: \"expired\" };\n state.topUps.set(topUpId, current);\n return current;\n }\n await sleep(pollIntervalMs);\n }\n },\n\n async reconcileFunding(positionId) {\n assertAttested(session);\n const auth = requireAuth(positionId);\n return rememberPosition(await client.reconcileFunding(positionId, auth));\n },\n\n async withdrawPosition(positionId, args) {\n validateExplicitWithdrawalInput(args);\n validateWithdrawalDestinations(args);\n assertAttested(session);\n const auth = requireAuth(positionId);\n const before = rememberPosition(await client.reconcileFunding(positionId, auth));\n const existingRedemption = findOpenRedemptionHistory(before, args);\n if (existingRedemption !== undefined) {\n const execution = {\n withdrawalId: existingRedemption.redemptionId,\n txSignatures: [...existingRedemption.txSignatures],\n };\n const redemption = {\n ...buildLpRedemptionRecord({\n execution,\n position: before,\n destinationAddresses: existingRedemption.destinationAddresses,\n acceptedLamports: existingRedemption.acceptedLamports,\n requestedTargetLamports: existingRedemption.acceptedLamports,\n landedBaselineLamports: 0,\n landedFeeBaselineLamports: 0,\n txSignatureBaseline: [],\n nowMs: existingRedemption.createdAtMs,\n }),\n redeemedLamports: existingRedemption.landedLamports,\n coordinatorStateVersion: existingRedemption.stateVersion,\n };\n state.redemptions.set(execution.withdrawalId, redemption);\n return { execution, position: before, redemption };\n }\n const claim = resolveWithdrawalClaim(before, args);\n const sourceCount = lpWithdrawalSourceCountForClaim(before, {\n ...claim,\n allowManyToOne: args.allowManyToOne,\n });\n const validationInput = {\n lpPositionId: positionId,\n destinationAddresses: args.destinationAddresses,\n depositPrincipalLamports: claim.depositPrincipalLamports,\n earnedFeeLamports: claim.earnedFeeLamports,\n requestedAtMs: nowMs(),\n allowManyToOne: args.allowManyToOne ?? false,\n sourceCount,\n };\n validateLpWithdrawalPlan(validationInput);\n const execution = await client.executeWithdrawal(\n {\n lpPositionId: validationInput.lpPositionId,\n destinationAddresses: validationInput.destinationAddresses,\n depositPrincipalLamports: validationInput.depositPrincipalLamports,\n earnedFeeLamports: validationInput.earnedFeeLamports,\n requestedAtMs: validationInput.requestedAtMs,\n allowManyToOne: args.allowManyToOne === true || sourceCount === 1,\n },\n auth,\n );\n const pendingRedemption = buildLpRedemptionRecord({\n execution,\n position: before,\n destinationAddresses: args.destinationAddresses,\n acceptedLamports: claim.depositPrincipalLamports + claim.earnedFeeLamports,\n requestedTargetLamports:\n (before.actorSync?.withdrawalRequestedLamports ?? 0) +\n claim.depositPrincipalLamports +\n claim.earnedFeeLamports,\n landedBaselineLamports: before.actorSync?.withdrawalLandedLamports ?? 0,\n landedFeeBaselineLamports: before.actorSync?.withdrawalLandedFeeLamports ?? 0,\n txSignatureBaseline: before.actorSync?.withdrawalTxHashes ?? [],\n nowMs: nowMs(),\n });\n state.redemptions.set(execution.withdrawalId, pendingRedemption);\n const position = await client\n .getPosition(positionId, auth)\n .then((refreshed) => rememberPosition(refreshed))\n .catch(() => before);\n const redemption = { ...pendingRedemption, lpPositionId: position.id };\n state.redemptions.set(execution.withdrawalId, redemption);\n return { execution, position, redemption };\n },\n\n async waitForWithdrawalConfirmation(positionId, execution, options = {}) {\n const auth = requireAuth(positionId);\n let record = resolveWithdrawalRecord({\n state,\n positionId,\n execution,\n options,\n });\n state.redemptions.set(record.redemptionId, record);\n const deadlineMs =\n nowMs() +\n (runtime.withdrawalConfirmationTimeoutMs ?? LP_WITHDRAWAL_CONFIRMATION_TIMEOUT_MS);\n const pollIntervalMs =\n runtime.withdrawalConfirmationPollIntervalMs ?? LP_WITHDRAWAL_CONFIRMATION_POLL_INTERVAL_MS;\n\n for (;;) {\n const position = rememberPosition(await client.getPosition(positionId, auth));\n options.onPosition?.(position);\n const reconciled = reconcileLpRedemptionFromActorSync(record, position);\n record = reconciled;\n state.redemptions.set(record.redemptionId, reconciled);\n options.onRedemptionUpdate?.(reconciled);\n if (reconciled.status === \"confirmed\") {\n return {\n withdrawalId: execution.withdrawalId,\n txSignatures: reconciled.txSignatures,\n redeemedLamports: reconciled.redeemedLamports,\n };\n }\n if (reconciled.status === \"failed\") {\n throw new Error(reconciled.error ?? WITHDRAWAL_NO_LAMPORTS_MESSAGE);\n }\n if (nowMs() > deadlineMs) {\n state.redemptions.set(record.redemptionId, { ...reconciled, status: \"reconciling\" });\n options.onRedemptionUpdate?.({ ...reconciled, status: \"reconciling\" });\n throw new LpRedemptionReconcilingError();\n }\n await sleep(pollIntervalMs);\n }\n },\n\n async withdrawFees(_positionId, args) {\n publicKey(args.destination);\n assertAttested(session);\n throw new RoutingError(\n \"VERSION_NOT_SUPPORTED\",\n \"LP fee withdrawal is not advertised by the coordinator\",\n );\n },\n\n async listPositions() {\n return [...state.positions.values()].map(clonePosition);\n },\n };\n}\n\nexport function defaultLpLifecycleClient(session: Session): LpLifecycleClient {\n let client = lifecycleClients.get(session);\n if (client === undefined) {\n client = createLpLifecycleClient(session);\n lifecycleClients.set(session, client);\n }\n return client;\n}\n\nfunction emitDkgProgress(\n options: CompleteDkgBatchOptions,\n position: LpPositionView,\n startIndex: number,\n total: number,\n completed: number,\n): void {\n options.onProgress?.({\n phase: \"dkg\",\n lpPositionId: position.id,\n startIndex,\n targetShardCount: startIndex + total,\n completed: Math.min(completed, total),\n total,\n });\n}\n\nasync function tryRefreshCompletedDkgWindow({\n client,\n positionId,\n auth,\n startIndex,\n total,\n expectedAddresses,\n state,\n}: {\n readonly client: LpCoordinatorClient;\n readonly positionId: string;\n readonly auth: LpPositionCodeAuth;\n readonly startIndex: number;\n readonly total: number;\n readonly expectedAddresses: readonly string[] | null;\n readonly state: LpLifecycleState;\n}): Promise<LpPositionView | null> {\n const position = await client.getPosition(positionId, auth).catch(() => null);\n if (position === null) return null;\n if (!hasCompletedDkgWindow(position, startIndex, total, expectedAddresses)) return null;\n state.positions.set(position.id, clonePosition(position));\n return position;\n}\n\nfunction hasCompletedDkgWindow(\n position: LpPositionView,\n startIndex: number,\n total: number,\n expectedAddresses: readonly string[] | null,\n): boolean {\n for (let offset = 0; offset < total; offset += 1) {\n const shard = position.shards.find((candidate) => candidate.index === startIndex + offset);\n if (shard === undefined) {\n return false;\n }\n if (expectedAddresses !== null && shard.address !== expectedAddresses[offset]) {\n return false;\n }\n }\n return true;\n}\n\nfunction assertNoUnsupportedFeePolicy(feePolicy: unknown): void {\n if (feePolicy === undefined) return;\n throw new RoutingError(\"VERSION_NOT_SUPPORTED\", UNSUPPORTED_FEE_POLICY_MESSAGE);\n}\n\nfunction fundingPlanFromShard(\n position: LpPositionView,\n shard: LpInventoryShard,\n): InitialFundingPlan | null {\n if (shard.requiredLamports === undefined || shard.requiredLamports <= 0) return null;\n return {\n address: shard.address,\n requiredLamports: shard.requiredLamports,\n qrPayload: `solana:${shard.address}`,\n position,\n };\n}\n\nfunction assertPositionMatchesAuth(position: LpPositionView, auth: LpPositionCodeAuth): void {\n if (\n position.authPublicKey !== bytesToHex(auth.authPublicKey) ||\n position.refillPublicKey !== bytesToHex(auth.refillPublicKey) ||\n position.withdrawalCommitment !== bytesToHex(auth.withdrawalCommitment)\n ) {\n throw new Error(POSITION_CODE_MISMATCH_MESSAGE);\n }\n}\n\nfunction assertShardCount(value: number, max: number, field: string): void {\n if (!Number.isInteger(value) || value < 1 || value > max) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n `${field} must be an integer in 1..${max}, received ${String(value)}`,\n );\n }\n}\n\nfunction resolveLpRefillShardCount(\n position: LpPositionView,\n requestedShardCount: number,\n capDefaultBatch: boolean,\n): number {\n const remainingShardCapacity = LP_MAX_TARGET_SHARDS - position.shards.length;\n if (remainingShardCapacity <= 0) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n `LP refill target_shard_count is already at ${LP_MAX_TARGET_SHARDS}`,\n );\n }\n const refillShardCount = capDefaultBatch\n ? Math.min(requestedShardCount, remainingShardCapacity)\n : requestedShardCount;\n if (position.shards.length + refillShardCount > LP_MAX_TARGET_SHARDS) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n `LP refill target_shard_count must be <= ${LP_MAX_TARGET_SHARDS}`,\n );\n }\n return refillShardCount;\n}\n\nfunction isLpPositionReadyForInitialFunding(position: LpPositionView): boolean {\n return position.status === \"active\" && position.shards.length >= position.targetShardCount;\n}\n\nfunction resolveWithdrawalClaim(\n position: LpPositionView,\n args: WithdrawPositionArgs,\n): { readonly depositPrincipalLamports: number; readonly earnedFeeLamports: number } {\n if (args.depositPrincipalLamports !== undefined || args.earnedFeeLamports !== undefined) {\n return {\n depositPrincipalLamports: args.depositPrincipalLamports ?? 0,\n earnedFeeLamports: args.earnedFeeLamports ?? 0,\n };\n }\n const legacyDepositPrincipalLamports = position.shards\n .filter((shard) => shard.status === \"AVAILABLE\" && shard.amountLamports > 0)\n .reduce((sum, shard) => sum + shard.amountLamports, 0);\n const actorRedeemablePrincipalLamports = Math.max(\n 0,\n position.actorSync?.redeemablePrincipalLamports ?? 0,\n );\n const actorRedeemableFeeLamports = Math.max(0, position.actorSync?.redeemableFeeLamports ?? 0);\n const hasActorProjection = hasActorRedeemableProjection(position.actorSync);\n const depositPrincipalLamports = resolveRedeemablePrincipalLamports(\n position.actorSync,\n legacyDepositPrincipalLamports,\n actorRedeemablePrincipalLamports,\n actorRedeemableFeeLamports,\n );\n const earnedFeeLamports = hasActorProjection\n ? actorRedeemableFeeLamports\n : Math.max(0, position.earnedLamports);\n const totalLamports = depositPrincipalLamports + earnedFeeLamports;\n if (!Number.isSafeInteger(totalLamports) || totalLamports <= 0) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n \"LP withdrawal requires available principal or earned fees\",\n );\n }\n return { depositPrincipalLamports, earnedFeeLamports };\n}\n\nfunction findOpenRedemptionHistory(\n position: LpPositionView,\n args: WithdrawPositionArgs,\n): LpRedemptionHistoryView | undefined {\n const hasExplicitClaim =\n args.depositPrincipalLamports !== undefined || args.earnedFeeLamports !== undefined;\n const requestedPrincipalLamports = args.depositPrincipalLamports ?? 0;\n const requestedFeeLamports = args.earnedFeeLamports ?? 0;\n return position.actorSync?.redemptionHistory?.find(\n (history) =>\n LP_REDEMPTION_HISTORY_OPEN_STATES.has(history.state) &&\n history.detailsTruncated !== true &&\n sameStringList(history.destinationAddresses, args.destinationAddresses) &&\n (!hasExplicitClaim ||\n (history.acceptedDepositPrincipalLamports === requestedPrincipalLamports &&\n history.acceptedEarnedFeeLamports === requestedFeeLamports)),\n );\n}\n\nfunction hasActorSyncLpActivity(sync: LpPositionView[\"actorSync\"]): boolean {\n if (sync === undefined) return false;\n return (\n sync.status !== \"idle\" ||\n sync.pendingReservationCount > 0 ||\n sync.reservedPayoutLamports > 0 ||\n sync.reimbursementDueCount > 0 ||\n sync.reimbursementDueSourceCount > 0 ||\n sync.reimbursementDuePayoutLamports > 0 ||\n sync.reimbursementDueNetworkFeeLamports > 0 ||\n sync.withdrawalRequestedLamports > 0 ||\n sync.withdrawalLandedLamports > 0 ||\n sync.withdrawalLandedFeeLamports > 0 ||\n sync.withdrawalCanceledLamports > 0 ||\n sync.withdrawalNetworkFeeLossLamports > 0 ||\n sync.withdrawalTxHashes.length > 0\n );\n}\n\nfunction resolveRedeemablePrincipalLamports(\n sync: LpPositionView[\"actorSync\"],\n legacyAvailableLamports: number,\n actorRedeemablePrincipalLamports: number,\n actorRedeemableFeeLamports: number,\n): number {\n if (sync?.redeemableProjectionAvailable !== true) return legacyAvailableLamports;\n if (legacyAvailableLamports <= 0) return actorRedeemablePrincipalLamports;\n if (actorRedeemablePrincipalLamports >= legacyAvailableLamports || hasActorSyncLpActivity(sync)) {\n return actorRedeemablePrincipalLamports;\n }\n return Math.max(\n actorRedeemablePrincipalLamports,\n legacyAvailableLamports - actorRedeemableFeeLamports,\n );\n}\n\nfunction hasActorRedeemableProjection(sync: LpPositionView[\"actorSync\"]): boolean {\n return sync?.redeemableProjectionAvailable === true;\n}\n\nfunction validateExplicitWithdrawalInput(args: WithdrawPositionArgs): void {\n if (args.depositPrincipalLamports === undefined && args.earnedFeeLamports === undefined) return;\n validateLpWithdrawalPlan({\n destinationAddresses: args.destinationAddresses,\n depositPrincipalLamports: args.depositPrincipalLamports ?? 0,\n earnedFeeLamports: args.earnedFeeLamports ?? 0,\n allowManyToOne: args.allowManyToOne,\n sourceCount: args.destinationAddresses.length,\n });\n}\n\nfunction validateWithdrawalDestinations(args: WithdrawPositionArgs): void {\n validateLpWithdrawalPlan({\n destinationAddresses: args.destinationAddresses,\n depositPrincipalLamports: 1,\n earnedFeeLamports: 0,\n allowManyToOne: true,\n });\n}\n\nfunction resolveWithdrawalRecord({\n state,\n positionId,\n execution,\n options,\n}: {\n readonly state: LpLifecycleState;\n readonly positionId: string;\n readonly execution: WithdrawalExecution;\n readonly options: WaitForWithdrawalConfirmationOptions;\n}): LpWithdrawalRecord {\n const record = state.redemptions.get(execution.withdrawalId) ?? options.redemptionRecord;\n if (record === undefined) throw new Error(WITHDRAWAL_MISSING_RECORD_MESSAGE);\n if (record.lpPositionId !== positionId || record.redemptionId !== execution.withdrawalId) {\n throw new PolicyValidationError(\"INVALID_REDEMPTION_PLAN\", WITHDRAWAL_RECORD_MISMATCH_MESSAGE);\n }\n return {\n ...record,\n destinationAddresses: [...record.destinationAddresses],\n txSignatures: [...record.txSignatures],\n txSignatureBaseline: [...record.txSignatureBaseline],\n landedFeeBaselineLamports: record.landedFeeBaselineLamports ?? 0,\n };\n}\n\nfunction lpWithdrawalSourceCountForClaim(\n position: LpPositionView,\n claim: {\n readonly depositPrincipalLamports: number;\n readonly earnedFeeLamports: number;\n readonly allowManyToOne?: boolean;\n },\n): number {\n let remainingPrincipalLamports = claim.depositPrincipalLamports;\n let principalSourceCount = 0;\n const principalCandidates = [...position.shards]\n .filter((shard) => shard.status === \"AVAILABLE\" && shard.amountLamports > 0)\n .sort((left, right) => left.shardId.localeCompare(right.shardId));\n for (const shard of principalCandidates) {\n if (remainingPrincipalLamports <= 0) break;\n principalSourceCount += 1;\n remainingPrincipalLamports -= shard.amountLamports;\n }\n const actorRedeemablePrincipalLamports = position.actorSync?.redeemablePrincipalLamports ?? 0;\n const actorRedeemablePrincipalSourceCount =\n position.actorSync?.redeemablePrincipalSourceCount ?? 0;\n if (\n claim.depositPrincipalLamports > 0 &&\n position.actorSync?.redeemableProjectionAvailable === true &&\n actorRedeemablePrincipalLamports >= claim.depositPrincipalLamports &&\n actorRedeemablePrincipalSourceCount > 0\n ) {\n principalSourceCount = actorRedeemablePrincipalSourceCount;\n }\n const observedEarnedFeeSourceCount =\n position.actorSync?.redeemableProjectionAvailable === true\n ? (position.actorSync.redeemableFeeSourceCount ?? 0)\n : position.actorSync?.redeemableFeeSourceCount ||\n position.actorSync?.reimbursementDueSourceCount ||\n 0;\n if (\n claim.earnedFeeLamports > 0 &&\n observedEarnedFeeSourceCount < 1 &&\n claim.allowManyToOne !== true\n ) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n FEE_SOURCE_COUNT_UNAVAILABLE_MESSAGE,\n );\n }\n const earnedFeeSourceCount =\n claim.earnedFeeLamports > 0 ? Math.max(1, observedEarnedFeeSourceCount) : 0;\n return principalSourceCount + earnedFeeSourceCount;\n}\n\nfunction buildLpRedemptionRecord({\n execution,\n position,\n destinationAddresses,\n acceptedLamports,\n requestedTargetLamports,\n landedBaselineLamports,\n landedFeeBaselineLamports,\n txSignatureBaseline,\n nowMs,\n}: {\n readonly execution: LpWithdrawalExecutionView;\n readonly position: LpPositionView;\n readonly destinationAddresses: readonly string[];\n readonly acceptedLamports: number;\n readonly requestedTargetLamports: number;\n readonly landedBaselineLamports: number;\n readonly landedFeeBaselineLamports: number;\n readonly txSignatureBaseline: readonly string[];\n readonly nowMs: number;\n}): LpWithdrawalRecord {\n return {\n redemptionId: execution.withdrawalId,\n lpPositionId: position.id,\n requestedAt: nowMs,\n status: \"pending\",\n destinationAddresses: [...destinationAddresses],\n acceptedLamports,\n requestedTargetLamports,\n landedBaselineLamports,\n landedFeeBaselineLamports,\n redeemedLamports: 0,\n txSignatures: [...execution.txSignatures],\n txSignatureBaseline: [...txSignatureBaseline],\n };\n}\n\nfunction reconcileLpRedemptionFromActorSync(\n record: LpWithdrawalRecord,\n position: LpPositionView,\n): LpWithdrawalRecord {\n const sync = position.actorSync;\n if (sync === undefined) return record;\n const history = sync.redemptionHistory?.find(\n (candidate) => candidate.redemptionId === record.redemptionId,\n );\n if (history !== undefined) {\n return reconcileLpRedemptionFromHistory(record, history);\n }\n const resolvedLamports =\n sync.withdrawalLandedLamports +\n sync.withdrawalLandedFeeLamports +\n sync.withdrawalCanceledLamports +\n sync.withdrawalNetworkFeeLossLamports;\n const settled =\n sync.withdrawalRequestedLamports >= record.requestedTargetLamports &&\n sync.withdrawalRequestedLamports <= resolvedLamports;\n const redeemedLamports = Math.max(\n sync.withdrawalLandedLamports -\n record.landedBaselineLamports +\n sync.withdrawalLandedFeeLamports -\n (record.landedFeeBaselineLamports ?? 0),\n 0,\n );\n const baselineSignatures = new Set(record.txSignatureBaseline);\n const txSignatures = sync.withdrawalTxHashes.filter(\n (signature) => !baselineSignatures.has(signature),\n );\n if (!settled) return { ...record, redeemedLamports, txSignatures };\n if (redeemedLamports <= 0) {\n return {\n ...record,\n status: \"failed\",\n redeemedLamports,\n txSignatures,\n error: WITHDRAWAL_NO_LAMPORTS_MESSAGE,\n };\n }\n return { ...record, status: \"confirmed\", redeemedLamports, txSignatures };\n}\n\nfunction reconcileLpRedemptionFromHistory(\n record: LpWithdrawalRecord,\n history: LpRedemptionHistoryView,\n): LpWithdrawalRecord {\n const observedStateVersion = record.coordinatorStateVersion ?? 0;\n if (history.stateVersion < observedStateVersion) return record;\n if (\n (record.acceptedLamports !== undefined &&\n history.acceptedLamports !== record.acceptedLamports) ||\n (history.detailsTruncated !== true &&\n !sameStringList(history.destinationAddresses, record.destinationAddresses))\n ) {\n return {\n ...record,\n status: \"failed\",\n coordinatorStateVersion: Math.max(observedStateVersion, history.stateVersion),\n error: WITHDRAWAL_HISTORY_MISMATCH_MESSAGE,\n };\n }\n const txSignatures = uniqueStrings([...record.txSignatures, ...history.txSignatures]);\n const base = {\n ...record,\n coordinatorStateVersion: history.stateVersion,\n redeemedLamports: history.landedLamports,\n txSignatures,\n destinationCount: history.destinationCount,\n txSignatureCount: history.txSignatureCount,\n detailsTruncated: history.detailsTruncated,\n error: undefined,\n };\n if (history.state === \"confirmed\") {\n return history.landedLamports > 0\n ? { ...base, status: \"confirmed\" }\n : { ...base, status: \"failed\", error: WITHDRAWAL_NO_LAMPORTS_MESSAGE };\n }\n if (history.state === \"rejected\") {\n return {\n ...base,\n status: \"failed\",\n error: WITHDRAWAL_NO_LAMPORTS_MESSAGE,\n };\n }\n return {\n ...base,\n status: record.status === \"reconciling\" ? \"reconciling\" : \"pending\",\n };\n}\n\nfunction hydrateLpRedemptionsFromPosition(state: LpLifecycleState, position: LpPositionView): void {\n for (const history of position.actorSync?.redemptionHistory ?? []) {\n const existing = state.redemptions.get(history.redemptionId);\n if (existing === undefined) {\n state.redemptions.set(history.redemptionId, lpWithdrawalRecordFromHistory(position, history));\n continue;\n }\n state.redemptions.set(\n history.redemptionId,\n reconcileLpRedemptionFromHistory(existing, history),\n );\n }\n}\n\nfunction lpWithdrawalRecordFromHistory(\n position: LpPositionView,\n history: LpRedemptionHistoryView,\n): LpWithdrawalRecord {\n const record: LpWithdrawalRecord = {\n redemptionId: history.redemptionId,\n lpPositionId: position.id,\n requestedAt: history.createdAtMs,\n status: \"pending\",\n destinationAddresses: [...history.destinationAddresses],\n acceptedLamports: history.acceptedLamports,\n requestedTargetLamports: history.acceptedLamports,\n landedBaselineLamports: 0,\n landedFeeBaselineLamports: 0,\n redeemedLamports: history.landedLamports,\n txSignatures: [...history.txSignatures],\n txSignatureBaseline: [],\n coordinatorStateVersion: history.stateVersion,\n destinationCount: history.destinationCount,\n txSignatureCount: history.txSignatureCount,\n detailsTruncated: history.detailsTruncated,\n };\n return reconcileLpRedemptionFromHistory(record, history);\n}\n\nfunction sameStringList(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction uniqueStrings(values: readonly string[]): string[] {\n return Array.from(new Set(values));\n}\n\nfunction isLpDkgActiveSessionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.includes(\"LP DKG session already active for position index\")\n );\n}\n\nfunction isLpDkgIndexDriftError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n return (\n (error.message.includes(\"LP DKG index\") &&\n error.message.includes(\"already exists for position\")) ||\n error.message.includes(\"LP DKG expected index\")\n );\n}\n\nfunction clonePosition(position: LpPositionView): LpPositionView {\n return {\n ...position,\n shards: position.shards.map((shard) => ({ ...shard })),\n actorSync:\n position.actorSync === undefined\n ? undefined\n : {\n ...position.actorSync,\n redemptionHistory: position.actorSync.redemptionHistory?.map((history) => ({\n ...history,\n destinationAddresses: [...history.destinationAddresses],\n txSignatures: [...history.txSignatures],\n })),\n },\n };\n}\n\nfunction generateId(prefix: string): string {\n return `${prefix}_${Array.from(randomBytes(8))\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\nfunction randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n\nfunction throwIfTopUpWaitAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return;\n throw new DOMException(\"LP top-up wait aborted\", \"AbortError\");\n}\n\nfunction defaultSleep(delayMs: number): Promise<void> {\n return new Promise((resolve) => {\n globalThis.setTimeout(resolve, delayMs);\n });\n}\n","/**\n * `@invisible-labs/sdk/lp` - liquidity-provider lifecycle (spec section 4.4).\n *\n * The high-level lifecycle functions own LP position auth, DKG completion,\n * initial funding selection, refill, withdrawal, and actor-sync confirmation.\n * Importing this module must not pull in `/user`, `/stats`, or `/events`.\n */\n\nimport type { Session } from \"../core/session.js\";\nimport { publicKey } from \"../core/brands.js\";\nimport { assertAttested } from \"../session/guards.js\";\nimport {\n defaultLpLifecycleClient,\n type CompleteDkgBatchOptions,\n type CreatePositionArgs,\n type CreatePositionResult,\n type InitialFundingPlan,\n type LpTopUpRequest,\n type RefillArgs,\n type WaitForTopUpOptions,\n type WaitForWithdrawalConfirmationOptions,\n type WithdrawalConfirmation,\n type WithdrawalExecution,\n type WithdrawPositionArgs,\n type WithdrawPositionResult,\n} from \"./lifecycle.js\";\n\nexport { createLpCoordinatorClient, LP_COMMAND_REQUEST_TIMEOUT_MS } from \"./coordinatorClient.js\";\nexport { createLpDkgBatch, type CreateLpDkgBatchInput, type LpDkgProgress } from \"./dkgBatch.js\";\nexport {\n createLpLifecycleClient,\n defaultLpLifecycleClient,\n isLpPositionAuthMissingError,\n isLpRedemptionReconcilingError,\n LP_MISSING_POSITION_CODE_MESSAGE,\n LP_REDEMPTION_RECONCILING_MESSAGE,\n type CompleteDkgBatchOptions,\n type CreatePositionArgs,\n type CreatePositionResult,\n type InitialFundingPlan,\n type LpLifecycleClient,\n type LpLifecycleDkgProgress,\n type LpLifecycleRuntime,\n type LpTopUpRequest,\n type LpWithdrawalRecord,\n type RefillArgs,\n type WaitForTopUpOptions,\n type WaitForWithdrawalConfirmationOptions,\n type WithdrawalConfirmation,\n type WithdrawalExecution,\n type WithdrawPositionArgs,\n type WithdrawPositionResult,\n} from \"./lifecycle.js\";\nexport {\n bytesToHex,\n deriveLpPositionCodeAuth,\n generateLpPositionCode,\n normalizeLpPositionCode,\n signLpCommandBytes,\n type LpPositionCode,\n type LpPositionCodeAuth,\n} from \"./positionCode.js\";\nexport type {\n FinalizeLpDkgBatchInput,\n FundingConfirmationInput,\n LpActorSyncView,\n LpCoordinatorClient,\n LpDkgClient,\n LpInventoryShard,\n LpRedemptionHistoryView,\n LpPositionView,\n LpWithdrawalExecutionView,\n OpenLpPositionInput,\n RefillLpPositionInput,\n SourceLiquidityUse,\n} from \"./types.js\";\n\nexport function createPosition(\n session: Session,\n args: CreatePositionArgs = {},\n): Promise<CreatePositionResult> {\n return defaultLpLifecycleClient(session).createPosition(args);\n}\n\nexport function recoverPosition(\n session: Session,\n args: { readonly code: string },\n): Promise<import(\"./types.js\").LpPositionView> {\n return defaultLpLifecycleClient(session).recoverPosition(args);\n}\n\nexport function confirmPositionCodeSaved(session: Session, positionId: string): void {\n defaultLpLifecycleClient(session).confirmPositionCodeSaved(positionId);\n}\n\nexport async function completeDkgBatch(\n session: Session,\n positionId: string,\n opts: CompleteDkgBatchOptions = {},\n): Promise<import(\"./types.js\").LpPositionView> {\n return await defaultLpLifecycleClient(session).completeDkgBatch(positionId, opts);\n}\n\nexport function refreshPosition(\n session: Session,\n positionId: string,\n): Promise<import(\"./types.js\").LpPositionView> {\n return defaultLpLifecycleClient(session).refreshPosition(positionId);\n}\n\nexport function refill(\n session: Session,\n positionId: string,\n args: RefillArgs = {},\n): Promise<import(\"./types.js\").LpPositionView> {\n return defaultLpLifecycleClient(session).refill(positionId, args);\n}\n\nexport function prepareInitialFunding(\n session: Session,\n positionId: string,\n): Promise<InitialFundingPlan | null> {\n return defaultLpLifecycleClient(session).prepareInitialFunding(positionId);\n}\n\nexport function prepareTopUp(session: Session, positionId: string): Promise<LpTopUpRequest> {\n return defaultLpLifecycleClient(session).prepareTopUp(positionId);\n}\n\nexport function waitForTopUp(\n session: Session,\n topUpId: string,\n options: WaitForTopUpOptions = {},\n): Promise<LpTopUpRequest> {\n return defaultLpLifecycleClient(session).waitForTopUp(topUpId, options);\n}\n\nexport function reconcileFunding(\n session: Session,\n positionId: string,\n): Promise<import(\"./types.js\").LpPositionView> {\n return defaultLpLifecycleClient(session).reconcileFunding(positionId);\n}\n\nexport function withdrawPosition(\n session: Session,\n positionId: string,\n args: WithdrawPositionArgs,\n): Promise<WithdrawPositionResult> {\n return defaultLpLifecycleClient(session).withdrawPosition(positionId, args);\n}\n\nexport function waitForWithdrawalConfirmation(\n session: Session,\n positionId: string,\n execution: WithdrawalExecution,\n options: WaitForWithdrawalConfirmationOptions = {},\n): Promise<WithdrawalConfirmation> {\n return defaultLpLifecycleClient(session).waitForWithdrawalConfirmation(\n positionId,\n execution,\n options,\n );\n}\n\n/**\n * LP fee withdrawal is coordinator-pending. The SDK validates the local input\n * and returns a typed `VERSION_NOT_SUPPORTED` routing error until advertised.\n */\nexport async function withdrawFees(\n session: Session,\n positionId: string,\n args: { readonly destination: string },\n): Promise<never> {\n publicKey(args.destination);\n assertAttested(session);\n return await defaultLpLifecycleClient(session).withdrawFees(positionId, args);\n}\n\nexport function listPositions(session: Session): Promise<import(\"./types.js\").LpPositionView[]> {\n return defaultLpLifecycleClient(session).listPositions();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/lp/positionCode.ts","../src/lp/withdrawalValidation.ts","../src/lp/coordinatorClient.ts","../src/lp/dkgBatch.ts","../src/lp/lifecycle.ts","../src/lp/index.ts"],"names":["lpPositionId","secretHex","publicKey","encoder","request","addresses","abortDkgSessions","LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS","sleep","refreshPosition","completeDkgBatch","execution","redemption","randomBytes","prepareTopUp","reconcileFunding"],"mappings":";;;;;;;;AAeA,IAAM,kBAAA,GAAqB,MAAA;AAC3B,IAAM,WAAA,GAAc,MAAA;AACpB,IAAM,iBAAA,GAAoB,EAAA;AAC1B,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAEhC,eAAsB,uBAAuB,YAAA,EAAmD;AAC9F,EAAA,oBAAA,CAAqB,YAAY,CAAA;AACjC,EAAA,MAAM,MAAA,GAAS,IAAI,UAAA,CAAW,EAAE,CAAA;AAChC,EAAA,SAAA,EAAU,CAAE,gBAAgB,MAAM,CAAA;AAClC,EAAA,MAAM,OAAA,GAAU,MAAM,SAAA,EAAU,CAAE,MAAA,CAAO,YAAY,EAAE,IAAA,EAA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AAA,CAAiB,UAAU,CAAA;AACtE;AAEO,SAAS,gBAAA,CACd,OAAA,EACA,UAAA,EACA,IAAA,EACiC;AACjC,EAAA,OAAO,wBAAA,CAAyB,OAAO,CAAA,CAAE,gBAAA,CAAiB,YAAY,IAAI,CAAA;AAC5E;AAEO,SAAS,8BACd,OAAA,EACA,UAAA,EACA,SAAA,EACA,OAAA,GAAgD,EAAC,EAChB;AACjC,EAAA,OAAO,wBAAA,CAAyB,OAAO,CAAA,CAAE,6BAAA;AAAA,IACvC,UAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;AACF;AAMA,eAAsB,YAAA,CACpB,OAAA,EACA,UAAA,EACA,IAAA,EACgB;AAChB,EAAA,SAAA,CAAU,KAAK,WAAW,CAAA;AAC1B,EAAA,cAAA,CAAe,OAAO,CAAA;AACtB,EAAA,OAAO,MAAM,wBAAA,CAAyB,OAAO,CAAA,CAAE,YAAA,CAAa,YAAY,IAAI,CAAA;AAC9E;AAEO,SAAS,cAAc,OAAA,EAAkE;AAC9F,EAAA,OAAO,wBAAA,CAAyB,OAAO,CAAA,CAAE,aAAA,EAAc;AACzD","file":"lp.js","sourcesContent":["import { isValidLpPositionId } from \"@invisible/shared\";\n\ndeclare const lpPositionCodeBrand: unique symbol;\n\nexport type LpPositionCode = string & { readonly [lpPositionCodeBrand]: \"LpPositionCode\" };\n\nexport type LpPositionCodeAuth = {\n readonly code: LpPositionCode;\n readonly lpPositionId: string;\n readonly authPublicKey: Uint8Array;\n readonly authPrivateKeyPkcs8: Uint8Array;\n readonly refillPublicKey: Uint8Array;\n readonly withdrawalCommitment: Uint8Array;\n};\n\nconst LEGACY_CODE_PREFIX = \"ilp1\";\nconst CODE_PREFIX = \"ilp2\";\nconst SECRET_HEX_LENGTH = 64;\nconst encoder = new TextEncoder();\n\nexport async function generateLpPositionCode(lpPositionId: string): Promise<LpPositionCodeAuth> {\n validateLpPositionId(lpPositionId);\n const secret = new Uint8Array(32);\n getCrypto().getRandomValues(secret);\n const keyPair = await getCrypto().subtle.generateKey({ name: \"Ed25519\" }, true, [\n \"sign\",\n \"verify\",\n ]);\n const [privatePkcs8, publicRaw] = await Promise.all([\n getCrypto().subtle.exportKey(\"pkcs8\", keyPair.privateKey),\n getCrypto().subtle.exportKey(\"raw\", keyPair.publicKey),\n ]);\n const code = encodeCode(\n lpPositionId,\n bytesToHex(secret),\n bytesToHex(new Uint8Array(privatePkcs8)),\n bytesToHex(new Uint8Array(publicRaw)),\n );\n secret.fill(0);\n return deriveLpPositionCodeAuth(code);\n}\n\nexport async function deriveLpPositionCodeAuth(input: string): Promise<LpPositionCodeAuth> {\n const code = normalizeLpPositionCode(input);\n const parsed = parseCode(code);\n const secret = hexToBytes(parsed.secretHex);\n try {\n const authPublicKey = parsed.authPublicKeyHex\n ? hexToBytes(parsed.authPublicKeyHex)\n : new Uint8Array();\n const authPrivateKeyPkcs8 = parsed.authPrivateKeyPkcs8Hex\n ? hexToBytes(parsed.authPrivateKeyPkcs8Hex)\n : new Uint8Array();\n if (authPublicKey.length > 0 || authPrivateKeyPkcs8.length > 0) {\n await assertAuthKeyPair(authPrivateKeyPkcs8, authPublicKey);\n }\n const refillPublicKey = await deriveBytes(\n \"invisible-lp-refill-public-key-v0\",\n parsed.lpPositionId,\n secret,\n );\n const withdrawalCommitment = await deriveBytes(\n \"invisible-lp-redemption-commitment-v0\",\n parsed.lpPositionId,\n secret,\n );\n return {\n code,\n lpPositionId: parsed.lpPositionId,\n authPublicKey,\n authPrivateKeyPkcs8,\n refillPublicKey,\n withdrawalCommitment,\n };\n } finally {\n secret.fill(0);\n }\n}\n\nexport function normalizeLpPositionCode(input: string): LpPositionCode {\n return input.trim() as LpPositionCode;\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport async function signLpCommandBytes(\n auth: LpPositionCodeAuth,\n bytes: Uint8Array,\n): Promise<Uint8Array> {\n if (auth.authPrivateKeyPkcs8.length === 0 || auth.authPublicKey.length === 0) {\n throw new Error(\"LP Position Code cannot sign owner commands; create a new ilp2 code\");\n }\n const privateKey = await getCrypto().subtle.importKey(\n \"pkcs8\",\n bufferSource(auth.authPrivateKeyPkcs8),\n { name: \"Ed25519\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(\n await getCrypto().subtle.sign({ name: \"Ed25519\" }, privateKey, bufferSource(bytes)),\n );\n}\n\nfunction encodeCode(\n lpPositionId: string,\n secretHex: string,\n authPrivateKeyPkcs8Hex: string,\n authPublicKeyHex: string,\n): LpPositionCode {\n return `${CODE_PREFIX}:${lpPositionId}:${secretHex}:${authPrivateKeyPkcs8Hex}:${authPublicKeyHex}` as LpPositionCode;\n}\n\nfunction parseCode(code: LpPositionCode): {\n readonly lpPositionId: string;\n readonly secretHex: string;\n readonly authPrivateKeyPkcs8Hex?: string;\n readonly authPublicKeyHex?: string;\n} {\n const parts = code.split(\":\");\n if (parts.length === 3 && parts[0] === LEGACY_CODE_PREFIX) {\n const [, lpPositionId, secretHex] = parts;\n validateLpPositionId(lpPositionId);\n if (!new RegExp(`^[0-9a-fA-F]{${SECRET_HEX_LENGTH}}$`).test(secretHex)) {\n throw new Error(\"LP Position Code secret must be 32 bytes hex\");\n }\n return { lpPositionId, secretHex: secretHex.toLowerCase() };\n }\n if (parts.length !== 5 || parts[0] !== CODE_PREFIX) {\n throw new Error(\"LP Position Code must use the ilp2 format\");\n }\n const [, lpPositionId, secretHex, authPrivateKeyPkcs8Hex, authPublicKeyHex] = parts;\n validateLpPositionId(lpPositionId);\n if (!new RegExp(`^[0-9a-fA-F]{${SECRET_HEX_LENGTH}}$`).test(secretHex)) {\n throw new Error(\"LP Position Code secret must be 32 bytes hex\");\n }\n if (!/^[0-9a-fA-F]+$/.test(authPrivateKeyPkcs8Hex) || authPrivateKeyPkcs8Hex.length < 64) {\n throw new Error(\"LP Position Code auth private key must be pkcs8 hex\");\n }\n if (!new RegExp(`^[0-9a-fA-F]{${SECRET_HEX_LENGTH}}$`).test(authPublicKeyHex)) {\n throw new Error(\"LP Position Code auth public key must be 32 bytes hex\");\n }\n return {\n lpPositionId,\n secretHex: secretHex.toLowerCase(),\n authPrivateKeyPkcs8Hex: authPrivateKeyPkcs8Hex.toLowerCase(),\n authPublicKeyHex: authPublicKeyHex.toLowerCase(),\n };\n}\n\nfunction validateLpPositionId(lpPositionId: string): void {\n if (!isValidLpPositionId(lpPositionId)) {\n throw new Error(\"LP Position Code has an invalid position id\");\n }\n}\n\nasync function deriveBytes(\n domain: string,\n lpPositionId: string,\n secret: Uint8Array,\n): Promise<Uint8Array> {\n const domainBytes = encoder.encode(`${domain}:${lpPositionId}:`);\n const material = new Uint8Array(domainBytes.length + secret.length);\n material.set(domainBytes);\n material.set(secret, domainBytes.length);\n const digest = await getCrypto().subtle.digest(\"SHA-256\", material);\n material.fill(0);\n return new Uint8Array(digest);\n}\n\nasync function assertAuthKeyPair(privatePkcs8: Uint8Array, publicRaw: Uint8Array): Promise<void> {\n if (publicRaw.length !== 32) {\n throw new Error(\"LP Position Code auth public key must be 32 bytes\");\n }\n const [privateKey, publicKey] = await Promise.all([\n getCrypto().subtle.importKey(\"pkcs8\", bufferSource(privatePkcs8), { name: \"Ed25519\" }, false, [\n \"sign\",\n ]),\n getCrypto().subtle.importKey(\"raw\", bufferSource(publicRaw), { name: \"Ed25519\" }, false, [\n \"verify\",\n ]),\n ]);\n const challenge = encoder.encode(\"invisible-lp-auth-self-test\");\n const signature = await getCrypto().subtle.sign({ name: \"Ed25519\" }, privateKey, challenge);\n const ok = await getCrypto().subtle.verify({ name: \"Ed25519\" }, publicKey, signature, challenge);\n if (!ok) {\n throw new Error(\"LP Position Code auth key pair is invalid\");\n }\n}\n\nfunction bufferSource(bytes: Uint8Array): ArrayBuffer {\n return new Uint8Array(bytes).buffer;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction getCrypto(): Crypto {\n if (globalThis.crypto === undefined || globalThis.crypto.subtle === undefined) {\n throw new Error(\"Web Crypto is required for LP Position Code handling\");\n }\n return globalThis.crypto;\n}\n","import { lamports, publicKey } from \"../core/brands.js\";\nimport { PolicyValidationError } from \"../core/errors.js\";\n\nexport interface LpWithdrawalPlanValidationInput {\n readonly depositPrincipalLamports: number;\n readonly earnedFeeLamports: number;\n readonly destinationAddresses: readonly string[];\n readonly allowManyToOne?: boolean;\n readonly sourceCount?: number;\n}\n\nconst SINGLE_DESTINATION_WITHDRAWAL_MESSAGE =\n \"single-destination withdrawal is privacy-degrading; pass allowManyToOne: true to acknowledge\";\nconst DESTINATION_SOURCE_COUNT_MESSAGE =\n \"LP withdrawal requires one destination per withdrawable source unless allowManyToOne is true\";\nconst SOURCE_COUNT_MESSAGE = \"LP withdrawal source count must be a positive integer\";\n\nexport function validateLpWithdrawalClaim(\n input: Pick<LpWithdrawalPlanValidationInput, \"depositPrincipalLamports\" | \"earnedFeeLamports\">,\n): void {\n const { depositPrincipalLamports, earnedFeeLamports } = input;\n lamports(depositPrincipalLamports);\n lamports(earnedFeeLamports);\n if (depositPrincipalLamports === 0 && earnedFeeLamports === 0) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n \"LP withdrawal requires a non-zero principal or earned-fee claim\",\n );\n }\n}\n\nexport function validateLpWithdrawalPlan(input: LpWithdrawalPlanValidationInput): void {\n const {\n depositPrincipalLamports,\n earnedFeeLamports,\n destinationAddresses,\n allowManyToOne,\n sourceCount,\n } = input;\n validateLpWithdrawalClaim({ depositPrincipalLamports, earnedFeeLamports });\n validateDestinationAddresses(destinationAddresses);\n if (sourceCount !== undefined && (!Number.isInteger(sourceCount) || sourceCount < 1)) {\n throw new PolicyValidationError(\"INVALID_WITHDRAWAL_PLAN\", SOURCE_COUNT_MESSAGE);\n }\n if (\n sourceCount !== undefined &&\n allowManyToOne !== true &&\n destinationAddresses.length !== sourceCount\n ) {\n throw new PolicyValidationError(\"INVALID_WITHDRAWAL_PLAN\", DESTINATION_SOURCE_COUNT_MESSAGE);\n }\n if (destinationAddresses.length === 1 && sourceCount !== 1 && allowManyToOne !== true) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n SINGLE_DESTINATION_WITHDRAWAL_MESSAGE,\n );\n }\n}\n\nfunction validateDestinationAddresses(destinationAddresses: readonly string[]): void {\n if (destinationAddresses.length === 0) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n \"at least one destination address is required\",\n );\n }\n const seen = new Set<string>();\n for (const address of destinationAddresses) {\n publicKey(address);\n if (seen.has(address)) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n `duplicate withdrawal destination: ${address}`,\n );\n }\n seen.add(address);\n }\n}\n","import type { Session } from \"../core/session.js\";\nimport { CommandError, PolicyValidationError, TransportError } from \"../core/errors.js\";\nimport { getSessionState } from \"../session/state.js\";\nimport {\n CoordinatorMessageType,\n requestEnvelope,\n type Envelope,\n} from \"../coordinator/protocolClient.js\";\nimport { bytesToHex, signLpCommandBytes, type LpPositionCodeAuth } from \"./positionCode.js\";\nimport { validateLpWithdrawalPlan } from \"./withdrawalValidation.js\";\nimport type {\n FinalizeLpDkgBatchInput,\n FundingConfirmationInput,\n LpActorSyncView,\n LpCoordinatorClient,\n LpInventoryShard,\n LpPositionRequestOptions,\n LpPositionView,\n LpRedemptionHistoryView,\n LpTopUpRequest,\n LpWithdrawalExecutionView,\n LpWithdrawalMode,\n OpenLpPositionInput,\n RefillLpPositionInput,\n} from \"./types.js\";\n\ntype LpCommandAction =\n | \"dkg_init\"\n | \"dkg_round1\"\n | \"dkg_round2\"\n | \"dkg_abort\"\n | \"position_open\"\n | \"position_get\"\n | \"dkg_finalize\"\n | \"refill\"\n | \"reconcile_funding\"\n | \"funding_plan\"\n | \"funding_confirmation\"\n | \"make_available\"\n | \"withdraw_request\"\n | \"prepare_top_up\"\n | \"top_up_status\";\n\ntype LpCommandBody = { readonly case: string; readonly value: Record<string, unknown> };\n\ntype ProtocolLpModule = {\n readonly encodeLpCommandForSigning: (command: unknown) => Uint8Array;\n readonly lpSignedCommandEnvelope: (\n command: unknown,\n signature: Uint8Array,\n ) => { readonly type: CoordinatorMessageType; readonly payload: Record<string, unknown> };\n readonly asLpCommandResponsePayload: (envelope: Envelope) => LpCommandResponsePayload;\n};\n\ntype LpCommandResponsePayload =\n | { readonly case: \"dkgInit\"; readonly value: { readonly session_id: string } }\n | {\n readonly case: \"dkgRound1\";\n readonly value: { readonly package: Uint8Array; readonly round2_for_lp: Uint8Array };\n }\n | {\n readonly case: \"dkgRound2\";\n readonly value: {\n readonly address: string;\n readonly joint_pubkey: Uint8Array;\n readonly shard_id: string;\n readonly index: number;\n };\n }\n | {\n readonly case: \"dkgAbort\";\n readonly value: { readonly aborted_session_count: number };\n }\n | { readonly case: \"position\"; readonly value: LpPositionViewPayload }\n | { readonly case: \"shards\"; readonly value: LpShardViewPayload[] }\n | { readonly case: \"shard\"; readonly value: LpShardViewPayload }\n | { readonly case: \"topUpRequest\"; readonly value: LpTopUpRequestPayload }\n | {\n readonly case: \"withdrawalExecution\";\n readonly value: {\n readonly withdrawal_id: string;\n readonly tx_signatures: string[];\n readonly accepted_lamports: number;\n readonly accepted_deposit_principal_lamports: number;\n readonly accepted_earned_fee_lamports: number;\n };\n };\n\ntype LpPositionViewPayload = {\n readonly lp_position_id: string;\n readonly status: LpPositionView[\"status\"];\n readonly target_shard_count: number;\n readonly auth_public_key: Uint8Array;\n readonly refill_public_key: Uint8Array;\n readonly redemption_commitment: Uint8Array;\n readonly committed_lamports: number;\n readonly earned_lamports: number;\n readonly refill_threshold: number;\n readonly shards: LpShardViewPayload[];\n readonly created_at_ms: number;\n readonly actor_sync?: {\n readonly lp_position_id: string;\n readonly status: LpActorSyncView[\"status\"];\n readonly source_liquidity_use: LpActorSyncView[\"sourceLiquidityUse\"];\n readonly redeemable_principal_lamports?: number;\n readonly redeemable_fee_lamports?: number;\n readonly lifetime_earned_lamports?: number;\n readonly redeemable_principal_source_count?: number;\n readonly redeemable_fee_source_count?: number;\n readonly redeemable_source_count?: number;\n readonly pending_reservation_count: number;\n readonly reserved_payout_lamports: number;\n readonly estimated_network_fee_lamports: number;\n readonly reimbursement_due_count: number;\n readonly reimbursement_due_source_count: number;\n readonly reimbursement_due_payout_lamports: number;\n readonly reimbursement_due_network_fee_lamports: number;\n readonly withdrawal_requested_lamports: number;\n readonly withdrawal_landed_lamports: number;\n readonly withdrawal_landed_fee_lamports: number;\n readonly withdrawal_canceled_lamports: number;\n readonly withdrawal_network_fee_loss_lamports: number;\n readonly withdrawal_tx_hashes: string[];\n readonly redemption_history?: LpRedemptionHistoryPayload[];\n readonly redemption_history_has_more?: boolean;\n readonly redemption_history_next_cursor?: string;\n readonly state_version: number;\n readonly updated_at_ms: number;\n };\n};\n\ntype LpRedemptionHistoryPayload = {\n readonly redemption_id: string;\n readonly state: LpRedemptionHistoryView[\"state\"];\n readonly withdrawal_mode?: LpWithdrawalMode;\n readonly accepted_lamports: number;\n readonly accepted_deposit_principal_lamports: number;\n readonly accepted_earned_fee_lamports: number;\n readonly landed_lamports: number;\n readonly landed_deposit_principal_lamports: number;\n readonly landed_earned_fee_lamports: number;\n readonly canceled_lamports: number;\n readonly canceled_deposit_principal_lamports: number;\n readonly canceled_earned_fee_lamports: number;\n readonly network_fee_lamports: number;\n readonly network_fee_loss_lamports: number;\n readonly failed_attempts: number;\n readonly destination_addresses: string[];\n readonly destination_count: number;\n readonly tx_signatures: string[];\n readonly tx_signature_count: number;\n readonly details_truncated: boolean;\n readonly state_version: number;\n readonly created_at_ms: number;\n readonly updated_at_ms: number;\n};\n\ntype LpShardViewPayload = {\n readonly lp_position_id: string;\n readonly shard_id: string;\n readonly index: number;\n readonly address: string;\n readonly amount_lamports: number;\n readonly required_lamports?: number;\n readonly status:\n | \"pregenerated\"\n | \"funding_queued\"\n | \"funded\"\n | \"cooling\"\n | \"available\"\n | \"reserved\"\n | \"retired\"\n | \"redeemed\";\n readonly funding_tx_signature?: string;\n readonly payout_tx_signature?: string;\n readonly cooling_until_ms?: number;\n};\n\ntype LpTopUpRequestPayload = {\n readonly top_up_id: string;\n readonly lp_position_id: string;\n readonly deposit_address: string;\n readonly expires_at_ms: number;\n readonly status: LpTopUpRequest[\"status\"];\n};\n\nconst COMMAND_TTL_MS = 30_000;\nexport const LP_COMMAND_REQUEST_TIMEOUT_MS = 120_000;\nexport const LP_DKG_ABORT_REQUEST_TIMEOUT_MS = 10_000;\nconst encoder = new TextEncoder();\nlet protocolPromise: Promise<ProtocolLpModule> | null = null;\n\nexport function createLpCoordinatorClient(session: Session): LpCoordinatorClient {\n return {\n initDkg(input, auth) {\n return initDkg(session, input, auth);\n },\n abortDkgSessions(lpPositionId, auth) {\n return abortDkgSessions(session, lpPositionId, auth);\n },\n dkgRound1(input, auth) {\n return dkgRound1(session, input, auth);\n },\n dkgRound2(input, auth) {\n return dkgRound2(session, input, auth);\n },\n openPosition(input, auth) {\n return openPosition(session, input, auth);\n },\n getPosition(lpPositionId, auth, options) {\n return getPosition(session, lpPositionId, auth, options);\n },\n finalizeDkgBatch(input, auth) {\n return finalizeDkgBatch(session, input, auth);\n },\n refillPosition(input, auth) {\n return refillPosition(session, input, auth);\n },\n reconcileFunding(lpPositionId, auth) {\n return reconcileFunding(session, lpPositionId, auth);\n },\n planFunding(input, auth) {\n return planFunding(session, input, auth);\n },\n confirmFunding(input, auth) {\n return confirmFunding(session, input, auth);\n },\n prepareTopUp(lpPositionId, auth) {\n return prepareTopUp(session, lpPositionId, auth);\n },\n getTopUpStatus(input, auth) {\n return getTopUpStatus(session, input, auth);\n },\n makeAvailable(input, auth) {\n return makeAvailable(session, input, auth);\n },\n executeWithdrawal(input, auth) {\n return executeWithdrawal(session, input, auth);\n },\n };\n}\n\nasync function initDkg(\n session: Session,\n input: { lpPositionId: string; index: number },\n auth: LpPositionCodeAuth,\n): Promise<{ sessionId: string }> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"dkg_init\", {\n case: \"dkgInit\",\n value: { index: input.index },\n });\n if (response.case !== \"dkgInit\") throw new Error(\"Unexpected LP DKG init response\");\n return { sessionId: response.value.session_id };\n}\n\nasync function abortDkgSessions(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n): Promise<{ abortedSessionCount: number }> {\n const response = await requestForPosition(\n session,\n lpPositionId,\n auth,\n \"dkg_abort\",\n {\n case: \"dkgAbort\",\n value: {},\n },\n { timeoutMs: LP_DKG_ABORT_REQUEST_TIMEOUT_MS },\n );\n if (response.case !== \"dkgAbort\") throw new Error(\"Unexpected LP DKG abort response\");\n return { abortedSessionCount: response.value.aborted_session_count };\n}\n\nasync function dkgRound1(\n session: Session,\n input: { sessionId: string; package: number[] },\n auth: LpPositionCodeAuth,\n): Promise<{ package: Uint8Array; round2ForLp: Uint8Array }> {\n const response = await request(session, auth, \"dkg_round1\", {\n case: \"dkgRound1\",\n value: {\n session_id: input.sessionId,\n package: Uint8Array.from(input.package),\n },\n });\n if (response.case !== \"dkgRound1\") throw new Error(\"Unexpected LP DKG round1 response\");\n return {\n package: response.value.package,\n round2ForLp: response.value.round2_for_lp,\n };\n}\n\nasync function dkgRound2(\n session: Session,\n input: { sessionId: string; package: number[]; delegatedShare: number[] },\n auth: LpPositionCodeAuth,\n): Promise<{ address: string; jointPubkey: Uint8Array; shardId: string; index: number }> {\n const response = await request(session, auth, \"dkg_round2\", {\n case: \"dkgRound2\",\n value: {\n session_id: input.sessionId,\n package: Uint8Array.from(input.package),\n delegated_share: Uint8Array.from(input.delegatedShare),\n },\n });\n if (response.case !== \"dkgRound2\") throw new Error(\"Unexpected LP DKG round2 response\");\n return {\n address: response.value.address,\n jointPubkey: response.value.joint_pubkey,\n shardId: response.value.shard_id,\n index: response.value.index,\n };\n}\n\nasync function openPosition(\n session: Session,\n input: OpenLpPositionInput,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"position_open\", {\n case: \"positionOpen\",\n value: {\n auth_public_key: Uint8Array.from(input.authPublicKey),\n refill_public_key: Uint8Array.from(input.refillPublicKey),\n redemption_commitment: Uint8Array.from(input.withdrawalCommitment),\n committed_lamports: input.committedLamports,\n shard_count: input.shardCount,\n shard_amount_lamports: input.shardAmountLamports,\n refill_threshold: input.refillThreshold,\n addresses: input.addresses,\n created_at_ms: input.createdAtMs,\n },\n });\n return expectPosition(response);\n}\n\nasync function getPosition(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n options: LpPositionRequestOptions = {},\n): Promise<LpPositionView> {\n let cursor: string | undefined;\n let position: LpPositionView | undefined;\n const seenCursors = new Set<string>();\n for (;;) {\n const pageOptions = lpPositionPageRequestOptions(options);\n const response = await requestForPosition(\n session,\n lpPositionId,\n auth,\n \"position_get\",\n {\n case: \"positionGet\",\n value: cursor === undefined ? {} : { redemption_history_cursor: cursor },\n },\n pageOptions,\n );\n const page = expectPosition(response);\n const mergedPosition =\n position === undefined ? page : mergePositionHistoryPages(position, page);\n position = mergedPosition;\n const actorSync = page.actorSync;\n if (actorSync?.redemptionHistoryHasMore !== true) return mergedPosition;\n const nextCursor = actorSync.redemptionHistoryNextCursor;\n if (nextCursor === undefined || seenCursors.has(nextCursor)) {\n throw new CommandError(\n \"REJECTED_STATE\",\n \"coordinator LP actor sync returned an invalid redemption history cursor\",\n );\n }\n seenCursors.add(nextCursor);\n cursor = nextCursor;\n }\n}\n\nfunction lpPositionPageRequestOptions(options: LpPositionRequestOptions): LpPositionRequestOptions {\n if (options.deadlineMs === undefined) return options;\n const remainingMs = options.deadlineMs - Date.now();\n if (remainingMs <= 0) {\n throw new CommandError(\"REJECTED_STALE_JOB\", \"LP position observation deadline elapsed\");\n }\n return {\n deadlineMs: options.deadlineMs,\n signal: options.signal,\n timeoutMs: Math.min(options.timeoutMs ?? LP_COMMAND_REQUEST_TIMEOUT_MS, remainingMs),\n };\n}\n\nasync function finalizeDkgBatch(\n session: Session,\n input: FinalizeLpDkgBatchInput,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"dkg_finalize\", {\n case: \"dkgFinalize\",\n value: {\n start_index: input.startIndex,\n addresses: input.addresses,\n finalized_at_ms: input.finalizedAtMs,\n },\n });\n return expectPosition(response);\n}\n\nasync function refillPosition(\n session: Session,\n input: RefillLpPositionInput,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"refill\", {\n case: \"refill\",\n value: {\n shard_count: input.shardCount,\n shard_amount_lamports: input.shardAmountLamports,\n addresses: input.addresses,\n authorized_at_ms: input.authorizedAtMs,\n },\n });\n return expectPosition(response);\n}\n\nasync function reconcileFunding(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n): Promise<LpPositionView> {\n const response = await requestForPosition(session, lpPositionId, auth, \"reconcile_funding\", {\n case: \"reconcileFunding\",\n value: {},\n });\n return expectPosition(response);\n}\n\nasync function planFunding(\n session: Session,\n input: { lpPositionId: string; shardCount: number; nowMs: number },\n auth: LpPositionCodeAuth,\n): Promise<LpInventoryShard[]> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"funding_plan\", {\n case: \"fundingPlan\",\n value: {\n shard_count: input.shardCount,\n planned_at_ms: input.nowMs,\n },\n });\n if (response.case !== \"shards\") throw new Error(\"Unexpected LP funding plan response\");\n return response.value.map(mapShard);\n}\n\nasync function confirmFunding(\n session: Session,\n input: FundingConfirmationInput,\n auth: LpPositionCodeAuth,\n): Promise<LpInventoryShard> {\n const response = await requestForPosition(\n session,\n input.lpPositionId,\n auth,\n \"funding_confirmation\",\n {\n case: \"fundingConfirmation\",\n value: {\n shard_id: input.shardId,\n amount_lamports: input.amountLamports,\n funding_tx_signature: input.fundingTxSignature,\n },\n },\n );\n if (response.case !== \"shard\") throw new Error(\"Unexpected LP funding confirmation response\");\n return mapShard(response.value);\n}\n\nasync function prepareTopUp(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n): Promise<LpTopUpRequest> {\n const response = await requestForPosition(session, lpPositionId, auth, \"prepare_top_up\", {\n case: \"prepareTopUp\",\n value: {},\n });\n if (response.case !== \"topUpRequest\") throw new Error(\"Unexpected LP top-up response\");\n return mapTopUpRequest(response.value);\n}\n\nasync function getTopUpStatus(\n session: Session,\n input: { lpPositionId: string; topUpId: string },\n auth: LpPositionCodeAuth,\n): Promise<LpTopUpRequest> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"top_up_status\", {\n case: \"topUpStatus\",\n value: { top_up_id: input.topUpId },\n });\n if (response.case !== \"topUpRequest\") throw new Error(\"Unexpected LP top-up response\");\n return mapTopUpRequest(response.value);\n}\n\nasync function makeAvailable(\n session: Session,\n input: { lpPositionId: string; shardId: string },\n auth: LpPositionCodeAuth,\n): Promise<LpInventoryShard> {\n const response = await requestForPosition(session, input.lpPositionId, auth, \"make_available\", {\n case: \"makeAvailable\",\n value: {\n shard_id: input.shardId,\n },\n });\n if (response.case !== \"shard\") throw new Error(\"Unexpected LP availability response\");\n return mapShard(response.value);\n}\n\nasync function executeWithdrawal(\n session: Session,\n input: {\n lpPositionId: string;\n destinationAddresses: string[];\n depositPrincipalLamports: number;\n earnedFeeLamports: number;\n withdrawalMode: LpWithdrawalMode;\n requestedAtMs: number;\n allowManyToOne?: boolean;\n },\n auth: LpPositionCodeAuth,\n): Promise<LpWithdrawalExecutionView> {\n validateLpWithdrawalPlan({\n destinationAddresses: input.destinationAddresses,\n depositPrincipalLamports:\n input.withdrawalMode === \"max_available\" ? 1 : input.depositPrincipalLamports,\n earnedFeeLamports: input.withdrawalMode === \"max_available\" ? 0 : input.earnedFeeLamports,\n // Max mode deliberately does not preview source count. The coordinator\n // owns the accepted split, so local destination validation must not reject\n // a one-destination request based on an unknown current source count.\n allowManyToOne: input.withdrawalMode === \"max_available\" || input.allowManyToOne,\n });\n const response = await requestForPosition(session, input.lpPositionId, auth, \"withdraw_request\", {\n case: \"withdrawRequest\",\n value: {\n destination_addresses: input.destinationAddresses,\n deposit_principal_lamports:\n input.withdrawalMode === \"max_available\" ? 0 : input.depositPrincipalLamports,\n earned_fee_lamports: input.withdrawalMode === \"max_available\" ? 0 : input.earnedFeeLamports,\n withdrawal_mode: input.withdrawalMode,\n requested_at_ms: input.requestedAtMs,\n },\n });\n if (response.case !== \"withdrawalExecution\") {\n throw new Error(\"Unexpected LP withdrawal execution response\");\n }\n const execution = response.value;\n if (\n BigInt(execution.accepted_lamports) !==\n BigInt(execution.accepted_deposit_principal_lamports) +\n BigInt(execution.accepted_earned_fee_lamports)\n ) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n \"Coordinator accepted withdrawal total does not match its principal and fee split\",\n );\n }\n if (\n input.withdrawalMode === \"exact\" &&\n (execution.accepted_deposit_principal_lamports !== input.depositPrincipalLamports ||\n execution.accepted_earned_fee_lamports !== input.earnedFeeLamports)\n ) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n \"Coordinator accepted withdrawal split does not match the signed exact claim\",\n );\n }\n return {\n withdrawalId: execution.withdrawal_id,\n txSignatures: [...execution.tx_signatures],\n acceptedLamports: execution.accepted_lamports,\n acceptedDepositPrincipalLamports: execution.accepted_deposit_principal_lamports,\n acceptedEarnedFeeLamports: execution.accepted_earned_fee_lamports,\n };\n}\n\nfunction request(\n session: Session,\n auth: LpPositionCodeAuth,\n action: LpCommandAction,\n payload: LpCommandBody,\n): Promise<LpCommandResponsePayload> {\n return requestForPosition(session, auth.lpPositionId, auth, action, payload);\n}\n\nasync function requestForPosition(\n session: Session,\n lpPositionId: string,\n auth: LpPositionCodeAuth,\n action: LpCommandAction,\n payload: LpCommandBody,\n options: LpPositionRequestOptions = {},\n): Promise<LpCommandResponsePayload> {\n const timeoutMs = options.timeoutMs ?? LP_COMMAND_REQUEST_TIMEOUT_MS;\n assertAuthMatchesPosition(lpPositionId, auth);\n const protocol = await loadProtocol();\n const state = getSessionState(session);\n const attestation = state.channel?.attestation;\n if (!attestation) {\n throw new TransportError(\"CONNECTION_LOST\", \"LP coordinator attestation is not available\");\n }\n\n const command = {\n lp_position_id: lpPositionId,\n action,\n nonce: randomBytes(32),\n expires_at_ms: Date.now() + Math.min(COMMAND_TTL_MS, timeoutMs),\n coordinator_attestation_hash: await coordinatorAttestationHash(\n attestation.binaryHash,\n attestation.pubkeyHex,\n ),\n payload,\n };\n const signature = await signLpCommandBytes(auth, protocol.encodeLpCommandForSigning(command));\n const { type, payload: envelopePayload } = protocol.lpSignedCommandEnvelope(command, signature);\n const requestOptions = lpPositionPageRequestOptions(options);\n const envelope = await requestEnvelope(session, type, envelopePayload, {\n timeoutMs: requestOptions.timeoutMs ?? LP_COMMAND_REQUEST_TIMEOUT_MS,\n signal: requestOptions.signal,\n });\n return protocol.asLpCommandResponsePayload(envelope);\n}\n\nfunction assertAuthMatchesPosition(lpPositionId: string, auth: LpPositionCodeAuth): void {\n if (lpPositionId === auth.lpPositionId) return;\n throw new PolicyValidationError(\n \"INVALID_POSITION_AUTH\",\n \"LP Position Code does not match the target LP position\",\n );\n}\n\nfunction expectPosition(response: LpCommandResponsePayload): LpPositionView {\n if (response.case !== \"position\") throw new Error(\"Unexpected LP position response\");\n return mapPosition(response.value);\n}\n\nfunction mapPosition(position: LpPositionViewPayload): LpPositionView {\n return {\n id: position.lp_position_id,\n status: position.status,\n targetShardCount: position.target_shard_count,\n authPublicKey: bytesToHex(position.auth_public_key),\n refillPublicKey: bytesToHex(position.refill_public_key),\n withdrawalCommitment: bytesToHex(position.redemption_commitment),\n committedLamports: position.committed_lamports,\n earnedLamports: position.earned_lamports,\n refillThreshold: position.refill_threshold,\n shards: position.shards.map(mapShard),\n createdAt: position.created_at_ms,\n ...(position.actor_sync === undefined\n ? {}\n : { actorSync: mapLpActorSync(position.actor_sync) }),\n };\n}\n\nfunction mapLpActorSync(\n actorSync: NonNullable<LpPositionViewPayload[\"actor_sync\"]>,\n): LpActorSyncView {\n const redeemableBucketValues = [\n actorSync.redeemable_principal_lamports,\n actorSync.redeemable_fee_lamports,\n actorSync.lifetime_earned_lamports,\n actorSync.redeemable_principal_source_count,\n actorSync.redeemable_fee_source_count,\n ];\n const redeemableBucketCount = redeemableBucketValues.filter(\n (value) => value !== undefined,\n ).length;\n if (redeemableBucketCount > 0 && redeemableBucketCount < redeemableBucketValues.length) {\n throw new CommandError(\n \"REJECTED_STATE\",\n \"coordinator LP actor sync redeemable buckets must be all-or-none\",\n );\n }\n const redeemableProjectionAvailable = redeemableBucketCount === redeemableBucketValues.length;\n return {\n lpPositionId: actorSync.lp_position_id,\n status: actorSync.status,\n sourceLiquidityUse: actorSync.source_liquidity_use,\n redeemableProjectionAvailable,\n redeemablePrincipalLamports: actorSync.redeemable_principal_lamports ?? 0,\n redeemableFeeLamports: actorSync.redeemable_fee_lamports ?? 0,\n lifetimeEarnedLamports: actorSync.lifetime_earned_lamports ?? 0,\n redeemablePrincipalSourceCount: actorSync.redeemable_principal_source_count ?? 0,\n redeemableFeeSourceCount: actorSync.redeemable_fee_source_count ?? 0,\n redeemableSourceCount: actorSync.redeemable_source_count,\n pendingReservationCount: actorSync.pending_reservation_count,\n reservedPayoutLamports: actorSync.reserved_payout_lamports,\n estimatedNetworkFeeLamports: actorSync.estimated_network_fee_lamports,\n reimbursementDueCount: actorSync.reimbursement_due_count,\n reimbursementDueSourceCount: actorSync.reimbursement_due_source_count,\n reimbursementDuePayoutLamports: actorSync.reimbursement_due_payout_lamports,\n reimbursementDueNetworkFeeLamports: actorSync.reimbursement_due_network_fee_lamports,\n withdrawalRequestedLamports: actorSync.withdrawal_requested_lamports,\n withdrawalLandedLamports: actorSync.withdrawal_landed_lamports,\n withdrawalLandedFeeLamports: actorSync.withdrawal_landed_fee_lamports,\n withdrawalCanceledLamports: actorSync.withdrawal_canceled_lamports,\n withdrawalNetworkFeeLossLamports: actorSync.withdrawal_network_fee_loss_lamports,\n withdrawalTxHashes: [...actorSync.withdrawal_tx_hashes],\n redemptionHistory: (actorSync.redemption_history ?? []).map(mapLpRedemptionHistory),\n redemptionHistoryHasMore: actorSync.redemption_history_has_more ?? false,\n ...(actorSync.redemption_history_next_cursor === undefined\n ? {}\n : { redemptionHistoryNextCursor: actorSync.redemption_history_next_cursor }),\n stateVersion: actorSync.state_version,\n updatedAtMs: actorSync.updated_at_ms,\n };\n}\n\nfunction mergePositionHistoryPages(first: LpPositionView, next: LpPositionView): LpPositionView {\n if (first.actorSync === undefined) return next;\n if (next.actorSync === undefined) return first;\n const historyByRedemptionId = new Map<string, LpRedemptionHistoryView>();\n for (const history of first.actorSync.redemptionHistory ?? []) {\n historyByRedemptionId.set(history.redemptionId, history);\n }\n for (const history of next.actorSync.redemptionHistory ?? []) {\n historyByRedemptionId.set(history.redemptionId, history);\n }\n return {\n ...first,\n actorSync: {\n ...first.actorSync,\n ...next.actorSync,\n redemptionHistory: [...historyByRedemptionId.values()],\n },\n };\n}\n\nfunction mapLpRedemptionHistory(history: LpRedemptionHistoryPayload): LpRedemptionHistoryView {\n return {\n redemptionId: history.redemption_id,\n state: history.state,\n ...(history.withdrawal_mode === undefined ? {} : { withdrawalMode: history.withdrawal_mode }),\n acceptedLamports: history.accepted_lamports,\n acceptedDepositPrincipalLamports: history.accepted_deposit_principal_lamports,\n acceptedEarnedFeeLamports: history.accepted_earned_fee_lamports,\n landedLamports: history.landed_lamports,\n landedDepositPrincipalLamports: history.landed_deposit_principal_lamports,\n landedEarnedFeeLamports: history.landed_earned_fee_lamports,\n canceledLamports: history.canceled_lamports,\n canceledDepositPrincipalLamports: history.canceled_deposit_principal_lamports,\n canceledEarnedFeeLamports: history.canceled_earned_fee_lamports,\n networkFeeLamports: history.network_fee_lamports,\n networkFeeLossLamports: history.network_fee_loss_lamports,\n failedAttempts: history.failed_attempts,\n destinationAddresses: [...history.destination_addresses],\n destinationCount: history.destination_count,\n txSignatures: [...history.tx_signatures],\n txSignatureCount: history.tx_signature_count,\n detailsTruncated: history.details_truncated,\n stateVersion: history.state_version,\n createdAtMs: history.created_at_ms,\n updatedAtMs: history.updated_at_ms,\n };\n}\n\nfunction mapShard(shard: LpShardViewPayload): LpInventoryShard {\n return {\n kind: \"lp\",\n lpPositionId: shard.lp_position_id,\n shardId: shard.shard_id,\n index: shard.index,\n address: shard.address,\n amountLamports: shard.amount_lamports,\n ...(shard.required_lamports === undefined ? {} : { requiredLamports: shard.required_lamports }),\n status: mapStatus(shard.status),\n fundingTxSignature: shard.funding_tx_signature,\n payoutTxSignature: shard.payout_tx_signature,\n coolingUntilMs: shard.cooling_until_ms,\n };\n}\n\nfunction mapTopUpRequest(request: LpTopUpRequestPayload): LpTopUpRequest {\n return {\n topUpId: request.top_up_id,\n positionId: request.lp_position_id,\n depositAddress: request.deposit_address,\n expiresAtMs: request.expires_at_ms,\n status: request.status,\n };\n}\n\nfunction mapStatus(status: LpShardViewPayload[\"status\"]): LpInventoryShard[\"status\"] {\n switch (status) {\n case \"pregenerated\":\n return \"PREGENERATED\";\n case \"funding_queued\":\n return \"FUNDING_QUEUED\";\n case \"funded\":\n return \"FUNDED\";\n case \"cooling\":\n return \"COOLING\";\n case \"available\":\n return \"AVAILABLE\";\n case \"reserved\":\n return \"RESERVED\";\n case \"retired\":\n return \"RETIRED\";\n case \"redeemed\":\n return \"REDEEMED\";\n }\n}\n\nasync function coordinatorAttestationHash(\n binaryHash: string,\n pubkeyHex: string,\n): Promise<Uint8Array> {\n const material = encoder.encode(\n `invisible-lp-attestation-v1\\0${binaryHash.toLowerCase()}\\0${pubkeyHex.toLowerCase()}`,\n );\n return new Uint8Array(await crypto.subtle.digest(\"SHA-256\", material));\n}\n\nfunction randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n\nfunction loadProtocol(): Promise<ProtocolLpModule> {\n protocolPromise ??= import(\"protocol/coordinator\") as Promise<ProtocolLpModule>;\n return protocolPromise;\n}\n","import type { LpPositionCodeAuth } from \"./positionCode.js\";\nimport type { LpCoordinatorClient } from \"./types.js\";\n\ntype LpDkgWorkerRequest =\n | {\n id: string;\n type: \"round1\";\n }\n | {\n id: string;\n type: \"round2\";\n teeRound1: number[];\n teeRound2ForLp: number[];\n };\n\ntype LpDkgWorkerResponse =\n | {\n id: string;\n type: \"round1\";\n package: number[];\n }\n | {\n id: string;\n type: \"round2\";\n package: number[];\n delegatedShare: number[];\n jointPubkey: number[];\n }\n | {\n id: string;\n type: \"error\";\n error: string;\n };\n\nexport type LpDkgProgress = {\n completed: number;\n total: number;\n address: string;\n};\n\nexport type CreateLpDkgBatchInput = {\n lpPositionId: string;\n startIndex: number;\n count: number;\n auth: LpPositionCodeAuth;\n client: LpCoordinatorClient;\n concurrency?: number;\n workerFactory?: () => Worker;\n useDeterministicTestAddresses?: boolean;\n onProgress?: (progress: LpDkgProgress) => void;\n};\n\nconst MAX_LP_DKG_CONCURRENCY = 8;\nconst DEFAULT_LP_DKG_CONCURRENCY = MAX_LP_DKG_CONCURRENCY;\nexport const LP_DKG_WORKER_REQUEST_TIMEOUT_MS = 30_000;\nexport const LP_DKG_WORKER_REQUEST_TIMEOUT_MESSAGE = \"LP DKG worker request timed out\";\nexport const LP_DKG_ABORT_CLEANUP_TIMEOUT_MS = 10_000;\nconst LP_DKG_ABORT_CLEANUP_TIMEOUT_MESSAGE = \"LP DKG session cleanup timed out\";\nconst LP_DKG_COMPLETED_SHARD_POLL_INTERVAL_MS = 500;\nconst LP_DKG_COMPLETED_SHARD_POLL_TIMEOUT_MS = 5 * 60_000 + 15_000;\nconst LP_DKG_ACTIVE_SESSION_RETRY_INTERVAL_MS = 2_000;\nconst LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS = LP_DKG_COMPLETED_SHARD_POLL_TIMEOUT_MS;\n\nexport async function createLpDkgBatch(input: CreateLpDkgBatchInput): Promise<string[]> {\n if (input.useDeterministicTestAddresses === true) {\n const addresses = Array.from({ length: input.count }, (_, offset) =>\n testAddress(input.lpPositionId, input.startIndex + offset),\n );\n for (const [offset, address] of addresses.entries()) {\n input.onProgress?.({\n completed: offset + 1,\n total: input.count,\n address,\n });\n }\n return addresses;\n }\n\n const workerCount = resolveConcurrency(input.count, input.concurrency);\n const workers: Worker[] = [];\n let workersTerminated = false;\n const terminateWorkers = (): void => {\n if (workersTerminated) return;\n workersTerminated = true;\n workers.forEach((worker) => worker.terminate());\n };\n const addresses = new Array<string>(input.count);\n let completed = 0;\n let nextOffset = 0;\n try {\n for (let index = 0; index < workerCount; index += 1) {\n workers.push(createWorker(input.workerFactory));\n }\n await Promise.all(\n workers.map(async (worker) => {\n for (;;) {\n const offset = nextOffset;\n nextOffset += 1;\n if (offset >= input.count) return;\n\n const index = input.startIndex + offset;\n const address = await createLpDkgShard(input, worker, index);\n addresses[offset] = address;\n completed += 1;\n input.onProgress?.({\n completed,\n total: input.count,\n address,\n });\n }\n }),\n );\n return addresses;\n } catch (error) {\n terminateWorkers();\n if (!isLpDkgSessionCoordinationError(error)) {\n await abortDkgSessionsAfterFailure(input);\n }\n throw error;\n } finally {\n terminateWorkers();\n }\n}\n\nasync function abortDkgSessionsAfterFailure(input: CreateLpDkgBatchInput): Promise<void> {\n const abortDkgSessions = input.client.abortDkgSessions;\n if (typeof abortDkgSessions !== \"function\") return;\n let timeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;\n try {\n const cleanupTimeout = new Promise<never>((_, reject) => {\n timeoutId = globalThis.setTimeout(\n () => reject(new Error(LP_DKG_ABORT_CLEANUP_TIMEOUT_MESSAGE)),\n LP_DKG_ABORT_CLEANUP_TIMEOUT_MS,\n );\n });\n await Promise.race([\n abortDkgSessions.call(input.client, input.lpPositionId, input.auth),\n cleanupTimeout,\n ]);\n } catch {\n // Preserve the original DKG failure. The coordinator TTL remains the\n // last-resort cleanup if the best-effort abort cannot be delivered.\n } finally {\n if (timeoutId !== undefined) globalThis.clearTimeout(timeoutId);\n }\n}\n\nasync function createLpDkgShard(\n input: CreateLpDkgBatchInput,\n worker: Worker,\n index: number,\n): Promise<string> {\n const deadline = Date.now() + LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS;\n let sawActiveSession = false;\n\n for (;;) {\n if (sawActiveSession) {\n const completedAddress = await getCompletedShardAddress(input, index);\n if (completedAddress !== null) return completedAddress;\n }\n\n try {\n return await runLpDkgShard(input, worker, index);\n } catch (error) {\n if (isLpDkgCompletedOrVisibleError(error)) {\n return waitForCompletedShardAddress(input, index);\n }\n if (!isLpDkgActiveSessionError(error)) throw error;\n\n sawActiveSession = true;\n const completedAddress = await getCompletedShardAddress(input, index);\n if (completedAddress !== null) return completedAddress;\n if (Date.now() >= deadline) throw error;\n await sleep(LP_DKG_ACTIVE_SESSION_RETRY_INTERVAL_MS);\n }\n }\n}\n\nasync function runLpDkgShard(\n input: CreateLpDkgBatchInput,\n worker: Worker,\n index: number,\n): Promise<string> {\n const roundId = `lp_dkg_${Date.now()}_${index}_${Math.random().toString(16).slice(2)}`;\n const initResponse = await input.client.initDkg(\n { lpPositionId: input.lpPositionId, index },\n input.auth,\n );\n\n const round1 = await workerRequest(worker, {\n id: roundId,\n type: \"round1\",\n });\n if (round1.type !== \"round1\") throw new Error(\"LP DKG worker returned wrong round1 type\");\n\n const round1Response = await input.client.dkgRound1(\n {\n sessionId: initResponse.sessionId,\n package: round1.package,\n },\n input.auth,\n );\n const round2 = await workerRequest(worker, {\n id: roundId,\n type: \"round2\",\n teeRound1: Array.from(round1Response.package),\n teeRound2ForLp: Array.from(round1Response.round2ForLp),\n });\n if (round2.type !== \"round2\") throw new Error(\"LP DKG worker returned wrong round2 type\");\n\n const round2Response = await input.client.dkgRound2(\n {\n sessionId: initResponse.sessionId,\n package: round2.package,\n delegatedShare: round2.delegatedShare,\n },\n input.auth,\n );\n if (!bytesEqual(Uint8Array.from(round2.jointPubkey), round2Response.jointPubkey)) {\n throw new Error(`LP DKG joint pubkey mismatch at index ${index}`);\n }\n if (round2Response.index !== index) {\n throw new Error(`LP DKG index mismatch: expected ${index}, got ${round2Response.index}`);\n }\n\n return round2Response.address;\n}\n\nasync function waitForCompletedShardAddress(\n input: CreateLpDkgBatchInput,\n index: number,\n): Promise<string> {\n const deadline = Date.now() + LP_DKG_COMPLETED_SHARD_POLL_TIMEOUT_MS;\n for (;;) {\n const address = await getCompletedShardAddress(input, index);\n if (address !== null) return address;\n if (Date.now() >= deadline) {\n throw new Error(`LP DKG completed shard ${index} did not become visible`);\n }\n await sleep(LP_DKG_COMPLETED_SHARD_POLL_INTERVAL_MS);\n }\n}\n\nasync function getCompletedShardAddress(\n input: CreateLpDkgBatchInput,\n index: number,\n): Promise<string | null> {\n const position = await input.client.getPosition(input.lpPositionId, input.auth);\n return position.shards.find((candidate) => candidate.index === index)?.address ?? null;\n}\n\nfunction workerRequest(worker: Worker, request: LpDkgWorkerRequest): Promise<LpDkgWorkerResponse> {\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;\n const onMessage = (event: MessageEvent<LpDkgWorkerResponse>) => {\n const message = event.data;\n if (message.id !== request.id) return;\n cleanup();\n if (message.type === \"error\") {\n reject(new Error(message.error));\n } else {\n resolve(message);\n }\n };\n const onError = (event: ErrorEvent) => {\n cleanup();\n reject(new Error(event.message));\n };\n const cleanup = () => {\n if (timeoutId !== undefined) globalThis.clearTimeout(timeoutId);\n worker.removeEventListener(\"message\", onMessage);\n worker.removeEventListener(\"error\", onError);\n };\n worker.addEventListener(\"message\", onMessage);\n worker.addEventListener(\"error\", onError);\n timeoutId = globalThis.setTimeout(() => {\n cleanup();\n reject(new Error(LP_DKG_WORKER_REQUEST_TIMEOUT_MESSAGE));\n }, LP_DKG_WORKER_REQUEST_TIMEOUT_MS);\n try {\n worker.postMessage(request);\n } catch (error) {\n cleanup();\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n });\n}\n\nfunction createWorker(workerFactory: (() => Worker) | undefined): Worker {\n if (workerFactory !== undefined) return workerFactory();\n return new Worker(new URL(\"./dkgWorker.js\", import.meta.url), { type: \"module\" });\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n let diff = 0;\n for (let index = 0; index < a.byteLength; index += 1) {\n diff |= a[index]! ^ b[index]!;\n }\n return diff === 0;\n}\n\nfunction isLpDkgCompletedOrVisibleError(error: unknown): boolean {\n if (!(error instanceof Error) || !error.message.includes(\"LP DKG index\")) return false;\n return (\n error.message.includes(\"already completed for position\") ||\n error.message.includes(\"already exists for position\")\n );\n}\n\nexport function isLpDkgActiveSessionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.includes(\"LP DKG session already active for position index\")\n );\n}\n\nexport function isLpDkgIndexDriftError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n return (\n (error.message.includes(\"LP DKG index\") &&\n error.message.includes(\"already exists for position\")) ||\n error.message.includes(\"LP DKG expected index\")\n );\n}\n\nfunction isLpDkgSessionCoordinationError(error: unknown): boolean {\n return isLpDkgActiveSessionError(error) || isLpDkgIndexDriftError(error);\n}\n\nfunction resolveConcurrency(count: number, requested: number | undefined): number {\n if (count <= 0) return 0;\n const concurrency = requested ?? DEFAULT_LP_DKG_CONCURRENCY;\n if (!Number.isFinite(concurrency)) return Math.min(count, DEFAULT_LP_DKG_CONCURRENCY);\n return Math.max(1, Math.min(count, MAX_LP_DKG_CONCURRENCY, Math.floor(concurrency)));\n}\n\nfunction sleep(delayMs: number): Promise<void> {\n return new Promise((resolve) => {\n globalThis.setTimeout(resolve, delayMs);\n });\n}\n\nfunction testAddress(lpPositionId: string, index: number): string {\n return `${lpPositionId}Shard${String(index).padStart(5, \"0\")}11111111111111111111`;\n}\n","import {\n LP_DEFAULT_REFILL_BATCH_SIZE,\n LP_DEFAULT_TARGET_SHARDS,\n LP_MAX_REFILL_BATCH_SIZE,\n LP_MAX_TARGET_SHARDS,\n} from \"@invisible/shared\";\nimport {\n CommandError,\n LpLifecycleError,\n PolicyValidationError,\n RoutingError,\n} from \"../core/errors.js\";\nimport type { Session } from \"../core/session.js\";\nimport { publicKey } from \"../core/brands.js\";\nimport { assertAttested } from \"../session/guards.js\";\nimport { createLpCoordinatorClient } from \"./coordinatorClient.js\";\nimport { createLpDkgBatch, isLpDkgActiveSessionError, isLpDkgIndexDriftError } from \"./dkgBatch.js\";\nimport {\n bytesToHex,\n deriveLpPositionCodeAuth,\n generateLpPositionCode,\n type LpPositionCodeAuth,\n} from \"./positionCode.js\";\nimport { validateLpWithdrawalClaim, validateLpWithdrawalPlan } from \"./withdrawalValidation.js\";\nimport type {\n LpCoordinatorClient,\n LpInventoryShard,\n LpPositionView,\n LpRedemptionHistoryView,\n LpWithdrawalExecutionView,\n LpWithdrawalMode,\n} from \"./types.js\";\n\nconst LP_ID_PREFIX = \"lp\";\nconst DEFAULT_SHARD_FUNDING_LAMPORTS = 101_000_000;\nconst DEFAULT_REFILL_THRESHOLD_RATIO = 0.2;\nconst LP_DKG_ACTIVE_SESSION_RETRY_DELAY_MS = 2_000;\nconst LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS = 5 * 60_000 + 15_000;\nconst LP_WITHDRAWAL_CONFIRMATION_POLL_INTERVAL_MS = 3_000;\nconst LP_WITHDRAWAL_CONFIRMATION_TIMEOUT_MS = 15 * 60_000;\nconst LP_WITHDRAWAL_READINESS_RETRY_DELAY_MS = 1_000;\nconst LP_WITHDRAWAL_READINESS_RETRY_ATTEMPTS = 30;\nconst LP_TOP_UP_WAIT_POLL_INTERVAL_MS = 1_000;\nconst LP_REDEMPTION_HISTORY_OPEN_STATES: ReadonlySet<LpRedemptionHistoryView[\"state\"]> = new Set([\n \"requested\",\n \"match_requested\",\n \"reserved\",\n \"pending\",\n]);\nexport const LP_REDEMPTION_RECONCILING_MESSAGE =\n \"LP redemption is still settling on the coordinator; it will reconcile from sync\";\nexport const LP_MISSING_POSITION_CODE_MESSAGE =\n \"Save or recover the LP Position Code before using LP funds\";\nconst POSITION_CODE_MISMATCH_MESSAGE = \"LP Position Code does not match this TEE position\";\nconst FUNDING_PLAN_EMPTY_MESSAGE = \"TEE returned an empty LP funding plan\";\nconst WITHDRAWAL_MISSING_RECORD_MESSAGE = \"LP withdrawal record is missing\";\nconst WITHDRAWAL_RECORD_MISMATCH_MESSAGE =\n \"LP withdrawal record does not match this confirmation request\";\nconst WITHDRAWAL_NO_LAMPORTS_MESSAGE = \"LP redemption did not land any lamports on-chain\";\nconst WITHDRAWAL_HISTORY_MISMATCH_MESSAGE = \"LP redemption history does not match this request\";\nconst LP_WITHDRAWAL_UNRESOLVED_FUNDING_MESSAGE =\n \"LP position has unresolved funding shards before redemption\";\nconst UNSUPPORTED_FEE_POLICY_MESSAGE =\n \"LP fee policy overrides are not advertised by the coordinator\";\nexport const LP_FEE_SOURCE_COUNT_UNAVAILABLE_MESSAGE =\n \"LP earned-fee source count is not available; pass allowManyToOne: true to acknowledge many-to-one withdrawal risk\";\n\nexport type LpLifecycleDkgProgress = {\n readonly phase: \"dkg\";\n readonly lpPositionId: string;\n readonly startIndex: number;\n readonly targetShardCount: number;\n readonly completed: number;\n readonly total: number;\n};\n\nexport interface CreatePositionArgs {\n readonly committedLamports?: number;\n readonly shardCount?: number;\n readonly refillThreshold?: number;\n readonly feePolicy?: unknown;\n /**\n * Called after SDK-owned code generation and before the coordinator open call.\n * Use this to show/save the code if coordinator intake fails.\n */\n readonly onPositionCode?: (code: LpGeneratedPositionCode) => void;\n}\n\nexport interface LpGeneratedPositionCode {\n readonly positionId: string;\n readonly lpPositionCode: string;\n}\n\nexport interface CreatePositionResult {\n readonly positionId: string;\n /** Shown once at onboarding; treat like a seed phrase. */\n readonly lpPositionCode: string;\n readonly position: LpPositionView;\n}\n\nexport interface CompleteDkgBatchOptions {\n readonly onProgress?: (progress: LpLifecycleDkgProgress) => void;\n readonly onPosition?: (position: LpPositionView) => void;\n readonly concurrency?: number;\n readonly workerFactory?: () => Worker;\n}\n\nexport interface InitialFundingPlan {\n readonly address: string;\n readonly requiredLamports: number;\n readonly qrPayload: string;\n readonly position: LpPositionView;\n}\n\nexport interface LpTopUpRequest {\n readonly topUpId: string;\n readonly positionId: string;\n readonly depositAddress: string;\n readonly expiresAtMs: number;\n readonly status: \"watching\" | \"funded\" | \"expired\";\n}\n\nexport interface WithdrawPositionArgs {\n /** Signed intent mode. The coordinator resolves max_available from sealed state. */\n readonly withdrawalMode: LpWithdrawalMode;\n /** Exact LP deposit-principal bucket claim. Required for exact mode. */\n readonly depositPrincipalLamports?: number;\n /** Exact earned-fee bucket claim. Required for exact mode. */\n readonly earnedFeeLamports?: number;\n readonly destinationAddresses: string[];\n /** Required to accept a privacy-degrading single-destination withdrawal. */\n readonly allowManyToOne?: boolean;\n}\n\nexport interface RefillArgs {\n readonly shardCount?: number;\n readonly onProgress?: (progress: LpLifecycleDkgProgress) => void;\n readonly onPosition?: (position: LpPositionView) => void;\n readonly workerFactory?: () => Worker;\n}\n\nexport interface WithdrawalExecution {\n readonly withdrawalId: string;\n readonly txSignatures: string[];\n readonly acceptedLamports?: number;\n readonly acceptedDepositPrincipalLamports?: number;\n readonly acceptedEarnedFeeLamports?: number;\n}\n\nexport interface LpWithdrawalRecord {\n readonly redemptionId: string;\n readonly lpPositionId: string;\n readonly requestedAt: number;\n readonly status: \"pending\" | \"reconciling\" | \"confirmed\" | \"failed\";\n readonly destinationAddresses: string[];\n readonly destinationCount?: number;\n readonly txSignatureCount?: number;\n readonly detailsTruncated?: boolean;\n readonly acceptedLamports?: number;\n readonly requestedTargetLamports: number;\n readonly landedBaselineLamports: number;\n readonly landedFeeBaselineLamports?: number;\n readonly redeemedLamports: number;\n readonly txSignatures: string[];\n readonly txSignatureBaseline: string[];\n readonly coordinatorStateVersion?: number;\n readonly error?: string;\n}\n\nexport interface WithdrawPositionResult {\n readonly execution: WithdrawalExecution;\n readonly position: LpPositionView;\n readonly redemption: LpWithdrawalRecord;\n}\n\nexport interface WithdrawalConfirmation {\n readonly withdrawalId: string;\n readonly txSignatures: string[];\n readonly redeemedLamports: number;\n}\n\nexport interface LpLifecycleRuntime {\n readonly coordinatorClient?: LpCoordinatorClient;\n readonly workerFactory?: () => Worker;\n readonly useDeterministicTestAddresses?: boolean;\n readonly nowMs?: () => number;\n readonly idFactory?: () => string;\n readonly sleep?: (delayMs: number) => Promise<void>;\n readonly dkgConcurrency?: number;\n readonly withdrawalConfirmationPollIntervalMs?: number;\n readonly withdrawalConfirmationTimeoutMs?: number;\n}\n\nexport interface WaitForWithdrawalConfirmationOptions {\n readonly onPosition?: (position: LpPositionView) => void;\n readonly onRedemptionUpdate?: (record: LpWithdrawalRecord) => void;\n readonly redemptionRecord?: LpWithdrawalRecord;\n /** Caller-owned absolute deadline preserved across client/session retries. */\n readonly deadlineMs?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface RecoverPositionArgs {\n readonly code: string;\n readonly deadlineMs?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface WaitForTopUpOptions {\n readonly signal?: AbortSignal;\n readonly pollIntervalMs?: number;\n readonly positionId?: string;\n}\n\nexport interface LpWithdrawalPlanPreviewArgs {\n readonly depositPrincipalLamports?: number;\n readonly earnedFeeLamports?: number;\n readonly allowManyToOne?: boolean;\n}\n\nexport interface LpWithdrawalPlanPreview {\n readonly depositPrincipalLamports: number;\n readonly earnedFeeLamports: number;\n readonly sourceCount: number;\n}\n\nclass LpRedemptionReconcilingError extends LpLifecycleError {\n constructor() {\n super(\"LP_REDEMPTION_RECONCILING\", LP_REDEMPTION_RECONCILING_MESSAGE);\n this.name = \"LpRedemptionReconcilingError\";\n }\n}\n\nclass LpPositionAuthMissingError extends LpLifecycleError {\n constructor() {\n super(\"LP_POSITION_AUTH_MISSING\", LP_MISSING_POSITION_CODE_MESSAGE);\n this.name = \"LpPositionAuthMissingError\";\n }\n}\n\nexport function isLpRedemptionReconcilingError(error: unknown): boolean {\n return (\n error instanceof LpRedemptionReconcilingError ||\n (error instanceof Error && error.message === LP_REDEMPTION_RECONCILING_MESSAGE)\n );\n}\n\nexport function isLpPositionAuthMissingError(error: unknown): boolean {\n return (\n error instanceof LpPositionAuthMissingError ||\n (error instanceof Error && error.message === LP_MISSING_POSITION_CODE_MESSAGE)\n );\n}\n\nexport function previewLpWithdrawalPlan(\n position: LpPositionView,\n args: LpWithdrawalPlanPreviewArgs = {},\n): LpWithdrawalPlanPreview {\n const claim = resolveWithdrawalClaim(position, args);\n return {\n ...claim,\n sourceCount: lpWithdrawalSourceCountForClaim(position, {\n ...claim,\n allowManyToOne: args.allowManyToOne,\n }),\n };\n}\n\nexport interface LpLifecycleClient {\n createPosition(args?: CreatePositionArgs): Promise<CreatePositionResult>;\n recoverPosition(args: RecoverPositionArgs): Promise<LpPositionView>;\n confirmPositionCodeSaved(positionId: string): void;\n completeDkgBatch(positionId: string, options?: CompleteDkgBatchOptions): Promise<LpPositionView>;\n refreshPosition(positionId: string): Promise<LpPositionView>;\n refill(positionId: string, args?: RefillArgs): Promise<LpPositionView>;\n prepareInitialFunding(positionId: string): Promise<InitialFundingPlan | null>;\n prepareTopUp(positionId: string): Promise<LpTopUpRequest>;\n waitForTopUp(topUpId: string, options?: WaitForTopUpOptions): Promise<LpTopUpRequest>;\n reconcileFunding(positionId: string): Promise<LpPositionView>;\n withdrawPosition(positionId: string, args: WithdrawPositionArgs): Promise<WithdrawPositionResult>;\n waitForWithdrawalConfirmation(\n positionId: string,\n execution: WithdrawalExecution,\n options?: WaitForWithdrawalConfirmationOptions,\n ): Promise<WithdrawalConfirmation>;\n withdrawFees(positionId: string, args: { readonly destination: string }): Promise<never>;\n listPositions(): Promise<LpPositionView[]>;\n}\n\ntype LpLifecycleState = {\n readonly authByPosition: Map<string, LpPositionCodeAuth>;\n readonly positions: Map<string, LpPositionView>;\n readonly redemptions: Map<string, LpWithdrawalRecord>;\n readonly topUps: Map<string, LpTopUpRequest>;\n};\n\nconst lifecycleClients = new WeakMap<Session, LpLifecycleClient>();\n\nexport function createLpLifecycleClient(\n session: Session,\n runtime: LpLifecycleRuntime = {},\n): LpLifecycleClient {\n const state: LpLifecycleState = {\n authByPosition: new Map(),\n positions: new Map(),\n redemptions: new Map(),\n topUps: new Map(),\n };\n const client = runtime.coordinatorClient ?? createLpCoordinatorClient(session);\n const nowMs = runtime.nowMs ?? Date.now;\n const sleep = runtime.sleep ?? defaultSleep;\n\n const requireAuth = (positionId: string): LpPositionCodeAuth => {\n const auth = state.authByPosition.get(positionId);\n if (auth === undefined) throw new LpPositionAuthMissingError();\n return auth;\n };\n\n const rememberPosition = (position: LpPositionView): LpPositionView => {\n const snapshot = clonePosition(position);\n state.positions.set(snapshot.id, snapshot);\n hydrateLpRedemptionsFromPosition(state, snapshot);\n return position;\n };\n\n const rememberAuth = (auth: LpPositionCodeAuth): void => {\n state.authByPosition.set(auth.lpPositionId, auth);\n };\n\n const refreshPosition = async (positionId: string): Promise<LpPositionView> => {\n const auth = requireAuth(positionId);\n return rememberPosition(await client.getPosition(positionId, auth));\n };\n\n const executeWithdrawalAfterFundingReadiness = async (\n positionId: string,\n input: Parameters<LpCoordinatorClient[\"executeWithdrawal\"]>[0],\n auth: LpPositionCodeAuth,\n ): Promise<LpWithdrawalExecutionView> => {\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await client.executeWithdrawal(input, auth);\n } catch (error) {\n const retryable =\n error instanceof CommandError &&\n error.message.includes(LP_WITHDRAWAL_UNRESOLVED_FUNDING_MESSAGE);\n if (!retryable || attempt >= LP_WITHDRAWAL_READINESS_RETRY_ATTEMPTS - 1) {\n throw error;\n }\n await sleep(LP_WITHDRAWAL_READINESS_RETRY_DELAY_MS);\n await client.reconcileFunding(positionId, auth).catch(() => undefined);\n }\n }\n };\n\n const completeDkgBatch = async (\n positionId: string,\n options: CompleteDkgBatchOptions = {},\n ): Promise<LpPositionView> => {\n assertAttested(session);\n const auth = requireAuth(positionId);\n let activeSessionRetryStartedAtMs: number | null = null;\n\n for (;;) {\n const current = rememberPosition(await client.getPosition(positionId, auth));\n options.onPosition?.(current);\n const startIndex = current.shards.length;\n const remaining = current.targetShardCount - startIndex;\n if (remaining <= 0) return current;\n\n emitDkgProgress(options, current, startIndex, remaining, 0);\n let expectedAddresses: string[] | null = null;\n try {\n const addresses = await createLpDkgBatch({\n lpPositionId: positionId,\n startIndex,\n count: remaining,\n auth,\n client,\n concurrency: options.concurrency ?? runtime.dkgConcurrency,\n workerFactory: options.workerFactory ?? runtime.workerFactory,\n useDeterministicTestAddresses: runtime.useDeterministicTestAddresses,\n onProgress: (progress) => {\n emitDkgProgress(options, current, startIndex, remaining, progress.completed);\n },\n });\n expectedAddresses = addresses;\n const position = await client.finalizeDkgBatch(\n {\n lpPositionId: positionId,\n startIndex,\n addresses,\n finalizedAtMs: nowMs(),\n },\n auth,\n );\n options.onPosition?.(position);\n emitDkgProgress(options, position, startIndex, remaining, remaining);\n return rememberPosition(position);\n } catch (error) {\n const reconciled = await tryRefreshCompletedDkgWindow({\n client,\n positionId,\n auth,\n startIndex,\n total: remaining,\n expectedAddresses,\n state,\n });\n if (reconciled !== null) return reconciled;\n if (isLpDkgIndexDriftError(error)) {\n activeSessionRetryStartedAtMs = null;\n continue;\n }\n if (!isLpDkgActiveSessionError(error)) throw error;\n\n const currentTime = nowMs();\n activeSessionRetryStartedAtMs ??= currentTime;\n if (currentTime - activeSessionRetryStartedAtMs >= LP_DKG_ACTIVE_SESSION_RETRY_TIMEOUT_MS) {\n throw error;\n }\n await sleep(LP_DKG_ACTIVE_SESSION_RETRY_DELAY_MS);\n }\n }\n };\n\n return {\n async createPosition(args = {}) {\n assertNoUnsupportedFeePolicy(args.feePolicy);\n const shardCount = args.shardCount ?? LP_DEFAULT_TARGET_SHARDS;\n assertShardCount(shardCount, LP_MAX_TARGET_SHARDS, \"shardCount\");\n assertAttested(session);\n const positionId = runtime.idFactory?.() ?? generateId(LP_ID_PREFIX);\n const auth = await generateLpPositionCode(positionId);\n rememberAuth(auth);\n args.onPositionCode?.({ positionId, lpPositionCode: auth.code });\n const committedLamports = args.committedLamports ?? DEFAULT_SHARD_FUNDING_LAMPORTS;\n const position = rememberPosition(\n await client.openPosition(\n {\n lpPositionId: positionId,\n authPublicKey: Array.from(auth.authPublicKey),\n refillPublicKey: Array.from(auth.refillPublicKey),\n withdrawalCommitment: Array.from(auth.withdrawalCommitment),\n committedLamports,\n shardCount,\n shardAmountLamports: DEFAULT_SHARD_FUNDING_LAMPORTS,\n refillThreshold:\n args.refillThreshold ?? Math.ceil(shardCount * DEFAULT_REFILL_THRESHOLD_RATIO),\n addresses: [],\n createdAtMs: nowMs(),\n },\n auth,\n ),\n );\n return { positionId, lpPositionCode: auth.code, position };\n },\n\n async recoverPosition(args) {\n const auth = await deriveLpPositionCodeAuth(args.code);\n rememberAuth(auth);\n const position = rememberPosition(\n await client.getPosition(auth.lpPositionId, auth, {\n deadlineMs: args.deadlineMs,\n signal: args.signal,\n }),\n );\n assertPositionMatchesAuth(position, auth);\n return position;\n },\n\n confirmPositionCodeSaved(_positionId) {\n return;\n },\n\n completeDkgBatch,\n\n refreshPosition,\n\n async refill(positionId, args = {}) {\n const requestedShardCount = args.shardCount ?? LP_DEFAULT_REFILL_BATCH_SIZE;\n assertShardCount(requestedShardCount, LP_MAX_REFILL_BATCH_SIZE, \"shardCount\");\n assertAttested(session);\n const auth = requireAuth(positionId);\n const current = await refreshPosition(positionId);\n args.onPosition?.(current);\n const refillShardCount = resolveLpRefillShardCount(\n current,\n requestedShardCount,\n args.shardCount === undefined,\n );\n const authorizedPosition = rememberPosition(\n await client.refillPosition(\n {\n lpPositionId: positionId,\n shardCount: refillShardCount,\n shardAmountLamports: DEFAULT_SHARD_FUNDING_LAMPORTS,\n addresses: [],\n authorizedAtMs: nowMs(),\n },\n auth,\n ),\n );\n args.onPosition?.(authorizedPosition);\n if (authorizedPosition.shards.length >= authorizedPosition.targetShardCount) {\n return authorizedPosition;\n }\n return completeDkgBatch(positionId, {\n onProgress: args.onProgress,\n onPosition: args.onPosition,\n workerFactory: args.workerFactory,\n });\n },\n\n async prepareInitialFunding(positionId) {\n assertAttested(session);\n const auth = requireAuth(positionId);\n const currentPosition = rememberPosition(await client.getPosition(positionId, auth));\n if (!isLpPositionReadyForInitialFunding(currentPosition)) return null;\n\n const initialShard = currentPosition.shards.find((shard) => shard.index === 0);\n if (initialShard === undefined) return null;\n if (initialShard.status === \"FUNDING_QUEUED\") {\n return fundingPlanFromShard(currentPosition, initialShard);\n }\n if (initialShard.status !== \"PREGENERATED\") return null;\n\n const existingQueuedShard = currentPosition.shards.find(\n (shard) => shard.status === \"FUNDING_QUEUED\",\n );\n if (existingQueuedShard !== undefined) return null;\n\n const [plannedShard] = await client.planFunding(\n { lpPositionId: positionId, shardCount: 1, nowMs: nowMs() },\n auth,\n );\n if (plannedShard === undefined) throw new Error(FUNDING_PLAN_EMPTY_MESSAGE);\n if (plannedShard.index !== 0) {\n throw new PolicyValidationError(\n \"INVALID_POSITION_AUTH\",\n \"Coordinator funding plan did not select LP_DKG_0\",\n );\n }\n const position = rememberPosition(await client.getPosition(positionId, auth));\n return fundingPlanFromShard(position, plannedShard);\n },\n\n async prepareTopUp(positionId) {\n assertAttested(session);\n const auth = requireAuth(positionId);\n const request = await client.prepareTopUp(positionId, auth);\n state.topUps.set(request.topUpId, request);\n return request;\n },\n\n async waitForTopUp(topUpId, options = {}) {\n const cached = state.topUps.get(topUpId);\n if (\n cached !== undefined &&\n options.positionId !== undefined &&\n cached.positionId !== options.positionId\n ) {\n throw new PolicyValidationError(\n \"INVALID_POSITION_AUTH\",\n \"Top-up request does not belong to the requested LP position\",\n );\n }\n const initial =\n cached ??\n (options.positionId === undefined\n ? undefined\n : await client.getTopUpStatus(\n { lpPositionId: options.positionId, topUpId },\n requireAuth(options.positionId),\n ));\n if (initial === undefined) {\n throw new PolicyValidationError(\n \"INVALID_POSITION_AUTH\",\n \"Top-up request is not known to this LP session\",\n );\n }\n const pollIntervalMs = options.pollIntervalMs ?? LP_TOP_UP_WAIT_POLL_INTERVAL_MS;\n let current = initial;\n for (;;) {\n throwIfTopUpWaitAborted(options.signal);\n if (current.status !== \"watching\") return current;\n const auth = requireAuth(current.positionId);\n current = await client.getTopUpStatus({ lpPositionId: current.positionId, topUpId }, auth);\n state.topUps.set(topUpId, current);\n if (current.status !== \"watching\") return current;\n if (nowMs() >= current.expiresAtMs) {\n current = await client.getTopUpStatus(\n { lpPositionId: current.positionId, topUpId },\n auth,\n );\n state.topUps.set(topUpId, current);\n if (current.status !== \"watching\") return current;\n current = { ...current, status: \"expired\" };\n state.topUps.set(topUpId, current);\n return current;\n }\n await sleep(pollIntervalMs);\n }\n },\n\n async reconcileFunding(positionId) {\n assertAttested(session);\n const auth = requireAuth(positionId);\n return rememberPosition(await client.reconcileFunding(positionId, auth));\n },\n\n async withdrawPosition(positionId, args) {\n validateExplicitWithdrawalInput(args);\n validateWithdrawalDestinations(args);\n assertAttested(session);\n const auth = requireAuth(positionId);\n const before = rememberPosition(await client.reconcileFunding(positionId, auth));\n const existingRedemption = findOpenRedemptionHistory(before, args);\n if (existingRedemption !== undefined) {\n const execution = {\n withdrawalId: existingRedemption.redemptionId,\n txSignatures: [...existingRedemption.txSignatures],\n acceptedLamports: existingRedemption.acceptedLamports,\n acceptedDepositPrincipalLamports: existingRedemption.acceptedDepositPrincipalLamports,\n acceptedEarnedFeeLamports: existingRedemption.acceptedEarnedFeeLamports,\n };\n const redemption = {\n ...buildLpRedemptionRecord({\n execution,\n position: before,\n destinationAddresses: existingRedemption.destinationAddresses,\n acceptedLamports: existingRedemption.acceptedLamports,\n requestedTargetLamports: existingRedemption.acceptedLamports,\n landedBaselineLamports: 0,\n landedFeeBaselineLamports: 0,\n txSignatureBaseline: [],\n nowMs: existingRedemption.createdAtMs,\n }),\n redeemedLamports: existingRedemption.landedLamports,\n coordinatorStateVersion: existingRedemption.stateVersion,\n };\n state.redemptions.set(execution.withdrawalId, redemption);\n return { execution, position: before, redemption };\n }\n const preview =\n args.withdrawalMode === \"exact\" ? previewLpWithdrawalPlan(before, args) : undefined;\n const requestedAtMs = nowMs();\n if (args.withdrawalMode === \"exact\") {\n validateLpWithdrawalPlan({\n destinationAddresses: args.destinationAddresses,\n depositPrincipalLamports: preview!.depositPrincipalLamports,\n earnedFeeLamports: preview!.earnedFeeLamports,\n allowManyToOne: args.allowManyToOne ?? false,\n sourceCount: preview!.sourceCount,\n });\n }\n const execution = await executeWithdrawalAfterFundingReadiness(\n positionId,\n {\n lpPositionId: positionId,\n destinationAddresses: args.destinationAddresses,\n depositPrincipalLamports:\n args.withdrawalMode === \"max_available\" ? 0 : preview!.depositPrincipalLamports,\n earnedFeeLamports:\n args.withdrawalMode === \"max_available\" ? 0 : preview!.earnedFeeLamports,\n withdrawalMode: args.withdrawalMode,\n requestedAtMs,\n allowManyToOne: args.allowManyToOne === true || preview?.sourceCount === 1,\n },\n auth,\n );\n const acceptedLamports = execution.acceptedLamports;\n if (args.withdrawalMode === \"max_available\" && acceptedLamports === undefined) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n \"LP redemption response did not include the sealed accepted amount\",\n );\n }\n const acceptedAmount =\n acceptedLamports ?? preview!.depositPrincipalLamports + preview!.earnedFeeLamports;\n const pendingRedemption = buildLpRedemptionRecord({\n execution,\n position: before,\n destinationAddresses: args.destinationAddresses,\n acceptedLamports: acceptedAmount,\n requestedTargetLamports:\n (before.actorSync?.withdrawalRequestedLamports ?? 0) + acceptedAmount,\n landedBaselineLamports: before.actorSync?.withdrawalLandedLamports ?? 0,\n landedFeeBaselineLamports: before.actorSync?.withdrawalLandedFeeLamports ?? 0,\n txSignatureBaseline: before.actorSync?.withdrawalTxHashes ?? [],\n nowMs: nowMs(),\n });\n state.redemptions.set(execution.withdrawalId, pendingRedemption);\n const position = await client\n .getPosition(positionId, auth)\n .then((refreshed) => rememberPosition(refreshed))\n .catch(() => before);\n const redemption = { ...pendingRedemption, lpPositionId: position.id };\n state.redemptions.set(execution.withdrawalId, redemption);\n return { execution, position, redemption };\n },\n\n async waitForWithdrawalConfirmation(positionId, execution, options = {}) {\n const auth = requireAuth(positionId);\n let record = resolveWithdrawalRecord({\n state,\n positionId,\n execution,\n options,\n });\n state.redemptions.set(record.redemptionId, record);\n const deadlineMs =\n options.deadlineMs ??\n nowMs() +\n (runtime.withdrawalConfirmationTimeoutMs ?? LP_WITHDRAWAL_CONFIRMATION_TIMEOUT_MS);\n const pollIntervalMs =\n runtime.withdrawalConfirmationPollIntervalMs ?? LP_WITHDRAWAL_CONFIRMATION_POLL_INTERVAL_MS;\n\n for (;;) {\n throwIfWithdrawalConfirmationAborted(options.signal);\n if (nowMs() >= deadlineMs) {\n markLpRedemptionReconciling(state, record, options);\n }\n const remainingMs = deadlineMs - nowMs();\n if (remainingMs <= 0) {\n markLpRedemptionReconciling(state, record, options);\n }\n let position: LpPositionView;\n try {\n position = rememberPosition(\n await client.getPosition(positionId, auth, {\n deadlineMs,\n signal: options.signal,\n }),\n );\n } catch (error) {\n if (isLpPositionObservationDeadlineError(error, deadlineMs, nowMs)) {\n markLpRedemptionReconciling(state, record, options);\n }\n throw error;\n }\n throwIfWithdrawalConfirmationAborted(options.signal);\n options.onPosition?.(position);\n const reconciled = reconcileLpRedemptionFromActorSync(record, position);\n record = reconciled;\n state.redemptions.set(record.redemptionId, reconciled);\n options.onRedemptionUpdate?.(reconciled);\n if (reconciled.status === \"confirmed\") {\n return {\n withdrawalId: execution.withdrawalId,\n txSignatures: reconciled.txSignatures,\n redeemedLamports: reconciled.redeemedLamports,\n };\n }\n if (reconciled.status === \"failed\") {\n throw new Error(reconciled.error ?? WITHDRAWAL_NO_LAMPORTS_MESSAGE);\n }\n if (nowMs() >= deadlineMs) {\n markLpRedemptionReconciling(state, reconciled, options);\n }\n await sleepWithAbort(sleep, pollIntervalMs, options.signal);\n }\n },\n\n async withdrawFees(_positionId, args) {\n publicKey(args.destination);\n assertAttested(session);\n throw new RoutingError(\n \"VERSION_NOT_SUPPORTED\",\n \"LP fee withdrawal is not advertised by the coordinator\",\n );\n },\n\n async listPositions() {\n return [...state.positions.values()].map(clonePosition);\n },\n };\n}\n\nexport function defaultLpLifecycleClient(session: Session): LpLifecycleClient {\n let client = lifecycleClients.get(session);\n if (client === undefined) {\n client = createLpLifecycleClient(session);\n lifecycleClients.set(session, client);\n }\n return client;\n}\n\nfunction emitDkgProgress(\n options: CompleteDkgBatchOptions,\n position: LpPositionView,\n startIndex: number,\n total: number,\n completed: number,\n): void {\n options.onProgress?.({\n phase: \"dkg\",\n lpPositionId: position.id,\n startIndex,\n targetShardCount: startIndex + total,\n completed: Math.min(completed, total),\n total,\n });\n}\n\nasync function tryRefreshCompletedDkgWindow({\n client,\n positionId,\n auth,\n startIndex,\n total,\n expectedAddresses,\n state,\n}: {\n readonly client: LpCoordinatorClient;\n readonly positionId: string;\n readonly auth: LpPositionCodeAuth;\n readonly startIndex: number;\n readonly total: number;\n readonly expectedAddresses: readonly string[] | null;\n readonly state: LpLifecycleState;\n}): Promise<LpPositionView | null> {\n const position = await client.getPosition(positionId, auth).catch(() => null);\n if (position === null) return null;\n if (!hasCompletedDkgWindow(position, startIndex, total, expectedAddresses)) return null;\n state.positions.set(position.id, clonePosition(position));\n return position;\n}\n\nfunction hasCompletedDkgWindow(\n position: LpPositionView,\n startIndex: number,\n total: number,\n expectedAddresses: readonly string[] | null,\n): boolean {\n for (let offset = 0; offset < total; offset += 1) {\n const shard = position.shards.find((candidate) => candidate.index === startIndex + offset);\n if (shard === undefined) {\n return false;\n }\n if (expectedAddresses !== null && shard.address !== expectedAddresses[offset]) {\n return false;\n }\n }\n return true;\n}\n\nfunction assertNoUnsupportedFeePolicy(feePolicy: unknown): void {\n if (feePolicy === undefined) return;\n throw new RoutingError(\"VERSION_NOT_SUPPORTED\", UNSUPPORTED_FEE_POLICY_MESSAGE);\n}\n\nfunction fundingPlanFromShard(\n position: LpPositionView,\n shard: LpInventoryShard,\n): InitialFundingPlan | null {\n if (shard.requiredLamports === undefined || shard.requiredLamports <= 0) return null;\n return {\n address: shard.address,\n requiredLamports: shard.requiredLamports,\n qrPayload: `solana:${shard.address}`,\n position,\n };\n}\n\nfunction assertPositionMatchesAuth(position: LpPositionView, auth: LpPositionCodeAuth): void {\n if (\n position.authPublicKey !== bytesToHex(auth.authPublicKey) ||\n position.refillPublicKey !== bytesToHex(auth.refillPublicKey) ||\n position.withdrawalCommitment !== bytesToHex(auth.withdrawalCommitment)\n ) {\n throw new Error(POSITION_CODE_MISMATCH_MESSAGE);\n }\n}\n\nfunction assertShardCount(value: number, max: number, field: string): void {\n if (!Number.isInteger(value) || value < 1 || value > max) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n `${field} must be an integer in 1..${max}, received ${String(value)}`,\n );\n }\n}\n\nfunction resolveLpRefillShardCount(\n position: LpPositionView,\n requestedShardCount: number,\n capDefaultBatch: boolean,\n): number {\n const remainingShardCapacity = LP_MAX_TARGET_SHARDS - position.shards.length;\n if (remainingShardCapacity <= 0) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n `LP refill target_shard_count is already at ${LP_MAX_TARGET_SHARDS}`,\n );\n }\n const refillShardCount = capDefaultBatch\n ? Math.min(requestedShardCount, remainingShardCapacity)\n : requestedShardCount;\n if (position.shards.length + refillShardCount > LP_MAX_TARGET_SHARDS) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n `LP refill target_shard_count must be <= ${LP_MAX_TARGET_SHARDS}`,\n );\n }\n return refillShardCount;\n}\n\nfunction isLpPositionReadyForInitialFunding(position: LpPositionView): boolean {\n return position.status === \"active\" && position.shards.length >= position.targetShardCount;\n}\n\nfunction resolveWithdrawalClaim(\n position: LpPositionView,\n args: Pick<LpWithdrawalPlanPreviewArgs, \"depositPrincipalLamports\" | \"earnedFeeLamports\">,\n): { readonly depositPrincipalLamports: number; readonly earnedFeeLamports: number } {\n if (args.depositPrincipalLamports !== undefined || args.earnedFeeLamports !== undefined) {\n const claim = {\n depositPrincipalLamports: args.depositPrincipalLamports ?? 0,\n earnedFeeLamports: args.earnedFeeLamports ?? 0,\n };\n validateLpWithdrawalClaim(claim);\n return claim;\n }\n const legacyDepositPrincipalLamports = position.shards\n .filter((shard) => shard.status === \"AVAILABLE\" && shard.amountLamports > 0)\n .reduce((sum, shard) => sum + shard.amountLamports, 0);\n const actorRedeemablePrincipalLamports = Math.max(\n 0,\n position.actorSync?.redeemablePrincipalLamports ?? 0,\n );\n const actorRedeemableFeeLamports = Math.max(0, position.actorSync?.redeemableFeeLamports ?? 0);\n const hasActorProjection = hasActorRedeemableProjection(position.actorSync);\n const depositPrincipalLamports = resolveRedeemablePrincipalLamports(\n position.actorSync,\n legacyDepositPrincipalLamports,\n actorRedeemablePrincipalLamports,\n actorRedeemableFeeLamports,\n );\n const earnedFeeLamports = hasActorProjection\n ? actorRedeemableFeeLamports\n : Math.max(0, position.earnedLamports);\n const totalLamports = depositPrincipalLamports + earnedFeeLamports;\n if (!Number.isSafeInteger(totalLamports) || totalLamports <= 0) {\n throw new PolicyValidationError(\n \"INVALID_AMOUNT\",\n \"LP withdrawal requires available principal or earned fees\",\n );\n }\n return { depositPrincipalLamports, earnedFeeLamports };\n}\n\nfunction findOpenRedemptionHistory(\n position: LpPositionView,\n args: WithdrawPositionArgs,\n): LpRedemptionHistoryView | undefined {\n const hasExplicitClaim = args.withdrawalMode === \"exact\";\n const requestedPrincipalLamports = args.depositPrincipalLamports ?? 0;\n const requestedFeeLamports = args.earnedFeeLamports ?? 0;\n return position.actorSync?.redemptionHistory?.find(\n (history) =>\n LP_REDEMPTION_HISTORY_OPEN_STATES.has(history.state) &&\n history.detailsTruncated !== true &&\n (history.withdrawalMode ?? \"exact\") === args.withdrawalMode &&\n sameStringList(history.destinationAddresses, args.destinationAddresses) &&\n (!hasExplicitClaim ||\n (history.acceptedDepositPrincipalLamports === requestedPrincipalLamports &&\n history.acceptedEarnedFeeLamports === requestedFeeLamports)),\n );\n}\n\nfunction hasActorSyncLpActivity(sync: LpPositionView[\"actorSync\"]): boolean {\n if (sync === undefined) return false;\n return (\n sync.status !== \"idle\" ||\n sync.pendingReservationCount > 0 ||\n sync.reservedPayoutLamports > 0 ||\n sync.reimbursementDueCount > 0 ||\n sync.reimbursementDueSourceCount > 0 ||\n sync.reimbursementDuePayoutLamports > 0 ||\n sync.reimbursementDueNetworkFeeLamports > 0 ||\n sync.withdrawalRequestedLamports > 0 ||\n sync.withdrawalLandedLamports > 0 ||\n sync.withdrawalLandedFeeLamports > 0 ||\n sync.withdrawalCanceledLamports > 0 ||\n sync.withdrawalNetworkFeeLossLamports > 0 ||\n sync.withdrawalTxHashes.length > 0\n );\n}\n\nfunction resolveRedeemablePrincipalLamports(\n sync: LpPositionView[\"actorSync\"],\n legacyAvailableLamports: number,\n actorRedeemablePrincipalLamports: number,\n actorRedeemableFeeLamports: number,\n): number {\n if (sync?.redeemableProjectionAvailable !== true) return legacyAvailableLamports;\n if (legacyAvailableLamports <= 0) return actorRedeemablePrincipalLamports;\n if (actorRedeemablePrincipalLamports >= legacyAvailableLamports || hasActorSyncLpActivity(sync)) {\n return actorRedeemablePrincipalLamports;\n }\n return Math.max(\n actorRedeemablePrincipalLamports,\n legacyAvailableLamports - actorRedeemableFeeLamports,\n );\n}\n\nfunction hasActorRedeemableProjection(sync: LpPositionView[\"actorSync\"]): boolean {\n return sync?.redeemableProjectionAvailable === true;\n}\n\nfunction validateExplicitWithdrawalInput(args: WithdrawPositionArgs): void {\n if (args.withdrawalMode === \"max_available\") {\n if (args.depositPrincipalLamports !== undefined || args.earnedFeeLamports !== undefined) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n \"max_available withdrawal must not carry exact bucket claims\",\n );\n }\n return;\n }\n if (args.depositPrincipalLamports === undefined || args.earnedFeeLamports === undefined) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n \"exact withdrawal requires both bucket claims\",\n );\n }\n validateLpWithdrawalPlan({\n destinationAddresses: args.destinationAddresses,\n depositPrincipalLamports: args.depositPrincipalLamports,\n earnedFeeLamports: args.earnedFeeLamports,\n allowManyToOne: args.allowManyToOne,\n sourceCount: args.destinationAddresses.length,\n });\n}\n\nfunction validateWithdrawalDestinations(args: WithdrawPositionArgs): void {\n validateLpWithdrawalPlan({\n destinationAddresses: args.destinationAddresses,\n depositPrincipalLamports: 1,\n earnedFeeLamports: 0,\n allowManyToOne: true,\n });\n}\n\nfunction resolveWithdrawalRecord({\n state,\n positionId,\n execution,\n options,\n}: {\n readonly state: LpLifecycleState;\n readonly positionId: string;\n readonly execution: WithdrawalExecution;\n readonly options: WaitForWithdrawalConfirmationOptions;\n}): LpWithdrawalRecord {\n const record = state.redemptions.get(execution.withdrawalId) ?? options.redemptionRecord;\n if (record === undefined) throw new Error(WITHDRAWAL_MISSING_RECORD_MESSAGE);\n if (record.lpPositionId !== positionId || record.redemptionId !== execution.withdrawalId) {\n throw new PolicyValidationError(\"INVALID_REDEMPTION_PLAN\", WITHDRAWAL_RECORD_MISMATCH_MESSAGE);\n }\n return {\n ...record,\n destinationAddresses: [...record.destinationAddresses],\n txSignatures: [...record.txSignatures],\n txSignatureBaseline: [...record.txSignatureBaseline],\n landedFeeBaselineLamports: record.landedFeeBaselineLamports ?? 0,\n };\n}\n\nfunction lpWithdrawalSourceCountForClaim(\n position: LpPositionView,\n claim: {\n readonly depositPrincipalLamports: number;\n readonly earnedFeeLamports: number;\n readonly allowManyToOne?: boolean;\n },\n): number {\n const actorSync = position.actorSync;\n const actorRedeemablePrincipalLamports = actorSync?.redeemablePrincipalLamports ?? 0;\n const actorRedeemableFeeLamports = actorSync?.redeemableFeeLamports ?? 0;\n const actorRedeemableSourceCount = actorSync?.redeemableSourceCount;\n if (\n actorSync?.redeemableProjectionAvailable === true &&\n claim.depositPrincipalLamports === actorRedeemablePrincipalLamports &&\n claim.earnedFeeLamports === actorRedeemableFeeLamports &&\n actorRedeemableSourceCount !== undefined\n ) {\n return actorRedeemableSourceCount;\n }\n\n let remainingPrincipalLamports = claim.depositPrincipalLamports;\n let principalSourceCount = 0;\n const principalCandidates = [...position.shards]\n .filter((shard) => shard.status === \"AVAILABLE\" && shard.amountLamports > 0)\n .sort((left, right) => left.shardId.localeCompare(right.shardId));\n for (const shard of principalCandidates) {\n if (remainingPrincipalLamports <= 0) break;\n principalSourceCount += 1;\n remainingPrincipalLamports -= shard.amountLamports;\n }\n const actorRedeemablePrincipalSourceCount =\n position.actorSync?.redeemablePrincipalSourceCount ?? 0;\n if (\n claim.depositPrincipalLamports > 0 &&\n position.actorSync?.redeemableProjectionAvailable === true &&\n actorRedeemablePrincipalLamports >= claim.depositPrincipalLamports &&\n actorRedeemablePrincipalSourceCount > 0\n ) {\n principalSourceCount = actorRedeemablePrincipalSourceCount;\n }\n const observedEarnedFeeSourceCount =\n position.actorSync?.redeemableProjectionAvailable === true\n ? (position.actorSync.redeemableFeeSourceCount ?? 0)\n : position.actorSync?.redeemableFeeSourceCount ||\n position.actorSync?.reimbursementDueSourceCount ||\n 0;\n if (\n claim.earnedFeeLamports > 0 &&\n observedEarnedFeeSourceCount < 1 &&\n claim.allowManyToOne !== true\n ) {\n throw new PolicyValidationError(\n \"INVALID_WITHDRAWAL_PLAN\",\n LP_FEE_SOURCE_COUNT_UNAVAILABLE_MESSAGE,\n );\n }\n const earnedFeeSourceCount =\n claim.earnedFeeLamports > 0 ? Math.max(1, observedEarnedFeeSourceCount) : 0;\n return principalSourceCount + earnedFeeSourceCount;\n}\n\nfunction buildLpRedemptionRecord({\n execution,\n position,\n destinationAddresses,\n acceptedLamports,\n requestedTargetLamports,\n landedBaselineLamports,\n landedFeeBaselineLamports,\n txSignatureBaseline,\n nowMs,\n}: {\n readonly execution: LpWithdrawalExecutionView;\n readonly position: LpPositionView;\n readonly destinationAddresses: readonly string[];\n readonly acceptedLamports: number;\n readonly requestedTargetLamports: number;\n readonly landedBaselineLamports: number;\n readonly landedFeeBaselineLamports: number;\n readonly txSignatureBaseline: readonly string[];\n readonly nowMs: number;\n}): LpWithdrawalRecord {\n return {\n redemptionId: execution.withdrawalId,\n lpPositionId: position.id,\n requestedAt: nowMs,\n status: \"pending\",\n destinationAddresses: [...destinationAddresses],\n acceptedLamports,\n requestedTargetLamports,\n landedBaselineLamports,\n landedFeeBaselineLamports,\n redeemedLamports: 0,\n txSignatures: [...execution.txSignatures],\n txSignatureBaseline: [...txSignatureBaseline],\n };\n}\n\nfunction reconcileLpRedemptionFromActorSync(\n record: LpWithdrawalRecord,\n position: LpPositionView,\n): LpWithdrawalRecord {\n const sync = position.actorSync;\n if (sync === undefined) return record;\n const history = sync.redemptionHistory?.find(\n (candidate) => candidate.redemptionId === record.redemptionId,\n );\n if (history !== undefined) {\n return reconcileLpRedemptionFromHistory(record, history);\n }\n const resolvedLamports =\n sync.withdrawalLandedLamports +\n sync.withdrawalLandedFeeLamports +\n sync.withdrawalCanceledLamports +\n sync.withdrawalNetworkFeeLossLamports;\n const settled =\n sync.withdrawalRequestedLamports >= record.requestedTargetLamports &&\n sync.withdrawalRequestedLamports <= resolvedLamports;\n const redeemedLamports = Math.max(\n sync.withdrawalLandedLamports -\n record.landedBaselineLamports +\n sync.withdrawalLandedFeeLamports -\n (record.landedFeeBaselineLamports ?? 0),\n 0,\n );\n const baselineSignatures = new Set(record.txSignatureBaseline);\n const txSignatures = sync.withdrawalTxHashes.filter(\n (signature) => !baselineSignatures.has(signature),\n );\n if (!settled) return { ...record, redeemedLamports, txSignatures };\n if (redeemedLamports <= 0) {\n return {\n ...record,\n status: \"failed\",\n redeemedLamports,\n txSignatures,\n error: WITHDRAWAL_NO_LAMPORTS_MESSAGE,\n };\n }\n return { ...record, status: \"confirmed\", redeemedLamports, txSignatures };\n}\n\nfunction reconcileLpRedemptionFromHistory(\n record: LpWithdrawalRecord,\n history: LpRedemptionHistoryView,\n): LpWithdrawalRecord {\n const observedStateVersion = record.coordinatorStateVersion ?? 0;\n if (history.stateVersion < observedStateVersion) return record;\n if (\n (record.acceptedLamports !== undefined &&\n history.acceptedLamports !== record.acceptedLamports) ||\n (history.detailsTruncated !== true &&\n !sameStringList(history.destinationAddresses, record.destinationAddresses))\n ) {\n return {\n ...record,\n status: \"failed\",\n coordinatorStateVersion: Math.max(observedStateVersion, history.stateVersion),\n error: WITHDRAWAL_HISTORY_MISMATCH_MESSAGE,\n };\n }\n const txSignatures = uniqueStrings([...record.txSignatures, ...history.txSignatures]);\n const base = {\n ...record,\n coordinatorStateVersion: history.stateVersion,\n redeemedLamports: history.landedLamports,\n txSignatures,\n destinationCount: history.destinationCount,\n txSignatureCount: history.txSignatureCount,\n detailsTruncated: history.detailsTruncated,\n error: undefined,\n };\n if (history.state === \"confirmed\") {\n return history.landedLamports > 0\n ? { ...base, status: \"confirmed\" }\n : { ...base, status: \"failed\", error: WITHDRAWAL_NO_LAMPORTS_MESSAGE };\n }\n if (history.state === \"rejected\") {\n return {\n ...base,\n status: \"failed\",\n error: WITHDRAWAL_NO_LAMPORTS_MESSAGE,\n };\n }\n return {\n ...base,\n status: record.status === \"reconciling\" ? \"reconciling\" : \"pending\",\n };\n}\n\nfunction hydrateLpRedemptionsFromPosition(state: LpLifecycleState, position: LpPositionView): void {\n for (const history of position.actorSync?.redemptionHistory ?? []) {\n const existing = state.redemptions.get(history.redemptionId);\n if (existing === undefined) {\n state.redemptions.set(history.redemptionId, lpWithdrawalRecordFromHistory(position, history));\n continue;\n }\n state.redemptions.set(\n history.redemptionId,\n reconcileLpRedemptionFromHistory(existing, history),\n );\n }\n}\n\nfunction lpWithdrawalRecordFromHistory(\n position: LpPositionView,\n history: LpRedemptionHistoryView,\n): LpWithdrawalRecord {\n const record: LpWithdrawalRecord = {\n redemptionId: history.redemptionId,\n lpPositionId: position.id,\n requestedAt: history.createdAtMs,\n status: \"pending\",\n destinationAddresses: [...history.destinationAddresses],\n acceptedLamports: history.acceptedLamports,\n requestedTargetLamports: history.acceptedLamports,\n landedBaselineLamports: 0,\n landedFeeBaselineLamports: 0,\n redeemedLamports: history.landedLamports,\n txSignatures: [...history.txSignatures],\n txSignatureBaseline: [],\n coordinatorStateVersion: history.stateVersion,\n destinationCount: history.destinationCount,\n txSignatureCount: history.txSignatureCount,\n detailsTruncated: history.detailsTruncated,\n };\n return reconcileLpRedemptionFromHistory(record, history);\n}\n\nfunction sameStringList(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction uniqueStrings(values: readonly string[]): string[] {\n return Array.from(new Set(values));\n}\n\nfunction clonePosition(position: LpPositionView): LpPositionView {\n return {\n ...position,\n shards: position.shards.map((shard) => ({ ...shard })),\n actorSync:\n position.actorSync === undefined\n ? undefined\n : {\n ...position.actorSync,\n redemptionHistory: position.actorSync.redemptionHistory?.map((history) => ({\n ...history,\n destinationAddresses: [...history.destinationAddresses],\n txSignatures: [...history.txSignatures],\n })),\n },\n };\n}\n\nfunction generateId(prefix: string): string {\n return `${prefix}_${Array.from(randomBytes(8))\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\nfunction randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n\nfunction throwIfTopUpWaitAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return;\n throw new DOMException(\"LP top-up wait aborted\", \"AbortError\");\n}\n\nfunction throwIfWithdrawalConfirmationAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return;\n throw new DOMException(\"LP withdrawal confirmation wait aborted\", \"AbortError\");\n}\n\nfunction markLpRedemptionReconciling(\n state: LpLifecycleState,\n record: LpWithdrawalRecord,\n options: WaitForWithdrawalConfirmationOptions,\n): never {\n const reconciling = { ...record, status: \"reconciling\" as const };\n state.redemptions.set(record.redemptionId, reconciling);\n options.onRedemptionUpdate?.(reconciling);\n throw new LpRedemptionReconcilingError();\n}\n\nfunction isLpPositionObservationDeadlineError(\n error: unknown,\n deadlineMs: number,\n nowMs: () => number,\n): boolean {\n return (\n error instanceof CommandError && error.code === \"REJECTED_STALE_JOB\" && nowMs() >= deadlineMs\n );\n}\n\nfunction sleepWithAbort(\n sleep: (delayMs: number) => Promise<void>,\n delayMs: number,\n signal: AbortSignal | undefined,\n): Promise<void> {\n if (signal === undefined) return sleep(delayMs);\n throwIfWithdrawalConfirmationAborted(signal);\n return new Promise((resolve, reject) => {\n const onAbort = () =>\n reject(new DOMException(\"LP withdrawal confirmation wait aborted\", \"AbortError\"));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n void sleep(delayMs)\n .then(resolve, reject)\n .finally(() => {\n signal.removeEventListener(\"abort\", onAbort);\n });\n });\n}\n\nfunction defaultSleep(delayMs: number): Promise<void> {\n return new Promise((resolve) => {\n globalThis.setTimeout(resolve, delayMs);\n });\n}\n","/**\n * `@invisible-labs/sdk/lp` - liquidity-provider lifecycle (spec section 4.4).\n *\n * The high-level lifecycle functions own LP position auth, DKG completion,\n * initial funding selection, refill, withdrawal, and actor-sync confirmation.\n * Importing this module must not pull in `/user`, `/stats`, or `/events`.\n */\n\nimport type { Session } from \"../core/session.js\";\nimport { publicKey } from \"../core/brands.js\";\nimport { assertAttested } from \"../session/guards.js\";\nimport {\n defaultLpLifecycleClient,\n type CompleteDkgBatchOptions,\n type CreatePositionArgs,\n type CreatePositionResult,\n type InitialFundingPlan,\n type LpTopUpRequest,\n type RefillArgs,\n type RecoverPositionArgs,\n type WaitForTopUpOptions,\n type WaitForWithdrawalConfirmationOptions,\n type WithdrawalConfirmation,\n type WithdrawalExecution,\n type WithdrawPositionArgs,\n type WithdrawPositionResult,\n} from \"./lifecycle.js\";\n\nexport {\n createLpCoordinatorClient,\n LP_COMMAND_REQUEST_TIMEOUT_MS,\n LP_DKG_ABORT_REQUEST_TIMEOUT_MS,\n} from \"./coordinatorClient.js\";\nexport {\n createLpDkgBatch,\n LP_DKG_ABORT_CLEANUP_TIMEOUT_MS,\n LP_DKG_WORKER_REQUEST_TIMEOUT_MESSAGE,\n LP_DKG_WORKER_REQUEST_TIMEOUT_MS,\n type CreateLpDkgBatchInput,\n type LpDkgProgress,\n} from \"./dkgBatch.js\";\nexport {\n createLpLifecycleClient,\n defaultLpLifecycleClient,\n isLpPositionAuthMissingError,\n isLpRedemptionReconcilingError,\n LP_FEE_SOURCE_COUNT_UNAVAILABLE_MESSAGE,\n LP_MISSING_POSITION_CODE_MESSAGE,\n LP_REDEMPTION_RECONCILING_MESSAGE,\n previewLpWithdrawalPlan,\n type CompleteDkgBatchOptions,\n type CreatePositionArgs,\n type CreatePositionResult,\n type InitialFundingPlan,\n type LpLifecycleClient,\n type LpLifecycleDkgProgress,\n type LpLifecycleRuntime,\n type LpTopUpRequest,\n type LpWithdrawalPlanPreview,\n type LpWithdrawalPlanPreviewArgs,\n type LpWithdrawalRecord,\n type RefillArgs,\n type RecoverPositionArgs,\n type WaitForTopUpOptions,\n type WaitForWithdrawalConfirmationOptions,\n type WithdrawalConfirmation,\n type WithdrawalExecution,\n type WithdrawPositionArgs,\n type WithdrawPositionResult,\n} from \"./lifecycle.js\";\nexport {\n bytesToHex,\n deriveLpPositionCodeAuth,\n generateLpPositionCode,\n normalizeLpPositionCode,\n signLpCommandBytes,\n type LpPositionCode,\n type LpPositionCodeAuth,\n} from \"./positionCode.js\";\nexport type {\n FinalizeLpDkgBatchInput,\n FundingConfirmationInput,\n LpActorSyncView,\n LpCoordinatorClient,\n LpDkgClient,\n LpInventoryShard,\n LpPositionRequestOptions,\n LpRedemptionHistoryView,\n LpPositionView,\n LpWithdrawalExecutionView,\n LpWithdrawalMode,\n OpenLpPositionInput,\n RefillLpPositionInput,\n SourceLiquidityUse,\n} from \"./types.js\";\n\nexport function createPosition(\n session: Session,\n args: CreatePositionArgs = {},\n): Promise<CreatePositionResult> {\n return defaultLpLifecycleClient(session).createPosition(args);\n}\n\nexport function recoverPosition(\n session: Session,\n args: RecoverPositionArgs,\n): Promise<import(\"./types.js\").LpPositionView> {\n return defaultLpLifecycleClient(session).recoverPosition(args);\n}\n\nexport function confirmPositionCodeSaved(session: Session, positionId: string): void {\n defaultLpLifecycleClient(session).confirmPositionCodeSaved(positionId);\n}\n\nexport async function completeDkgBatch(\n session: Session,\n positionId: string,\n opts: CompleteDkgBatchOptions = {},\n): Promise<import(\"./types.js\").LpPositionView> {\n return await defaultLpLifecycleClient(session).completeDkgBatch(positionId, opts);\n}\n\nexport function refreshPosition(\n session: Session,\n positionId: string,\n): Promise<import(\"./types.js\").LpPositionView> {\n return defaultLpLifecycleClient(session).refreshPosition(positionId);\n}\n\nexport function refill(\n session: Session,\n positionId: string,\n args: RefillArgs = {},\n): Promise<import(\"./types.js\").LpPositionView> {\n return defaultLpLifecycleClient(session).refill(positionId, args);\n}\n\nexport function prepareInitialFunding(\n session: Session,\n positionId: string,\n): Promise<InitialFundingPlan | null> {\n return defaultLpLifecycleClient(session).prepareInitialFunding(positionId);\n}\n\nexport function prepareTopUp(session: Session, positionId: string): Promise<LpTopUpRequest> {\n return defaultLpLifecycleClient(session).prepareTopUp(positionId);\n}\n\nexport function waitForTopUp(\n session: Session,\n topUpId: string,\n options: WaitForTopUpOptions = {},\n): Promise<LpTopUpRequest> {\n return defaultLpLifecycleClient(session).waitForTopUp(topUpId, options);\n}\n\nexport function reconcileFunding(\n session: Session,\n positionId: string,\n): Promise<import(\"./types.js\").LpPositionView> {\n return defaultLpLifecycleClient(session).reconcileFunding(positionId);\n}\n\nexport function withdrawPosition(\n session: Session,\n positionId: string,\n args: WithdrawPositionArgs,\n): Promise<WithdrawPositionResult> {\n return defaultLpLifecycleClient(session).withdrawPosition(positionId, args);\n}\n\nexport function waitForWithdrawalConfirmation(\n session: Session,\n positionId: string,\n execution: WithdrawalExecution,\n options: WaitForWithdrawalConfirmationOptions = {},\n): Promise<WithdrawalConfirmation> {\n return defaultLpLifecycleClient(session).waitForWithdrawalConfirmation(\n positionId,\n execution,\n options,\n );\n}\n\n/**\n * LP fee withdrawal is coordinator-pending. The SDK validates the local input\n * and returns a typed `VERSION_NOT_SUPPORTED` routing error until advertised.\n */\nexport async function withdrawFees(\n session: Session,\n positionId: string,\n args: { readonly destination: string },\n): Promise<never> {\n publicKey(args.destination);\n assertAttested(session);\n return await defaultLpLifecycleClient(session).withdrawFees(positionId, args);\n}\n\nexport function listPositions(session: Session): Promise<import(\"./types.js\").LpPositionView[]> {\n return defaultLpLifecycleClient(session).listPositions();\n}\n"]}
|