@zama-fhe/sdk 3.4.0-alpha.9 → 3.4.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.
Files changed (73) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/ethers/index.cjs +1 -1
  4. package/dist/cjs/ethers/index.cjs.map +1 -1
  5. package/dist/cjs/fhevm-relayer.cjs +1 -1
  6. package/dist/cjs/fhevm-relayer.cjs.map +1 -1
  7. package/dist/cjs/index.cjs +1 -1
  8. package/dist/cjs/index.cjs.map +1 -1
  9. package/dist/cjs/node/index.cjs.map +1 -1
  10. package/dist/cjs/query/index.cjs +1 -1
  11. package/dist/cjs/query/index.cjs.map +1 -1
  12. package/dist/cjs/relayer.cjs +1 -1
  13. package/dist/cjs/relayer.cjs.map +1 -1
  14. package/dist/cjs/sdk-events.cjs +2 -0
  15. package/dist/cjs/sdk-events.cjs.map +1 -0
  16. package/dist/cjs/token.cjs +1 -1
  17. package/dist/cjs/token.cjs.map +1 -1
  18. package/dist/cjs/viem/index.cjs +1 -1
  19. package/dist/cjs/viem/index.cjs.map +1 -1
  20. package/dist/esm/{base-signer-Ds8CoYy0.d.ts → base-signer-BvL-jMNO.d.ts} +15 -2
  21. package/dist/esm/base-signer-YpkEmlp2.js +2 -0
  22. package/dist/esm/base-signer-YpkEmlp2.js.map +1 -0
  23. package/dist/esm/chains/index.d.ts +1 -1
  24. package/dist/esm/cleartext/index.d.ts +2 -2
  25. package/dist/esm/cleartext/index.js +1 -1
  26. package/dist/esm/{cleartext-_RCZVPOe.d.ts → cleartext-CxlICeUh.d.ts} +2 -2
  27. package/dist/esm/{cleartext-DfX0GUj1.js → cleartext-Qqh5JohW.js} +2 -2
  28. package/dist/esm/{cleartext-DfX0GUj1.js.map → cleartext-Qqh5JohW.js.map} +1 -1
  29. package/dist/esm/ethers/index.d.ts +53 -5
  30. package/dist/esm/ethers/index.js +1 -1
  31. package/dist/esm/ethers/index.js.map +1 -1
  32. package/dist/esm/fhevm-relayer-4Zd4QkKq.js +2 -0
  33. package/dist/esm/fhevm-relayer-4Zd4QkKq.js.map +1 -0
  34. package/dist/esm/{zama-sdk-BhD6nWLL.d.ts → index-DLaQtvYu.d.ts} +1253 -1780
  35. package/dist/esm/index-DNofJMCK.d.ts +61 -0
  36. package/dist/esm/{index-doNE2KoX.d.ts → index-S6_V7aAH.d.ts} +10 -1
  37. package/dist/esm/index.d.ts +8 -79
  38. package/dist/esm/index.js +1 -1
  39. package/dist/esm/index.js.map +1 -1
  40. package/dist/esm/node/index.d.ts +5 -5
  41. package/dist/esm/node/index.js +1 -1
  42. package/dist/esm/node/index.js.map +1 -1
  43. package/dist/esm/query/index.d.ts +522 -3
  44. package/dist/esm/query/index.js +1 -1
  45. package/dist/esm/query/index.js.map +1 -1
  46. package/dist/esm/relayer-BWHOLVcG.js +2 -0
  47. package/dist/esm/relayer-BWHOLVcG.js.map +1 -0
  48. package/dist/esm/sdk-events-D68bJ5jT.js +2 -0
  49. package/dist/esm/sdk-events-D68bJ5jT.js.map +1 -0
  50. package/dist/esm/token-Bn8I7xAu.js +2 -0
  51. package/dist/esm/token-Bn8I7xAu.js.map +1 -0
  52. package/dist/esm/{types-Tk8PiPCk.d.ts → types-BEz-VgR_.d.ts} +6 -3
  53. package/dist/esm/{types-CELdIAFG.d.ts → types-CWPSTRF6.d.ts} +98 -146
  54. package/dist/esm/{types-DlSUyFe2.d.ts → types-Dr7AmEs1.d.ts} +3 -3
  55. package/dist/esm/viem/index.d.ts +34 -5
  56. package/dist/esm/viem/index.js +1 -1
  57. package/dist/esm/viem/index.js.map +1 -1
  58. package/dist/esm/web/index.d.ts +2 -2
  59. package/dist/esm/web/index.js +1 -1
  60. package/package.json +3 -3
  61. package/dist/cjs/wrappers-registry.cjs +0 -2
  62. package/dist/cjs/wrappers-registry.cjs.map +0 -1
  63. package/dist/esm/base-signer-9CqICeQ8.js +0 -2
  64. package/dist/esm/base-signer-9CqICeQ8.js.map +0 -1
  65. package/dist/esm/fhevm-relayer-Bb_-KFJA.js +0 -2
  66. package/dist/esm/fhevm-relayer-Bb_-KFJA.js.map +0 -1
  67. package/dist/esm/index-9Cn2VKDw.d.ts +0 -329
  68. package/dist/esm/relayer-DLlyoabr.js +0 -2
  69. package/dist/esm/relayer-DLlyoabr.js.map +0 -1
  70. package/dist/esm/token-BBGMtloT.js +0 -2
  71. package/dist/esm/token-BBGMtloT.js.map +0 -1
  72. package/dist/esm/wrappers-registry-B1GuTt5t.js +0 -2
  73. package/dist/esm/wrappers-registry-B1GuTt5t.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"token.cjs","names":["ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","SigningRejectedError","SigningFailedError","ConfigurationError","SignerNotConfiguredError","WalletAccountNotReadyError","swallow","ZamaError","requireConfigured","nameContract","symbolContract","decimalsContract","supportsInterfaceContract","ERC7984_INTERFACE_ID","ERC7984_WRAPPER_INTERFACE_ID","ZamaError","toError","#requireSigner","swallow","confidentialTransferContract","confidentialTransferFromContract","confidentialTransferAndCallContract","confidentialTransferFromAndCallContract","setOperatorContract","isOperatorContract","confidentialBalanceOfContract","submitSdkTransaction","ConfigurationError"],"sources":["../../src/errors/encryption.ts","../../src/errors/transaction.ts","../../src/errors/rpc.ts","../../src/errors/chain.ts","../../src/errors/balance.ts","../../src/errors/fatal-batch.ts","../../src/utils/alignment.ts","../../src/utils/assertions.ts","../../src/events/sdk-events.ts","../../src/utils/concurrency.ts","../../src/utils/fhe-type.ts","../../src/utils/handles.ts","../../src/utils/submit-transaction.ts","../../src/token/token.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** FHE encryption failed. */\nexport class EncryptionFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.EncryptionFailed, message, options);\n this.name = \"EncryptionFailedError\";\n }\n}\n\n/** FHE decryption failed. */\nexport class DecryptionFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DecryptionFailed, message, options);\n this.name = \"DecryptionFailedError\";\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** On-chain transaction reverted. */\nexport class TransactionRevertedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.TransactionReverted, message, options);\n this.name = \"TransactionRevertedError\";\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * The consumer's RPC provider rate-limited an on-chain read the SDK performs\n * during decryption (e.g. the ACL check) — HTTP 429 or JSON-RPC `-32005`. An\n * RPC-endpoint problem, **not** a decryption/entitlement failure, and safe to\n * **retry**. Kept distinct from the relayer's own back-pressure\n * ({@link RelayerRequestFailedError}).\n *\n * Backoff for chain RPC is owned by the consumer's transport: viem/ethers\n * already honor the `Retry-After` header and retry internally before this error\n * surfaces, so it is configured on the transport you pass via `chain.network`\n * (not re-implemented here).\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof RpcRateLimitError) {\n * // back off and retry; consider a higher-throughput RPC endpoint\n * }\n * }\n * ```\n */\nexport class RpcRateLimitError extends ZamaError {\n /**\n * Suggested delay before retrying, in **seconds**, when a numeric `retryAfter`\n * is present on the error. Usually `undefined` for chain RPC: the `Retry-After`\n * header is consumed by the consumer's viem/ethers transport (which owns the\n * backoff), not surfaced here — see the class doc.\n */\n readonly retryAfter: number | undefined;\n\n constructor(message: string, options?: ErrorOptions & { retryAfter?: number }) {\n const { retryAfter, ...errorOptions } = options ?? {};\n super(ZamaErrorCode.RpcRateLimited, message, errorOptions);\n this.name = \"RpcRateLimitError\";\n this.retryAfter = retryAfter;\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * Thrown when the signer and provider are connected to different chains at the\n * start of a write operation.\n *\n * Every write method runs a chain-alignment pre-flight check. If\n * `signer.getChainId()` and `provider.getChainId()` return different values,\n * this error is thrown before any RPC mutation is attempted.\n *\n * @example\n * ```ts\n * try {\n * await token.shield(1000n);\n * } catch (e) {\n * if (e instanceof ChainMismatchError) {\n * console.error(\n * `Signer is on chain ${e.signerChainId} but provider is on chain ${e.providerChainId}`,\n * );\n * }\n * }\n * ```\n */\nexport class ChainMismatchError extends ZamaError {\n readonly operation: string;\n readonly signerChainId: number;\n readonly providerChainId: number;\n\n constructor(\n {\n operation,\n signerChainId,\n providerChainId,\n }: { operation: string; signerChainId: number; providerChainId: number },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.ChainMismatch,\n `Operation \"${operation}\" requires signer and provider to be on the same chain, ` +\n `but signer is on chain ${signerChainId} and provider is on chain ${providerChainId}.`,\n options,\n );\n this.name = \"ChainMismatchError\";\n this.operation = operation;\n this.signerChainId = signerChainId;\n this.providerChainId = providerChainId;\n }\n}\n","import type { Address } from \"viem\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Structured details shared by balance-related errors. */\nexport interface BalanceErrorDetails {\n readonly requested: bigint;\n readonly available: bigint;\n readonly token: Address;\n}\n\n/** Confidential (cToken) balance is insufficient for the requested operation. */\nexport class InsufficientConfidentialBalanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The available balance at the time of the check. */\n readonly available: bigint;\n /** The token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientConfidentialBalance, message, options);\n this.name = \"InsufficientConfidentialBalanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** ERC-20 balance is insufficient for the requested shield amount. */\nexport class InsufficientERC20BalanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The available balance at the time of the check. */\n readonly available: bigint;\n /** The ERC-20 token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientERC20Balance, message, options);\n this.name = \"InsufficientERC20BalanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** ERC-20 allowance granted to the wrapper is insufficient for the requested wrap amount. */\nexport class InsufficientAllowanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The allowance available at the time of the check. */\n readonly available: bigint;\n /** The underlying ERC-20 token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientAllowance, message, options);\n this.name = \"InsufficientAllowanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** Balance validation could not be performed (no cached credentials and decryption not possible). */\nexport class BalanceCheckUnavailableError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.BalanceCheckUnavailable, message, options);\n this.name = \"BalanceCheckUnavailableError\";\n }\n}\n\n/** A public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\nexport class ERC20ReadFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.ERC20ReadFailed, message, options);\n this.name = \"ERC20ReadFailedError\";\n }\n}\n","import { ConfigurationError } from \"./relayer\";\nimport { RpcRateLimitError } from \"./rpc\";\nimport { SigningRejectedError, SigningFailedError } from \"./signing\";\n\n/**\n * Returns `true` for errors that should abort an entire batch operation\n * rather than be recorded per-item — wallet signature rejected, signing\n * infrastructure broken, SDK misconfigured, or the RPC provider throttling.\n * These are systemic failures that won't recover within the same call; for a\n * rate-limit in particular, the per-item retry loop would only amplify the\n * throttle by re-hitting the already-rate-limited endpoint.\n *\n * Callers iterating over a batch (e.g. per-token decrypt) should rethrow when\n * this predicate is true so the whole batch aborts, and record the error\n * per-item otherwise.\n */\nexport function isFatalBatchError(error: unknown): boolean {\n return (\n error instanceof SigningRejectedError ||\n error instanceof SigningFailedError ||\n error instanceof ConfigurationError ||\n error instanceof RpcRateLimitError\n );\n}\n","import {\n ChainMismatchError,\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n} from \"../errors\";\nimport type { GenericProvider, GenericSigner, WalletAccount } from \"../types\";\n\n/**\n * Pre-flight guard for signer-required operations. Resolves the connected\n * wallet account (refreshing once if the signer reports it isn't ready) and\n * verifies the signer's chain matches the provider's.\n *\n * @internal\n */\nexport async function requireAlignedWalletAccount(\n operation: string,\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n): Promise<WalletAccount> {\n if (!signer) {\n throw new SignerNotConfiguredError(operation);\n }\n let account: WalletAccount;\n try {\n account = signer.requireWalletAccount(operation);\n } catch (error) {\n if (!(error instanceof WalletAccountNotReadyError) || !signer.refreshWalletAccount) {\n throw error;\n }\n await signer.refreshWalletAccount();\n account = signer.requireWalletAccount(operation);\n }\n const providerChainId = await provider.getChainId();\n if (account.chainId !== providerChainId) {\n throw new ChainMismatchError({ operation, signerChainId: account.chainId, providerChainId });\n }\n return account;\n}\n\n/**\n * Variant of {@link requireAlignedWalletAccount} that returns only the aligned\n * chain ID. Useful when a write path only needs to ensure signer/provider\n * coherence and doesn't otherwise consume the account.\n *\n * @internal\n */\nexport async function requireChainAlignment(\n operation: string,\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n): Promise<number> {\n return (await requireAlignedWalletAccount(operation, signer, provider)).chainId;\n}\n","export function assertNonNullable<T>(value: T, context: string): asserts value is NonNullable<T> {\n if (value === null || value === undefined) {\n throw new TypeError(`${context} must not be null or undefined`);\n }\n}\n\nexport function assertObject(\n value: unknown,\n context: string,\n): asserts value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${context} must be an object, got ${typeof value}`);\n }\n}\n\nexport function assertString(value: unknown, context: string): asserts value is string {\n if (typeof value !== \"string\") {\n throw new TypeError(`${context} must be a string, got ${typeof value}`);\n }\n}\n\nexport function assertArray(value: unknown, context: string): asserts value is unknown[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} must be an array, got ${typeof value}`);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport function assertFunction(value: unknown, context: string): asserts value is Function {\n if (typeof value !== \"function\") {\n throw new TypeError(`${context} must be a function, got ${typeof value}`);\n }\n}\n\nexport function assertBigint(value: unknown, context: string): asserts value is bigint {\n if (typeof value !== \"bigint\") {\n throw new TypeError(`${context} must be a bigint, got ${typeof value}`);\n }\n}\n\n/** Assert that `obj[key]` is a string. Narrows `obj` to include `{ [key]: string }`. */\nexport function assertStringProp<\n K extends string,\n O extends Record<string, unknown> = Record<string, unknown>,\n>(obj: O, key: K, context: string): asserts obj is O & Record<K, string> {\n assertString(obj[key], context);\n}\n\n/** Assert that `obj[key]` is a function. Narrows `obj` to include `{ [key]: F }`. */\nexport function assertFunctionProp<\n K extends string,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n F extends Function,\n O extends Record<string, unknown> = Record<string, unknown>,\n>(obj: O, key: K, context: string): asserts obj is O & Record<K, F> {\n assertFunction(obj[key], context);\n}\n\nexport function assertCondition(condition: boolean, message: string): asserts condition {\n if (!condition) {\n throw new TypeError(message);\n }\n}\n","import type { Address, Hex } from \"viem\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/types\";\nimport type { ShieldPath } from \"../types/token\";\n\n/**\n * All SDK event keys, accessible as `ZamaSDKEvents.EncryptStart` etc.\n */\nexport const ZamaSDKEvents = {\n // FHE operations\n EncryptStart: \"encrypt:start\",\n EncryptEnd: \"encrypt:end\",\n EncryptError: \"encrypt:error\",\n DecryptStart: \"decrypt:start\",\n DecryptEnd: \"decrypt:end\",\n DecryptError: \"decrypt:error\",\n // Write operations\n TransactionError: \"transaction:error\",\n ShieldSubmitted: \"shield:submitted\",\n TransferSubmitted: \"transfer:submitted\",\n TransferFromSubmitted: \"transferFrom:submitted\",\n SetOperatorSubmitted: \"setOperator:submitted\",\n ApproveUnderlyingSubmitted: \"approveUnderlying:submitted\",\n WrapSubmitted: \"wrap:submitted\",\n UnwrapSubmitted: \"unwrap:submitted\",\n FinalizeUnwrapSubmitted: \"finalizeUnwrap:submitted\",\n // Delegation operations\n DelegationSubmitted: \"delegation:submitted\",\n RevokeDelegationSubmitted: \"revokeDelegation:submitted\",\n // Unshield orchestration\n UnshieldPhase1Submitted: \"unshield:phase1_submitted\",\n UnshieldPhase2Started: \"unshield:phase2_started\",\n UnshieldPhase2Submitted: \"unshield:phase2_submitted\",\n} as const;\n\n/** Union of all SDK event type strings. */\nexport type ZamaSDKEventType = (typeof ZamaSDKEvents)[keyof typeof ZamaSDKEvents];\n\n// -- Base fields present on every event --\n\nexport interface BaseEvent {\n tokenAddress?: Address;\n timestamp: number;\n /** Shared identifier linking related events in multi-phase operations (e.g. unshield). */\n operationId?: string;\n}\n\n// -- Per-event typed payloads --\n\nexport interface EncryptStartEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.EncryptStart;\n}\n\nexport interface EncryptEndEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.EncryptEnd;\n durationMs: number;\n}\n\nexport interface EncryptErrorEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.EncryptError;\n /** The error that caused the encryption to fail. */\n error: Error;\n durationMs: number;\n}\n\nexport interface DecryptStartEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.DecryptStart;\n /** Encrypted values being decrypted — correlate with matching DecryptEnd/DecryptError. */\n encryptedValues: EncryptedValue[];\n}\n\nexport interface DecryptEndEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.DecryptEnd;\n durationMs: number;\n /** Encrypted values that were decrypted. */\n encryptedValues: EncryptedValue[];\n /** Decrypted values keyed by encrypted value — use this to correlate events to specific entries. */\n result: Record<EncryptedValue, ClearValue>;\n}\n\nexport interface DecryptErrorEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.DecryptError;\n /** The error that caused the decryption to fail. */\n error: Error;\n durationMs: number;\n /** Encrypted values that were being decrypted when the error occurred. */\n encryptedValues: EncryptedValue[];\n}\n\nexport interface TransactionErrorEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.TransactionError;\n /** Which SDK operation failed. */\n operation: TransactionOperation;\n /** The error that caused the transaction to fail. */\n error: Error;\n}\n\nexport interface ShieldSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.ShieldSubmitted;\n txHash: Hex;\n /** Which execution path was used: single-tx `transferAndCall` or two-tx `approveAndWrap`. */\n shieldPath: ShieldPath;\n}\n\nexport interface TransferSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.TransferSubmitted;\n txHash: Hex;\n}\n\nexport interface TransferFromSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.TransferFromSubmitted;\n txHash: Hex;\n}\n\nexport interface SetOperatorSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.SetOperatorSubmitted;\n txHash: Hex;\n}\n\nexport interface ApproveUnderlyingSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.ApproveUnderlyingSubmitted;\n txHash: Hex;\n /** Which approval transaction was submitted. */\n step: \"reset\" | \"approve\";\n}\n\n/**\n * Emitted by the standalone `wrap()` escape hatch (not by `shield()`, which\n * emits {@link ShieldSubmittedEvent}). Distinct so a caller-initiated `wrap`\n * isn't conflated with `shield()`'s internal `approveAndWrap` leg — mirroring\n * how `unwrap` emits its own event rather than reusing the unshield phases.\n */\nexport interface WrapSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.WrapSubmitted;\n txHash: Hex;\n}\n\nexport interface UnwrapSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.UnwrapSubmitted;\n txHash: Hex;\n}\n\nexport interface FinalizeUnwrapSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.FinalizeUnwrapSubmitted;\n txHash: Hex;\n}\n\nexport interface DelegationSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.DelegationSubmitted;\n txHash: Hex;\n}\n\nexport interface RevokeDelegationSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.RevokeDelegationSubmitted;\n txHash: Hex;\n}\n\nexport interface UnshieldPhase1SubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.UnshieldPhase1Submitted;\n txHash: Hex;\n}\n\nexport interface UnshieldPhase2StartedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.UnshieldPhase2Started;\n}\n\nexport interface UnshieldPhase2SubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.UnshieldPhase2Submitted;\n txHash: Hex;\n}\n\n/**\n * Discriminated union of all SDK events.\n *\n * Decrypt events carry encrypted values and decrypted clear-text values so event\n * subscribers can correlate and bind them in UI layers. Events never carry\n * private keys, permit signatures, or ZK proofs.\n */\nexport type ZamaSDKEvent =\n | EncryptStartEvent\n | EncryptEndEvent\n | EncryptErrorEvent\n | DecryptStartEvent\n | DecryptEndEvent\n | DecryptErrorEvent\n | TransactionErrorEvent\n | ShieldSubmittedEvent\n | TransferSubmittedEvent\n | TransferFromSubmittedEvent\n | SetOperatorSubmittedEvent\n | ApproveUnderlyingSubmittedEvent\n | WrapSubmittedEvent\n | UnwrapSubmittedEvent\n | FinalizeUnwrapSubmittedEvent\n | DelegationSubmittedEvent\n | RevokeDelegationSubmittedEvent\n | UnshieldPhase1SubmittedEvent\n | UnshieldPhase2StartedEvent\n | UnshieldPhase2SubmittedEvent;\n\nexport type ZamaSDKEventListener = (event: ZamaSDKEvent) => void;\n\n/** Distributive Omit that preserves the discriminated union. */\nexport type ZamaSDKEventInput = ZamaSDKEvent extends infer E\n ? E extends ZamaSDKEvent\n ? Omit<E, \"timestamp\" | \"tokenAddress\">\n : never\n : never;\n\n/**\n * Single source of truth for each transaction operation's submitted-event payload.\n *\n * Adding a write op = adding one entry here. `TransactionOperation` is then\n * `keyof typeof transactionOperationMetadata`, so the dispatch table and the\n * operation union cannot drift.\n *\n * The `satisfies` check enforces that every entry produces a valid\n * {@link ZamaSDKEventInput}.\n */\nexport const transactionOperationMetadata = {\n approveUnderlying: {\n submittedEvent: (txHash: Hex) => ({\n type: ZamaSDKEvents.ApproveUnderlyingSubmitted,\n txHash,\n step: \"approve\" as const,\n }),\n },\n \"approveUnderlying:reset\": {\n submittedEvent: (txHash: Hex) => ({\n type: ZamaSDKEvents.ApproveUnderlyingSubmitted,\n txHash,\n step: \"reset\" as const,\n }),\n },\n delegateDecryption: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.DelegationSubmitted, txHash }),\n },\n finalizeUnwrap: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.FinalizeUnwrapSubmitted, txHash }),\n },\n revokeDelegation: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.RevokeDelegationSubmitted, txHash }),\n },\n setOperator: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.SetOperatorSubmitted, txHash }),\n },\n \"shield:transferAndCall\": {\n submittedEvent: (txHash: Hex) => ({\n type: ZamaSDKEvents.ShieldSubmitted,\n txHash,\n shieldPath: \"transferAndCall\" as const,\n }),\n },\n \"shield:approveAndWrap\": {\n submittedEvent: (txHash: Hex) => ({\n type: ZamaSDKEvents.ShieldSubmitted,\n txHash,\n shieldPath: \"approveAndWrap\" as const,\n }),\n },\n wrap: { submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.WrapSubmitted, txHash }) },\n transfer: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.TransferSubmitted, txHash }),\n },\n transferAndCall: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.TransferSubmitted, txHash }),\n },\n transferFrom: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.TransferFromSubmitted, txHash }),\n },\n transferFromAndCall: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.TransferFromSubmitted, txHash }),\n },\n unwrap: { submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.UnwrapSubmitted, txHash }) },\n unwrapAll: { submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.UnwrapSubmitted, txHash }) },\n} satisfies Record<string, { submittedEvent: (txHash: Hex) => ZamaSDKEventInput }>;\n\n/**\n * SDK transaction operations that emit submitted/error lifecycle events.\n *\n * Operation strings encode the execution-path discriminator for flows that have\n * one (`shield:transferAndCall` vs. `shield:approveAndWrap`), routing both error\n * and success events on a single field — see {@link transactionOperationMetadata}.\n */\nexport type TransactionOperation = keyof typeof transactionOperationMetadata;\n","/**\n * Execute an array of async thunks with bounded concurrency.\n * Defaults to `Infinity` (equivalent to `Promise.all`).\n */\nexport async function pLimit<T>(\n fns: (() => Promise<T>)[],\n maxConcurrency = Infinity,\n): Promise<T[]> {\n if (Number.isFinite(maxConcurrency) && maxConcurrency <= 0) {\n throw new Error(\"maxConcurrency must be a positive number\");\n }\n if (!Number.isFinite(maxConcurrency) || maxConcurrency >= fns.length) {\n return Promise.all(fns.map((f) => f()));\n }\n\n const results: T[] = Array.from({ length: fns.length });\n let index = 0;\n\n async function worker() {\n while (index < fns.length) {\n const i = index++;\n if (fns[i]) {\n results[i] = await fns[i]();\n }\n }\n }\n\n await Promise.all(Array.from({ length: maxConcurrency }, worker));\n return results;\n}\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import type { EncryptedValue } from \"../relayer/types\";\nimport { encryptionBitsFromFheTypeId, isFheTypeId } from \"./fhe-type\";\n\nexport const ZERO_ENCRYPTED_VALUE =\n \"0x0000000000000000000000000000000000000000000000000000000000000000\" as const;\n\n/**\n * Check whether an encrypted value represents the zero value.\n */\nexport function isEncryptedValueZero(encryptedValue: string): boolean {\n return encryptedValue === ZERO_ENCRYPTED_VALUE || encryptedValue === \"0x\";\n}\n\n/**\n * Per-request cleartext-bit budget enforced by the KMS gateway, mirrored from\n * `@fhevm/sdk`'s `MAX_KMS_DECRYPT_DECRYPTION_BIT_LIMIT` (protocol-level constant,\n * not imported — see {@link MAX_CONTRACTS_PER_PERMIT} for why). Internal: decrypt\n * requests are chunked to respect it automatically, so callers never need this value.\n */\nexport const MAX_DECRYPTION_REQUEST_BITS = 2048;\n\n/** Max encryption bit width among all currently-known FHE types (euint256). */\nconst MAX_KNOWN_ENCRYPTION_BITS = 256;\n\n/**\n * Cleartext bit cost of decrypting a single handle, derived from its FHE\n * type (encoded at bits 8-15 of the handle — the same layout `@fhevm/sdk`'s\n * `FhevmHandle` decodes, byte 30 of the 32-byte handle).\n *\n * Falls back to {@link MAX_KNOWN_ENCRYPTION_BITS} for an unrecognized type\n * byte, or for a value that isn't parseable hex at all, instead of throwing.\n * A real on-chain handle is always well-formed with a valid type byte, so\n * this fallback only ever fires for synthetic test/placeholder handles —\n * deliberately more permissive than the relayer's own strict validation so\n * chunking stays safe without requiring every test fixture to encode a real\n * FHE handle. Do not tighten this to match relayer semantics.\n */\nexport function encryptionBitsForHandle(encryptedValue: EncryptedValue): number {\n let handleValue: bigint;\n try {\n handleValue = BigInt(encryptedValue);\n } catch {\n return MAX_KNOWN_ENCRYPTION_BITS;\n }\n const typeByte = Number((handleValue >> 8n) & 0xffn);\n return isFheTypeId(typeByte) ? encryptionBitsFromFheTypeId(typeByte) : MAX_KNOWN_ENCRYPTION_BITS;\n}\n\n/**\n * Split `handles` into groups whose cumulative cleartext-bit cost never\n * exceeds `maxBits`, preserving input order. Unlike {@link chunkContracts}\n * (fixed-size slices), a greedy accumulate-until-exceeded walk is required\n * since per-handle cost varies by FHE type. A handle whose own cost exceeds\n * `maxBits` still gets a solo chunk — always makes forward progress.\n */\nexport function chunkHandlesByBitBudget(\n handles: readonly EncryptedValue[],\n maxBits: number = MAX_DECRYPTION_REQUEST_BITS,\n): EncryptedValue[][] {\n const chunks: EncryptedValue[][] = [];\n let current: EncryptedValue[] = [];\n let currentBits = 0;\n\n for (const handle of handles) {\n const bits = encryptionBitsForHandle(handle);\n if (current.length > 0 && currentBits + bits > maxBits) {\n chunks.push(current);\n current = [];\n currentBits = 0;\n }\n current.push(handle);\n currentBits += bits;\n }\n if (current.length > 0) {\n chunks.push(current);\n }\n return chunks;\n}\n","import type { Hex } from \"viem\";\nimport { TransactionRevertedError, ZamaError } from \"../errors\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { transactionOperationMetadata, ZamaSDKEvents } from \"../events/sdk-events\";\nimport type {\n GenericLogger,\n GenericProvider,\n GenericSigner,\n TransactionResult,\n WriteContractConfig,\n} from \"../types\";\nimport { swallow } from \"./swallow\";\n\n/**\n * Shared write-transaction pipeline for SDK calls that submit a transaction.\n *\n * On success: writes the tx, emits the per-operation submitted event from\n * {@link transactionOperationMetadata}, fires `onSubmitted`, waits for the\n * receipt, and returns `{ txHash, receipt }`.\n *\n * On failure: emits a {@link ZamaSDKEvents.TransactionError} event with the\n * transaction-level error it will throw, then throws it. Existing `ZamaError`\n * instances are rethrown as-is; all other failures are wrapped in\n * `TransactionRevertedError` with the original error as `cause`.\n */\nexport async function submitTransaction(params: {\n operation: TransactionOperation;\n signer: GenericSigner;\n provider: GenericProvider;\n config: WriteContractConfig;\n emit: (input: ZamaSDKEventInput) => void;\n onSubmitted?: (txHash: Hex) => void;\n logger: GenericLogger;\n}): Promise<TransactionResult> {\n const { operation, signer, provider, config, emit, onSubmitted, logger } = params;\n const metadata = transactionOperationMetadata[operation];\n\n try {\n const txHash = await signer.writeContract(config);\n emit(metadata.submittedEvent(txHash));\n void swallow(`${operation}: onSubmitted`, () => onSubmitted?.(txHash), logger);\n const receipt = await provider.waitForTransactionReceipt(txHash);\n return { txHash, receipt };\n } catch (error) {\n const failure =\n error instanceof ZamaError\n ? error\n : new TransactionRevertedError(`Transaction failed during ${operation}`, { cause: error });\n\n emit({ type: ZamaSDKEvents.TransactionError, operation, error: failure });\n throw failure;\n }\n}\n","import { type Address, getAddress, type Hex } from \"viem\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferAndCallContract,\n confidentialTransferContract,\n confidentialTransferFromAndCallContract,\n confidentialTransferFromContract,\n decimalsContract,\n ERC7984_INTERFACE_ID,\n ERC7984_WRAPPER_INTERFACE_ID,\n isOperatorContract,\n nameContract,\n setOperatorContract,\n supportsInterfaceContract,\n symbolContract,\n} from \"../contracts\";\nimport {\n BalanceCheckUnavailableError,\n ConfigurationError,\n DecryptionFailedError,\n EncryptionFailedError,\n InsufficientConfidentialBalanceError,\n isFatalBatchError,\n requireConfigured,\n ZamaError,\n} from \"../errors\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { toError } from \"../utils\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\nimport { assertBigint } from \"../utils/assertions\";\nimport { pLimit } from \"../utils/concurrency\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport { submitTransaction as submitSdkTransaction } from \"../utils/submit-transaction\";\nimport { swallow } from \"../utils/swallow\";\nimport type {\n GenericSigner,\n TransactionResult,\n TransferCallbacks,\n TransferOptions,\n WriteContractConfig,\n} from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\n\n/** Options for {@link Token.batchDecryptBalancesAs}. */\nexport interface BatchDecryptAsOptions {\n /** The address of the account that delegated decryption rights. */\n delegatorAddress: Address;\n /** Pre-fetched encrypted values. When omitted, they are fetched from the chain. */\n encryptedValues?: EncryptedValue[];\n /**\n * The account whose on-chain balance to read. Defaults to the delegator\n * address, which is the common case (the delegator grants permission to\n * decrypt their own balance). Only set this when the account differs\n * from the delegator.\n *\n * Matches the `account` parameter of `confidentialBalanceOf(account)` on-chain.\n */\n accountAddress?: Address;\n /** Maximum number of concurrent decrypt calls. Default: 10. */\n maxConcurrency?: number;\n /** Called when decryption fails for a single token. Return a fallback bigint. */\n onError?: (error: Error, address: Address) => bigint;\n}\n\n/** Result of {@link Token.batchBalancesOf}. */\nexport interface BatchBalancesResult {\n /** Successfully decrypted balances, keyed by token address. */\n results: Map<Address, bigint>;\n /** Per-token errors for tokens that failed to decrypt. */\n errors: Map<Address, ZamaError>;\n}\n\n/**\n * High-level interface for an ERC-7984 confidential token.\n * Hides FHE complexity (encryption, decryption, EIP-712 signing) behind\n * familiar ERC-20-like methods.\n *\n * For ERC-7984 wrappers (shield/unshield), use {@link WrappedToken} instead —\n * it extends `Token` with wrapper-specific operations.\n *\n * Decryption, credentials, caching, and event emission are handled by the\n * owning {@link ZamaSDK} — this class only exposes token-scoped helpers\n * that delegate to `sdk.decryption.decryptValues` and `sdk.permits.grantPermit`.\n */\nexport class Token {\n readonly sdk: ZamaSDK;\n readonly address: Address;\n\n constructor(sdk: ZamaSDK, address: Address) {\n this.sdk = sdk;\n this.address = getAddress(address);\n }\n\n /** Resolve `sdk.signer` or throw {@link SignerNotConfiguredError} tagged with `operation`. */\n #requireSigner(operation: string): GenericSigner {\n return requireConfigured(this.sdk.signer, operation);\n }\n\n // METADATA\n\n /** Read the token name from the contract. */\n async name(): Promise<string> {\n return this.sdk.provider.readContract(nameContract(this.address));\n }\n\n /** Read the token symbol from the contract. */\n async symbol(): Promise<string> {\n return this.sdk.provider.readContract(symbolContract(this.address));\n }\n\n /** Read the token decimals from the contract. */\n async decimals(): Promise<number> {\n return this.sdk.provider.readContract(decimalsContract(this.address));\n }\n\n // ERC-165 DISCOVERY\n\n /**\n * ERC-165 check for {@link ERC7984_INTERFACE_ID} support.\n *\n * @returns `true` if the contract implements the ERC-7984 confidential token interface.\n */\n async isConfidential(): Promise<boolean> {\n return this.sdk.provider.readContract(\n supportsInterfaceContract(this.address, ERC7984_INTERFACE_ID),\n );\n }\n\n /**\n * ERC-165 check for IERC7984ERC20Wrapper support.\n *\n * @returns `true` if the contract implements the ERC-7984 wrapper interface\n * ({@link ERC7984_WRAPPER_INTERFACE_ID}, `0x1f1c62b2`).\n */\n async isWrapper(): Promise<boolean> {\n return this.sdk.provider.readContract(\n supportsInterfaceContract(this.address, ERC7984_WRAPPER_INTERFACE_ID),\n );\n }\n\n // BALANCES\n\n /**\n * Decrypt and return the plaintext balance for the given owner.\n * Acquires FHE credentials via a wallet signature if none are cached.\n *\n * @param owner - Balance owner address.\n * @returns The decrypted plaintext balance as a bigint.\n * @throws if FHE decryption fails. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balance = await token.balanceOf(\"0xOwner\");\n * ```\n */\n async balanceOf(owner: Address): Promise<bigint> {\n const ownerAddress = getAddress(owner);\n const encryptedValue = await this.readConfidentialBalanceOf(ownerAddress);\n const result = await this.sdk.decryption.decryptValues([\n { encryptedValue, contractAddress: this.address },\n ]);\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(`Decryption returned no value for ${encryptedValue}`);\n }\n assertBigint(value, \"balanceOf: result[encryptedValue]\");\n return value;\n }\n\n /**\n * Return the raw encrypted balance without decrypting.\n *\n * @param owner - Balance owner address.\n * @returns The encrypted balance as a hex string.\n *\n * @example\n * ```ts\n * const encryptedValue = await token.confidentialBalanceOf(\"0xOwner\");\n * ```\n */\n async confidentialBalanceOf(owner: Address): Promise<EncryptedValue> {\n return this.readConfidentialBalanceOf(getAddress(owner));\n }\n\n /**\n * Decrypt the balance of a delegator using delegated decryption credentials.\n * The connected signer acts as the delegatee who has been granted permission\n * by the delegator to decrypt their balance.\n *\n * Clear values are cached in storage keyed by `(account, token, encryptedValue)`.\n * Because every on-chain balance change produces a new encrypted value,\n * stale cache entries are never served. Cache write failures are silently\n * ignored — they do not affect the returned value.\n *\n * @param delegatorAddress - The address of the account that delegated decryption rights.\n * @param accountAddress - The account whose on-chain balance to read. Defaults\n * to the delegator address.\n * @returns The decrypted plaintext balance as a bigint.\n * @throws if no active delegation exists. {@link DelegationNotFoundError}\n * @throws if the delegation has expired. {@link DelegationExpiredError}\n * @throws if delegated decryption fails. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balance = await token.decryptBalanceAs({\n * delegatorAddress: \"0xDelegator\",\n * });\n * ```\n */\n async decryptBalanceAs({\n delegatorAddress,\n accountAddress,\n }: {\n delegatorAddress: Address;\n accountAddress?: Address;\n }): Promise<bigint> {\n await requireChainAlignment(\"decryptBalanceAs\", this.sdk.signer, this.sdk.provider);\n const normalizedDelegator = getAddress(delegatorAddress);\n const normalizedAccount = accountAddress ? getAddress(accountAddress) : normalizedDelegator;\n\n const encryptedValue = await this.readConfidentialBalanceOf(normalizedAccount);\n if (isEncryptedValueZero(encryptedValue)) {\n return 0n;\n }\n\n const result = await this.sdk.decryption.delegatedDecryptValues(\n [{ encryptedValue, contractAddress: this.address }],\n normalizedDelegator,\n normalizedAccount,\n );\n\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(\n `Delegated decryption returned no value for ${encryptedValue}`,\n );\n }\n assertBigint(value, \"decryptBalanceAs: result[encryptedValue]\");\n return value;\n }\n\n // BATCH STATICS\n\n /**\n * Decrypt confidential balances for multiple tokens in parallel, returning\n * successes and per-token errors separately. Pre-authorizes all token\n * addresses in a single wallet signature, then delegates each decrypt to\n * `sdk.decryption.decryptValues`.\n *\n * Tokens that fail to decrypt land in `errors` rather than aborting the\n * whole batch — caller decides how to surface them.\n *\n * @param tokens - Array of {@link Token} instances bound to the same SDK.\n * @param owner - Balance owner address.\n * @returns `{ results, errors }` partitioning the per-token outcomes.\n *\n * @example\n * ```ts\n * const { results, errors } = await Token.batchBalancesOf(tokens, owner);\n * ```\n */\n static async batchBalancesOf(tokens: Token[], owner: Address): Promise<BatchBalancesResult> {\n const results = new Map<Address, bigint>();\n const errors = new Map<Address, ZamaError>();\n if (tokens.length === 0) {\n return { results, errors };\n }\n\n const sdk = Token.assertSameSdk(tokens);\n // Fail fast on chain mismatch before prompting the wallet for a signature.\n await requireChainAlignment(\"batchBalancesOf\", sdk.signer, sdk.provider);\n // Pre-authorize the full token set in one wallet signature so subsequent\n // per-token decryptValues calls reuse the cached credentials.\n await sdk.permits.grantPermit(tokens.map((t) => t.address));\n\n const outcomes = await pLimit(\n tokens.map((t) => async () => {\n try {\n return { status: \"fulfilled\" as const, value: await t.balanceOf(owner) };\n } catch (reason) {\n return { status: \"rejected\" as const, reason };\n }\n }),\n 5,\n );\n\n for (let i = 0; i < tokens.length; i++) {\n const tokenAddress = tokens[i]!.address;\n const outcome = outcomes[i]!;\n if (outcome.status === \"fulfilled\") {\n results.set(tokenAddress, outcome.value);\n } else {\n const reason = outcome.reason;\n // Session-level failures (user rejected signature, SDK misconfigured)\n // apply to every token — surface them instead of collecting per-token.\n if (isFatalBatchError(reason)) {\n throw reason;\n }\n const error =\n reason instanceof ZamaError\n ? reason\n : new DecryptionFailedError(toError(reason).message, { cause: reason });\n errors.set(tokenAddress, error);\n }\n }\n\n // Total failure: surface the first error so callers know nothing decrypted.\n if (errors.size === tokens.length) {\n const firstError = errors.values().next().value;\n throw firstError ?? new DecryptionFailedError(\"All token balance decryptions failed\");\n }\n\n return { results, errors };\n }\n\n /**\n * Batch decrypt confidential balances as a delegate across multiple tokens.\n * Mirrors {@link batchBalancesOf} but uses delegated credentials.\n *\n * **Error handling:** If a per-token decryption fails and no `onError` callback\n * is provided, errors are collected and thrown as an aggregated\n * `DecryptionFailedError`. When the relayer returns no value for an encrypted value,\n * a `DecryptionFailedError` is thrown for that token (never silently returns `0n`).\n * Pass `onError: () => 0n` to opt into the silent zero behavior.\n *\n * @param tokens - Array of Token instances to decrypt balances for.\n * @param options - Delegated decryption configuration.\n * @returns A Map from token address to decrypted balance.\n * @throws if no active delegation exists. {@link DelegationNotFoundError}\n * @throws if the delegation has expired. {@link DelegationExpiredError}\n * @throws if any decryption fails and no `onError` is provided. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balances = await Token.batchDecryptBalancesAs(tokens, {\n * delegatorAddress: \"0xDelegator\",\n * onError: (err, addr) => { console.error(addr, err); return 0n; },\n * });\n * ```\n */\n static async batchDecryptBalancesAs(\n tokens: Token[],\n options: BatchDecryptAsOptions,\n ): Promise<Map<Address, bigint>> {\n if (tokens.length === 0) {\n return new Map();\n }\n\n const sdk = Token.assertSameSdk(tokens);\n const results = new Map<Address, bigint>();\n const errors = new Map<Address, ZamaError>();\n const normalizedAccount = options.accountAddress\n ? getAddress(options.accountAddress)\n : getAddress(options.delegatorAddress);\n const maxConcurrency = options.maxConcurrency ?? 10;\n if (options.encryptedValues && tokens.length !== options.encryptedValues.length) {\n throw new DecryptionFailedError(\n `tokens.length (${tokens.length}) must equal encryptedValues.length (${options.encryptedValues.length})`,\n );\n }\n const resolvedEncryptedValues =\n options.encryptedValues ??\n (await Token.readBalanceHandlesBatch(tokens, normalizedAccount, errors, maxConcurrency));\n\n const decryptRequests: Array<{ token: Token; encryptedValue: EncryptedValue }> = [];\n for (const [index, token] of tokens.entries()) {\n const encryptedValue = resolvedEncryptedValues[index];\n if (!encryptedValue || errors.has(token.address)) {\n continue;\n }\n if (isEncryptedValueZero(encryptedValue)) {\n // Zero balance → skip the relayer; no decryption needed.\n results.set(token.address, 0n);\n } else {\n decryptRequests.push({ token, encryptedValue });\n }\n }\n\n if (decryptRequests.length > 0) {\n const decrypted = await sdk.decryption.delegatedBatchDecryptValues({\n encryptedInputs: decryptRequests.map(({ token, encryptedValue }) => ({\n encryptedValue,\n contractAddress: token.address,\n })),\n delegatorAddress: options.delegatorAddress,\n accountAddress: options.accountAddress,\n maxConcurrency,\n });\n\n for (const [index, item] of decrypted.items.entries()) {\n const request = decryptRequests[index];\n if (!request) {\n continue;\n }\n if (item.error) {\n errors.set(request.token.address, item.error);\n continue;\n }\n const value = item.value;\n if (value === undefined) {\n errors.set(\n request.token.address,\n new DecryptionFailedError(\n `Batch delegated decryption returned no value for ${item.encryptedValue} on token ${request.token.address}`,\n ),\n );\n continue;\n }\n assertBigint(value, \"batchDecryptBalancesAs: result[encryptedValue]\");\n results.set(request.token.address, value);\n }\n }\n\n if (errors.size === 0) {\n return results;\n }\n\n if (options.onError) {\n const callbackErrors: Array<{ address: Address; error: Error }> = [];\n for (const [address, error] of errors) {\n try {\n results.set(address, options.onError(error, address));\n } catch (callbackError) {\n callbackErrors.push({ address, error: toError(callbackError) });\n }\n }\n if (callbackErrors.length > 0) {\n const message = callbackErrors\n .map(({ address, error }) => `${address}: ${error.message}`)\n .join(\"; \");\n throw new DecryptionFailedError(\n `Batch delegated decryption onError callback failed for ${callbackErrors.length} token(s): ${message}`,\n { cause: callbackErrors[0]?.error },\n );\n }\n return results;\n }\n\n const errorEntries = Array.from(errors.entries());\n const message = errorEntries.map(([addr, e]) => `${addr}: ${e.message}`).join(\"; \");\n throw new DecryptionFailedError(\n `Batch delegated decryption failed for ${errors.size} token(s): ${message}`,\n { cause: errorEntries[0]?.[1] },\n );\n }\n\n private static async readBalanceHandlesBatch(\n tokens: Token[],\n accountAddress: Address,\n errors: Map<Address, ZamaError>,\n maxConcurrency: number,\n ): Promise<Array<EncryptedValue | undefined>> {\n const outcomes = await pLimit(\n tokens.map((token) => async () => {\n try {\n return {\n status: \"fulfilled\" as const,\n value: await token.readConfidentialBalanceOf(accountAddress),\n };\n } catch (reason) {\n return { status: \"rejected\" as const, reason };\n }\n }),\n maxConcurrency,\n );\n\n const encryptedValues: Array<EncryptedValue | undefined> = [];\n for (const [index, token] of tokens.entries()) {\n const outcome = outcomes[index];\n if (!outcome) {\n continue;\n }\n if (outcome.status === \"fulfilled\") {\n encryptedValues[index] = outcome.value;\n continue;\n }\n if (isFatalBatchError(outcome.reason)) {\n throw outcome.reason;\n }\n errors.set(\n token.address,\n outcome.reason instanceof ZamaError\n ? outcome.reason\n : new DecryptionFailedError(toError(outcome.reason).message, { cause: outcome.reason }),\n );\n }\n return encryptedValues;\n }\n\n // WRITE OPERATIONS\n\n /**\n * Confidential transfer. Encrypts the amount via FHE, then calls the contract.\n *\n * By default, the SDK validates the confidential balance before submitting.\n * If a cached plaintext balance exists it is used; otherwise, if credentials\n * are cached, it decrypts on the fly. Set `skipBalanceCheck: true` to bypass\n * this validation (e.g. for smart wallets).\n *\n * @param to - Recipient address.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param options - Optional: `skipBalanceCheck` (default `false`).\n * @returns The transaction hash and mined receipt.\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}\n * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransfer(\"0xRecipient\", 1000n);\n * ```\n */\n async confidentialTransfer(\n to: Address,\n amount: bigint,\n options?: TransferOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransfer\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransfer\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const { skipBalanceCheck = false, onEncryptComplete, onTransferSubmitted } = options ?? {};\n\n const normalizedTo = getAddress(to);\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount);\n }\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n });\n void swallow(\"transfer: onEncryptComplete\", () => onEncryptComplete?.(), this.sdk.logger);\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transfer\",\n config: confidentialTransferContract(\n this.address,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n ),\n onSubmitted: onTransferSubmitted,\n });\n }\n\n /**\n * Operator encrypted transfer on behalf of another address.\n * The caller must be an approved operator for `from`.\n *\n * @param from - The address to transfer from (caller must be an approved operator).\n * @param to - Recipient address.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferFrom(\"0xFrom\", \"0xTo\", 500n);\n * ```\n */\n async confidentialTransferFrom(\n from: Address,\n to: Address,\n amount: bigint,\n callbacks?: TransferCallbacks,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferFrom\");\n await requireAlignedWalletAccount(\n \"confidentialTransferFrom\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const normalizedFrom = getAddress(from);\n const normalizedTo = getAddress(to);\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: normalizedFrom,\n });\n void swallow(\n \"transferFrom: onEncryptComplete\",\n () => callbacks?.onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferFrom\",\n config: confidentialTransferFromContract(\n this.address,\n normalizedFrom,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n ),\n onSubmitted: callbacks?.onTransferSubmitted,\n });\n }\n\n /**\n * ERC-7984 `confidentialTransferAndCall`: encrypted transfer that also invokes\n * the recipient's receiver hook (`onConfidentialTransferReceived`) in a single\n * transaction. The caller crafts the opaque `data` payload — the SDK does not\n * encode, validate, or interpret it.\n *\n * Balance validation follows the same rules as {@link Token.confidentialTransfer}.\n *\n * @param to - Recipient address. Must implement the ERC-7984 receiver hook.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param data - Opaque bytes forwarded to the recipient's receiver hook.\n * @param options - Optional: `skipBalanceCheck` (default `false`).\n * @returns The transaction hash and mined receipt.\n *\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}\n * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferAndCall(\n * \"0xRecipient\",\n * 1000n,\n * \"0xabcd\", // caller-encoded payload forwarded to the receiver hook\n * );\n * ```\n */\n async confidentialTransferAndCall(\n to: Address,\n amount: bigint,\n data: Hex,\n options?: TransferOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferAndCall\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransferAndCall\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const { skipBalanceCheck = false, onEncryptComplete, onTransferSubmitted } = options ?? {};\n\n const normalizedTo = getAddress(to);\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount);\n }\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n });\n void swallow(\n \"transferAndCall: onEncryptComplete\",\n () => onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferAndCall\",\n config: confidentialTransferAndCallContract(\n this.address,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n data,\n ),\n onSubmitted: onTransferSubmitted,\n });\n }\n\n /**\n * ERC-7984 `confidentialTransferFromAndCall`: operator-initiated encrypted\n * transfer that also invokes the recipient's receiver hook in a single\n * transaction. The caller must be an approved operator for `from` and crafts\n * the opaque `data` payload — the SDK does not encode or interpret it.\n *\n * @param from - The address to transfer from (caller must be an approved operator).\n * @param to - Recipient address. Must implement the ERC-7984 receiver hook.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param data - Opaque bytes forwarded to the recipient's receiver hook.\n * @param callbacks - Optional progress callbacks.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferFromAndCall(\n * \"0xFrom\",\n * \"0xRecipient\",\n * 500n,\n * \"0xabcd\",\n * );\n * ```\n */\n async confidentialTransferFromAndCall(\n from: Address,\n to: Address,\n amount: bigint,\n data: Hex,\n callbacks?: TransferCallbacks,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferFromAndCall\");\n await requireAlignedWalletAccount(\n \"confidentialTransferFromAndCall\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const normalizedFrom = getAddress(from);\n const normalizedTo = getAddress(to);\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: normalizedFrom,\n });\n void swallow(\n \"transferFromAndCall: onEncryptComplete\",\n () => callbacks?.onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferFromAndCall\",\n config: confidentialTransferFromAndCallContract(\n this.address,\n normalizedFrom,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n data,\n ),\n onSubmitted: callbacks?.onTransferSubmitted,\n });\n }\n\n // OPERATOR APPROVAL\n\n /**\n * Set operator approval for the confidential token.\n * Defaults to 1 hour from now if `until` is not specified.\n *\n * @param operator - The address to set as an operator.\n * @param until - Optional Unix timestamp for approval expiry. Defaults to now + 1 hour.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.setOperator(\"0xOperator\");\n * ```\n */\n async setOperator(operator: Address, until?: number): Promise<TransactionResult> {\n this.#requireSigner(\"setOperator\");\n await requireChainAlignment(\"setOperator\", this.sdk.signer, this.sdk.provider);\n const normalizedOperator = getAddress(operator);\n return this.submitTransaction({\n operation: \"setOperator\",\n config: setOperatorContract(this.address, normalizedOperator, until),\n });\n }\n\n /**\n * Check if a spender is an approved operator for a given holder.\n *\n * @param holder - The token holder address.\n * @param spender - The address to check operator approval for.\n * @returns `true` if the spender is an approved operator for the holder.\n *\n * @example\n * ```ts\n * if (await token.isOperator(\"0xHolder\", \"0xSpender\")) {\n * // spender can call transferFrom on behalf of holder\n * }\n * ```\n */\n async isOperator(holder: Address, spender: Address): Promise<boolean> {\n return this.sdk.provider.readContract(\n isOperatorContract(this.address, getAddress(holder), getAddress(spender)),\n );\n }\n\n // PROTECTED HELPERS\n\n /**\n * Read the on-chain encrypted balance for a given owner.\n *\n * @internal\n */\n protected async readConfidentialBalanceOf(owner: Address): Promise<EncryptedValue> {\n return await this.sdk.provider.readContract(confidentialBalanceOfContract(this.address, owner));\n }\n\n /**\n * Pre-flight check: decrypt the confidential balance and compare against the\n * requested amount. If credentials are cached the decrypt happens silently;\n * if not, throws {@link BalanceCheckUnavailableError} instead of triggering\n * a surprise EIP-712 popup.\n *\n * @internal\n */\n protected async assertConfidentialBalance(amount: bigint): Promise<void> {\n if (amount === 0n) {\n return;\n }\n\n let balance: bigint;\n try {\n const account = await requireAlignedWalletAccount(\n \"assertConfidentialBalance\",\n this.sdk.signer,\n this.sdk.provider,\n );\n balance = await this.balanceOf(getAddress(account.address));\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new BalanceCheckUnavailableError(`Balance validation failed (token: ${this.address})`, {\n cause: error,\n });\n }\n\n if (balance < amount) {\n throw new InsufficientConfidentialBalanceError(\n `Insufficient confidential balance: requested ${amount}, available ${balance} (token: ${this.address})`,\n { requested: amount, available: balance, token: this.address },\n );\n }\n }\n\n /**\n * Emit a token-scoped event through the owning {@link ZamaSDK} so that\n * subscribers see a unified stream.\n *\n * @internal\n */\n protected emit(input: ZamaSDKEventInput): void {\n this.sdk.emitEvent(input, this.address);\n }\n\n /**\n * Submit a token-scoped write transaction through the shared SDK transaction\n * pipeline. Callers keep pre-flight and operation-specific work local.\n *\n * @internal\n */\n protected async submitTransaction(params: {\n operation: TransactionOperation;\n config: WriteContractConfig;\n onSubmitted?: (txHash: Hex) => void;\n }): Promise<TransactionResult> {\n const { operation, config, onSubmitted } = params;\n return submitSdkTransaction({\n operation,\n signer: this.#requireSigner(operation),\n provider: this.sdk.provider,\n config,\n emit: (input) => this.emit(input),\n onSubmitted,\n logger: this.sdk.logger,\n });\n }\n\n /** Verify all tokens share the same SDK instance and return it. */\n private static assertSameSdk(tokens: Token[]): ZamaSDK {\n const sdk = tokens[0]!.sdk;\n for (let i = 1; i < tokens.length; i++) {\n if (tokens[i]!.sdk !== sdk) {\n throw new ConfigurationError(\n \"All tokens in a batch operation must share the same ZamaSDK instance\",\n );\n }\n }\n return sdk;\n }\n}\n"],"mappings":"4FAGA,IAAa,EAAb,cAA2CA,EAAAA,CAAU,CACnD,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,iBAAkB,EAAS,CAAO,EACtD,KAAK,KAAO,uBACd,CACF,EAGa,EAAb,cAA2CD,EAAAA,CAAU,CACnD,YAAY,EAAiB,EAAwB,C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,CAC/D,CAEJ,CAQA,KAAe,EAAgC,CAC7C,KAAK,IAAI,UAAU,EAAO,KAAK,OAAO,CACxC,CAQA,MAAgB,kBAAkB,EAIH,CAC7B,GAAM,CAAE,YAAW,SAAQ,eAAgB,EAC3C,OAAOW,EAAqB,CAC1B,YACA,OAAQ,KAAKT,GAAe,CAAS,EACrC,SAAU,KAAK,IAAI,SACnB,SACA,KAAO,GAAU,KAAK,KAAK,CAAK,EAChC,cACA,OAAQ,KAAK,IAAI,MACnB,CAAC,CACH,CAGA,OAAe,cAAc,EAA0B,CACrD,IAAM,EAAM,EAAO,EAAE,CAAE,IACvB,IAAK,IAAI,EAAI,EAAG,EAAI,EAAO,OAAQ,IACjC,GAAI,EAAO,EAAE,CAAE,MAAQ,EACrB,MAAM,IAAIU,EAAAA,EACR,sEACF,EAGJ,OAAO,CACT,CACF"}
