@invisi-labs/sdk 1.2.0 → 1.2.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/protocol/AddressRegistry.ts","../src/transactions/signing/revocation.ts","../src/transactions/records.ts","../src/transactions/preparation/inputs.ts","../src/gas/gas-estimation.ts","../src/transactions/proving/proof.ts","../src/transactions/proving/proof-integrity.ts","../src/transactions/execution/calldata.ts","../src/transactions/proving/witness.ts","../src/transactions/signing/funding.ts","../src/transactions/execution/operation-execution.ts","../src/transactions/execution/operation-preview.ts","../src/transactions/execution/PreparedTransaction.ts","../src/client/infrastructure.ts","../src/client/Invisi.ts","../src/transactions/preparation/explicit-preparation.ts","../src/discovery/protocol-events.ts","../src/discovery/receipt-logs.ts","../src/discovery/discovery.ts"],"sourcesContent":["import { AddressRegistry as Registry, type RegistrationPreparation } from \"@invisi-labs/rpc\";\nimport type { Provider } from \"ethers\";\nimport { prepareWithErrors } from \"../errors\";\nimport { EthersChainReader } from \"../integrations/ethers\";\n\n/** Registry operations accept the application's existing ethers provider. */\nexport class AddressRegistry extends Registry {\n override prepareRegistration(\n options:\n | RegistrationPreparation\n | (Omit<RegistrationPreparation, \"reader\"> & { provider: Provider })\n ) {\n return prepareWithErrors(\"prepareRegistration\", async () => {\n if (\"provider\" in options) {\n const { provider, ...preparation } = options;\n return super.prepareRegistration({\n ...preparation,\n reader: new EthersChainReader(provider),\n });\n }\n return super.prepareRegistration(options);\n });\n }\n}\n","import { createSigningRequest } from \"@invisi-labs/primitives\";\nimport { encodeRevokeCreditTypedData } from \"@invisi-labs/protocol\";\nimport { getAddress, verifyTypedData } from \"ethers\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport type { OperationPlan, TransactionRuntime } from \"../operation-types\";\nexport async function revocationSigningRequest(\n plan: OperationPlan,\n runtime: Pick<TransactionRuntime, \"reader\" | \"options\">\n) {\n const params = plan.credit?.revocation;\n if (!params) throw Error(\"operation is not a public Credit revocation\");\n await runtime.options.protocol.validateDeployment(runtime.reader);\n const block = await runtime.reader.getBlock(await runtime.reader.getLatestBlockNumber());\n if (block.timestamp > params.deadline) throw Error(\"revocation authorization expired\");\n const request = createSigningRequest(\n encodeRevokeCreditTypedData({ ...plan.context, now: block.timestamp }, params)\n );\n if ((await runtime.reader.getBlock(block.number)).hash !== block.hash)\n throw Error(\"canonical revocation block changed\");\n return request;\n}\nexport async function acceptRevocationSignature(\n plan: OperationPlan,\n signature: Hex,\n runtime: Pick<TransactionRuntime, \"reader\" | \"options\">\n) {\n if (!/^0x(?:[0-9a-fA-F]{2})+$/.test(signature)) throw Error(\"invalid revocation signature\");\n const request = await revocationSigningRequest(plan, runtime),\n owner = plan.credit!.revocation!.owner;\n let valid = false;\n try {\n valid =\n getAddress(\n verifyTypedData(request.domain, request.types, request.message, signature)\n ) === getAddress(owner);\n } catch {}\n if (!valid && runtime.options.fundingVerifier)\n valid = await runtime.options.fundingVerifier.verifyTypedData({\n ...request,\n address: owner,\n signature,\n });\n if (!valid) throw Error(\"invalid owner revocation signature\");\n return signature;\n}\n","import type { CreditDeliveryState, Note } from \"@invisi-labs/primitives\";\nimport type { Hex } from \"@invisi-labs/prover\";\n\nexport interface WalletScope {\n namespace: string;\n chainId: bigint;\n protocolAddress: Hex;\n ownerAddress: Hex;\n}\n\nexport function creditReservationKey(commitment: string): string {\n return \"credit:\" + commitment;\n}\n\nexport interface Checkpoint {\n number: bigint;\n hash: Hex;\n}\n\nexport type SpentState = \"unknown\" | \"unspent\" | \"spent\";\n\nexport interface ReceiptPosition {\n commitment: Hex;\n treeId: bigint;\n leafIndex: number;\n blockNumber: bigint;\n blockHash: Hex;\n transactionHash?: Hex;\n}\n\nexport interface NoteRecord extends ReceiptPosition {\n note: Note;\n spent: SpentState;\n checkedThrough?: Checkpoint;\n}\n\nexport interface CreditRecord extends ReceiptPosition {\n receivingKeySource?: { kind: \"draw\" | \"update\"; commitment: Hex };\n revoked?: boolean;\n state: CreditDeliveryState;\n role: \"owner\" | \"spender\";\n spent: SpentState;\n checkedThrough?: Checkpoint;\n}\n\nexport type OperationStatus =\n | \"prepared\"\n | \"authorized\"\n | \"proved\"\n | \"ready\"\n | \"submitted\"\n | \"confirmed\"\n | \"failed\"\n | \"expired\"\n | \"uncertain\"\n | \"reorged\";\n","import type { Hex, InputSource } from \"@invisi-labs/protocol/contracts\";\nimport type { OperationPlan } from \"../operation-types\";\nimport { creditReservationKey } from \"../records\";\n\nexport function inputFacts(\n plan: OperationPlan\n): Array<{ key: string; reservationKey: string; nullifier: Hex; kind: \"notes\" | \"credits\" }> {\n const credit = plan.credit;\n const noteNullifiers = plan.params?.nullifiers ?? [];\n let creditNullifiers: readonly Hex[] = [];\n\n if (credit?.draw) {\n creditNullifiers = credit.draw.nullifiers;\n } else if (credit?.update) {\n creditNullifiers = [credit.update.nullifier];\n }\n\n if (\n noteNullifiers.length !== plan.inputs.length ||\n creditNullifiers.length !== (credit?.inputs.length ?? 0)\n ) {\n throw new Error(\"operation input statement count mismatch\");\n }\n\n return [\n ...plan.inputs.map((input, index) => ({\n key: input.commitment,\n reservationKey: input.commitment,\n nullifier: noteNullifiers[index]!,\n kind: \"notes\" as const,\n })),\n ...(credit?.inputs ?? []).map((input, index) => ({\n key: input.commitment + \":\" + input.role,\n reservationKey: creditReservationKey(input.commitment),\n nullifier: creditNullifiers[index]!,\n kind: \"credits\" as const,\n })),\n ];\n}\n\nexport function operationSources(plan: OperationPlan): readonly InputSource[] {\n const noteSources = plan.params?.sources;\n if (noteSources != null) return noteSources;\n\n const credit = plan.credit;\n if (credit?.draw) return credit.draw.sources;\n if (credit?.update) return [credit.update.source];\n return [];\n}\n","import type { TokenProtocol } from \"@invisi-labs/rpc\";\nimport type { OperationPlan } from \"../transactions/operation-types\";\nimport { getDocumentedGasReference, type DocumentedGasShape } from \"@invisi-labs/protocol\";\nimport { operationSources } from \"../transactions/preparation/inputs\";\n/** A pre-proof documented scenario reference; conditions remain visible in the result. */\nexport function getOperationGasReference(plan: OperationPlan, _protocol?: TokenProtocol) {\n let query: DocumentedGasShape = { kind: plan.kind };\n const credit = plan.credit;\n if (plan.statement?.target === \"noir-recursive\")\n return getDocumentedGasReference({ kind: \"aggregate\" });\n if (credit?.creation)\n query = { kind: \"create-credit\", scenario: \"first-allocation-empty-tree\" };\n else if (credit?.update)\n query = { kind: \"update-credit\", scenario: \"after-draw-preserve-usage\" };\n else if (credit?.draw)\n query = {\n kind: \"draw-credit\",\n capacity: plan.capacity!,\n creditInputs: credit.inputs.length,\n distinctPayers: credit.draw.payers.length,\n sourceTrees: operationSources(plan).length,\n noteOutputs: 1,\n creditOutputs: credit.outputs.length,\n creditCiphertextBytes: 485,\n noteCiphertextBytes: 160,\n clueBytes: 68,\n scenario: \"distinct-payers\",\n };\n else if (plan.kind === \"transfer\")\n query = {\n kind: \"transact\",\n capacity: plan.capacity!,\n noteInputs: plan.inputs.length,\n noteOutputs: plan.outputs.length,\n sourceTrees: operationSources(plan).length,\n noteCiphertextBytes: 160,\n clueBytes: 68,\n scenario: !plan.inputs.length\n ? \"public-funding\"\n : !plan.outputs.length\n ? \"withdrawal\"\n : !(plan.funding.amount ?? 0n) &&\n !(plan.params?.withdrawalAmount ?? 0n) &&\n !(plan.params?.feeAmount ?? 0n)\n ? \"private\"\n : \"mixed\",\n };\n if (credit) {\n const feeAmount =\n credit.creation?.feeAmount ??\n credit.update?.feeAmount ??\n credit.draw?.feeAmount ??\n credit.revocation?.feeAmount ??\n 0n;\n query = {\n ...query,\n feeEnabled: feeAmount > 0n,\n feeMechanism: feeAmount > 0n ? (credit.draw ? \"draw-deduction\" : \"owner-pull\") : \"none\",\n };\n }\n if (\n plan.outputs.some((o) => (o.delivery.ciphertext.length - 2) / 2 !== 160) ||\n credit?.outputs.some((o) => o.deliveries.some((d) => (d.ciphertext.length - 2) / 2 !== 485))\n )\n return getDocumentedGasReference({ kind: \"unmeasured-delivery-size\" });\n return getDocumentedGasReference(query);\n}\nexport { getDocumentedGasReference } from \"@invisi-labs/protocol\";\nexport type { DocumentedGasReference, DocumentedGasShape } from \"@invisi-labs/protocol\";\n","import type { ProofBundle } from \"@invisi-labs/prover\";\n\n/** Whitelist the public proof fields; a custom local backend cannot accidentally export its witness. */\nexport function publicProof(bundle: ProofBundle): ProofBundle {\n return {\n formatVersion: bundle.formatVersion,\n circuitName: bundle.circuitName,\n target: bundle.target,\n bbVersion: bundle.bbVersion,\n artifactSha256: bundle.artifactSha256,\n vkSha256: bundle.vkSha256,\n proofHex: bundle.proofHex,\n proofSha256: bundle.proofSha256,\n publicInputs: [...bundle.publicInputs],\n };\n}\n","import type { ProofBundle, ProofStatement } from \"@invisi-labs/prover\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { bytesToHex } from \"@noble/hashes/utils\";\nimport { getBytes } from \"ethers\";\nfunction check(ok: unknown, message: string): asserts ok {\n if (!ok) throw new Error(message);\n}\nexport function sameStatement(proof: ProofBundle, expected: ProofStatement): void {\n check(\n proof.formatVersion === 1 &&\n proof.bbVersion === \"6.0.0\" &&\n proof.circuitName === expected.circuitName &&\n proof.target === expected.target &&\n proof.artifactSha256 === expected.artifactSha256 &&\n proof.vkSha256 === expected.vkSha256,\n \"proof release/target mismatch\"\n );\n check(\n proof.publicInputs.length === expected.expectedPublicInputs.length &&\n proof.publicInputs.every((word, i) => word === expected.expectedPublicInputs[i]),\n \"proof public statement mismatch\"\n );\n check(\n /^0x(?:[a-fA-F0-9]{2})+$/.test(proof.proofHex) &&\n bytesToHex(sha256(getBytes(proof.proofHex))) === proof.proofSha256,\n \"proof integrity mismatch\"\n );\n}\n","import {\n buildRevokeCreditCalldata,\n buildCreateCreditCalldata,\n buildCreditDrawCalldata,\n buildShieldCalldata,\n buildUpdateCreditCalldata,\n buildTransactCalldata,\n type TransactionCall,\n} from \"@invisi-labs/protocol\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport type { SavedOperation } from \"../operation-types\";\n\nexport async function encodeOperation(saved: SavedOperation): Promise<TransactionCall> {\n const plan = saved.plan;\n const credit = plan.credit;\n const caller = plan.fundingMode === \"caller\" ? plan.funding.payer : undefined;\n const common = { context: plan.context, proof: saved.proof?.proofHex ?? (\"0x\" as Hex) };\n const funded = { ...common, funding: plan.funding, ...(caller ? { caller } : {}) };\n\n let encoded: { data: Hex };\n if (credit?.update) {\n encoded = buildUpdateCreditCalldata({\n ...funded,\n params: credit.update,\n deliveries: credit.deliveries,\n });\n } else if (credit?.creation) {\n encoded = buildCreateCreditCalldata({\n ...funded,\n params: credit.creation,\n deliveries: credit.deliveries,\n });\n } else if (credit?.draw) {\n encoded = buildCreditDrawCalldata({\n ...common,\n params: credit.draw,\n deliveries: credit.deliveries,\n });\n } else if (credit?.revocation) {\n encoded = buildRevokeCreditCalldata({\n context: plan.context,\n params: credit.revocation,\n signature: credit.revocationSignature ?? \"0x\",\n ...(credit.revocationCaller ? { caller: credit.revocationCaller } : {}),\n });\n } else if (plan.kind === \"shield\") {\n encoded = await buildShieldCalldata({\n ...funded,\n params: plan.shieldParams!,\n outputs: plan.shieldOutputs!,\n deliveries: plan.outputs.map((output) => output.delivery),\n });\n } else {\n encoded = buildTransactCalldata({\n ...funded,\n params: plan.params!,\n deliveries: plan.outputs.map((output) => output.delivery),\n });\n }\n\n return { to: plan.context.protocolAddress, data: encoded.data, value: 0n };\n}\n","import { assertCreditUpdatePlan } from \"../../credit/state\";\nimport { type AuthorizedStatement } from \"@invisi-labs/primitives\";\nimport { WitnessBuilder } from \"@invisi-labs/prover\";\nimport { type TokenProtocol } from \"@invisi-labs/rpc\";\nimport type { ProvingRequest } from \"@invisi-labs/prover\";\nimport type { OperationPlan } from \"../operation-types\";\n\nexport async function witnessFor(\n protocol: TokenProtocol,\n plan: OperationPlan,\n authorization?: AuthorizedStatement\n): Promise<ProvingRequest> {\n const builder = new WitnessBuilder(protocol);\n const credit = plan.credit;\n\n if (credit) {\n if (!authorization) throw new Error(\"private Credit wallet authorization required\");\n\n if (credit.update) {\n await assertCreditUpdatePlan(plan);\n if (!credit.updateChanges) throw Error(\"Credit update adjustment required\");\n return builder.updateCredit({\n params: credit.update,\n deliveries: credit.deliveries,\n input: credit.inputs[0]!,\n state: credit.outputs[0]!.state,\n changes: credit.updateChanges,\n authorization,\n });\n }\n if (credit.creation)\n return builder.createCredit({\n params: credit.creation,\n deliveries: credit.deliveries,\n state: credit.outputs[0]!.state,\n authorization,\n });\n if (credit.draw) {\n return builder.drawCredit({\n timestamp: plan.preparedAt.timestamp,\n params: credit.draw,\n deliveries: credit.deliveries,\n inputs: credit.inputs,\n amounts: credit.amounts!,\n output: plan.outputs[0]!.note!,\n authorization,\n });\n }\n throw new Error(\"unsupported Credit operation\");\n }\n\n return builder.transact({\n params: plan.params!,\n deliveries: plan.outputs.map((output) => output.delivery),\n funding: plan.funding,\n inputs: plan.inputs,\n outputs: plan.outputs.map((output) => ({\n identity: output.identity,\n amount: output.amount,\n ...(output.note ? { note: output.note } : {}),\n })),\n ...(authorization ? { authorization } : {}),\n target: plan.statement!.target,\n });\n}\n","import {\n encodeAggregateFundingTypedData,\n encodeShieldFundingTypedData,\n encodeTransactFundingTypedData,\n} from \"@invisi-labs/protocol\";\nimport type { SavedOperation } from \"../operation-types\";\n\nexport async function fundingTypedData(saved: SavedOperation) {\n const plan = saved.plan;\n if (plan.credit) throw Error(\"Credit operations have no funding authorization\");\n if (plan.kind === \"shield\") {\n return encodeShieldFundingTypedData({\n context: plan.context,\n params: plan.shieldParams!,\n outputs: plan.shieldOutputs!,\n deliveries: plan.outputs.map((output) => output.delivery),\n funding: plan.funding,\n });\n }\n if (plan.statement?.target === \"noir-recursive\") {\n return encodeAggregateFundingTypedData(plan.context, {\n params: plan.params!,\n deliveries: plan.outputs.map((output) => output.delivery),\n funding: plan.funding,\n });\n }\n return encodeTransactFundingTypedData(\n plan.context,\n saved.proof!.proofHex,\n plan.params!,\n plan.outputs.map((output) => output.delivery),\n plan.funding\n );\n}\n","import {\n AuthorizedStatement,\n computeOwnerAddress,\n computeWalletAuthorizationDigest,\n createSigningRequest,\n walletAuthorizationTypedData,\n} from \"@invisi-labs/primitives\";\nimport { WitnessBuilder } from \"@invisi-labs/prover\";\nimport { type TokenProtocol } from \"@invisi-labs/rpc\";\nimport type { Prover } from \"@invisi-labs/prover\";\nimport { Signature, SigningKey, concat, getBytes, verifyTypedData } from \"ethers\";\nimport type {\n FundingAuthorizationVerifier,\n FundingSigner,\n FundingTypedData,\n OperationPlan,\n SavedOperation,\n TransactionProveOptions,\n TransactionRuntime,\n} from \"../operation-types\";\nimport { publicProof } from \"../proving/proof\";\nimport { sameStatement } from \"../proving/proof-integrity\";\nimport { witnessFor } from \"../proving/witness\";\nimport { fundingTypedData } from \"../signing/funding\";\nimport { authorizationRequest, statement } from \"../signing/statement\";\n\nexport async function proveOperation(\n protocol: TokenProtocol,\n plan: OperationPlan,\n authorization: AuthorizedStatement | undefined,\n prover: Prover,\n options: TransactionProveOptions\n) {\n if (Object.hasOwn(options, \"target\")) {\n throw new Error(\"prove accepts execution, not a backend target\");\n }\n const { execution = \"single\", ...proverOptions } = options;\n if (execution !== \"single\" && execution !== \"aggregate\") {\n throw new Error(\"execution must be single or aggregate\");\n }\n const frozen = statement(plan);\n if (\n execution === \"aggregate\" &&\n (plan.kind !== \"transfer\" || !plan.capacity || plan.capacity > 10)\n ) {\n throw new Error(\"aggregate execution requires a C1..C10 transfer\");\n }\n if (plan.kind === \"transfer\") {\n // Only the proof backend/key changes; public words and wallet authorization stay fixed.\n plan.statement = WitnessBuilder.statement(\n frozen.circuitName,\n frozen.expectedPublicInputs,\n execution === \"aggregate\" ? \"noir-recursive\" : \"evm\"\n );\n }\n const request = await witnessFor(protocol, plan, authorization);\n if (JSON.stringify({ ...request, witness: undefined }) !== JSON.stringify(plan.statement))\n throw new Error(\"prepared proof statement changed\");\n try {\n const proof = publicProof(await prover.prove(request, proverOptions));\n sameStatement(proof, plan.statement!);\n if (\n (await prover.verify(\n structuredClone(proof),\n structuredClone(plan.statement!),\n proverOptions\n )) !== true\n )\n throw new Error(\"proof verification failed\");\n return proof;\n } catch {\n options.signal?.throwIfAborted();\n throw new Error(\"operation proof generation or verification failed\");\n }\n}\n\nexport async function signOperationFunding(\n saved: SavedOperation,\n signer: FundingSigner,\n verifier?: FundingAuthorizationVerifier\n) {\n const payer = saved.plan.funding.payer!;\n if (signer.address.toLowerCase() !== payer.toLowerCase())\n throw new Error(\"funding signer is not the payer\");\n const typed = await fundingTypedData(saved);\n const signature = await signer.signTypedData(structuredClone(typed));\n return verifyFundingSignature(typed, payer, signature, verifier);\n}\n\n/** Export only typed commitments, never private note openings or authorization witnesses. */\nexport function walletSigningRequest(plan: OperationPlan) {\n return createSigningRequest(walletAuthorizationTypedData(authorizationRequest(plan)));\n}\n\n/** Recover the EOA key and build the existing private witness without receiving a private key. */\nexport async function acceptWalletSignature(plan: OperationPlan, signature: string) {\n const request = authorizationRequest(plan);\n const digest = computeWalletAuthorizationDigest(request);\n try {\n const signed = Signature.from(signature);\n const publicKey = getBytes(SigningKey.recoverPublicKey(digest, signed));\n const owner = await computeOwnerAddress(publicKey);\n if (owner.toLowerCase() !== plan.scope.ownerAddress.toLowerCase()) {\n throw new Error(\"wallet signature identity mismatch\");\n }\n return new AuthorizedStatement(plan.scope.ownerAddress, digest, {\n public_key_x: Array.from(publicKey.slice(1, 33)),\n public_key_y: Array.from(publicKey.slice(33)),\n signature: Array.from(getBytes(concat([signed.r, signed.s]))),\n });\n } catch {\n throw new Error(\"invalid wallet authorization signature\");\n }\n}\n\n/** The remote round trip may outlive the nonce or deadline selected during preparation. */\nexport async function fundingSigningRequest(\n saved: SavedOperation,\n runtime: Pick<TransactionRuntime, \"reader\" | \"options\">\n) {\n const plan = saved.plan;\n if (plan.fundingMode !== \"signature\") {\n throw new Error(\"operation does not require a funding signature\");\n }\n if (plan.kind !== \"shield\" && !saved.proof) {\n throw new Error(\"proof must precede funding authorization\");\n }\n await runtime.options.protocol.validateDeployment(runtime.reader);\n const block = await runtime.reader.getBlock(await runtime.reader.getLatestBlockNumber());\n if (block.timestamp > plan.deadline || block.timestamp > (plan.funding.deadline ?? 0n)) {\n throw new Error(\"funding authorization expired\");\n }\n if (\n (await runtime.reader.getFundingNonce(plan.context, plan.funding.payer!, block)) !==\n plan.funding.sigNonce\n ) {\n throw new Error(\"funding nonce changed; prepare again\");\n }\n const request = createSigningRequest(await fundingTypedData(saved));\n if ((await runtime.reader.getBlock(block.number)).hash !== block.hash) {\n throw new Error(\"canonical funding block changed\");\n }\n return request;\n}\n\n/** Verify against reconstructed operation data, never caller-supplied typed data. */\nexport async function acceptFundingSignature(\n saved: SavedOperation,\n signature: string,\n runtime: Pick<TransactionRuntime, \"reader\" | \"options\">\n) {\n if (!/^0x(?:[a-fA-F0-9]{2})+$/.test(signature)) {\n throw new Error(\"invalid EVM funding signature\");\n }\n const request = await fundingSigningRequest(saved, runtime);\n return verifyFundingSignature(\n request,\n saved.plan.funding.payer!,\n signature,\n runtime.options.fundingVerifier\n );\n}\n\nasync function verifyFundingSignature(\n request: FundingTypedData,\n payer: `0x${string}`,\n signature: string,\n verifier?: FundingAuthorizationVerifier\n) {\n if (!/^0x(?:[a-fA-F0-9]{2})+$/.test(signature)) {\n throw new Error(\"invalid EVM funding signature\");\n }\n const types = Object.fromEntries(\n Object.entries(request.types).map(([name, fields]) => [name, [...fields]])\n );\n let validEOA = false;\n try {\n validEOA =\n verifyTypedData(request.domain, types, request.message, signature).toLowerCase() ===\n payer.toLowerCase();\n if (validEOA) {\n // Normalize EIP-2098 and parity-style EOA signatures for Solidity SignatureChecker.\n signature = Signature.from(signature).serialized;\n }\n } catch {\n validEOA = false;\n }\n const valid = verifier\n ? await verifier.verifyTypedData({\n ...structuredClone(request),\n address: payer,\n signature: signature as `0x${string}`,\n })\n : validEOA;\n if (valid !== true) {\n throw new Error(\"invalid EVM funding signature\");\n }\n return signature as `0x${string}`;\n}\n","import { normalizeCreditPolicy, normalizeCreditUsage } from \"@invisi-labs/primitives\";\nimport { normalizeFunding } from \"@invisi-labs/protocol\";\nimport type { OperationPlan } from \"../operation-types\";\nimport { inputFacts } from \"../preparation/inputs\";\nimport type { OperationStatus } from \"../records\";\nimport { requiresAuthorization } from \"../signing/statement\";\nexport function operationPreview(plan: OperationPlan, status: OperationStatus) {\n const p = plan;\n const fee =\n p.params ??\n p.shieldParams ??\n p.credit?.creation ??\n p.credit?.update ??\n p.credit?.draw ??\n p.credit?.revocation;\n const funding = normalizeFunding(p.funding);\n return {\n id: p.id,\n kind: p.kind,\n status,\n context: { ...p.context },\n inputs: inputFacts(p).length,\n inputDetails: [\n ...p.inputs.map((input) => ({\n kind: \"notes\" as const,\n commitment: input.commitment,\n amount: input.note.amount,\n owner: input.note.ownerAddress,\n treeId: input.treeId,\n leafIndex: input.leafIndex,\n })),\n ...(p.credit?.inputs ?? []).map((input) => ({\n kind: \"credits\" as const,\n commitment: input.commitment,\n revocationShard: input.state.note.revocationShard,\n revocationSlot: input.state.note.revocationSlot,\n owner: input.state.note.ownerWalletIdentity,\n spender: input.state.note.spenderWalletIdentity,\n expiry: input.state.note.expiry,\n availableCredit: input.state.note.availableCredit,\n unlimited: input.state.note.unlimited,\n role: input.role,\n treeId: input.treeId,\n leafIndex: input.leafIndex,\n })),\n ],\n funding: {\n payer: funding.payer,\n amount: funding.amount,\n authorization: p.fundingMode,\n sigNonce: funding.sigNonce,\n deadline: funding.deadline,\n permit: { deadline: funding.permit.deadline },\n },\n creditOutputs: p.credit?.outputs.map((output) => ({\n commitment: output.commitment,\n revocationShard: output.state.note.revocationShard,\n revocationSlot: output.state.note.revocationSlot,\n expiry: output.state.note.expiry,\n owner: output.state.note.ownerWalletIdentity,\n spender: output.state.note.spenderWalletIdentity,\n ...normalizeCreditPolicy(output.state.note),\n availableCredit: output.state.note.availableCredit,\n unlimited: output.state.note.unlimited,\n ...normalizeCreditUsage(output.state.note),\n })),\n creditUpdate: p.credit?.updateChanges ? structuredClone(p.credit.updateChanges) : undefined,\n creditDraw: p.credit?.draw\n ? {\n grossAmount: p.credit.draw.totalAmount,\n feeAmount: p.credit.draw.feeAmount ?? 0n,\n netAmount: p.credit.draw.totalAmount - (p.credit.draw.feeAmount ?? 0n),\n payers: p.credit.draw.payers.map((payer) => ({ ...payer })),\n }\n : undefined,\n creditFeePayer:\n p.credit?.creation?.owner ?? p.credit?.update?.owner ?? p.credit?.revocation?.owner,\n outputs: p.outputs.map((output) => ({\n commitment: output.commitment,\n to: output.address,\n amount: output.amount,\n change: output.change,\n })),\n capacity: p.capacity,\n deadline: p.deadline,\n feeRecipient: fee?.feeRecipient,\n feeAmount: fee?.feeAmount ?? 0n,\n fundingAmount: p.funding.amount ?? 0n,\n fundingPayer: p.funding.payer,\n withdrawalAmount: p.params?.withdrawalAmount ?? 0n,\n withdrawalAddress: p.params?.withdrawalAddress,\n permissions: {\n walletAuthorization: requiresAuthorization(p),\n proof: p.kind !== \"shield\" && p.kind !== \"revoke-credit\",\n fundingAuthorization: p.fundingMode === \"signature\",\n },\n };\n}\n","import { bindBroadcasterOperation } from \"../../broadcaster/operation-bridge\";\nimport {\n Wallet,\n prepareWalletRequest,\n acceptWalletResponse,\n type PreparedWalletRequest,\n type WalletResponse,\n} from \"@invisi-labs/primitives\";\nimport { revocationSigningRequest, acceptRevocationSignature } from \"../signing/revocation\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport { TransactionOutput } from \"../../notes/TransactionOutput\";\nimport { MissingCapabilityError, type AuthorizedStatement } from \"@invisi-labs/primitives\";\nimport { normalizeFunding, type TransactionCall } from \"@invisi-labs/protocol\";\nimport type { ProofBundle, Prover } from \"@invisi-labs/prover\";\nimport { exportBroadcasterIntent } from \"../../broadcaster/intent\";\nimport { getOperationGasReference } from \"../../gas/gas-estimation\";\nimport type {\n OperationAggregateMember,\n OperationPlan,\n SavedOperation,\n TransactionProveOptions,\n TransactionRuntime,\n} from \"../operation-types\";\nimport { publicProof } from \"../proving/proof\";\nimport { sameStatement } from \"../proving/proof-integrity\";\nimport type { OperationStatus } from \"../records\";\nimport { authorizationRequest, requiresAuthorization, statement } from \"../signing/statement\";\nimport { encodeOperation } from \"./calldata\";\nimport {\n acceptFundingSignature,\n acceptWalletSignature,\n fundingSigningRequest,\n proveOperation,\n walletSigningRequest,\n} from \"./operation-execution\";\nimport { operationPreview } from \"./operation-preview\";\nfunction check(ok: unknown, message: string): asserts ok {\n if (!ok) throw new Error(message);\n}\n\ntype Runtime = TransactionRuntime & {\n reprepare?: (\n intent: import(\"../../broadcaster/broadcaster-preparation\").PreparationIntent\n ) => Promise<OperationPlan>;\n};\ntype Lifecycle = { generation: number; busy: boolean };\n/** An immutable, local transaction handle. No wallet inventory, reservations or persistence. */\nexport class PreparedTransaction {\n readonly #runtime: Runtime;\n readonly #saved: SavedOperation;\n readonly #authorization: AuthorizedStatement | undefined;\n readonly #walletRequests = new Map<string, PreparedWalletRequest<\"wallet.authorize\">>();\n readonly #lifecycle: Lifecycle;\n readonly status: OperationStatus;\n private constructor(\n runtime: Runtime,\n saved: SavedOperation,\n status: OperationStatus,\n lifecycle: Lifecycle,\n authorization?: AuthorizedStatement\n ) {\n this.#runtime = runtime;\n this.#saved = structuredClone(saved);\n this.#lifecycle = lifecycle;\n this.#authorization = authorization;\n this.status = status;\n bindBroadcasterOperation(this, {\n quote: (client, options) => this.#quoteForBroadcaster(client, options),\n submit: (client) => this.#submitViaBroadcaster(client),\n provenanceContext: async () => {\n this.current();\n return {\n chainId: this.#saved.plan.context.chainId,\n protocolAddress: this.#saved.plan.context.protocolAddress,\n };\n },\n readProvenance: async () => {\n this.current();\n return structuredClone(this.#saved.provenance);\n },\n proveProvenance: (capability, reprove) => this.#proveProvenance(capability, reprove),\n });\n Object.freeze(this);\n }\n static prepare(runtime: Runtime, plan: OperationPlan): PreparedTransaction {\n return new PreparedTransaction(\n runtime,\n { plan: structuredClone(plan), generation: 0 },\n \"prepared\",\n { generation: 0, busy: false }\n );\n }\n broadcasterQuote() {\n return this.#saved.broadcasterQuote\n ? structuredClone(this.#saved.broadcasterQuote)\n : undefined;\n }\n async #quoteForBroadcaster(\n client: import(\"../../broadcaster/index\").BroadcasterClient,\n options: import(\"../../broadcaster/broadcaster-preparation\").BroadcasterQuoteOptions\n ): Promise<PreparedTransaction> {\n this.current();\n check(\n this.status === \"prepared\" && this.#runtime.reprepare,\n \"broadcaster must attach to an unsigned prepared transaction\"\n );\n const { prepareBroadcasterPlan } =\n await import(\"../../broadcaster/broadcaster-preparation\");\n const selected = await prepareBroadcasterPlan(\n this.#saved.plan,\n this.#runtime.reprepare,\n client,\n options\n );\n return new PreparedTransaction(\n this.#runtime,\n {\n plan: selected.plan,\n broadcasterQuote: selected.quote,\n broadcasterBinding: selected.broadcasterBinding,\n generation: 0,\n },\n \"prepared\",\n { generation: 0, busy: false }\n );\n }\n async #proveProvenance(\n capability?: import(\"../../broadcaster/provenance-preparation\").PreparedProvenanceCapability,\n reprove = false\n ) {\n this.current();\n check(this.status === \"ready\", \"Ready transaction required for Provenance\");\n const { provePreparedProvenance } =\n await import(\"../../broadcaster/provenance-preparation\");\n this.#lifecycle.busy = true;\n try {\n const packet = await provePreparedProvenance(\n this.#saved,\n this.#runtime,\n capability,\n reprove\n );\n if (!this.#saved.broadcasterAttempted) this.#saved.provenance = structuredClone(packet);\n return packet;\n } finally {\n this.#lifecycle.busy = false;\n }\n }\n async #submitViaBroadcaster(client: import(\"../../broadcaster/index\").BroadcasterClient) {\n this.current();\n check(this.status === \"ready\", \"transaction is not ready\");\n const { validateBroadcastEnvelope, validatePreparedBroadcast } =\n await import(\"../../broadcaster/provenance-preparation\");\n validateBroadcastEnvelope(this.#saved, client);\n if (this.#saved.broadcasterSubmissionId) {\n try {\n return await client.status(this.#saved.broadcasterSubmissionId);\n } catch (error) {\n const { BroadcasterRpcError } = await import(\"../../broadcaster/index\");\n if (!(error instanceof BroadcasterRpcError) || error.code !== -32001) throw error;\n }\n }\n // A lost first response has no ID yet. Resend the retained request; only the relay can deduplicate it.\n if (!this.#saved.broadcasterAttempted) {\n const requirements = await client.submissionRequirements(this.#saved.broadcasterQuote!);\n if (\n requirements.provenanceRequired &&\n this.#saved.plan.inputs.length &&\n !this.#saved.provenance\n )\n await this.#proveProvenance();\n await validatePreparedBroadcast(this.#saved, client, this.#runtime);\n }\n this.#saved.externalized = true;\n this.#saved.broadcasterAttempted = true;\n const result = await client.submitTransaction(\n this.#saved.call!.data,\n this.#saved.broadcasterQuote!,\n structuredClone(this.#saved.provenance?.sidecars ?? [])\n );\n check(\n !this.#saved.broadcasterSubmissionId ||\n this.#saved.broadcasterSubmissionId === result.id,\n \"broadcaster changed submission ID\"\n );\n this.#saved.broadcasterSubmissionId = result.id;\n return result;\n }\n get id() {\n return this.#saved.plan.id;\n }\n get kind() {\n return this.#saved.plan.kind;\n }\n async estimateGas(options: { from?: `0x${string}` } = {}) {\n const provider = this.#runtime.options.provider;\n if (!provider)\n throw new MissingCapabilityError(\"ethers provider for final eth_estimateGas\");\n const call = await this.exportTransaction();\n return {\n source: \"rpc\" as const,\n gasUnits: await provider.estimateGas({ ...call, ...options }),\n };\n }\n getGasReference() {\n return getOperationGasReference(this.#saved.plan, this.#runtime.options.protocol);\n }\n /** Final Note outputs, including change; Credit outputs are not exported as IPN. */\n getOutputs(): readonly TransactionOutput[] {\n return Object.freeze(\n this.#saved.plan.outputs.map((output) => new TransactionOutput(output))\n );\n }\n preview() {\n return operationPreview(this.#saved.plan, this.status);\n }\n /** Obtain a firm quote before signing. This intent contains no private inputs or witness. */\n async exportBroadcasterIntent() {\n this.current();\n check(\n [\"prepared\", \"authorized\"].includes(this.status),\n \"quote intent requires a prepared transaction\"\n );\n return exportBroadcasterIntent(this.#saved.plan);\n }\n private current() {\n check(\n !this.#lifecycle.busy && this.#lifecycle.generation === this.#saved.generation,\n \"stale transaction handle or active worker\"\n );\n }\n private async stage(\n stage: string,\n allowed: OperationStatus[],\n work: (\n saved: SavedOperation\n ) => Promise<{ status: OperationStatus; authorization?: AuthorizedStatement }>,\n signal?: AbortSignal\n ): Promise<PreparedTransaction> {\n signal?.throwIfAborted();\n this.current();\n check(allowed.includes(this.status), `invalid transaction stage for ${stage}`);\n this.#lifecycle.busy = true;\n const saved = structuredClone(this.#saved);\n try {\n const next = await work(saved);\n signal?.throwIfAborted();\n saved.generation++;\n this.#lifecycle.generation = saved.generation;\n return new PreparedTransaction(\n this.#runtime,\n saved,\n next.status,\n this.#lifecycle,\n next.authorization ?? this.#authorization\n );\n } finally {\n this.#lifecycle.busy = false;\n }\n }\n async exportRevocationAuthorization() {\n this.current();\n check(this.status === \"prepared\", \"revocation is not awaiting authorization\");\n return revocationSigningRequest(this.#saved.plan, this.#runtime);\n }\n async withRevocationSignature(signature: Hex): Promise<PreparedTransaction> {\n this.current();\n const verified = await acceptRevocationSignature(\n this.#saved.plan,\n signature,\n this.#runtime\n );\n return this.stage(\"revocation authorization\", [\"prepared\"], async (saved) => {\n saved.plan.credit!.revocationSignature = verified;\n saved.call = await this.encode(saved);\n return { status: \"ready\" };\n });\n }\n /** Export the same portable request used by managed native wallet transports. */\n async exportWalletRequest(id: string, options: { signal?: AbortSignal } = {}) {\n options.signal?.throwIfAborted();\n this.current();\n check(\n requiresAuthorization(this.#saved.plan),\n \"operation does not require wallet authorization\"\n );\n check(\n [\"prepared\", \"authorized\"].includes(this.status),\n \"operation is not awaiting wallet authorization\"\n );\n check(!this.#walletRequests.has(id), \"wallet request id already exported\");\n const request = authorizationRequest(this.#saved.plan);\n const prepared = prepareWalletRequest(\n Wallet.fromAddress(this.#saved.plan.scope.ownerAddress),\n id,\n \"wallet.authorize\",\n {\n ...request,\n words: request.words.map(String),\n context: {\n chainId: request.context.chainId.toString(),\n protocolAddress: request.context.protocolAddress.toString(),\n },\n }\n );\n this.#walletRequests.set(id, prepared);\n return structuredClone(prepared.request);\n }\n\n /** Independently validate host authorization against the retained request and frozen plan. */\n async withWalletResponse(\n response: WalletResponse,\n options: { signal?: AbortSignal } = {}\n ): Promise<PreparedTransaction> {\n options.signal?.throwIfAborted();\n this.current();\n check(\n requiresAuthorization(this.#saved.plan),\n \"operation does not require wallet authorization\"\n );\n const prepared = this.#walletRequests.get(response.id);\n check(prepared, \"unknown wallet request response\");\n const authorization = await acceptWalletResponse(\n prepared,\n response as WalletResponse<\"wallet.authorize\">\n );\n return this.stage(\n \"wallet authorization\",\n [\"prepared\", \"authorized\"],\n async () => ({ status: \"authorized\", authorization }),\n options.signal\n );\n }\n\n /** Public EIP-712 request; signing transport and key custody belong to the caller. */\n async exportWalletAuthorization(options: { signal?: AbortSignal } = {}) {\n options.signal?.throwIfAborted();\n this.current();\n check(\n requiresAuthorization(this.#saved.plan),\n \"operation does not require wallet authorization\"\n );\n check(\n [\"prepared\", \"authorized\"].includes(this.status),\n \"operation is not awaiting wallet authorization\"\n );\n return walletSigningRequest(this.#saved.plan);\n }\n\n /** Attach an external EOA signature, retaining its witness only at the private proving boundary. */\n async withWalletSignature(\n signature: string,\n options: { signal?: AbortSignal } = {}\n ): Promise<PreparedTransaction> {\n options.signal?.throwIfAborted();\n this.current();\n check(\n requiresAuthorization(this.#saved.plan),\n \"operation does not require wallet authorization\"\n );\n check(\n [\"prepared\", \"authorized\"].includes(this.status),\n \"operation is not awaiting wallet authorization\"\n );\n const authorization = await acceptWalletSignature(this.#saved.plan, signature);\n return this.stage(\n \"wallet authorization\",\n [\"prepared\", \"authorized\"],\n async () => ({ status: \"authorized\", authorization }),\n options.signal\n );\n }\n\n /** Export only after proving when the funding authorization binds an actual proof hash. */\n async exportFundingAuthorization(options: { signal?: AbortSignal } = {}) {\n options.signal?.throwIfAborted();\n this.current();\n check(\n this.status === (this.kind === \"shield\" ? \"prepared\" : \"proved\"),\n \"operation is not awaiting funding authorization or proof\"\n );\n const request = await fundingSigningRequest(this.#saved, this.#runtime);\n options.signal?.throwIfAborted();\n this.current();\n return request;\n }\n\n /** Verify an external signature against this handle's own frozen operation. */\n async withFundingSignature(\n signature: string,\n options: { signal?: AbortSignal } = {}\n ): Promise<PreparedTransaction> {\n options.signal?.throwIfAborted();\n this.current();\n check(\n this.status === (this.kind === \"shield\" ? \"prepared\" : \"proved\"),\n \"operation is not awaiting funding authorization or proof\"\n );\n const verified = await acceptFundingSignature(this.#saved, signature, this.#runtime);\n return this.stage(\n \"funding authorization\",\n this.kind === \"shield\" ? [\"prepared\"] : [\"proved\"],\n async (saved) => {\n saved.plan.funding.signature = verified;\n if (saved.plan.statement?.target !== \"noir-recursive\") {\n saved.call = await this.encode(saved);\n }\n return { status: \"ready\" };\n },\n options.signal\n );\n }\n\n async prove(options?: TransactionProveOptions): Promise<PreparedTransaction>;\n async prove(backend: Prover, options?: TransactionProveOptions): Promise<PreparedTransaction>;\n async prove(\n backendOrOptions: Prover | TransactionProveOptions = {},\n suppliedOptions: TransactionProveOptions = {}\n ): Promise<PreparedTransaction> {\n const options = { ...(\"prove\" in backendOrOptions ? suppliedOptions : backendOrOptions) };\n check(\n !this.#saved.broadcasterQuote || options.execution !== \"aggregate\",\n \"a broadcaster quote requires direct execution\"\n );\n const plan = this.#saved.plan;\n check(\n plan.kind !== \"shield\" && plan.kind !== \"revoke-credit\",\n \"operation requires no proof\"\n );\n if (requiresAuthorization(plan)) {\n check(\n this.#authorization,\n \"local wallet authorization required; authorize again after recovery\"\n );\n }\n const prover =\n \"prove\" in backendOrOptions ? backendOrOptions : this.#runtime.options.prover;\n if (!prover) {\n throw new MissingCapabilityError(\"prover\");\n }\n return this.stage(\n \"proof\",\n requiresAuthorization(plan) ? [\"authorized\"] : [\"prepared\"],\n async (saved) => {\n const p = saved.plan;\n saved.proof = await proveOperation(\n this.#runtime.options.protocol,\n p,\n this.#authorization,\n prover,\n options\n );\n if (p.fundingMode === \"signature\") {\n return { status: \"proved\" };\n }\n if (p.statement?.target !== \"noir-recursive\") {\n saved.call = await this.encode(saved);\n }\n return { status: \"ready\" };\n },\n options.signal\n );\n }\n\n private encode(saved: SavedOperation): Promise<TransactionCall> {\n return encodeOperation(saved);\n }\n\n /** Shield caller funding needs no wallet signing or proof; this step only encodes its frozen request. */\n async ready(): Promise<PreparedTransaction> {\n check(\n (this.kind === \"shield\" && this.#saved.plan.fundingMode === \"caller\") ||\n this.kind === \"revoke-credit\",\n \"operation needs authorization or proof first\"\n );\n return this.stage(\"encoding\", [\"prepared\"], async (saved) => {\n saved.call = await this.encode(saved);\n return { status: \"ready\" };\n });\n }\n\n async exportTransaction(): Promise<TransactionCall> {\n this.current();\n check(\n this.#saved.plan.statement?.target !== \"noir-recursive\",\n \"recursive operations must be exported as aggregate members\"\n );\n check(this.status === \"ready\" && this.#saved.call, \"transaction is not ready\");\n return structuredClone(this.#saved.call);\n }\n exportProof(): ProofBundle {\n this.current();\n check(this.#saved.proof, \"transaction has no proof\");\n return publicProof(this.#saved.proof);\n }\n exportAggregateMember(): OperationAggregateMember {\n this.current();\n const saved = this.#saved,\n plan = saved.plan;\n check(\n this.status === \"ready\" &&\n plan.params &&\n saved.proof &&\n plan.statement?.target === \"noir-recursive\" &&\n plan.statement.circuitName.startsWith(\"transact_user_slots\") &&\n (plan.capacity ?? 0) <= 10,\n \"ready recursive C1..C10 transaction required\"\n );\n sameStatement(saved.proof, statement(plan));\n check(\n saved.proof.proofHex.length === 2 + 458 * 64,\n \"recursive member proof must have 458 fields\"\n );\n return {\n bundle: publicProof(saved.proof),\n statement: structuredClone(plan.statement),\n context: { ...plan.context },\n request: {\n params: structuredClone(plan.params),\n deliveries: plan.outputs.map((output) => structuredClone(output.delivery)),\n funding: normalizeFunding(plan.funding),\n },\n };\n }\n toJSON() {\n return { transaction: true, id: this.id, kind: this.kind, status: this.status };\n }\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this.toJSON();\n }\n}\n","import { MissingCapabilityError } from \"@invisi-labs/primitives\";\nimport { ProtocolRpcClient } from \"@invisi-labs/rpc\";\nimport { EthersChainReader, EthersFundingVerifier } from \"../integrations/ethers\";\nimport { configureRecipientInfrastructure } from \"../notes/recipient-infrastructure\";\nimport type { TransactionInfrastructure } from \"../transactions/operation-types\";\n\n/** Resolve adapters without starting synchronization or accessing wallet state. */\nexport function configureTransactionInfrastructure<T extends TransactionInfrastructure>(\n options: T\n): T {\n const { provider } = options;\n const reader = options.chainReader ?? (provider ? new EthersChainReader(provider) : undefined);\n const protocolRpc =\n options.protocolRpc instanceof ProtocolRpcClient && reader\n ? options.protocolRpc.withReader(reader)\n : options.protocolRpc;\n const fundingVerifier =\n options.fundingVerifier ??\n (provider\n ? new EthersFundingVerifier(provider, options.protocol.context.chainId)\n : undefined);\n return configureRecipientInfrastructure({\n ...options,\n ...(reader ? { chainReader: reader } : {}),\n ...(protocolRpc ? { protocolRpc } : {}),\n ...(fundingVerifier ? { fundingVerifier } : {}),\n });\n}\n\n/** Validate the selected chain and pinned deployment before any managed state access. */\nexport async function validateTransactionInfrastructure(\n options: TransactionInfrastructure\n): Promise<void> {\n if (!options.chainReader) throw new MissingCapabilityError(\"chain reader\");\n if (\n options.provider &&\n (await options.provider.getNetwork()).chainId !== options.protocol.context.chainId\n )\n throw new Error(\"provider deployment chain mismatch\");\n await options.protocol.validateDeployment(options.chainReader);\n}\n","import { MissingCapabilityError, Wallet } from \"@invisi-labs/primitives\";\nimport type { RegistrationOperation, RegistrationPreparation } from \"@invisi-labs/rpc\";\nimport { ProtocolRpcClient } from \"@invisi-labs/rpc\";\nimport { prepareWithErrors } from \"../errors\";\nimport { AddressRegistry } from \"../protocol/AddressRegistry\";\nimport type { PreparedTransaction } from \"../transactions/execution/PreparedTransaction\";\nimport type {\n ExplicitRevokeCreditPreparation,\n ExplicitCreateCreditPreparation,\n ExplicitDrawCreditPreparation,\n ExplicitShieldPreparation,\n ExplicitUpdateCreditPreparation,\n ExplicitTransferPreparation,\n TransactionIdentity,\n} from \"../transactions/explicit-types\";\nimport type { TransactionInfrastructure } from \"../transactions/operation-types\";\nimport { explicitPreparation } from \"../transactions/preparation/explicit-preparation\";\nimport {\n configureTransactionInfrastructure,\n validateTransactionInfrastructure,\n} from \"./infrastructure\";\n\n/** Compose independent Chain RPC and indexed Protocol RPC with local wallet capabilities. */\nexport type InvisiOptions = Omit<TransactionInfrastructure, \"wallet\" | \"protocol\" | \"coinSelector\">;\ntype InvisiInfrastructure = InvisiOptions;\n\n/** Public wallet and registry-specific inputs; signing remains external. */\nexport type RegistrationPreparationOptions = Pick<RegistrationPreparation, \"update\" | \"deadline\"> &\n Pick<TransactionIdentity, \"wallet\">;\n\n/** Stateless transaction preparation and independent infrastructure composition. */\nexport class Invisi {\n readonly #options: InvisiInfrastructure;\n\n constructor(options: InvisiOptions = {}) {\n if (\"addressLookup\" in options || \"addressResolver\" in options)\n throw new TypeError(\n \"Recipient lookup belongs to each EVM output; caller resolver injection is not supported\"\n );\n if (\"ciphertextCodecs\" in options || \"envelopeVersion\" in options) {\n throw new Error(\n \"SDK envelope versions are fixed; encode application payload bytes externally\"\n );\n }\n if (\"signer\" in options || \"fundingSigner\" in options) {\n throw new Error(\n \"Invisi does not accept signer defaults; export a signing request and attach the external signature\"\n );\n }\n for (const key of [\n \"store\",\n \"viewing\",\n \"authorization\",\n \"namespace\",\n \"coinSelector\",\n \"wallet\",\n \"protocol\",\n ]) {\n if (key in options)\n throw new TypeError(`Wallet state and permissions belong to WalletSession: ${key}`);\n }\n this.#options = {\n ...options,\n };\n Object.freeze(this);\n }\n\n /** A detached snapshot of shared infrastructure; wallet permissions and persistence stay external. */\n getInfrastructure(): Readonly<InvisiOptions> {\n return Object.freeze({\n ...this.#options,\n });\n }\n\n private async resolve(options: TransactionIdentity): Promise<TransactionInfrastructure> {\n const runtime = configureTransactionInfrastructure({\n ...this.getInfrastructure(),\n ...options,\n });\n await validateTransactionInfrastructure(runtime);\n return runtime;\n }\n\n /** Discover the selected chain's registry and prepare an independent signing request. */\n async prepareRegistration(\n options: RegistrationPreparationOptions\n ): Promise<RegistrationOperation> {\n return prepareWithErrors(\"prepareRegistration\", async () => {\n for (const key of Object.keys(options)) {\n if (![\"wallet\", \"update\", \"deadline\"].includes(key)) {\n throw new Error(`Unknown registration option: ${key}`);\n }\n }\n this.assertPublicIdentity(options);\n const selected = { ...options };\n const { provider, protocolRpc } = this.#options;\n if (!provider) throw new MissingCapabilityError(\"ethers provider\");\n if (!(protocolRpc instanceof ProtocolRpcClient)) {\n throw new MissingCapabilityError(\"Protocol RPC deployment discovery\");\n }\n const chainId = (await provider.getNetwork()).chainId;\n const deployment = await protocolRpc.getDeployment(chainId);\n if (!deployment.registry) {\n throw new MissingCapabilityError(\"receiving-key registry deployment\");\n }\n const registry = new AddressRegistry(\n { chainId, registryAddress: deployment.registry.address },\n { expectedRuntimeCodeHash: deployment.registry.runtimeCodeHash }\n );\n return registry.prepareRegistration({ ...selected, provider });\n });\n }\n\n private assertPublicIdentity(options: Pick<TransactionIdentity, \"wallet\">): void {\n const { wallet } = options;\n if (\n !(wallet instanceof Wallet) ||\n [\"getViewer\", \"getDetector\", \"exportAuthorization\"].some((key) => key in wallet)\n ) {\n throw new Error(\n \"Independent preparation requires a Wallet without private capabilities\"\n );\n }\n for (const key of [\"authorization\", \"signer\", \"fundingSigner\", \"viewing\"]) {\n if (key in options)\n throw new Error(`Independent preparation does not accept capability: ${key}`);\n }\n }\n\n private resolveExplicit(options: TransactionIdentity): Promise<TransactionInfrastructure> {\n this.assertPublicIdentity(options);\n return this.resolve({ wallet: options.wallet, protocol: options.protocol });\n }\n\n async prepareTransfer(options: ExplicitTransferPreparation): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareTransfer\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, request, request.tokenAddress);\n return preparation.prepareTransfer(request);\n });\n }\n async prepareShield(options: ExplicitShieldPreparation): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareShield\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, {}, request.tokenAddress);\n return preparation.prepareShield(request);\n });\n }\n async prepareCreateCredit(\n options: ExplicitCreateCreditPreparation\n ): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareCreateCredit\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, {}, request.tokenAddress);\n return preparation.prepareCreateCredit(request);\n });\n }\n async prepareDrawCredit(options: ExplicitDrawCreditPreparation): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareDrawCredit\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, request, request.tokenAddress);\n return preparation.prepareDrawCredit(request);\n });\n }\n async prepareUpdateCredit(\n options: ExplicitUpdateCreditPreparation\n ): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareUpdateCredit\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, request, request.tokenAddress);\n return preparation.prepareUpdateCredit(request);\n });\n }\n async prepareRevokeCredit(\n options: ExplicitRevokeCreditPreparation\n ): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareRevokeCredit\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, {}, request.tokenAddress);\n return preparation.prepareRevokeCredit(request);\n });\n }\n\n toJSON() {\n return { invisi: true };\n }\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this.toJSON();\n }\n}\n","import { getAddress } from \"ethers\";\nimport { PreparedTransaction } from \"../execution/PreparedTransaction\";\nimport type { CreditInput, NoteInput } from \"../explicit-types\";\nimport type { PreparationInventory, TransactionInfrastructure } from \"../operation-types\";\nimport { positiveAmount } from \"./prepare-common\";\nimport { TransactionPreparation } from \"./transaction-preparation\";\n\n/** Only explicitly supplied records participate. No store or automatic coin selection. */\nexport function explicitPreparation(\n options: TransactionInfrastructure,\n data: {\n inputs?: readonly NoteInput[];\n creditInputs?: readonly CreditInput[];\n changeAddress?: string;\n },\n tokenAddress: `0x${string}`\n) {\n if (!options.chainReader) throw new Error(\"chain reader required\");\n const inputs = structuredClone(data.inputs ?? []);\n const credits = structuredClone(data.creditInputs ?? []);\n const inventory: PreparationInventory = { notes: {}, credits: {}, reservations: {} };\n const context = options.protocol.context;\n function position(input: NoteInput | CreditInput) {\n if (\n typeof input.treeId !== \"bigint\" ||\n input.treeId < 0n ||\n input.treeId >= 1n << 256n ||\n !Number.isInteger(input.leafIndex) ||\n input.leafIndex < 0 ||\n input.leafIndex >= 65536\n )\n throw new Error(\"invalid explicit input position\");\n }\n for (const input of inputs) {\n position(input);\n positiveAmount(input.note.amount);\n if (inventory.notes[input.commitment]) throw new Error(\"duplicate explicit note input\");\n if (\n input.note.chainId !== context.chainId ||\n input.note.protocolAddress !== BigInt(context.protocolAddress) ||\n input.note.ownerAddress !== options.wallet.ownerAddress\n )\n throw new Error(\"explicit note identity or deployment mismatch\");\n inventory.notes[input.commitment] = { ...input, spent: \"unspent\" };\n }\n for (const input of credits) {\n position(input);\n if (input.role !== \"owner\" && input.role !== \"spender\")\n throw new Error(\"invalid explicit Credit role\");\n const key = input.commitment + \":\" + input.role;\n if (inventory.credits[key]) throw new Error(\"duplicate explicit Credit input\");\n inventory.credits[key] = { ...input, spent: \"unspent\" };\n }\n const scope = {\n ...context,\n namespace: \"explicit\",\n ownerAddress: options.wallet.ownerAddress,\n };\n const capabilities = options;\n\n if (inputs.some((input) => input.note.tokenAddress !== BigInt(getAddress(tokenAddress))))\n throw new Error(\"explicit note token mismatch\");\n const runtime = {\n options: { ...capabilities, protocol: options.protocol.forToken(tokenAddress) },\n reader: options.chainReader!,\n scope,\n };\n const reprepare = (\n intent: import(\"../../broadcaster/broadcaster-preparation\").PreparationIntent\n ) =>\n import(\"../../broadcaster/broadcaster-preparation\").then(({ prepareIntent }) =>\n prepareIntent(\n {\n ...runtime,\n explicitInputs: true,\n ...(data.changeAddress ? { changeAddress: data.changeAddress } : {}),\n readInventory: async () => structuredClone(inventory),\n complete: async (plan) => plan,\n },\n intent\n )\n );\n return new TransactionPreparation<PreparedTransaction>({\n ...runtime,\n explicitInputs: true,\n ...(data.changeAddress ? { changeAddress: data.changeAddress } : {}),\n readInventory: async () => structuredClone(inventory),\n complete: async (plan) => PreparedTransaction.prepare({ ...runtime, reprepare }, plan),\n });\n}\n","import { invisiProtocolAbi } from \"@invisi-labs/protocol/contracts\";\nimport { Interface, type ParamType } from \"ethers\";\n\nconst protocolInterface = new Interface(invisiProtocolAbi);\n\n/** Decode only canonical protocol receipt bytes before routing events to token wallets. */\nexport function decodeProtocolEvent(log: { data: string; topics: readonly string[] }) {\n const decoded = protocolInterface.parseLog(log);\n if (!decoded) throw new Error(\"Unknown protocol receipt event\");\n const encoded = protocolInterface.encodeEventLog(decoded.fragment, decoded.args);\n if (\n encoded.data.toLowerCase() !== log.data.toLowerCase() ||\n encoded.topics.length !== log.topics.length ||\n encoded.topics.some(\n (topic, index) => topic.toLowerCase() !== log.topics[index]!.toLowerCase()\n )\n )\n throw new Error(\"Noncanonical protocol receipt event\");\n const value = (type: ParamType, item: unknown): unknown => {\n if (type.baseType === \"array\")\n return Array.from(item as readonly unknown[], (v) => value(type.arrayChildren!, v));\n if (type.baseType === \"tuple\")\n return Object.fromEntries(\n type.components!.map((t, i) => [t.name, value(t, (item as readonly unknown[])[i])])\n );\n return item;\n };\n const args = Object.fromEntries(\n decoded.fragment.inputs.map((type, i) => [type.name, value(type, decoded.args[i])])\n );\n return { eventName: decoded.name, args };\n}\n","import type { CanonicalReceipt } from \"@invisi-labs/protocol\";\nimport type { Address } from \"@invisi-labs/protocol/contracts\";\nimport type { DeliveryEventLog } from \"./discovery\";\nimport { decodeProtocolEvent } from \"./protocol-events\";\n\n/** Decode independently fetched canonical receipt bytes, never normalized service events. */\nexport function readProtocolLogs(\n receipt: CanonicalReceipt,\n protocolAddress: Address\n): DeliveryEventLog[] {\n if (\n receipt.status !== \"success\" ||\n !/^0x[0-9a-fA-F]{64}$/.test(receipt.transactionHash) ||\n typeof receipt.block.number !== \"bigint\" ||\n receipt.block.number < 0n ||\n !/^0x[0-9a-fA-F]{64}$/.test(receipt.block.hash)\n )\n throw new Error(\"Invalid canonical protocol receipt\");\n const seen = new Set<number>();\n return receipt.logs\n .filter((log) => log.address.toLowerCase() === protocolAddress.toLowerCase())\n .map((log) => {\n if (\n log.transactionHash.toLowerCase() !== receipt.transactionHash.toLowerCase() ||\n !Number.isSafeInteger(log.logIndex) ||\n log.logIndex < 0 ||\n seen.has(log.logIndex)\n )\n throw new Error(\"Invalid canonical receipt log identity\");\n seen.add(log.logIndex);\n const decoded = decodeProtocolEvent(log);\n return {\n address: log.address,\n eventName: decoded.eventName,\n args: decoded.args as Record<string, unknown>,\n blockNumber: receipt.block.number,\n blockHash: receipt.block.hash,\n transactionHash: receipt.transactionHash.toLowerCase(),\n logIndex: log.logIndex,\n removed: false,\n } as DeliveryEventLog;\n })\n .sort((a, b) => a.logIndex! - b.logIndex!);\n}\n","import { DeliveryDecryptionError } from \"@invisi-labs/primitives\";\nimport type { authenticatedDecryptor } from \"@invisi-labs/primitives\";\nimport { MAX_CIPHERTEXT_BYTES } from \"@invisi-labs/primitives\";\nimport type { Address, Hex } from \"@invisi-labs/protocol/contracts\";\nimport { isAddress } from \"ethers\";\n\nimport {\n decodeAddress,\n ReceivingAddress,\n type CreditDeliveryState,\n type Note,\n} from \"@invisi-labs/primitives\";\nimport { normalizeOpaqueDelivery } from \"@invisi-labs/protocol\";\n\nexport interface DiscoveryContext {\n chainId: bigint;\n protocolAddress: Address;\n}\n/** Decoded logs from complete canonical transaction receipts, including insertion logs. */\nexport interface DeliveryEventLog {\n address: string;\n eventName: string;\n args?: Record<string, unknown>;\n blockNumber?: bigint | null;\n blockHash?: Hex | null;\n transactionHash?: Hex | null;\n logIndex?: number | null;\n removed?: boolean;\n}\nexport interface DeliveryCandidate {\n tokenAddress: Address;\n treeId: bigint;\n leafIndex: number;\n commitment: Hex;\n role: \"funds\" | \"owner\" | \"spender\";\n delivery: { ciphertext: Hex; clue: Hex };\n blockNumber: bigint;\n blockHash: Hex;\n transactionHash: Hex;\n}\nconst EVENTS = new Set([\n \"CommitmentsInserted\",\n \"BatchOutputs\",\n \"Shield\",\n \"Transact\",\n \"CrossTreeTransact\",\n \"CreditCreated\",\n \"CreditDraw\",\n \"CreditUpdated\",\n \"CreditRevoked\",\n]);\nfunction check(ok: unknown, message: string): asserts ok {\n if (!ok) throw new Error(message);\n}\nfunction object(value: unknown): Record<string, unknown> {\n check(value && typeof value === \"object\" && !Array.isArray(value), \"invalid event object\");\n return value as Record<string, unknown>;\n}\nfunction array(value: unknown): unknown[] {\n check(Array.isArray(value), \"invalid event array\");\n check(\n Array.from({ length: value.length }, (_, i) => i in value).every(Boolean),\n \"sparse event array\"\n );\n return value;\n}\nfunction integer(value: unknown): bigint {\n check(\n typeof value === \"bigint\" || (typeof value === \"number\" && Number.isSafeInteger(value)),\n \"invalid event integer\"\n );\n const n = BigInt(value);\n check(n >= 0n, \"negative event integer\");\n return n;\n}\nfunction index(value: unknown): number {\n const n = integer(value);\n check(n < 65536n, \"invalid event leaf index\");\n return Number(n);\n}\nfunction hash(value: unknown): Hex {\n check(typeof value === \"string\" && /^0x[0-9a-fA-F]{64}$/.test(value), \"invalid event hash\");\n return value.toLowerCase() as Hex;\n}\nfunction contextCheck(context: DiscoveryContext): void {\n check(context.chainId >= 0n && context.chainId < 1n << 64n, \"invalid discovery chain\");\n check(\n isAddress(context.protocolAddress) && BigInt(context.protocolAddress) !== 0n,\n \"invalid discovery instance/token\"\n );\n}\nconst position = (tree: bigint, at: number) => `${tree}:${at}`;\n\n/** Correlate deliveries with canonical insertion events, never service-supplied balances or positions.\n * The caller selects a confirmed chain/deployment and supplies complete decoded receipts.\n */\nexport function extractDeliveryCandidates(\n logs: readonly DeliveryEventLog[],\n context: DiscoveryContext,\n confirmedThrough: bigint\n): DeliveryCandidate[] {\n contextCheck(context);\n check(confirmedThrough >= 0n, \"invalid confirmed height\");\n const relevant = logs.filter(\n (log) =>\n log.address.toLowerCase() === context.protocolAddress.toLowerCase() &&\n EVENTS.has(log.eventName)\n );\n const insertions = new Map<string, Hex>();\n const metadata = (log: DeliveryEventLog) => {\n check(!log.removed, \"discovery resync required after reorg\");\n check(\n typeof log.blockNumber === \"bigint\" &&\n log.blockNumber >= 0n &&\n log.blockNumber <= confirmedThrough,\n \"event is not confirmed\"\n );\n check(Number.isSafeInteger(log.logIndex) && log.logIndex! >= 0, \"invalid log position\");\n return {\n blockNumber: log.blockNumber,\n blockHash: hash(log.blockHash),\n transactionHash: hash(log.transactionHash),\n };\n };\n const insertionKey = (log: DeliveryEventLog, tree: bigint, at: number) =>\n `${hash(log.transactionHash)}:${position(tree, at)}`;\n for (const log of relevant) {\n metadata(log);\n if (log.eventName !== \"CommitmentsInserted\" && log.eventName !== \"BatchOutputs\") continue;\n const a = object(log.args),\n tree = integer(a.treeId),\n start = index(a.startLeafIndex),\n leaves = array(log.eventName === \"BatchOutputs\" ? a.noteCommitments : a.commitments);\n check(tree > 0n && tree < 1n << 64n, \"invalid insertion tree\");\n check(start + leaves.length <= 65536, \"insertion exceeds tree capacity\");\n for (const [i, leaf] of leaves.entries()) {\n const key = insertionKey(log, tree, start + i),\n value = hash(leaf),\n previous = insertions.get(key);\n check(!previous || previous === value, \"conflicting insertion events\");\n insertions.set(key, value);\n }\n }\n const results = new Map<string, DeliveryCandidate>();\n const add = (\n log: DeliveryEventLog,\n tree: bigint,\n at: number,\n commitment: unknown,\n role: DeliveryCandidate[\"role\"],\n wire: unknown,\n token: unknown = log.args?.token ??\n (log.args?.params as { token?: unknown; creation?: { token?: unknown } } | undefined)\n ?.token ??\n (log.args?.params as { creation?: { token?: unknown } } | undefined)?.creation?.token\n ) => {\n check(tree > 0n && tree < 1n << 64n, \"invalid output tree\");\n const inserted = insertions.get(insertionKey(log, tree, at));\n check(inserted, \"delivery has no matching canonical insertion\");\n if (commitment !== undefined)\n check(hash(commitment) === inserted, \"delivery commitment conflicts with insertion\");\n const delivery = normalizeOpaqueDelivery(wire as never, { allowEmpty: role === \"funds\" });\n check(\n typeof token === \"string\" && isAddress(token) && BigInt(token) !== 0n,\n \"invalid event token\"\n );\n const value = {\n tokenAddress: token as Address,\n treeId: tree,\n leafIndex: at,\n commitment: inserted,\n role,\n delivery,\n ...metadata(log),\n };\n const key = `${insertionKey(log, tree, at)}:${role}`,\n previous = results.get(key);\n check(\n !previous ||\n (previous.tokenAddress.toLowerCase() === token.toLowerCase() &&\n previous.delivery.ciphertext === delivery.ciphertext &&\n previous.delivery.clue === delivery.clue &&\n previous.blockHash === value.blockHash),\n \"conflicting delivery events\"\n );\n results.set(key, value);\n };\n const creation = (\n log: DeliveryEventLog,\n a: Record<string, unknown>,\n fields: Record<string, unknown>\n ) => {\n const tree = integer(a.outputTreeId),\n leaf = index(a.leafIndex),\n ds = array(a.deliveries);\n check(ds.length === 2, \"invalid Credit delivery slots\");\n add(log, tree, leaf, fields.creditCommitment, \"owner\", ds[0]);\n add(log, tree, leaf, fields.creditCommitment, \"spender\", ds[1]);\n };\n for (const log of relevant) {\n const a = object(log.args);\n if (log.eventName === \"Shield\") {\n const ds = array(a.deliveries),\n tree = integer(a.treeId),\n start = index(a.startLeafIndex);\n check(start + ds.length <= 65536, \"shield exceeds tree capacity\");\n ds.forEach((d, i) => add(log, tree, start + i, undefined, \"funds\", d));\n } else if (log.eventName === \"Transact\" || log.eventName === \"CrossTreeTransact\") {\n const cs = array(a.noteCommitments),\n ds = array(a.deliveries),\n leaves = array(a.leafIndices),\n tree = integer(a.outputTreeId);\n check(\n cs.length === ds.length && cs.length === leaves.length,\n \"invalid transact delivery slots\"\n );\n cs.forEach((c, i) => add(log, tree, index(leaves[i]), c, \"funds\", ds[i]));\n } else if (log.eventName === \"BatchOutputs\") {\n const tokens = array(a.tokens);\n const cs = array(a.noteCommitments),\n tree = integer(a.treeId),\n start = index(a.startLeafIndex),\n packed = a.packedDeliveries;\n check(\n typeof packed === \"string\" && /^0x(?:[0-9a-fA-F]{2})*$/.test(packed),\n \"invalid packed deliveries\"\n );\n check(tokens.length === cs.length, \"batch token count mismatch\");\n check(start + cs.length <= 65536, \"batch exceeds tree capacity\");\n let offset = 2;\n cs.forEach((c, i) => {\n check(offset + 4 <= packed.length, \"truncated delivery length prefix\");\n const length = Number.parseInt(packed.slice(offset, offset + 4), 16);\n offset += 4;\n check(\n length <= MAX_CIPHERTEXT_BYTES &&\n offset + length * 2 + (length === 0 ? 0 : 136) <= packed.length,\n \"invalid packed delivery length\"\n );\n const ciphertext = `0x${packed.slice(offset, offset + length * 2)}`;\n offset += length * 2;\n const clue = length === 0 ? \"0x\" : `0x${packed.slice(offset, offset + 136)}`;\n if (length !== 0) offset += 136;\n add(log, tree, start + i, c, \"funds\", { ciphertext, clue }, tokens[i]);\n });\n check(offset === packed.length, \"trailing packed delivery bytes\");\n } else if (log.eventName === \"CreditCreated\") creation(log, a, a);\n else if (log.eventName === \"CreditUpdated\") creation(log, a, object(a.params));\n else if (log.eventName === \"CreditDraw\") {\n const p = object(a.params),\n cs = array(p.creditCommitments),\n ds = array(a.deliveries),\n leaves = array(a.leafIndices),\n tree = integer(a.outputTreeId);\n check(\n ds.length === 2 * cs.length + 1 && leaves.length === cs.length + 1,\n \"invalid draw delivery slots\"\n );\n cs.forEach((c, i) => {\n add(log, tree, index(leaves[i]), c, \"owner\", ds[2 * i]);\n add(log, tree, index(leaves[i]), c, \"spender\", ds[2 * i + 1]);\n });\n add(\n log,\n tree,\n index(leaves[cs.length]),\n p.noteCommitment,\n \"funds\",\n ds[2 * cs.length],\n p.token\n );\n }\n }\n return [...results.values()];\n}\nexport interface DiscoveredNote extends Omit<DeliveryCandidate, \"delivery\" | \"role\"> {\n note: Note;\n}\nexport interface DiscoveredCredit extends Omit<DeliveryCandidate, \"delivery\"> {\n role: \"owner\" | \"spender\";\n state: CreditDeliveryState;\n}\n/** Authenticate private deliveries from a single batch of canonical receipts. */\nexport async function decryptCandidates(\n logs: readonly DeliveryEventLog[],\n options: {\n context: DiscoveryContext;\n viewing: ReturnType<typeof authenticatedDecryptor>;\n confirmedThrough: bigint;\n }\n): Promise<{ notes: DiscoveredNote[]; credits: DiscoveredCredit[] }> {\n contextCheck(options.context);\n decodeAddress(ReceivingAddress.fromIdentity(options.viewing.ownerAddress).toString());\n check(\n !logs.some(\n (log) =>\n log.address.toLowerCase() === options.context.protocolAddress.toLowerCase() &&\n log.removed\n ),\n \"discovery resync required after reorg\"\n );\n const candidates = extractDeliveryCandidates(logs, options.context, options.confirmedThrough);\n const positions = new Map<string, DeliveryCandidate>();\n const unique = new Map<string, DeliveryCandidate>();\n for (const candidate of candidates) {\n const key = position(candidate.treeId, candidate.leafIndex);\n const previous = positions.get(key);\n check(\n !previous ||\n (previous.commitment === candidate.commitment &&\n previous.blockHash === candidate.blockHash &&\n previous.transactionHash === candidate.transactionHash &&\n previous.tokenAddress.toLowerCase() === candidate.tokenAddress.toLowerCase()),\n \"conflicting canonical position\"\n );\n positions.set(key, candidate);\n unique.set(`${key}:${candidate.role}`, candidate);\n }\n const notes: DiscoveredNote[] = [];\n const credits: DiscoveredCredit[] = [];\n for (const candidate of unique.values()) {\n const { delivery, role, ...positionData } = candidate;\n const context = {\n chainId: options.context.chainId,\n protocolAddress: BigInt(options.context.protocolAddress),\n tokenAddress: BigInt(candidate.tokenAddress),\n outputCommitment: candidate.commitment,\n };\n // Non-recipient ciphertexts and failed authentication are normal scan outcomes.\n try {\n if (role === \"funds\") {\n if (delivery.ciphertext === \"0x\") continue;\n const note = await options.viewing.decryptNote(delivery.ciphertext, context);\n if (note !== null) notes.push({ ...positionData, note });\n } else {\n const state = await options.viewing.decryptCredit(delivery.ciphertext, {\n ...context,\n role,\n });\n if (state !== null) credits.push({ ...positionData, role, state });\n }\n } catch (error) {\n if (error instanceof DeliveryDecryptionError) throw error;\n /* Unrelated or invalid local ciphertext: never add unauthenticated amounts. */\n }\n }\n return { notes, credits };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB,gBAA8C;AAMnE,IAAM,kBAAN,cAA8B,SAAS;AAAA,EACjC,oBACL,SAGF;AACE,WAAO,kBAAkB,uBAAuB,YAAY;AACxD,UAAI,cAAc,SAAS;AACvB,cAAM,EAAE,UAAU,GAAG,YAAY,IAAI;AACrC,eAAO,MAAM,oBAAoB;AAAA,UAC7B,GAAG;AAAA,UACH,QAAQ,IAAI,kBAAkB,QAAQ;AAAA,QAC1C,CAAC;AAAA,MACL;AACA,aAAO,MAAM,oBAAoB,OAAO;AAAA,IAC5C,CAAC;AAAA,EACL;AACJ;;;ACvBA,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,YAAY,uBAAuB;AAG5C,eAAsB,yBAClB,MACA,SACF;AACE,QAAM,SAAS,KAAK,QAAQ;AAC5B,MAAI,CAAC,OAAQ,OAAM,MAAM,6CAA6C;AACtE,QAAM,QAAQ,QAAQ,SAAS,mBAAmB,QAAQ,MAAM;AAChE,QAAM,QAAQ,MAAM,QAAQ,OAAO,SAAS,MAAM,QAAQ,OAAO,qBAAqB,CAAC;AACvF,MAAI,MAAM,YAAY,OAAO,SAAU,OAAM,MAAM,kCAAkC;AACrF,QAAM,UAAU;AAAA,IACZ,4BAA4B,EAAE,GAAG,KAAK,SAAS,KAAK,MAAM,UAAU,GAAG,MAAM;AAAA,EACjF;AACA,OAAK,MAAM,QAAQ,OAAO,SAAS,MAAM,MAAM,GAAG,SAAS,MAAM;AAC7D,UAAM,MAAM,oCAAoC;AACpD,SAAO;AACX;AACA,eAAsB,0BAClB,MACA,WACA,SACF;AACE,MAAI,CAAC,0BAA0B,KAAK,SAAS,EAAG,OAAM,MAAM,8BAA8B;AAC1F,QAAM,UAAU,MAAM,yBAAyB,MAAM,OAAO,GACxD,QAAQ,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M,QAAQ,QAAQ,YAAY,SAAS,YAAY,OAAO;AAC3E,YAAI,SAAS,KAAM,OAAM,KAAK,EAAE,GAAG,cAAc,KAAK,CAAC;AAAA,MAC3D,OAAO;AACH,cAAM,QAAQ,MAAM,QAAQ,QAAQ,cAAc,SAAS,YAAY;AAAA,UACnE,GAAG;AAAA,UACH;AAAA,QACJ,CAAC;AACD,YAAI,UAAU,KAAM,SAAQ,KAAK,EAAE,GAAG,cAAc,MAAM,MAAM,CAAC;AAAA,MACrE;AAAA,IACJ,SAAS,OAAO;AACZ,UAAI,iBAAiB,wBAAyB,OAAM;AAAA,IAExD;AAAA,EACJ;AACA,SAAO,EAAE,OAAO,QAAQ;AAC5B;","names":["index","getDocumentedGasReference","createSigningRequest","WitnessBuilder","getBytes","verifyTypedData","WitnessBuilder","createSigningRequest","getBytes","verifyTypedData","normalizeFunding","check","normalizeFunding","MissingCapabilityError","MissingCapabilityError","MissingCapabilityError","Wallet","ProtocolRpcClient","getAddress","position","getAddress","MissingCapabilityError","ProtocolRpcClient","Wallet","index","check"]}
1
+ {"version":3,"sources":["../src/protocol/AddressRegistry.ts","../src/transactions/signing/revocation.ts","../src/transactions/records.ts","../src/transactions/preparation/inputs.ts","../src/gas/gas-estimation.ts","../src/transactions/proving/proof.ts","../src/transactions/proving/proof-integrity.ts","../src/transactions/execution/calldata.ts","../src/transactions/proving/witness.ts","../src/transactions/signing/funding.ts","../src/transactions/execution/operation-execution.ts","../src/transactions/execution/operation-preview.ts","../src/transactions/execution/PreparedTransaction.ts","../src/client/infrastructure.ts","../src/client/Invisi.ts","../src/transactions/preparation/explicit-preparation.ts","../src/discovery/protocol-events.ts","../src/discovery/receipt-logs.ts","../src/discovery/discovery.ts"],"sourcesContent":["import { AddressRegistry as Registry, type RegistrationPreparation } from \"@invisi-labs/rpc\";\nimport type { Provider } from \"ethers\";\nimport { prepareWithErrors } from \"../errors\";\nimport { EthersChainReader } from \"../integrations/ethers\";\n\n/** Registry operations accept the application's existing ethers provider. */\nexport class AddressRegistry extends Registry {\n override prepareRegistration(\n options:\n | RegistrationPreparation\n | (Omit<RegistrationPreparation, \"reader\"> & { provider: Provider })\n ) {\n return prepareWithErrors(\"prepareRegistration\", async () => {\n if (\"provider\" in options) {\n const { provider, ...preparation } = options;\n return super.prepareRegistration({\n ...preparation,\n reader: new EthersChainReader(provider),\n });\n }\n return super.prepareRegistration(options);\n });\n }\n}\n","import { createSigningRequest } from \"@invisi-labs/primitives\";\nimport { encodeRevokeCreditTypedData } from \"@invisi-labs/protocol\";\nimport { getAddress, verifyTypedData } from \"ethers\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport type { OperationPlan, TransactionRuntime } from \"../operation-types\";\nexport async function revocationSigningRequest(\n plan: OperationPlan,\n runtime: Pick<TransactionRuntime, \"reader\" | \"options\">\n) {\n const params = plan.credit?.revocation;\n if (!params) throw Error(\"operation is not a public Credit revocation\");\n await runtime.options.protocol.validateDeployment(runtime.reader);\n const block = await runtime.reader.getBlock(await runtime.reader.getLatestBlockNumber());\n if (block.timestamp > params.deadline) throw Error(\"revocation authorization expired\");\n const request = createSigningRequest(\n encodeRevokeCreditTypedData({ ...plan.context, now: block.timestamp }, params)\n );\n if ((await runtime.reader.getBlock(block.number)).hash !== block.hash)\n throw Error(\"canonical revocation block changed\");\n return request;\n}\nexport async function acceptRevocationSignature(\n plan: OperationPlan,\n signature: Hex,\n runtime: Pick<TransactionRuntime, \"reader\" | \"options\">\n) {\n if (!/^0x(?:[0-9a-fA-F]{2})+$/.test(signature)) throw Error(\"invalid revocation signature\");\n const request = await revocationSigningRequest(plan, runtime),\n owner = plan.credit!.revocation!.owner;\n let valid = false;\n try {\n valid =\n getAddress(\n verifyTypedData(request.domain, request.types, request.message, signature)\n ) === getAddress(owner);\n } catch {}\n if (!valid && runtime.options.fundingVerifier)\n valid = await runtime.options.fundingVerifier.verifyTypedData({\n ...request,\n address: owner,\n signature,\n });\n if (!valid) throw Error(\"invalid owner revocation signature\");\n return signature;\n}\n","import type { CreditDeliveryState, Note } from \"@invisi-labs/primitives\";\nimport type { Hex } from \"@invisi-labs/prover\";\n\nexport interface WalletScope {\n namespace: string;\n chainId: bigint;\n protocolAddress: Hex;\n ownerAddress: Hex;\n}\n\nexport function creditReservationKey(commitment: string): string {\n return \"credit:\" + commitment;\n}\n\nexport interface Checkpoint {\n number: bigint;\n hash: Hex;\n}\n\nexport type SpentState = \"unknown\" | \"unspent\" | \"spent\";\n\nexport interface ReceiptPosition {\n commitment: Hex;\n treeId: bigint;\n leafIndex: number;\n blockNumber: bigint;\n blockHash: Hex;\n transactionHash?: Hex;\n}\n\nexport interface NoteRecord extends ReceiptPosition {\n note: Note;\n spent: SpentState;\n checkedThrough?: Checkpoint;\n}\n\nexport interface CreditRecord extends ReceiptPosition {\n receivingKeySource?: { kind: \"draw\" | \"update\"; commitment: Hex };\n revoked?: boolean;\n state: CreditDeliveryState;\n role: \"owner\" | \"spender\";\n spent: SpentState;\n checkedThrough?: Checkpoint;\n}\n\nexport type OperationStatus =\n | \"prepared\"\n | \"authorized\"\n | \"proved\"\n | \"ready\"\n | \"submitted\"\n | \"confirmed\"\n | \"failed\"\n | \"expired\"\n | \"uncertain\"\n | \"reorged\";\n","import type { Hex, InputSource } from \"@invisi-labs/protocol/contracts\";\nimport type { OperationPlan } from \"../operation-types\";\nimport { creditReservationKey } from \"../records\";\n\nexport function inputFacts(\n plan: OperationPlan\n): Array<{ key: string; reservationKey: string; nullifier: Hex; kind: \"notes\" | \"credits\" }> {\n const credit = plan.credit;\n const noteNullifiers = plan.params?.nullifiers ?? [];\n let creditNullifiers: readonly Hex[] = [];\n\n if (credit?.draw) {\n creditNullifiers = credit.draw.nullifiers;\n } else if (credit?.update) {\n creditNullifiers = [credit.update.nullifier];\n }\n\n if (\n noteNullifiers.length !== plan.inputs.length ||\n creditNullifiers.length !== (credit?.inputs.length ?? 0)\n ) {\n throw new Error(\"operation input statement count mismatch\");\n }\n\n return [\n ...plan.inputs.map((input, index) => ({\n key: input.commitment,\n reservationKey: input.commitment,\n nullifier: noteNullifiers[index]!,\n kind: \"notes\" as const,\n })),\n ...(credit?.inputs ?? []).map((input, index) => ({\n key: input.commitment + \":\" + input.role,\n reservationKey: creditReservationKey(input.commitment),\n nullifier: creditNullifiers[index]!,\n kind: \"credits\" as const,\n })),\n ];\n}\n\nexport function operationSources(plan: OperationPlan): readonly InputSource[] {\n const noteSources = plan.params?.sources;\n if (noteSources != null) return noteSources;\n\n const credit = plan.credit;\n if (credit?.draw) return credit.draw.sources;\n if (credit?.update) return [credit.update.source];\n return [];\n}\n","import type { TokenProtocol } from \"@invisi-labs/rpc\";\nimport type { OperationPlan } from \"../transactions/operation-types\";\nimport { getDocumentedGasReference, type DocumentedGasShape } from \"@invisi-labs/protocol\";\nimport { operationSources } from \"../transactions/preparation/inputs\";\n/** A pre-proof documented scenario reference; conditions remain visible in the result. */\nexport function getOperationGasReference(plan: OperationPlan, _protocol?: TokenProtocol) {\n let query: DocumentedGasShape = { kind: plan.kind };\n const credit = plan.credit;\n if (plan.statement?.target === \"noir-recursive\")\n return getDocumentedGasReference({ kind: \"aggregate\" });\n if (credit?.creation)\n query = { kind: \"create-credit\", scenario: \"first-allocation-empty-tree\" };\n else if (credit?.update)\n query = { kind: \"update-credit\", scenario: \"after-draw-preserve-usage\" };\n else if (credit?.draw)\n query = {\n kind: \"draw-credit\",\n capacity: plan.capacity!,\n creditInputs: credit.inputs.length,\n distinctPayers: credit.draw.payers.length,\n sourceTrees: operationSources(plan).length,\n noteOutputs: 1,\n creditOutputs: credit.outputs.length,\n creditCiphertextBytes: 485,\n noteCiphertextBytes: 160,\n clueBytes: 68,\n scenario: \"distinct-payers\",\n };\n else if (plan.kind === \"transfer\")\n query = {\n kind: \"transact\",\n capacity: plan.capacity!,\n noteInputs: plan.inputs.length,\n noteOutputs: plan.outputs.length,\n sourceTrees: operationSources(plan).length,\n noteCiphertextBytes: 160,\n clueBytes: 68,\n scenario: !plan.inputs.length\n ? \"public-funding\"\n : !plan.outputs.length\n ? \"withdrawal\"\n : !(plan.funding.amount ?? 0n) &&\n !(plan.params?.withdrawalAmount ?? 0n) &&\n !(plan.params?.feeAmount ?? 0n)\n ? \"private\"\n : \"mixed\",\n };\n if (credit) {\n const feeAmount =\n credit.creation?.feeAmount ??\n credit.update?.feeAmount ??\n credit.draw?.feeAmount ??\n credit.revocation?.feeAmount ??\n 0n;\n query = {\n ...query,\n feeEnabled: feeAmount > 0n,\n feeMechanism: feeAmount > 0n ? (credit.draw ? \"draw-deduction\" : \"owner-pull\") : \"none\",\n };\n }\n if (\n plan.outputs.some((o) => (o.delivery.ciphertext.length - 2) / 2 !== 160) ||\n credit?.outputs.some((o) => o.deliveries.some((d) => (d.ciphertext.length - 2) / 2 !== 485))\n )\n return getDocumentedGasReference({ kind: \"unmeasured-delivery-size\" });\n return getDocumentedGasReference(query);\n}\nexport { getDocumentedGasReference } from \"@invisi-labs/protocol\";\nexport type { DocumentedGasReference, DocumentedGasShape } from \"@invisi-labs/protocol\";\n","import type { ProofBundle } from \"@invisi-labs/prover\";\n\n/** Whitelist the public proof fields; a custom local backend cannot accidentally export its witness. */\nexport function publicProof(bundle: ProofBundle): ProofBundle {\n return {\n formatVersion: bundle.formatVersion,\n circuitName: bundle.circuitName,\n target: bundle.target,\n bbVersion: bundle.bbVersion,\n artifactSha256: bundle.artifactSha256,\n vkSha256: bundle.vkSha256,\n proofHex: bundle.proofHex,\n proofSha256: bundle.proofSha256,\n publicInputs: [...bundle.publicInputs],\n };\n}\n","import type { ProofBundle, ProofStatement } from \"@invisi-labs/prover\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { bytesToHex } from \"@noble/hashes/utils\";\nimport { getBytes } from \"ethers\";\nfunction check(ok: unknown, message: string): asserts ok {\n if (!ok) throw new Error(message);\n}\nexport function sameStatement(proof: ProofBundle, expected: ProofStatement): void {\n check(\n proof.formatVersion === 1 &&\n proof.bbVersion === \"6.0.0\" &&\n proof.circuitName === expected.circuitName &&\n proof.target === expected.target &&\n proof.artifactSha256 === expected.artifactSha256 &&\n proof.vkSha256 === expected.vkSha256,\n \"proof release/target mismatch\"\n );\n check(\n proof.publicInputs.length === expected.expectedPublicInputs.length &&\n proof.publicInputs.every((word, i) => word === expected.expectedPublicInputs[i]),\n \"proof public statement mismatch\"\n );\n check(\n /^0x(?:[a-fA-F0-9]{2})+$/.test(proof.proofHex) &&\n bytesToHex(sha256(getBytes(proof.proofHex))) === proof.proofSha256,\n \"proof integrity mismatch\"\n );\n}\n","import {\n buildRevokeCreditCalldata,\n buildCreateCreditCalldata,\n buildCreditDrawCalldata,\n buildShieldCalldata,\n buildUpdateCreditCalldata,\n buildTransactCalldata,\n type TransactionCall,\n} from \"@invisi-labs/protocol\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport type { SavedOperation } from \"../operation-types\";\n\nexport async function encodeOperation(saved: SavedOperation): Promise<TransactionCall> {\n const plan = saved.plan;\n const credit = plan.credit;\n const caller = plan.fundingMode === \"caller\" ? plan.funding.payer : undefined;\n const common = { context: plan.context, proof: saved.proof?.proofHex ?? (\"0x\" as Hex) };\n const funded = { ...common, funding: plan.funding, ...(caller ? { caller } : {}) };\n\n let encoded: { data: Hex };\n if (credit?.update) {\n encoded = buildUpdateCreditCalldata({\n ...funded,\n params: credit.update,\n deliveries: credit.deliveries,\n });\n } else if (credit?.creation) {\n encoded = buildCreateCreditCalldata({\n ...funded,\n params: credit.creation,\n deliveries: credit.deliveries,\n });\n } else if (credit?.draw) {\n encoded = buildCreditDrawCalldata({\n ...common,\n params: credit.draw,\n deliveries: credit.deliveries,\n });\n } else if (credit?.revocation) {\n encoded = buildRevokeCreditCalldata({\n context: plan.context,\n params: credit.revocation,\n signature: credit.revocationSignature ?? \"0x\",\n ...(credit.revocationCaller ? { caller: credit.revocationCaller } : {}),\n });\n } else if (plan.kind === \"shield\") {\n encoded = await buildShieldCalldata({\n ...funded,\n params: plan.shieldParams!,\n outputs: plan.shieldOutputs!,\n deliveries: plan.outputs.map((output) => output.delivery),\n });\n } else {\n encoded = buildTransactCalldata({\n ...funded,\n params: plan.params!,\n deliveries: plan.outputs.map((output) => output.delivery),\n });\n }\n\n return { to: plan.context.protocolAddress, data: encoded.data, value: 0n };\n}\n","import { assertCreditUpdatePlan } from \"../../credit/state\";\nimport { type AuthorizedStatement } from \"@invisi-labs/primitives\";\nimport { WitnessBuilder } from \"@invisi-labs/prover\";\nimport { type TokenProtocol } from \"@invisi-labs/rpc\";\nimport type { ProvingRequest } from \"@invisi-labs/prover\";\nimport type { OperationPlan } from \"../operation-types\";\n\nexport async function witnessFor(\n protocol: TokenProtocol,\n plan: OperationPlan,\n authorization?: AuthorizedStatement\n): Promise<ProvingRequest> {\n const builder = new WitnessBuilder(protocol);\n const credit = plan.credit;\n\n if (credit) {\n if (!authorization) throw new Error(\"private Credit wallet authorization required\");\n\n if (credit.update) {\n await assertCreditUpdatePlan(plan);\n if (!credit.updateChanges) throw Error(\"Credit update adjustment required\");\n return builder.updateCredit({\n params: credit.update,\n deliveries: credit.deliveries,\n input: credit.inputs[0]!,\n state: credit.outputs[0]!.state,\n changes: credit.updateChanges,\n authorization,\n });\n }\n if (credit.creation)\n return builder.createCredit({\n params: credit.creation,\n deliveries: credit.deliveries,\n state: credit.outputs[0]!.state,\n authorization,\n });\n if (credit.draw) {\n return builder.drawCredit({\n timestamp: plan.preparedAt.timestamp,\n params: credit.draw,\n deliveries: credit.deliveries,\n inputs: credit.inputs,\n amounts: credit.amounts!,\n output: plan.outputs[0]!.note!,\n authorization,\n });\n }\n throw new Error(\"unsupported Credit operation\");\n }\n\n return builder.transact({\n params: plan.params!,\n deliveries: plan.outputs.map((output) => output.delivery),\n funding: plan.funding,\n inputs: plan.inputs,\n outputs: plan.outputs.map((output) => ({\n identity: output.identity,\n amount: output.amount,\n ...(output.note ? { note: output.note } : {}),\n })),\n ...(authorization ? { authorization } : {}),\n target: plan.statement!.target,\n });\n}\n","import {\n encodeAggregateFundingTypedData,\n encodeShieldFundingTypedData,\n encodeTransactFundingTypedData,\n} from \"@invisi-labs/protocol\";\nimport type { SavedOperation } from \"../operation-types\";\n\nexport async function fundingTypedData(saved: SavedOperation) {\n const plan = saved.plan;\n if (plan.credit) throw Error(\"Credit operations have no funding authorization\");\n if (plan.kind === \"shield\") {\n return encodeShieldFundingTypedData({\n context: plan.context,\n params: plan.shieldParams!,\n outputs: plan.shieldOutputs!,\n deliveries: plan.outputs.map((output) => output.delivery),\n funding: plan.funding,\n });\n }\n if (plan.statement?.target === \"noir-recursive\") {\n return encodeAggregateFundingTypedData(plan.context, {\n params: plan.params!,\n deliveries: plan.outputs.map((output) => output.delivery),\n funding: plan.funding,\n });\n }\n return encodeTransactFundingTypedData(\n plan.context,\n saved.proof!.proofHex,\n plan.params!,\n plan.outputs.map((output) => output.delivery),\n plan.funding\n );\n}\n","import {\n AuthorizedStatement,\n computeOwnerAddress,\n computeWalletAuthorizationDigest,\n createSigningRequest,\n walletAuthorizationTypedData,\n} from \"@invisi-labs/primitives\";\nimport { WitnessBuilder } from \"@invisi-labs/prover\";\nimport { type TokenProtocol } from \"@invisi-labs/rpc\";\nimport type { Prover } from \"@invisi-labs/prover\";\nimport { Signature, SigningKey, concat, getBytes, verifyTypedData } from \"ethers\";\nimport type {\n FundingAuthorizationVerifier,\n FundingSigner,\n FundingTypedData,\n OperationPlan,\n SavedOperation,\n TransactionProveOptions,\n TransactionRuntime,\n} from \"../operation-types\";\nimport { publicProof } from \"../proving/proof\";\nimport { sameStatement } from \"../proving/proof-integrity\";\nimport { witnessFor } from \"../proving/witness\";\nimport { fundingTypedData } from \"../signing/funding\";\nimport { authorizationRequest, statement } from \"../signing/statement\";\n\nexport async function proveOperation(\n protocol: TokenProtocol,\n plan: OperationPlan,\n authorization: AuthorizedStatement | undefined,\n prover: Prover,\n options: TransactionProveOptions\n) {\n if (Object.hasOwn(options, \"target\")) {\n throw new Error(\"prove accepts execution, not a backend target\");\n }\n const { execution = \"single\", ...proverOptions } = options;\n if (execution !== \"single\" && execution !== \"aggregate\") {\n throw new Error(\"execution must be single or aggregate\");\n }\n const frozen = statement(plan);\n if (\n execution === \"aggregate\" &&\n (plan.kind !== \"transfer\" || !plan.capacity || plan.capacity > 10)\n ) {\n throw new Error(\"aggregate execution requires a C1..C10 transfer\");\n }\n if (plan.kind === \"transfer\") {\n // Only the proof backend/key changes; public words and wallet authorization stay fixed.\n plan.statement = WitnessBuilder.statement(\n frozen.circuitName,\n frozen.expectedPublicInputs,\n execution === \"aggregate\" ? \"noir-recursive\" : \"evm\"\n );\n }\n const request = await witnessFor(protocol, plan, authorization);\n if (JSON.stringify({ ...request, witness: undefined }) !== JSON.stringify(plan.statement))\n throw new Error(\"prepared proof statement changed\");\n try {\n const proof = publicProof(await prover.prove(request, proverOptions));\n sameStatement(proof, plan.statement!);\n if (\n (await prover.verify(\n structuredClone(proof),\n structuredClone(plan.statement!),\n proverOptions\n )) !== true\n )\n throw new Error(\"proof verification failed\");\n return proof;\n } catch {\n options.signal?.throwIfAborted();\n throw new Error(\"operation proof generation or verification failed\");\n }\n}\n\nexport async function signOperationFunding(\n saved: SavedOperation,\n signer: FundingSigner,\n verifier?: FundingAuthorizationVerifier\n) {\n const payer = saved.plan.funding.payer!;\n if (signer.address.toLowerCase() !== payer.toLowerCase())\n throw new Error(\"funding signer is not the payer\");\n const typed = await fundingTypedData(saved);\n const signature = await signer.signTypedData(structuredClone(typed));\n return verifyFundingSignature(typed, payer, signature, verifier);\n}\n\n/** Export only typed commitments, never private note openings or authorization witnesses. */\nexport function walletSigningRequest(plan: OperationPlan) {\n return createSigningRequest(walletAuthorizationTypedData(authorizationRequest(plan)));\n}\n\n/** Recover the EOA key and build the existing private witness without receiving a private key. */\nexport async function acceptWalletSignature(plan: OperationPlan, signature: string) {\n const request = authorizationRequest(plan);\n const digest = computeWalletAuthorizationDigest(request);\n try {\n const signed = Signature.from(signature);\n const publicKey = getBytes(SigningKey.recoverPublicKey(digest, signed));\n const owner = await computeOwnerAddress(publicKey);\n if (owner.toLowerCase() !== plan.scope.ownerAddress.toLowerCase()) {\n throw new Error(\"wallet signature identity mismatch\");\n }\n return new AuthorizedStatement(plan.scope.ownerAddress, digest, {\n public_key_x: Array.from(publicKey.slice(1, 33)),\n public_key_y: Array.from(publicKey.slice(33)),\n signature: Array.from(getBytes(concat([signed.r, signed.s]))),\n });\n } catch {\n throw new Error(\"invalid wallet authorization signature\");\n }\n}\n\n/** The remote round trip may outlive the nonce or deadline selected during preparation. */\nexport async function fundingSigningRequest(\n saved: SavedOperation,\n runtime: Pick<TransactionRuntime, \"reader\" | \"options\">\n) {\n const plan = saved.plan;\n if (plan.fundingMode !== \"signature\") {\n throw new Error(\"operation does not require a funding signature\");\n }\n if (plan.kind !== \"shield\" && !saved.proof) {\n throw new Error(\"proof must precede funding authorization\");\n }\n await runtime.options.protocol.validateDeployment(runtime.reader);\n const block = await runtime.reader.getBlock(await runtime.reader.getLatestBlockNumber());\n if (block.timestamp > plan.deadline || block.timestamp > (plan.funding.deadline ?? 0n)) {\n throw new Error(\"funding authorization expired\");\n }\n if (\n (await runtime.reader.getFundingNonce(plan.context, plan.funding.payer!, block)) !==\n plan.funding.sigNonce\n ) {\n throw new Error(\"funding nonce changed; prepare again\");\n }\n const request = createSigningRequest(await fundingTypedData(saved));\n if ((await runtime.reader.getBlock(block.number)).hash !== block.hash) {\n throw new Error(\"canonical funding block changed\");\n }\n return request;\n}\n\n/** Verify against reconstructed operation data, never caller-supplied typed data. */\nexport async function acceptFundingSignature(\n saved: SavedOperation,\n signature: string,\n runtime: Pick<TransactionRuntime, \"reader\" | \"options\">\n) {\n if (!/^0x(?:[a-fA-F0-9]{2})+$/.test(signature)) {\n throw new Error(\"invalid EVM funding signature\");\n }\n const request = await fundingSigningRequest(saved, runtime);\n return verifyFundingSignature(\n request,\n saved.plan.funding.payer!,\n signature,\n runtime.options.fundingVerifier\n );\n}\n\nasync function verifyFundingSignature(\n request: FundingTypedData,\n payer: `0x${string}`,\n signature: string,\n verifier?: FundingAuthorizationVerifier\n) {\n if (!/^0x(?:[a-fA-F0-9]{2})+$/.test(signature)) {\n throw new Error(\"invalid EVM funding signature\");\n }\n const types = Object.fromEntries(\n Object.entries(request.types).map(([name, fields]) => [name, [...fields]])\n );\n let validEOA = false;\n try {\n validEOA =\n verifyTypedData(request.domain, types, request.message, signature).toLowerCase() ===\n payer.toLowerCase();\n if (validEOA) {\n // Normalize EIP-2098 and parity-style EOA signatures for Solidity SignatureChecker.\n signature = Signature.from(signature).serialized;\n }\n } catch {\n validEOA = false;\n }\n const valid = verifier\n ? await verifier.verifyTypedData({\n ...structuredClone(request),\n address: payer,\n signature: signature as `0x${string}`,\n })\n : validEOA;\n if (valid !== true) {\n throw new Error(\"invalid EVM funding signature\");\n }\n return signature as `0x${string}`;\n}\n","import { normalizeCreditPolicy, normalizeCreditUsage } from \"@invisi-labs/primitives\";\nimport { normalizeFunding } from \"@invisi-labs/protocol\";\nimport type { OperationPlan } from \"../operation-types\";\nimport { inputFacts } from \"../preparation/inputs\";\nimport type { OperationStatus } from \"../records\";\nimport { requiresAuthorization } from \"../signing/statement\";\nexport function operationPreview(plan: OperationPlan, status: OperationStatus) {\n const p = plan;\n const fee =\n p.params ??\n p.shieldParams ??\n p.credit?.creation ??\n p.credit?.update ??\n p.credit?.draw ??\n p.credit?.revocation;\n const funding = normalizeFunding(p.funding);\n return {\n id: p.id,\n kind: p.kind,\n status,\n context: { ...p.context },\n inputs: inputFacts(p).length,\n inputDetails: [\n ...p.inputs.map((input) => ({\n kind: \"notes\" as const,\n commitment: input.commitment,\n amount: input.note.amount,\n owner: input.note.ownerAddress,\n treeId: input.treeId,\n leafIndex: input.leafIndex,\n })),\n ...(p.credit?.inputs ?? []).map((input) => ({\n kind: \"credits\" as const,\n commitment: input.commitment,\n revocationShard: input.state.note.revocationShard,\n revocationSlot: input.state.note.revocationSlot,\n owner: input.state.note.ownerWalletIdentity,\n spender: input.state.note.spenderWalletIdentity,\n expiry: input.state.note.expiry,\n availableCredit: input.state.note.availableCredit,\n unlimited: input.state.note.unlimited,\n role: input.role,\n treeId: input.treeId,\n leafIndex: input.leafIndex,\n })),\n ],\n funding: {\n payer: funding.payer,\n amount: funding.amount,\n authorization: p.fundingMode,\n sigNonce: funding.sigNonce,\n deadline: funding.deadline,\n permit: { deadline: funding.permit.deadline },\n },\n creditOutputs: p.credit?.outputs.map((output) => ({\n commitment: output.commitment,\n revocationShard: output.state.note.revocationShard,\n revocationSlot: output.state.note.revocationSlot,\n expiry: output.state.note.expiry,\n owner: output.state.note.ownerWalletIdentity,\n spender: output.state.note.spenderWalletIdentity,\n ...normalizeCreditPolicy(output.state.note),\n availableCredit: output.state.note.availableCredit,\n unlimited: output.state.note.unlimited,\n ...normalizeCreditUsage(output.state.note),\n })),\n creditUpdate: p.credit?.updateChanges ? structuredClone(p.credit.updateChanges) : undefined,\n creditDraw: p.credit?.draw\n ? {\n grossAmount: p.credit.draw.totalAmount,\n feeAmount: p.credit.draw.feeAmount ?? 0n,\n netAmount: p.credit.draw.totalAmount - (p.credit.draw.feeAmount ?? 0n),\n payers: p.credit.draw.payers.map((payer) => ({ ...payer })),\n }\n : undefined,\n creditFeePayer:\n p.credit?.creation?.owner ?? p.credit?.update?.owner ?? p.credit?.revocation?.owner,\n outputs: p.outputs.map((output) => ({\n commitment: output.commitment,\n to: output.address,\n amount: output.amount,\n change: output.change,\n })),\n capacity: p.capacity,\n deadline: p.deadline,\n feeRecipient: fee?.feeRecipient,\n feeAmount: fee?.feeAmount ?? 0n,\n fundingAmount: p.funding.amount ?? 0n,\n fundingPayer: p.funding.payer,\n withdrawalAmount: p.params?.withdrawalAmount ?? 0n,\n withdrawalAddress: p.params?.withdrawalAddress,\n permissions: {\n walletAuthorization: requiresAuthorization(p),\n proof: p.kind !== \"shield\" && p.kind !== \"revoke-credit\",\n fundingAuthorization: p.fundingMode === \"signature\",\n },\n };\n}\n","import { bindBroadcasterOperation } from \"../../broadcaster/operation-bridge\";\nimport {\n Wallet,\n prepareWalletRequest,\n acceptWalletResponse,\n type PreparedWalletRequest,\n type WalletResponse,\n} from \"@invisi-labs/primitives\";\nimport { revocationSigningRequest, acceptRevocationSignature } from \"../signing/revocation\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport { TransactionOutput } from \"../../notes/TransactionOutput\";\nimport { MissingCapabilityError, type AuthorizedStatement } from \"@invisi-labs/primitives\";\nimport { normalizeFunding, type TransactionCall } from \"@invisi-labs/protocol\";\nimport type { ProofBundle, Prover } from \"@invisi-labs/prover\";\nimport { exportBroadcasterIntent } from \"../../broadcaster/intent\";\nimport { getOperationGasReference } from \"../../gas/gas-estimation\";\nimport type {\n OperationAggregateMember,\n OperationPlan,\n SavedOperation,\n TransactionProveOptions,\n TransactionRuntime,\n} from \"../operation-types\";\nimport { publicProof } from \"../proving/proof\";\nimport { sameStatement } from \"../proving/proof-integrity\";\nimport type { OperationStatus } from \"../records\";\nimport { authorizationRequest, requiresAuthorization, statement } from \"../signing/statement\";\nimport { encodeOperation } from \"./calldata\";\nimport {\n acceptFundingSignature,\n acceptWalletSignature,\n fundingSigningRequest,\n proveOperation,\n walletSigningRequest,\n} from \"./operation-execution\";\nimport { operationPreview } from \"./operation-preview\";\nfunction check(ok: unknown, message: string): asserts ok {\n if (!ok) throw new Error(message);\n}\n\ntype Runtime = TransactionRuntime & {\n reprepare?: (\n intent: import(\"../../broadcaster/broadcaster-preparation\").PreparationIntent\n ) => Promise<OperationPlan>;\n};\ntype Lifecycle = { generation: number; busy: boolean };\n/** An immutable, local transaction handle. No wallet inventory, reservations or persistence. */\nexport class PreparedTransaction {\n readonly #runtime: Runtime;\n readonly #saved: SavedOperation;\n readonly #authorization: AuthorizedStatement | undefined;\n readonly #walletRequests = new Map<string, PreparedWalletRequest<\"wallet.authorize\">>();\n readonly #lifecycle: Lifecycle;\n readonly status: OperationStatus;\n private constructor(\n runtime: Runtime,\n saved: SavedOperation,\n status: OperationStatus,\n lifecycle: Lifecycle,\n authorization?: AuthorizedStatement\n ) {\n this.#runtime = runtime;\n this.#saved = structuredClone(saved);\n this.#lifecycle = lifecycle;\n this.#authorization = authorization;\n this.status = status;\n bindBroadcasterOperation(this, {\n quote: (client, options) => this.#quoteForBroadcaster(client, options),\n submit: (client) => this.#submitViaBroadcaster(client),\n provenanceContext: async () => {\n this.current();\n return {\n chainId: this.#saved.plan.context.chainId,\n protocolAddress: this.#saved.plan.context.protocolAddress,\n };\n },\n readProvenance: async () => {\n this.current();\n return structuredClone(this.#saved.provenance);\n },\n proveProvenance: (capability, reprove) => this.#proveProvenance(capability, reprove),\n });\n Object.freeze(this);\n }\n static prepare(runtime: Runtime, plan: OperationPlan): PreparedTransaction {\n return new PreparedTransaction(\n runtime,\n { plan: structuredClone(plan), generation: 0 },\n \"prepared\",\n { generation: 0, busy: false }\n );\n }\n broadcasterQuote() {\n return this.#saved.broadcasterQuote\n ? structuredClone(this.#saved.broadcasterQuote)\n : undefined;\n }\n async #quoteForBroadcaster(\n client: import(\"../../broadcaster/index\").BroadcasterClient,\n options: import(\"../../broadcaster/broadcaster-preparation\").BroadcasterQuoteOptions\n ): Promise<PreparedTransaction> {\n this.current();\n check(\n this.status === \"prepared\" && this.#runtime.reprepare,\n \"broadcaster must attach to an unsigned prepared transaction\"\n );\n const { prepareBroadcasterPlan } =\n await import(\"../../broadcaster/broadcaster-preparation\");\n const selected = await prepareBroadcasterPlan(\n this.#saved.plan,\n this.#runtime.reprepare,\n client,\n options\n );\n return new PreparedTransaction(\n this.#runtime,\n {\n plan: selected.plan,\n broadcasterQuote: selected.quote,\n broadcasterBinding: selected.broadcasterBinding,\n generation: 0,\n },\n \"prepared\",\n { generation: 0, busy: false }\n );\n }\n async #proveProvenance(\n capability?: import(\"../../broadcaster/provenance-preparation\").PreparedProvenanceCapability,\n reprove = false\n ) {\n this.current();\n check(this.status === \"ready\", \"Ready transaction required for Provenance\");\n const { provePreparedProvenance } =\n await import(\"../../broadcaster/provenance-preparation\");\n this.#lifecycle.busy = true;\n try {\n const packet = await provePreparedProvenance(\n this.#saved,\n this.#runtime,\n capability,\n reprove\n );\n if (!this.#saved.broadcasterAttempted) this.#saved.provenance = structuredClone(packet);\n return packet;\n } finally {\n this.#lifecycle.busy = false;\n }\n }\n async #submitViaBroadcaster(client: import(\"../../broadcaster/index\").BroadcasterClient) {\n this.current();\n check(this.status === \"ready\", \"transaction is not ready\");\n const { validateBroadcastEnvelope, validatePreparedBroadcast } =\n await import(\"../../broadcaster/provenance-preparation\");\n validateBroadcastEnvelope(this.#saved, client);\n if (this.#saved.broadcasterSubmissionId) {\n try {\n return await client.status(this.#saved.broadcasterSubmissionId);\n } catch (error) {\n const { BroadcasterRpcError } = await import(\"../../broadcaster/index\");\n if (!(error instanceof BroadcasterRpcError) || error.code !== -32001) throw error;\n }\n }\n // A lost first response has no ID yet. Resend the retained request; only the relay can deduplicate it.\n if (!this.#saved.broadcasterAttempted) {\n const requirements = await client.submissionRequirements(this.#saved.broadcasterQuote!);\n if (\n requirements.provenanceRequired &&\n this.#saved.plan.inputs.length &&\n !this.#saved.provenance\n )\n await this.#proveProvenance();\n await validatePreparedBroadcast(this.#saved, client, this.#runtime);\n }\n this.#saved.externalized = true;\n this.#saved.broadcasterAttempted = true;\n const result = await client.submitTransaction(\n this.#saved.call!.data,\n this.#saved.broadcasterQuote!,\n structuredClone(this.#saved.provenance?.sidecars ?? [])\n );\n check(\n !this.#saved.broadcasterSubmissionId ||\n this.#saved.broadcasterSubmissionId === result.id,\n \"broadcaster changed submission ID\"\n );\n this.#saved.broadcasterSubmissionId = result.id;\n return result;\n }\n get id() {\n return this.#saved.plan.id;\n }\n get kind() {\n return this.#saved.plan.kind;\n }\n async estimateGas(options: { from?: `0x${string}` } = {}) {\n const provider = this.#runtime.options.provider;\n if (!provider)\n throw new MissingCapabilityError(\"ethers provider for final eth_estimateGas\");\n const call = await this.exportTransaction();\n return {\n source: \"rpc\" as const,\n gasUnits: await provider.estimateGas({ ...call, ...options }),\n };\n }\n getGasReference() {\n return getOperationGasReference(this.#saved.plan, this.#runtime.options.protocol);\n }\n /** Final Note outputs, including change; Credit outputs are not exported as IPN. */\n getOutputs(): readonly TransactionOutput[] {\n return Object.freeze(\n this.#saved.plan.outputs.map((output) => new TransactionOutput(output))\n );\n }\n preview() {\n return operationPreview(this.#saved.plan, this.status);\n }\n /** Obtain a firm quote before signing. This intent contains no private inputs or witness. */\n async exportBroadcasterIntent() {\n this.current();\n check(\n [\"prepared\", \"authorized\"].includes(this.status),\n \"quote intent requires a prepared transaction\"\n );\n return exportBroadcasterIntent(this.#saved.plan);\n }\n private current() {\n check(\n !this.#lifecycle.busy && this.#lifecycle.generation === this.#saved.generation,\n \"stale transaction handle or active worker\"\n );\n }\n private async stage(\n stage: string,\n allowed: OperationStatus[],\n work: (\n saved: SavedOperation\n ) => Promise<{ status: OperationStatus; authorization?: AuthorizedStatement }>,\n signal?: AbortSignal\n ): Promise<PreparedTransaction> {\n signal?.throwIfAborted();\n this.current();\n check(allowed.includes(this.status), `invalid transaction stage for ${stage}`);\n this.#lifecycle.busy = true;\n const saved = structuredClone(this.#saved);\n try {\n const next = await work(saved);\n signal?.throwIfAborted();\n saved.generation++;\n this.#lifecycle.generation = saved.generation;\n return new PreparedTransaction(\n this.#runtime,\n saved,\n next.status,\n this.#lifecycle,\n next.authorization ?? this.#authorization\n );\n } finally {\n this.#lifecycle.busy = false;\n }\n }\n async exportRevocationAuthorization() {\n this.current();\n check(this.status === \"prepared\", \"revocation is not awaiting authorization\");\n return revocationSigningRequest(this.#saved.plan, this.#runtime);\n }\n async withRevocationSignature(signature: Hex): Promise<PreparedTransaction> {\n this.current();\n const verified = await acceptRevocationSignature(\n this.#saved.plan,\n signature,\n this.#runtime\n );\n return this.stage(\"revocation authorization\", [\"prepared\"], async (saved) => {\n saved.plan.credit!.revocationSignature = verified;\n saved.call = await this.encode(saved);\n return { status: \"ready\" };\n });\n }\n /** Export the same portable request used by managed native wallet transports. */\n async exportWalletRequest(id: string, options: { signal?: AbortSignal } = {}) {\n options.signal?.throwIfAborted();\n this.current();\n check(\n requiresAuthorization(this.#saved.plan),\n \"operation does not require wallet authorization\"\n );\n check(\n [\"prepared\", \"authorized\"].includes(this.status),\n \"operation is not awaiting wallet authorization\"\n );\n check(!this.#walletRequests.has(id), \"wallet request id already exported\");\n const request = authorizationRequest(this.#saved.plan);\n const prepared = prepareWalletRequest(\n Wallet.fromAddress(this.#saved.plan.scope.ownerAddress),\n id,\n \"wallet.authorize\",\n {\n ...request,\n words: request.words.map(String),\n context: {\n chainId: request.context.chainId.toString(),\n protocolAddress: request.context.protocolAddress.toString(),\n },\n }\n );\n this.#walletRequests.set(id, prepared);\n return structuredClone(prepared.request);\n }\n\n /** Independently validate host authorization against the retained request and frozen plan. */\n async withWalletResponse(\n response: WalletResponse,\n options: { signal?: AbortSignal } = {}\n ): Promise<PreparedTransaction> {\n options.signal?.throwIfAborted();\n this.current();\n check(\n requiresAuthorization(this.#saved.plan),\n \"operation does not require wallet authorization\"\n );\n const prepared = this.#walletRequests.get(response.id);\n check(prepared, \"unknown wallet request response\");\n const authorization = await acceptWalletResponse(\n prepared,\n response as WalletResponse<\"wallet.authorize\">\n );\n return this.stage(\n \"wallet authorization\",\n [\"prepared\", \"authorized\"],\n async () => ({ status: \"authorized\", authorization }),\n options.signal\n );\n }\n\n /** Public EIP-712 request; signing transport and key custody belong to the caller. */\n async exportWalletAuthorization(options: { signal?: AbortSignal } = {}) {\n options.signal?.throwIfAborted();\n this.current();\n check(\n requiresAuthorization(this.#saved.plan),\n \"operation does not require wallet authorization\"\n );\n check(\n [\"prepared\", \"authorized\"].includes(this.status),\n \"operation is not awaiting wallet authorization\"\n );\n return walletSigningRequest(this.#saved.plan);\n }\n\n /** Attach an external EOA signature, retaining its witness only at the private proving boundary. */\n async withWalletSignature(\n signature: string,\n options: { signal?: AbortSignal } = {}\n ): Promise<PreparedTransaction> {\n options.signal?.throwIfAborted();\n this.current();\n check(\n requiresAuthorization(this.#saved.plan),\n \"operation does not require wallet authorization\"\n );\n check(\n [\"prepared\", \"authorized\"].includes(this.status),\n \"operation is not awaiting wallet authorization\"\n );\n const authorization = await acceptWalletSignature(this.#saved.plan, signature);\n return this.stage(\n \"wallet authorization\",\n [\"prepared\", \"authorized\"],\n async () => ({ status: \"authorized\", authorization }),\n options.signal\n );\n }\n\n /** Export only after proving when the funding authorization binds an actual proof hash. */\n async exportFundingAuthorization(options: { signal?: AbortSignal } = {}) {\n options.signal?.throwIfAborted();\n this.current();\n check(\n this.status === (this.kind === \"shield\" ? \"prepared\" : \"proved\"),\n \"operation is not awaiting funding authorization or proof\"\n );\n const request = await fundingSigningRequest(this.#saved, this.#runtime);\n options.signal?.throwIfAborted();\n this.current();\n return request;\n }\n\n /** Verify an external signature against this handle's own frozen operation. */\n async withFundingSignature(\n signature: string,\n options: { signal?: AbortSignal } = {}\n ): Promise<PreparedTransaction> {\n options.signal?.throwIfAborted();\n this.current();\n check(\n this.status === (this.kind === \"shield\" ? \"prepared\" : \"proved\"),\n \"operation is not awaiting funding authorization or proof\"\n );\n const verified = await acceptFundingSignature(this.#saved, signature, this.#runtime);\n return this.stage(\n \"funding authorization\",\n this.kind === \"shield\" ? [\"prepared\"] : [\"proved\"],\n async (saved) => {\n saved.plan.funding.signature = verified;\n if (saved.plan.statement?.target !== \"noir-recursive\") {\n saved.call = await this.encode(saved);\n }\n return { status: \"ready\" };\n },\n options.signal\n );\n }\n\n async prove(options?: TransactionProveOptions): Promise<PreparedTransaction>;\n async prove(backend: Prover, options?: TransactionProveOptions): Promise<PreparedTransaction>;\n async prove(\n backendOrOptions: Prover | TransactionProveOptions = {},\n suppliedOptions: TransactionProveOptions = {}\n ): Promise<PreparedTransaction> {\n const options = { ...(\"prove\" in backendOrOptions ? suppliedOptions : backendOrOptions) };\n check(\n !this.#saved.broadcasterQuote || options.execution !== \"aggregate\",\n \"a broadcaster quote requires direct execution\"\n );\n const plan = this.#saved.plan;\n check(\n plan.kind !== \"shield\" && plan.kind !== \"revoke-credit\",\n \"operation requires no proof\"\n );\n if (requiresAuthorization(plan)) {\n check(\n this.#authorization,\n \"local wallet authorization required; authorize again after recovery\"\n );\n }\n const prover =\n \"prove\" in backendOrOptions ? backendOrOptions : this.#runtime.options.prover;\n if (!prover) {\n throw new MissingCapabilityError(\"prover\");\n }\n return this.stage(\n \"proof\",\n requiresAuthorization(plan) ? [\"authorized\"] : [\"prepared\"],\n async (saved) => {\n const p = saved.plan;\n saved.proof = await proveOperation(\n this.#runtime.options.protocol,\n p,\n this.#authorization,\n prover,\n options\n );\n if (p.fundingMode === \"signature\") {\n return { status: \"proved\" };\n }\n if (p.statement?.target !== \"noir-recursive\") {\n saved.call = await this.encode(saved);\n }\n return { status: \"ready\" };\n },\n options.signal\n );\n }\n\n private encode(saved: SavedOperation): Promise<TransactionCall> {\n return encodeOperation(saved);\n }\n\n /** Shield caller funding needs no wallet signing or proof; this step only encodes its frozen request. */\n async ready(): Promise<PreparedTransaction> {\n check(\n (this.kind === \"shield\" && this.#saved.plan.fundingMode === \"caller\") ||\n this.kind === \"revoke-credit\",\n \"operation needs authorization or proof first\"\n );\n return this.stage(\"encoding\", [\"prepared\"], async (saved) => {\n saved.call = await this.encode(saved);\n return { status: \"ready\" };\n });\n }\n\n async exportTransaction(): Promise<TransactionCall> {\n this.current();\n check(\n this.#saved.plan.statement?.target !== \"noir-recursive\",\n \"recursive operations must be exported as aggregate members\"\n );\n check(this.status === \"ready\" && this.#saved.call, \"transaction is not ready\");\n return structuredClone(this.#saved.call);\n }\n exportProof(): ProofBundle {\n this.current();\n check(this.#saved.proof, \"transaction has no proof\");\n return publicProof(this.#saved.proof);\n }\n exportAggregateMember(): OperationAggregateMember {\n this.current();\n const saved = this.#saved,\n plan = saved.plan;\n check(\n this.status === \"ready\" &&\n plan.params &&\n saved.proof &&\n plan.statement?.target === \"noir-recursive\" &&\n plan.statement.circuitName.startsWith(\"transact_user_slots\") &&\n (plan.capacity ?? 0) <= 10,\n \"ready recursive C1..C10 transaction required\"\n );\n sameStatement(saved.proof, statement(plan));\n check(\n saved.proof.proofHex.length === 2 + 458 * 64,\n \"recursive member proof must have 458 fields\"\n );\n return {\n bundle: publicProof(saved.proof),\n statement: structuredClone(plan.statement),\n context: { ...plan.context },\n request: {\n params: structuredClone(plan.params),\n deliveries: plan.outputs.map((output) => structuredClone(output.delivery)),\n funding: normalizeFunding(plan.funding),\n },\n };\n }\n toJSON() {\n return { transaction: true, id: this.id, kind: this.kind, status: this.status };\n }\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this.toJSON();\n }\n}\n","import { MissingCapabilityError } from \"@invisi-labs/primitives\";\nimport { ProtocolRpcClient } from \"@invisi-labs/rpc\";\nimport { EthersChainReader, EthersFundingVerifier } from \"../integrations/ethers\";\nimport { configureRecipientInfrastructure } from \"../notes/recipient-infrastructure\";\nimport type { TransactionInfrastructure } from \"../transactions/operation-types\";\n\n/** Resolve adapters without starting synchronization or accessing wallet state. */\nexport function configureTransactionInfrastructure<T extends TransactionInfrastructure>(\n options: T\n): T {\n const { provider } = options;\n const reader = options.chainReader ?? (provider ? new EthersChainReader(provider) : undefined);\n const protocolRpc =\n options.protocolRpc instanceof ProtocolRpcClient && reader\n ? options.protocolRpc.withReader(reader)\n : options.protocolRpc;\n const fundingVerifier =\n options.fundingVerifier ??\n (provider\n ? new EthersFundingVerifier(provider, options.protocol.context.chainId)\n : undefined);\n return configureRecipientInfrastructure({\n ...options,\n ...(reader ? { chainReader: reader } : {}),\n ...(protocolRpc ? { protocolRpc } : {}),\n ...(fundingVerifier ? { fundingVerifier } : {}),\n });\n}\n\n/** Validate the selected chain and pinned deployment before any managed state access. */\nexport async function validateTransactionInfrastructure(\n options: TransactionInfrastructure\n): Promise<void> {\n if (!options.chainReader) throw new MissingCapabilityError(\"chain reader\");\n if (\n options.provider &&\n (await options.provider.getNetwork()).chainId !== options.protocol.context.chainId\n )\n throw new Error(\"provider deployment chain mismatch\");\n await options.protocol.validateDeployment(options.chainReader);\n}\n","import { MissingCapabilityError, Wallet } from \"@invisi-labs/primitives\";\nimport type { RegistrationOperation, RegistrationPreparation } from \"@invisi-labs/rpc\";\nimport { ProtocolRpcClient } from \"@invisi-labs/rpc\";\nimport { prepareWithErrors } from \"../errors\";\nimport { AddressRegistry } from \"../protocol/AddressRegistry\";\nimport type { PreparedTransaction } from \"../transactions/execution/PreparedTransaction\";\nimport type {\n ExplicitRevokeCreditPreparation,\n ExplicitCreateCreditPreparation,\n ExplicitDrawCreditPreparation,\n ExplicitShieldPreparation,\n ExplicitUpdateCreditPreparation,\n ExplicitTransferPreparation,\n TransactionIdentity,\n} from \"../transactions/explicit-types\";\nimport type { TransactionInfrastructure } from \"../transactions/operation-types\";\nimport { explicitPreparation } from \"../transactions/preparation/explicit-preparation\";\nimport {\n configureTransactionInfrastructure,\n validateTransactionInfrastructure,\n} from \"./infrastructure\";\n\n/** Compose independent Chain RPC and indexed Protocol RPC with local wallet capabilities. */\nexport type InvisiOptions = Omit<TransactionInfrastructure, \"wallet\" | \"protocol\" | \"coinSelector\">;\ntype InvisiInfrastructure = InvisiOptions;\n\n/** Public wallet and registry-specific inputs; signing remains external. */\nexport type RegistrationPreparationOptions = Pick<RegistrationPreparation, \"update\" | \"deadline\"> &\n Pick<TransactionIdentity, \"wallet\">;\n\n/** Stateless transaction preparation and independent infrastructure composition. */\nexport class Invisi {\n readonly #options: InvisiInfrastructure;\n\n constructor(options: InvisiOptions = {}) {\n if (\"addressLookup\" in options || \"addressResolver\" in options)\n throw new TypeError(\n \"Recipient lookup belongs to each EVM output; caller resolver injection is not supported\"\n );\n if (\"ciphertextCodecs\" in options || \"envelopeVersion\" in options) {\n throw new Error(\n \"SDK envelope versions are fixed; encode application payload bytes externally\"\n );\n }\n if (\"signer\" in options || \"fundingSigner\" in options) {\n throw new Error(\n \"Invisi does not accept signer defaults; export a signing request and attach the external signature\"\n );\n }\n for (const key of [\n \"store\",\n \"viewing\",\n \"authorization\",\n \"namespace\",\n \"coinSelector\",\n \"wallet\",\n \"protocol\",\n ]) {\n if (key in options)\n throw new TypeError(`Wallet state and permissions belong to WalletSession: ${key}`);\n }\n this.#options = {\n ...options,\n };\n Object.freeze(this);\n }\n\n /** A detached snapshot of shared infrastructure; wallet permissions and persistence stay external. */\n getInfrastructure(): Readonly<InvisiOptions> {\n return Object.freeze({\n ...this.#options,\n });\n }\n\n private async resolve(options: TransactionIdentity): Promise<TransactionInfrastructure> {\n const runtime = configureTransactionInfrastructure({\n ...this.getInfrastructure(),\n ...options,\n });\n await validateTransactionInfrastructure(runtime);\n return runtime;\n }\n\n /** Discover the selected chain's registry and prepare an independent signing request. */\n async prepareRegistration(\n options: RegistrationPreparationOptions\n ): Promise<RegistrationOperation> {\n return prepareWithErrors(\"prepareRegistration\", async () => {\n for (const key of Object.keys(options)) {\n if (![\"wallet\", \"update\", \"deadline\"].includes(key)) {\n throw new Error(`Unknown registration option: ${key}`);\n }\n }\n this.assertPublicIdentity(options);\n const selected = { ...options };\n const { provider, protocolRpc } = this.#options;\n if (!provider) throw new MissingCapabilityError(\"ethers provider\");\n if (!(protocolRpc instanceof ProtocolRpcClient)) {\n throw new MissingCapabilityError(\"Protocol RPC deployment discovery\");\n }\n const chainId = (await provider.getNetwork()).chainId;\n const deployment = await protocolRpc.getDeployment(chainId);\n if (!deployment.registry) {\n throw new MissingCapabilityError(\"receiving-key registry deployment\");\n }\n const registry = new AddressRegistry(\n { chainId, registryAddress: deployment.registry.address },\n { expectedRuntimeCodeHash: deployment.registry.runtimeCodeHash }\n );\n return registry.prepareRegistration({ ...selected, provider });\n });\n }\n\n private assertPublicIdentity(options: Pick<TransactionIdentity, \"wallet\">): void {\n const { wallet } = options;\n if (\n !(wallet instanceof Wallet) ||\n [\"getViewer\", \"getDetector\", \"exportAuthorization\"].some((key) => key in wallet)\n ) {\n throw new Error(\n \"Independent preparation requires a Wallet without private capabilities\"\n );\n }\n for (const key of [\"authorization\", \"signer\", \"fundingSigner\", \"viewing\"]) {\n if (key in options)\n throw new Error(`Independent preparation does not accept capability: ${key}`);\n }\n }\n\n private resolveExplicit(options: TransactionIdentity): Promise<TransactionInfrastructure> {\n this.assertPublicIdentity(options);\n return this.resolve({ wallet: options.wallet, protocol: options.protocol });\n }\n\n async prepareTransfer(options: ExplicitTransferPreparation): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareTransfer\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, request, request.tokenAddress);\n return preparation.prepareTransfer(request);\n });\n }\n async prepareShield(options: ExplicitShieldPreparation): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareShield\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, {}, request.tokenAddress);\n return preparation.prepareShield(request);\n });\n }\n async prepareCreateCredit(\n options: ExplicitCreateCreditPreparation\n ): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareCreateCredit\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, {}, request.tokenAddress);\n return preparation.prepareCreateCredit(request);\n });\n }\n async prepareDrawCredit(options: ExplicitDrawCreditPreparation): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareDrawCredit\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, request, request.tokenAddress);\n return preparation.prepareDrawCredit(request);\n });\n }\n async prepareUpdateCredit(\n options: ExplicitUpdateCreditPreparation\n ): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareUpdateCredit\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, request, request.tokenAddress);\n return preparation.prepareUpdateCredit(request);\n });\n }\n async prepareRevokeCredit(\n options: ExplicitRevokeCreditPreparation\n ): Promise<PreparedTransaction> {\n return prepareWithErrors(\"prepareRevokeCredit\", async () => {\n const { wallet, protocol, ...input } = options;\n const request = structuredClone(input);\n const runtime = await this.resolveExplicit(options);\n const preparation = explicitPreparation(runtime, {}, request.tokenAddress);\n return preparation.prepareRevokeCredit(request);\n });\n }\n\n toJSON() {\n return { invisi: true };\n }\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this.toJSON();\n }\n}\n","import { getAddress } from \"ethers\";\nimport { PreparedTransaction } from \"../execution/PreparedTransaction\";\nimport type { CreditInput, NoteInput } from \"../explicit-types\";\nimport type { PreparationInventory, TransactionInfrastructure } from \"../operation-types\";\nimport { positiveAmount } from \"./prepare-common\";\nimport { TransactionPreparation } from \"./transaction-preparation\";\n\n/** Only explicitly supplied records participate. No store or automatic coin selection. */\nexport function explicitPreparation(\n options: TransactionInfrastructure,\n data: {\n inputs?: readonly NoteInput[];\n creditInputs?: readonly CreditInput[];\n changeAddress?: string;\n },\n tokenAddress: `0x${string}`\n) {\n if (!options.chainReader) throw new Error(\"chain reader required\");\n const inputs = structuredClone(data.inputs ?? []);\n const credits = structuredClone(data.creditInputs ?? []);\n const inventory: PreparationInventory = { notes: {}, credits: {}, reservations: {} };\n const context = options.protocol.context;\n function position(input: NoteInput | CreditInput) {\n if (\n typeof input.treeId !== \"bigint\" ||\n input.treeId < 0n ||\n input.treeId >= 1n << 256n ||\n !Number.isInteger(input.leafIndex) ||\n input.leafIndex < 0 ||\n input.leafIndex >= 65536\n )\n throw new Error(\"invalid explicit input position\");\n }\n for (const input of inputs) {\n position(input);\n positiveAmount(input.note.amount);\n if (inventory.notes[input.commitment]) throw new Error(\"duplicate explicit note input\");\n if (\n input.note.chainId !== context.chainId ||\n input.note.protocolAddress !== BigInt(context.protocolAddress) ||\n input.note.ownerAddress !== options.wallet.ownerAddress\n )\n throw new Error(\"explicit note identity or deployment mismatch\");\n inventory.notes[input.commitment] = { ...input, spent: \"unspent\" };\n }\n for (const input of credits) {\n position(input);\n if (input.role !== \"owner\" && input.role !== \"spender\")\n throw new Error(\"invalid explicit Credit role\");\n const key = input.commitment + \":\" + input.role;\n if (inventory.credits[key]) throw new Error(\"duplicate explicit Credit input\");\n inventory.credits[key] = { ...input, spent: \"unspent\" };\n }\n const scope = {\n ...context,\n namespace: \"explicit\",\n ownerAddress: options.wallet.ownerAddress,\n };\n const capabilities = options;\n\n if (inputs.some((input) => input.note.tokenAddress !== BigInt(getAddress(tokenAddress))))\n throw new Error(\"explicit note token mismatch\");\n const runtime = {\n options: { ...capabilities, protocol: options.protocol.forToken(tokenAddress) },\n reader: options.chainReader!,\n scope,\n };\n const reprepare = (\n intent: import(\"../../broadcaster/broadcaster-preparation\").PreparationIntent\n ) =>\n import(\"../../broadcaster/broadcaster-preparation\").then(({ prepareIntent }) =>\n prepareIntent(\n {\n ...runtime,\n explicitInputs: true,\n ...(data.changeAddress ? { changeAddress: data.changeAddress } : {}),\n readInventory: async () => structuredClone(inventory),\n complete: async (plan) => plan,\n },\n intent\n )\n );\n return new TransactionPreparation<PreparedTransaction>({\n ...runtime,\n explicitInputs: true,\n ...(data.changeAddress ? { changeAddress: data.changeAddress } : {}),\n readInventory: async () => structuredClone(inventory),\n complete: async (plan) => PreparedTransaction.prepare({ ...runtime, reprepare }, plan),\n });\n}\n","import { invisiProtocolAbi } from \"@invisi-labs/protocol/contracts\";\nimport { Interface, type ParamType } from \"ethers\";\n\nconst protocolInterface = new Interface(invisiProtocolAbi);\n\n/** Decode only canonical protocol receipt bytes before routing events to token wallets. */\nexport function decodeProtocolEvent(log: { data: string; topics: readonly string[] }) {\n const decoded = protocolInterface.parseLog(log);\n if (!decoded) throw new Error(\"Unknown protocol receipt event\");\n const encoded = protocolInterface.encodeEventLog(decoded.fragment, decoded.args);\n if (\n encoded.data.toLowerCase() !== log.data.toLowerCase() ||\n encoded.topics.length !== log.topics.length ||\n encoded.topics.some(\n (topic, index) => topic.toLowerCase() !== log.topics[index]!.toLowerCase()\n )\n )\n throw new Error(\"Noncanonical protocol receipt event\");\n const value = (type: ParamType, item: unknown): unknown => {\n if (type.baseType === \"array\")\n return Array.from(item as readonly unknown[], (v) => value(type.arrayChildren!, v));\n if (type.baseType === \"tuple\")\n return Object.fromEntries(\n type.components!.map((t, i) => [t.name, value(t, (item as readonly unknown[])[i])])\n );\n return item;\n };\n const args = Object.fromEntries(\n decoded.fragment.inputs.map((type, i) => [type.name, value(type, decoded.args[i])])\n );\n return { eventName: decoded.name, args };\n}\n","import type { CanonicalReceipt } from \"@invisi-labs/protocol\";\nimport type { Address } from \"@invisi-labs/protocol/contracts\";\nimport type { DeliveryEventLog } from \"./discovery\";\nimport { decodeProtocolEvent } from \"./protocol-events\";\n\n/** Decode independently fetched canonical receipt bytes, never normalized service events. */\nexport function readProtocolLogs(\n receipt: CanonicalReceipt,\n protocolAddress: Address\n): DeliveryEventLog[] {\n if (\n receipt.status !== \"success\" ||\n !/^0x[0-9a-fA-F]{64}$/.test(receipt.transactionHash) ||\n typeof receipt.block.number !== \"bigint\" ||\n receipt.block.number < 0n ||\n !/^0x[0-9a-fA-F]{64}$/.test(receipt.block.hash)\n )\n throw new Error(\"Invalid canonical protocol receipt\");\n const seen = new Set<number>();\n return receipt.logs\n .filter((log) => log.address.toLowerCase() === protocolAddress.toLowerCase())\n .map((log) => {\n if (\n log.transactionHash.toLowerCase() !== receipt.transactionHash.toLowerCase() ||\n !Number.isSafeInteger(log.logIndex) ||\n log.logIndex < 0 ||\n seen.has(log.logIndex)\n )\n throw new Error(\"Invalid canonical receipt log identity\");\n seen.add(log.logIndex);\n const decoded = decodeProtocolEvent(log);\n return {\n address: log.address,\n eventName: decoded.eventName,\n args: decoded.args as Record<string, unknown>,\n blockNumber: receipt.block.number,\n blockHash: receipt.block.hash,\n transactionHash: receipt.transactionHash.toLowerCase(),\n logIndex: log.logIndex,\n removed: false,\n } as DeliveryEventLog;\n })\n .sort((a, b) => a.logIndex! - b.logIndex!);\n}\n","import { DeliveryAuthenticationError, validateDeliveryCiphertext } from \"@invisi-labs/primitives\";\nimport type { authenticatedDecryptor } from \"@invisi-labs/primitives\";\nimport { MAX_CIPHERTEXT_BYTES } from \"@invisi-labs/primitives\";\nimport type { Address, Hex } from \"@invisi-labs/protocol/contracts\";\nimport { isAddress } from \"ethers\";\n\nimport {\n decodeAddress,\n ReceivingAddress,\n type CreditDeliveryState,\n type Note,\n} from \"@invisi-labs/primitives\";\nimport { normalizeOpaqueDelivery } from \"@invisi-labs/protocol\";\n\nexport interface DiscoveryContext {\n chainId: bigint;\n protocolAddress: Address;\n}\n/** Decoded logs from complete canonical transaction receipts, including insertion logs. */\nexport interface DeliveryEventLog {\n address: string;\n eventName: string;\n args?: Record<string, unknown>;\n blockNumber?: bigint | null;\n blockHash?: Hex | null;\n transactionHash?: Hex | null;\n logIndex?: number | null;\n removed?: boolean;\n}\nexport interface DeliveryCandidate {\n tokenAddress: Address;\n treeId: bigint;\n leafIndex: number;\n commitment: Hex;\n role: \"funds\" | \"owner\" | \"spender\";\n delivery: { ciphertext: Hex; clue: Hex };\n blockNumber: bigint;\n blockHash: Hex;\n transactionHash: Hex;\n}\nconst EVENTS = new Set([\n \"CommitmentsInserted\",\n \"BatchOutputs\",\n \"Shield\",\n \"Transact\",\n \"CrossTreeTransact\",\n \"CreditCreated\",\n \"CreditDraw\",\n \"CreditUpdated\",\n \"CreditRevoked\",\n]);\nfunction check(ok: unknown, message: string): asserts ok {\n if (!ok) throw new Error(message);\n}\nfunction object(value: unknown): Record<string, unknown> {\n check(value && typeof value === \"object\" && !Array.isArray(value), \"invalid event object\");\n return value as Record<string, unknown>;\n}\nfunction array(value: unknown): unknown[] {\n check(Array.isArray(value), \"invalid event array\");\n check(\n Array.from({ length: value.length }, (_, i) => i in value).every(Boolean),\n \"sparse event array\"\n );\n return value;\n}\nfunction integer(value: unknown): bigint {\n check(\n typeof value === \"bigint\" || (typeof value === \"number\" && Number.isSafeInteger(value)),\n \"invalid event integer\"\n );\n const n = BigInt(value);\n check(n >= 0n, \"negative event integer\");\n return n;\n}\nfunction index(value: unknown): number {\n const n = integer(value);\n check(n < 65536n, \"invalid event leaf index\");\n return Number(n);\n}\nfunction hash(value: unknown): Hex {\n check(typeof value === \"string\" && /^0x[0-9a-fA-F]{64}$/.test(value), \"invalid event hash\");\n return value.toLowerCase() as Hex;\n}\nfunction contextCheck(context: DiscoveryContext): void {\n check(context.chainId >= 0n && context.chainId < 1n << 64n, \"invalid discovery chain\");\n check(\n isAddress(context.protocolAddress) && BigInt(context.protocolAddress) !== 0n,\n \"invalid discovery instance/token\"\n );\n}\nconst position = (tree: bigint, at: number) => `${tree}:${at}`;\n\n/** Correlate deliveries with canonical insertion events, never service-supplied balances or positions.\n * The caller selects a confirmed chain/deployment and supplies complete decoded receipts.\n */\nexport function extractDeliveryCandidates(\n logs: readonly DeliveryEventLog[],\n context: DiscoveryContext,\n confirmedThrough: bigint\n): DeliveryCandidate[] {\n contextCheck(context);\n check(confirmedThrough >= 0n, \"invalid confirmed height\");\n const relevant = logs.filter(\n (log) =>\n log.address.toLowerCase() === context.protocolAddress.toLowerCase() &&\n EVENTS.has(log.eventName)\n );\n const insertions = new Map<string, Hex>();\n const metadata = (log: DeliveryEventLog) => {\n check(!log.removed, \"discovery resync required after reorg\");\n check(\n typeof log.blockNumber === \"bigint\" &&\n log.blockNumber >= 0n &&\n log.blockNumber <= confirmedThrough,\n \"event is not confirmed\"\n );\n check(Number.isSafeInteger(log.logIndex) && log.logIndex! >= 0, \"invalid log position\");\n return {\n blockNumber: log.blockNumber,\n blockHash: hash(log.blockHash),\n transactionHash: hash(log.transactionHash),\n };\n };\n const insertionKey = (log: DeliveryEventLog, tree: bigint, at: number) =>\n `${hash(log.transactionHash)}:${position(tree, at)}`;\n for (const log of relevant) {\n metadata(log);\n if (log.eventName !== \"CommitmentsInserted\" && log.eventName !== \"BatchOutputs\") continue;\n const a = object(log.args),\n tree = integer(a.treeId),\n start = index(a.startLeafIndex),\n leaves = array(log.eventName === \"BatchOutputs\" ? a.noteCommitments : a.commitments);\n check(tree > 0n && tree < 1n << 64n, \"invalid insertion tree\");\n check(start + leaves.length <= 65536, \"insertion exceeds tree capacity\");\n for (const [i, leaf] of leaves.entries()) {\n const key = insertionKey(log, tree, start + i),\n value = hash(leaf),\n previous = insertions.get(key);\n check(!previous || previous === value, \"conflicting insertion events\");\n insertions.set(key, value);\n }\n }\n const results = new Map<string, DeliveryCandidate>();\n const add = (\n log: DeliveryEventLog,\n tree: bigint,\n at: number,\n commitment: unknown,\n role: DeliveryCandidate[\"role\"],\n wire: unknown,\n token: unknown = log.args?.token ??\n (log.args?.params as { token?: unknown; creation?: { token?: unknown } } | undefined)\n ?.token ??\n (log.args?.params as { creation?: { token?: unknown } } | undefined)?.creation?.token\n ) => {\n check(tree > 0n && tree < 1n << 64n, \"invalid output tree\");\n const inserted = insertions.get(insertionKey(log, tree, at));\n check(inserted, \"delivery has no matching canonical insertion\");\n if (commitment !== undefined)\n check(hash(commitment) === inserted, \"delivery commitment conflicts with insertion\");\n const delivery = normalizeOpaqueDelivery(wire as never, { allowEmpty: role === \"funds\" });\n check(\n typeof token === \"string\" && isAddress(token) && BigInt(token) !== 0n,\n \"invalid event token\"\n );\n const value = {\n tokenAddress: token as Address,\n treeId: tree,\n leafIndex: at,\n commitment: inserted,\n role,\n delivery,\n ...metadata(log),\n };\n const key = `${insertionKey(log, tree, at)}:${role}`,\n previous = results.get(key);\n check(\n !previous ||\n (previous.tokenAddress.toLowerCase() === token.toLowerCase() &&\n previous.delivery.ciphertext === delivery.ciphertext &&\n previous.delivery.clue === delivery.clue &&\n previous.blockHash === value.blockHash),\n \"conflicting delivery events\"\n );\n results.set(key, value);\n };\n const creation = (\n log: DeliveryEventLog,\n a: Record<string, unknown>,\n fields: Record<string, unknown>\n ) => {\n const tree = integer(a.outputTreeId),\n leaf = index(a.leafIndex),\n ds = array(a.deliveries);\n check(ds.length === 2, \"invalid Credit delivery slots\");\n add(log, tree, leaf, fields.creditCommitment, \"owner\", ds[0]);\n add(log, tree, leaf, fields.creditCommitment, \"spender\", ds[1]);\n };\n for (const log of relevant) {\n const a = object(log.args);\n if (log.eventName === \"Shield\") {\n const ds = array(a.deliveries),\n tree = integer(a.treeId),\n start = index(a.startLeafIndex);\n check(start + ds.length <= 65536, \"shield exceeds tree capacity\");\n ds.forEach((d, i) => add(log, tree, start + i, undefined, \"funds\", d));\n } else if (log.eventName === \"Transact\" || log.eventName === \"CrossTreeTransact\") {\n const cs = array(a.noteCommitments),\n ds = array(a.deliveries),\n leaves = array(a.leafIndices),\n tree = integer(a.outputTreeId);\n check(\n cs.length === ds.length && cs.length === leaves.length,\n \"invalid transact delivery slots\"\n );\n cs.forEach((c, i) => add(log, tree, index(leaves[i]), c, \"funds\", ds[i]));\n } else if (log.eventName === \"BatchOutputs\") {\n const tokens = array(a.tokens);\n const cs = array(a.noteCommitments),\n tree = integer(a.treeId),\n start = index(a.startLeafIndex),\n packed = a.packedDeliveries;\n check(\n typeof packed === \"string\" && /^0x(?:[0-9a-fA-F]{2})*$/.test(packed),\n \"invalid packed deliveries\"\n );\n check(tokens.length === cs.length, \"batch token count mismatch\");\n check(start + cs.length <= 65536, \"batch exceeds tree capacity\");\n let offset = 2;\n cs.forEach((c, i) => {\n check(offset + 4 <= packed.length, \"truncated delivery length prefix\");\n const length = Number.parseInt(packed.slice(offset, offset + 4), 16);\n offset += 4;\n check(\n length <= MAX_CIPHERTEXT_BYTES &&\n offset + length * 2 + (length === 0 ? 0 : 136) <= packed.length,\n \"invalid packed delivery length\"\n );\n const ciphertext = `0x${packed.slice(offset, offset + length * 2)}`;\n offset += length * 2;\n const clue = length === 0 ? \"0x\" : `0x${packed.slice(offset, offset + 136)}`;\n if (length !== 0) offset += 136;\n add(log, tree, start + i, c, \"funds\", { ciphertext, clue }, tokens[i]);\n });\n check(offset === packed.length, \"trailing packed delivery bytes\");\n } else if (log.eventName === \"CreditCreated\") creation(log, a, a);\n else if (log.eventName === \"CreditUpdated\") creation(log, a, object(a.params));\n else if (log.eventName === \"CreditDraw\") {\n const p = object(a.params),\n cs = array(p.creditCommitments),\n ds = array(a.deliveries),\n leaves = array(a.leafIndices),\n tree = integer(a.outputTreeId);\n check(\n ds.length === 2 * cs.length + 1 && leaves.length === cs.length + 1,\n \"invalid draw delivery slots\"\n );\n cs.forEach((c, i) => {\n add(log, tree, index(leaves[i]), c, \"owner\", ds[2 * i]);\n add(log, tree, index(leaves[i]), c, \"spender\", ds[2 * i + 1]);\n });\n add(\n log,\n tree,\n index(leaves[cs.length]),\n p.noteCommitment,\n \"funds\",\n ds[2 * cs.length],\n p.token\n );\n }\n }\n return [...results.values()];\n}\nexport interface DiscoveredNote extends Omit<DeliveryCandidate, \"delivery\" | \"role\"> {\n note: Note;\n}\nexport interface DiscoveredCredit extends Omit<DeliveryCandidate, \"delivery\"> {\n role: \"owner\" | \"spender\";\n state: CreditDeliveryState;\n}\n/** Authenticate private deliveries from a single batch of canonical receipts. */\nexport async function decryptCandidates(\n logs: readonly DeliveryEventLog[],\n options: {\n context: DiscoveryContext;\n viewing: Pick<\n ReturnType<typeof authenticatedDecryptor>,\n \"ownerAddress\" | \"decryptNote\" | \"decryptCredit\"\n > &\n Partial<Pick<ReturnType<typeof authenticatedDecryptor>, \"detectCandidates\">>;\n confirmedThrough: bigint;\n roles?: readonly DeliveryCandidate[\"role\"][];\n }\n): Promise<{\n notes: DiscoveredNote[];\n credits: DiscoveredCredit[];\n unresolved?: DeliveryCandidate[];\n}> {\n contextCheck(options.context);\n decodeAddress(ReceivingAddress.fromIdentity(options.viewing.ownerAddress).toString());\n check(\n !logs.some(\n (log) =>\n log.address.toLowerCase() === options.context.protocolAddress.toLowerCase() &&\n log.removed\n ),\n \"discovery resync required after reorg\"\n );\n const candidates = extractDeliveryCandidates(logs, options.context, options.confirmedThrough);\n const positions = new Map<string, DeliveryCandidate>();\n const unique = new Map<string, DeliveryCandidate>();\n for (const candidate of candidates) {\n const key = position(candidate.treeId, candidate.leafIndex);\n const previous = positions.get(key);\n check(\n !previous ||\n (previous.commitment === candidate.commitment &&\n previous.blockHash === candidate.blockHash &&\n previous.transactionHash === candidate.transactionHash &&\n previous.tokenAddress.toLowerCase() === candidate.tokenAddress.toLowerCase()),\n \"conflicting canonical position\"\n );\n positions.set(key, candidate);\n unique.set(`${key}:${candidate.role}`, candidate);\n }\n const notes: DiscoveredNote[] = [];\n const credits: DiscoveredCredit[] = [];\n const unresolved: DeliveryCandidate[] = [];\n const list = [...unique.values()].filter(\n (candidate) => !options.roles || options.roles.includes(candidate.role)\n );\n if (!list.length) return { notes, credits };\n const detection = options.viewing.detectCandidates\n ? await options.viewing.detectCandidates(\n list.map((candidate) => ({\n chainId: options.context.chainId,\n protocolAddress: BigInt(options.context.protocolAddress),\n tokenAddress: BigInt(candidate.tokenAddress),\n outputCommitment: candidate.commitment,\n ownerAddress: options.viewing.ownerAddress,\n role: candidate.role,\n clue: candidate.delivery.clue,\n ciphertext: candidate.delivery.ciphertext,\n }))\n )\n : list.map(() => \"candidate\" as const);\n for (const [index, candidate] of list.entries()) {\n if (detection[index] === \"not-recipient\") continue;\n if (detection[index] === \"unresolved\") {\n unresolved.push(candidate);\n continue;\n }\n const { delivery, role, ...positionData } = candidate;\n if (role === \"funds\" && delivery.ciphertext === \"0x\") continue;\n try {\n validateDeliveryCiphertext(delivery.ciphertext, role === \"funds\" ? \"funds\" : \"credit\");\n } catch {\n unresolved.push(candidate);\n continue;\n }\n const context = {\n chainId: options.context.chainId,\n protocolAddress: BigInt(options.context.protocolAddress),\n tokenAddress: BigInt(candidate.tokenAddress),\n outputCommitment: candidate.commitment,\n clue: delivery.clue,\n };\n // Authentication ambiguity is retained, never asserted to be a nonrecipient.\n try {\n if (role === \"funds\") {\n if (delivery.ciphertext === \"0x\") continue;\n const note = await options.viewing.decryptNote(delivery.ciphertext, context);\n if (note !== null) notes.push({ ...positionData, note });\n } else {\n const state = await options.viewing.decryptCredit(delivery.ciphertext, {\n ...context,\n role,\n });\n if (state !== null) credits.push({ ...positionData, role, state });\n }\n } catch (error) {\n if (error instanceof DeliveryAuthenticationError) {\n unresolved.push(candidate);\n continue;\n }\n throw error;\n }\n }\n return { notes, credits, ...(unresolved.length ? { unresolved } : {}) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB,gBAA8C;AAMnE,IAAM,kBAAN,cAA8B,SAAS;AAAA,EACjC,oBACL,SAGF;AACE,WAAO,kBAAkB,uBAAuB,YAAY;AACxD,UAAI,cAAc,SAAS;AACvB,cAAM,EAAE,UAAU,GAAG,YAAY,IAAI;AACrC,eAAO,MAAM,oBAAoB;AAAA,UAC7B,GAAG;AAAA,UACH,QAAQ,IAAI,kBAAkB,QAAQ;AAAA,QAC1C,CAAC;AAAA,MACL;AACA,aAAO,MAAM,oBAAoB,OAAO;AAAA,IAC5C,CAAC;AAAA,EACL;AACJ;;;ACvBA,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,YAAY,uBAAuB;AAG5C,eAAsB,yBAClB,MACA,SACF;AACE,QAAM,SAAS,KAAK,QAAQ;AAC5B,MAAI,CAAC,OAAQ,OAAM,MAAM,6CAA6C;AACtE,QAAM,QAAQ,QAAQ,SAAS,mBAAmB,QAAQ,MAAM;AAChE,QAAM,QAAQ,MAAM,QAAQ,OAAO,SAAS,MAAM,QAAQ,OAAO,qBAAqB,CAAC;AACvF,MAAI,MAAM,YAAY,OAAO,SAAU,OAAM,MAAM,kCAAkC;AACrF,QAAM,UAAU;AAAA,IACZ,4BAA4B,EAAE,GAAG,KAAK,SAAS,KAAK,MAAM,UAAU,GAAG,MAAM;AAAA,EACjF;AACA,OAAK,MAAM,QAAQ,OAAO,SAAS,MAAM,MAAM,GAAG,SAAS,MAAM;AAC7D,UAAM,MAAM,oCAAoC;AACpD,SAAO;AACX;AACA,eAAsB,0BAClB,MACA,WACA,SACF;AACE,MAAI,CAAC,0BAA0B,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AAQ,QAAQ,cAAc,SAAS,YAAY;AAAA,UACnE,GAAG;AAAA,UACH;AAAA,QACJ,CAAC;AACD,YAAI,UAAU,KAAM,SAAQ,KAAK,EAAE,GAAG,cAAc,MAAM,MAAM,CAAC;AAAA,MACrE;AAAA,IACJ,SAAS,OAAO;AACZ,UAAI,iBAAiB,6BAA6B;AAC9C,mBAAW,KAAK,SAAS;AACzB;AAAA,MACJ;AACA,YAAM;AAAA,IACV;AAAA,EACJ;AACA,SAAO,EAAE,OAAO,SAAS,GAAI,WAAW,SAAS,EAAE,WAAW,IAAI,CAAC,EAAG;AAC1E;","names":["index","getDocumentedGasReference","createSigningRequest","WitnessBuilder","getBytes","verifyTypedData","WitnessBuilder","createSigningRequest","getBytes","verifyTypedData","normalizeFunding","check","normalizeFunding","MissingCapabilityError","MissingCapabilityError","MissingCapabilityError","Wallet","ProtocolRpcClient","getAddress","position","getAddress","MissingCapabilityError","ProtocolRpcClient","Wallet","index","check","index"]}