@invisi-labs/sdk 1.1.6 → 1.1.7

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.
Files changed (67) hide show
  1. package/dist/{NoteOutput-DRkVnwlx.d.cts → broadcaster-preparation-DMxxZ_1Q.d.cts} +309 -120
  2. package/dist/{NoteOutput-DpDC6T2O.d.ts → broadcaster-preparation-DMxxZ_1Q.d.ts} +309 -120
  3. package/dist/broadcaster-preparation-RMWQFYNL.js +11 -0
  4. package/dist/broadcaster-preparation-UGOTO4SX.cjs +11 -0
  5. package/dist/broadcaster-preparation-UGOTO4SX.cjs.map +1 -0
  6. package/dist/chunk-7F7ZZW3L.cjs +374 -0
  7. package/dist/chunk-7F7ZZW3L.cjs.map +1 -0
  8. package/dist/{chunk-4SD3MW6N.js → chunk-EHP5TBC6.js} +1347 -2493
  9. package/dist/chunk-EHP5TBC6.js.map +1 -0
  10. package/dist/{broadcaster-preparation-QVL62KM6.js → chunk-GTPUYPQL.js} +6 -6
  11. package/dist/chunk-GTPUYPQL.js.map +1 -0
  12. package/dist/{chunk-FL4TIGWW.js → chunk-ITTGBIG2.js} +617 -521
  13. package/dist/chunk-ITTGBIG2.js.map +1 -0
  14. package/dist/chunk-J2JH6HIG.cjs +1877 -0
  15. package/dist/chunk-J2JH6HIG.cjs.map +1 -0
  16. package/dist/chunk-LOU7AP2B.cjs +128 -0
  17. package/dist/chunk-LOU7AP2B.cjs.map +1 -0
  18. package/dist/chunk-RHNIHI4P.cjs +3565 -0
  19. package/dist/chunk-RHNIHI4P.cjs.map +1 -0
  20. package/dist/{chunk-QC6TQR3R.js → chunk-XHKQ2BO2.js} +12 -12
  21. package/dist/chunk-XHKQ2BO2.js.map +1 -0
  22. package/dist/ethers.cjs +11 -385
  23. package/dist/ethers.cjs.map +1 -1
  24. package/dist/ethers.d.cts +3 -4
  25. package/dist/ethers.d.ts +3 -4
  26. package/dist/ethers.js +1 -1
  27. package/dist/index.cjs +451 -7845
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +72 -702
  30. package/dist/index.d.ts +72 -702
  31. package/dist/index.js +374 -862
  32. package/dist/index.js.map +1 -1
  33. package/dist/receipt-logs-CvC951p7.d.cts +318 -0
  34. package/dist/receipt-logs-m0-bhaxW.d.ts +318 -0
  35. package/dist/session-support.cjs +168 -0
  36. package/dist/session-support.cjs.map +1 -0
  37. package/dist/session-support.d.cts +252 -0
  38. package/dist/session-support.d.ts +252 -0
  39. package/dist/session-support.js +168 -0
  40. package/dist/session-support.js.map +1 -0
  41. package/package.json +10 -20
  42. package/dist/broadcaster-preparation-QVL62KM6.js.map +0 -1
  43. package/dist/chunk-4SD3MW6N.js.map +0 -1
  44. package/dist/chunk-FL4TIGWW.js.map +0 -1
  45. package/dist/chunk-QC6TQR3R.js.map +0 -1
  46. package/dist/indexeddb.cjs +0 -6878
  47. package/dist/indexeddb.cjs.map +0 -1
  48. package/dist/indexeddb.d.cts +0 -20
  49. package/dist/indexeddb.d.ts +0 -20
  50. package/dist/indexeddb.js +0 -71
  51. package/dist/indexeddb.js.map +0 -1
  52. package/dist/memory.cjs +0 -6886
  53. package/dist/memory.cjs.map +0 -1
  54. package/dist/memory.d.cts +0 -12
  55. package/dist/memory.d.ts +0 -12
  56. package/dist/memory.js +0 -11
  57. package/dist/sqlite.cjs +0 -6862
  58. package/dist/sqlite.cjs.map +0 -1
  59. package/dist/sqlite.d.cts +0 -28
  60. package/dist/sqlite.d.ts +0 -28
  61. package/dist/sqlite.js +0 -55
  62. package/dist/sqlite.js.map +0 -1
  63. package/dist/state-C4HZFotm.d.cts +0 -78
  64. package/dist/state-C4HZFotm.d.ts +0 -78
  65. package/dist/store-8aBhnbGr.d.ts +0 -42
  66. package/dist/store-YrbXb6CY.d.cts +0 -42
  67. /package/dist/{memory.js.map → broadcaster-preparation-RMWQFYNL.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/payment-note/codec.ts","../src/transactions/signing/statement.ts","../src/broadcaster/intent.ts","../src/payment-request/codec.ts","../src/payment-request/binary.ts","../src/payment-request/validation.ts","../src/payment-note/export.ts","../src/notes/NoteOutput.ts","../src/notes/resolve-recipient.ts","../src/payment-request/match-output.ts","../src/payment-request/execution.ts","../src/notes/recipient-infrastructure.ts","../src/discovery/membership.ts","../src/transactions/preparation/credit-values.ts","../src/transactions/preparation/transaction-preparation.ts","../src/transactions/preparation/prepare-common.ts","../src/transactions/preparation/selection.ts","../src/transactions/preparation/prepare-credit.ts"],"sourcesContent":["import { MissingCapabilityError } from \"@invisi-labs/core\";\n\n/** Stable codes returned by public SDK prepare* methods; inspect details instead of matching messages. */\nexport type InvisiErrorCode =\n /**\n * Other preparation failure, such as invalid amounts, expired deadlines,\n * or conflicting registration state. Inspect message and cause.\n */\n | \"PREPARATION_FAILED\"\n /**\n * Required infrastructure or permissions were not supplied.\n * The capability field identifies what is missing.\n */\n | \"MISSING_CAPABILITY\"\n /**\n * The recipient string is not a valid full 0i address or nonzero EVM owner address.\n * No registration lookup is attempted for this invalid string.\n */\n | \"INVALID_RECIPIENT\"\n /**\n * A successful lookup found no receiving keys for this short 0x owner\n * at the queried state. Indexed data may lag behind the latest chain state.\n * Full 0i addresses contain receiving keys and do not require registration.\n */\n | \"EVM_ADDRESS_NOT_REGISTERED\"\n /**\n * Recipient lookup failed or returned invalid keys. Inspect cause.\n * Registration status is unknown; this does not mean the owner is unregistered.\n */\n | \"RECIPIENT_LOOKUP_FAILED\";\n\nexport interface InvisiErrorDetails {\n operation?: string;\n address?: string;\n /** Zero-based index into the caller's outputs array, excluding automatic change. */\n outputIndex?: number;\n field?: string;\n capability?: string;\n cause?: unknown;\n}\n\n/** Stable application-facing preparation failure with the original cause. */\nexport class InvisiError extends Error {\n readonly code: InvisiErrorCode;\n readonly operation: string | undefined;\n readonly address: string | undefined;\n readonly outputIndex: number | undefined;\n readonly field: string | undefined;\n readonly capability: string | undefined;\n\n constructor(code: InvisiErrorCode, message: string, details: InvisiErrorDetails = {}) {\n super(message, { cause: details.cause });\n this.name = \"InvisiError\";\n this.code = code;\n this.operation = details.operation;\n this.address = details.address;\n this.outputIndex = details.outputIndex;\n this.field = details.field;\n this.capability = details.capability;\n }\n}\n\n/** Keep nested failures intact; do not infer business codes from English messages. */\nexport async function prepareWithErrors<T>(\n operation: string,\n prepare: () => Promise<T>\n): Promise<T> {\n try {\n return await prepare();\n } catch (cause) {\n if (cause instanceof InvisiError) {\n if (cause.operation) throw cause;\n throw new InvisiError(cause.code, cause.message, {\n operation,\n ...(cause.address === undefined ? {} : { address: cause.address }),\n ...(cause.outputIndex === undefined ? {} : { outputIndex: cause.outputIndex }),\n ...(cause.field === undefined ? {} : { field: cause.field }),\n ...(cause.capability === undefined ? {} : { capability: cause.capability }),\n cause: cause.cause,\n });\n }\n throw new InvisiError(\n cause instanceof MissingCapabilityError ? \"MISSING_CAPABILITY\" : \"PREPARATION_FAILED\",\n cause instanceof Error ? cause.message : \"Transaction preparation failed\",\n {\n operation,\n cause,\n ...(cause instanceof MissingCapabilityError\n ? { capability: cause.capability }\n : {}),\n }\n );\n }\n}\n","import { FIELD_MODULUS } from \"@invisi-labs/core\";\nimport { decodeBase64, encodeBase64, getAddress, getBytes, hexlify, concat } from \"ethers\";\nimport type { PaymentNoteData } from \"./types\";\n\nfunction uint(value: bigint, bytes: number): Uint8Array {\n if (typeof value !== \"bigint\" || value < 0n || value >= 1n << BigInt(bytes * 8))\n throw new RangeError(`Invalid uint${bytes * 8} payment note field`);\n return getBytes(`0x${value.toString(16).padStart(bytes * 2, \"0\")}`);\n}\nfunction validate(value: PaymentNoteData): void {\n const keys = [\n \"chainId\",\n \"protocolAddress\",\n \"tokenAddress\",\n \"amount\",\n \"ownerAddress\",\n \"nonce\",\n \"commitment\",\n ];\n if (\n !value ||\n typeof value !== \"object\" ||\n Object.keys(value).some((key) => !keys.includes(key))\n )\n throw new TypeError(\"Invalid payment note fields\");\n uint(value.chainId, 8);\n uint(value.amount, 16);\n if (value.chainId === 0n || value.amount === 0n)\n throw new RangeError(\"Positive chainId and amount required\");\n for (const key of [\"protocolAddress\", \"ownerAddress\", \"tokenAddress\"] as const) {\n getAddress(value[key]);\n if (key !== \"tokenAddress\" && BigInt(value[key]) === 0n)\n throw new RangeError(`Invalid ${key}`);\n }\n uint(value.nonce, 32);\n if (value.nonce >= FIELD_MODULUS) throw new RangeError(\"Invalid payment note nonce\");\n if (\n !/^0x[\\da-f]{64}$/i.test(value.commitment) ||\n BigInt(value.commitment) <= 0n ||\n BigInt(value.commitment) >= FIELD_MODULUS\n )\n throw new RangeError(\"Invalid payment note commitment\");\n}\nexport function encodePaymentNote(value: PaymentNoteData): string {\n validate(value);\n const bytes = concat([\n new Uint8Array([1]),\n uint(value.chainId, 8),\n getBytes(value.protocolAddress),\n getBytes(value.tokenAddress),\n uint(value.amount, 16),\n getBytes(value.ownerAddress),\n uint(value.nonce, 32),\n getBytes(value.commitment),\n ]);\n return `ipn:${encodeBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\")}`;\n}\nexport function decodePaymentNote(encoded: string): PaymentNoteData {\n if (\n typeof encoded !== \"string\" ||\n encoded.length !== 203 ||\n !/^ipn:[A-Za-z0-9_-]+$/.test(encoded)\n )\n throw new TypeError(\"Invalid payment note encoding\");\n const bytes = decodeBase64(encoded.slice(4).replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\");\n if (bytes.length !== 149 || bytes[0] !== 1)\n throw new Error(\"Unsupported payment note version or length\");\n let offset = 1;\n const take = (size: number) => {\n const value = hexlify(bytes.slice(offset, (offset += size))) as `0x${string}`;\n return value;\n };\n const value: PaymentNoteData = {\n chainId: BigInt(take(8)),\n protocolAddress: getAddress(take(20)) as `0x${string}`,\n tokenAddress: getAddress(take(20)) as `0x${string}`,\n amount: BigInt(take(16)),\n ownerAddress: getAddress(take(20)).toLowerCase() as `0x${string}`,\n nonce: BigInt(take(32)),\n commitment: take(32),\n };\n if (encodePaymentNote(value) !== encoded) throw new Error(\"Noncanonical payment note encoding\");\n return value;\n}\n","import { creditPeriods, type WalletOperation } from \"@invisi-labs/core\";\nimport {\n WitnessBuilder,\n cancelCreditPublicInputs,\n createCreditPublicInputs,\n creditDrawPublicInputs,\n topUpCreditPublicInputs,\n transactUserPublicInputs,\n} from \"@invisi-labs/protocol\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport type { ProofStatement } from \"@invisi-labs/prover\";\nimport type { OperationPlan } from \"../operation-types\";\n\nexport function requiresAuthorization(plan: OperationPlan): boolean {\n // Derive the exemption from the actual frozen transaction, never an API/mode flag.\n const ownerOnlyFullWithdrawal =\n !plan.credit &&\n plan.inputs.length > 0 &&\n plan.outputs.length === 0 &&\n plan.params !== undefined &&\n plan.params.outputCommitments.length === 0 &&\n (plan.params.feeAmount ?? 0n) === 0n &&\n BigInt(plan.params.feeRecipient ?? 0n) === 0n &&\n (plan.funding.amount ?? 0n) === 0n &&\n plan.fundingMode === \"none\" &&\n BigInt(plan.params.withdrawalAddress) === BigInt(plan.scope.ownerAddress) &&\n plan.params.withdrawalAmount ===\n plan.inputs.reduce((sum, input) => sum + input.note.amount, 0n) &&\n plan.inputs.every((input) => input.note.ownerAddress === plan.scope.ownerAddress);\n if (ownerOnlyFullWithdrawal) return false;\n return !!plan.credit || plan.inputs.length > 0;\n}\n\nexport function statement(plan: OperationPlan): ProofStatement {\n if (!plan.statement) throw new Error(\"operation has no proof statement\");\n\n const credit = plan.credit;\n let words: Hex[];\n if (credit?.topUp) {\n words = topUpCreditPublicInputs(\n plan.context,\n credit.topUp,\n credit.deliveries,\n plan.funding\n );\n } else if (credit?.creation) {\n words = createCreditPublicInputs(\n plan.context,\n credit.creation,\n credit.deliveries,\n plan.funding\n );\n } else if (credit?.draw) {\n words = creditDrawPublicInputs(plan.context, credit.draw, credit.deliveries);\n } else if (credit?.cancel) {\n words = cancelCreditPublicInputs(plan.context, credit.cancel);\n } else {\n words = transactUserPublicInputs(\n plan.context,\n plan.params!,\n plan.outputs.map((output) => output.delivery),\n plan.funding\n );\n }\n\n const result = WitnessBuilder.statement(\n plan.statement.circuitName,\n words,\n plan.statement.target\n );\n if (JSON.stringify(result) !== JSON.stringify(plan.statement)) {\n throw new Error(\"frozen operation statement changed\");\n }\n return result;\n}\n\nexport function authorizationRequest(plan: OperationPlan) {\n let operation: WalletOperation = \"transact\";\n if (plan.kind === \"draw-credit\") {\n operation = \"credit-draw\";\n } else if (\n plan.kind === \"create-credit\" ||\n plan.kind === \"top-up-credit\" ||\n plan.kind === \"cancel-credit\"\n ) {\n operation = plan.kind;\n }\n\n return {\n context: {\n chainId: plan.context.chainId,\n protocolAddress: BigInt(plan.context.protocolAddress),\n },\n operation,\n capacity: plan.capacity!,\n words: statement(plan).expectedPublicInputs.slice(0, -2).map(BigInt),\n };\n}\n\nexport function operationExpired(plan: OperationPlan, now: bigint): boolean {\n if (now > plan.deadline) return true;\n\n const credit = plan.credit;\n if (credit?.topUp && now >= credit.topUp.previousExpiry) return true;\n if (credit?.creation && now >= credit.creation.expiry) return true;\n if (credit?.draw) {\n if (credit.draw.expiries.some((expiry) => now >= expiry)) return true;\n const prepared = creditPeriods(plan.preparedAt.timestamp),\n current = creditPeriods(now);\n if (\n prepared.currentDay !== current.currentDay ||\n prepared.currentMonth !== current.currentMonth\n )\n return true;\n }\n return false;\n}\n","import { normalizeFunding } from \"@invisi-labs/protocol\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport { invisiProtocolAbi } from \"@invisi-labs/protocol/contracts\";\nimport { Interface } from \"ethers\";\nimport type { OperationPlan } from \"../transactions/operation-types\";\nimport { statement } from \"../transactions/signing/statement\";\n\n/** Public frozen request for quote signing. Empty proof/signature make this deliberately non-sendable. */\nexport function exportBroadcasterIntent(plan: OperationPlan) {\n if (plan.kind === \"draw-credit\" || (plan.statement && plan.statement.target !== \"evm\"))\n throw new Error(\"unsupported broadcaster operation\");\n if (plan.statement) statement(plan);\n const feeDefaults = <T extends { feeRecipient?: string; feeAmount?: bigint }>(params: T) => ({\n ...params,\n feeRecipient: params.feeRecipient ?? \"0x0000000000000000000000000000000000000000\",\n feeAmount: params.feeAmount ?? 0n,\n });\n const funding = { ...normalizeFunding(plan.funding), signature: \"0x\" };\n let method: string;\n let args: unknown[];\n if (plan.params) {\n method = \"transact\";\n args = [\n \"0x\",\n {\n params: feeDefaults(plan.params),\n deliveries: plan.outputs.map((o) => o.delivery),\n funding,\n },\n ];\n } else if (plan.shieldParams) {\n method = \"shield\";\n args = [\n feeDefaults(plan.shieldParams),\n plan.shieldOutputs,\n plan.outputs.map((o) => o.delivery),\n funding,\n ];\n } else if (plan.credit?.topUp) {\n method = \"topUpCredit\";\n args = [\n \"0x\",\n { ...plan.credit.topUp, creation: feeDefaults(plan.credit.topUp.creation) },\n plan.credit.deliveries,\n funding,\n ];\n } else if (plan.credit?.creation) {\n method = \"createCredit\";\n args = [\"0x\", feeDefaults(plan.credit.creation), plan.credit.deliveries, funding];\n } else if (plan.credit?.cancel) {\n method = \"cancelCredit\";\n args = [\"0x\", feeDefaults(plan.credit.cancel)];\n } else throw new Error(\"unsupported broadcaster operation\");\n const abi = invisiProtocolAbi.filter(\n (item) =>\n item.type === \"function\" &&\n item.name === method &&\n (method !== \"transact\" || item.inputs[1]?.type === \"tuple\")\n );\n return {\n sendable: false as const,\n data: new Interface(abi).encodeFunctionData(method, args) as Hex,\n };\n}\n","import { ReceivingAddress } from \"@invisi-labs/core\";\nimport { decodeBase64, encodeBase64, getBytes, hexlify } from \"ethers\";\nimport { concat, Reader, uint } from \"./binary\";\nimport type { PaymentRequest, NoteOutputRecipient } from \"./types\";\nimport { MAX_REQUEST_PAYLOAD_BYTES, validatePaymentRequest } from \"./validation\";\n\nconst PREFIX = \"ipr:\";\nconst VERSION = 1;\nconst MAX_BINARY_BYTES = 186 + MAX_REQUEST_PAYLOAD_BYTES;\nfunction base64url(data: Uint8Array): string {\n return encodeBase64(data).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Encode only the request, never the current output nonce or local registry lookup choice. */\nexport function encodePaymentRequest(request: PaymentRequest): string {\n validatePaymentRequest(request);\n const recipient = request.recipient;\n const parts = [\n new Uint8Array([\n VERSION,\n recipient.type === \"evm\" ? 1 : recipient.type === \"invisi\" ? 2 : 3,\n ]),\n uint(request.chainId, 8, \"chainId\"),\n getBytes(request.protocolAddress),\n getBytes(request.tokenAddress),\n uint(request.amount, 16, \"amount\"),\n ];\n if (recipient.type === \"identity\") parts.push(getBytes(recipient.identity));\n else {\n const parsed = ReceivingAddress.parse(recipient.address);\n parts.push(getBytes(parsed.ownerAddress));\n if (recipient.type === \"invisi\") {\n const keys = parsed.getReceivingKeys();\n parts.push(keys.viewingPublicKey, keys.clueKey);\n } else parts.push(new Uint8Array([recipient.envelope === false ? 0 : 1]));\n parts.push(new Uint8Array([recipient.nonce === undefined ? 0 : 1]));\n if (recipient.nonce !== undefined) parts.push(uint(recipient.nonce, 32, \"nonce\"));\n if (recipient.type === \"invisi\" || recipient.envelope !== false) {\n const payload = request.payload ?? new Uint8Array();\n parts.push(uint(BigInt(payload.length), 2, \"payloadLength\"), payload);\n }\n }\n return PREFIX + base64url(concat(parts));\n}\n\n/** Decode a canonical Note request offline, with exact resource and byte-layout checks. */\nexport function decodePaymentRequest(encoded: string): PaymentRequest {\n if (\n typeof encoded !== \"string\" ||\n !encoded.startsWith(PREFIX) ||\n encoded.length > 4 + Math.ceil((MAX_BINARY_BYTES * 8) / 6)\n )\n throw new Error(\"Invalid payment request encoding\");\n const text = encoded.slice(PREFIX.length);\n if (!/^[A-Za-z0-9_-]+$/.test(text) || text.length % 4 === 1)\n throw new Error(\"Invalid payment request Base64URL\");\n const data = decodeBase64(\n text.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (text.length % 4)) % 4)\n );\n if (base64url(data) !== text) throw new Error(\"Noncanonical payment request Base64URL\");\n const reader = new Reader(data);\n if (reader.integer(1) !== BigInt(VERSION))\n throw new Error(\"Unsupported payment request version\");\n const type = reader.integer(1);\n if (type < 1n || type > 3n) throw new Error(\"Unsupported payment request recipient type\");\n const context = {\n chainId: reader.integer(8),\n protocolAddress: hexlify(reader.take(20)) as `0x${string}`,\n tokenAddress: hexlify(reader.take(20)) as `0x${string}`,\n amount: reader.integer(16),\n };\n let recipient: NoteOutputRecipient;\n let payload: Uint8Array | undefined;\n if (type === 3n)\n recipient = { type: \"identity\", identity: hexlify(reader.take(32)) as `0x${string}` };\n else {\n const ownerAddress = hexlify(reader.take(20)) as `0x${string}`;\n let address: string;\n let envelope = true;\n if (type === 2n)\n address = ReceivingAddress.from({\n ownerAddress,\n viewingPublicKey: reader.take(33),\n clueKey: reader.take(32),\n }).toString();\n else {\n address = ReceivingAddress.fromIdentity(ownerAddress).toString();\n const value = reader.integer(1);\n if (value > 1n) throw new Error(\"Invalid envelope flag\");\n envelope = value === 1n;\n }\n const present = reader.integer(1);\n if (present > 1n) throw new Error(\"Invalid nonce presence flag\");\n const nonce = present === 1n ? reader.integer(32) : undefined;\n recipient =\n type === 2n\n ? { type: \"invisi\", address, ...(nonce === undefined ? {} : { nonce }) }\n : { type: \"evm\", address, envelope, ...(nonce === undefined ? {} : { nonce }) };\n if (envelope) {\n const length = Number(reader.integer(2));\n if (length > MAX_REQUEST_PAYLOAD_BYTES)\n throw new RangeError(\"payload exceeds funds envelope limit\");\n if (length !== 0) payload = reader.take(length);\n }\n }\n reader.done();\n const request = {\n ...context,\n recipient,\n ...(payload === undefined ? {} : { payload }),\n } as PaymentRequest;\n validatePaymentRequest(request);\n if (encodePaymentRequest(request) !== encoded) throw new Error(\"Noncanonical payment request\");\n return request;\n}\n","/** Fixed-width unsigned big-endian encoding; no runtime-specific bigint extension. */\nexport function uint(value: bigint, size: number, name: string): Uint8Array {\n if (typeof value !== \"bigint\" || value < 0n || value >= 1n << BigInt(size * 8))\n throw new RangeError(`${name} must be uint${size * 8}`);\n const result = new Uint8Array(size);\n for (let i = size - 1; i >= 0; i--) {\n result[i] = Number(value & 255n);\n value >>= 8n;\n }\n return result;\n}\nexport function concat(parts: readonly Uint8Array[]): Uint8Array {\n const result = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let offset = 0;\n for (const part of parts) {\n result.set(part, offset);\n offset += part.length;\n }\n return result;\n}\nexport class Reader {\n #offset = 0;\n constructor(readonly data: Uint8Array) {}\n take(size: number): Uint8Array {\n if (this.#offset + size > this.data.length) throw new Error(\"Truncated payment request\");\n const result = this.data.slice(this.#offset, this.#offset + size);\n this.#offset += size;\n return result;\n }\n integer(size: number): bigint {\n return this.take(size).reduce((n, b) => (n << 8n) | BigInt(b), 0n);\n }\n done(): void {\n if (this.#offset !== this.data.length) throw new Error(\"Trailing payment request bytes\");\n }\n}\n","import { FIELD_MODULUS, MAX_CIPHERTEXT_BYTES, ReceivingAddress } from \"@invisi-labs/core\";\nimport { getAddress } from \"ethers\";\nimport { uint } from \"./binary\";\nimport type { PaymentRequest } from \"./types\";\n\n/** Funds envelope v1 consists of 160 fixed bytes plus the raw application payload. */\nexport const MAX_REQUEST_PAYLOAD_BYTES = MAX_CIPHERTEXT_BYTES - 160;\nexport function fields(value: unknown, allowed: readonly string[], name: string): void {\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new TypeError(`Invalid ${name}`);\n for (const key of Object.keys(value))\n if (!allowed.includes(key)) throw new TypeError(`Unsupported ${name} field ${key}`);\n}\nexport function nonce(value: bigint): bigint {\n uint(value, 32, \"nonce\");\n if (value >= FIELD_MODULUS)\n throw new RangeError(\"nonce must be a canonical BN254 field element\");\n return value;\n}\nexport function validatePaymentRequest(request: PaymentRequest): void {\n fields(\n request,\n [\"chainId\", \"protocolAddress\", \"tokenAddress\", \"amount\", \"recipient\", \"payload\"],\n \"payment request\"\n );\n uint(request.chainId, 8, \"chainId\");\n if (request.chainId === 0n) throw new RangeError(\"chainId must be positive\");\n const protocol = getAddress(request.protocolAddress);\n getAddress(request.tokenAddress);\n if (BigInt(protocol) === 0n) throw new RangeError(\"protocol address must be nonzero\");\n uint(request.amount, 16, \"amount\");\n if (request.amount === 0n) throw new RangeError(\"amount must be positive\");\n const recipient = request.recipient;\n fields(\n recipient,\n [\"type\", \"address\", \"nonce\", \"identity\", \"envelope\", \"addressLookup\"],\n \"recipient\"\n );\n if (recipient.type === \"identity\") {\n fields(recipient, [\"type\", \"identity\"], \"identity recipient\");\n if (\n typeof recipient.identity !== \"string\" ||\n !/^0x[\\da-f]{64}$/i.test(recipient.identity) ||\n BigInt(recipient.identity) <= 0n ||\n BigInt(recipient.identity) >= FIELD_MODULUS\n )\n throw new RangeError(\"identity must be a nonzero canonical BN254 field element\");\n if (request.payload !== undefined)\n throw new TypeError(\"payload requires an encrypted envelope\");\n return;\n }\n if (recipient.type !== \"evm\" && recipient.type !== \"invisi\")\n throw new TypeError(\"Invalid recipient type\");\n fields(\n recipient,\n recipient.type === \"evm\"\n ? [\"type\", \"address\", \"nonce\", \"envelope\", \"addressLookup\"]\n : [\"type\", \"address\", \"nonce\"],\n \"recipient\"\n );\n const parsed = ReceivingAddress.parse(recipient.address);\n if ((recipient.type === \"evm\") !== (parsed.kind === \"short\"))\n throw new TypeError(\"recipient address type mismatch\");\n if (BigInt(parsed.ownerAddress) === 0n) throw new RangeError(\"owner address must be nonzero\");\n if (recipient.nonce !== undefined) nonce(recipient.nonce);\n if (recipient.type === \"evm\") {\n if (recipient.envelope !== undefined && typeof recipient.envelope !== \"boolean\")\n throw new TypeError(\"evm envelope must be boolean\");\n if (\n recipient.addressLookup !== undefined &&\n ![\"chain\", \"protocol-rpc\"].includes(recipient.addressLookup)\n )\n throw new TypeError(\"Invalid recipient addressLookup\");\n if (recipient.envelope === false && request.payload !== undefined)\n throw new TypeError(\"payload requires an encrypted envelope\");\n }\n if (request.payload !== undefined && !(request.payload instanceof Uint8Array))\n throw new TypeError(\"payload must be Uint8Array\");\n if ((request.payload?.length ?? 0) > MAX_REQUEST_PAYLOAD_BYTES)\n throw new RangeError(\"payload exceeds funds envelope limit\");\n}\n","import type { PreparedOutput } from \"../transactions/operation-types\";\nimport { encodePaymentNote } from \"./codec\";\n\n/** Export the complete opening; identity-only outputs intentionally have no opening. */\nexport function exportPaymentNote(output: PreparedOutput): string {\n const note = output.note;\n if (output.recipient.type === \"identity\" || !note)\n throw new Error(\"Identity outputs cannot export an IPN\");\n return encodePaymentNote({\n chainId: note.chainId,\n protocolAddress: output.context.protocolAddress,\n tokenAddress: output.context.tokenAddress,\n amount: note.amount,\n ownerAddress: note.ownerAddress,\n nonce: note.nonce,\n commitment: output.commitment,\n });\n}\n","import { exportPaymentNote } from \"../payment-note/export\";\nimport {\n FIELD_MODULUS,\n ReceivingAddress,\n computeNoteCommitment,\n computeNoteIdentity,\n createClue,\n encryptPrivateTransferNote,\n generateNonce,\n type Note,\n type ReceivingKeyLookup,\n} from \"@invisi-labs/core\";\nimport type { Delivery, Hex } from \"@invisi-labs/protocol/contracts\";\nimport { AbiCoder, getAddress, hexlify, keccak256 } from \"ethers\";\nimport { InvisiError } from \"../errors\";\nimport type { PreparedOutput } from \"../transactions/operation-types\";\nimport type { AddressLookup } from \"./recipient-infrastructure\";\nimport { resolveRecipient } from \"./resolve-recipient\";\n\nimport type {\n NoteOutputContext,\n NoteOutputRecipient,\n PaymentRequest,\n NoteOutputExecutionOptions,\n} from \"../payment-request/types\";\nexport type {\n NoteOutputContext,\n NoteOutputRecipient,\n PaymentRequest,\n NoteOutputExecutionOptions,\n} from \"../payment-request/types\";\nimport { encodePaymentRequest, decodePaymentRequest } from \"../payment-request/codec\";\nimport { assertRequestMatchesOutput } from \"../payment-request/match-output\";\nimport { applyExecutionOptions } from \"../payment-request/execution\";\nfunction nonceValue(value: bigint): bigint {\n if (typeof value !== \"bigint\" || value < 0n || value >= FIELD_MODULUS)\n throw new RangeError(\"nonce must be a canonical BN254 field element\");\n return value;\n}\nfunction identityValue(value: Hex): Hex {\n if (\n typeof value !== \"string\" ||\n !/^0x[0-9a-fA-F]{64}$/.test(value) ||\n BigInt(value) <= 0n ||\n BigInt(value) >= FIELD_MODULUS\n )\n throw new RangeError(\"identity must be a nonzero canonical BN254 field element\");\n return value.toLowerCase() as Hex;\n}\nfunction payloadCopy(value?: Uint8Array): Uint8Array {\n if (value === undefined) return new Uint8Array();\n if (!(value instanceof Uint8Array)) throw new TypeError(\"payload must be Uint8Array\");\n return Uint8Array.from(value);\n}\nfunction fingerprint(delivery: Delivery): Hex {\n return keccak256(\n AbiCoder.defaultAbiCoder().encode([\"bytes\", \"bytes\"], [delivery.ciphertext, delivery.clue])\n ) as Hex;\n}\nfunction checkedContext(context: NoteOutputContext): NoteOutputContext {\n if (typeof context.chainId !== \"bigint\" || context.chainId <= 0n)\n throw new RangeError(\"chainId must be positive\");\n const protocolAddress = getAddress(context.protocolAddress) as Hex;\n const tokenAddress = getAddress(context.tokenAddress) as Hex;\n if (BigInt(protocolAddress) === 0n) throw new RangeError(\"protocol address must be nonzero\");\n return { chainId: context.chainId, protocolAddress, tokenAddress };\n}\nfunction encrypted(recipient: NoteOutputRecipient): boolean {\n return (\n recipient.type === \"invisi\" || (recipient.type === \"evm\" && recipient.envelope !== false)\n );\n}\nfunction rejectLegacy(value: object): void {\n for (const key of [\n \"expectedCommitment\",\n \"nonce\",\n \"envelope\",\n \"context\",\n \"to\",\n \"addressResolver\",\n \"addressLookup\",\n ])\n if (key in value) throw new TypeError(`${key} is not a NoteOutput create option`);\n}\nconst outputCreation = Symbol(\"NoteOutput.create\");\n\n/** Immutable output statement and optional recoverable opening. */\nexport class NoteOutput {\n readonly to: string;\n readonly ipp: string;\n readonly amount: bigint;\n readonly identity: Hex;\n readonly commitment: Hex;\n readonly deliveryFingerprint: Hex;\n /** Encrypted EVM delivery is resolved by preparation; the original offline intent stays pending. */\n readonly deliveryPending: boolean;\n declare readonly context: NoteOutputContext;\n declare readonly recipient: NoteOutputRecipient;\n declare readonly nonce: bigint | undefined;\n declare readonly payload: Uint8Array;\n declare readonly preparedOutput: PreparedOutput;\n private constructor(output: PreparedOutput, token: symbol, ipp: string) {\n if (token !== outputCreation)\n throw new TypeError(\"outputs must be created with NoteOutput.create\");\n const saved = structuredClone(output);\n this.ipp = ipp;\n this.to = saved.address;\n this.amount = saved.amount;\n this.identity = saved.identity;\n this.commitment = saved.commitment;\n this.deliveryFingerprint = fingerprint(saved.delivery);\n this.deliveryPending = saved.deliveryPending === true;\n Object.defineProperties(this, {\n context: { enumerable: true, get: () => structuredClone(saved.context) },\n recipient: { enumerable: true, get: () => structuredClone(saved.recipient) },\n nonce: { enumerable: true, get: () => saved.note?.nonce },\n payload: { enumerable: true, get: () => payloadCopy(saved.note?.payload) },\n preparedOutput: { enumerable: true, get: () => structuredClone(saved) },\n });\n Object.freeze(this);\n }\n /** Private offline delivery data; does not assert that the output has been mined. */\n exportPaymentNote(): string {\n return exportPaymentNote(this.preparedOutput);\n }\n static async create(\n input: PaymentRequest | string,\n execution: NoteOutputExecutionOptions = {}\n ): Promise<NoteOutput> {\n if (typeof input !== \"string\") rejectLegacy(input);\n const request =\n typeof input === \"string\" ? decodePaymentRequest(input) : structuredClone(input);\n rejectLegacy(request);\n const options = applyExecutionOptions(request, execution);\n if (\n typeof options.amount !== \"bigint\" ||\n options.amount <= 0n ||\n options.amount >= 1n << 128n\n )\n throw new RangeError(\"amount must be a positive uint128\");\n const context = checkedContext(options);\n const recipient = structuredClone(options.recipient);\n if (!recipient || ![\"evm\", \"invisi\", \"identity\"].includes(recipient.type))\n throw new TypeError(\"invalid recipient type\");\n if (\"expectedCommitment\" in recipient)\n throw new TypeError(\"expectedCommitment is not supported\");\n const envelope = encrypted(recipient);\n if (!envelope && options.payload !== undefined)\n throw new TypeError(\"payload requires an encrypted envelope\");\n let identity: Hex;\n let note: Note | undefined;\n let resolved: ReceivingAddress | undefined;\n let address: string;\n if (recipient.type === \"identity\") {\n if (\"nonce\" in recipient || \"envelope\" in recipient || \"addressLookup\" in recipient)\n throw new TypeError(\"identity recipient cannot specify nonce or envelope\");\n identity = identityValue(recipient.identity);\n address = identity;\n } else {\n if (\n recipient.type === \"evm\" &&\n recipient.envelope !== undefined &&\n typeof recipient.envelope !== \"boolean\"\n )\n throw new TypeError(\"evm envelope must be boolean\");\n if (recipient.type === \"invisi\" && \"envelope\" in recipient)\n throw new TypeError(\"invisi recipient is always encrypted\");\n let parsed: ReceivingAddress;\n try {\n parsed = ReceivingAddress.parse(recipient.address);\n } catch (cause) {\n throw new InvisiError(\"INVALID_RECIPIENT\", \"Invalid recipient address\", {\n address: recipient.address,\n field: \"to\",\n cause,\n });\n }\n if ((recipient.type === \"evm\") !== (parsed.kind === \"short\"))\n throw new TypeError(\"recipient address type mismatch\");\n resolved = parsed;\n if (recipient.type === \"evm\") {\n if (\n recipient.addressLookup !== undefined &&\n recipient.addressLookup !== \"chain\" &&\n recipient.addressLookup !== \"protocol-rpc\"\n )\n throw new TypeError(\"invalid recipient addressLookup\");\n recipient.addressLookup ??= \"protocol-rpc\";\n } else if (\"addressLookup\" in recipient)\n throw new TypeError(\"addressLookup only applies to EVM recipients\");\n const nonce = nonceValue(\n recipient.nonce === undefined ? generateNonce() : recipient.nonce\n );\n recipient.nonce = nonce;\n identity = await computeNoteIdentity(BigInt(resolved.ownerAddress), nonce);\n address = recipient.address;\n note = {\n chainId: context.chainId,\n protocolAddress: BigInt(context.protocolAddress),\n tokenAddress: BigInt(context.tokenAddress),\n ownerAddress: resolved.ownerAddress,\n amount: options.amount,\n nonce,\n payload: payloadCopy(options.payload),\n };\n }\n const commitment = await computeNoteCommitment(\n context.chainId,\n identity,\n BigInt(context.tokenAddress),\n options.amount\n );\n let delivery: Delivery = { ciphertext: \"0x\", clue: \"0x\" };\n if (envelope && recipient.type === \"invisi\") {\n const keys = resolved!.getReceivingKeys();\n delivery = {\n ciphertext: hexlify(\n await encryptPrivateTransferNote(keys.viewingPublicKey, note!, {\n chainId: context.chainId,\n protocolAddress: BigInt(context.protocolAddress),\n outputCommitment: commitment,\n })\n ) as Hex,\n clue: hexlify(createClue(keys.clueKey)) as Hex,\n };\n }\n const ipp = typeof input === \"string\" ? input : encodePaymentRequest(request);\n return new NoteOutput(\n {\n context,\n recipient,\n amount: options.amount,\n ...(note ? { note } : {}),\n identity,\n commitment,\n delivery,\n ...(envelope && recipient.type === \"evm\" ? { deliveryPending: true as const } : {}),\n address,\n change: false,\n },\n outputCreation,\n ipp\n );\n }\n assertCommitment(expectedHex: Hex): void {\n if (\n typeof expectedHex !== \"string\" ||\n expectedHex.toLowerCase() !== this.commitment.toLowerCase()\n )\n throw new Error(\"note output commitment mismatch\");\n }\n get note(): Note | undefined {\n return this.preparedOutput.note;\n }\n get delivery(): Delivery {\n return this.preparedOutput.delivery;\n }\n}\nexport async function materializeNoteOutput(\n payment: NoteOutput,\n context: NoteOutputContext,\n lookup?: (source: AddressLookup) => ReceivingKeyLookup\n): Promise<PreparedOutput> {\n if (\"expectedCommitment\" in payment) throw new TypeError(\"expectedCommitment is not supported\");\n const cached = (payment as Partial<NoteOutput>).preparedOutput;\n if (cached === undefined) throw new TypeError(\"outputs must be created with NoteOutput.create\");\n const output = structuredClone(cached);\n const expectedContext = checkedContext(context);\n const copied = payment as NoteOutput;\n for (const actual of [output.context, copied.context]) {\n if (\n !actual ||\n actual.chainId !== expectedContext.chainId ||\n BigInt(actual.protocolAddress) !== BigInt(expectedContext.protocolAddress) ||\n BigInt(actual.tokenAddress) !== BigInt(expectedContext.tokenAddress)\n )\n throw new Error(\"note output chain, protocol or token mismatch\");\n }\n if (\n output.amount !== payment.amount ||\n output.address !== payment.to ||\n output.identity !== copied.identity ||\n output.commitment !== copied.commitment ||\n JSON.stringify(output.recipient, (_, v) => (typeof v === \"bigint\" ? v.toString() : v)) !==\n JSON.stringify(copied.recipient, (_, v) => (typeof v === \"bigint\" ? v.toString() : v))\n )\n throw new Error(\"note output material does not match payment intent\");\n if (fingerprint(output.delivery) !== copied.deliveryFingerprint)\n throw new Error(\"note output delivery fingerprint mismatch\");\n const hasCiphertext = output.delivery.ciphertext !== \"0x\";\n const hasClue = output.delivery.clue !== \"0x\";\n const pending = output.deliveryPending === true;\n if (\n copied.deliveryPending !== pending ||\n (\"deliveryPending\" in output && output.deliveryPending !== true)\n )\n throw new Error(\"note output pending delivery mismatch\");\n if (\n hasCiphertext !== hasClue ||\n (pending\n ? hasCiphertext || output.recipient.type !== \"evm\" || !encrypted(output.recipient)\n : hasCiphertext !== encrypted(output.recipient))\n )\n throw new Error(\"note output delivery mode mismatch\");\n const recipient = output.recipient;\n if (\"expectedCommitment\" in recipient) throw new Error(\"expectedCommitment is not supported\");\n if (!encrypted(recipient) && payloadCopy(payment.payload).length !== 0)\n throw new Error(\"payload requires an encrypted envelope\");\n if (recipient.type === \"identity\") {\n if (\n !/^0x[0-9a-fA-F]{64}$/.test(output.identity) ||\n output.address !== output.identity ||\n output.note ||\n \"nonce\" in recipient ||\n \"envelope\" in recipient ||\n \"addressLookup\" in recipient ||\n recipient.identity.toLowerCase() !== output.identity.toLowerCase()\n )\n throw new Error(\"opaque identity output material mismatch\");\n identityValue(output.identity);\n } else {\n const note = output.note;\n const parsed = ReceivingAddress.parse(recipient.address);\n if (\n recipient.type === \"evm\" &&\n recipient.addressLookup !== undefined &&\n recipient.addressLookup !== \"chain\" &&\n recipient.addressLookup !== \"protocol-rpc\"\n )\n throw new Error(\"invalid recipient addressLookup\");\n if (recipient.type === \"invisi\" && \"addressLookup\" in recipient)\n throw new Error(\"addressLookup only applies to EVM recipients\");\n if (\n output.address !== recipient.address ||\n (recipient.type === \"evm\" &&\n recipient.envelope !== undefined &&\n typeof recipient.envelope !== \"boolean\") ||\n (recipient.type === \"invisi\" && \"envelope\" in recipient)\n )\n throw new Error(\"recipient material mismatch\");\n if (\n !note ||\n note.chainId !== context.chainId ||\n note.protocolAddress !== BigInt(context.protocolAddress) ||\n note.tokenAddress !== BigInt(context.tokenAddress) ||\n note.ownerAddress !== parsed.ownerAddress ||\n note.amount !== output.amount ||\n note.nonce !== recipient.nonce ||\n note.nonce !== payment.nonce ||\n hexlify(payloadCopy(note.payload)) !== hexlify(payloadCopy(payment.payload))\n )\n throw new Error(\"note output opening does not match payment intent\");\n if ((recipient.type === \"evm\") !== (parsed.kind === \"short\"))\n throw new Error(\"recipient type mismatch\");\n if (\n (await computeNoteIdentity(BigInt(note.ownerAddress), nonceValue(note.nonce))) !==\n output.identity\n )\n throw new Error(\"note output identity mismatch\");\n }\n if (\n typeof output.amount !== \"bigint\" ||\n output.amount <= 0n ||\n output.amount >= 1n << 128n ||\n (await computeNoteCommitment(\n context.chainId,\n output.identity,\n BigInt(context.tokenAddress),\n output.amount\n )) !== output.commitment\n )\n throw new Error(\"note output commitment mismatch\");\n assertRequestMatchesOutput(payment.ipp, output);\n if (pending) {\n if (recipient.type !== \"evm\") throw new Error(\"only EVM outputs may have pending delivery\");\n const resolved = await resolveRecipient(\n recipient.address,\n lookup?.(recipient.addressLookup ?? \"protocol-rpc\"),\n { field: \"to\" }\n );\n const keys = resolved.getReceivingKeys();\n output.delivery = {\n ciphertext: hexlify(\n await encryptPrivateTransferNote(keys.viewingPublicKey, output.note!, {\n chainId: context.chainId,\n protocolAddress: BigInt(context.protocolAddress),\n outputCommitment: output.commitment,\n })\n ) as Hex,\n clue: hexlify(createClue(keys.clueKey)) as Hex,\n };\n delete output.deliveryPending;\n }\n return output;\n}\n\n/** Retain a validated factory output's resolved delivery in a copyable operation intent. */\nexport function resolvedOutputSnapshot(payment: NoteOutput, output: PreparedOutput): NoteOutput {\n const copy = structuredClone(payment);\n Object.assign(copy, {\n preparedOutput: structuredClone(output),\n deliveryFingerprint: fingerprint(output.delivery),\n deliveryPending: false,\n });\n return copy;\n}\n","import {\n MissingCapabilityError,\n ReceivingAddress,\n type ReceivingKeyLookup,\n} from \"@invisi-labs/core\";\nimport { InvisiError, type InvisiErrorDetails } from \"../errors\";\n\n/** Resolve once during preparation; prepared deliveries keep this public key snapshot. */\nexport async function resolveRecipient(\n address: string,\n lookup: ReceivingKeyLookup | undefined,\n details: Pick<InvisiErrorDetails, \"field\" | \"outputIndex\"> = {}\n): Promise<ReceivingAddress> {\n const context = { ...details, address };\n let recipient: ReceivingAddress;\n try {\n recipient = ReceivingAddress.parse(address);\n } catch (cause) {\n throw new InvisiError(\"INVALID_RECIPIENT\", \"Invalid recipient address\", {\n ...context,\n cause,\n });\n }\n if (recipient.kind === \"long\") return recipient;\n if (!lookup) {\n throw new InvisiError(\"MISSING_CAPABILITY\", \"Missing registry lookup capability\", {\n ...context,\n capability: \"registry lookup\",\n });\n }\n let keys: Awaited<ReturnType<ReceivingKeyLookup>>;\n try {\n keys = await lookup(recipient.ownerAddress);\n } catch (cause) {\n if (cause instanceof MissingCapabilityError) {\n throw new InvisiError(\"MISSING_CAPABILITY\", cause.message, {\n ...context,\n cause,\n capability: cause.capability,\n });\n }\n throw new InvisiError(\"RECIPIENT_LOOKUP_FAILED\", \"Recipient registry lookup failed\", {\n ...context,\n cause,\n });\n }\n if (keys == null) {\n throw new InvisiError(\n \"EVM_ADDRESS_NOT_REGISTERED\",\n \"EVM address has no registered receiving keys\",\n context\n );\n }\n try {\n return ReceivingAddress.from({\n ownerAddress: recipient.ownerAddress,\n viewingPublicKey: keys.viewingPublicKey,\n clueKey: keys.clueKey,\n });\n } catch (cause) {\n throw new InvisiError(\n \"RECIPIENT_LOOKUP_FAILED\",\n \"Registry returned invalid receiving keys\",\n { ...context, cause }\n );\n }\n}\n","import { ReceivingAddress } from \"@invisi-labs/core\";\nimport { hexlify } from \"ethers\";\nimport type { PreparedOutput } from \"../transactions/operation-types\";\nimport { decodePaymentRequest } from \"./codec\";\n\n/** A copyable factory output must still satisfy its original public request. */\nexport function assertRequestMatchesOutput(ipp: string, output: PreparedOutput): void {\n const request = decodePaymentRequest(ipp);\n const expected = request.recipient;\n const actual = output.recipient;\n if (\n request.chainId !== output.context.chainId ||\n BigInt(request.protocolAddress) !== BigInt(output.context.protocolAddress) ||\n BigInt(request.tokenAddress) !== BigInt(output.context.tokenAddress) ||\n request.amount !== output.amount ||\n expected.type !== actual.type\n )\n throw new Error(\"IPR does not match output context or recipient\");\n if (expected.type === \"identity\") {\n if (actual.type !== \"identity\" || BigInt(expected.identity) !== BigInt(actual.identity))\n throw new Error(\"IPR identity mismatch\");\n return;\n }\n if (actual.type === \"identity\") throw new Error(\"IPR recipient type mismatch\");\n const parsed = ReceivingAddress.parse(expected.address);\n const resolved = ReceivingAddress.parse(actual.address);\n if (\n parsed.ownerAddress !== resolved.ownerAddress ||\n (expected.nonce !== undefined && expected.nonce !== output.note?.nonce) ||\n hexlify(request.payload ?? new Uint8Array()) !==\n hexlify(output.note?.payload ?? new Uint8Array())\n )\n throw new Error(\"IPR does not match output opening\");\n if (\n expected.type === \"evm\" &&\n actual.type === \"evm\" &&\n (expected.envelope !== false) !== (actual.envelope !== false)\n )\n throw new Error(\"IPR envelope mismatch\");\n if (expected.type === \"invisi\") {\n const a = parsed.getReceivingKeys(),\n b = resolved.getReceivingKeys();\n if (\n hexlify(a.viewingPublicKey) !== hexlify(b.viewingPublicKey) ||\n hexlify(a.clueKey) !== hexlify(b.clueKey)\n )\n throw new Error(\"IPR receiving keys mismatch\");\n }\n}\n","import type { NoteOutputExecutionOptions, PaymentRequest } from \"./types\";\nimport { fields, nonce } from \"./validation\";\n\n/** Apply payer-local decisions to a copy, without changing the encoded request. */\nexport function applyExecutionOptions(\n request: PaymentRequest,\n execution: NoteOutputExecutionOptions\n): PaymentRequest {\n fields(execution, [\"nonce\", \"addressLookup\"], \"execution options\");\n const copy = structuredClone(request);\n const recipient = copy.recipient;\n if (execution.nonce !== undefined) {\n if (recipient.type === \"identity\")\n throw new TypeError(\"identity recipient cannot specify nonce\");\n nonce(execution.nonce);\n if (recipient.nonce !== undefined && recipient.nonce !== execution.nonce)\n throw new Error(\"nonce conflicts with the fixed payment request\");\n recipient.nonce = execution.nonce;\n }\n if (execution.addressLookup !== undefined) {\n if (recipient.type !== \"evm\" || recipient.envelope === false)\n throw new TypeError(\"addressLookup requires an encrypted EVM recipient\");\n if (![\"chain\", \"protocol-rpc\"].includes(execution.addressLookup))\n throw new TypeError(\"Invalid addressLookup\");\n recipient.addressLookup = execution.addressLookup;\n }\n return copy;\n}\n","import {\n MissingCapabilityError,\n ReceivingAddress,\n type ReceivingKeyLookup,\n} from \"@invisi-labs/core\";\nimport { ProtocolRpcClient } from \"@invisi-labs/rpc\";\nimport { EthersAddressResolver } from \"../integrations/ethers\";\nimport type { TransactionInfrastructure } from \"../transactions/operation-types\";\n\nexport type AddressLookup = \"chain\" | \"protocol-rpc\";\nconst recipientInfrastructure = Symbol(\"SDK recipient infrastructure\");\ntype InternalInfrastructure = {\n [recipientInfrastructure]?: (source: AddressLookup) => ReceivingKeyLookup;\n};\n\n/** Capture deployment pins before a Protocol is bound to an operation's token. */\nexport function configureRecipientInfrastructure<T extends TransactionInfrastructure>(\n options: T\n): T {\n const { provider, protocolRpc, chainReader } = options;\n const registry = options.protocol.deployment.registry;\n const deployment = options.protocol.deployment;\n const lookup =\n (source: AddressLookup): ReceivingKeyLookup =>\n async (ownerAddress) => {\n if (!registry) throw new MissingCapabilityError(\"receiving-key registry deployment\");\n if (source === \"chain\") {\n if (!provider)\n throw new MissingCapabilityError(\"ethers provider for registry lookup\");\n return new EthersAddressResolver(\n provider,\n {\n chainId: deployment.chainId,\n registryAddress: registry.address,\n },\n registry.runtimeCodeHash\n ).lookup(ownerAddress);\n }\n if (!(protocolRpc instanceof ProtocolRpcClient))\n throw new MissingCapabilityError(\"Protocol RPC recipient discovery\");\n const rpc = chainReader ? protocolRpc.withReader(chainReader) : protocolRpc;\n const discovered = await rpc.getDeployment(deployment.chainId);\n if (\n discovered.protocol.address !== deployment.protocol.address ||\n discovered.protocol.runtimeCodeHash !== deployment.protocol.runtimeCodeHash ||\n discovered.protocol.fromBlock !== deployment.protocol.fromBlock ||\n discovered.registry?.address !== registry.address ||\n discovered.registry.runtimeCodeHash !== registry.runtimeCodeHash ||\n discovered.registry.fromBlock !== registry.fromBlock\n )\n throw new Error(\"Recipient registry deployment pins mismatch\");\n const registration = await rpc.getReceivingAddress(ownerAddress);\n return registration\n ? ReceivingAddress.parse(registration.receivingAddress).getReceivingKeys()\n : null;\n };\n return { ...options, [recipientInfrastructure]: lookup };\n}\n\n/** Internal lookup plumbing; public APIs never accept resolver functions. */\nexport function recipientLookup(\n options: object,\n source: AddressLookup = \"protocol-rpc\"\n): ReceivingKeyLookup {\n return async (ownerAddress) => {\n const lookup = (options as InternalInfrastructure)[recipientInfrastructure];\n if (!lookup) throw new MissingCapabilityError(\"recipient infrastructure\");\n return lookup(source)(ownerAddress);\n };\n}\n","import type { Hex } from \"@invisi-labs/protocol/contracts\";\n\nimport { FIELD_MODULUS, poseidonHash } from \"@invisi-labs/core\";\nimport type {\n CanonicalBlock,\n ChainReader,\n Membership,\n TransactionContext,\n} from \"@invisi-labs/protocol\";\nexport async function verifyMembership(\n reader: ChainReader,\n context: TransactionContext,\n block: CanonicalBlock,\n input: { treeId: bigint; leafIndex: number; commitment: Hex },\n proof: Membership\n): Promise<void> {\n if (\n proof.block.hash !== block.hash ||\n proof.block.number !== block.number ||\n proof.leaf !== input.commitment ||\n proof.treeId !== input.treeId ||\n proof.leafIndex !== input.leafIndex ||\n proof.path.length !== 16 ||\n !Number.isInteger(input.leafIndex) ||\n input.leafIndex < 0 ||\n input.leafIndex >= 65536 ||\n !(await reader.isKnownRoot(context, input.treeId, proof.root, block))\n )\n throw new Error(\"membership context/root mismatch\");\n let root = BigInt(input.commitment);\n for (let i = 0; i < 16; i++) {\n const sibling = proof.path[i]!;\n if (typeof sibling !== \"bigint\" || sibling < 0n || sibling >= FIELD_MODULUS)\n throw new Error(\"noncanonical membership path\");\n root = BigInt(\n await poseidonHash((input.leafIndex >> i) & 1 ? [sibling, root] : [root, sibling])\n );\n }\n if (root !== BigInt(proof.root))\n throw new Error(\"membership path does not produce canonical root\");\n}\n","import type { Hex } from \"@invisi-labs/protocol/contracts\";\n\nimport {\n computeCreditCommitment,\n computeCreditSharedKeyHash,\n type CreditDeliveryState,\n} from \"@invisi-labs/core\";\nexport async function creditLeaf(state: CreditDeliveryState): Promise<Hex> {\n const n = state.note;\n return computeCreditCommitment(\n n.chainId,\n n.spenderWalletIdentity,\n n.ownerWalletIdentity,\n n.spenderPayout,\n n.ownerPayout,\n n.tokenAddress,\n n.amount,\n n.nonce,\n n.expiry,\n await computeCreditSharedKeyHash(n.creditSharedKey),\n n\n );\n}\n","import {\n normalizeTransactRequest,\n transactUserPublicInputs,\n WitnessBuilder,\n ZERO_ADDRESS,\n} from \"@invisi-labs/protocol\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport { getAddress } from \"ethers\";\nimport { NoteOutput, resolvedOutputSnapshot } from \"../../notes/NoteOutput\";\nimport type {\n CancelCreditPreparation,\n CreateCreditPreparation,\n DrawCreditPreparation,\n OperationPlan,\n PreparationRuntime,\n ShieldPreparation,\n TopUpCreditPreparation,\n TransferPreparation,\n} from \"../operation-types\";\nimport {\n positiveAmount,\n positiveOutputAmount,\n Preparation,\n type PreparationFrame,\n} from \"./prepare-common\";\nimport { CreditPreparation } from \"./prepare-credit\";\n\n/** Shared preparation engine for managed sessions and explicitly supplied inputs. */\nexport class TransactionPreparation<Result> {\n #intent: import(\"../../broadcaster/broadcaster-preparation\").PreparationIntent | undefined;\n constructor(readonly context: PreparationRuntime<Result>) {\n const complete = context.complete;\n this.context = {\n ...context,\n complete: (plan) => {\n const intent = this.#intent ? structuredClone(this.#intent) : undefined;\n if (intent && (intent.kind === \"transfer\" || intent.kind === \"shield\")) {\n const businessOutputs = plan.outputs.filter((output) => !output.change);\n intent.options.outputs = intent.options.outputs.map((payment, index) =>\n resolvedOutputSnapshot(payment, businessOutputs[index]!)\n );\n }\n return complete({ ...plan, ...(intent ? { intent } : {}) });\n },\n };\n }\n private runtime(tokenAddress: Hex): PreparationRuntime<Result> {\n if (\n getAddress(tokenAddress) !==\n getAddress(this.context.options.protocol.context.tokenAddress)\n )\n throw new Error(\"preparation token mismatch\");\n return this.context;\n }\n private get scope() {\n return this.context.scope;\n }\n async prepareTransfer(options: TransferPreparation): Promise<Result> {\n this.#intent = { kind: \"transfer\", options: structuredClone(options) };\n if (Object.hasOwn(options, \"target\") || Object.hasOwn(options, \"execution\")) {\n throw new Error(\n \"prepareTransfer accepts no target or execution; choose execution in prove()\"\n );\n }\n const copied = structuredClone(options);\n const runtime = this.runtime(copied.tokenAddress);\n if (copied.commitments !== undefined && copied.commitments.length === 0)\n throw new Error(\"empty explicit input selection\");\n const preparation = new Preparation({\n ...runtime,\n ...(copied.commitments !== undefined ? { inputSelection: copied.commitments } : {}),\n });\n const frame = await preparation.frame(copied.deadline);\n if (copied.outputs.length > 168) throw new Error(\"transfer supports at most 168 outputs\");\n let withdrawalAddress: Hex = ZERO_ADDRESS;\n let withdrawalAmount = 0n;\n if (copied.withdrawal !== undefined) {\n withdrawalAddress = getAddress(copied.withdrawal.to) as Hex;\n positiveAmount(copied.withdrawal.amount);\n if (BigInt(withdrawalAddress) === 0n)\n throw new Error(\"withdrawal destination must be nonzero\");\n withdrawalAmount = copied.withdrawal.amount;\n }\n if (copied.outputs.length === 0 && withdrawalAmount === 0n)\n throw new Error(\"transfer requires a private output or public withdrawal\");\n const feeRecipient = copied.fee ? (getAddress(copied.fee.recipient) as Hex) : ZERO_ADDRESS;\n const feeAmount = copied.fee?.amount ?? 0n;\n if (copied.fee) {\n positiveAmount(feeAmount);\n if (BigInt(feeRecipient) === 0n) throw new Error(\"fee recipient must be nonzero\");\n }\n const total = copied.outputs.reduce(\n (sum, output, index) => sum + positiveOutputAmount(output, index),\n withdrawalAmount + feeAmount\n );\n const funding = await preparation.funding(copied.funding, frame);\n return this.funds(\n copied.outputs,\n total,\n withdrawalAddress,\n withdrawalAmount,\n { recipient: feeRecipient, amount: feeAmount },\n frame,\n funding,\n preparation\n );\n }\n\n private async funds(\n payments: readonly NoteOutput[],\n total: bigint,\n withdrawalAddress: `0x${string}`,\n withdrawalAmount: bigint,\n fee: { recipient: Hex; amount: bigint },\n frame: PreparationFrame,\n funding: Pick<OperationPlan, \"funding\" | \"fundingMode\">,\n preparation: Preparation<Result>\n ): Promise<Result> {\n if (total >= 1n << 135n) {\n throw new Error(\"transaction sum exceeds uint135\");\n }\n const { context, block, deadline } = frame;\n const selection = await preparation.selectFunds(\n total - (funding.funding.amount ?? 0n),\n frame\n );\n const outputs = await Promise.all(\n payments.map((payment, index) => preparation.output(payment, context, false, index))\n );\n const change = selection.amount + (funding.funding.amount ?? 0n) - total;\n if (change > 0n) {\n outputs.push(await preparation.change(change, context));\n }\n const params = {\n token: context.tokenAddress,\n sources: selection.sources,\n nullifiers: selection.nullifiers,\n outputCommitments: outputs.map((output) => output.commitment),\n withdrawalAddress,\n withdrawalAmount,\n deadline,\n feeRecipient: fee.recipient,\n feeAmount: fee.amount,\n };\n const deliveries = outputs.map((output) => output.delivery);\n const normalized = normalizeTransactRequest(context, params, deliveries, funding.funding);\n const statement = WitnessBuilder.statement(\n `transact_user_slots${normalized.capacity}`,\n transactUserPublicInputs(context, params, deliveries, funding.funding),\n \"evm\"\n );\n await preparation.assertBlock(frame);\n return preparation.runtime.complete({\n version: 1,\n id: crypto.randomUUID(),\n kind: \"transfer\",\n context,\n scope: this.scope,\n preparedAt: block,\n deadline,\n outputs,\n inputs: selection.inputs,\n ...funding,\n params,\n capacity: normalized.capacity,\n statement,\n });\n }\n\n async prepareShield(options: ShieldPreparation): Promise<Result> {\n this.#intent = { kind: \"shield\", options: structuredClone(options) };\n const copied = structuredClone(options);\n const preparation = new Preparation(this.runtime(copied.tokenAddress));\n const frame = await preparation.frame(copied.deadline);\n const funding = await preparation.funding(copied.funding, frame);\n if (copied.outputs.length < 1 || copied.outputs.length > 10) {\n throw new Error(\"shield requires 1..10 outputs\");\n }\n const outputs = await Promise.all(\n copied.outputs.map((output, index) =>\n preparation.output(output, frame.context, false, index)\n )\n );\n if (\n outputs.reduce((sum, output) => sum + output.amount, 0n) !==\n (funding.funding.amount ?? 0n) - (copied.fee?.amount ?? 0n)\n ) {\n throw new Error(\"shield funding must equal output total\");\n }\n await preparation.assertBlock(frame);\n return preparation.runtime.complete({\n version: 1,\n id: crypto.randomUUID(),\n kind: \"shield\",\n context: frame.context,\n scope: this.scope,\n preparedAt: frame.block,\n deadline: frame.deadline,\n outputs,\n inputs: [],\n ...funding,\n shieldParams: {\n token: frame.context.tokenAddress,\n feeRecipient: copied.fee?.recipient ?? ZERO_ADDRESS,\n feeAmount: copied.fee?.amount ?? 0n,\n outputCommitments: outputs.map((output) => output.commitment),\n deadline: frame.deadline,\n },\n shieldOutputs: outputs.map((output) => ({\n identity: output.identity,\n amount: output.amount,\n })),\n });\n }\n\n prepareCreateCredit(options: CreateCreditPreparation): Promise<Result> {\n this.#intent = { kind: \"create-credit\", options: structuredClone(options) };\n return new CreditPreparation(this.runtime(options.tokenAddress)).create(\n structuredClone(options)\n );\n }\n\n prepareDrawCredit(options: DrawCreditPreparation): Promise<Result> {\n this.#intent = undefined;\n return new CreditPreparation(this.runtime(options.tokenAddress)).draw(\n structuredClone(options)\n );\n }\n\n prepareTopUpCredit(options: TopUpCreditPreparation): Promise<Result> {\n this.#intent = { kind: \"top-up-credit\", options: structuredClone(options) };\n return new CreditPreparation(this.runtime(options.tokenAddress)).topUp(\n structuredClone(options)\n );\n }\n\n prepareCancelCredit(options: CancelCreditPreparation): Promise<Result> {\n this.#intent = { kind: \"cancel-credit\", options: structuredClone(options) };\n return new CreditPreparation(this.runtime(options.tokenAddress)).cancel(\n structuredClone(options)\n );\n }\n}\n","import type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport { getAddress } from \"ethers\";\nimport { InvisiError } from \"../../errors\";\nimport { NoteOutput, materializeNoteOutput } from \"../../notes/NoteOutput\";\nimport { recipientLookup } from \"../../notes/recipient-infrastructure\";\n\nimport {\n MissingCapabilityError,\n computeNoteCommitment,\n computeNoteIdentity,\n} from \"@invisi-labs/core\";\nimport {\n normalizeFunding,\n type CanonicalBlock,\n type FundingInput,\n type Membership,\n type NoteMembership,\n type TransactionContext,\n} from \"@invisi-labs/protocol\";\nimport { verifyMembership } from \"../../discovery/membership\";\nimport type {\n FundingSource,\n OperationPlan,\n PreparationRuntime,\n PreparedOutput,\n} from \"../operation-types\";\nimport type { NoteRecord } from \"../records\";\nimport { selectNotes, type SelectableNote } from \"./selection\";\n\nexport interface PreparationFrame {\n context: TransactionContext;\n block: CanonicalBlock;\n deadline: bigint;\n}\n\nexport function positiveAmount(value: bigint, bits = 128): bigint {\n if (typeof value !== \"bigint\" || value <= 0n || value >= 1n << BigInt(bits)) {\n throw new Error(`amount must be a positive uint${bits}`);\n }\n return value;\n}\n\n/** Reject non-byte JavaScript inputs before copying; empty bytes explicitly clear metadata. */\nexport function copyApplicationPayload(value?: Uint8Array): Uint8Array {\n if (value === undefined) return new Uint8Array();\n if (!(value instanceof Uint8Array)) throw new TypeError(\"payload must be Uint8Array\");\n return Uint8Array.from(value);\n}\n\n/** Preserve the offending payment position even when summing transfer amounts first. */\nexport function positiveOutputAmount(payment: NoteOutput, outputIndex?: number): bigint {\n try {\n return positiveAmount(payment.amount);\n } catch (cause) {\n throw new InvisiError(\n \"PREPARATION_FAILED\",\n cause instanceof Error ? cause.message : \"Invalid output amount\",\n {\n address: payment.to,\n field: \"amount\",\n ...(outputIndex === undefined ? {} : { outputIndex }),\n cause,\n }\n );\n }\n}\n\n/** Shared local preparation checks; private witnesses never enter this object's public records. */\nexport class Preparation<Result> {\n readonly #roots = new Map<bigint, Hex>();\n constructor(readonly runtime: PreparationRuntime<Result>) {}\n\n async frame(requested?: bigint): Promise<PreparationFrame> {\n const { reader, options } = this.runtime;\n await options.protocol.validateDeployment(reader);\n const block = await reader.getBlock(await reader.getLatestBlockNumber());\n const deadline = requested ?? block.timestamp + (options.transactionTTL ?? 300n);\n if (typeof deadline !== \"bigint\" || deadline < block.timestamp || deadline >= 1n << 64n) {\n throw new Error(\"invalid transaction deadline\");\n }\n const state = await this.runtime.readInventory();\n if (state.invalidated) {\n throw new Error(\"wallet requires canonical resync\");\n }\n for (const point of [state.observedThrough]) {\n if (point && (await reader.getBlock(point.number)).hash !== point.hash) {\n throw new Error(\"canonical wallet checkpoint changed; resync required\");\n }\n }\n return {\n context: {\n ...options.protocol.context,\n now: block.timestamp,\n timestamp: block.timestamp,\n },\n block,\n deadline,\n };\n }\n\n async assertBlock(frame: PreparationFrame): Promise<void> {\n if ((await this.runtime.reader.getBlock(frame.block.number)).hash !== frame.block.hash) {\n throw new Error(\"canonical block changed while preparing\");\n }\n }\n\n async funding(\n source: FundingSource | undefined,\n frame: PreparationFrame\n ): Promise<{ funding: FundingInput; fundingMode: OperationPlan[\"fundingMode\"] }> {\n if (!source) {\n return { funding: {}, fundingMode: \"none\" };\n }\n positiveAmount(source.amount);\n const payer = getAddress(source.payer) as Hex;\n const mode = source.authorization ?? \"signature\";\n if (BigInt(payer) === 0n) {\n throw new Error(\"funding payer must be nonzero\");\n }\n if (mode !== \"signature\" && mode !== \"caller\") {\n throw new Error(\"invalid funding authorization mode\");\n }\n if (mode === \"caller\" && (source.sigNonce || source.deadline)) {\n throw new Error(\"caller funding uses zero nonce/deadline\");\n }\n const funding = normalizeFunding({\n payer,\n amount: source.amount,\n sigNonce:\n mode === \"caller\"\n ? 0n\n : (source.sigNonce ??\n (await this.runtime.reader.getFundingNonce(\n frame.context,\n payer,\n frame.block\n ))),\n deadline: mode === \"caller\" ? 0n : (source.deadline ?? frame.deadline),\n ...(source.permit ? { permit: structuredClone(source.permit) } : {}),\n });\n if (mode === \"signature\" && funding.deadline < frame.block.timestamp) {\n throw new Error(\"funding authorization deadline has expired\");\n }\n return { funding, fundingMode: mode };\n }\n\n async change(amount: bigint, context: TransactionContext): Promise<PreparedOutput> {\n const address =\n this.runtime.changeAddress ??\n this.runtime.options.wallet.getReceivingAddress().toString();\n try {\n const output = await NoteOutput.create({\n chainId: context.chainId,\n protocolAddress: context.protocolAddress,\n tokenAddress: context.tokenAddress,\n amount,\n recipient: address.startsWith(\"0i\")\n ? { type: \"invisi\", address }\n : { type: \"evm\", address },\n });\n return await this.output(output, context, true);\n } catch (cause) {\n if (cause instanceof InvisiError)\n throw new InvisiError(cause.code, cause.message, {\n address,\n field: \"changeAddress\",\n ...(cause.capability ? { capability: cause.capability } : {}),\n cause: cause.cause ?? cause,\n });\n throw new InvisiError(\n \"PREPARATION_FAILED\",\n cause instanceof Error ? cause.message : \"Change output preparation failed\",\n { address, field: \"changeAddress\", cause }\n );\n }\n }\n\n async output(\n payment: NoteOutput,\n context: TransactionContext,\n change = false,\n outputIndex?: number\n ): Promise<PreparedOutput> {\n try {\n positiveOutputAmount(payment, outputIndex);\n const output = await materializeNoteOutput(payment, context, (source) =>\n recipientLookup(this.runtime.options, source)\n );\n return { ...output, change };\n } catch (cause) {\n if (cause instanceof InvisiError) {\n throw new InvisiError(cause.code, cause.message, {\n address: cause.address ?? payment.to,\n field: change ? \"changeAddress\" : (cause.field ?? \"to\"),\n ...(outputIndex === undefined ? {} : { outputIndex }),\n ...(cause.capability ? { capability: cause.capability } : {}),\n cause: cause.cause ?? cause,\n });\n }\n throw new InvisiError(\n \"PREPARATION_FAILED\",\n cause instanceof Error ? cause.message : \"Output preparation failed\",\n {\n address: payment.to,\n field: change ? \"changeAddress\" : \"to\",\n ...(outputIndex === undefined ? {} : { outputIndex }),\n cause,\n }\n );\n }\n }\n\n async membership(\n input: { treeId: bigint; leafIndex: number; commitment: Hex },\n frame: PreparationFrame\n ): Promise<Membership> {\n const { options, reader } = this.runtime;\n if (!options.protocolRpc)\n throw new MissingCapabilityError(\"Protocol RPC membership provider\");\n const root = this.#roots.get(input.treeId);\n const proof = await options.protocolRpc.getMembership(\n frame.context,\n {\n ...input,\n ...(root ? { root } : {}),\n },\n frame.block\n );\n if (root && proof.root !== root)\n throw new Error(\"membership provider changed the pinned source root\");\n await verifyMembership(reader, frame.context, frame.block, input, proof);\n this.#roots.set(input.treeId, proof.root);\n return { ...proof, path: [...proof.path] };\n }\n\n async selectFunds(target: bigint, frame: PreparationFrame, maxInputs = 168) {\n const { scope, options, reader } = this.runtime;\n const state = await this.runtime.readInventory();\n if (state.invalidated) {\n throw new Error(\"wallet requires canonical resync\");\n }\n const need = target > 0n ? target : 0n;\n const nullifier = options.wallet.exportNullifier();\n const reserved = new Set(Object.keys(state.reservations));\n const eligible = Object.values(state.notes).filter(\n (note) =>\n note.note.tokenAddress === BigInt(frame.context.tokenAddress) &&\n note.spent === \"unspent\" &&\n !reserved.has(note.commitment)\n );\n const byId = new Map(eligible.map((note) => [note.commitment, note]));\n const choices = this.runtime.inputSelection\n ? [...this.runtime.inputSelection]\n : this.runtime.explicitInputs\n ? eligible.map((note) => note.commitment)\n : need > 0n && options.coinSelector\n ? await options.coinSelector.select(storedCandidates(eligible), need)\n : selectNotes(eligible, need, reserved).map((note) => note.commitment);\n if (\n !Array.isArray(choices) ||\n new Set(choices).size !== choices.length ||\n choices.some((id) => !byId.has(id))\n ) {\n throw new Error(\"invalid or duplicate coin selection\");\n }\n const selected = choices.map((id) => structuredClone(byId.get(id)!));\n const amount = selected.reduce((sum, input) => sum + input.note.amount, 0n);\n if (amount < need) {\n throw new Error(\"coin selection has insufficient verified funds\");\n }\n if (selected.length > maxInputs || amount >= 1n << 135n) {\n throw new Error(\"coin selection exceeds transaction capacity\");\n }\n const inputs: Array<NoteMembership & { commitment: Hex }> = [];\n const sources = new Map<bigint, Hex>();\n const nullifiers: Hex[] = [];\n for (const input of selected) {\n const note = input.note;\n const c = frame.context;\n if (\n note.ownerAddress !== scope.ownerAddress ||\n note.chainId !== c.chainId ||\n note.protocolAddress !== BigInt(c.protocolAddress) ||\n note.tokenAddress !== BigInt(c.tokenAddress) ||\n (await computeNoteCommitment(\n c.chainId,\n await computeNoteIdentity(BigInt(note.ownerAddress), note.nonce),\n note.tokenAddress,\n note.amount\n )) !== input.commitment\n ) {\n throw new Error(\"selected input preimage/context mismatch\");\n }\n const proof = await this.membership(input, frame);\n const path = [...proof.path];\n const root = proof.root;\n if (sources.has(input.treeId) && sources.get(input.treeId) !== root) {\n throw new Error(\"source roots do not share a canonical snapshot\");\n }\n sources.set(input.treeId, root);\n inputs.push({\n note,\n commitment: input.commitment,\n treeId: input.treeId,\n leafIndex: input.leafIndex,\n path,\n });\n nullifiers.push(\n await nullifier!.compute(c.chainId, input.commitment, input.note.nonce)\n );\n }\n await this.assertUnspent(nullifiers, frame);\n return {\n inputs,\n sources: [...sources]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([treeId, merkleRoot]) => ({ treeId, merkleRoot })),\n nullifiers,\n amount,\n };\n }\n\n async assertUnspent(nullifiers: readonly Hex[], frame: PreparationFrame): Promise<void> {\n if (nullifiers.length) {\n const spent = await this.runtime.reader.isSpent(frame.context, nullifiers, frame.block);\n if (spent.length !== nullifiers.length || spent.some((value) => value !== false)) {\n throw new Error(\"selected input spent or invalid spent-state response\");\n }\n }\n }\n}\n\n// Managed custom selectors retain access to receipt metadata. Explicit inputs\n// use their own exact selection and never pass fabricated metadata to a selector.\nfunction storedCandidates(inputs: readonly SelectableNote[]): NoteRecord[] {\n const records = inputs.filter(\n (input): input is NoteRecord =>\n \"blockNumber\" in input &&\n typeof input.blockNumber === \"bigint\" &&\n \"blockHash\" in input &&\n typeof input.blockHash === \"string\"\n );\n if (records.length !== inputs.length)\n throw new Error(\"custom coin selection requires stored receipt metadata\");\n return structuredClone(records);\n}\n","import type { NoteRecord } from \"../records\";\n/** Minimal input count by descending amount, with deterministic tree/position/commitment ties. */\nexport type SelectableNote = Pick<\n NoteRecord,\n \"note\" | \"commitment\" | \"treeId\" | \"leafIndex\" | \"spent\"\n>;\nexport function selectNotes<T extends SelectableNote>(\n notes: readonly T[],\n target: bigint,\n reserved: ReadonlySet<string>\n): T[] {\n if (typeof target !== \"bigint\" || target < 0n)\n throw new Error(\"selection target must be a nonnegative amount\");\n if (target === 0n) return [];\n const eligible = notes.filter(\n (note) => note.spent === \"unspent\" && !reserved.has(note.commitment)\n );\n for (const record of eligible)\n if (\n typeof record.note.amount !== \"bigint\" ||\n record.note.amount <= 0n ||\n record.note.amount >= 1n << 128n\n )\n throw new Error(\"invalid verified note amount\");\n eligible.sort((a, b) =>\n a.note.amount > b.note.amount\n ? -1\n : a.note.amount < b.note.amount\n ? 1\n : a.treeId < b.treeId\n ? -1\n : a.treeId > b.treeId\n ? 1\n : a.leafIndex - b.leafIndex || a.commitment.localeCompare(b.commitment)\n );\n const selected: T[] = [];\n let total = 0n;\n for (const record of eligible) {\n selected.push(structuredClone(record));\n total += record.note.amount;\n if (total >= target) return selected;\n }\n throw new Error(\"insufficient verified available funds\");\n}\n","import type {\n CreateCreditParams,\n Delivery,\n Hex,\n InputSource,\n} from \"@invisi-labs/protocol/contracts\";\nimport { getAddress, hexlify, toBeHex } from \"ethers\";\nimport { recipientLookup } from \"../../notes/recipient-infrastructure\";\nimport { resolveRecipient } from \"../../notes/resolve-recipient\";\n\nimport {\n FIELD_MODULUS,\n applyCreditDrawUsage,\n computeCreditNullifier,\n computeCreditRecoveryPad,\n createClue,\n deriveRemainderNonce,\n encryptCreditNote,\n generateCreditSharedKey,\n generateNonce,\n normalizeCreditDeliveryState,\n normalizeCreditPolicy,\n type CreditDeliveryState,\n} from \"@invisi-labs/core\";\nimport {\n WitnessBuilder,\n cancelCreditPublicInputs,\n createCreditPublicInputs,\n creditDrawPublicInputs,\n selectCreditDrawCircuit,\n topUpCreditPublicInputs,\n word,\n} from \"@invisi-labs/protocol\";\nimport type { CircuitName } from \"@invisi-labs/prover\";\nimport { creditLeaf } from \"./credit-values\";\n\nimport type {\n CancelCreditPreparation,\n CreateCreditPreparation,\n DrawCreditPreparation,\n OperationPlan,\n PreparationRuntime,\n PreparedCreditInput,\n PreparedCreditOutput,\n TopUpCreditPreparation,\n} from \"../operation-types\";\nimport {\n Preparation,\n copyApplicationPayload,\n positiveAmount,\n type PreparationFrame,\n} from \"./prepare-common\";\n\nconst EMPTY: Delivery = { ciphertext: \"0x\", clue: \"0x\" };\n\n/** Current Credit roles, payout addresses and receiving snapshots are frozen before authorization. */\nexport class CreditPreparation<Result> {\n readonly #prepare: Preparation<Result>;\n\n constructor(readonly runtime: PreparationRuntime<Result>) {\n this.#prepare = new Preparation(runtime);\n }\n\n private expiry(value: bigint, frame: PreparationFrame): bigint {\n if (typeof value !== \"bigint\" || value <= frame.block.timestamp || value >= 1n << 64n) {\n throw new Error(\"Credit expiry must be a future uint64 timestamp\");\n }\n return value;\n }\n\n private async seal(\n input: CreditDeliveryState,\n frame: PreparationFrame\n ): Promise<PreparedCreditOutput> {\n const state = normalizeCreditDeliveryState(input);\n const commitment = await creditLeaf(state);\n const context = {\n chainId: frame.context.chainId,\n protocolAddress: BigInt(frame.context.protocolAddress),\n outputCommitment: commitment,\n };\n const deliveries = (await Promise.all(\n ([\"owner\", \"spender\"] as const).map(async (role) => {\n const keys =\n role === \"owner\" ? state.ownerReceivingKeys : state.spenderReceivingKeys;\n return {\n ciphertext: hexlify(\n await encryptCreditNote(keys.viewingPublicKey, state, { ...context, role })\n ) as Hex,\n clue: hexlify(createClue(keys.clueKey)) as Hex,\n };\n })\n )) as [Delivery, Delivery];\n return { state, commitment, deliveries };\n }\n\n private async input(\n commitment: Hex,\n role: \"owner\" | \"spender\",\n frame: PreparationFrame\n ): Promise<{ input: PreparedCreditInput; nullifier: Hex; source: InputSource }> {\n const stored = (await this.runtime.readInventory()).credits[commitment + \":\" + role];\n if (!stored || stored.spent !== \"unspent\" || stored.role !== role) {\n throw new Error(`confirmed unspent ${role} Credit is unavailable`);\n }\n const state = normalizeCreditDeliveryState(stored.state);\n const n = state.note;\n if (\n (role === \"owner\" ? n.ownerWalletIdentity : n.spenderWalletIdentity) !==\n this.runtime.scope.ownerAddress ||\n n.chainId !== frame.context.chainId ||\n n.protocolAddress !== BigInt(frame.context.protocolAddress) ||\n n.tokenAddress !== BigInt(frame.context.tokenAddress) ||\n (await creditLeaf(state)) !== commitment\n ) {\n throw new Error(\"Credit role, commitment or deployment mismatch\");\n }\n const proof = await this.#prepare.membership(stored, frame);\n const path = [...proof.path];\n const nullifier = await computeCreditNullifier(n.chainId, n.creditSharedKey, commitment);\n await this.#prepare.assertUnspent([nullifier], frame);\n return {\n input: {\n state,\n commitment,\n role,\n treeId: stored.treeId,\n leafIndex: stored.leafIndex,\n path,\n },\n nullifier,\n source: {\n treeId: stored.treeId,\n merkleRoot: proof.root,\n },\n };\n }\n\n private base(frame: PreparationFrame, kind: OperationPlan[\"kind\"]): OperationPlan {\n return {\n version: 1,\n id: crypto.randomUUID(),\n kind,\n context: frame.context,\n scope: this.runtime.scope,\n preparedAt: frame.block,\n deadline: frame.deadline,\n outputs: [],\n inputs: [],\n funding: {},\n fundingMode: \"none\",\n };\n }\n\n async create(options: CreateCreditPreparation): Promise<Result> {\n positiveAmount(options.amount, 126);\n const frame = await this.#prepare.frame(options.deadline);\n const expiry = this.expiry(options.expiry, frame);\n const spender = await resolveRecipient(\n options.spender,\n recipientLookup(this.runtime.options),\n { field: \"spender\" }\n );\n const owner = await resolveRecipient(\n this.runtime.options.wallet.getReceivingAddress().toString(),\n recipientLookup(this.runtime.options),\n { field: \"wallet\" }\n );\n const ownerPayout = getAddress(owner.ownerAddress) as Hex;\n const spenderPayout = getAddress(spender.ownerAddress) as Hex;\n if (BigInt(ownerPayout) === 0n || BigInt(spenderPayout) === 0n) {\n throw new Error(\"Credit payouts must be nonzero\");\n }\n const output = await this.seal(\n {\n note: {\n chainId: frame.context.chainId,\n protocolAddress: BigInt(frame.context.protocolAddress),\n tokenAddress: BigInt(frame.context.tokenAddress),\n ownerWalletIdentity: this.runtime.scope.ownerAddress,\n spenderWalletIdentity: spender.ownerAddress,\n ownerPayout: BigInt(ownerPayout),\n spenderPayout: BigInt(spenderPayout),\n ...normalizeCreditPolicy({\n singleLimit: options.singleLimit ?? 0n,\n dailyLimit: options.dailyLimit ?? 0n,\n monthlyLimit: options.monthlyLimit ?? 0n,\n }),\n amount: options.amount,\n payload: copyApplicationPayload(options.payload),\n expiry,\n nonce: generateNonce(),\n creditSharedKey: generateCreditSharedKey(),\n },\n ownerReceivingKeys: owner.getReceivingKeys(),\n spenderReceivingKeys: spender.getReceivingKeys(),\n },\n frame\n );\n return this.creation(\n this.base(frame, \"create-credit\"),\n output,\n options.amount,\n options.funding,\n options.fee,\n frame\n );\n }\n\n private async creation(\n plan: OperationPlan,\n output: PreparedCreditOutput,\n delta: bigint,\n fundingSource: CreateCreditPreparation[\"funding\"],\n fee: CreateCreditPreparation[\"fee\"],\n frame: PreparationFrame,\n previous?: Awaited<ReturnType<CreditPreparation<Result>[\"input\"]>>\n ): Promise<Result> {\n const funding = await this.#prepare.funding(fundingSource, frame);\n const selected = await this.#prepare.selectFunds(\n delta + (fee?.amount ?? 0n) - (funding.funding.amount ?? 0n),\n frame,\n 10\n );\n const change =\n selected.amount + (funding.funding.amount ?? 0n) - delta - (fee?.amount ?? 0n);\n plan.inputs = selected.inputs;\n Object.assign(plan, funding);\n if (change > 0n) {\n plan.outputs.push(await this.#prepare.change(change, frame.context));\n }\n const creation: CreateCreditParams = {\n token: frame.context.tokenAddress,\n feeRecipient: fee?.recipient ?? \"0x0000000000000000000000000000000000000000\",\n feeAmount: fee?.amount ?? 0n,\n sources: selected.sources,\n nullifiers: selected.nullifiers,\n creditCommitment: output.commitment,\n changeCommitment: plan.outputs[0]?.commitment ?? word(0n),\n owner: getAddress(toBeHex(output.state.note.ownerPayout, 20) as Hex) as Hex,\n expiry: output.state.note.expiry,\n deadline: frame.deadline,\n };\n const deliveries = [...output.deliveries, plan.outputs[0]?.delivery ?? { ...EMPTY }];\n plan.capacity = 10;\n plan.credit = {\n inputs: previous ? [previous.input] : [],\n outputs: [output],\n deliveries,\n creation,\n };\n if (previous) {\n plan.credit.topUp = {\n creation,\n creditSource: previous.source,\n creditNullifier: previous.nullifier,\n previousExpiry: previous.input.state.note.expiry,\n };\n plan.statement = WitnessBuilder.statement(\n \"credit_top_up\",\n topUpCreditPublicInputs(frame.context, plan.credit.topUp, deliveries, plan.funding)\n );\n } else {\n plan.statement = WitnessBuilder.statement(\n \"create_credit\",\n createCreditPublicInputs(frame.context, creation, deliveries, plan.funding)\n );\n }\n await this.#prepare.assertBlock(frame);\n return this.runtime.complete(plan);\n }\n\n async topUp(options: TopUpCreditPreparation): Promise<Result> {\n positiveAmount(options.additionalAmount, 126);\n const frame = await this.#prepare.frame(options.deadline);\n const previous = await this.input(options.credit, \"owner\", frame);\n const old = previous.input.state;\n if (old.note.expiry <= frame.block.timestamp) {\n throw new Error(\"previous Credit has expired\");\n }\n const expiry = this.expiry(options.expiry ?? old.note.expiry, frame);\n if (expiry < old.note.expiry) {\n throw new Error(\"Credit expiry must not decrease\");\n }\n const amount = positiveAmount(old.note.amount + options.additionalAmount, 126);\n const output = await this.seal(\n {\n ...old,\n note: {\n ...old.note,\n singleLimit: options.singleLimit ?? old.note.singleLimit ?? 0n,\n dailyLimit: options.dailyLimit ?? old.note.dailyLimit ?? 0n,\n monthlyLimit: options.monthlyLimit ?? old.note.monthlyLimit ?? 0n,\n amount,\n expiry,\n nonce: generateNonce(),\n payload: copyApplicationPayload(\n options.payload === undefined ? old.note.payload : options.payload\n ),\n },\n },\n frame\n );\n return this.creation(\n this.base(frame, \"top-up-credit\"),\n output,\n options.additionalAmount,\n options.funding,\n options.fee,\n frame,\n previous\n );\n }\n\n async draw(options: DrawCreditPreparation): Promise<Result> {\n const frame = await this.#prepare.frame(options.deadline);\n const profile = selectCreditDrawCircuit(options.credits.length);\n if (new Set(options.credits.map((value) => value.credit)).size !== options.credits.length) {\n throw new Error(\"duplicate Credit input\");\n }\n const members = await Promise.all(\n options.credits.map((value) => this.input(value.credit, \"spender\", frame))\n );\n const payout = members[0]!.input.state.note.spenderPayout;\n const sources = new Map<bigint, Hex>();\n const outputs: PreparedCreditOutput[] = [];\n const deliveries: Delivery[] = [];\n const recoveryAmounts: Hex[] = [];\n const remainders: Hex[] = [];\n const amounts: bigint[] = [];\n for (const [i, member] of members.entries()) {\n const state = member.input.state;\n const n = state.note;\n const amount = positiveAmount(options.credits[i]!.amount, 126);\n if (n.spenderPayout !== payout) {\n throw new Error(\n \"Credit draw requires separate groups for different public payouts; one call must be atomic\"\n );\n }\n this.expiry(n.expiry, frame);\n if (amount > n.amount) {\n throw new Error(\"Credit draw exceeds remaining amount\");\n }\n if (\n sources.has(member.source.treeId) &&\n sources.get(member.source.treeId) !== member.source.merkleRoot\n ) {\n throw new Error(\"Credit source root mismatch\");\n }\n sources.set(member.source.treeId, member.source.merkleRoot);\n amounts.push(amount);\n const usage = applyCreditDrawUsage(n, amount, frame.block.timestamp);\n const remaining = n.amount - amount;\n if (remaining === 0n) {\n remainders.push(word(0n));\n recoveryAmounts.push(word(0n));\n deliveries.push({ ...EMPTY }, { ...EMPTY });\n continue;\n }\n const args = [\n n.chainId,\n n.protocolAddress,\n n.tokenAddress,\n BigInt(member.nullifier),\n n.creditSharedKey,\n ] as const;\n const output = await this.seal(\n {\n ...state,\n note: {\n ...n,\n ...usage,\n amount: remaining,\n payload: copyApplicationPayload(\n options.credits[i]!.payload === undefined\n ? n.payload\n : options.credits[i]!.payload\n ),\n nonce: await deriveRemainderNonce(...args),\n },\n },\n frame\n );\n outputs.push(output);\n remainders.push(output.commitment);\n recoveryAmounts.push(\n word((remaining + (await computeCreditRecoveryPad(...args))) % FIELD_MODULUS)\n );\n deliveries.push(...output.deliveries);\n }\n const plan = this.base(frame, \"draw-credit\");\n const params = {\n token: frame.context.tokenAddress,\n sources: [...sources]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([treeId, merkleRoot]) => ({ treeId, merkleRoot })),\n nullifiers: members.map((member) => member.nullifier),\n remainderCommitments: remainders,\n expiries: members.map((member) => member.input.state.note.expiry),\n recoveryAmounts,\n spender: getAddress(toBeHex(payout, 20) as Hex) as Hex,\n totalAmount: amounts.reduce((sum, amount) => sum + amount, 0n),\n deadline: frame.deadline,\n };\n plan.capacity = profile.maxSize;\n plan.credit = {\n inputs: members.map((member) => member.input),\n outputs,\n deliveries,\n draw: params,\n amounts,\n };\n plan.statement = WitnessBuilder.statement(\n profile.name as CircuitName,\n creditDrawPublicInputs(frame.context, params, deliveries)\n );\n await this.#prepare.assertBlock(frame);\n return this.runtime.complete(plan);\n }\n\n async cancel(options: CancelCreditPreparation): Promise<Result> {\n const frame = await this.#prepare.frame(options.deadline);\n const previous = await this.input(options.credit, \"owner\", frame);\n const n = previous.input.state.note;\n const plan = this.base(frame, \"cancel-credit\");\n if ((options.fee?.amount ?? 0n) >= n.amount)\n throw new Error(\"fee must be less than the cancellation refund\");\n const params = {\n feeRecipient: options.fee?.recipient ?? \"0x0000000000000000000000000000000000000000\",\n feeAmount: options.fee?.amount ?? 0n,\n token: frame.context.tokenAddress,\n source: previous.source,\n nullifier: previous.nullifier,\n owner: getAddress(toBeHex(n.ownerPayout, 20) as Hex) as Hex,\n amount: n.amount,\n deadline: frame.deadline,\n };\n plan.capacity = 1;\n plan.credit = { inputs: [previous.input], outputs: [], deliveries: [], cancel: params };\n plan.statement = WitnessBuilder.statement(\n \"credit_cancel\",\n cancelCreditPublicInputs(frame.context, params)\n );\n await this.#prepare.assertBlock(frame);\n return this.runtime.complete(plan);\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,8BAA8B;AA0ChC,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAAuB,SAAiB,UAA8B,CAAC,GAAG;AAClF,UAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;AACvC,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,YAAY,QAAQ;AACzB,SAAK,UAAU,QAAQ;AACvB,SAAK,cAAc,QAAQ;AAC3B,SAAK,QAAQ,QAAQ;AACrB,SAAK,aAAa,QAAQ;AAAA,EAC9B;AACJ;AAGA,eAAsB,kBAClB,WACA,SACU;AACV,MAAI;AACA,WAA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WAAO,IAAI,kBAAkB,KAAK,QAAQ,QAAQ,YAAY,CAAC,EAAE;AAAA,MAC7D,gBAAgB,OAAO;AAAA,IAC3B;AAAA,EACJ;AAAA,EAEA,mBAAmB,SAAkD;AACjE,SAAK,UAAU,EAAE,MAAM,iBAAiB,SAAS,gBAAgB,OAAO,EAAE;AAC1E,WAAO,IAAI,kBAAkB,KAAK,QAAQ,QAAQ,YAAY,CAAC,EAAE;AAAA,MAC7D,gBAAgB,OAAO;AAAA,IAC3B;AAAA,EACJ;AAAA,EAEA,oBAAoB,SAAmD;AACnE,SAAK,UAAU,EAAE,MAAM,iBAAiB,SAAS,gBAAgB,OAAO,EAAE;AAC1E,WAAO,IAAI,kBAAkB,KAAK,QAAQ,QAAQ,YAAY,CAAC,EAAE;AAAA,MAC7D,gBAAgB,OAAO;AAAA,IAC3B;AAAA,EACJ;AACJ;","names":["value","ReceivingAddress","decodeBase64","encodeBase64","getBytes","hexlify","uint","concat","FIELD_MODULUS","getAddress","uint","FIELD_MODULUS","getAddress","encodeBase64","uint","getBytes","ReceivingAddress","concat","decodeBase64","hexlify","nonce","FIELD_MODULUS","ReceivingAddress","getAddress","hexlify","MissingCapabilityError","ReceivingAddress","ReceivingAddress","MissingCapabilityError","ReceivingAddress","hexlify","ReceivingAddress","hexlify","FIELD_MODULUS","getAddress","ReceivingAddress","nonce","hexlify","MissingCapabilityError","ReceivingAddress","MissingCapabilityError","ReceivingAddress","FIELD_MODULUS","transactUserPublicInputs","WitnessBuilder","getAddress","getAddress","MissingCapabilityError","computeNoteCommitment","computeNoteIdentity","normalizeFunding","getAddress","normalizeFunding","MissingCapabilityError","computeNoteCommitment","computeNoteIdentity","getAddress","hexlify","FIELD_MODULUS","createClue","generateNonce","WitnessBuilder","cancelCreditPublicInputs","createCreditPublicInputs","creditDrawPublicInputs","topUpCreditPublicInputs","hexlify","createClue","getAddress","generateNonce","WitnessBuilder","topUpCreditPublicInputs","createCreditPublicInputs","FIELD_MODULUS","creditDrawPublicInputs","cancelCreditPublicInputs","getAddress","statement","WitnessBuilder","transactUserPublicInputs"]}