1
+ {"version":3,"file":"token.cjs","names":["ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","SigningRejectedError","SigningFailedError","ConfigurationError","SignerNotConfiguredError","WalletAccountNotReadyError","transactionOperationMetadata","swallow","ZamaError","ZamaSDKEvents","requireConfigured","nameContract","symbolContract","decimalsContract","supportsInterfaceContract","ERC7984_INTERFACE_ID","ERC7984_WRAPPER_INTERFACE_ID","ZamaError","toError","#requireSigner","swallow","confidentialTransferContract","confidentialTransferFromContract","confidentialTransferAndCallContract","confidentialTransferFromAndCallContract","setOperatorContract","isOperatorContract","confidentialBalanceOfContract","submitSdkTransaction","ConfigurationError"],"sources":["../../src/errors/encryption.ts","../../src/errors/transaction.ts","../../src/errors/rpc.ts","../../src/errors/chain.ts","../../src/errors/balance.ts","../../src/errors/fatal-batch.ts","../../src/utils/alignment.ts","../../src/utils/assertions.ts","../../src/utils/fhe-type.ts","../../src/utils/handles.ts","../../src/utils/concurrency.ts","../../src/utils/submit-transaction.ts","../../src/token/token.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** FHE encryption failed. */\nexport class EncryptionFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.EncryptionFailed, message, options);\n this.name = \"EncryptionFailedError\";\n }\n}\n\n/** FHE decryption failed. */\nexport class DecryptionFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DecryptionFailed, message, options);\n this.name = \"DecryptionFailedError\";\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** On-chain transaction reverted. */\nexport class TransactionRevertedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.TransactionReverted, message, options);\n this.name = \"TransactionRevertedError\";\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * The consumer's RPC provider rate-limited an on-chain read the SDK performs\n * during decryption (e.g. the ACL check) — HTTP 429 or JSON-RPC `-32005`. An\n * RPC-endpoint problem, **not** a decryption/entitlement failure, and safe to\n * **retry**. Kept distinct from the relayer's own back-pressure\n * ({@link RelayerRequestFailedError}).\n *\n * Backoff for chain RPC is owned by the consumer's transport: viem/ethers\n * already honor the `Retry-After` header and retry internally before this error\n * surfaces, so it is configured on the transport you pass via `chain.network`\n * (not re-implemented here).\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof RpcRateLimitError) {\n * // back off and retry; consider a higher-throughput RPC endpoint\n * }\n * }\n * ```\n */\nexport class RpcRateLimitError extends ZamaError {\n /**\n * Suggested delay before retrying, in **seconds**, when a numeric `retryAfter`\n * is present on the error. Usually `undefined` for chain RPC: the `Retry-After`\n * header is consumed by the consumer's viem/ethers transport (which owns the\n * backoff), not surfaced here — see the class doc.\n */\n readonly retryAfter: number | undefined;\n\n constructor(message: string, options?: ErrorOptions & { retryAfter?: number }) {\n const { retryAfter, ...errorOptions } = options ?? {};\n super(ZamaErrorCode.RpcRateLimited, message, errorOptions);\n this.name = \"RpcRateLimitError\";\n this.retryAfter = retryAfter;\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * Thrown when the signer and provider are connected to different chains at the\n * start of a write operation.\n *\n * Every write method runs a chain-alignment pre-flight check. If\n * `signer.getChainId()` and `provider.getChainId()` return different values,\n * this error is thrown before any RPC mutation is attempted.\n *\n * @example\n * ```ts\n * try {\n * await token.shield(1000n);\n * } catch (e) {\n * if (e instanceof ChainMismatchError) {\n * console.error(\n * `Signer is on chain ${e.signerChainId} but provider is on chain ${e.providerChainId}`,\n * );\n * }\n * }\n * ```\n */\nexport class ChainMismatchError extends ZamaError {\n /** Name of the operation that triggered the check. */\n readonly operation: string;\n /** Chain ID the signer is connected to. */\n readonly signerChainId: number;\n /** Chain ID the provider is connected to. */\n readonly providerChainId: number;\n\n constructor(\n {\n operation,\n signerChainId,\n providerChainId,\n }: { operation: string; signerChainId: number; providerChainId: number },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.ChainMismatch,\n `Operation \"${operation}\" requires signer and provider to be on the same chain, ` +\n `but signer is on chain ${signerChainId} and provider is on chain ${providerChainId}.`,\n options,\n );\n this.name = \"ChainMismatchError\";\n this.operation = operation;\n this.signerChainId = signerChainId;\n this.providerChainId = providerChainId;\n }\n}\n","import type { Address } from \"viem\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Structured details shared by balance-related errors. */\nexport interface BalanceErrorDetails {\n /** Amount the caller requested, in the token's base units. */\n readonly requested: bigint;\n /** Amount available at the time of the check, in the token's base units. */\n readonly available: bigint;\n /** Address of the token contract involved. */\n readonly token: Address;\n}\n\n/** Confidential (cToken) balance is insufficient for the requested operation. */\nexport class InsufficientConfidentialBalanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The available balance at the time of the check. */\n readonly available: bigint;\n /** The token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientConfidentialBalance, message, options);\n this.name = \"InsufficientConfidentialBalanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** ERC-20 balance is insufficient for the requested shield amount. */\nexport class InsufficientERC20BalanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The available balance at the time of the check. */\n readonly available: bigint;\n /** The ERC-20 token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientERC20Balance, message, options);\n this.name = \"InsufficientERC20BalanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** ERC-20 allowance granted to the wrapper is insufficient for the requested wrap amount. */\nexport class InsufficientAllowanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The allowance available at the time of the check. */\n readonly available: bigint;\n /** The underlying ERC-20 token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientAllowance, message, options);\n this.name = \"InsufficientAllowanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** Balance validation could not be performed (no cached credentials and decryption not possible). */\nexport class BalanceCheckUnavailableError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.BalanceCheckUnavailable, message, options);\n this.name = \"BalanceCheckUnavailableError\";\n }\n}\n\n/** A public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\nexport class ERC20ReadFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.ERC20ReadFailed, message, options);\n this.name = \"ERC20ReadFailedError\";\n }\n}\n","import { ConfigurationError } from \"./relayer\";\nimport { RpcRateLimitError } from \"./rpc\";\nimport { SigningRejectedError, SigningFailedError } from \"./signing\";\n\n/**\n * Returns `true` for errors that should abort an entire batch operation\n * rather than be recorded per-item — wallet signature rejected, signing\n * infrastructure broken, SDK misconfigured, or the RPC provider throttling.\n * These are systemic failures that won't recover within the same call; for a\n * rate-limit in particular, the per-item retry loop would only amplify the\n * throttle by re-hitting the already-rate-limited endpoint.\n *\n * Callers iterating over a batch (e.g. per-token decrypt) should rethrow when\n * this predicate is true so the whole batch aborts, and record the error\n * per-item otherwise.\n */\nexport function isFatalBatchError(error: unknown): boolean {\n return (\n error instanceof SigningRejectedError ||\n error instanceof SigningFailedError ||\n error instanceof ConfigurationError ||\n error instanceof RpcRateLimitError\n );\n}\n","import {\n ChainMismatchError,\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n} from \"../errors\";\nimport type { GenericProvider, GenericSigner, WalletAccount } from \"../types\";\n\n/**\n * Pre-flight guard for signer-required operations. Resolves the connected\n * wallet account (refreshing once if the signer reports it isn't ready) and\n * verifies the signer's chain matches the provider's.\n *\n * @internal\n */\nexport async function requireAlignedWalletAccount(\n operation: string,\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n): Promise<WalletAccount> {\n if (!signer) {\n throw new SignerNotConfiguredError(operation);\n }\n let account: WalletAccount;\n try {\n account = signer.requireWalletAccount(operation);\n } catch (error) {\n if (!(error instanceof WalletAccountNotReadyError) || !signer.refreshWalletAccount) {\n throw error;\n }\n await signer.refreshWalletAccount();\n account = signer.requireWalletAccount(operation);\n }\n const providerChainId = await provider.getChainId();\n if (account.chainId !== providerChainId) {\n throw new ChainMismatchError({ operation, signerChainId: account.chainId, providerChainId });\n }\n return account;\n}\n\n/**\n * Variant of {@link requireAlignedWalletAccount} that returns only the aligned\n * chain ID. Useful when a write path only needs to ensure signer/provider\n * coherence and doesn't otherwise consume the account.\n *\n * @internal\n */\nexport async function requireChainAlignment(\n operation: string,\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n): Promise<number> {\n return (await requireAlignedWalletAccount(operation, signer, provider)).chainId;\n}\n","export function assertNonNullable<T>(value: T, context: string): asserts value is NonNullable<T> {\n if (value === null || value === undefined) {\n throw new TypeError(`${context} must not be null or undefined`);\n }\n}\n\nexport function assertObject(\n value: unknown,\n context: string,\n): asserts value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${context} must be an object, got ${typeof value}`);\n }\n}\n\nexport function assertString(value: unknown, context: string): asserts value is string {\n if (typeof value !== \"string\") {\n throw new TypeError(`${context} must be a string, got ${typeof value}`);\n }\n}\n\nexport function assertArray(value: unknown, context: string): asserts value is unknown[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} must be an array, got ${typeof value}`);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport function assertFunction(value: unknown, context: string): asserts value is Function {\n if (typeof value !== \"function\") {\n throw new TypeError(`${context} must be a function, got ${typeof value}`);\n }\n}\n\nexport function assertBigint(value: unknown, context: string): asserts value is bigint {\n if (typeof value !== \"bigint\") {\n throw new TypeError(`${context} must be a bigint, got ${typeof value}`);\n }\n}\n\n/** Assert that `obj[key]` is a string. Narrows `obj` to include `{ [key]: string }`. */\nexport function assertStringProp<\n K extends string,\n O extends Record<string, unknown> = Record<string, unknown>,\n>(obj: O, key: K, context: string): asserts obj is O & Record<K, string> {\n assertString(obj[key], context);\n}\n\n/** Assert that `obj[key]` is a function. Narrows `obj` to include `{ [key]: F }`. */\nexport function assertFunctionProp<\n K extends string,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n F extends Function,\n O extends Record<string, unknown> = Record<string, unknown>,\n>(obj: O, key: K, context: string): asserts obj is O & Record<K, F> {\n assertFunction(obj[key], context);\n}\n\nexport function assertCondition(condition: boolean, message: string): asserts condition {\n if (!condition) {\n throw new TypeError(message);\n }\n}\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import type { EncryptedValue } from \"../relayer/types\";\nimport { encryptionBitsFromFheTypeId, isFheTypeId } from \"./fhe-type\";\n\n/** All-zero encrypted-value sentinel — a 32-byte zero handle representing the cleartext value `0`. */\nexport const ZERO_ENCRYPTED_VALUE =\n \"0x0000000000000000000000000000000000000000000000000000000000000000\" as const;\n\n/**\n * Check whether an encrypted value represents the zero value.\n */\nexport function isEncryptedValueZero(encryptedValue: string): boolean {\n return encryptedValue === ZERO_ENCRYPTED_VALUE || encryptedValue === \"0x\";\n}\n\n/**\n * Per-request cleartext-bit budget enforced by the KMS gateway, mirrored from\n * `@fhevm/sdk`'s `MAX_KMS_DECRYPT_DECRYPTION_BIT_LIMIT` (protocol-level constant,\n * not imported — see {@link MAX_CONTRACTS_PER_PERMIT} for why). Internal: decrypt\n * requests are chunked to respect it automatically, so callers never need this value.\n */\nexport const MAX_DECRYPTION_REQUEST_BITS = 2048;\n\n/** Max encryption bit width among all currently-known FHE types (euint256). */\nconst MAX_KNOWN_ENCRYPTION_BITS = 256;\n\n/**\n * Cleartext bit cost of decrypting a single handle, derived from its FHE\n * type (encoded at bits 8-15 of the handle — the same layout `@fhevm/sdk`'s\n * `FhevmHandle` decodes, byte 30 of the 32-byte handle).\n *\n * Falls back to {@link MAX_KNOWN_ENCRYPTION_BITS} for an unrecognized type\n * byte, or for a value that isn't parseable hex at all, instead of throwing.\n * A real on-chain handle is always well-formed with a valid type byte, so\n * this fallback only ever fires for synthetic test/placeholder handles —\n * deliberately more permissive than the relayer's own strict validation so\n * chunking stays safe without requiring every test fixture to encode a real\n * FHE handle. Do not tighten this to match relayer semantics.\n */\nexport function encryptionBitsForHandle(encryptedValue: EncryptedValue): number {\n let handleValue: bigint;\n try {\n handleValue = BigInt(encryptedValue);\n } catch {\n return MAX_KNOWN_ENCRYPTION_BITS;\n }\n const typeByte = Number((handleValue >> 8n) & 0xffn);\n return isFheTypeId(typeByte) ? encryptionBitsFromFheTypeId(typeByte) : MAX_KNOWN_ENCRYPTION_BITS;\n}\n\n/**\n * Split `handles` into groups whose cumulative cleartext-bit cost never\n * exceeds `maxBits`, preserving input order. Unlike {@link chunkContracts}\n * (fixed-size slices), a greedy accumulate-until-exceeded walk is required\n * since per-handle cost varies by FHE type. A handle whose own cost exceeds\n * `maxBits` still gets a solo chunk — always makes forward progress.\n */\nexport function chunkHandlesByBitBudget(\n handles: readonly EncryptedValue[],\n maxBits: number = MAX_DECRYPTION_REQUEST_BITS,\n): EncryptedValue[][] {\n const chunks: EncryptedValue[][] = [];\n let current: EncryptedValue[] = [];\n let currentBits = 0;\n\n for (const handle of handles) {\n const bits = encryptionBitsForHandle(handle);\n if (current.length > 0 && currentBits + bits > maxBits) {\n chunks.push(current);\n current = [];\n currentBits = 0;\n }\n current.push(handle);\n currentBits += bits;\n }\n if (current.length > 0) {\n chunks.push(current);\n }\n return chunks;\n}\n","/**\n * Execute an array of async thunks with bounded concurrency.\n * Defaults to `Infinity` (equivalent to `Promise.all`).\n */\nexport async function pLimit<T>(\n fns: (() => Promise<T>)[],\n maxConcurrency = Infinity,\n): Promise<T[]> {\n if (Number.isFinite(maxConcurrency) && maxConcurrency <= 0) {\n throw new Error(\"maxConcurrency must be a positive number\");\n }\n if (!Number.isFinite(maxConcurrency) || maxConcurrency >= fns.length) {\n return Promise.all(fns.map((f) => f()));\n }\n\n const results: T[] = Array.from({ length: fns.length });\n let index = 0;\n\n async function worker() {\n while (index < fns.length) {\n const i = index++;\n if (fns[i]) {\n results[i] = await fns[i]();\n }\n }\n }\n\n await Promise.all(Array.from({ length: maxConcurrency }, worker));\n return results;\n}\n","import type { Hex } from \"viem\";\nimport { TransactionRevertedError, ZamaError } from \"../errors\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { transactionOperationMetadata, ZamaSDKEvents } from \"../events/sdk-events\";\nimport type {\n GenericLogger,\n GenericProvider,\n GenericSigner,\n TransactionResult,\n WriteContractConfig,\n} from \"../types\";\nimport { swallow } from \"./swallow\";\n\n/**\n * Shared write-transaction pipeline for SDK calls that submit a transaction.\n *\n * On success: writes the tx, emits the per-operation submitted event from\n * {@link transactionOperationMetadata}, fires `onSubmitted`, waits for the\n * receipt, and returns `{ txHash, receipt }`.\n *\n * On failure: emits a {@link ZamaSDKEvents.TransactionError} event with the\n * transaction-level error it will throw, then throws it. Existing `ZamaError`\n * instances are rethrown as-is; all other failures are wrapped in\n * `TransactionRevertedError` with the original error as `cause`.\n */\nexport async function submitTransaction(params: {\n operation: TransactionOperation;\n signer: GenericSigner;\n provider: GenericProvider;\n config: WriteContractConfig;\n emit: (input: ZamaSDKEventInput) => void;\n onSubmitted?: (txHash: Hex) => void;\n logger: GenericLogger;\n}): Promise<TransactionResult> {\n const { operation, signer, provider, config, emit, onSubmitted, logger } = params;\n const metadata = transactionOperationMetadata[operation];\n\n try {\n const txHash = await signer.writeContract(config);\n emit(metadata.submittedEvent(txHash));\n void swallow(`${operation}: onSubmitted`, () => onSubmitted?.(txHash), logger);\n const receipt = await provider.waitForTransactionReceipt(txHash);\n return { txHash, receipt };\n } catch (error) {\n const failure =\n error instanceof ZamaError\n ? error\n : new TransactionRevertedError(`Transaction failed during ${operation}`, { cause: error });\n\n emit({ type: ZamaSDKEvents.TransactionError, operation, error: failure });\n throw failure;\n }\n}\n","import { type Address, getAddress, type Hex } from \"viem\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferAndCallContract,\n confidentialTransferContract,\n confidentialTransferFromAndCallContract,\n confidentialTransferFromContract,\n decimalsContract,\n ERC7984_INTERFACE_ID,\n ERC7984_WRAPPER_INTERFACE_ID,\n isOperatorContract,\n nameContract,\n setOperatorContract,\n supportsInterfaceContract,\n symbolContract,\n} from \"../contracts\";\nimport {\n BalanceCheckUnavailableError,\n ConfigurationError,\n DecryptionFailedError,\n EncryptionFailedError,\n InsufficientConfidentialBalanceError,\n isFatalBatchError,\n requireConfigured,\n ZamaError,\n} from \"../errors\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { toError } from \"../utils\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\nimport { assertBigint } from \"../utils/assertions\";\nimport { pLimit } from \"../utils/concurrency\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport { submitTransaction as submitSdkTransaction } from \"../utils/submit-transaction\";\nimport { swallow } from \"../utils/swallow\";\nimport type {\n GenericSigner,\n TransactionResult,\n TransferCallbacks,\n TransferOptions,\n WriteContractConfig,\n} from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\n\n/** Options for {@link Token.batchDecryptBalancesAs}. */\nexport interface BatchDecryptAsOptions {\n /** The address of the account that delegated decryption rights. */\n delegatorAddress: Address;\n /** Pre-fetched encrypted values. When omitted, they are fetched from the chain. */\n encryptedValues?: EncryptedValue[];\n /**\n * The account whose on-chain balance to read. Defaults to the delegator\n * address, which is the common case (the delegator grants permission to\n * decrypt their own balance). Only set this when the account differs\n * from the delegator.\n *\n * Matches the `account` parameter of `confidentialBalanceOf(account)` on-chain.\n */\n accountAddress?: Address;\n /** Maximum number of concurrent decrypt calls. Default: 10. */\n maxConcurrency?: number;\n /** Called when decryption fails for a single token. Return a fallback bigint. */\n onError?: (error: Error, address: Address) => bigint;\n}\n\n/** Result of {@link Token.batchBalancesOf}. */\nexport interface BatchBalancesResult {\n /** Successfully decrypted balances, keyed by token address. */\n results: Map<Address, bigint>;\n /** Per-token errors for tokens that failed to decrypt. */\n errors: Map<Address, ZamaError>;\n}\n\n/**\n * High-level interface for an ERC-7984 confidential token.\n * Hides FHE complexity (encryption, decryption, EIP-712 signing) behind\n * familiar ERC-20-like methods.\n *\n * For ERC-7984 wrappers (shield/unshield), use {@link WrappedToken} instead —\n * it extends `Token` with wrapper-specific operations.\n *\n * Decryption, credentials, caching, and event emission are handled by the\n * owning {@link ZamaSDK} — this class only exposes token-scoped helpers\n * that delegate to `sdk.decryption.decryptValues` and `sdk.permits.grantPermit`.\n */\nexport class Token {\n /** The SDK instance this token operates through. */\n readonly sdk: ZamaSDK;\n /** Checksummed address of the confidential token contract. */\n readonly address: Address;\n\n constructor(sdk: ZamaSDK, address: Address) {\n this.sdk = sdk;\n this.address = getAddress(address);\n }\n\n /** Resolve `sdk.signer` or throw {@link SignerNotConfiguredError} tagged with `operation`. */\n #requireSigner(operation: string): GenericSigner {\n return requireConfigured(this.sdk.signer, operation);\n }\n\n // METADATA\n\n /** Read the token name from the contract. */\n async name(): Promise<string> {\n return this.sdk.provider.readContract(nameContract(this.address));\n }\n\n /** Read the token symbol from the contract. */\n async symbol(): Promise<string> {\n return this.sdk.provider.readContract(symbolContract(this.address));\n }\n\n /** Read the token decimals from the contract. */\n async decimals(): Promise<number> {\n return this.sdk.provider.readContract(decimalsContract(this.address));\n }\n\n // ERC-165 DISCOVERY\n\n /**\n * ERC-165 check for {@link ERC7984_INTERFACE_ID} support.\n *\n * @returns `true` if the contract implements the ERC-7984 confidential token interface.\n */\n async isConfidential(): Promise<boolean> {\n return this.sdk.provider.readContract(\n supportsInterfaceContract(this.address, ERC7984_INTERFACE_ID),\n );\n }\n\n /**\n * ERC-165 check for IERC7984ERC20Wrapper support.\n *\n * @returns `true` if the contract implements the ERC-7984 wrapper interface\n * ({@link ERC7984_WRAPPER_INTERFACE_ID}, `0x1f1c62b2`).\n */\n async isWrapper(): Promise<boolean> {\n return this.sdk.provider.readContract(\n supportsInterfaceContract(this.address, ERC7984_WRAPPER_INTERFACE_ID),\n );\n }\n\n // BALANCES\n\n /**\n * Decrypt and return the plaintext balance for the given owner.\n * Acquires FHE credentials via a wallet signature if none are cached.\n *\n * @param owner - Balance owner address.\n * @returns The decrypted plaintext balance as a bigint.\n * @throws if FHE decryption fails. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balance = await token.balanceOf(\"0xOwner\");\n * ```\n */\n async balanceOf(owner: Address): Promise<bigint> {\n const ownerAddress = getAddress(owner);\n const encryptedValue = await this.readConfidentialBalanceOf(ownerAddress);\n const result = await this.sdk.decryption.decryptValues([\n { encryptedValue, contractAddress: this.address },\n ]);\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(`Decryption returned no value for ${encryptedValue}`);\n }\n assertBigint(value, \"balanceOf: result[encryptedValue]\");\n return value;\n }\n\n /**\n * Return the raw encrypted balance without decrypting.\n *\n * @param owner - Balance owner address.\n * @returns The encrypted balance as a hex string.\n *\n * @example\n * ```ts\n * const encryptedValue = await token.confidentialBalanceOf(\"0xOwner\");\n * ```\n */\n async confidentialBalanceOf(owner: Address): Promise<EncryptedValue> {\n return this.readConfidentialBalanceOf(getAddress(owner));\n }\n\n /**\n * Decrypt the balance of a delegator using delegated decryption credentials.\n * The connected signer acts as the delegatee who has been granted permission\n * by the delegator to decrypt their balance.\n *\n * Clear values are cached in storage keyed by `(account, token, encryptedValue)`.\n * Because every on-chain balance change produces a new encrypted value,\n * stale cache entries are never served. Cache write failures are silently\n * ignored — they do not affect the returned value.\n *\n * @param delegatorAddress - The address of the account that delegated decryption rights.\n * @param accountAddress - The account whose on-chain balance to read. Defaults\n * to the delegator address.\n * @returns The decrypted plaintext balance as a bigint.\n * @throws if no active delegation exists. {@link DelegationNotFoundError}\n * @throws if the delegation has expired. {@link DelegationExpiredError}\n * @throws if delegated decryption fails. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balance = await token.decryptBalanceAs({\n * delegatorAddress: \"0xDelegator\",\n * });\n * ```\n */\n async decryptBalanceAs({\n delegatorAddress,\n accountAddress,\n }: {\n delegatorAddress: Address;\n accountAddress?: Address;\n }): Promise<bigint> {\n await requireChainAlignment(\"decryptBalanceAs\", this.sdk.signer, this.sdk.provider);\n const normalizedDelegator = getAddress(delegatorAddress);\n const normalizedAccount = accountAddress ? getAddress(accountAddress) : normalizedDelegator;\n\n const encryptedValue = await this.readConfidentialBalanceOf(normalizedAccount);\n if (isEncryptedValueZero(encryptedValue)) {\n return 0n;\n }\n\n const result = await this.sdk.decryption.delegatedDecryptValues(\n [{ encryptedValue, contractAddress: this.address }],\n normalizedDelegator,\n normalizedAccount,\n );\n\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(\n `Delegated decryption returned no value for ${encryptedValue}`,\n );\n }\n assertBigint(value, \"decryptBalanceAs: result[encryptedValue]\");\n return value;\n }\n\n // BATCH STATICS\n\n /**\n * Decrypt confidential balances for multiple tokens in parallel, returning\n * successes and per-token errors separately. Pre-authorizes all token\n * addresses in a single wallet signature, then delegates each decrypt to\n * `sdk.decryption.decryptValues`.\n *\n * Tokens that fail to decrypt land in `errors` rather than aborting the\n * whole batch — caller decides how to surface them.\n *\n * @param tokens - Array of {@link Token} instances bound to the same SDK.\n * @param owner - Balance owner address.\n * @returns `{ results, errors }` partitioning the per-token outcomes.\n *\n * @example\n * ```ts\n * const { results, errors } = await Token.batchBalancesOf(tokens, owner);\n * ```\n */\n static async batchBalancesOf(tokens: Token[], owner: Address): Promise<BatchBalancesResult> {\n const results = new Map<Address, bigint>();\n const errors = new Map<Address, ZamaError>();\n if (tokens.length === 0) {\n return { results, errors };\n }\n\n const sdk = Token.assertSameSdk(tokens);\n // Fail fast on chain mismatch before prompting the wallet for a signature.\n await requireChainAlignment(\"batchBalancesOf\", sdk.signer, sdk.provider);\n // Pre-authorize the full token set in one wallet signature so subsequent\n // per-token decryptValues calls reuse the cached credentials.\n await sdk.permits.grantPermit(tokens.map((t) => t.address));\n\n const outcomes = await pLimit(\n tokens.map((t) => async () => {\n try {\n return { status: \"fulfilled\" as const, value: await t.balanceOf(owner) };\n } catch (reason) {\n return { status: \"rejected\" as const, reason };\n }\n }),\n 5,\n );\n\n for (let i = 0; i < tokens.length; i++) {\n const tokenAddress = tokens[i]!.address;\n const outcome = outcomes[i]!;\n if (outcome.status === \"fulfilled\") {\n results.set(tokenAddress, outcome.value);\n } else {\n const reason = outcome.reason;\n // Session-level failures (user rejected signature, SDK misconfigured)\n // apply to every token — surface them instead of collecting per-token.\n if (isFatalBatchError(reason)) {\n throw reason;\n }\n const error =\n reason instanceof ZamaError\n ? reason\n : new DecryptionFailedError(toError(reason).message, { cause: reason });\n errors.set(tokenAddress, error);\n }\n }\n\n // Total failure: surface the first error so callers know nothing decrypted.\n if (errors.size === tokens.length) {\n const firstError = errors.values().next().value;\n throw firstError ?? new DecryptionFailedError(\"All token balance decryptions failed\");\n }\n\n return { results, errors };\n }\n\n /**\n * Batch decrypt confidential balances as a delegate across multiple tokens.\n * Mirrors {@link batchBalancesOf} but uses delegated credentials.\n *\n * **Error handling:** If a per-token decryption fails and no `onError` callback\n * is provided, errors are collected and thrown as an aggregated\n * `DecryptionFailedError`. When the relayer returns no value for an encrypted value,\n * a `DecryptionFailedError` is thrown for that token (never silently returns `0n`).\n * Pass `onError: () => 0n` to opt into the silent zero behavior.\n *\n * @param tokens - Array of Token instances to decrypt balances for.\n * @param options - Delegated decryption configuration.\n * @returns A Map from token address to decrypted balance.\n * @throws if no active delegation exists. {@link DelegationNotFoundError}\n * @throws if the delegation has expired. {@link DelegationExpiredError}\n * @throws if any decryption fails and no `onError` is provided. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balances = await Token.batchDecryptBalancesAs(tokens, {\n * delegatorAddress: \"0xDelegator\",\n * onError: (err, addr) => { console.error(addr, err); return 0n; },\n * });\n * ```\n */\n static async batchDecryptBalancesAs(\n tokens: Token[],\n options: BatchDecryptAsOptions,\n ): Promise<Map<Address, bigint>> {\n if (tokens.length === 0) {\n return new Map();\n }\n\n const sdk = Token.assertSameSdk(tokens);\n const results = new Map<Address, bigint>();\n const errors = new Map<Address, ZamaError>();\n const normalizedAccount = options.accountAddress\n ? getAddress(options.accountAddress)\n : getAddress(options.delegatorAddress);\n const maxConcurrency = options.maxConcurrency ?? 10;\n if (options.encryptedValues && tokens.length !== options.encryptedValues.length) {\n throw new DecryptionFailedError(\n `tokens.length (${tokens.length}) must equal encryptedValues.length (${options.encryptedValues.length})`,\n );\n }\n const resolvedEncryptedValues =\n options.encryptedValues ??\n (await Token.readBalanceHandlesBatch(tokens, normalizedAccount, errors, maxConcurrency));\n\n const decryptRequests: Array<{ token: Token; encryptedValue: EncryptedValue }> = [];\n for (const [index, token] of tokens.entries()) {\n const encryptedValue = resolvedEncryptedValues[index];\n if (!encryptedValue || errors.has(token.address)) {\n continue;\n }\n if (isEncryptedValueZero(encryptedValue)) {\n // Zero balance → skip the relayer; no decryption needed.\n results.set(token.address, 0n);\n } else {\n decryptRequests.push({ token, encryptedValue });\n }\n }\n\n if (decryptRequests.length > 0) {\n const decrypted = await sdk.decryption.delegatedBatchDecryptValues({\n encryptedInputs: decryptRequests.map(({ token, encryptedValue }) => ({\n encryptedValue,\n contractAddress: token.address,\n })),\n delegatorAddress: options.delegatorAddress,\n accountAddress: options.accountAddress,\n maxConcurrency,\n });\n\n for (const [index, item] of decrypted.items.entries()) {\n const request = decryptRequests[index];\n if (!request) {\n continue;\n }\n if (item.error) {\n errors.set(request.token.address, item.error);\n continue;\n }\n const value = item.value;\n if (value === undefined) {\n errors.set(\n request.token.address,\n new DecryptionFailedError(\n `Batch delegated decryption returned no value for ${item.encryptedValue} on token ${request.token.address}`,\n ),\n );\n continue;\n }\n assertBigint(value, \"batchDecryptBalancesAs: result[encryptedValue]\");\n results.set(request.token.address, value);\n }\n }\n\n if (errors.size === 0) {\n return results;\n }\n\n if (options.onError) {\n const callbackErrors: Array<{ address: Address; error: Error }> = [];\n for (const [address, error] of errors) {\n try {\n results.set(address, options.onError(error, address));\n } catch (callbackError) {\n callbackErrors.push({ address, error: toError(callbackError) });\n }\n }\n if (callbackErrors.length > 0) {\n const message = callbackErrors\n .map(({ address, error }) => `${address}: ${error.message}`)\n .join(\"; \");\n throw new DecryptionFailedError(\n `Batch delegated decryption onError callback failed for ${callbackErrors.length} token(s): ${message}`,\n { cause: callbackErrors[0]?.error },\n );\n }\n return results;\n }\n\n const errorEntries = Array.from(errors.entries());\n const message = errorEntries.map(([addr, e]) => `${addr}: ${e.message}`).join(\"; \");\n throw new DecryptionFailedError(\n `Batch delegated decryption failed for ${errors.size} token(s): ${message}`,\n { cause: errorEntries[0]?.[1] },\n );\n }\n\n private static async readBalanceHandlesBatch(\n tokens: Token[],\n accountAddress: Address,\n errors: Map<Address, ZamaError>,\n maxConcurrency: number,\n ): Promise<Array<EncryptedValue | undefined>> {\n const outcomes = await pLimit(\n tokens.map((token) => async () => {\n try {\n return {\n status: \"fulfilled\" as const,\n value: await token.readConfidentialBalanceOf(accountAddress),\n };\n } catch (reason) {\n return { status: \"rejected\" as const, reason };\n }\n }),\n maxConcurrency,\n );\n\n const encryptedValues: Array<EncryptedValue | undefined> = [];\n for (const [index, token] of tokens.entries()) {\n const outcome = outcomes[index];\n if (!outcome) {\n continue;\n }\n if (outcome.status === \"fulfilled\") {\n encryptedValues[index] = outcome.value;\n continue;\n }\n if (isFatalBatchError(outcome.reason)) {\n throw outcome.reason;\n }\n errors.set(\n token.address,\n outcome.reason instanceof ZamaError\n ? outcome.reason\n : new DecryptionFailedError(toError(outcome.reason).message, { cause: outcome.reason }),\n );\n }\n return encryptedValues;\n }\n\n // WRITE OPERATIONS\n\n /**\n * Confidential transfer. Encrypts the amount via FHE, then calls the contract.\n *\n * By default, the SDK validates the confidential balance before submitting.\n * If a cached plaintext balance exists it is used; otherwise, if credentials\n * are cached, it decrypts on the fly. Set `skipBalanceCheck: true` to bypass\n * this validation (e.g. for smart wallets).\n *\n * @param to - Recipient address.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param options - Optional: `skipBalanceCheck` (default `false`).\n * @returns The transaction hash and mined receipt.\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}\n * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransfer(\"0xRecipient\", 1000n);\n * ```\n */\n async confidentialTransfer(\n to: Address,\n amount: bigint,\n options?: TransferOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransfer\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransfer\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const { skipBalanceCheck = false, onEncryptComplete, onTransferSubmitted } = options ?? {};\n\n const normalizedTo = getAddress(to);\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount);\n }\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n });\n void swallow(\"transfer: onEncryptComplete\", () => onEncryptComplete?.(), this.sdk.logger);\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transfer\",\n config: confidentialTransferContract(\n this.address,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n ),\n onSubmitted: onTransferSubmitted,\n });\n }\n\n /**\n * Operator encrypted transfer on behalf of another address.\n * The caller must be an approved operator for `from`.\n *\n * @param from - The address to transfer from (caller must be an approved operator).\n * @param to - Recipient address.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferFrom(\"0xFrom\", \"0xTo\", 500n);\n * ```\n */\n async confidentialTransferFrom(\n from: Address,\n to: Address,\n amount: bigint,\n callbacks?: TransferCallbacks,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferFrom\");\n await requireAlignedWalletAccount(\n \"confidentialTransferFrom\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const normalizedFrom = getAddress(from);\n const normalizedTo = getAddress(to);\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: normalizedFrom,\n });\n void swallow(\n \"transferFrom: onEncryptComplete\",\n () => callbacks?.onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferFrom\",\n config: confidentialTransferFromContract(\n this.address,\n normalizedFrom,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n ),\n onSubmitted: callbacks?.onTransferSubmitted,\n });\n }\n\n /**\n * ERC-7984 `confidentialTransferAndCall`: encrypted transfer that also invokes\n * the recipient's receiver hook (`onConfidentialTransferReceived`) in a single\n * transaction. The caller crafts the opaque `data` payload — the SDK does not\n * encode, validate, or interpret it.\n *\n * Balance validation follows the same rules as {@link Token.confidentialTransfer}.\n *\n * @param to - Recipient address. Must implement the ERC-7984 receiver hook.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param data - Opaque bytes forwarded to the recipient's receiver hook.\n * @param options - Optional: `skipBalanceCheck` (default `false`).\n * @returns The transaction hash and mined receipt.\n *\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}\n * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferAndCall(\n * \"0xRecipient\",\n * 1000n,\n * \"0xabcd\", // caller-encoded payload forwarded to the receiver hook\n * );\n * ```\n */\n async confidentialTransferAndCall(\n to: Address,\n amount: bigint,\n data: Hex,\n options?: TransferOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferAndCall\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransferAndCall\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const { skipBalanceCheck = false, onEncryptComplete, onTransferSubmitted } = options ?? {};\n\n const normalizedTo = getAddress(to);\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount);\n }\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n });\n void swallow(\n \"transferAndCall: onEncryptComplete\",\n () => onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferAndCall\",\n config: confidentialTransferAndCallContract(\n this.address,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n data,\n ),\n onSubmitted: onTransferSubmitted,\n });\n }\n\n /**\n * ERC-7984 `confidentialTransferFromAndCall`: operator-initiated encrypted\n * transfer that also invokes the recipient's receiver hook in a single\n * transaction. The caller must be an approved operator for `from` and crafts\n * the opaque `data` payload — the SDK does not encode or interpret it.\n *\n * @param from - The address to transfer from (caller must be an approved operator).\n * @param to - Recipient address. Must implement the ERC-7984 receiver hook.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param data - Opaque bytes forwarded to the recipient's receiver hook.\n * @param callbacks - Optional progress callbacks.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferFromAndCall(\n * \"0xFrom\",\n * \"0xRecipient\",\n * 500n,\n * \"0xabcd\",\n * );\n * ```\n */\n async confidentialTransferFromAndCall(\n from: Address,\n to: Address,\n amount: bigint,\n data: Hex,\n callbacks?: TransferCallbacks,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferFromAndCall\");\n await requireAlignedWalletAccount(\n \"confidentialTransferFromAndCall\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const normalizedFrom = getAddress(from);\n const normalizedTo = getAddress(to);\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: normalizedFrom,\n });\n void swallow(\n \"transferFromAndCall: onEncryptComplete\",\n () => callbacks?.onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferFromAndCall\",\n config: confidentialTransferFromAndCallContract(\n this.address,\n normalizedFrom,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n data,\n ),\n onSubmitted: callbacks?.onTransferSubmitted,\n });\n }\n\n // OPERATOR APPROVAL\n\n /**\n * Set operator approval for the confidential token.\n * Defaults to 1 hour from now if `until` is not specified.\n *\n * @param operator - The address to set as an operator.\n * @param until - Optional Unix timestamp for approval expiry. Defaults to now + 1 hour.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.setOperator(\"0xOperator\");\n * ```\n */\n async setOperator(operator: Address, until?: number): Promise<TransactionResult> {\n this.#requireSigner(\"setOperator\");\n await requireChainAlignment(\"setOperator\", this.sdk.signer, this.sdk.provider);\n const normalizedOperator = getAddress(operator);\n return this.submitTransaction({\n operation: \"setOperator\",\n config: setOperatorContract(this.address, normalizedOperator, until),\n });\n }\n\n /**\n * Check if a spender is an approved operator for a given holder.\n *\n * @param holder - The token holder address.\n * @param spender - The address to check operator approval for.\n * @returns `true` if the spender is an approved operator for the holder.\n *\n * @example\n * ```ts\n * if (await token.isOperator(\"0xHolder\", \"0xSpender\")) {\n * // spender can call transferFrom on behalf of holder\n * }\n * ```\n */\n async isOperator(holder: Address, spender: Address): Promise<boolean> {\n return this.sdk.provider.readContract(\n isOperatorContract(this.address, getAddress(holder), getAddress(spender)),\n );\n }\n\n // PROTECTED HELPERS\n\n /**\n * Read the on-chain encrypted balance for a given owner.\n *\n * @internal\n */\n protected async readConfidentialBalanceOf(owner: Address): Promise<EncryptedValue> {\n return await this.sdk.provider.readContract(confidentialBalanceOfContract(this.address, owner));\n }\n\n /**\n * Pre-flight check: decrypt the confidential balance and compare against the\n * requested amount. If credentials are cached the decrypt happens silently;\n * if not, throws {@link BalanceCheckUnavailableError} instead of triggering\n * a surprise EIP-712 popup.\n *\n * @internal\n */\n protected async assertConfidentialBalance(amount: bigint): Promise<void> {\n if (amount === 0n) {\n return;\n }\n\n let balance: bigint;\n try {\n const account = await requireAlignedWalletAccount(\n \"assertConfidentialBalance\",\n this.sdk.signer,\n this.sdk.provider,\n );\n balance = await this.balanceOf(getAddress(account.address));\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new BalanceCheckUnavailableError(`Balance validation failed (token: ${this.address})`, {\n cause: error,\n });\n }\n\n if (balance < amount) {\n throw new InsufficientConfidentialBalanceError(\n `Insufficient confidential balance: requested ${amount}, available ${balance} (token: ${this.address})`,\n { requested: amount, available: balance, token: this.address },\n );\n }\n }\n\n /**\n * Emit a token-scoped event through the owning {@link ZamaSDK} so that\n * subscribers see a unified stream.\n *\n * @internal\n */\n protected emit(input: ZamaSDKEventInput): void {\n this.sdk.emitEvent(input, this.address);\n }\n\n /**\n * Submit a token-scoped write transaction through the shared SDK transaction\n * pipeline. Callers keep pre-flight and operation-specific work local.\n *\n * @internal\n */\n protected async submitTransaction(params: {\n operation: TransactionOperation;\n config: WriteContractConfig;\n onSubmitted?: (txHash: Hex) => void;\n }): Promise<TransactionResult> {\n const { operation, config, onSubmitted } = params;\n return submitSdkTransaction({\n operation,\n signer: this.#requireSigner(operation),\n provider: this.sdk.provider,\n config,\n emit: (input) => this.emit(input),\n onSubmitted,\n logger: this.sdk.logger,\n });\n }\n\n /** Verify all tokens share the same SDK instance and return it. */\n private static assertSameSdk(tokens: Token[]): ZamaSDK {\n const sdk = tokens[0]!.sdk;\n for (let i = 1; i < tokens.length; i++) {\n if (tokens[i]!.sdk !== sdk) {\n throw new ConfigurationError(\n \"All tokens in a batch operation must share the same ZamaSDK instance\",\n );\n }\n }\n return sdk;\n }\n}\n"],"mappings":"qFAGA,IAAa,EAAb,cAA2CA,EAAAA,CAAU,CACnD,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,iBAAkB,EAAS,CAAO,EACtD,KAAK,KAAO,uBACd,CACF,EAGa,EAAb,cAA2CD,EAAAA,CAAU,CACnD,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,iBAAkB,EAAS,CAAO,EACtD,KAAK,KAAO,uBACd,CACF,ECba,EAAb,cAA8CC,EAAAA,CAAU,CACtD,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,oBAAqB,EAAS,CAAO,EACzD,KAAK,KAAO,0BACd,CACF,ECiBa,EAAb,cAAuCC,EAAAA,CAAU,CAO/C,WAEA,YAAY,EAAiB,EAAkD,CAC7E,GAAM,CAAE,aAAY,GAAG,GAAiB,GAAW,CAAC,EACpD,MAAMC,EAAAA,EAAc,eAAgB,EAAS,CAAY,EACzD,KAAK,KAAO,oBACZ,KAAK,WAAa,CACpB,CACF,ECjBa,EAAb,cAAwCC,E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s"),n=require("../eip1193-subscribe.cjs");let r=require("viem");var i=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){return this.#e.readContract(e)}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getBlockTimestamp(){return(await this.#e.getBlock()).timestamp}};function a(e){let t=(e.primaryType?e.types[e.primaryType]:void 0)??[],n={...e.message};for(let{name:e,type:r}of t)/^uint\d*$/.test(r)&&(n[e]=BigInt(n[e]));return n}function o(e){if(!(!e.account||!e.chain))return{address:(0,r.getAddress)(e.account.address),chainId:e.chain.id}}var s=class extends t.t{#e;#t;#n;constructor(e){super(o(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(t){if(!this.#e.account)throw new e.V(t);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`),{EIP712Domain:r,...i}=e.types;return t.signTypedData({account:n,primaryType:e.primaryType,types:i,domain:e.domain,message:a(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?n.t({provider:this.#t,getInitialWalletAccount:()=>o(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function c(e){return t.i(new s({walletClient:e.walletClient,ethereum:e.ethereum}),new i({publicClient:e.publicClient}),e)}function l(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function u(t,n,r){return t.readContract(e.S(n,r))}function d(t,n){return t.readContract(e.N(n))}function f(t,n,r){return t.readContract(e.m(n,r))}function p(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.T(n,r,i,a)})}function m(t,n,r,i,a,o){return t.writeContract({chain:t.chain,account:l(t),...e.P(n,r,i,a,o)})}function h(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.F(n,r,i,a)})}function g(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.O(n,r,i,a)})}function _(t,n,r,i){return t.writeContract({chain:t.chain,account:l(t),...e.M(n,r,i)})}function v(t,n,r,i){return t.writeContract({chain:t.chain,account:l(t),...e.I(n,r,i)})}function y(t,n){return t.readContract(e.i(n))}function b(t,n){return t.readContract(e.a(n))}function x(t,n,r,i){return t.readContract(e.o(n,r,i))}function S(t,n,r){return t.readContract(e.r(n,r))}function C(t,n,r){return t.readContract(e.t(n,r))}function w(t,n,r){return t.readContract(e.n(n,r))}function T(t,n,r){return t.readContract(e.s(n,r))}exports.ViemProvider=i,exports.ViemSigner=s,exports.createConfig=c,exports.readConfidentialBalanceOfContract=u,exports.readConfidentialTokenAddressContract=C,exports.readIsConfidentialTokenValidContract=T,exports.readSupportsInterfaceContract=f,exports.readTokenAddressContract=w,exports.readTokenPairContract=S,exports.readTokenPairsContract=y,exports.readTokenPairsLengthContract=b,exports.readTokenPairsSliceContract=x,exports.readUnderlyingTokenContract=d,exports.writeConfidentialTransferContract=p,exports.writeFinalizeUnwrapContract=g,exports.writeSetOperatorContract=_,exports.writeUnwrapContract=m,exports.writeUnwrapFromBalanceContract=h,exports.writeWrapContract=v;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../sdk-events.cjs"),t=require("../base-signer.cjs"),n=require("../eip1193-subscribe.cjs");let r=require("viem");var i=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){return this.#e.readContract(e)}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getBlockTimestamp(){return(await this.#e.getBlock()).timestamp}};function a(e){let t=(e.primaryType?e.types[e.primaryType]:void 0)??[],n={...e.message};for(let{name:e,type:r}of t)/^uint\d*$/.test(r)&&(n[e]=BigInt(n[e]));return n}function o(e){if(!(!e.account||!e.chain))return{address:(0,r.getAddress)(e.account.address),chainId:e.chain.id}}var s=class extends t.t{#e;#t;#n;constructor(e){super(o(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(t){if(!this.#e.account)throw new e.U(t);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`),{EIP712Domain:r,...i}=e.types;return t.signTypedData({account:n,primaryType:e.primaryType,types:i,domain:e.domain,message:a(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?n.t({provider:this.#t,getInitialWalletAccount:()=>o(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function c(e){return t.i(new s({walletClient:e.walletClient,ethereum:e.ethereum}),new i({publicClient:e.publicClient}),e)}function l(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function u(t,n,r){return t.readContract(e.w(n,r))}function d(t,n){return t.readContract(e.F(n))}function f(t,n,r){return t.readContract(e.g(n,r))}function p(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.D(n,r,i,a)})}function m(t,n,r,i,a,o){return t.writeContract({chain:t.chain,account:l(t),...e.I(n,r,i,a,o)})}function h(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.L(n,r,i,a)})}function g(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.A(n,r,i,a)})}function _(t,n,r,i){return t.writeContract({chain:t.chain,account:l(t),...e.P(n,r,i)})}function v(t,n,r,i){return t.writeContract({chain:t.chain,account:l(t),...e.R(n,r,i)})}function y(t,n){return t.readContract(e.o(n))}function b(t,n){return t.readContract(e.s(n))}function x(t,n,r,i){return t.readContract(e.c(n,r,i))}function S(t,n,r){return t.readContract(e.a(n,r))}function C(t,n,r){return t.readContract(e.r(n,r))}function w(t,n,r){return t.readContract(e.i(n,r))}function T(t,n,r){return t.readContract(e.l(n,r))}exports.BaseSigner=t.t,exports.ViemProvider=i,exports.ViemSigner=s,exports.ZamaSDKEvents=e.t,exports.createConfig=c,exports.readConfidentialBalanceOfContract=u,exports.readConfidentialTokenAddressContract=C,exports.readIsConfidentialTokenValidContract=T,exports.readSupportsInterfaceContract=f,exports.readTokenAddressContract=w,exports.readTokenPairContract=S,exports.readTokenPairsContract=y,exports.readTokenPairsLengthContract=b,exports.readTokenPairsSliceContract=x,exports.readUnderlyingTokenContract=d,exports.writeConfidentialTransferContract=p,exports.writeFinalizeUnwrapContract=g,exports.writeSetOperatorContract=_,exports.writeUnwrapContract=m,exports.writeUnwrapFromBalanceContract=h,exports.writeWrapContract=v;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#publicClient","BaseSigner","#walletClient","#ethereum","#unsubscribeProvider","#subscribeToProvider","WalletNotConnectedError","#requireAccount","eip1193Subscribe","buildZamaConfig","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/viem/viem-provider.ts","../../../src/viem/viem-signer.ts","../../../src/viem/config.ts","../../../src/viem/contracts.ts"],"sourcesContent":["import type {\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Hex,\n PublicClient,\n} from \"viem\";\nimport type { GenericProvider, ReadContractConfig, TransactionReceipt } from \"../types\";\n\n/** Configuration for {@link ViemProvider}. */\nexport interface ViemProviderConfig {\n /** A viem `PublicClient` backing all read operations. */\n publicClient: PublicClient;\n}\n\n/**\n * Read-only {@link GenericProvider} backed by a viem `PublicClient`.\n *\n * Use this for integrations that only need public chain reads before the user has Pair with a\n * {@link ViemSigner} when wallet authority is required; the two can share a transport or point at\n * independent RPCs.\n *\n * @example\n * ```ts\n * const publicClient = createPublicClient({ chain: sepolia, transport: http(ALCHEMY_URL) });\n * const provider = new ViemProvider({ publicClient });\n * ```\n */\nexport class ViemProvider implements GenericProvider {\n readonly #publicClient: PublicClient;\n\n constructor(config: ViemProviderConfig) {\n this.#publicClient = config.publicClient;\n }\n\n async getChainId(): Promise<number> {\n return this.#publicClient.getChainId();\n }\n\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return this.#publicClient.readContract(config);\n }\n\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n return this.#publicClient.waitForTransactionReceipt({ hash });\n }\n\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#publicClient.getBlock();\n return block.timestamp;\n }\n}\n","import type {\n Account,\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n EIP1193Provider,\n WalletClient,\n Hex,\n} from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { writeContract } from \"viem/actions\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\n\n/**\n * Configuration for {@link ViemSigner}.\n *\n * The optional `ethereum` field is needed for `subscribe()` (EIP-1193\n * `accountsChanged` / `disconnect` events). It cannot be auto-extracted from\n * `walletClient` because viem's `custom(ethereum)` transport captures the\n * provider in a closure and does **not** expose `on` / `removeListener` on\n * `walletClient.transport`.\n *\n * If you omit `ethereum`, `subscribe()` returns a no-op. For automatic\n * wallet lifecycle handling, consider using `WagmiSigner` instead.\n */\nexport interface ViemSignerConfig {\n /** Wallet client for signing and write operations. */\n walletClient: WalletClient;\n ethereum?: EIP1193Provider;\n}\n\n// viem requires uint values as bigints, but the KMS permit message carries them\n// as decimal strings. Convert by declared field type rather than by name so every\n// permit version is covered (V1 `durationDays`, V2 `durationSeconds`, ...).\nfunction messageWithBigIntUints(typedData: EIP712TypedData): Record<string, unknown> {\n const fields = (typedData.primaryType ? typedData.types[typedData.primaryType] : undefined) ?? [];\n const message: Record<string, unknown> = { ...typedData.message };\n for (const { name, type } of fields) {\n if (/^uint\\d*$/.test(type)) {\n message[name] = BigInt(message[name] as string | number | bigint);\n }\n }\n return message;\n}\n\nfunction walletAccountFromWalletClient(walletClient: WalletClient): WalletAccount | undefined {\n if (!walletClient.account || !walletClient.chain) {\n return undefined;\n }\n const address = getAddress(walletClient.account.address);\n return { address, chainId: walletClient.chain.id };\n}\n\nexport class ViemSigner extends BaseSigner {\n readonly #walletClient: WalletClient;\n readonly #ethereum?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n\n constructor(config: ViemSignerConfig) {\n super(walletAccountFromWalletClient(config.walletClient));\n this.#walletClient = config.walletClient;\n this.#ethereum = config.ethereum;\n this.#unsubscribeProvider = this.#subscribeToProvider();\n }\n\n #requireAccount(operation: string): { walletClient: WalletClient; account: Account } {\n if (!this.#walletClient.account) {\n throw new WalletNotConnectedError(operation);\n }\n return { walletClient: this.#walletClient, account: this.#walletClient.account };\n }\n\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"signTypedData\");\n const { EIP712Domain: _, ...sigTypes } = typedData.types;\n return walletClient.signTypedData({\n account,\n primaryType: typedData.primaryType,\n types: sigTypes,\n domain: typedData.domain,\n message: messageWithBigIntUints(typedData),\n // Cast: EIP712TypedData is structural (`Eip712Like`), so viem cannot correlate primaryType/types/message and the inferred `message` collapses to `never`.\n } as Parameters<typeof walletClient.signTypedData>[0]);\n }\n\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"writeContract\");\n return walletClient.writeContract({\n chain: walletClient.chain,\n account,\n ...config,\n } as Parameters<typeof writeContract>[1]);\n }\n\n #subscribeToProvider(): () => void {\n if (!this.#ethereum) {\n return () => {};\n }\n return eip1193Subscribe({\n provider: this.#ethereum,\n getInitialWalletAccount: () => walletAccountFromWalletClient(this.#walletClient),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n }\n\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n}\n","import type { FheChain } from \"../chains\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { buildZamaConfig } from \"../config/build\";\nimport { ViemProvider } from \"./viem-provider\";\nimport { ViemSigner } from \"./viem-signer\";\nimport type { ZamaConfigViem } from \"./types\";\n\n/** Create a {@link ZamaConfig} from viem clients. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigViem<TChains>,\n): ZamaConfig {\n const signer = new ViemSigner({ walletClient: params.walletClient, ethereum: params.ethereum });\n const provider = new ViemProvider({ publicClient: params.publicClient });\n return buildZamaConfig(signer, provider, params);\n}\n","import type { PublicClient, WalletClient, Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\n// ── Helpers ────────────────────────────────────────────────\n\nfunction requireAccount(client: WalletClient) {\n if (!client.account) {\n throw new TypeError(\"WalletClient has no account\");\n }\n return client.account;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\nexport function readConfidentialBalanceOfContract(\n client: PublicClient,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return client.readContract(confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\nexport function readUnderlyingTokenContract(client: PublicClient, wrapperAddress: Address) {\n return client.readContract(underlyingContract(wrapperAddress));\n}\n\nexport function readSupportsInterfaceContract(\n client: PublicClient,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return client.readContract(supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\nexport function writeConfidentialTransferContract(\n client: WalletClient,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n });\n}\n\nexport function writeUnwrapContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof),\n });\n}\n\nexport function writeUnwrapFromBalanceContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance),\n });\n}\n\nexport function writeFinalizeUnwrapContract(\n client: WalletClient,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n });\n}\n\nexport function writeSetOperatorContract(\n client: WalletClient,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...setOperatorContract(tokenAddress, operator, until),\n });\n}\n\nexport function writeWrapContract(\n client: WalletClient,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...wrapContract(wrapperAddress, to, amount),\n });\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\nexport function readTokenPairsContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsContract(registry));\n}\n\nexport function readTokenPairsLengthContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsLengthContract(registry));\n}\n\nexport function readTokenPairsSliceContract(\n client: PublicClient,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return client.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\nexport function readTokenPairContract(client: PublicClient, registry: Address, index: bigint) {\n return client.readContract(getTokenPairContract(registry, index));\n}\n\nexport function readConfidentialTokenAddressContract(\n client: PublicClient,\n registry: Address,\n tokenAddress: Address,\n) {\n return client.readContract(getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\nexport function readTokenAddressContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\nexport function readIsConfidentialTokenValidContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"2MA6BA,IAAa,EAAb,KAAqD,CACnD,GAEA,YAAY,EAA4B,CACtC,KAAKA,GAAgB,EAAO,YAC9B,CAEA,MAAM,YAA8B,CAClC,OAAO,KAAKA,GAAc,WAAW,CACvC,CAEA,MAAM,aAKJ,EACkF,CAClF,OAAO,KAAKA,GAAc,aAAa,CAAM,CAC/C,CAEA,MAAM,0BAA0B,EAAwC,CACtE,OAAO,KAAK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EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAwB,EAAU,CAAwB,CAAC,CACxF,CAEA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAiC,EAAU,CAAwB,CAAC,CACjG"}
1
+ {"version":3,"file":"index.cjs","names":["#publicClient","BaseSigner","#walletClient","#ethereum","#unsubscribeProvider","#subscribeToProvider","WalletNotConnectedError","#requireAccount","eip1193Subscribe","buildZamaConfig","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/viem/viem-provider.ts","../../../src/viem/viem-signer.ts","../../../src/viem/config.ts","../../../src/viem/contracts.ts"],"sourcesContent":["import type {\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Hex,\n PublicClient,\n} from \"viem\";\nimport type { GenericProvider, ReadContractConfig, TransactionReceipt } from \"../types\";\n\n/** Configuration for {@link ViemProvider}. */\nexport interface ViemProviderConfig {\n /** A viem `PublicClient` backing all read operations. */\n publicClient: PublicClient;\n}\n\n/**\n * Read-only {@link GenericProvider} backed by a viem `PublicClient`.\n *\n * Use this for integrations that only need public chain reads before the user has Pair with a\n * {@link ViemSigner} when wallet authority is required; the two can share a transport or point at\n * independent RPCs.\n *\n * @example\n * ```ts\n * const publicClient = createPublicClient({ chain: sepolia, transport: http(ALCHEMY_URL) });\n * const provider = new ViemProvider({ publicClient });\n * ```\n */\nexport class ViemProvider implements GenericProvider {\n readonly #publicClient: PublicClient;\n\n constructor(config: ViemProviderConfig) {\n this.#publicClient = config.publicClient;\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n return this.#publicClient.getChainId();\n }\n\n /** Execute a read-only call and return the decoded result. */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return this.#publicClient.readContract(config);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n return this.#publicClient.waitForTransactionReceipt({ hash });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#publicClient.getBlock();\n return block.timestamp;\n }\n}\n","import type {\n Account,\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n EIP1193Provider,\n WalletClient,\n Hex,\n} from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { writeContract } from \"viem/actions\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\n\n/**\n * Configuration for {@link ViemSigner}.\n *\n * The optional `ethereum` field is needed for `subscribe()` (EIP-1193\n * `accountsChanged` / `disconnect` events). It cannot be auto-extracted from\n * `walletClient` because viem's `custom(ethereum)` transport captures the\n * provider in a closure and does **not** expose `on` / `removeListener` on\n * `walletClient.transport`.\n *\n * If you omit `ethereum`, `subscribe()` returns a no-op. For automatic\n * wallet lifecycle handling, consider using `WagmiSigner` instead.\n */\nexport interface ViemSignerConfig {\n /** Wallet client for signing and write operations. */\n walletClient: WalletClient;\n /** Raw EIP-1193 provider enabling wallet lifecycle events; omit for a no-op `subscribe()`. */\n ethereum?: EIP1193Provider;\n}\n\n// viem requires uint values as bigints, but the KMS permit message carries them\n// as decimal strings. Convert by declared field type rather than by name so every\n// permit version is covered (V1 `durationDays`, V2 `durationSeconds`, ...).\nfunction messageWithBigIntUints(typedData: EIP712TypedData): Record<string, unknown> {\n const fields = (typedData.primaryType ? typedData.types[typedData.primaryType] : undefined) ?? [];\n const message: Record<string, unknown> = { ...typedData.message };\n for (const { name, type } of fields) {\n if (/^uint\\d*$/.test(type)) {\n message[name] = BigInt(message[name] as string | number | bigint);\n }\n }\n return message;\n}\n\nfunction walletAccountFromWalletClient(walletClient: WalletClient): WalletAccount | undefined {\n if (!walletClient.account || !walletClient.chain) {\n return undefined;\n }\n const address = getAddress(walletClient.account.address);\n return { address, chainId: walletClient.chain.id };\n}\n\n/**\n * {@link GenericSigner} backed by a viem `WalletClient` for EIP-712 signing and\n * write transactions. Pass `ethereum` in {@link ViemSignerConfig} to track\n * wallet lifecycle events.\n */\nexport class ViemSigner extends BaseSigner {\n readonly #walletClient: WalletClient;\n readonly #ethereum?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n\n constructor(config: ViemSignerConfig) {\n super(walletAccountFromWalletClient(config.walletClient));\n this.#walletClient = config.walletClient;\n this.#ethereum = config.ethereum;\n this.#unsubscribeProvider = this.#subscribeToProvider();\n }\n\n #requireAccount(operation: string): { walletClient: WalletClient; account: Account } {\n if (!this.#walletClient.account) {\n throw new WalletNotConnectedError(operation);\n }\n return { walletClient: this.#walletClient, account: this.#walletClient.account };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"signTypedData\");\n const { EIP712Domain: _, ...sigTypes } = typedData.types;\n return walletClient.signTypedData({\n account,\n primaryType: typedData.primaryType,\n types: sigTypes,\n domain: typedData.domain,\n message: messageWithBigIntUints(typedData),\n // Cast: EIP712TypedData is structural (`Eip712Like`), so viem cannot correlate primaryType/types/message and the inferred `message` collapses to `never`.\n } as Parameters<typeof walletClient.signTypedData>[0]);\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"writeContract\");\n return walletClient.writeContract({\n chain: walletClient.chain,\n account,\n ...config,\n } as Parameters<typeof writeContract>[1]);\n }\n\n #subscribeToProvider(): () => void {\n if (!this.#ethereum) {\n return () => {};\n }\n return eip1193Subscribe({\n provider: this.#ethereum,\n getInitialWalletAccount: () => walletAccountFromWalletClient(this.#walletClient),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n}\n","import type { FheChain } from \"../chains\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { buildZamaConfig } from \"../config/build\";\nimport { ViemProvider } from \"./viem-provider\";\nimport { ViemSigner } from \"./viem-signer\";\nimport type { ZamaConfigViem } from \"./types\";\n\n/** Create a {@link ZamaConfig} from viem clients. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigViem<TChains>,\n): ZamaConfig {\n const signer = new ViemSigner({ walletClient: params.walletClient, ethereum: params.ethereum });\n const provider = new ViemProvider({ publicClient: params.publicClient });\n return buildZamaConfig(signer, provider, params);\n}\n","import type { PublicClient, WalletClient, Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\n// ── Helpers ────────────────────────────────────────────────\n\nfunction requireAccount(client: WalletClient) {\n if (!client.account) {\n throw new TypeError(\"WalletClient has no account\");\n }\n return client.account;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via a viem client. */\nexport function readConfidentialBalanceOfContract(\n client: PublicClient,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return client.readContract(confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via a viem client. */\nexport function readUnderlyingTokenContract(client: PublicClient, wrapperAddress: Address) {\n return client.readContract(underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via a viem client. */\nexport function readSupportsInterfaceContract(\n client: PublicClient,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return client.readContract(supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via a viem wallet client. */\nexport function writeConfidentialTransferContract(\n client: WalletClient,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via a viem wallet client. */\nexport function writeUnwrapContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via a viem wallet client. */\nexport function writeUnwrapFromBalanceContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance),\n });\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via a viem wallet client. */\nexport function writeFinalizeUnwrapContract(\n client: WalletClient,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n });\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via a viem wallet client. */\nexport function writeSetOperatorContract(\n client: WalletClient,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...setOperatorContract(tokenAddress, operator, until),\n });\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via a viem wallet client. */\nexport function writeWrapContract(\n client: WalletClient,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...wrapContract(wrapperAddress, to, amount),\n });\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via a viem client. */\nexport function readTokenPairsContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via a viem client. */\nexport function readTokenPairsLengthContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via a viem client. */\nexport function readTokenPairsSliceContract(\n client: PublicClient,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return client.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via a viem client. */\nexport function readTokenPairContract(client: PublicClient, registry: Address, index: bigint) {\n return client.readContract(getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via a viem client. */\nexport function readConfidentialTokenAddressContract(\n client: PublicClient,\n registry: Address,\n tokenAddress: Address,\n) {\n return client.readContract(getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via a viem client. */\nexport function readTokenAddressContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via a viem client. */\nexport function readIsConfidentialTokenValidContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"oMA6BA,IAAa,EAAb,KAAqD,CACnD,GAEA,YAAY,EAA4B,CACtC,KAAKA,GAAgB,EAAO,YAC9B,CAGA,MAAM,YAA8B,CAClC,OAAO,KAAKA,GAAc,WAAW,CACvC,CAGA,MAAM,aAKJ,EACkF,CAClF,OAAO,KAAKA,GAAc,aAAa,CAAM,CAC/C,CAGA,MAAM,0BAA0B,EAAwC,CACtE,OAAO,KAAKA,GAAc,0BAA0B,CAAE,MAAK,CAAC,CAC9D,CAGA,MAAM,mBAAqC,CAEzC,OAAO,MADa,KAAKA,GAAc,SAAS,EAAA,CACnC,SACf,CACF,ECvBA,SAAS,EAAuB,EAAqD,CACnF,IAAM,GAAU,EAAU,YAAc,EAAU,MAAM,EAAU,aAAe,IAAA,KAAc,CAAC,EAC1F,EAAmC,CAAE,GAAG,EAAU,OAAQ,EAChE,IAAK,GAAM,CAAE,OAAM,UAAU,EACvB,YAAY,KAAK,CAAI,IACvB,EAAQ,GAAQ,OAAO,EAAQ,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B,EAAuB,CAAe,CAC5F,CAAC,CACH,CAGA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAO,cAAc,CAC1B,MAAO,EAAO,MACd,QAAS,EAAe,CAAM,EAC9B,GAAGC,EAAAA,EAAoB,EAAc,EAAU,CAAK,CACtD,CAAC,CACH,CAGA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAO,cAAc,CAC1B,MAAO,EAAO,MACd,QAAS,EAAe,CAAM,EAC9B,GAAGC,EAAAA,EAAa,EAAgB,EAAI,CAAM,CAC5C,CAAC,CACH,CAKA,SAAgB,EAAuB,EAAsB,EAAmB,CAC9E,OAAO,EAAO,aAAaC,EAAAA,EAAsB,CAAQ,CAAC,CAC5D,CAGA,SAAgB,EAA6B,EAAsB,EAAmB,CACpF,OAAO,EAAO,aAAaC,EAAAA,EAA4B,CAAQ,CAAC,CAClE,CAGA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAA2B,EAAU,EAAW,CAAO,CAAC,CACrF,CAGA,SAAgB,EAAsB,EAAsB,EAAmB,EAAe,CAC5F,OAAO,EAAO,aAAaC,EAAAA,EAAqB,EAAU,CAAK,CAAC,CAClE,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAoC,EAAU,CAAY,CAAC,CACxF,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAwB,EAAU,CAAwB,CAAC,CACxF,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAiC,EAAU,CAAwB,CAAC,CACjG"}
@@ -1,4 +1,4 @@
1
- import { S as WriteFunctionName, b as WriteContractArgs, d as WalletAccount, h as ContractAbi, m as WalletAccountStore, p as WalletAccountListener, u as GenericSigner, x as WriteContractConfig, zt as EIP712TypedData } from "./types-CELdIAFG.js";
1
+ import { Lt as EIP712TypedData, S as WriteFunctionName, b as WriteContractArgs, d as WalletAccount, h as ContractAbi, m as WalletAccountStore, p as WalletAccountListener, u as GenericSigner, x as WriteContractConfig } from "./types-CWPSTRF6.js";
2
2
  import { Hex } from "viem";
3
3
  //#region src/signer/wallet-account-store.d.ts
4
4
  /**
@@ -12,6 +12,7 @@ import { Hex } from "viem";
12
12
  declare class MutableWalletAccountStore implements WalletAccountStore {
13
13
  #private;
14
14
  constructor(initial?: WalletAccount);
15
+ /** Return the current wallet account snapshot, or `undefined` when none is set. */
15
16
  getSnapshot(): WalletAccount | undefined;
16
17
  /**
17
18
  * Whether the store has received at least one snapshot (via the constructor
@@ -26,6 +27,11 @@ declare class MutableWalletAccountStore implements WalletAccountStore {
26
27
  * subscriber otherwise.
27
28
  */
28
29
  setSnapshot(next: WalletAccount | undefined): void;
30
+ /**
31
+ * Register a listener for wallet account changes, emitting the current
32
+ * snapshot immediately if one exists.
33
+ * @returns An unsubscribe function.
34
+ */
29
35
  subscribe(listener: WalletAccountListener): () => void;
30
36
  }
31
37
  /**
@@ -48,15 +54,22 @@ declare function createWalletAccountStore(initial?: WalletAccount): MutableWalle
48
54
  */
49
55
  declare abstract class BaseSigner implements GenericSigner, Disposable {
50
56
  #private;
57
+ /** Observable wallet account readiness state. */
51
58
  readonly walletAccount: MutableWalletAccountStore;
52
59
  constructor(initial?: WalletAccount);
60
+ /** Return the connected wallet account or throw {@link WalletNotConnectedError}. */
53
61
  requireWalletAccount(operation: string): WalletAccount;
62
+ /** Sign EIP-712 typed data (used for decrypt authorization). */
54
63
  abstract signTypedData(typedData: EIP712TypedData): Promise<Hex>;
64
+ /** Send a write transaction and return the tx hash. */
55
65
  abstract writeContract<const TAbi extends ContractAbi, TFunctionName extends WriteFunctionName<TAbi>, const TArgs extends WriteContractArgs<TAbi, TFunctionName>>(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex>;
66
+ /** Release adapter-owned wallet watchers or provider event listeners; idempotent. */
56
67
  dispose(): void;
68
+ /** `Disposable` support; delegates to {@link BaseSigner.dispose}. */
57
69
  [Symbol.dispose](): void;
70
+ /** Subclass cleanup hook, invoked once on the first {@link BaseSigner.dispose} call. */
58
71
  protected onDispose(): void;
59
72
  }
60
73
  //#endregion
61
74
  export { MutableWalletAccountStore as n, createWalletAccountStore as r, BaseSigner as t };
62
- //# sourceMappingURL=base-signer-Ds8CoYy0.d.ts.map
75
+ //# sourceMappingURL=base-signer-BvL-jMNO.d.ts.map