@invisi-labs/sdk 1.1.7 → 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.
- package/README.md +5 -0
- package/dist/broadcaster-3KTB4JO2.cjs +21 -0
- package/dist/broadcaster-3KTB4JO2.cjs.map +1 -0
- package/dist/broadcaster-7ZKKSTZQ.js +21 -0
- package/dist/broadcaster-preparation-PJ263WBL.cjs +15 -0
- package/dist/broadcaster-preparation-PJ263WBL.cjs.map +1 -0
- package/dist/broadcaster-preparation-ZQAPZAUG.js +15 -0
- package/dist/broadcaster-preparation-ZQAPZAUG.js.map +1 -0
- package/dist/{chunk-LOU7AP2B.cjs → chunk-2URICDPW.cjs} +72 -33
- package/dist/chunk-2URICDPW.cjs.map +1 -0
- package/dist/chunk-3D24ABYR.js +86 -0
- package/dist/chunk-3D24ABYR.js.map +1 -0
- package/dist/chunk-3KTQQZOW.cjs +71 -0
- package/dist/chunk-3KTQQZOW.cjs.map +1 -0
- package/dist/chunk-4SDP53YQ.cjs +765 -0
- package/dist/chunk-4SDP53YQ.cjs.map +1 -0
- package/dist/{chunk-XHKQ2BO2.js → chunk-4VI6LYGH.js} +25 -2
- package/dist/chunk-4VI6LYGH.js.map +1 -0
- package/dist/chunk-BBSRP4MH.cjs +287 -0
- package/dist/chunk-BBSRP4MH.cjs.map +1 -0
- package/dist/chunk-DGMVGFKM.js +41 -0
- package/dist/chunk-DGMVGFKM.js.map +1 -0
- package/dist/chunk-DHQEB6JR.cjs +1616 -0
- package/dist/chunk-DHQEB6JR.cjs.map +1 -0
- package/dist/chunk-FKF67XE6.js +1616 -0
- package/dist/chunk-FKF67XE6.js.map +1 -0
- package/dist/chunk-GUD3LAUO.js +765 -0
- package/dist/chunk-GUD3LAUO.js.map +1 -0
- package/dist/chunk-HCB7RQ3S.cjs +79 -0
- package/dist/chunk-HCB7RQ3S.cjs.map +1 -0
- package/dist/{chunk-GTPUYPQL.js → chunk-HKGJXQVN.js} +69 -30
- package/dist/chunk-HKGJXQVN.js.map +1 -0
- package/dist/chunk-HLH5JZD4.js +287 -0
- package/dist/chunk-HLH5JZD4.js.map +1 -0
- package/dist/chunk-J6TZZVAM.cjs +230 -0
- package/dist/chunk-J6TZZVAM.cjs.map +1 -0
- package/dist/{chunk-7F7ZZW3L.cjs → chunk-LOR6PYH5.cjs} +25 -2
- package/dist/chunk-LOR6PYH5.cjs.map +1 -0
- package/dist/chunk-MA2QZEF5.cjs +399 -0
- package/dist/chunk-MA2QZEF5.cjs.map +1 -0
- package/dist/chunk-MI4IP4ZD.cjs +86 -0
- package/dist/chunk-MI4IP4ZD.cjs.map +1 -0
- package/dist/chunk-OCZLJKIA.cjs +41 -0
- package/dist/chunk-OCZLJKIA.cjs.map +1 -0
- package/dist/chunk-R5YAOJKB.js +71 -0
- package/dist/chunk-R5YAOJKB.js.map +1 -0
- package/dist/chunk-RY4M2CIQ.js +399 -0
- package/dist/chunk-RY4M2CIQ.js.map +1 -0
- package/dist/chunk-THMD5QO2.js +79 -0
- package/dist/chunk-THMD5QO2.js.map +1 -0
- package/dist/chunk-ZD2652WH.js +230 -0
- package/dist/chunk-ZD2652WH.js.map +1 -0
- package/dist/credit.cjs +1 -0
- package/dist/credit.cjs.map +1 -0
- package/dist/credit.d.cts +12 -0
- package/dist/credit.d.ts +12 -0
- package/dist/credit.js +1 -0
- package/dist/credit.js.map +1 -0
- package/dist/ethers.cjs +2 -2
- package/dist/ethers.cjs.map +1 -1
- package/dist/ethers.d.cts +15 -4
- package/dist/ethers.d.ts +15 -4
- package/dist/ethers.js +1 -1
- package/dist/index-CLhGwLxZ.d.cts +42 -0
- package/dist/index-Crp-ZFiM.d.ts +42 -0
- package/dist/index.cjs +69 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -14
- package/dist/index.d.ts +21 -14
- package/dist/index.js +64 -33
- package/dist/index.js.map +1 -1
- package/dist/note.cjs +11 -0
- package/dist/note.cjs.map +1 -0
- package/dist/note.d.cts +29 -0
- package/dist/note.d.ts +29 -0
- package/dist/note.js +11 -0
- package/dist/note.js.map +1 -0
- package/dist/{broadcaster-preparation-DMxxZ_1Q.d.cts → operation-bridge-CoECSxfi.d.cts} +130 -245
- package/dist/{broadcaster-preparation-DMxxZ_1Q.d.ts → operation-bridge-CoECSxfi.d.ts} +130 -245
- package/dist/preparation-HUBTVCZE.js +404 -0
- package/dist/preparation-HUBTVCZE.js.map +1 -0
- package/dist/preparation-QD3ZSYV5.cjs +404 -0
- package/dist/preparation-QD3ZSYV5.cjs.map +1 -0
- package/dist/provenance-preparation-43DN2WK7.cjs +16 -0
- package/dist/provenance-preparation-43DN2WK7.cjs.map +1 -0
- package/dist/provenance-preparation-HEZE4L5H.js +16 -0
- package/dist/provenance-preparation-HEZE4L5H.js.map +1 -0
- package/dist/provenance.cjs +59 -0
- package/dist/provenance.cjs.map +1 -0
- package/dist/provenance.d.cts +34 -0
- package/dist/provenance.d.ts +34 -0
- package/dist/provenance.js +59 -0
- package/dist/provenance.js.map +1 -0
- package/dist/{receipt-logs-m0-bhaxW.d.ts → receipt-logs-DQRJK0l8.d.cts} +84 -78
- package/dist/{receipt-logs-CvC951p7.d.cts → receipt-logs-fMR6Bwql.d.ts} +84 -78
- package/dist/session-support.cjs +28 -7
- package/dist/session-support.cjs.map +1 -1
- package/dist/session-support.d.cts +71 -39
- package/dist/session-support.d.ts +71 -39
- package/dist/session-support.js +58 -37
- package/dist/session-support.js.map +1 -1
- package/package.json +22 -6
- package/dist/broadcaster-preparation-RMWQFYNL.js +0 -11
- package/dist/broadcaster-preparation-UGOTO4SX.cjs +0 -11
- package/dist/broadcaster-preparation-UGOTO4SX.cjs.map +0 -1
- package/dist/chunk-7F7ZZW3L.cjs.map +0 -1
- package/dist/chunk-EHP5TBC6.js +0 -3565
- package/dist/chunk-EHP5TBC6.js.map +0 -1
- package/dist/chunk-GTPUYPQL.js.map +0 -1
- package/dist/chunk-ITTGBIG2.js +0 -1877
- package/dist/chunk-ITTGBIG2.js.map +0 -1
- package/dist/chunk-J2JH6HIG.cjs +0 -1877
- package/dist/chunk-J2JH6HIG.cjs.map +0 -1
- package/dist/chunk-LOU7AP2B.cjs.map +0 -1
- package/dist/chunk-RHNIHI4P.cjs +0 -3565
- package/dist/chunk-RHNIHI4P.cjs.map +0 -1
- package/dist/chunk-XHKQ2BO2.js.map +0 -1
- /package/dist/{broadcaster-preparation-RMWQFYNL.js.map → broadcaster-7ZKKSTZQ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/payment-note/codec.ts","../src/errors.ts","../src/notes/resolve-recipient.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/payment-request/match-output.ts","../src/payment-request/execution.ts"],"sourcesContent":["import { FIELD_MODULUS } from \"@invisi-labs/primitives\";\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 { MissingCapabilityError } from \"@invisi-labs/primitives\";\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 {\n MissingCapabilityError,\n ReceivingAddress,\n type ReceivingKeyLookup,\n} from \"@invisi-labs/primitives\";\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/primitives\";\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/primitives\";\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/primitives\";\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 BigInt(context.protocolAddress),\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 BigInt(context.protocolAddress),\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 { ReceivingAddress } from \"@invisi-labs/primitives\";\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"],"mappings":";AAAA,SAAS,qBAAqB;AAC9B,SAAS,cAAc,cAAc,YAAY,UAAU,SAAS,cAAc;AAGlF,SAAS,KAAK,OAAe,OAA2B;AACpD,MAAI,OAAO,UAAU,YAAY,QAAQ,MAAM,SAAS,MAAM,OAAO,QAAQ,CAAC;AAC1E,UAAM,IAAI,WAAW,eAAe,QAAQ,CAAC,qBAAqB;AACtE,SAAO,SAAS,KAAK,MAAM,SAAS,EAAE,EAAE,SAAS,QAAQ,GAAG,GAAG,CAAC,EAAE;AACtE;AACA,SAAS,SAAS,OAA8B;AAC5C,QAAM,OAAO;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAC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AM,QACtB,MAAM;AAAA,IACH,QAAQ;AAAA,IACR,OAAO,QAAQ,eAAe;AAAA,IAC9B,OAAO;AAAA,IACP,OAAO,QAAQ,YAAY;AAAA,IAC3B,OAAO;AAAA,EACX,MAAO,OAAO;AAEd,UAAM,IAAI,MAAM,iCAAiC;AACrD,6BAA2B,QAAQ,KAAK,MAAM;AAC9C,MAAI,SAAS;AACT,QAAI,UAAU,SAAS,MAAO,OAAM,IAAI,MAAM,4CAA4C;AAC1F,UAAM,WAAW,MAAM;AAAA,MACnB,UAAU;AAAA,MACV,SAAS,UAAU,iBAAiB,cAAc;AAAA,MAClD,EAAE,OAAO,KAAK;AAAA,IAClB;AACA,UAAM,OAAO,SAAS,iBAAiB;AACvC,WAAO,WAAW;AAAA,MACd,YAAYA;AAAA,QACR,MAAM,2BAA2B,KAAK,kBAAkB,OAAO,MAAO;AAAA,UAClE,SAAS,QAAQ;AAAA,UACjB,iBAAiB,OAAO,QAAQ,eAAe;AAAA,UAC/C,kBAAkB,OAAO;AAAA,QAC7B,CAAC;AAAA,MACL;AAAA,MACA,MAAMA,SAAQ,WAAW,KAAK,OAAO,CAAC;AAAA,IAC1C;AACA,WAAO,OAAO;AAAA,EAClB;AACA,SAAO;AACX;AAGO,SAAS,uBAAuB,SAAqB,QAAoC;AAC5F,QAAM,OAAO,gBAAgB,OAAO;AACpC,SAAO,OAAO,MAAM;AAAA,IAChB,gBAAgB,gBAAgB,MAAM;AAAA,IACtC,qBAAqB,YAAY,OAAO,QAAQ;AAAA,IAChD,iBAAiB;AAAA,EACrB,CAAC;AACD,SAAO;AACX;","names":["value","MissingCapabilityError","MissingCapabilityError","ReceivingAddress","decodeBase64","encodeBase64","getBytes","hexlify","uint","concat","FIELD_MODULUS","ReceivingAddress","getAddress","uint","FIELD_MODULUS","getAddress","ReceivingAddress","encodeBase64","uint","getBytes","ReceivingAddress","concat","decodeBase64","hexlify","nonce","FIELD_MODULUS","ReceivingAddress","getAddress","hexlify","ReceivingAddress","hexlify","ReceivingAddress","hexlify","FIELD_MODULUS","getAddress","ReceivingAddress","nonce","hexlify"]}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/transactions/signing/statement.ts
|
|
2
|
+
var _primitives = require('@invisi-labs/primitives');
|
|
3
|
+
var _prover = require('@invisi-labs/prover');
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
var _protocol = require('@invisi-labs/protocol');
|
|
10
|
+
function requiresAuthorization(plan) {
|
|
11
|
+
if (_optionalChain([plan, 'access', _ => _.credit, 'optionalAccess', _2 => _2.revocation])) return false;
|
|
12
|
+
const ownerOnlyFullWithdrawal = !plan.credit && plan.inputs.length > 0 && plan.outputs.length === 0 && plan.params !== void 0 && plan.params.noteCommitments.length === 0 && (_nullishCoalesce(plan.params.feeAmount, () => ( 0n))) === 0n && BigInt(_nullishCoalesce(plan.params.feeRecipient, () => ( 0n))) === 0n && (_nullishCoalesce(plan.funding.amount, () => ( 0n))) === 0n && plan.fundingMode === "none" && BigInt(plan.params.withdrawalAddress) === BigInt(plan.scope.ownerAddress) && plan.params.withdrawalAmount === plan.inputs.reduce((sum, input) => sum + input.note.amount, 0n) && plan.inputs.every((input) => input.note.ownerAddress === plan.scope.ownerAddress);
|
|
13
|
+
if (ownerOnlyFullWithdrawal) return false;
|
|
14
|
+
return !!plan.credit || plan.inputs.length > 0;
|
|
15
|
+
}
|
|
16
|
+
function statement(plan) {
|
|
17
|
+
if (!plan.statement) throw new Error("operation has no proof statement");
|
|
18
|
+
const credit = plan.credit;
|
|
19
|
+
let words;
|
|
20
|
+
if (_optionalChain([credit, 'optionalAccess', _3 => _3.update]))
|
|
21
|
+
words = _protocol.updateCreditPublicInputs.call(void 0, plan.context, credit.update, credit.deliveries);
|
|
22
|
+
else if (_optionalChain([credit, 'optionalAccess', _4 => _4.creation]))
|
|
23
|
+
words = _protocol.createCreditPublicInputs.call(void 0, plan.context, credit.creation, credit.deliveries);
|
|
24
|
+
else if (_optionalChain([credit, 'optionalAccess', _5 => _5.draw]))
|
|
25
|
+
words = _protocol.creditDrawPublicInputs.call(void 0, plan.context, credit.draw, credit.deliveries);
|
|
26
|
+
else {
|
|
27
|
+
words = _protocol.transactUserPublicInputs.call(void 0,
|
|
28
|
+
plan.context,
|
|
29
|
+
plan.params,
|
|
30
|
+
plan.outputs.map((output) => output.delivery),
|
|
31
|
+
plan.funding
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
const result = _prover.WitnessBuilder.statement(
|
|
35
|
+
plan.statement.circuitName,
|
|
36
|
+
words,
|
|
37
|
+
plan.statement.target
|
|
38
|
+
);
|
|
39
|
+
if (JSON.stringify(result) !== JSON.stringify(plan.statement)) {
|
|
40
|
+
throw new Error("frozen operation statement changed");
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
function authorizationRequest(plan) {
|
|
45
|
+
let operation = "transact";
|
|
46
|
+
if (plan.kind === "draw-credit") {
|
|
47
|
+
operation = "credit-draw";
|
|
48
|
+
} else if (plan.kind === "create-credit" || plan.kind === "update-credit") {
|
|
49
|
+
operation = plan.kind;
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
context: {
|
|
53
|
+
chainId: plan.context.chainId,
|
|
54
|
+
protocolAddress: BigInt(plan.context.protocolAddress)
|
|
55
|
+
},
|
|
56
|
+
operation,
|
|
57
|
+
capacity: plan.capacity,
|
|
58
|
+
words: statement(plan).expectedPublicInputs.slice(0, -2).map(BigInt)
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function operationExpired(plan, now) {
|
|
62
|
+
if (now > plan.deadline) return true;
|
|
63
|
+
const credit = plan.credit;
|
|
64
|
+
if (_optionalChain([credit, 'optionalAccess', _6 => _6.inputs, 'access', _7 => _7.some, 'call', _8 => _8((i) => now > i.state.note.expiry)])) return true;
|
|
65
|
+
if (_optionalChain([credit, 'optionalAccess', _9 => _9.draw])) {
|
|
66
|
+
const prepared = _primitives.creditPeriods.call(void 0, plan.preparedAt.timestamp), current = _primitives.creditPeriods.call(void 0, now);
|
|
67
|
+
if (prepared.currentDay !== current.currentDay || prepared.currentMonth !== current.currentMonth)
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
exports.requiresAuthorization = requiresAuthorization; exports.statement = statement; exports.authorizationRequest = authorizationRequest; exports.operationExpired = operationExpired;
|
|
79
|
+
//# sourceMappingURL=chunk-HCB7RQ3S.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/wx/Workspace/invisi-lab/invisi-sdk-ts/packages/sdk/dist/chunk-HCB7RQ3S.cjs","../src/transactions/signing/statement.ts"],"names":[],"mappings":"AAAA;ACAA,qDAAoD;AACpD,6CAA+B;AAC/B;AACI;AACA;AACA;AACA;AAAA,iDACG;AAKA,SAAS,qBAAA,CAAsB,IAAA,EAA8B;AAChE,EAAA,GAAA,iBAAI,IAAA,mBAAK,MAAA,6BAAQ,YAAA,EAAY,OAAO,KAAA;AAEpC,EAAA,MAAM,wBAAA,EACF,CAAC,IAAA,CAAK,OAAA,GACN,IAAA,CAAK,MAAA,CAAO,OAAA,EAAS,EAAA,GACrB,IAAA,CAAK,OAA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;AACX;AD3BA;AACA;AACE;AACA;AACA;AACA;AACF,uLAAC","file":"/Users/wx/Workspace/invisi-lab/invisi-sdk-ts/packages/sdk/dist/chunk-HCB7RQ3S.cjs","sourcesContent":[null,"import { creditPeriods, type WalletOperation } from \"@invisi-labs/primitives\";\nimport { WitnessBuilder } from \"@invisi-labs/prover\";\nimport {\n createCreditPublicInputs,\n creditDrawPublicInputs,\n updateCreditPublicInputs,\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 if (plan.credit?.revocation) return false;\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.noteCommitments.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?.update)\n words = updateCreditPublicInputs(plan.context, credit.update, credit.deliveries);\n else if (credit?.creation)\n words = createCreditPublicInputs(plan.context, credit.creation, credit.deliveries);\n else if (credit?.draw)\n words = creditDrawPublicInputs(plan.context, credit.draw, credit.deliveries);\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 (plan.kind === \"create-credit\" || plan.kind === \"update-credit\") {\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?.inputs.some((i) => now > i.state.note.expiry)) return true;\n if (credit?.draw) {\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"]}
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
TransactionPreparation,
|
|
3
3
|
exportBroadcasterIntent
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-HLH5JZD4.js";
|
|
5
|
+
import {
|
|
6
|
+
broadcasterRequestHash
|
|
7
|
+
} from "./chunk-R5YAOJKB.js";
|
|
8
|
+
import {
|
|
9
|
+
assertCreditUpdatePlan
|
|
10
|
+
} from "./chunk-RY4M2CIQ.js";
|
|
5
11
|
|
|
6
12
|
// src/broadcaster/broadcaster-preparation.ts
|
|
7
13
|
import { getAddress } from "ethers";
|
|
@@ -12,16 +18,34 @@ async function prepareIntent(runtime, intent) {
|
|
|
12
18
|
return preparation.prepareTransfer(intent.options);
|
|
13
19
|
case "shield":
|
|
14
20
|
return preparation.prepareShield(intent.options);
|
|
21
|
+
case "draw-credit":
|
|
22
|
+
return preparation.prepareDrawCredit(intent.options);
|
|
15
23
|
case "create-credit":
|
|
16
24
|
return preparation.prepareCreateCredit(intent.options);
|
|
17
|
-
case "
|
|
18
|
-
return preparation.
|
|
19
|
-
case "
|
|
20
|
-
return preparation.
|
|
25
|
+
case "update-credit":
|
|
26
|
+
return preparation.prepareUpdateCredit(intent.options);
|
|
27
|
+
case "revoke-credit":
|
|
28
|
+
return preparation.prepareRevokeCredit(intent.options);
|
|
21
29
|
}
|
|
22
30
|
}
|
|
23
31
|
async function prepareBroadcasterPlan(plan, reprepare, client, options) {
|
|
32
|
+
const finalize = async (final) => {
|
|
33
|
+
const data = exportBroadcasterIntent(final).data;
|
|
34
|
+
const quote = await client.getQuote(data, {
|
|
35
|
+
chainId: final.context.chainId,
|
|
36
|
+
protocol: final.context.protocolAddress
|
|
37
|
+
});
|
|
38
|
+
return {
|
|
39
|
+
plan: final,
|
|
40
|
+
quote,
|
|
41
|
+
broadcasterBinding: {
|
|
42
|
+
configuration: { ...client.configuration },
|
|
43
|
+
intentHash: broadcasterRequestHash(data)
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
};
|
|
24
47
|
if (!plan.intent) throw new Error("operation has no supported preparation intent");
|
|
48
|
+
await assertCreditUpdatePlan(plan);
|
|
25
49
|
const intent = structuredClone(plan.intent);
|
|
26
50
|
intent.options.deadline = plan.deadline;
|
|
27
51
|
const maxFee = options.maxFeeAmount;
|
|
@@ -30,16 +54,45 @@ async function prepareBroadcasterPlan(plan, reprepare, client, options) {
|
|
|
30
54
|
throw new Error("maxFeeAmount must be a positive uint128");
|
|
31
55
|
if (!Number.isInteger(attempts) || attempts < 1 || attempts > 16)
|
|
32
56
|
throw new Error("maxAttempts must be 1..16");
|
|
57
|
+
if (intent.kind !== "transfer" && intent.kind !== "shield") {
|
|
58
|
+
if (options.feeSource || options.fundingPermit)
|
|
59
|
+
throw new Error("Credit fees use the owner allowance or gross draw deduction");
|
|
60
|
+
let current = plan;
|
|
61
|
+
let previousAmount2 = 0n;
|
|
62
|
+
for (let i = 0; i < attempts; i++) {
|
|
63
|
+
const schedule2 = await client.estimateQuote(exportBroadcasterIntent(current).data);
|
|
64
|
+
const minimum = BigInt(schedule2.feeAmount), amount = minimum > previousAmount2 ? minimum : previousAmount2;
|
|
65
|
+
const recipient = getAddress(schedule2.feeRecipient);
|
|
66
|
+
if (amount <= 0n || amount > maxFee || amount >= 1n << 128n || BigInt(recipient) === 0n)
|
|
67
|
+
throw new Error("broadcaster fee exceeds user limit or is invalid");
|
|
68
|
+
const request = structuredClone(intent);
|
|
69
|
+
request.options.fee = { recipient, amount };
|
|
70
|
+
current = await reprepare(request);
|
|
71
|
+
await assertCreditUpdatePlan(current);
|
|
72
|
+
if (current.credit?.revocation)
|
|
73
|
+
current.credit.revocationCaller = client.configuration.quoteSigner;
|
|
74
|
+
const data = exportBroadcasterIntent(current).data;
|
|
75
|
+
const recalculated = await client.estimateQuote(data);
|
|
76
|
+
if (getAddress(recalculated.feeRecipient) !== recipient || BigInt(recalculated.feeAmount) <= 0n || BigInt(recalculated.feeAmount) > maxFee)
|
|
77
|
+
throw new Error("broadcaster fee exceeds user limit or recipient changed");
|
|
78
|
+
if (amount >= BigInt(recalculated.feeAmount)) {
|
|
79
|
+
current.intent = structuredClone(intent);
|
|
80
|
+
return finalize(current);
|
|
81
|
+
}
|
|
82
|
+
previousAmount2 = amount;
|
|
83
|
+
}
|
|
84
|
+
throw new Error("broadcaster fee did not stabilize within the preparation limit");
|
|
85
|
+
}
|
|
33
86
|
const funding = "funding" in intent.options ? intent.options.funding : void 0;
|
|
34
|
-
let source = options.feeSource ?? (
|
|
35
|
-
if (!["public-funding", "private-inputs"
|
|
87
|
+
let source = options.feeSource ?? (funding ? "public-funding" : "private-inputs");
|
|
88
|
+
if (!["public-funding", "private-inputs"].includes(source))
|
|
36
89
|
throw new Error("unsupported fee source");
|
|
37
|
-
if (intent.kind === "
|
|
90
|
+
if (intent.kind === "shield" && source !== "public-funding")
|
|
38
91
|
throw new Error("fee source is unavailable for this operation");
|
|
39
92
|
if (source === "public-funding" && !funding)
|
|
40
93
|
throw new Error("public funding fee requires an explicit payer");
|
|
41
94
|
const permitCallback = options.fundingPermit;
|
|
42
|
-
let schedule = await client.
|
|
95
|
+
let schedule = await client.estimateQuote(exportBroadcasterIntent(plan).data);
|
|
43
96
|
let previousAmount = 0n;
|
|
44
97
|
for (let i = 0; i < attempts; i++) {
|
|
45
98
|
const minimum = BigInt(schedule.feeAmount);
|
|
@@ -47,11 +100,11 @@ async function prepareBroadcasterPlan(plan, reprepare, client, options) {
|
|
|
47
100
|
const recipient = getAddress(schedule.feeRecipient);
|
|
48
101
|
if (amount <= 0n || amount > maxFee || amount >= 1n << 128n || BigInt(recipient) === 0n)
|
|
49
102
|
throw new Error("broadcaster fee exceeds user limit or is invalid");
|
|
50
|
-
if (options.feeSource === void 0 && funding && plan.inputs.length > 0 &&
|
|
51
|
-
const business = intent.
|
|
103
|
+
if (options.feeSource === void 0 && funding && plan.inputs.length > 0 && intent.kind === "transfer") {
|
|
104
|
+
const business = intent.options.outputs.reduce(
|
|
52
105
|
(sum, output) => sum + output.amount,
|
|
53
106
|
intent.options.withdrawal?.amount ?? 0n
|
|
54
|
-
)
|
|
107
|
+
);
|
|
55
108
|
const change = plan.inputs.reduce((sum, input) => sum + input.note.amount, funding.amount) - business;
|
|
56
109
|
source = change >= amount ? "private-inputs" : "public-funding";
|
|
57
110
|
}
|
|
@@ -59,8 +112,6 @@ async function prepareBroadcasterPlan(plan, reprepare, client, options) {
|
|
|
59
112
|
throw new Error(
|
|
60
113
|
"existing permit cannot fund an increased amount; provide fundingPermit for final gross funding or approve separately"
|
|
61
114
|
);
|
|
62
|
-
if (source === "payout" && amount >= plan.credit.cancel.amount)
|
|
63
|
-
throw new Error("fee must be less than the cancellation refund");
|
|
64
115
|
const request = structuredClone(intent);
|
|
65
116
|
request.options.fee = { recipient, amount };
|
|
66
117
|
if (funding && "funding" in request.options) {
|
|
@@ -78,10 +129,7 @@ async function prepareBroadcasterPlan(plan, reprepare, client, options) {
|
|
|
78
129
|
const next = await reprepare(request);
|
|
79
130
|
if (source === "private-inputs" && next.inputs.length === 0)
|
|
80
131
|
throw new Error("private-inputs fee requires private funds");
|
|
81
|
-
const recalculated = await client.
|
|
82
|
-
plan.context.tokenAddress,
|
|
83
|
-
exportBroadcasterIntent(next).data
|
|
84
|
-
);
|
|
132
|
+
const recalculated = await client.estimateQuote(exportBroadcasterIntent(next).data);
|
|
85
133
|
const required = BigInt(recalculated.feeAmount);
|
|
86
134
|
if (getAddress(recalculated.feeRecipient) !== recipient || required <= 0n || required > maxFee)
|
|
87
135
|
throw new Error("broadcaster fee exceeds user limit or recipient changed");
|
|
@@ -99,21 +147,12 @@ async function prepareBroadcasterPlan(plan, reprepare, client, options) {
|
|
|
99
147
|
if (!permit) throw new Error("fundingPermit did not return a permit");
|
|
100
148
|
request.options.funding = { ...request.options.funding, permit };
|
|
101
149
|
final = await reprepare(request);
|
|
102
|
-
const permitted = await client.
|
|
103
|
-
plan.context.tokenAddress,
|
|
104
|
-
exportBroadcasterIntent(final).data
|
|
105
|
-
);
|
|
150
|
+
const permitted = await client.estimateQuote(exportBroadcasterIntent(final).data);
|
|
106
151
|
if (getAddress(permitted.feeRecipient) !== recipient || BigInt(permitted.feeAmount) > amount)
|
|
107
152
|
throw new Error("permit changed the required fee; prepare again");
|
|
108
153
|
}
|
|
109
154
|
final.intent = structuredClone(intent);
|
|
110
|
-
return
|
|
111
|
-
plan: final,
|
|
112
|
-
quote: await client.quote(exportBroadcasterIntent(final).data, {
|
|
113
|
-
chainId: final.context.chainId,
|
|
114
|
-
protocol: final.context.protocolAddress
|
|
115
|
-
})
|
|
116
|
-
};
|
|
155
|
+
return finalize(final);
|
|
117
156
|
}
|
|
118
157
|
previousAmount = amount;
|
|
119
158
|
schedule = recalculated;
|
|
@@ -125,4 +164,4 @@ export {
|
|
|
125
164
|
prepareIntent,
|
|
126
165
|
prepareBroadcasterPlan
|
|
127
166
|
};
|
|
128
|
-
//# sourceMappingURL=chunk-
|
|
167
|
+
//# sourceMappingURL=chunk-HKGJXQVN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/broadcaster/broadcaster-preparation.ts"],"sourcesContent":["import { broadcasterRequestHash } from \"./index\";\nimport type { SavedOperation } from \"../transactions/operation-types\";\nimport { assertCreditUpdatePlan } from \"../credit/state\";\nimport { getAddress } from \"ethers\";\nimport type {\n RevokeCreditPreparation,\n CreateCreditPreparation,\n DrawCreditPreparation,\n OperationPlan,\n PreparationRuntime,\n ShieldPreparation,\n UpdateCreditPreparation,\n TransferPreparation,\n} from \"../transactions/operation-types\";\nimport { TransactionPreparation } from \"../transactions/preparation/transaction-preparation\";\nimport type { BroadcasterClient, SignedBroadcasterQuote } from \"./index\";\nimport { exportBroadcasterIntent } from \"./intent\";\nexport type PreparationIntent =\n | { kind: \"transfer\"; options: TransferPreparation }\n | { kind: \"shield\"; options: ShieldPreparation }\n | { kind: \"create-credit\"; options: CreateCreditPreparation }\n | { kind: \"draw-credit\"; options: DrawCreditPreparation }\n | { kind: \"update-credit\"; options: UpdateCreditPreparation }\n | { kind: \"revoke-credit\"; options: RevokeCreditPreparation };\nexport type BroadcasterFeeSource = \"public-funding\" | \"private-inputs\";\nexport interface BroadcasterQuoteOptions {\n maxFeeAmount: bigint;\n feeSource?: BroadcasterFeeSource;\n maxAttempts?: number;\n /** Optional app-owned permit signing, requested once for the final gross funding amount. */\n fundingPermit?: (request: {\n payer: `0x${string}`;\n amount: bigint;\n tokenAddress: `0x${string}`;\n protocolAddress: `0x${string}`;\n }) => Promise<NonNullable<TransferPreparation[\"funding\"]>[\"permit\"]>;\n}\nexport async function prepareIntent(\n runtime: PreparationRuntime<OperationPlan>,\n intent: PreparationIntent\n): Promise<OperationPlan> {\n const preparation = new TransactionPreparation(runtime);\n switch (intent.kind) {\n case \"transfer\":\n return preparation.prepareTransfer(intent.options);\n case \"shield\":\n return preparation.prepareShield(intent.options);\n case \"draw-credit\":\n return preparation.prepareDrawCredit(intent.options);\n case \"create-credit\":\n return preparation.prepareCreateCredit(intent.options);\n case \"update-credit\":\n return preparation.prepareUpdateCredit(intent.options);\n case \"revoke-credit\":\n return preparation.prepareRevokeCredit(intent.options);\n }\n}\nexport async function prepareBroadcasterPlan(\n plan: OperationPlan,\n reprepare: (intent: PreparationIntent) => Promise<OperationPlan>,\n client: BroadcasterClient,\n options: BroadcasterQuoteOptions\n): Promise<{\n plan: OperationPlan;\n quote: SignedBroadcasterQuote;\n broadcasterBinding: NonNullable<SavedOperation[\"broadcasterBinding\"]>;\n}> {\n const finalize = async (final: OperationPlan) => {\n const data = exportBroadcasterIntent(final).data;\n const quote = await client.getQuote(data, {\n chainId: final.context.chainId,\n protocol: final.context.protocolAddress,\n });\n return {\n plan: final,\n quote,\n broadcasterBinding: {\n configuration: { ...client.configuration },\n intentHash: broadcasterRequestHash(data),\n },\n };\n };\n if (!plan.intent) throw new Error(\"operation has no supported preparation intent\");\n await assertCreditUpdatePlan(plan);\n const intent = structuredClone(plan.intent);\n intent.options.deadline = plan.deadline;\n const maxFee = options.maxFeeAmount;\n const attempts = options.maxAttempts ?? 4;\n if (typeof maxFee !== \"bigint\" || maxFee <= 0n || maxFee >= 1n << 128n)\n throw new Error(\"maxFeeAmount must be a positive uint128\");\n if (!Number.isInteger(attempts) || attempts < 1 || attempts > 16)\n throw new Error(\"maxAttempts must be 1..16\");\n if (intent.kind !== \"transfer\" && intent.kind !== \"shield\") {\n if (options.feeSource || options.fundingPermit)\n throw new Error(\"Credit fees use the owner allowance or gross draw deduction\");\n let current = plan;\n let previousAmount = 0n;\n for (let i = 0; i < attempts; i++) {\n const schedule = await client.estimateQuote(exportBroadcasterIntent(current).data);\n const minimum = BigInt(schedule.feeAmount),\n amount = minimum > previousAmount ? minimum : previousAmount;\n const recipient = getAddress(schedule.feeRecipient) as `0x${string}`;\n if (amount <= 0n || amount > maxFee || amount >= 1n << 128n || BigInt(recipient) === 0n)\n throw new Error(\"broadcaster fee exceeds user limit or is invalid\");\n const request = structuredClone(intent);\n request.options.fee = { recipient, amount };\n current = await reprepare(request);\n await assertCreditUpdatePlan(current);\n if (current.credit?.revocation)\n current.credit.revocationCaller = client.configuration.quoteSigner as `0x${string}`;\n const data = exportBroadcasterIntent(current).data;\n const recalculated = await client.estimateQuote(data);\n if (\n getAddress(recalculated.feeRecipient) !== recipient ||\n BigInt(recalculated.feeAmount) <= 0n ||\n BigInt(recalculated.feeAmount) > maxFee\n )\n throw new Error(\"broadcaster fee exceeds user limit or recipient changed\");\n if (amount >= BigInt(recalculated.feeAmount)) {\n current.intent = structuredClone(intent);\n return finalize(current);\n }\n previousAmount = amount;\n }\n throw new Error(\"broadcaster fee did not stabilize within the preparation limit\");\n }\n const funding = \"funding\" in intent.options ? intent.options.funding : undefined;\n let source = options.feeSource ?? (funding ? \"public-funding\" : \"private-inputs\");\n if (![\"public-funding\", \"private-inputs\"].includes(source))\n throw new Error(\"unsupported fee source\");\n if (intent.kind === \"shield\" && source !== \"public-funding\")\n throw new Error(\"fee source is unavailable for this operation\");\n if (source === \"public-funding\" && !funding)\n throw new Error(\"public funding fee requires an explicit payer\");\n const permitCallback = options.fundingPermit;\n let schedule = await client.estimateQuote(exportBroadcasterIntent(plan).data);\n let previousAmount = 0n;\n for (let i = 0; i < attempts; i++) {\n const minimum = BigInt(schedule.feeAmount);\n const amount = minimum > previousAmount ? minimum : previousAmount;\n const recipient = getAddress(schedule.feeRecipient) as `0x${string}`;\n if (amount <= 0n || amount > maxFee || amount >= 1n << 128n || BigInt(recipient) === 0n)\n throw new Error(\"broadcaster fee exceeds user limit or is invalid\");\n // Prefer already available private change; never add a payer implicitly.\n if (\n options.feeSource === undefined &&\n funding &&\n plan.inputs.length > 0 &&\n intent.kind === \"transfer\"\n ) {\n const business = intent.options.outputs.reduce(\n (sum, output) => sum + output.amount,\n intent.options.withdrawal?.amount ?? 0n\n );\n const change =\n plan.inputs.reduce((sum, input) => sum + input.note.amount, funding.amount) -\n business;\n source = change >= amount ? \"private-inputs\" : \"public-funding\";\n }\n if (\n source === \"public-funding\" &&\n funding?.permit &&\n funding.permit.deadline !== 0n &&\n !permitCallback\n )\n throw new Error(\n \"existing permit cannot fund an increased amount; provide fundingPermit for final gross funding or approve separately\"\n );\n const request = structuredClone(intent);\n request.options.fee = { recipient, amount };\n if (funding && \"funding\" in request.options) {\n const signedFunding = { ...funding };\n if (funding.authorization === \"caller\") {\n delete signedFunding.sigNonce;\n delete signedFunding.deadline;\n }\n request.options.funding = {\n ...signedFunding,\n amount: funding.amount + (source === \"public-funding\" ? amount : 0n),\n authorization: \"signature\",\n };\n }\n const next = await reprepare(request);\n if (source === \"private-inputs\" && next.inputs.length === 0)\n throw new Error(\"private-inputs fee requires private funds\");\n const recalculated = await client.estimateQuote(exportBroadcasterIntent(next).data);\n const required = BigInt(recalculated.feeAmount);\n if (\n getAddress(recalculated.feeRecipient) !== recipient ||\n required <= 0n ||\n required > maxFee\n )\n throw new Error(\"broadcaster fee exceeds user limit or recipient changed\");\n if (amount >= required) {\n let final = next;\n if (permitCallback) {\n if (!funding || !(\"funding\" in request.options))\n throw new Error(\"fundingPermit requires public funding\");\n const permit = await permitCallback({\n payer: funding.payer,\n amount: request.options.funding!.amount,\n tokenAddress: plan.context.tokenAddress,\n protocolAddress: plan.context.protocolAddress,\n });\n if (!permit) throw new Error(\"fundingPermit did not return a permit\");\n request.options.funding = { ...request.options.funding!, permit };\n final = await reprepare(request);\n const permitted = await client.estimateQuote(exportBroadcasterIntent(final).data);\n if (\n getAddress(permitted.feeRecipient) !== recipient ||\n BigInt(permitted.feeAmount) > amount\n )\n throw new Error(\"permit changed the required fee; prepare again\");\n }\n final.intent = structuredClone(intent);\n return finalize(final);\n }\n previousAmount = amount;\n schedule = recalculated;\n }\n throw new Error(\"broadcaster fee did not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