@invisi-labs/primitives 0.0.0-stage → 1.2.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/disclosure/disclosure.ts","../src/wallet/capabilities.ts","../src/wallet/wallet.ts","../src/wallet/wallet-object.ts","../src/delivery/memo.ts","../src/wallet/signing-request.ts","../src/delivery/payload.ts","../src/delivery/decryptor.ts","../src/wallet/wallet-wire.ts","../src/provenance/intent-hash.ts"],"sourcesContent":["import { bytesToHex } from \"@noble/hashes/utils\";\nimport { FIELD_MODULUS } from \"../crypto/random\";\nimport {\n decryptCreditState,\n decryptCreditPayload,\n decryptNotePayload,\n decryptPrivateTransferNote,\n exportPayloadKey,\n type CreditStateDecryptionContext,\n type NoteBytes,\n type NoteDecryptionContext,\n} from \"../delivery/encryption\";\nimport { computeNoteCommitment, computeNoteIdentity } from \"../notes/commitment\";\nimport {\n computeCreditCommitment,\n computeCreditSharedKeyHash,\n normalizeCreditPolicy,\n normalizeCreditUsage,\n} from \"../credit/state\";\nimport type { CreditState, CreditPolicy, CreditUsage, Note } from \"../types\";\n\n/** A Credit commitment opening excludes encrypted memos and the shared recovery/nullifier secret. */\nexport interface CreditOpening\n extends\n Omit<CreditState, \"creditSharedKey\" | \"memo\" | keyof CreditPolicy | keyof CreditUsage>,\n CreditPolicy,\n CreditUsage {\n creditSharedKeyHash: `0x${string}`;\n}\n\n/** Independently authenticated output data. Core verification alone does not establish inclusion. */\nexport interface DisclosureOutput {\n chainId: bigint;\n protocolAddress: bigint;\n tokenAddress: bigint;\n outputCommitment: `0x${string}`;\n role: \"funds\" | \"owner\" | \"spender\";\n ciphertext?: NoteBytes | undefined;\n}\n\n/** Sensitive transport material: obtain it only through the explicit export() operation. */\nexport interface DisclosureExport {\n version: 1;\n kind: \"note\" | \"credit\";\n method: \"opening\" | \"payload-key\";\n context: {\n chainId: string;\n protocolAddress: string;\n tokenAddress: string;\n outputCommitment: `0x${string}`;\n };\n data: Record<string, string>;\n}\n\nexport type DisclosureResult =\n | { kind: \"note\"; note: Readonly<Note> }\n | { kind: \"credit\"; note: Readonly<CreditOpening & { payload?: Uint8Array }> };\n\nconst NOTE_FIELDS = [\"ownerAddress\", \"amount\", \"nonce\"] as const;\nconst CREDIT_FIELDS = [\n \"spenderWalletIdentity\",\n \"ownerWalletIdentity\",\n \"revocationShard\",\n \"revocationSlot\",\n \"nonce\",\n \"expiry\",\n \"creditSharedKeyHash\",\n \"singleLimit\",\n \"dailyLimit\",\n \"monthlyLimit\",\n \"availableCredit\",\n \"unlimited\",\n \"lastDay\",\n \"dailySpent\",\n \"lastMonth\",\n \"monthlySpent\",\n \"totalSpent\",\n] as const;\n\nfunction record(value: unknown, fields: readonly string[]): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new Error(\"invalid disclosure object\");\n const keys = Object.keys(value);\n if (keys.length !== fields.length || keys.some((key) => !fields.includes(key)))\n throw new Error(\"unexpected disclosure fields\");\n return value as Record<string, unknown>;\n}\n\nfunction number(value: unknown, bits: number, label: string): bigint {\n if (typeof value !== \"bigint\" || value < 0n || value >= 1n << BigInt(bits))\n throw new Error(`invalid disclosure ${label}`);\n return value;\n}\n\nfunction decimal(value: unknown, bits: number, label: string): bigint {\n if (typeof value !== \"string\" || !/^(0|[1-9][0-9]*)$/.test(value) || value.length > 78)\n throw new Error(`invalid disclosure ${label}`);\n return number(BigInt(value), bits, label);\n}\n\nfunction hash(value: unknown, label: string, field = true): `0x${string}` {\n if (typeof value !== \"string\" || !/^0x[0-9a-fA-F]{64}$/.test(value))\n throw new Error(`invalid disclosure ${label}`);\n if (field && BigInt(value) >= FIELD_MODULUS) throw new Error(`invalid disclosure ${label}`);\n return value.toLowerCase() as `0x${string}`;\n}\n\nfunction owner(value: unknown, label: string): `0x${string}` {\n if (typeof value !== \"string\" || !/^0x[0-9a-fA-F]{40}$/.test(value) || BigInt(value) === 0n)\n throw new Error(`invalid disclosure ${label}`);\n return value.toLowerCase() as `0x${string}`;\n}\n\nfunction nonce(value: bigint): bigint {\n if (value < 0n || value >= FIELD_MODULUS) throw new Error(\"invalid disclosure nonce\");\n return value;\n}\n\nfunction context(value: Pick<DisclosureOutput, \"chainId\" | \"protocolAddress\" | \"tokenAddress\">) {\n const result = {\n chainId: number(value.chainId, 64, \"chainId\"),\n protocolAddress: number(value.protocolAddress, 160, \"protocolAddress\"),\n tokenAddress: number(value.tokenAddress, 160, \"tokenAddress\"),\n };\n if (result.protocolAddress === 0n || result.tokenAddress === 0n)\n throw new Error(\"disclosure addresses must be nonzero\");\n return result;\n}\n\nfunction encode(values: Record<string, bigint | string>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [key, value.toString()])\n );\n}\n\nasync function creditOpening(note: CreditState): Promise<CreditOpening> {\n const copied = { ...note };\n return {\n ...context(copied),\n ...normalizeCreditPolicy(copied),\n ...normalizeCreditUsage(copied),\n availableCredit: number(copied.availableCredit, 128, \"availableCredit\"),\n unlimited: copied.unlimited,\n spenderWalletIdentity: owner(copied.spenderWalletIdentity, \"spender identity\"),\n ownerWalletIdentity: owner(copied.ownerWalletIdentity, \"owner identity\"),\n revocationShard: number(copied.revocationShard, 64, \"revocation shard\"),\n revocationSlot: number(copied.revocationSlot, 16, \"revocation slot\"),\n nonce: nonce(copied.nonce),\n expiry: number(copied.expiry, 64, \"expiry\"),\n creditSharedKeyHash: await computeCreditSharedKeyHash(copied.creditSharedKey),\n };\n}\n\nasync function commitment(note: Note | CreditOpening): Promise<`0x${string}`> {\n if (\"creditSharedKeyHash\" in note) {\n return computeCreditCommitment({ ...note, creditSharedKey: 0n }, note.creditSharedKeyHash);\n }\n return computeNoteCommitment(\n note.chainId,\n BigInt(note.protocolAddress),\n await computeNoteIdentity(BigInt(note.ownerAddress), note.nonce),\n note.tokenAddress,\n note.amount\n );\n}\n\n/** Scoped disclosure material. Default JSON/inspection is redacted; export() is deliberately sensitive. */\nexport class Disclosure {\n readonly #material: DisclosureExport;\n\n private constructor(material: DisclosureExport) {\n this.#material = {\n ...material,\n context: Object.freeze({ ...material.context }),\n data: Object.freeze({ ...material.data }),\n };\n Object.freeze(this.#material);\n Object.freeze(this);\n }\n\n static async fromNote(value: Note): Promise<Disclosure> {\n const copied = { ...value };\n const note: Note = {\n ...context(copied),\n ownerAddress: owner(copied.ownerAddress, \"owner address\"),\n amount: number(copied.amount, 128, \"amount\"),\n nonce: nonce(copied.nonce),\n };\n return new Disclosure({\n version: 1,\n kind: \"note\",\n method: \"opening\",\n context: {\n ...encode(context(note)),\n outputCommitment: await commitment(note),\n } as DisclosureExport[\"context\"],\n data: encode({\n ownerAddress: note.ownerAddress,\n amount: note.amount,\n nonce: note.nonce,\n }),\n });\n }\n\n static async fromCredit(value: CreditState): Promise<Disclosure> {\n const note = await creditOpening(value);\n const data = Object.fromEntries(\n CREDIT_FIELDS.map((key) => [\n key,\n key === \"unlimited\" ? (note.unlimited ? \"1\" : \"0\") : note[key].toString(),\n ])\n );\n return new Disclosure({\n version: 1,\n kind: \"credit\",\n method: \"opening\",\n context: {\n ...encode(context(note)),\n outputCommitment: await commitment(note),\n } as DisclosureExport[\"context\"],\n data,\n });\n }\n\n /** Low-level factory; normally use wallet.getViewer().discloseNote(). */\n static async fromEncryptedNote(\n key: NoteBytes,\n envelope: NoteBytes,\n value: NoteDecryptionContext\n ): Promise<Disclosure> {\n const scoped = { ...value };\n const copied = typeof envelope === \"string\" ? envelope : Uint8Array.from(envelope);\n const localKey = typeof key === \"string\" ? key : Uint8Array.from(key);\n try {\n await decryptPrivateTransferNote(localKey, copied, scoped);\n return await Disclosure.fromEnvelope(localKey, copied, scoped, \"funds\");\n } finally {\n if (localKey instanceof Uint8Array) localKey.fill(0);\n }\n }\n\n /** Exposes the full selected Credit envelope, including its shared key and receiving snapshots. */\n static async fromEncryptedCredit(\n key: NoteBytes,\n envelope: NoteBytes,\n value: CreditStateDecryptionContext\n ): Promise<Disclosure> {\n const scoped = { ...value };\n const copied = typeof envelope === \"string\" ? envelope : Uint8Array.from(envelope);\n const localKey = typeof key === \"string\" ? key : Uint8Array.from(key);\n try {\n await decryptCreditState(localKey, copied, scoped);\n return await Disclosure.fromEnvelope(localKey, copied, scoped, scoped.role);\n } finally {\n if (localKey instanceof Uint8Array) localKey.fill(0);\n }\n }\n\n private static async fromEnvelope(\n key: NoteBytes,\n envelope: NoteBytes,\n scoped: NoteDecryptionContext,\n role: DisclosureOutput[\"role\"]\n ): Promise<Disclosure> {\n const payloadKey = await exportPayloadKey(key, envelope, role !== \"funds\");\n try {\n return new Disclosure({\n version: 1,\n kind: role === \"funds\" ? \"note\" : \"credit\",\n method: \"payload-key\",\n context: {\n ...encode(context(scoped)),\n outputCommitment: hash(scoped.outputCommitment, \"commitment\"),\n } as DisclosureExport[\"context\"],\n data: {\n payloadKey: `0x${bytesToHex(payloadKey)}`,\n ownerAddress: owner(scoped.ownerAddress, \"owner address\"),\n role,\n },\n });\n } finally {\n payloadKey.fill(0);\n }\n }\n\n /** Parse untrusted JSON material; verification against an independent output is still required. */\n static async fromExport(value: unknown): Promise<Disclosure> {\n const root = record(value, [\"version\", \"kind\", \"method\", \"context\", \"data\"]);\n if (\n root.version !== 1 ||\n (root.kind !== \"note\" && root.kind !== \"credit\") ||\n (root.method !== \"opening\" && root.method !== \"payload-key\")\n )\n throw new Error(\"unsupported disclosure format\");\n const rawContext = record(root.context, [\n \"chainId\",\n \"protocolAddress\",\n \"tokenAddress\",\n \"outputCommitment\",\n ]);\n const scoped = context({\n chainId: decimal(rawContext.chainId, 64, \"chainId\"),\n protocolAddress: decimal(rawContext.protocolAddress, 160, \"protocolAddress\"),\n tokenAddress: decimal(rawContext.tokenAddress, 160, \"tokenAddress\"),\n });\n const outputCommitment = hash(rawContext.outputCommitment, \"commitment\");\n const fields =\n root.method === \"payload-key\"\n ? [\"payloadKey\", \"ownerAddress\", \"role\"]\n : root.kind === \"note\"\n ? NOTE_FIELDS\n : CREDIT_FIELDS;\n const raw = record(root.data, fields);\n const data: Record<string, string> = {};\n for (const key of fields) {\n if (key === \"role\") {\n if (\n root.kind === \"note\"\n ? raw[key] !== \"funds\"\n : raw[key] !== \"owner\" && raw[key] !== \"spender\"\n )\n throw new Error(\"invalid disclosure role\");\n data[key] = raw[key] as string;\n } else if (\n key === \"payloadKey\" ||\n key.endsWith(\"Identity\") ||\n key === \"ownerAddress\" ||\n key === \"creditSharedKeyHash\"\n ) {\n data[key] =\n key.endsWith(\"Identity\") || key === \"ownerAddress\"\n ? owner(raw[key], key)\n : hash(raw[key], key, key !== \"payloadKey\");\n } else if (key === \"unlimited\") {\n if (raw[key] !== \"0\" && raw[key] !== \"1\")\n throw Error(\"invalid disclosure unlimited\");\n data[key] = raw[key] as string;\n } else {\n const bits =\n key === \"availableCredit\"\n ? 128\n : key.endsWith(\"Payout\")\n ? 160\n : key === \"expiry\"\n ? 64\n : key === \"amount\"\n ? root.kind === \"note\"\n ? 128\n : 126\n : 254;\n const parsed = decimal(raw[key], bits, key);\n if (key === \"nonce\") nonce(parsed);\n data[key] = parsed.toString();\n }\n }\n const material: DisclosureExport = {\n version: 1,\n kind: root.kind,\n method: root.method,\n context: { ...encode(scoped), outputCommitment } as DisclosureExport[\"context\"],\n data,\n };\n const result = new Disclosure(material);\n if (material.method === \"opening\")\n await result.verify({\n ...scoped,\n outputCommitment,\n role: material.kind === \"note\" ? \"funds\" : \"owner\",\n });\n return result;\n }\n\n getScope() {\n const { version, kind, method } = this.#material;\n return {\n version,\n kind,\n method,\n permitsOwnerSweep: kind === \"note\",\n revealsNoteConsumption: kind === \"note\",\n revealsCreditSharedKey: kind === \"credit\" && method === \"payload-key\",\n revealsReceivingKeys: kind === \"credit\" && method === \"payload-key\",\n revealsMemo: method === \"payload-key\",\n revealsPayload: method === \"payload-key\",\n };\n }\n\n /** Explicitly export sensitive, JSON-compatible material for a chosen recipient. */\n export(): DisclosureExport {\n return {\n ...this.#material,\n context: { ...this.#material.context },\n data: { ...this.#material.data },\n };\n }\n\n async verify(value: DisclosureOutput): Promise<DisclosureResult> {\n const output = {\n ...value,\n ciphertext:\n value.ciphertext instanceof Uint8Array\n ? Uint8Array.from(value.ciphertext)\n : value.ciphertext,\n };\n const scoped = context(output);\n const material = this.#material;\n for (const field of [\"chainId\", \"protocolAddress\", \"tokenAddress\"] as const) {\n if (scoped[field].toString() !== material.context[field])\n throw new Error(\"disclosure deployment context mismatch\");\n }\n if (hash(output.outputCommitment, \"commitment\") !== material.context.outputCommitment)\n throw new Error(\"disclosure output commitment mismatch\");\n if (\n material.kind === \"note\"\n ? output.role !== \"funds\"\n : output.role !== \"owner\" && output.role !== \"spender\"\n )\n throw new Error(\"disclosure output role mismatch\");\n const data = material.data;\n if (material.method === \"payload-key\") {\n if (output.role !== data.role || output.ciphertext === undefined)\n throw new Error(\"disclosure requires the selected role envelope\");\n const decryption = {\n ...scoped,\n outputCommitment: output.outputCommitment,\n ownerAddress: data.ownerAddress as `0x${string}`,\n };\n if (material.kind === \"note\")\n return {\n kind: \"note\",\n note: Object.freeze(\n await decryptNotePayload(\n data.payloadKey as `0x${string}`,\n output.ciphertext,\n decryption\n )\n ),\n };\n const state = await decryptCreditPayload(\n data.payloadKey as `0x${string}`,\n output.ciphertext,\n { ...decryption, role: output.role as \"owner\" | \"spender\" }\n );\n return {\n kind: \"credit\",\n note: Object.freeze({\n ...(await creditOpening(state.note)),\n ...(state.note.payload === undefined\n ? {}\n : { payload: structuredClone(state.note.payload) }),\n }),\n };\n }\n if (material.kind === \"note\") {\n const note: Note = {\n ...scoped,\n ownerAddress: data.ownerAddress as `0x${string}`,\n amount: BigInt(data.amount!),\n nonce: BigInt(data.nonce!),\n };\n if ((await commitment(note)) !== material.context.outputCommitment)\n throw new Error(\"disclosure opening commitment mismatch\");\n return { kind: \"note\", note: Object.freeze(note) };\n }\n const note: CreditOpening = {\n ...scoped,\n spenderWalletIdentity: data.spenderWalletIdentity as `0x${string}`,\n ownerWalletIdentity: data.ownerWalletIdentity as `0x${string}`,\n revocationShard: BigInt(data.revocationShard!),\n revocationSlot: BigInt(data.revocationSlot!),\n nonce: BigInt(data.nonce!),\n expiry: BigInt(data.expiry!),\n ...normalizeCreditPolicy(\n Object.fromEntries(\n [\"singleLimit\", \"dailyLimit\", \"monthlyLimit\"].map((k) => [k, BigInt(data[k]!)])\n )\n ),\n ...normalizeCreditUsage(\n Object.fromEntries(\n [\"lastDay\", \"dailySpent\", \"lastMonth\", \"monthlySpent\", \"totalSpent\"].map(\n (k) => [k, BigInt(data[k]!)]\n )\n )\n ),\n availableCredit: BigInt(data.availableCredit!),\n unlimited: data.unlimited === \"1\",\n creditSharedKeyHash: data.creditSharedKeyHash as `0x${string}`,\n };\n if ((await commitment(note)) !== material.context.outputCommitment)\n throw new Error(\"disclosure opening commitment mismatch\");\n return { kind: \"credit\", note: Object.freeze(note) };\n }\n\n toJSON() {\n return { capability: \"disclosure\", ...this.getScope() };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this.toJSON();\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils\";\nimport { ReceivingAddress } from \"../address/receiving-address\";\nimport {\n decryptCreditState,\n decryptPrivateTransferNote,\n viewingPublicKey,\n type CreditStateDecryptionContext,\n type NoteBytes,\n type NoteDecryptionContext,\n} from \"../delivery/encryption\";\nimport { Disclosure } from \"../disclosure/disclosure\";\nimport { deriveClueKey } from \"../fmd/fmd\";\nimport { computeNoteNullifier } from \"../notes/nullifier\";\nimport {\n buildWalletAuthorizationWitness,\n computeOwnerAddress,\n computeWalletAuthorizationDigest,\n type WalletAuthorizationRequest,\n type WalletAuthorizationWitness,\n type WalletBytes,\n} from \"./wallet\";\n\ntype Identity = `0x${string}`;\n\nconst copyWitness = (witness: WalletAuthorizationWitness): WalletAuthorizationWitness => ({\n public_key_x: [...witness.public_key_x],\n public_key_y: [...witness.public_key_y],\n signature: [...witness.signature],\n});\n\nconst inspect = Symbol.for(\"nodejs.util.inspect.custom\");\n\nfunction copyBytes(value: WalletBytes): Uint8Array {\n if (typeof value === \"string\" && !/^0x(?:[0-9a-fA-F]{2})+$/.test(value)) {\n throw new Error(\"invalid hexadecimal bytes\");\n }\n return typeof value === \"string\" ? hexToBytes(value.slice(2)) : Uint8Array.from(value);\n}\n\nfunction identity(value: Identity): Identity {\n return ReceivingAddress.fromIdentity(value).ownerAddress;\n}\n\n/** Local viewing permission, permitting note recovery and owner-only sweep, without arbitrary spending. */\nexport class ViewingCapability {\n readonly #key: Uint8Array;\n readonly ownerAddress: Identity;\n\n constructor(ownerAddress: Identity, privateKey: WalletBytes, expectedPublicKey?: Uint8Array) {\n this.ownerAddress = identity(ownerAddress);\n this.#key = copyBytes(privateKey);\n const publicKey = viewingPublicKey(this.#key);\n if (expectedPublicKey && bytesToHex(publicKey) !== bytesToHex(expectedPublicKey)) {\n throw new Error(\"viewing key pair mismatch\");\n }\n Object.freeze(this);\n }\n\n decryptNote(envelope: NoteBytes, context: Omit<NoteDecryptionContext, \"ownerAddress\">) {\n return decryptPrivateTransferNote(this.#key, envelope, {\n ...context,\n ownerAddress: this.ownerAddress,\n });\n }\n\n decryptCredit(\n envelope: NoteBytes,\n context: Omit<CreditStateDecryptionContext, \"ownerAddress\">\n ) {\n return decryptCreditState(this.#key, envelope, {\n ...context,\n ownerAddress: this.ownerAddress,\n });\n }\n\n getPublicKey(): Uint8Array {\n return viewingPublicKey(this.#key);\n }\n\n /** Disclose this authenticated output's payload key, without exporting the wallet viewing key. */\n discloseNote(envelope: NoteBytes, context: Omit<NoteDecryptionContext, \"ownerAddress\">) {\n return Disclosure.fromEncryptedNote(this.#key, envelope, {\n ...context,\n ownerAddress: this.ownerAddress,\n });\n }\n\n /** Exposes the entire Credit envelope; prefer Disclosure.fromCredit() for hash-only opening. */\n discloseCredit(\n envelope: NoteBytes,\n context: Omit<CreditStateDecryptionContext, \"ownerAddress\">\n ) {\n return Disclosure.fromEncryptedCredit(this.#key, envelope, {\n ...context,\n ownerAddress: this.ownerAddress,\n });\n }\n\n /** Explicit sensitive export for delegating viewing. It grants note recovery and owner-only sweep permission. */\n exportKey(): Uint8Array {\n return Uint8Array.from(this.#key);\n }\n\n toJSON() {\n return { capability: \"viewing\", ownerAddress: this.ownerAddress };\n }\n\n [inspect]() {\n return this.toJSON();\n }\n}\n\n/** Delegated candidate detection key, without viewing or spending. */\nexport class Detector {\n readonly #key: Uint8Array;\n readonly #clueKey: Uint8Array;\n\n constructor(key: Uint8Array) {\n this.#key = Uint8Array.from(key);\n this.#clueKey = deriveClueKey(this.#key);\n Object.freeze(this);\n }\n\n getClueKey(): Uint8Array {\n return Uint8Array.from(this.#clueKey);\n }\n\n /** Full detection delegation; the receiver chooses the checked prefix length. */\n exportKey(): Uint8Array {\n return Uint8Array.from(this.#key);\n }\n\n toJSON() {\n return { capability: \"detection\" };\n }\n\n [inspect]() {\n return this.toJSON();\n }\n}\n\n/** Note-derived spent-state calculation; the note opening supplies its nonce. */\nexport class NullifierCapability {\n readonly ownerAddress: Identity;\n\n private constructor(ownerAddress: Identity) {\n this.ownerAddress = identity(ownerAddress);\n Object.freeze(this);\n }\n\n static fromIdentity(ownerAddress: Identity): NullifierCapability {\n return new NullifierCapability(ownerAddress);\n }\n\n compute(\n chainId: bigint,\n protocolAddress: bigint,\n commitment: Identity,\n nonce: bigint\n ): Promise<Identity> {\n return computeNoteNullifier(chainId, protocolAddress, nonce, commitment);\n }\n\n toJSON() {\n return { capability: \"nullifier\", ownerAddress: this.ownerAddress };\n }\n\n [inspect]() {\n return this.toJSON();\n }\n}\n\n/** Frozen local authorization. Witness access is an explicit trusted proving boundary. */\nexport class AuthorizedStatement {\n readonly #witness: WalletAuthorizationWitness;\n readonly digest: Identity;\n readonly ownerAddress: Identity;\n\n constructor(ownerAddress: Identity, digest: Identity, witness: WalletAuthorizationWitness) {\n this.ownerAddress = ownerAddress;\n this.digest = digest;\n this.#witness = copyWitness(witness);\n Object.freeze(this);\n }\n\n withWitness<T>(assemble: (witness: WalletAuthorizationWitness) => T): T {\n return assemble(copyWitness(this.#witness));\n }\n\n toJSON() {\n return { ownerAddress: this.ownerAddress, digest: this.digest };\n }\n\n [inspect]() {\n return this.toJSON();\n }\n}\n\nexport interface WalletAuthorizationProvider {\n readonly ownerAddress: Identity;\n authorize(request: WalletAuthorizationRequest): Promise<AuthorizedStatement>;\n}\n\n/** Invisi circuit authorization, independent of an EVM funding wallet or submitter. */\nexport class WalletAuthorization implements WalletAuthorizationProvider {\n readonly #privateKey: Uint8Array;\n readonly #publicKey: Uint8Array;\n readonly ownerAddress: Identity;\n\n private constructor(ownerAddress: Identity, privateKey: Uint8Array, publicKey: Uint8Array) {\n this.ownerAddress = ownerAddress;\n this.#privateKey = privateKey;\n this.#publicKey = publicKey;\n Object.freeze(this);\n }\n\n static async fromMaterial(\n ownerAddress: Identity,\n privateKey: WalletBytes\n ): Promise<WalletAuthorization> {\n const privateBytes = copyBytes(privateKey);\n const publicBytes = secp256k1.getPublicKey(privateBytes, false);\n if ((await computeOwnerAddress(publicBytes)) !== identity(ownerAddress)) {\n throw new Error(\"owner address mismatch\");\n }\n return new WalletAuthorization(identity(ownerAddress), privateBytes, publicBytes);\n }\n\n getPublicKey(): Uint8Array {\n return Uint8Array.from(this.#publicKey);\n }\n\n async authorize(request: WalletAuthorizationRequest): Promise<AuthorizedStatement> {\n const frozen = { ...request, context: { ...request.context }, words: [...request.words] };\n const digest = computeWalletAuthorizationDigest(frozen);\n const witness = await buildWalletAuthorizationWitness(\n {\n ownerAddress: this.ownerAddress,\n spendingPrivateKey: this.#privateKey,\n spendingPublicKey: this.#publicKey,\n },\n frozen\n );\n return new AuthorizedStatement(this.ownerAddress, digest, witness);\n }\n\n toJSON() {\n return { capability: \"wallet-authorization\", ownerAddress: this.ownerAddress };\n }\n\n [inspect]() {\n return this.toJSON();\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { keccak_256 } from \"@noble/hashes/sha3\";\nimport { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from \"@noble/hashes/utils\";\nimport { FIELD_MODULUS } from \"../crypto/random\";\nimport { deriveClueKey } from \"../fmd/fmd\";\nimport type { ProtocolContext } from \"../types\";\n\nexport type WalletBytes = Uint8Array | `0x${string}`;\nexport interface InvisiWallet {\n spendingPrivateKey: Uint8Array;\n spendingPublicKey: Uint8Array;\n viewingPrivateKey: Uint8Array;\n viewingPublicKey: Uint8Array;\n detectionSeed: Uint8Array;\n detectionKey: Uint8Array;\n clueKey: Uint8Array;\n ownerAddress: `0x${string}`;\n}\nconst OPERATIONS = {\n transact: \"Transact\",\n \"create-credit\": \"CreateCredit\",\n \"credit-draw\": \"CreditDraw\",\n \"update-credit\": \"UpdateCredit\",\n} as const;\nexport type WalletOperation = keyof typeof OPERATIONS;\nexport interface WalletAuthorizationRequest {\n context: ProtocolContext;\n operation: WalletOperation;\n capacity: number;\n /** Complete, canonically padded operation words before the two digest limbs. */\n words: readonly bigint[];\n}\nexport const WALLET_AUTHORIZATION_TYPES = {\n WalletAuthorization: [\n { name: \"operation\", type: \"bytes32\" },\n { name: \"statementHash\", type: \"bytes32\" },\n ],\n} as const;\nconst FMD_SCALAR_MODULUS =\n 2111115437357092606062206234695386632838870926408408195193685246394721360383n;\nconst hex = (value: Uint8Array): `0x${string}` => `0x${bytesToHex(value)}`;\nfunction bytes(value: string | Uint8Array, length?: number): Uint8Array {\n if (typeof value === \"string\" && !/^0x(?:[0-9a-fA-F]{2})*$/.test(value))\n throw new Error(\"invalid hexadecimal bytes\");\n if (typeof value !== \"string\" && !(value instanceof Uint8Array))\n throw new TypeError(\"expected bytes\");\n const result = typeof value === \"string\" ? hexToBytes(value.slice(2)) : Uint8Array.from(value);\n if (length !== undefined && result.length !== length)\n throw new Error(`expected ${length} bytes`);\n return result;\n}\nfunction integer(value: Uint8Array): bigint {\n return BigInt(\"0x\" + bytesToHex(value));\n}\nfunction word(value: bigint): Uint8Array {\n if (value < 0n || value >= 1n << 256n) throw new RangeError(\"value exceeds uint256\");\n return hexToBytes(value.toString(16).padStart(64, \"0\"));\n}\nfunction nonzeroField(value: bigint, name: string): void {\n if (typeof value !== \"bigint\" || value <= 0n || value >= FIELD_MODULUS)\n throw new RangeError(`invalid ${name}`);\n}\nfunction deriveScalar(\n key: Uint8Array,\n salt: string,\n littleEndian = false,\n modulus = FIELD_MODULUS\n): Uint8Array {\n for (let counter = 0; counter <= 0xffffffff; counter++) {\n const info = new Uint8Array([counter >>> 24, counter >>> 16, counter >>> 8, counter]);\n const result = hkdf(sha256, key, utf8ToBytes(salt), info, 32);\n if (littleEndian) result[31] = result[31]! & 7;\n const candidate = integer(littleEndian ? result.slice().reverse() : result);\n if (candidate > 0n && candidate < (littleEndian ? FMD_SCALAR_MODULUS : modulus))\n return result;\n result.fill(0);\n }\n throw new Error(\"scalar derivation exhausted\");\n}\n\n/** Standard EVM owner address from a validated secp256k1 public key. */\nexport async function computeOwnerAddress(publicKey: WalletBytes): Promise<`0x${string}`> {\n const point = secp256k1.ProjectivePoint.fromHex(bytes(publicKey));\n point.assertValidity();\n return hex(keccak_256(point.toRawBytes(false).slice(1)).slice(12));\n}\n\n/** Derive a complete Invisi wallet from an EVM account private key, independent of HD paths. */\nexport async function deriveWallet(privateKey: string | Uint8Array): Promise<InvisiWallet> {\n const input = bytes(privateKey, 32);\n let root: Uint8Array | undefined;\n let spendingPrivateKey: Uint8Array | undefined;\n let viewingPrivateKey: Uint8Array | undefined;\n let detectionSeed: Uint8Array | undefined;\n let detectionKey: Uint8Array | undefined;\n let complete = false;\n try {\n if (!secp256k1.utils.isValidPrivateKey(input)) {\n throw new RangeError(\"invalid EVM account private key\");\n }\n root = hkdf(sha256, input, utf8ToBytes(\"Invisi.WalletRoot.v1\"), new Uint8Array(), 32);\n spendingPrivateKey = Uint8Array.from(input);\n viewingPrivateKey = deriveScalar(\n root,\n \"Invisi.WalletViewingKey.v1\",\n false,\n secp256k1.CURVE.n\n );\n detectionSeed = hkdf(\n sha256,\n root,\n utf8ToBytes(\"Invisi.WalletDetectionSeed.v1\"),\n new Uint8Array(),\n 32\n );\n const spendingPublicKey = secp256k1.getPublicKey(spendingPrivateKey, false);\n const ownerAddress = await computeOwnerAddress(spendingPublicKey);\n nonzeroField(BigInt(ownerAddress), \"owner address\");\n detectionKey = deriveScalar(detectionSeed, \"Invisi.WalletDetectionKey.v1\", true);\n const wallet = {\n spendingPrivateKey,\n spendingPublicKey,\n viewingPrivateKey,\n viewingPublicKey: secp256k1.getPublicKey(viewingPrivateKey, true),\n detectionSeed,\n detectionKey,\n clueKey: deriveClueKey(detectionKey),\n ownerAddress,\n };\n complete = true;\n return wallet;\n } finally {\n input.fill(0);\n root?.fill(0);\n if (!complete) {\n spendingPrivateKey?.fill(0);\n viewingPrivateKey?.fill(0);\n detectionSeed?.fill(0);\n detectionKey?.fill(0);\n }\n }\n}\n\n/** EIP712 data for private circuit authorization, independent of EVM funding signatures. */\nexport function walletAuthorizationTypedData(request: WalletAuthorizationRequest) {\n const { context, operation, capacity, words } = request;\n if (!Object.hasOwn(OPERATIONS, operation)) throw new Error(\"unsupported wallet operation\");\n const allowed =\n operation === \"transact\"\n ? [\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130,\n 140, 150, 160, 170, 180, 190,\n ]\n : operation === \"credit-draw\"\n ? [1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 70, 80]\n : [1];\n if (!allowed.includes(capacity)) throw new Error(\"invalid operation capacity\");\n if (!Array.isArray(words) || words.length < 2) throw new Error(\"public words required\");\n for (const value of words)\n if (typeof value !== \"bigint\" || value < 0n || value >= FIELD_MODULUS)\n throw new RangeError(\"noncanonical public field\");\n const { chainId, protocolAddress } = context;\n if (typeof chainId !== \"bigint\" || chainId < 0n || chainId >= 1n << 64n)\n throw new RangeError(\"invalid chain id\");\n if (\n typeof protocolAddress !== \"bigint\" ||\n protocolAddress <= 0n ||\n protocolAddress >= 1n << 160n\n )\n throw new RangeError(\"invalid protocol address\");\n if (words[0] !== chainId) throw new Error(\"statement chain mismatch\");\n if (words[1] !== protocolAddress) throw new Error(\"statement instance mismatch\");\n const statement = concatBytes(\n word(BigInt(capacity)),\n word(64n),\n word(BigInt(words.length)),\n ...words.map(word)\n );\n return {\n domain: {\n name: \"InvisibleProtocol\",\n version: \"1\",\n chainId,\n verifyingContract:\n `0x${protocolAddress.toString(16).padStart(40, \"0\")}` as `0x${string}`,\n },\n types: WALLET_AUTHORIZATION_TYPES,\n primaryType: \"WalletAuthorization\" as const,\n message: {\n operation: hex(\n keccak_256(\n utf8ToBytes(\n `Invisi.${OPERATIONS[operation]}.${operation === \"transact\" ? \"v1\" : \"v4\"}`\n )\n )\n ),\n statementHash: hex(keccak_256(statement)),\n },\n };\n}\n\nexport function computeWalletAuthorizationDigest(\n request: WalletAuthorizationRequest\n): `0x${string}` {\n const data = walletAuthorizationTypedData(request),\n hashText = (text: string) => keccak_256(utf8ToBytes(text));\n const domain = keccak_256(\n concatBytes(\n hashText(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n hashText(data.domain.name),\n hashText(data.domain.version),\n word(data.domain.chainId),\n word(BigInt(data.domain.verifyingContract))\n )\n );\n const structure = keccak_256(\n concatBytes(\n hashText(\"WalletAuthorization(bytes32 operation,bytes32 statementHash)\"),\n bytes(data.message.operation),\n bytes(data.message.statementHash)\n )\n );\n return hex(keccak_256(concatBytes(new Uint8Array([0x19, 0x01]), domain, structure)));\n}\n\n/** Raw low-s r||s; this signature stays in the private proving witness. */\nexport function signWalletAuthorization(\n privateKey: WalletBytes,\n request: WalletAuthorizationRequest\n): `0x${string}` {\n return hex(\n secp256k1\n .sign(bytes(computeWalletAuthorizationDigest(request)), bytes(privateKey, 32), {\n lowS: true,\n })\n .toCompactRawBytes()\n );\n}\n\nexport async function verifyWalletAuthorization(\n expectedIdentity: `0x${string}`,\n publicKey: WalletBytes,\n signature: WalletBytes,\n request: WalletAuthorizationRequest\n): Promise<boolean> {\n const raw = bytes(signature, 64),\n digest = bytes(computeWalletAuthorizationDigest(request));\n if ((await computeOwnerAddress(publicKey)) !== expectedIdentity) return false;\n return secp256k1.verify(raw, digest, bytes(publicKey), { lowS: true });\n}\n\nexport interface WalletAuthorizationWitness {\n public_key_x: number[];\n public_key_y: number[];\n signature: number[];\n}\n/** Local signature witness; never serialize this as an ordinary application request. */\nexport async function buildWalletAuthorizationWitness(\n wallet: Pick<InvisiWallet, \"spendingPrivateKey\" | \"spendingPublicKey\" | \"ownerAddress\">,\n request: WalletAuthorizationRequest\n): Promise<WalletAuthorizationWitness> {\n const publicKey = secp256k1.ProjectivePoint.fromHex(bytes(wallet.spendingPublicKey)).toRawBytes(\n false\n );\n const privateKey = bytes(wallet.spendingPrivateKey, 32),\n identity = wallet.ownerAddress;\n const statement = { ...request, context: { ...request.context }, words: [...request.words] };\n try {\n const derived = secp256k1.getPublicKey(privateKey, false);\n if (!derived.every((value, i) => value === publicKey[i]))\n throw new Error(\"spending key pair mismatch\");\n if (BigInt(await computeOwnerAddress(publicKey)) !== BigInt(identity))\n throw new Error(\"owner address mismatch\");\n return {\n public_key_x: Array.from(publicKey.slice(1, 33)),\n public_key_y: Array.from(publicKey.slice(33)),\n signature: Array.from(bytes(signWalletAuthorization(privateKey, statement), 64)),\n };\n } finally {\n privateKey.fill(0);\n }\n}\n","import { ReceivingAddress } from \"../address/receiving-address\";\nimport { MissingCapabilityError } from \"../errors\";\nimport { NullifierCapability } from \"./capabilities\";\n\n/** Public identity and receiving keys. */\nexport class WalletAddress {\n readonly #address: ReceivingAddress;\n\n protected constructor(address: ReceivingAddress) {\n this.#address = address;\n }\n\n get ownerAddress(): `0x${string}` {\n return this.#address.ownerAddress;\n }\n\n get viewingPublicKey(): Uint8Array {\n return this.#address.viewingPublicKey;\n }\n\n get clueKey(): Uint8Array {\n return this.#address.clueKey;\n }\n\n /** Complete 0i receiving address. Owner-only wallets must first resolve their receiving keys. */\n getAddress(): string {\n if (this.#address.kind !== \"long\") {\n throw new MissingCapabilityError(\"resolved receiving keys\");\n }\n return this.#address.toString();\n }\n\n getReceivingAddress(): ReceivingAddress {\n return this.#address;\n }\n\n /** Nullifiers derive from public identity and do not grant spending authority. */\n exportNullifier(): NullifierCapability {\n return NullifierCapability.fromIdentity(this.ownerAddress);\n }\n\n toJSON() {\n return { ownerAddress: this.ownerAddress, address: this.#address.toString() };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return this.toJSON();\n }\n}\n\n/** Address-only wallet. Contains no private keys or private capability methods. */\nexport class Wallet extends WalletAddress {\n private constructor(address: ReceivingAddress) {\n super(address);\n Object.freeze(this);\n }\n\n /** Parse a complete 0i address or an EVM owner address without network access. */\n static fromAddress(address: ReceivingAddress | string): Wallet {\n if (typeof address !== \"string\" && !(address instanceof ReceivingAddress)) {\n throw new TypeError(\"expected a validated receiving address\");\n }\n return new Wallet(typeof address === \"string\" ? ReceivingAddress.parse(address) : address);\n }\n}\n","/** Optional encrypted output metadata; never part of a financial commitment. */\nexport type Memo = string | Uint8Array;\nexport const MAX_MEMO_BYTES = 256;\ndeclare const TextEncoder: { new (): { encode(value: string): Uint8Array } };\ndeclare const TextDecoder: {\n new (\n label: string,\n options: { fatal: boolean; ignoreBOM: boolean }\n ): { decode(value: Uint8Array): string };\n};\n/** Encode text strictly as UTF-8, or copy opaque bytes, with a 256-byte limit. */\nexport function encodeMemo(memo?: Memo): Uint8Array {\n if (memo === undefined) return new Uint8Array();\n let encoded: Uint8Array;\n if (typeof memo === \"string\") {\n for (let i = 0; i < memo.length; i++) {\n const unit = memo.charCodeAt(i);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = memo.charCodeAt(++i);\n if (!(next >= 0xdc00 && next <= 0xdfff))\n throw new Error(\"memo contains an invalid surrogate\");\n } else if (unit >= 0xdc00 && unit <= 0xdfff)\n throw new Error(\"memo contains an invalid surrogate\");\n }\n encoded = new TextEncoder().encode(memo);\n } else if (memo instanceof Uint8Array) encoded = Uint8Array.from(memo);\n else throw new TypeError(\"memo must be text or Uint8Array\");\n if (encoded.length > MAX_MEMO_BYTES) throw new RangeError(\"memo exceeds 256 bytes\");\n return encoded;\n}\n/** Explicit strict UTF-8 decoding; opaque bytes remain valid even when decoding fails. */\nexport function decodeMemoText(memo: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(memo);\n}\n","import { TypedDataEncoder, type TypedDataDomain, type TypedDataField } from \"ethers\";\n\n/** JSON-safe EIP-712 data, directly consumable by an external signing tool. */\nexport interface SigningRequest {\n domain: {\n name?: string;\n version?: string;\n chainId?: string;\n verifyingContract?: string;\n salt?: string;\n };\n primaryType: string;\n types: Record<string, TypedDataField[]>;\n message: Record<string, unknown>;\n}\n\n/** Normalize through ethers; do not implement a second typed-data encoder. */\nexport function createSigningRequest(data: {\n domain: TypedDataDomain;\n primaryType: string;\n types: Record<string, readonly TypedDataField[]>;\n message: Record<string, unknown>;\n}): SigningRequest {\n const types = Object.fromEntries(\n Object.entries(data.types).map(([name, fields]) => [name, [...fields]])\n );\n const payload = TypedDataEncoder.getPayload(data.domain, types, data.message);\n if (payload.primaryType !== data.primaryType) {\n throw new Error(\"signing request primary type mismatch\");\n }\n // signTypedData builds its own domain type; wallet RPC transports can add it themselves.\n delete payload.types.EIP712Domain;\n return structuredClone(payload);\n}\n","import type { CreditDataV1, FundsDataV1 } from \"../types\";\nimport { encodeMemo } from \"./memo\";\n\nfunction encodeData(data: unknown): Uint8Array {\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n throw new TypeError(\"v1 payload data must be an object\");\n }\n for (const key of Object.keys(data)) {\n if (key !== \"memo\") throw new Error(`unsupported v1 payload field ${key}`);\n }\n const memo = encodeMemo((data as FundsDataV1).memo);\n return new Uint8Array([1, ...memo]);\n}\nfunction readData(value: Uint8Array): { memo?: Uint8Array } {\n if (!(value instanceof Uint8Array) || value.length < 1) {\n throw new Error(\"payload version required\");\n }\n if (value[0] !== 1) throw new Error(\"unsupported payload version\");\n const memo = Uint8Array.from(value.subarray(1));\n if (memo.length > 256) throw new Error(\"invalid memo length\");\n return memo.length === 0 ? {} : { memo };\n}\n/** Pure memo codec: payload version1 followed by memo bytes; no flags or address semantics. */\nexport const fundsV1 = Object.freeze({\n encode(data: FundsDataV1 = {}): Uint8Array {\n return encodeData(data);\n },\n decode(value: Uint8Array): { memo?: Uint8Array } {\n return readData(value);\n },\n});\n/** Credit uses the same memo-only application layout, independently of its financial fields. */\nexport const creditV1 = Object.freeze({\n encode(data: CreditDataV1 = {}): Uint8Array {\n return encodeData(data);\n },\n decode(value: Uint8Array): { memo?: Uint8Array } {\n return readData(value);\n },\n});\n","import { bytesToHex } from \"@noble/hashes/utils\";\nimport type { Wallet } from \"../wallet/wallet-object\";\nimport { deliveryCodec, validateDeliveryCiphertext } from \"./delivery-codec\";\nimport { noteCommitment, creditCommitment } from \"./validation\";\nimport type { NoteBytes, NoteDecryptionContext, CreditStateDecryptionContext } from \"./types\";\n\n/** App-owned decryption. Only null means nonrecipient; operational failures must reject. */\nexport interface DeliveryDecryptor {\n decryptNote(envelope: NoteBytes, context: NoteDecryptionContext): Promise<Uint8Array | null>;\n decryptCredit(\n envelope: NoteBytes,\n context: CreditStateDecryptionContext\n ): Promise<Uint8Array | null>;\n}\n\n/** Keeps App failures and invalid plaintext distinct from unrelated local scan candidates. */\nexport class DeliveryDecryptionError extends Error {\n constructor(cause: unknown) {\n super(cause instanceof Error ? cause.message : \"delivery decryption failed\", { cause });\n this.name = \"DeliveryDecryptionError\";\n }\n}\n\nfunction checkedPlaintext(\n plaintext: Uint8Array,\n codec: { minimum: number; maximum: number }\n): Uint8Array {\n if (!(plaintext instanceof Uint8Array)) throw new Error(\"invalid decrypted plaintext\");\n if (plaintext.length + 78 < codec.minimum || plaintext.length + 78 > codec.maximum)\n throw new Error(\"invalid plaintext length\");\n return plaintext.slice();\n}\n\n/** Bind untrusted App plaintext to the requested wallet, deployment, token and commitment. */\nexport function authenticatedDecryptor(wallet: Wallet, decryptor: DeliveryDecryptor) {\n const ownerAddress = wallet.ownerAddress;\n return {\n ownerAddress,\n async decryptNote(\n envelope: NoteBytes,\n context: Omit<NoteDecryptionContext, \"ownerAddress\">\n ) {\n context = { ...context };\n try {\n const bytes = validateDeliveryCiphertext(envelope, \"funds\");\n const full = { ...context, ownerAddress };\n const plaintext = await decryptor.decryptNote(bytes.slice(), { ...full });\n if (plaintext === null) return null;\n const codec = deliveryCodec(bytes[0]!);\n if (codec.kind !== \"funds\") throw new Error(\"unexpected envelope kind\");\n const note = codec.decode(checkedPlaintext(plaintext, codec), full);\n if (\n BigInt(note.ownerAddress) !== BigInt(ownerAddress) ||\n note.tokenAddress !== context.tokenAddress\n )\n throw new Error(\"decrypted note context mismatch\");\n await noteCommitment(full, note);\n return note;\n } catch (cause) {\n throw new DeliveryDecryptionError(cause);\n }\n },\n async decryptCredit(\n envelope: NoteBytes,\n context: Omit<CreditStateDecryptionContext, \"ownerAddress\">\n ) {\n context = { ...context };\n try {\n const bytes = validateDeliveryCiphertext(envelope, \"credit\");\n const full = { ...context, ownerAddress };\n const plaintext = await decryptor.decryptCredit(bytes.slice(), { ...full });\n if (plaintext === null) return null;\n const codec = deliveryCodec(bytes[0]!);\n if (codec.kind !== \"credit\") throw new Error(\"unexpected envelope kind\");\n const state = codec.decode(checkedPlaintext(plaintext, codec), full);\n const identity =\n context.role === \"owner\"\n ? state.note.ownerWalletIdentity\n : state.note.spenderWalletIdentity;\n if (\n BigInt(identity) !== BigInt(ownerAddress) ||\n state.note.tokenAddress !== context.tokenAddress\n )\n throw new Error(\"decrypted credit context mismatch\");\n if (wallet.getReceivingAddress().kind === \"long\") {\n const keys =\n context.role === \"owner\"\n ? state.ownerReceivingKeys\n : state.spenderReceivingKeys;\n if (bytesToHex(keys.viewingPublicKey) !== bytesToHex(wallet.viewingPublicKey))\n throw new Error(\"decrypted credit receiving key mismatch\");\n }\n await creditCommitment(full, state.note);\n return state;\n } catch (cause) {\n throw new DeliveryDecryptionError(cause);\n }\n },\n };\n}\n","import { authenticatedDecryptor } from \"../delivery/decryptor\";\nimport type { Note, CreditDeliveryState, CreditState } from \"../types\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils\";\nimport { ReceivingAddress } from \"../address/receiving-address\";\nimport { validateDeliveryCiphertext } from \"../delivery/delivery-codec\";\nimport { validateContext } from \"../delivery/validation\";\nimport type { CreditStateDecryptionContext, NoteDecryptionContext } from \"../delivery/types\";\nimport { AuthorizedStatement } from \"./capabilities\";\nimport { Wallet } from \"./wallet-object\";\nimport {\n computeOwnerAddress,\n computeWalletAuthorizationDigest,\n verifyWalletAuthorization,\n type WalletAuthorizationRequest,\n type WalletOperation,\n} from \"./wallet\";\n\nexport type WalletHex = `0x${string}`;\nexport type WalletMethod =\n | \"wallet.public\"\n | \"wallet.detect\"\n | \"wallet.decryptNote\"\n | \"wallet.decryptCredit\"\n | \"wallet.authorize\";\nexport interface WalletWireContext {\n chainId: string;\n protocolAddress: string;\n}\nexport interface WalletDecryptContext extends WalletWireContext {\n tokenAddress: string;\n outputCommitment: WalletHex;\n role?: \"owner\" | \"spender\";\n}\nexport interface WalletParams {\n \"wallet.public\": Record<string, never>;\n \"wallet.detect\": { clues: WalletHex[] };\n \"wallet.decryptNote\": { envelope: WalletHex; context: WalletDecryptContext };\n \"wallet.decryptCredit\": { envelope: WalletHex; context: WalletDecryptContext };\n \"wallet.authorize\": {\n operation: WalletOperation;\n capacity: number;\n words: string[];\n context: WalletWireContext;\n };\n}\nexport interface WalletResults {\n \"wallet.public\": {\n viewingPublicKey: WalletHex;\n spendingPublicKey: WalletHex;\n clueKey: WalletHex;\n };\n \"wallet.detect\": { matches: boolean[] };\n \"wallet.decryptNote\": { plaintext: WalletHex };\n \"wallet.decryptCredit\": { plaintext: WalletHex };\n \"wallet.authorize\": { spendingPublicKey: WalletHex; signature: WalletHex; digest: WalletHex };\n}\nexport interface WalletAcceptedResults {\n \"wallet.public\": WalletResults[\"wallet.public\"];\n \"wallet.detect\": WalletResults[\"wallet.detect\"];\n \"wallet.decryptNote\": Note & { payload: Uint8Array };\n \"wallet.decryptCredit\": CreditDeliveryState & { note: CreditState & { payload: Uint8Array } };\n \"wallet.authorize\": AuthorizedStatement;\n}\nexport type WalletRequest<M extends WalletMethod = WalletMethod> = {\n version: 1;\n id: string;\n ownerAddress: WalletHex;\n method: M;\n params: WalletParams[M];\n};\nexport type WalletResponse<M extends WalletMethod = WalletMethod> = {\n version: 1;\n id: string;\n ownerAddress: WalletHex;\n method: M;\n} & ({ result: WalletResults[M]; error?: never } | { error: { code: string }; result?: never });\nexport interface PreparedWalletRequest<M extends WalletMethod = WalletMethod> {\n readonly request: WalletRequest<M>;\n}\nexport const walletHex = (bytes: Uint8Array): WalletHex => `0x${bytesToHex(bytes)}`;\nexport function walletBytes(value: unknown, length?: number): Uint8Array {\n if (typeof value !== \"string\" || !/^0x(?:[0-9a-f]{2})*$/.test(value))\n throw new Error(\"invalid canonical hex bytes\");\n const bytes = hexToBytes(value.slice(2));\n if (length !== undefined && bytes.length !== length) throw new Error(\"invalid byte length\");\n return bytes;\n}\nexport function walletInteger(value: unknown): bigint {\n if (typeof value !== \"string\" || !/^(0|[1-9][0-9]*)$/.test(value) || value.length > 78)\n throw new Error(\"invalid canonical integer\");\n return BigInt(value);\n}\nexport function walletAuthorizationParams(\n params: WalletParams[\"wallet.authorize\"]\n): WalletAuthorizationRequest {\n return {\n ...params,\n words: params.words.map(walletInteger),\n context: {\n chainId: walletInteger(params.context.chainId),\n protocolAddress: walletInteger(params.context.protocolAddress),\n },\n };\n}\nexport function walletDecryptionContext(\n request: WalletRequest<\"wallet.decryptNote\" | \"wallet.decryptCredit\">\n): NoteDecryptionContext & { role?: \"owner\" | \"spender\" } {\n const context = request.params.context;\n return {\n chainId: walletInteger(context.chainId),\n protocolAddress: walletInteger(context.protocolAddress),\n tokenAddress: walletInteger(context.tokenAddress),\n outputCommitment: context.outputCommitment,\n ownerAddress: request.ownerAddress,\n ...(context.role ? { role: context.role } : {}),\n };\n}\nfunction freeze<T>(value: T): T {\n if (value && typeof value === \"object\") {\n Object.values(value).forEach(freeze);\n Object.freeze(value);\n }\n return value;\n}\nfunction exactKeys(value: unknown, keys: string[]): void {\n if (\n !value ||\n typeof value !== \"object\" ||\n Array.isArray(value) ||\n Object.keys(value).some((key) => !keys.includes(key)) ||\n keys.some((key) => !Object.hasOwn(value, key))\n )\n throw new Error(\"unexpected wallet fields\");\n}\nexport function validateWalletRequest(request: WalletRequest): void {\n exactKeys(request, [\"version\", \"id\", \"ownerAddress\", \"method\", \"params\"]);\n if (\n request.version !== 1 ||\n typeof request.id !== \"string\" ||\n !/^[\\x21-\\x7e]{1,128}$/.test(request.id)\n )\n throw new Error(\"invalid wallet request envelope\");\n walletBytes(request.ownerAddress, 20);\n ReceivingAddress.fromIdentity(request.ownerAddress);\n switch (request.method) {\n case \"wallet.public\":\n exactKeys(request.params, []);\n break;\n case \"wallet.detect\": {\n exactKeys(request.params, [\"clues\"]);\n const { clues } = request.params as WalletParams[\"wallet.detect\"];\n if (!Array.isArray(clues) || clues.length > 1024) throw new Error(\"invalid clues\");\n clues.forEach((clue) => walletBytes(clue, 68));\n break;\n }\n case \"wallet.authorize\": {\n exactKeys(request.params, [\"operation\", \"capacity\", \"words\", \"context\"]);\n const params = request.params as WalletParams[\"wallet.authorize\"];\n exactKeys(params.context, [\"chainId\", \"protocolAddress\"]);\n if (!Array.isArray(params.words) || params.words.length > 8192)\n throw new Error(\"invalid authorization words\");\n computeWalletAuthorizationDigest(walletAuthorizationParams(params));\n break;\n }\n case \"wallet.decryptNote\":\n case \"wallet.decryptCredit\": {\n const typed = request as WalletRequest<\"wallet.decryptNote\" | \"wallet.decryptCredit\">;\n exactKeys(typed.params, [\"envelope\", \"context\"]);\n exactKeys(typed.params.context, [\n \"chainId\",\n \"protocolAddress\",\n \"tokenAddress\",\n \"outputCommitment\",\n ...(request.method === \"wallet.decryptCredit\" ? [\"role\"] : []),\n ]);\n const context = walletDecryptionContext(typed);\n walletBytes(context.outputCommitment, 32);\n validateContext(context, context.tokenAddress);\n if (\n request.method === \"wallet.decryptCredit\" &&\n context.role !== \"owner\" &&\n context.role !== \"spender\"\n )\n throw new Error(\"invalid credit role\");\n if (request.method === \"wallet.decryptNote\" && context.role !== undefined)\n throw new Error(\"unexpected note role\");\n walletBytes(typed.params.envelope);\n validateDeliveryCiphertext(\n typed.params.envelope,\n request.method === \"wallet.decryptCredit\" ? \"credit\" : \"funds\"\n );\n break;\n }\n default:\n throw new Error(\"unsupported wallet method\");\n }\n}\nconst retainedWallets = new WeakMap<PreparedWalletRequest, Wallet>();\nexport function prepareWalletRequest<M extends WalletMethod>(\n wallet: Wallet,\n id: string,\n method: M,\n params: WalletParams[M]\n): PreparedWalletRequest<M> {\n if (!(wallet instanceof Wallet)) throw new TypeError(\"public Wallet required\");\n const request = structuredClone({\n version: 1 as const,\n id,\n ownerAddress: wallet.ownerAddress.toLowerCase() as WalletHex,\n method,\n params,\n });\n validateWalletRequest(request);\n const prepared = freeze({ request });\n retainedWallets.set(prepared, wallet);\n return prepared;\n}\n/** Validate native output against the retained request before using it in business state. */\nexport async function acceptWalletResponse<M extends WalletMethod>(\n prepared: PreparedWalletRequest<M>,\n response: WalletResponse<M>\n): Promise<WalletAcceptedResults[M]> {\n return acceptResponse(prepared, response);\n}\nasync function acceptResponse(\n prepared: PreparedWalletRequest,\n response: WalletResponse\n): Promise<any> {\n const wallet = retainedWallets.get(prepared);\n if (!wallet) throw new Error(\"wallet request was not prepared by this SDK instance\");\n const request = prepared.request;\n validateWalletRequest(request);\n const safe = structuredClone(response);\n if (\n safe.version !== request.version ||\n safe.id !== request.id ||\n safe.ownerAddress !== request.ownerAddress ||\n safe.method !== request.method\n )\n throw new Error(\"wallet response envelope mismatch\");\n validateWalletResponses([request], [safe]);\n if (\"error\" in safe) throw new NativeWalletError(safe.error!.code);\n const result = safe.result as any;\n exactKeys(\n result,\n request.method === \"wallet.public\"\n ? [\"viewingPublicKey\", \"spendingPublicKey\", \"clueKey\"]\n : request.method === \"wallet.authorize\"\n ? [\"spendingPublicKey\", \"signature\", \"digest\"]\n : request.method === \"wallet.detect\"\n ? [\"matches\"]\n : [\"plaintext\"]\n );\n if (request.method === \"wallet.public\") {\n walletBytes(result.spendingPublicKey, 65);\n walletBytes(result.viewingPublicKey, 33);\n walletBytes(result.clueKey, 32);\n if ((await computeOwnerAddress(result.spendingPublicKey)) !== request.ownerAddress)\n throw new Error(\"wallet public identity mismatch\");\n if (\n wallet.getReceivingAddress().kind === \"long\" &&\n (walletHex(wallet.viewingPublicKey) !== result.viewingPublicKey ||\n walletHex(wallet.clueKey) !== result.clueKey)\n )\n throw new Error(\"wallet receiving key mismatch\");\n ReceivingAddress.from({\n ownerAddress: request.ownerAddress,\n viewingPublicKey: walletBytes(result.viewingPublicKey),\n clueKey: walletBytes(result.clueKey),\n });\n } else if (request.method === \"wallet.authorize\") {\n const auth = walletAuthorizationParams(request.params as WalletParams[\"wallet.authorize\"]);\n if (\n result.digest !== computeWalletAuthorizationDigest(auth) ||\n !(await verifyWalletAuthorization(\n request.ownerAddress,\n result.spendingPublicKey,\n result.signature,\n auth\n ))\n )\n throw new Error(\"invalid wallet authorization response\");\n const publicKey = walletBytes(result.spendingPublicKey, 65);\n return new AuthorizedStatement(request.ownerAddress, result.digest, {\n public_key_x: Array.from(publicKey.slice(1, 33)),\n public_key_y: Array.from(publicKey.slice(33)),\n signature: Array.from(walletBytes(result.signature, 64)),\n });\n } else if (request.method === \"wallet.detect\") {\n if (\n !Array.isArray(result.matches) ||\n result.matches.length !==\n (request.params as WalletParams[\"wallet.detect\"]).clues.length ||\n result.matches.some((v: unknown) => typeof v !== \"boolean\")\n )\n throw new Error(\"invalid detection response\");\n } else {\n const typed = request as WalletRequest<\"wallet.decryptNote\" | \"wallet.decryptCredit\">;\n const context = walletDecryptionContext(typed);\n const plaintext = walletBytes(result.plaintext);\n const viewing = authenticatedDecryptor(wallet, {\n decryptNote: async () => plaintext,\n decryptCredit: async () => plaintext,\n });\n return typed.method === \"wallet.decryptNote\"\n ? viewing.decryptNote(typed.params.envelope, context)\n : viewing.decryptCredit(typed.params.envelope, context as CreditStateDecryptionContext);\n }\n return result;\n}\n\n/** Native errors contain machine-readable codes only. */\nexport class NativeWalletError extends Error {\n constructor(readonly code: string) {\n super(code);\n this.name = \"NativeWalletError\";\n }\n}\nexport const MAX_WALLET_BATCH_BYTES = 16 * 1024 * 1024;\nfunction boundedJson(value: unknown): void {\n const json = JSON.stringify(value);\n if (typeof json !== \"string\" || new TextEncoder().encode(json).length > MAX_WALLET_BATCH_BYTES)\n throw new Error(\"wallet batch exceeds encoded size limit\");\n}\nexport function validateWalletBatch(requests: readonly WalletRequest[]): void {\n if (!Array.isArray(requests) || requests.length > 1024) throw new Error(\"invalid wallet batch\");\n boundedJson(requests);\n const ids = new Set<string>();\n for (const request of requests) {\n validateWalletRequest(request);\n if (ids.has(request.id)) throw new Error(\"duplicate wallet request id\");\n if (request.ownerAddress !== requests[0]!.ownerAddress)\n throw new Error(\"mixed wallet batch owners\");\n ids.add(request.id);\n }\n}\n/** Check every envelope before returning responses in request order. */\nexport function validateWalletResponses(\n requests: readonly WalletRequest[],\n responses: readonly WalletResponse[]\n): WalletResponse[] {\n validateWalletBatch(requests);\n if (!Array.isArray(responses) || responses.length !== requests.length)\n throw new Error(\"wallet response batch length mismatch\");\n boundedJson(responses);\n const expected = new Map(requests.map((request) => [request.id, request]));\n const found = new Map<string, WalletResponse>();\n for (const response of responses) {\n if (!response || typeof response !== \"object\") throw new Error(\"invalid wallet response\");\n const request = expected.get(response.id);\n if (\n !request ||\n found.has(response.id) ||\n response.version !== 1 ||\n response.method !== request.method ||\n response.ownerAddress !== request.ownerAddress\n )\n throw new Error(\"wallet response envelope mismatch\");\n if (Object.hasOwn(response, \"error\")) {\n exactKeys(response, [\"version\", \"id\", \"ownerAddress\", \"method\", \"error\"]);\n exactKeys(response.error, [\"code\"]);\n if (\n typeof response.error?.code !== \"string\" ||\n !/^[A-Z][A-Z0-9_]{0,127}$/.test(response.error.code)\n )\n throw new Error(\"invalid native wallet error\");\n } else {\n exactKeys(response, [\"version\", \"id\", \"ownerAddress\", \"method\", \"result\"]);\n if (\n !response.result ||\n typeof response.result !== \"object\" ||\n Array.isArray(response.result)\n )\n throw new Error(\"invalid wallet result\");\n const result = response.result as any;\n exactKeys(\n result,\n request.method === \"wallet.public\"\n ? [\"viewingPublicKey\", \"spendingPublicKey\", \"clueKey\"]\n : request.method === \"wallet.authorize\"\n ? [\"spendingPublicKey\", \"signature\", \"digest\"]\n : request.method === \"wallet.detect\"\n ? [\"matches\"]\n : [\"plaintext\"]\n );\n if (request.method === \"wallet.public\") {\n walletBytes(result.viewingPublicKey, 33);\n walletBytes(result.spendingPublicKey, 65);\n walletBytes(result.clueKey, 32);\n } else if (request.method === \"wallet.authorize\") {\n walletBytes(result.spendingPublicKey, 65);\n walletBytes(result.signature, 64);\n walletBytes(result.digest, 32);\n } else if (request.method === \"wallet.detect\") {\n if (\n !Array.isArray(result.matches) ||\n result.matches.length !==\n (request.params as WalletParams[\"wallet.detect\"]).clues.length ||\n result.matches.some((value: unknown) => typeof value !== \"boolean\")\n )\n throw new Error(\"invalid detection response\");\n } else {\n walletBytes(result.plaintext);\n }\n }\n found.set(response.id, response);\n }\n return requests.map((request) => found.get(request.id)!);\n}\nexport async function acceptWalletResponses(\n prepared: readonly PreparedWalletRequest[],\n responses: readonly WalletResponse[]\n): Promise<unknown[]> {\n for (const item of prepared) {\n if (!retainedWallets.has(item))\n throw new Error(\"wallet request was not prepared by this SDK instance\");\n }\n const ordered = validateWalletResponses(\n prepared.map((item) => item.request),\n structuredClone(responses)\n );\n return Promise.all(prepared.map((item, index) => acceptWalletResponse(item, ordered[index]!)));\n}\n","import { AbiCoder, keccak256, toBeHex } from \"ethers\";\nexport function provenanceIntentHash(originalRequestHash: string): string {\n return keccak256(\n AbiCoder.defaultAbiCoder().encode(\n [\"string\", \"bytes32\"],\n [\"InvisiBroadcasterProvenanceIntentV1\", toBeHex(BigInt(originalRequestHash), 32)]\n )\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AA0D3B,IAAM,cAAc,CAAC,gBAAgB,UAAU,OAAO;AACtD,IAAM,gBAAgB;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ;AAEA,SAAS,OAAO,OAAgB,QAAoD;AAChF,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK;AAC1D,UAAM,IAAI,MAAM,2BAA2B;AAC/C,QAAM,OAAO,OAAO,KAAK,KAAK;AAC9B,MAAI,KAAK,WAAW,OAAO,UAAU,KAAK,KAAK,CAAC,QAAQ,CAAC,OAAO,SAAS,GAAG,CAAC;AACzE,UAAM,IAAI,MAAM,8BAA8B;AAClD,SAAO;AACX;AAEA,SAAS,OAAO,OAAgB,MAAc,OAAuB;AACjE,MAAI,OAAO,UAAU,YAAY,QAAQ,MAAM,SAAS,MAAM,OAAO,IAAI;AACrE,UAAM,IAAI,MAAM,sBAAsB,KAAK,EAAE;AACjD,SAAO;AACX;AAEA,SAAS,QAAQ,OAAgB,MAAc,OAAuB;AAClE,MAAI,OAAO,UAAU,YAAY,CAAC,oBAAoB,KAAK,KAAK,KAAK,MAAM,SAAS;AAChF,UAAM,IAAI,MAAM,sBAAsB,KAAK,EAAE;AACjD,SAAO,OAAO,OAAO,KAAK,GA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AClB,aAAW,QAAQ,UAAU;AACzB,QAAI,CAAC,gBAAgB,IAAI,IAAI;AACzB,YAAM,IAAI,MAAM,sDAAsD;AAAA,EAC9E;AACA,QAAM,UAAU;AAAA,IACZ,SAAS,IAAI,CAAC,SAAS,KAAK,OAAO;AAAA,IACnC,gBAAgB,SAAS;AAAA,EAC7B;AACA,SAAO,QAAQ,IAAI,SAAS,IAAI,CAAC,MAAM,UAAU,qBAAqB,MAAM,QAAQ,KAAK,CAAE,CAAC,CAAC;AACjG;;;ACtaA,SAAS,UAAU,WAAW,eAAe;AACtC,SAAS,qBAAqB,qBAAqC;AACtE,SAAO;AAAA,IACH,SAAS,gBAAgB,EAAE;AAAA,MACvB,CAAC,UAAU,SAAS;AAAA,MACpB,CAAC,uCAAuC,QAAQ,OAAO,mBAAmB,GAAG,EAAE,CAAC;AAAA,IACpF;AAAA,EACJ;AACJ;","names":["note","secp256k1","bytesToHex","hexToBytes","bytesToHex","bytesToHex","context","identity","hexToBytes","bytesToHex","context","commitment","nonce","secp256k1","bytesToHex","context","bytes","identity","bytesToHex","bytesToHex","hexToBytes","bytes","bytesToHex","hexToBytes","context"]}