@zama-fhe/sdk 3.7.0-beta.2 → 3.7.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/chains/index.cjs +1 -1
- package/dist/cjs/chains.cjs +1 -1
- package/dist/cjs/chains.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/node/index.cjs +1 -1
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/esm/base-signer-CwsN9lXD.js +2 -0
- package/dist/esm/{base-signer-D5Cwv7yb.js.map → base-signer-CwsN9lXD.js.map} +1 -1
- package/dist/esm/{base-signer-DIYZwDnc.d.ts → base-signer-D902THgk.d.ts} +2 -2
- package/dist/esm/chains/index.d.ts +2 -2
- package/dist/esm/chains/index.js +1 -1
- package/dist/esm/{chains-ByyCdrrd.js → chains-iPpnjXql.js} +2 -2
- package/dist/esm/{chains-ByyCdrrd.js.map → chains-iPpnjXql.js.map} +1 -1
- package/dist/esm/cleartext/index.d.ts +2 -2
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-PCpNqRGV.js → cleartext-B58fIRPQ.js} +2 -2
- package/dist/esm/{cleartext-PCpNqRGV.js.map → cleartext-B58fIRPQ.js.map} +1 -1
- package/dist/esm/{cleartext-3HOk1BAg.d.ts → cleartext-B6vrnBzO.d.ts} +2 -2
- package/dist/esm/{encryption-BKoalB4o.js → encryption-6AVd-82z.js} +2 -2
- package/dist/esm/{encryption-BKoalB4o.js.map → encryption-6AVd-82z.js.map} +1 -1
- package/dist/esm/{erc165-DbMOt-s6.js → erc165-rAtrIcS8.js} +2 -2
- package/dist/esm/{erc165-DbMOt-s6.js.map → erc165-rAtrIcS8.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +4 -4
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/{fhevm-relayer-CtrnKjJf.js → fhevm-relayer-Y5XYNOcs.js} +2 -2
- package/dist/esm/{fhevm-relayer-CtrnKjJf.js.map → fhevm-relayer-Y5XYNOcs.js.map} +1 -1
- package/dist/esm/{index-ijgDL4IC.d.ts → index-Cdbp_93f.d.ts} +24 -4
- package/dist/esm/{index-BHrjck_q.d.ts → index-CsuDB4UI.d.ts} +4 -4
- package/dist/esm/{index-DJYq1rAB.d.ts → index-DlpdjcMQ.d.ts} +1542 -1091
- package/dist/esm/index.d.ts +108 -8
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.d.ts +5 -5
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/node/index.js.map +1 -1
- package/dist/esm/query/index.d.ts +4 -495
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/{relayer-CVKO9GmQ.js → relayer-C3jVhqSK.js} +2 -2
- package/dist/esm/{relayer-CVKO9GmQ.js.map → relayer-C3jVhqSK.js.map} +1 -1
- package/dist/esm/{token-CRJ8eCr7.js → token-CBG_zTyz.js} +2 -2
- package/dist/esm/{token-CRJ8eCr7.js.map → token-CBG_zTyz.js.map} +1 -1
- package/dist/esm/{types-Bz5-wHPv.d.ts → types-Crf7ymyj.d.ts} +2 -2
- package/dist/esm/{types-v0_sfkli.d.ts → types-CuldbZne.d.ts} +3 -3
- package/dist/esm/{types-CI6BtpB7.d.ts → types-DnJSNoEC.d.ts} +3 -3
- package/dist/esm/{validation-BRu06AM_.js → validation-ClSvPh6P.js} +2 -2
- package/dist/esm/{validation-BRu06AM_.js.map → validation-ClSvPh6P.js.map} +1 -1
- package/dist/esm/vaults/index.d.ts +2 -3
- package/dist/esm/vaults/index.js +1 -1
- package/dist/esm/viem/index.d.ts +4 -4
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/web/index.d.ts +1 -1
- package/dist/esm/web/index.js +1 -1
- package/dist/esm/{wrapped-token-BOtzaSAY.js → wrapped-token-BpvG7nqK.js} +2 -2
- package/dist/esm/{wrapped-token-BOtzaSAY.js.map → wrapped-token-BpvG7nqK.js.map} +1 -1
- package/package.json +1 -1
- package/dist/esm/base-signer-D5Cwv7yb.js +0 -2
- package/dist/esm/invalidation-CJ-pzOUG.d.ts +0 -46
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["ZamaError","ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","DecryptionFailedError","NoCiphertextError","RelayerRequestFailedError","SigningRejectedError","SigningFailedError","RpcRateLimitError","InvalidTransportKeyPairError","RevokedKmsContextError","isInvalidTransportKeyPairMessage","isRevokedKmsContextError","isNotEntitledMessage","parseHandleFromMessage","hasStructuredRpcRateLimitSignal","extractRetryAfter","extractHttpStatus","isRpcRateLimitError","isRelayerError","isRelayerTimeoutError","ZamaError","extractHttpStatus","isRelayerTimeoutError","isRelayerError","RelayerRequestFailedError","extractRetryAfter","EncryptionFailedError","buildZamaConfig","#signer","#provider","#cachingService","#credentialService","#logger","#emitEvent","requireConfigured","ZamaSDKEvents","#requireCredentialService","requireChainAlignment","#failPermit","#clearDecryptCacheForRequester","requireAlignedWalletAccount","swallow","#signer","#provider","#delegationService","requireConfigured","#requireSigner","requireAlignedWalletAccount","#signer","#provider","#router","#decryptionService","requireConfigured","#requireDecryptionService","requireAlignedWalletAccount","#offlineService","#credentialService","z","checksummedAddress","#storage","#logger","#decryptNamespace","#decryptKeysNamespace","#buildStorageKey","#indexWriteQueue","#addToIndex","#doDelete","#doClearForRequester","#doClearAll","#readIndex","DecryptionFailedError","checksum","#cache","#credentialService","#delegationService","#router","#emitEvent","#decrypt","#withPropagationRetry","#assertAllDelegationsActive","#setHandleResult","isFatalBatchError","#missingBatchItem","#toZamaError","pLimit","#decryptValues","isInvalidTransportKeyPairMessage","isEncryptedValueZero","isRpcRateLimitError","#rpcRateLimitError","chunkHandlesByBitBudget","ZamaSDKEvents","#runDecryptRequests","RevokedKmsContextError","SigningFailedError","ZamaError","toError","#decryptRequest","DecryptionFailedError","RpcRateLimitError","extractRetryAfter","extractRevertErrorName","#router","#provider","#emitEvent","#logger","#submitAclTransaction","submitTransaction","#throwAclRevertIfMatched","TransactionRevertedError","#router","#emitEvent","ZamaSDKEvents","toError","#signer","#router","#cachingService","#credentialService","#logger","#walletAccountListeners","#unsubscribeSigner","#handleWalletAccountChange","swallow","z","checksummedAddress","unixSeconds","hex","#provider","#router","#encryption","parseSchema","ConfigurationError","#buildCalldata","#buildConfidentialTransfer","#buildConfidentialTransferFrom","#buildSetOperator","#buildUnwrap","#buildUnwrapAll","#buildFinalizeUnwrap","#buildApproveUnderlying","#buildWrap","#buildTransferAndCall","#buildDelegateDecryption","#buildRevokeDelegation","unhandled","EncryptionFailedError","confidentialTransferContract","confidentialTransferFromContract","setOperatorContract","unwrapContract","confidentialBalanceOfContract","unwrapFromBalanceContract","finalizeUnwrapContract","approveContract","wrapContract","transferAndCallContract","ConfigurationError","parseSchema","DerivationSecretSchema","DerivationSecretHolder","#router","#registryTTL","#registryAddresses","#onEvent","#logger","#cachingService","#lifecycleService","#encryptionService","#decryptionService","#credentialService","#delegationService","#offlineService","WrappersRegistry","CredentialService","Token","WrappedToken"],"sources":["../../src/errors/match.ts","../../src/errors/entitlement.ts","../../src/errors/delegation.ts","../../src/errors/decrypt.ts","../../src/errors/encrypt.ts","../../src/abi/acl.abi.ts","../../src/contracts/acl.ts","../../src/contracts/constants.ts","../../src/config/create.ts","../../src/namespaces/permits.ts","../../src/namespaces/delegations.ts","../../src/namespaces/decryption.ts","../../src/namespaces/offline.ts","../../src/storage/chrome-session-storage.ts","../../src/services/caching-service.ts","../../src/credentials/decrypt-permit.ts","../../src/services/decryption-service.ts","../../src/errors/acl-revert.ts","../../src/services/delegation-service.ts","../../src/services/encryption-service.ts","../../src/services/lifecycle-service.ts","../../src/schemas/offline.ts","../../src/services/offline-service.ts","../../src/zama-sdk.ts"],"sourcesContent":["import { ZamaError } from \"./base\";\nimport type { ZamaErrorCode } from \"./base\";\nimport type { ChainMismatchError } from \"./chain\";\nimport type {\n KeyWrappingError,\n NoCiphertextError,\n PreparedPermitChainMismatchError,\n PreparedPermitExpiredError,\n TransportKeyPairChangedError,\n TransportKeyPairExpiredError,\n InvalidTransportKeyPairError,\n RevokedKmsContextError,\n} from \"./credential\";\nimport type {\n AclPausedError,\n DelegationContractIsSelfError,\n DelegationCooldownError,\n DelegationDelegateEqualsContractError,\n DelegationExpirationTooSoonError,\n DelegationExpiredError,\n DelegationExpiryUnchangedError,\n DelegationNotFoundError,\n DelegationNotPropagatedError,\n DelegationSelfNotAllowedError,\n} from \"./delegation\";\nimport type {\n DecryptionFailedError,\n EncryptionFailedError,\n EncryptOffloadUnavailableError,\n} from \"./encryption\";\nimport type {\n BalanceCheckUnavailableError,\n ERC20ReadFailedError,\n InsufficientAllowanceError,\n InsufficientConfidentialBalanceError,\n InsufficientERC20BalanceError,\n} from \"./balance\";\nimport type { ConfigurationError, RelayerRequestFailedError } from \"./relayer\";\nimport type { NotEntitledError } from \"./entitlement\";\nimport type { RpcRateLimitError } from \"./rpc\";\nimport type {\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n WalletNotConnectedError,\n} from \"./signer\";\nimport type { SigningFailedError, SigningRejectedError } from \"./signing\";\nimport type { TransactionRevertedError } from \"./transaction\";\nimport type { UnshieldAlreadyFinalizedError } from \"./unshield\";\n\n/**\n * Maps each {@link ZamaErrorCode} to the error class thrown with that code, so\n * {@link matchZamaError} handlers receive the matched subtype instead of the base\n * `ZamaError`.\n */\nexport interface ErrorForCode {\n /** Thrown for {@link ZamaErrorCode.SigningRejected}. */\n [ZamaErrorCode.SigningRejected]: SigningRejectedError;\n /** Thrown for {@link ZamaErrorCode.SigningFailed}. */\n [ZamaErrorCode.SigningFailed]: SigningFailedError;\n /** Thrown for {@link ZamaErrorCode.EncryptionFailed}. */\n [ZamaErrorCode.EncryptionFailed]: EncryptionFailedError;\n /** Thrown for {@link ZamaErrorCode.DecryptionFailed}. */\n [ZamaErrorCode.DecryptionFailed]: DecryptionFailedError;\n /** Thrown for {@link ZamaErrorCode.EncryptOffloadUnavailable}. */\n [ZamaErrorCode.EncryptOffloadUnavailable]: EncryptOffloadUnavailableError;\n /** Thrown for {@link ZamaErrorCode.TransactionReverted}. */\n [ZamaErrorCode.TransactionReverted]: TransactionRevertedError;\n /** Thrown for {@link ZamaErrorCode.TransportKeyPairExpired}. */\n [ZamaErrorCode.TransportKeyPairExpired]: TransportKeyPairExpiredError;\n /** Thrown for {@link ZamaErrorCode.InvalidTransportKeyPair}. */\n [ZamaErrorCode.InvalidTransportKeyPair]: InvalidTransportKeyPairError;\n /** Thrown for {@link ZamaErrorCode.RevokedKmsContext}. */\n [ZamaErrorCode.RevokedKmsContext]: RevokedKmsContextError;\n /** Thrown for {@link ZamaErrorCode.NoCiphertext}. */\n [ZamaErrorCode.NoCiphertext]: NoCiphertextError;\n /** Thrown for {@link ZamaErrorCode.RelayerRequestFailed}. */\n [ZamaErrorCode.RelayerRequestFailed]: RelayerRequestFailedError;\n /** Thrown for {@link ZamaErrorCode.NotEntitled}. */\n [ZamaErrorCode.NotEntitled]: NotEntitledError;\n /** Thrown for {@link ZamaErrorCode.RpcRateLimited}. */\n [ZamaErrorCode.RpcRateLimited]: RpcRateLimitError;\n /** Thrown for {@link ZamaErrorCode.Configuration}. */\n [ZamaErrorCode.Configuration]: ConfigurationError;\n /** Thrown for {@link ZamaErrorCode.DelegationSelfNotAllowed}. */\n [ZamaErrorCode.DelegationSelfNotAllowed]: DelegationSelfNotAllowedError;\n /** Thrown for {@link ZamaErrorCode.DelegationCooldown}. */\n [ZamaErrorCode.DelegationCooldown]: DelegationCooldownError;\n /** Thrown for {@link ZamaErrorCode.DelegationNotFound}. */\n [ZamaErrorCode.DelegationNotFound]: DelegationNotFoundError;\n /** Thrown for {@link ZamaErrorCode.DelegationExpired}. */\n [ZamaErrorCode.DelegationExpired]: DelegationExpiredError;\n /** Thrown for {@link ZamaErrorCode.InsufficientConfidentialBalance}. */\n [ZamaErrorCode.InsufficientConfidentialBalance]: InsufficientConfidentialBalanceError;\n /** Thrown for {@link ZamaErrorCode.InsufficientERC20Balance}. */\n [ZamaErrorCode.InsufficientERC20Balance]: InsufficientERC20BalanceError;\n /** Thrown for {@link ZamaErrorCode.InsufficientAllowance}. */\n [ZamaErrorCode.InsufficientAllowance]: InsufficientAllowanceError;\n /** Thrown for {@link ZamaErrorCode.BalanceCheckUnavailable}. */\n [ZamaErrorCode.BalanceCheckUnavailable]: BalanceCheckUnavailableError;\n /** Thrown for {@link ZamaErrorCode.ERC20ReadFailed}. */\n [ZamaErrorCode.ERC20ReadFailed]: ERC20ReadFailedError;\n /** Thrown for {@link ZamaErrorCode.DelegationExpiryUnchanged}. */\n [ZamaErrorCode.DelegationExpiryUnchanged]: DelegationExpiryUnchangedError;\n /** Thrown for {@link ZamaErrorCode.DelegationDelegateEqualsContract}. */\n [ZamaErrorCode.DelegationDelegateEqualsContract]: DelegationDelegateEqualsContractError;\n /** Thrown for {@link ZamaErrorCode.DelegationContractIsSelf}. */\n [ZamaErrorCode.DelegationContractIsSelf]: DelegationContractIsSelfError;\n /** Thrown for {@link ZamaErrorCode.AclPaused}. */\n [ZamaErrorCode.AclPaused]: AclPausedError;\n /** Thrown for {@link ZamaErrorCode.DelegationExpirationTooSoon}. */\n [ZamaErrorCode.DelegationExpirationTooSoon]: DelegationExpirationTooSoonError;\n /** Thrown for {@link ZamaErrorCode.DelegationNotPropagated}. */\n [ZamaErrorCode.DelegationNotPropagated]: DelegationNotPropagatedError;\n /** Thrown for {@link ZamaErrorCode.ChainMismatch}. */\n [ZamaErrorCode.ChainMismatch]: ChainMismatchError;\n /** Thrown for {@link ZamaErrorCode.SignerNotConfigured}. */\n [ZamaErrorCode.SignerNotConfigured]: SignerNotConfiguredError;\n /** Thrown for {@link ZamaErrorCode.WalletNotConnected}. */\n [ZamaErrorCode.WalletNotConnected]: WalletNotConnectedError;\n /** Thrown for {@link ZamaErrorCode.WalletAccountNotReady}. */\n [ZamaErrorCode.WalletAccountNotReady]: WalletAccountNotReadyError;\n /** Thrown for {@link ZamaErrorCode.KeyWrappingFailed}. */\n [ZamaErrorCode.KeyWrappingFailed]: KeyWrappingError;\n /** Thrown for {@link ZamaErrorCode.TransportKeyPairChanged}. */\n [ZamaErrorCode.TransportKeyPairChanged]: TransportKeyPairChangedError;\n /** Thrown for {@link ZamaErrorCode.PreparedPermitChainMismatch}. */\n [ZamaErrorCode.PreparedPermitChainMismatch]: PreparedPermitChainMismatchError;\n /** Thrown for {@link ZamaErrorCode.PreparedPermitExpired}. */\n [ZamaErrorCode.PreparedPermitExpired]: PreparedPermitExpiredError;\n /** Thrown for {@link ZamaErrorCode.UnshieldAlreadyFinalized}. */\n [ZamaErrorCode.UnshieldAlreadyFinalized]: UnshieldAlreadyFinalizedError;\n}\n\n/**\n * Pattern-match on a {@link ZamaError} by its error code. Each handler receives the\n * error class for its code, so subclass fields are available without a cast.\n * Falls through to the `_` wildcard handler if no specific handler matches.\n * Returns `undefined` if the error is not a `ZamaError` and no `_` handler is provided.\n *\n * @example\n * ```ts\n * matchZamaError(error, {\n * SIGNING_REJECTED: () => toast(\"Please approve in wallet\"),\n * INSUFFICIENT_CONFIDENTIAL_BALANCE: (e) => toast(`Need ${e.requested}, have ${e.available}`),\n * RELAYER_REQUEST_FAILED: (e) => toast(`Relayer failed (${e.statusCode})`),\n * _: () => toast(\"Unknown error\"),\n * });\n * ```\n */\nexport function matchZamaError<R>(\n error: unknown,\n handlers: { [K in ZamaErrorCode]?: (error: ErrorForCode[K]) => R } & {\n _?: (error: unknown) => R;\n },\n): R | undefined {\n if (error instanceof ZamaError) {\n // `error.code` narrows the handler at runtime; the cast bridges the per-code param types.\n const handler = handlers[error.code] as ((error: ZamaError) => R) | undefined;\n if (handler) {\n return handler(error);\n }\n }\n return handlers._?.(error);\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * The signer (or delegator) lacks ACL permission to decrypt the encrypted value —\n * `persistAllowed` returned `false`. Terminal and **non-retryable**: the fix is\n * an on-chain grant (`FHE.allow`), or for indexers, to wait for a backfill once\n * the grant lands. Distinct from transient failures like {@link RpcRateLimitError}.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof NotEntitledError) {\n * // don't retry — wait for an ACL grant / backfill\n * }\n * }\n * ```\n */\nexport class NotEntitledError extends ZamaError {\n /** The encrypted value the actor is not entitled to decrypt. */\n readonly encryptedValue: string;\n /** The contract the encrypted value belongs to. */\n readonly contractAddress: string;\n /** The actor (signer or delegator) that lacks ACL permission. */\n readonly account: string;\n\n constructor(\n args: { encryptedValue: string; contractAddress: string; account: string },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.NotEntitled,\n `Account ${args.account} is not entitled to decrypt encrypted value ${args.encryptedValue} ` +\n `on contract ${args.contractAddress}. This is not a transient failure — ` +\n `the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,\n options,\n );\n this.name = \"NotEntitledError\";\n this.encryptedValue = args.encryptedValue;\n this.contractAddress = args.contractAddress;\n this.account = args.account;\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n// Delegation errors — thrown by SDK pre-flight checks and by delegation\n// transaction callsites when they map ACL Solidity revert reasons.\n\n/** Delegation cannot target self (delegate === msg.sender). */\nexport class DelegationSelfNotAllowedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationSelfNotAllowed, message, options);\n this.name = \"DelegationSelfNotAllowedError\";\n }\n}\n\n/** Only one delegate/revoke per (delegator, delegate, contract) per block. */\nexport class DelegationCooldownError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationCooldown, message, options);\n this.name = \"DelegationCooldownError\";\n }\n}\n\n/** No active delegation found for this (delegator, delegate, contract) tuple. */\nexport class DelegationNotFoundError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationNotFound, message, options);\n this.name = \"DelegationNotFoundError\";\n }\n}\n\n/** The delegation has expired. */\nexport class DelegationExpiredError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationExpired, message, options);\n this.name = \"DelegationExpiredError\";\n }\n}\n\n/** The new expiration date equals the current one. */\nexport class DelegationExpiryUnchangedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationExpiryUnchanged, message, options);\n this.name = \"DelegationExpiryUnchangedError\";\n }\n}\n\n/** Delegate address cannot be the contract address. */\nexport class DelegationDelegateEqualsContractError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationDelegateEqualsContract, message, options);\n this.name = \"DelegationDelegateEqualsContractError\";\n }\n}\n\n/** Contract address cannot be the sender address. */\nexport class DelegationContractIsSelfError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationContractIsSelf, message, options);\n this.name = \"DelegationContractIsSelfError\";\n }\n}\n\n/** The ACL contract is paused. */\nexport class AclPausedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.AclPaused, message, options);\n this.name = \"AclPausedError\";\n }\n}\n\n/** Expiration date is too soon (must be at least 1 hour in the future). */\nexport class DelegationExpirationTooSoonError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationExpirationTooSoon, message, options);\n this.name = \"DelegationExpirationTooSoonError\";\n }\n}\n\n/**\n * Delegation exists on L1 but hasn't propagated to the gateway yet.\n *\n * After calling `delegateForUserDecryption()`, the delegation is recorded on-chain\n * immediately. However, the gateway (deployed on Arbitrum) must sync this state\n * via cross-chain event propagation, which usually completes within ~10 blocks\n * (a few seconds).\n *\n * Calling `decryptBalanceAs` during this window will fail because the gateway's\n * `isHandleDelegatedForUserDecryption()` check reads from its own synced copy\n * of the ACL state, which hasn't been updated yet.\n *\n * **You rarely need to handle this directly:** the delegated-decrypt path rides\n * out the propagation window with a bounded internal retry (~30s), so a decrypt\n * issued right after the grant simply waits for sync. This error only surfaces\n * if the window outlasts the retry budget, or when retries are disabled via\n * `waitForPropagation: false`.\n *\n * **Note:** This error is raised as a best-effort heuristic — when a delegated\n * decryption receives an HTTP 500 from the relayer, the most likely cause is a\n * propagation delay. However, the same status code can occur if the gateway or\n * relayer experiences an unrelated internal error.\n */\nexport class DelegationNotPropagatedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationNotPropagated, message, options);\n this.name = \"DelegationNotPropagatedError\";\n }\n}\n","import type { ZamaError } from \"./base\";\nimport { DecryptionFailedError } from \"./encryption\";\nimport {\n InvalidTransportKeyPairError,\n NoCiphertextError,\n RevokedKmsContextError,\n} from \"./credential\";\nimport { RelayerRequestFailedError } from \"./relayer\";\nimport { DelegationNotPropagatedError } from \"./delegation\";\nimport { NotEntitledError } from \"./entitlement\";\nimport { RpcRateLimitError } from \"./rpc\";\nimport { SigningRejectedError, SigningFailedError } from \"./signing\";\nimport {\n extractHttpStatus,\n extractRetryAfter,\n hasStructuredRpcRateLimitSignal,\n isInvalidTransportKeyPairMessage,\n isNotEntitledMessage,\n isRelayerError,\n isRelayerTimeoutError,\n isRevokedKmsContextError,\n isRpcRateLimitError,\n parseHandleFromMessage,\n} from \"../utils/error\";\n\n/**\n * Context the caller supplies so a not-entitled / delegation failure can be\n * mapped precisely. The request context (`contractAddress` / `account`) is not\n * present on the raw error, so it is injected here.\n */\nexport interface DecryptErrorContext {\n isDelegated?: boolean;\n contractAddress?: string;\n /** The ACL actor (signer, or delegator for delegated decrypt). */\n account?: string;\n}\n\n/**\n * Every typed SDK error `wrapDecryptError` may see on its way in (from a prior\n * classification, a worker rethrow, or a caller-level retry) and must pass\n * through unchanged rather than collapse into terminal `DecryptionFailedError`.\n * A single source of truth for the early-return check below and for the\n * `errors.test.ts` \"every typed cause passes through unchanged\" test — so a\n * class dropped from this array is caught by that test instead of silently\n * falling through to the generic fallback.\n *\n * This is a fixed, decrypt-scoped subset of the taxonomy maintained by hand\n * (unlike {@link RETRYABLE_BY_CODE} in `base.ts`, it has no `Complete<>` tie\n * to `ZamaErrorCode`) — a new decrypt-path error class must be added here\n * explicitly, since there's no compiler check forcing it.\n */\nexport const DECRYPT_PASSTHROUGH_ERROR_TYPES = [\n DecryptionFailedError,\n NoCiphertextError,\n RelayerRequestFailedError,\n DelegationNotPropagatedError,\n SigningRejectedError,\n SigningFailedError,\n NotEntitledError,\n RpcRateLimitError,\n InvalidTransportKeyPairError,\n RevokedKmsContextError,\n] as const;\n\n/**\n * The single decryption-error classifier. Maps a caught error to the right typed\n * SDK error: not-entitled (ACL), consumer RPC rate-limit, NoCiphertext (400),\n * DelegationNotPropagated (delegated 500 *or* a delegated ACL denial, which is\n * transient), RelayerRequestFailed (other HTTP), or the generic DecryptionFailed\n * fallback.\n *\n * Errors that are already typed SDK errors are returned as-is so callers can\n * still match the original cause. All structured signals (codes, status, cause\n * chain) are read from the error itself.\n */\nexport function wrapDecryptError(\n error: unknown,\n fallbackMessage: string,\n ctx: DecryptErrorContext = {},\n): ZamaError {\n if (DECRYPT_PASSTHROUGH_ERROR_TYPES.some((ErrorType) => error instanceof ErrorType)) {\n return error as ZamaError;\n }\n\n const message = error instanceof Error ? error.message : fallbackMessage;\n\n // Stale transport key pair the relayer can't re-derive (post KMS/TKMS rotation).\n // Typed so the decrypt path can evict the vault entry and regenerate on retry.\n if (error instanceof Error && isInvalidTransportKeyPairMessage(error.message)) {\n return new InvalidTransportKeyPairError(error.message, { cause: error });\n }\n\n // The permit's KMS context was revoked on-chain (InvalidKmsContext revert).\n // Typed so the decrypt path can evict the dead permit, re-grant, and retry once.\n if (isRevokedKmsContextError(error)) {\n return new RevokedKmsContextError(\n \"The permit's KMS context has been revoked on-chain, so the permit is no longer usable. \" +\n \"The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry \" +\n \"failed the same way. The on-chain validity check is cached for up to 15 minutes, so a \" +\n \"just-revoked context can keep failing across that window. Retry after the window; the \" +\n \"SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.\",\n { cause: error },\n );\n }\n\n // Actor not entitled (ACL). The relayer throws a message-only Error; the handle\n // is parseable from it and the contract/account come from the request context\n // the caller holds.\n if (error instanceof Error && isNotEntitledMessage(error.message)) {\n // On the delegated path the \"not entitled\" verdict comes from the\n // *delegator's* `persistAllowed` L1 read, which has no staleness tolerance:\n // it returns false *transiently* when the delegation has just landed or the\n // consumer's RPC serves a lagging block. Terminal `NotEntitledError` (\"never\n // retry\") would be the wrong signal for that propagation window, so — mirroring\n // the delegated-500 branch below — surface the retryable\n // `DelegationNotPropagatedError` instead. A direct signer denial (non-\n // delegated) stays terminal `NotEntitledError`.\n if (ctx.isDelegated) {\n return new DelegationNotPropagatedError(\n \"Delegated decryption was denied by the on-chain ACL check. \" +\n \"This is most commonly caused by the delegation not having propagated yet, or by the \" +\n \"RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few \" +\n \"seconds) and the SDK retries across that window; seeing this means it did not sync in time. \" +\n \"Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may \" +\n \"genuinely lack the on-chain ACL grant.\",\n { cause: error },\n );\n }\n return new NotEntitledError(\n {\n encryptedValue: parseHandleFromMessage(error.message) ?? \"\",\n contractAddress: ctx.contractAddress ?? \"\",\n account: ctx.account ?? \"\",\n },\n { cause: error },\n );\n }\n\n // Consumer's RPC provider throttling an on-chain read. An unambiguous\n // structured signal (-32005 / viem `status: 429`) wins over any HTTP status;\n // relayer-origin errors are `@fhevm/sdk` `Relayer*` classes and are excluded by\n // `isRelayerError`, staying RelayerRequestFailedError below.\n if (hasStructuredRpcRateLimitSignal(error)) {\n return new RpcRateLimitError(message, { cause: error, retryAfter: extractRetryAfter(error) });\n }\n\n const statusCode = extractHttpStatus(error);\n\n // A message-only throttle (\"Too Many Requests\" / \"rate limit\") is trusted only\n // when no HTTP status is present — otherwise the status classification (e.g. a\n // relayer error whose body mentions a rate limit) takes precedence.\n if (statusCode === undefined && isRpcRateLimitError(error)) {\n return new RpcRateLimitError(message, { cause: error, retryAfter: extractRetryAfter(error) });\n }\n\n if (statusCode === 400) {\n return new NoCiphertextError(\n error instanceof Error ? error.message : \"No ciphertext for this account\",\n { cause: error },\n );\n }\n\n if (ctx.isDelegated && statusCode === 500) {\n return new DelegationNotPropagatedError(\n \"Delegated decryption failed with a server error. \" +\n \"This is most commonly caused by the delegation not having propagated to the gateway yet. \" +\n \"Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries \" +\n \"across that window; seeing this means it did not sync in time — retry shortly. \" +\n \"If the error persists, the gateway or relayer may be experiencing an unrelated issue.\",\n { cause: error },\n );\n }\n\n if (isRelayerError(error) || statusCode !== undefined) {\n return new RelayerRequestFailedError(message, statusCode, {\n cause: error,\n retryAfter: extractRetryAfter(error),\n // A relayer timeout carries no HTTP status but is safe to retry; force\n // `retryable` so it isn't misclassified as terminal. Other relayer errors\n // fall back to the status-based default (429 → retryable).\n retryable: isRelayerTimeoutError(error) || undefined,\n });\n }\n\n return new DecryptionFailedError(fallbackMessage, { cause: error });\n}\n","import {\n extractHttpStatus,\n extractRetryAfter,\n isRelayerError,\n isRelayerTimeoutError,\n} from \"../utils/error\";\nimport { ZamaError } from \"./base\";\nimport { EncryptionFailedError } from \"./encryption\";\nimport { RelayerRequestFailedError } from \"./relayer\";\n\n/**\n * Inspect a caught encryption error for an `@fhevm/sdk` relayer origin or HTTP\n * status code and return the appropriate typed SDK error. Relayer transport\n * failures without a status, plus HTTP failures from the relayer or an\n * intermediary such as Cloudflare/Kong, surface as\n * {@link RelayerRequestFailedError} instead of collapsing into a generic\n * {@link EncryptionFailedError}.\n *\n * Errors that are already typed SDK errors are returned as-is so callers can\n * still match the original cause.\n *\n * The relayer's HTTP status may surface as `status` or `statusCode` anywhere in\n * the cause chain; {@link extractHttpStatus} walks the chain for either, mirroring\n * {@link wrapDecryptError}.\n */\nexport function wrapEncryptError(error: unknown, fallbackMessage: string): ZamaError {\n if (error instanceof ZamaError) {\n return error;\n }\n\n const statusCode = extractHttpStatus(error);\n // A relayer timeout carries no HTTP status but is safe to retry — surface it as\n // a retryable RelayerRequestFailedError rather than a terminal EncryptionFailed.\n const isTimeout = isRelayerTimeoutError(error);\n\n if (statusCode !== undefined || isRelayerError(error)) {\n return new RelayerRequestFailedError(\n error instanceof Error ? error.message : fallbackMessage,\n statusCode,\n { cause: error, retryAfter: extractRetryAfter(error), retryable: isTimeout || undefined },\n );\n }\n\n return new EncryptionFailedError(fallbackMessage, { cause: error });\n}\n","// DO NOT EDIT: generated by `pnpm abi:build` from\n// contracts/out/Impl.sol/IACL.json.\n// Regenerate after `pnpm contracts:build`; `pnpm abi:check` enforces this in CI.\nexport const aclAbi = [\n {\n type: \"function\",\n name: \"allow\",\n inputs: [\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"allowForDecryption\",\n inputs: [{ name: \"handlesList\", type: \"bytes32[]\", internalType: \"bytes32[]\" }],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"allowTransient\",\n inputs: [\n { name: \"ciphertext\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"cleanTransientStorage\",\n inputs: [],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"delegateForUserDecryption\",\n inputs: [\n { name: \"delegate\", type: \"address\", internalType: \"address\" },\n { name: \"contractAddress\", type: \"address\", internalType: \"address\" },\n { name: \"expirationDate\", type: \"uint64\", internalType: \"uint64\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getUserDecryptionDelegationExpirationDate\",\n inputs: [\n { name: \"delegator\", type: \"address\", internalType: \"address\" },\n { name: \"delegate\", type: \"address\", internalType: \"address\" },\n { name: \"contractAddress\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint64\", internalType: \"uint64\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAccountDenied\",\n inputs: [{ name: \"account\", type: \"address\", internalType: \"address\" }],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAllowed\",\n inputs: [\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAllowedForDecryption\",\n inputs: [{ name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" }],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isHandleDelegatedForUserDecryption\",\n inputs: [\n { name: \"delegator\", type: \"address\", internalType: \"address\" },\n { name: \"delegate\", type: \"address\", internalType: \"address\" },\n { name: \"contractAddress\", type: \"address\", internalType: \"address\" },\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"multicall\",\n inputs: [{ name: \"data\", type: \"bytes[]\", internalType: \"bytes[]\" }],\n outputs: [{ name: \"results\", type: \"bytes[]\", internalType: \"bytes[]\" }],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"persistAllowed\",\n inputs: [\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"revokeDelegationForUserDecryption\",\n inputs: [\n { name: \"delegate\", type: \"address\", internalType: \"address\" },\n { name: \"contractAddress\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n] as const;\n","import type { Address } from \"viem\";\nimport { aclAbi } from \"../abi/acl.abi\";\n\n/**\n * Returns the contract config to delegate user decryption rights.\n *\n * @example\n * ```ts\n * const txHash = await signer.writeContract(\n * delegateForUserDecryptionContract(aclAddress, delegateAddress, contractAddress, expirationDate),\n * );\n * ```\n */\nexport function delegateForUserDecryptionContract(\n aclAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n expirationDate: bigint,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"delegateForUserDecryption\",\n args: [delegateAddress, contractAddress, expirationDate],\n } as const;\n}\n\n/**\n * Returns the contract config to revoke a user decryption delegation.\n *\n * @example\n * ```ts\n * const txHash = await signer.writeContract(\n * revokeDelegationContract(aclAddress, delegateAddress, contractAddress),\n * );\n * ```\n */\nexport function revokeDelegationContract(\n aclAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"revokeDelegationForUserDecryption\",\n args: [delegateAddress, contractAddress],\n } as const;\n}\n\n/**\n * Returns the contract config to read the delegation expiry date.\n *\n * @example\n * ```ts\n * const expiry = await provider.readContract(\n * getDelegationExpiryContract(aclAddress, delegatorAddress, delegateAddress, contractAddress),\n * );\n * ```\n */\nexport function getDelegationExpiryContract(\n aclAddress: Address,\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"getUserDecryptionDelegationExpirationDate\",\n args: [delegatorAddress, delegateAddress, contractAddress],\n } as const;\n}\n\n/**\n * Returns the contract config to check if a specific handle is delegated.\n *\n * @example\n * ```ts\n * const isDelegated = await provider.readContract(\n * isHandleDelegatedContract(aclAddress, delegatorAddress, delegateAddress, contractAddress, handle),\n * );\n * ```\n */\nexport function isHandleDelegatedContract(\n aclAddress: Address,\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n handle: `0x${string}`,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, handle],\n } as const;\n}\n","/** uint64 max — represents a permanent (no-expiry) delegation. */\nexport const MAX_UINT64 = 2n ** 64n - 1n;\n\n/**\n * uint48 max — represents a permanent (no-expiry) operator approval.\n * `setOperator`'s `until` argument is a `uint48` timestamp; this fits in a\n * JS number (< 2^53) and mirrors {@link MAX_UINT64}'s \"permanent\" role.\n */\nexport const MAX_UINT48 = 2 ** 48 - 1;\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"./build\";\nimport type { ZamaConfig, ZamaConfigGeneric } from \"./types\";\n\n/**\n * Create a {@link ZamaConfig} from a custom {@link GenericSigner} and\n * {@link GenericProvider}. Use this when the built-in adapter paths\n * (`@zama-fhe/sdk/viem`, `@zama-fhe/sdk/ethers`, `@zama-fhe/react-sdk/wagmi`)\n * don't cover your setup — e.g. a server-side relayer that implements\n * `GenericSigner` directly.\n *\n * @example\n * ```ts\n * import { createConfig, memoryStorage } from \"@zama-fhe/sdk\";\n * import { web } from \"@zama-fhe/sdk/web\";\n * import { sepolia } from \"@zama-fhe/sdk/chains\";\n *\n * const config = createConfig({\n * chains: [sepolia],\n * signer: myCustomSigner,\n * provider: myCustomProvider,\n * storage: memoryStorage,\n * relayers: { [sepolia.id]: web() },\n * });\n * const sdk = new ZamaSDK(config);\n * ```\n */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigGeneric<TChains>,\n): ZamaConfig {\n return buildZamaConfig(params.signer, params.provider, params);\n}\n","import { getAddress, type Address, type Hex } from \"viem\";\nimport type { CredentialService } from \"../credentials/credential-service\";\nimport type { PreparedPermit } from \"../credentials/types\";\nimport { requireConfigured } from \"../errors\";\nimport type { PermitOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { ZamaSDKEvents } from \"../events/sdk-events\";\nimport type { CachingService } from \"../services/caching-service\";\nimport type { GenericLogger, GenericProvider, GenericSigner } from \"../types\";\nimport { swallow } from \"../utils\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\n\n/**\n * Public namespace for permit and transport-key-pair management.\n *\n * Exposed as `sdk.permits`. Owns the SDK-level guards (chain alignment, empty-array\n * short-circuit, decrypt-cache invalidation) and delegates the actual work to the\n * internal {@link CredentialService}.\n *\n * The namespace is named `permits` because the user-facing concept is the signed-permit\n * store. The transport key pair is invisible plumbing — there is no `getTransportKeyPair()`\n * surfaced; the key pair exists to sign permits and is created automatically when needed.\n * {@link clear} wipes both the permit store and the transport key pair (permits\n * cascade-delete with the key pair).\n *\n * When `transportKeyPairScope` is configured (opt-in shared-tenant scope for B2B2C/WaaS\n * operators), {@link clear} and {@link revokePermits} stay signer-level only — they never\n * touch the shared key pair. {@link revokeTransportKeyPair} is the distinct,\n * operator-level operation for that.\n */\nexport class Permits {\n readonly #signer: GenericSigner | undefined;\n readonly #provider: GenericProvider;\n readonly #cachingService: CachingService;\n readonly #credentialService: CredentialService | undefined;\n readonly #logger: GenericLogger;\n readonly #emitEvent: (input: ZamaSDKEventInput) => void;\n\n /** @internal */\n constructor(opts: {\n signer: GenericSigner | undefined;\n provider: GenericProvider;\n cachingService: CachingService;\n credentialService: CredentialService | undefined;\n logger: GenericLogger;\n emitEvent: (input: ZamaSDKEventInput) => void;\n }) {\n this.#signer = opts.signer;\n this.#provider = opts.provider;\n this.#cachingService = opts.cachingService;\n this.#credentialService = opts.credentialService;\n this.#logger = opts.logger;\n this.#emitEvent = opts.emitEvent;\n }\n\n #requireCredentialService(operation: string): CredentialService {\n return requireConfigured(this.#credentialService, operation);\n }\n\n /**\n * Emit a {@link ZamaSDKEvents.PermitError} event for a pre-flight guard\n * failure (no signer/CredentialService configured, chain mismatch) and\n * rethrow the same error unchanged. These guards run in this namespace\n * layer, before {@link CredentialService} (and its own equivalent choke\n * point) is ever reached, so without this they'd be invisible to `onEvent`\n * regardless of what CredentialService itself emits.\n *\n * Only for the pre-flight guards below — never wrap a delegated\n * `CredentialService` call in this, since that call already emits\n * internally on failure; doing it here too would double-emit.\n */\n #failPermit(operation: PermitOperation, error: unknown): never {\n this.#emitEvent({\n type: ZamaSDKEvents.PermitError,\n operation,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n throw error;\n }\n\n /**\n * Sign and store an EIP-712 permit authorizing direct decryption for the\n * given contract addresses.\n *\n * Idempotent: if a permit covering the requested set already exists, no\n * wallet prompt occurs. Otherwise the SDK chunks the uncovered subset into\n * groups of ≤10 contracts and prompts once per chunk; partial mid-flight\n * rejection is preserved (already-signed chunks are persisted before the\n * next prompt).\n *\n * @param contracts - Contract addresses to authorize.\n * @throws if `transportKeyPairDerivationSecret` is configured and the keypair fails to wrap or\n * unwrap. {@link KeyWrappingError}\n */\n async grantPermit(contracts: Address[]): Promise<void> {\n if (contracts.length === 0) {\n return;\n }\n let service: CredentialService;\n try {\n service = this.#requireCredentialService(\"grantPermit\");\n await requireChainAlignment(\"grantPermit\", this.#signer, this.#provider);\n } catch (error) {\n this.#failPermit(\"grantPermit\", error);\n }\n await service.grantPermit(contracts);\n }\n\n /**\n * Sign and store an EIP-712 delegation permit authorizing decryption on\n * behalf of `delegator`. Same idempotence/chunking semantics as {@link grantPermit}.\n *\n * @param delegator - The address that delegated decryption rights to the connected signer.\n * @param contracts - Contract addresses to authorize.\n * @throws if `transportKeyPairDerivationSecret` is configured and the keypair fails to wrap or\n * unwrap. {@link KeyWrappingError}\n */\n async grantDelegationPermit(delegator: Address, contracts: Address[]): Promise<void> {\n if (contracts.length === 0) {\n return;\n }\n let service: CredentialService;\n try {\n service = this.#requireCredentialService(\"grantDelegationPermit\");\n await requireChainAlignment(\"grantDelegationPermit\", this.#signer, this.#provider);\n } catch (error) {\n this.#failPermit(\"grantDelegationPermit\", error);\n }\n await service.grantPermit(contracts, delegator);\n }\n\n /**\n * Pure store lookup: is there a permit covering `contracts`?\n * No wallet prompt, no transport key pair generation. Returns `false` when no signer\n * is configured, or when `transportKeyPairDerivationSecret` is configured and the stored keypair\n * fails to unwrap. Does not swallow other errors (e.g. a failing storage backend), which\n * propagate normally.\n */\n async hasPermit(contracts: Address[]): Promise<boolean> {\n if (!this.#credentialService) {\n return false;\n }\n return this.#credentialService.hasPermit(contracts);\n }\n\n /**\n * Pure store lookup for a delegation permit. Never throws when the stored keypair\n * fails to unwrap, reporting no permit instead; other errors still propagate.\n *\n * @param delegator - The address that delegated decryption rights to the connected signer.\n * @param contracts - Contract addresses to check.\n * @returns `true` if cached delegation permits cover all requested contracts.\n */\n async hasDelegationPermit(delegator: Address, contracts: Address[]): Promise<boolean> {\n if (!this.#credentialService) {\n return false;\n }\n return this.#credentialService.hasPermit(contracts, delegator);\n }\n\n /**\n * Best-effort transport-key-pair prefetch for the connected signer.\n *\n * Optional latency optimization: decrypt and permit flows remain correct\n * without it because they lazily create the transport key pair when needed.\n *\n * Silent no-op when no signer is configured or no wallet account is\n * available. The transport key pair is generated through the relayer dispatcher's\n * currently active chain — see {@link LifecycleService}, which calls\n * `switchChain` before fanning the wallet-account change out to listeners,\n * so any downstream caller (including React adapters) observes the\n * dispatcher on the wallet chain by the time it invokes warmup.\n *\n * Not for pre-warming a shared `transportKeyPairScope`: this call's wallet-account\n * precondition doesn't conceptually apply to a scope-wide key, and would silently\n * no-op precisely when an operator is most likely to be calling it (no end-user\n * connected yet). Use {@link warmTransportKeyPairScope} instead.\n *\n * @throws if `transportKeyPairDerivationSecret` is configured and the keypair fails to wrap or\n * unwrap. {@link KeyWrappingError}\n */\n async warmTransportKeyPair(): Promise<void> {\n const service = this.#credentialService;\n if (!service) {\n return;\n }\n const account = this.#signer?.walletAccount.getSnapshot();\n if (!account) {\n return;\n }\n await service.warmTransportKeyPair(account.address);\n }\n\n /**\n * Offline permit flow, phase 2: verify and persist the signature an\n * out-of-process signer produced for a `sdk.offline.preparePermit` payload.\n *\n * No wallet account required: the permit is scoped by `prepared.signerAddress`\n * (and `prepared.delegatorAddress`, if present), not a connected signer.\n *\n * @param prepared - The payload `sdk.offline.preparePermit` returned.\n * @param signature - The 65-byte `eth_signTypedData_v4` signature over `prepared.eip712`.\n * @throws if `prepared` doesn't match the `PreparedPermit` shape (e.g. it crossed a\n * process boundary and was corrupted). {@link ConfigurationError}\n * @throws if the chain embedded in `prepared.eip712` doesn't match the active chain. {@link PreparedPermitChainMismatchError}\n * @throws if the permit's validity window has already elapsed. {@link PreparedPermitExpiredError}\n * @throws if the transport key pair changed since prepare. {@link TransportKeyPairChangedError}\n * @throws if the signature is invalid or malformed. {@link SigningFailedError}\n */\n async registerPermit(prepared: PreparedPermit, signature: Hex): Promise<void> {\n let service: CredentialService;\n try {\n service = this.#requireCredentialService(\"registerPermit\");\n } catch (error) {\n this.#failPermit(\"registerPermit\", error);\n }\n await service.registerPermit(prepared, signature);\n await this.#clearDecryptCacheForRequester(prepared.signerAddress);\n }\n\n /**\n * Wipe FHE permits for the current signer.\n *\n * - With no argument: every permit referencing this signer is removed across\n * all chains and delegators. The transport key pair survives — use {@link clear} to\n * also wipe the transport key pair.\n * - With a contract list: every signed permit in the direct-decrypt scope\n * (current chain) whose immutable payload touches any listed address is\n * removed. Delegation permits are not touched in this mode.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n */\n async revokePermits(contracts?: Address[]): Promise<void> {\n const service = this.#requireCredentialService(\"revokePermits\");\n const account = await requireAlignedWalletAccount(\n \"revokePermits\",\n this.#signer,\n this.#provider,\n );\n const signerAddress = getAddress(account.address);\n try {\n await service.revokePermits(contracts);\n } finally {\n await this.#clearDecryptCacheForRequester(signerAddress);\n }\n }\n\n /**\n * Wipe the transport key pair for the current signer and cascade-delete every permit\n * (across chains and delegators) referencing it.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n */\n async clear(): Promise<void> {\n const service = this.#requireCredentialService(\"clear\");\n const account = await requireAlignedWalletAccount(\"clear\", this.#signer, this.#provider);\n const signerAddress = getAddress(account.address);\n try {\n await service.clearCredentials();\n } finally {\n await this.#clearDecryptCacheForRequester(signerAddress);\n }\n }\n\n async #clearDecryptCacheForRequester(signerAddress: Address): Promise<void> {\n await swallow(\n \"clear decrypt cache\",\n () => this.#cachingService.clearForRequester(signerAddress),\n this.#logger,\n );\n }\n\n /**\n * Revoke the shared transport key pair for `transportKeyPairScope`. Storage-only,\n * operator-level action: no wallet account or signer needs to be connected.\n *\n * Deletes the shared key pair; every permit in the scope embeds its public key, so\n * they're all treated as stale on next access. Signer-level {@link clear} never does\n * this — it only ever wipes the calling signer's own permits.\n *\n * Not best-effort, unlike most credential-store writes: a storage failure rejects\n * instead of being logged and swallowed. This is the primitive an operator reaches\n * for on suspected key compromise — a resolved promise must mean the key pair is\n * actually gone.\n *\n * Stops the SDK from reissuing or reusing the deleted key — does not revoke any\n * permit already issued under it. A permit is a self-contained, bearer-style EIP-712\n * signature the relayer accepts independently of this SDK; one exfiltrated alongside\n * the key remains usable until its own `permitTTL` expiry regardless of this call.\n *\n * @param scopeId - Must match the configured `transportKeyPairScope`, as a guard\n * against revoking the wrong scope by mistake.\n * @throws if no scope is configured, or `scopeId` doesn't match it. {@link ConfigurationError}\n * @throws if the underlying storage delete fails.\n */\n async revokeTransportKeyPair(scopeId: string): Promise<void> {\n const service = this.#requireCredentialService(\"revokeTransportKeyPair\");\n await service.revokeTransportKeyPair(scopeId);\n }\n\n /**\n * Warm the shared transport key pair for `transportKeyPairScope` — the pre-warm\n * counterpart to {@link revokeTransportKeyPair}. Storage-only, operator-level action:\n * no wallet account or signer needs to be connected. Prefer this over\n * {@link warmTransportKeyPair} for a scoped key pair: unlike that method, this never\n * silently no-ops for lack of a connected wallet, because a scope-wide key was never\n * tied to one in the first place.\n *\n * @param scopeId - Must match the configured `transportKeyPairScope`, as a guard\n * against warming the wrong scope by mistake.\n * @throws if no scope is configured, or `scopeId` doesn't match it. {@link ConfigurationError}\n * @throws if `transportKeyPairDerivationSecret` is configured and the keypair fails to wrap or\n * unwrap. {@link KeyWrappingError}\n */\n async warmTransportKeyPairScope(scopeId: string): Promise<void> {\n const service = this.#requireCredentialService(\"warmTransportKeyPairScope\");\n await service.warmTransportKeyPairScope(scopeId);\n }\n}\n","import type { Address } from \"viem\";\nimport type { DelegationService, DelegationStatus } from \"../services/delegation-service\";\nimport type { GenericProvider, GenericSigner, TransactionResult } from \"../types\";\nimport { requireAlignedWalletAccount } from \"../utils/alignment\";\nimport { requireConfigured } from \"../errors\";\n\n/**\n * Public namespace for on-chain decryption-delegation management.\n *\n * Exposed as `sdk.delegations`. Owns the SDK-level guards (signer requirement, chain\n * alignment, delegator address resolution from the wallet account) and delegates the\n * actual work to the internal {@link DelegationService}.\n *\n * Delegation operations write to the host chain ACL; after a delegation is mined,\n * the gateway syncs the ACL state via cross-chain event propagation — usually\n * within ~10 blocks (a few seconds). Delegated decryption rides out that window\n * with a bounded internal retry, so callers can decrypt right after granting.\n */\nexport class Delegations {\n readonly #signer: GenericSigner | undefined;\n readonly #provider: GenericProvider;\n readonly #delegationService: DelegationService;\n\n /** @internal */\n constructor(opts: {\n signer: GenericSigner | undefined;\n provider: GenericProvider;\n delegationService: DelegationService;\n }) {\n this.#signer = opts.signer;\n this.#provider = opts.provider;\n this.#delegationService = opts.delegationService;\n }\n\n #requireSigner(operation: string): GenericSigner {\n return requireConfigured(this.#signer, operation);\n }\n\n /**\n * Delegate decryption rights for a confidential contract to another address.\n * Calls `ACL.delegateForUserDecryption()` on-chain.\n *\n * The delegation is recorded on L1 immediately, but the gateway must sync the\n * ACL state via cross-chain event propagation — usually within ~10 blocks (a\n * few seconds). You do not need to wait: delegated decryption rides out that\n * window with a bounded internal retry, so you can decrypt right after this\n * resolves.\n *\n * @param contractAddress - The confidential contract address to delegate on.\n * @param delegateAddress - Address to delegate decryption rights to.\n * @param expirationDate - Optional expiration date (defaults to permanent delegation via `uint64.max`).\n * @returns The transaction hash and mined receipt.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if `expirationDate` is less than 1 hour in the future. {@link DelegationExpirationTooSoonError}\n * @throws if the delegate equals the connected wallet. {@link DelegationSelfNotAllowedError}\n * @throws if the delegate equals the contract address. {@link DelegationDelegateEqualsContractError}\n * @throws if the new expiry equals the current one. {@link DelegationExpiryUnchangedError}\n * @throws if the delegation transaction reverts. {@link TransactionRevertedError}\n */\n async delegateDecryption({\n contractAddress,\n delegateAddress,\n expirationDate,\n }: {\n contractAddress: Address;\n delegateAddress: Address;\n expirationDate?: Date;\n }): Promise<TransactionResult> {\n const signer = this.#requireSigner(\"delegateDecryption\");\n const account = await requireAlignedWalletAccount(\n \"delegateDecryption\",\n this.#signer,\n this.#provider,\n );\n return this.#delegationService.delegateDecryption(signer, {\n contractAddress,\n delegateAddress,\n delegatorAddress: account.address,\n expirationDate,\n });\n }\n\n /**\n * Revoke decryption delegation for a confidential contract.\n * Calls `ACL.revokeDelegationForUserDecryption()` on-chain.\n *\n * @param contractAddress - The confidential contract address to revoke delegation on.\n * @param delegateAddress - Address to revoke delegation from.\n * @returns The transaction hash and mined receipt.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if no delegation exists for this (delegator, delegate, contract) tuple. {@link DelegationNotFoundError}\n * @throws if the revocation transaction reverts. {@link TransactionRevertedError}\n */\n async revokeDelegation({\n contractAddress,\n delegateAddress,\n }: {\n contractAddress: Address;\n delegateAddress: Address;\n }): Promise<TransactionResult> {\n const signer = this.#requireSigner(\"revokeDelegation\");\n const account = await requireAlignedWalletAccount(\n \"revokeDelegation\",\n this.#signer,\n this.#provider,\n );\n return this.#delegationService.revokeDelegation(signer, {\n contractAddress,\n delegateAddress,\n delegatorAddress: account.address,\n });\n }\n\n /**\n * Check whether a delegation is active for the given contract address.\n *\n * Signer-independent: works without a configured signer.\n *\n * @param contractAddress - The confidential contract address.\n * @param delegatorAddress - The address that granted the delegation.\n * @param delegateAddress - The address that received delegation rights.\n * @returns `true` if the delegation exists and has not expired.\n */\n async isActive(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<boolean> {\n return this.#delegationService.isDelegated(params);\n }\n\n /**\n * Get the expiration timestamp of a delegation for the given contract.\n *\n * Signer-independent: works without a configured signer.\n *\n * @param contractAddress - The confidential contract address.\n * @param delegatorAddress - The address that granted the delegation.\n * @param delegateAddress - The address that received delegation rights.\n * @returns Unix timestamp as bigint. `0n` = no delegation. `2^64 - 1` = permanent.\n */\n async getExpiry(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<bigint> {\n return this.#delegationService.getDelegationExpiry(params);\n }\n\n /**\n * Get activity and expiry together in a single on-chain read, instead of\n * calling {@link isActive} and {@link getExpiry} separately.\n *\n * Signer-independent: works without a configured signer.\n *\n * @param contractAddress - The confidential contract address.\n * @param delegatorAddress - The address that granted the delegation.\n * @param delegateAddress - The address that received delegation rights.\n * @returns `{ isActive, expiryTimestamp }` — activity and the raw expiry timestamp together.\n */\n async getStatus(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<DelegationStatus> {\n return this.#delegationService.getStatus(params);\n }\n}\n","import type { Address } from \"viem\";\nimport { requireConfigured, wrapDecryptError } from \"../errors\";\nimport type { EncryptedInput } from \"../query/user-decrypt\";\nimport type { ChainRouter } from \"../chains/router\";\nimport type {\n ClearValue,\n DecryptPublicValuesResult,\n EncryptedValue,\n FhevmRelayerOptions,\n} from \"../relayer/types\";\nimport type {\n BatchDecryptResult,\n DecryptionService,\n DelegatedDecryptOptions,\n} from \"../services/decryption-service\";\nimport type { GenericProvider, GenericSigner } from \"../types\";\nimport { requireAlignedWalletAccount } from \"../utils/alignment\";\nimport { assertNonNullable } from \"../utils\";\n\n/**\n * Public namespace for FHE decryption — the canonical way to decrypt.\n *\n * Exposed as `sdk.decryption`. Prefer these methods over the low-level\n * `sdk.relayer.decryptValues` / `decryptPublicValues`: they\n * assemble the credential bundle (transport key pair, EIP-712 permit) for you,\n * cache results, and wrap relayer errors. Reach for `sdk.relayer.*` only when\n * you must control credential assembly by hand.\n *\n * Owns the SDK-level guards (signer requirement on\n * `decryptValues` and `delegatedDecryptValues`, empty-array\n * short-circuit on `decryptPublicValues`, relayer error wrapping) and delegates the\n * actual work to the internal {@link DecryptionService} or the relayer directly for\n * `decryptPublicValues`.\n *\n * **Mixed signer requirement:** `decryptValues` and\n * `delegatedDecryptValues` need a configured signer; `decryptPublicValues`\n * does not. Each method documents its requirement in its JSDoc.\n *\n * **Request chunking:** decrypt requests are split internally to stay under\n * the relayer's 2048-cleartext-bit per-request budget — callers never need to\n * size batches themselves.\n */\nexport class Decryption {\n readonly #signer: GenericSigner | undefined;\n readonly #provider: GenericProvider;\n readonly #router: ChainRouter;\n readonly #decryptionService: DecryptionService | undefined;\n\n /** @internal */\n constructor(opts: {\n signer: GenericSigner | undefined;\n provider: GenericProvider;\n router: ChainRouter;\n decryptionService: DecryptionService | undefined;\n }) {\n this.#signer = opts.signer;\n this.#provider = opts.provider;\n this.#router = opts.router;\n this.#decryptionService = opts.decryptionService;\n }\n\n #requireDecryptionService(operation: string): DecryptionService {\n return requireConfigured(this.#decryptionService, operation);\n }\n\n /**\n * Decrypt one or more FHE encrypted values. Results are cached — repeated calls\n * for the same encrypted value skip the relayer round-trip.\n *\n * Zero encrypted values are mapped to `0n` without hitting the relayer.\n * Events (`DecryptStart/End/Error`) are emitted uniformly.\n * Relayer errors are wrapped into typed SDK errors.\n *\n * @param encryptedInput - Encrypted values to decrypt, each paired with its contract address.\n * @param options - Per-call `signal` and `timeout` forwarded to the relayer round-trip.\n * @returns A record mapping each encrypted value to its decrypted clear-text value.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n *\n * @example\n * ```ts\n * const values = await sdk.decryption.decryptValues([\n * { encryptedValue: balance, contractAddress: cUSDT },\n * ]);\n * console.log(values[balance]); // 1000n\n * ```\n */\n async decryptValues(\n encryptedInput: EncryptedInput[],\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<Record<EncryptedValue, ClearValue>> {\n const service = this.#requireDecryptionService(\"decryptValues\");\n const account = await requireAlignedWalletAccount(\n \"decryptValues\",\n this.#signer,\n this.#provider,\n );\n return service.decryptValues(encryptedInput, account.address, options);\n }\n\n /**\n * Decrypt one or more FHE encrypted values using delegated credentials.\n *\n * Mirrors {@link decryptValues} with delegated credentials — same caching and\n * zero-value short-circuit. Before reading from cache or calling the relayer,\n * every non-zero encrypted value's contract must have an active delegation from the\n * delegator to the connected signer; missing or expired delegations fail fast.\n *\n * @param encryptedInputs - FHE encrypted values paired with their contract addresses.\n * @param delegatorAddress - The address that granted delegation rights.\n * @param accountAddress - Address used as the cache key's \"requester\"\n * dimension. Defaults to `delegatorAddress`. Pass the actual account address\n * when decrypting on behalf of someone whose balance is stored under a\n * different address (e.g. `decryptBalanceAs` with an explicit `accountAddress`).\n * @param options - Delegated-decrypt options. By default the call rides out the\n * gateway propagation window ({@link DelegatedDecryptOptions.waitForPropagation});\n * pass `{ waitForPropagation: false }` to fail fast instead.\n * @returns Map of encrypted value → clear-text value.\n *\n * @example\n * ```ts\n * const values = await sdk.decryption.delegatedDecryptValues([\n * { encryptedValue: balance, contractAddress: tokenAddr },\n * ], delegatorAddr);\n * console.log(values[balance]); // 1000n\n * ```\n */\n async delegatedDecryptValues(\n encryptedInputs: EncryptedInput[],\n delegatorAddress: Address,\n accountAddress: Address = delegatorAddress,\n options?: DelegatedDecryptOptions,\n ): Promise<Record<EncryptedValue, ClearValue>> {\n const service = this.#requireDecryptionService(\"delegatedDecryptValues\");\n const account = await requireAlignedWalletAccount(\n \"delegatedDecryptValues\",\n this.#signer,\n this.#provider,\n );\n return service.delegatedDecryptValues(\n encryptedInputs,\n delegatorAddress,\n account.address,\n accountAddress,\n options,\n );\n }\n\n /**\n * Publicly decrypt one or more FHE encrypted values.\n *\n * Signer-independent: works without a configured signer.\n * Returns the decryption proof alongside the clear-text values so callers\n * can submit on-chain finalization transactions (e.g. `finalizeUnwrap`).\n *\n * @param encryptedValues - FHE encrypted values to decrypt publicly.\n * @param options - Per-call `signal` and `timeout` forwarded to the relayer round-trip.\n * @returns Clear-text values, ABI-encoded values, and the decryption proof.\n *\n * @example\n * ```ts\n * const { clearValues, decryptionProof, abiEncodedClearValues } =\n * await sdk.decryption.decryptPublicValues([encryptedValue]);\n * ```\n */\n async decryptPublicValues(\n encryptedValues: EncryptedValue[],\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<DecryptPublicValuesResult> {\n if (encryptedValues.length === 0) {\n return { clearValues: {}, decryptionProof: \"0x\", abiEncodedClearValues: \"0x\" };\n }\n\n try {\n const result = await this.#router.relayer.decryptPublicValuesWithSignatures({\n encryptedValues,\n options,\n });\n const clearValues: Record<EncryptedValue, ClearValue> = {};\n result.checkSignaturesArgs.handlesList.forEach((handle, i) => {\n assertNonNullable(result.clearValues[i], `result.clearValues[${i}]`);\n clearValues[handle] = result.clearValues[i].value;\n });\n return {\n clearValues,\n abiEncodedClearValues: result.checkSignaturesArgs.abiEncodedCleartexts,\n decryptionProof: result.checkSignaturesArgs.decryptionProof,\n };\n } catch (error) {\n throw wrapDecryptError(error, \"Public decryption failed\");\n }\n }\n\n /**\n * Batch-decrypt delegated encrypted values with per-entry error isolation.\n *\n * Attempts a single batch request first. If the batch fails with a non-fatal\n * error (e.g. one entry is invalid), falls back to per-entry decryption so\n * healthy entries still resolve. Each item in the result carries either a\n * decrypted value or an error — callers decide how to surface partial failures.\n *\n * @param encryptedInputs - FHE encrypted values paired with their contract addresses.\n * @param delegatorAddress - The address that granted delegation rights.\n * @param accountAddress - The account on whose behalf decryption is performed. Defaults to `delegatorAddress`.\n * @param maxConcurrency - Maximum parallel decrypt calls during per-entry fallback.\n * @param waitForPropagation - Ride out the gateway propagation window on the\n * initial batch attempt (default `true`). See {@link DelegatedDecryptOptions.waitForPropagation}.\n * @returns Per-entry results, each with a value or an error.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws A failure that affects the whole session (rejected signature, RPC\n * rate limit, revoked KMS context) rejects the call instead of landing in a\n * per-entry error.\n *\n * @example\n * ```ts\n * const result = await sdk.decryption.delegatedBatchDecryptValues({\n * encryptedInputs: [\n * { encryptedValue: encryptedValue1, contractAddress: tokenA },\n * { encryptedValue: encryptedValue2, contractAddress: tokenB },\n * ],\n * delegatorAddress: \"0xDelegator\",\n * maxConcurrency: 5,\n * });\n * for (const item of result.items) {\n * if (item.error) console.error(item.encryptedValue, item.error);\n * else console.log(item.encryptedValue, item.value);\n * }\n * ```\n */\n async delegatedBatchDecryptValues({\n encryptedInputs,\n delegatorAddress,\n accountAddress = delegatorAddress,\n maxConcurrency,\n waitForPropagation,\n }: {\n encryptedInputs: EncryptedInput[];\n delegatorAddress: Address;\n accountAddress?: Address;\n maxConcurrency?: number;\n } & DelegatedDecryptOptions): Promise<BatchDecryptResult> {\n const service = this.#requireDecryptionService(\"delegatedBatchDecryptValues\");\n const account = await requireAlignedWalletAccount(\n \"delegatedBatchDecryptValues\",\n this.#signer,\n this.#provider,\n );\n return service.delegatedBatchDecryptHandlesAs({\n encryptedInputs,\n delegatorAddress,\n delegateAddress: account.address,\n accountAddress,\n maxConcurrency,\n waitForPropagation,\n });\n }\n}\n","import type { CredentialService } from \"../credentials/credential-service\";\nimport type { PreparedPermit, PreparePermitRequest } from \"../credentials/types\";\nimport type { OfflineService } from \"../services/offline-service\";\nimport type {\n PreparedFor,\n PrepareOptions,\n PrepareTransactionRequest,\n TransactionKind,\n} from \"../types\";\n\n/**\n * Namespace for the offline-signing pipeline —\n * `prepare → [external sign + self-publish]` — for institutional custody, HSM\n * ceremonies, and policy-engine workflows where signing runs out-of-process and\n * cannot happen synchronously in a single Promise.\n */\nexport class Offline {\n readonly #offlineService: OfflineService;\n readonly #credentialService: CredentialService;\n\n /** @internal */\n constructor(offlineService: OfflineService, credentialService: CredentialService) {\n this.#offlineService = offlineService;\n this.#credentialService = credentialService;\n }\n\n /**\n * Build an RLP-encoded unsigned transaction for the given request. The\n * caller signs it externally — via an HSM ceremony, an out-of-process\n * custodian, or any signer holding the key — and broadcasts the signed bytes\n * through its own channel.\n *\n * Signer-optional: works without a configured signer (canonical shape for\n * cross-process custody — the back-end signer service consumes\n * `prepared.unsignedTx` and returns signed bytes).\n *\n * @remarks\n * `request.from` is only a declaration — the SDK does not prove the caller\n * controls it, and an EIP-1559 unsigned tx carries no `from` field at all\n * (the on-chain sender is whichever key signs the bytes). Point `from` at\n * the account the custodian will sign with; custodians enforce key-control\n * at sign time — a signing request for a key the credential can't use fails\n * there — so a mismatched `from` cannot make the custodian sign from an\n * account you don't control. Verifying control of `from` up front is still\n * the application's responsibility.\n */\n prepare<K extends TransactionKind>(\n request: Extract<PrepareTransactionRequest, { kind: K }>,\n options?: PrepareOptions,\n ): Promise<PreparedFor<K>> {\n return this.#offlineService.prepare(request, options);\n }\n\n /**\n * Build the offline-signing payload for a decryption permit: the unsigned\n * EIP-712 typed data plus everything `sdk.permits.registerPermit` needs to\n * verify and persist the signature an out-of-process signer returns for it.\n *\n * Not a `prepare()` transaction kind: a permit is not a transaction —\n * nothing is broadcast, and registering the signature is a local operation,\n * not a relayer round-trip.\n *\n * Signer-optional, like {@link prepare}: `request.signer` is an explicit\n * address, not a connected wallet account. Building the typed data still\n * reads the chain's KMS signers context on-chain — signer-offline, not\n * network-offline.\n *\n * One permit per call: unlike `sdk.permits.grantPermit`, this never widens\n * an existing permit or chunks over 10 contracts — `request.contracts` maps\n * to exactly one signature.\n *\n * @throws if `request.contracts` is empty or exceeds 10 addresses, `request.delegator`\n * equals `request.signer`, or `request.durationDays` exceeds the V1 permit maximum\n * of 365 days. {@link ConfigurationError}\n * @throws if a concurrent `permits.revokeTransportKeyPair()` rotates the transport key\n * pair while this call is generating one. {@link TransportKeyPairChangedError}\n */\n preparePermit(request: PreparePermitRequest): Promise<PreparedPermit> {\n return this.#credentialService.preparePermit(request);\n }\n}\n","import type { GenericStorage } from \"../types\";\n\n/** Minimal chrome.storage.session typings (avoids depending on @types/chrome). */\ndeclare const chrome: {\n storage: {\n session: {\n get(key: string): Promise<Record<string, unknown>>;\n set(items: Record<string, unknown>): Promise<void>;\n remove(key: string): Promise<void>;\n };\n };\n};\n\n/**\n * {@link GenericStorage} backed by `chrome.storage.session`.\n *\n * Use this in MV3 web extensions so the wallet signature survives\n * service worker restarts and is shared across popup, background,\n * and content script contexts.\n *\n * @example\n * ```ts\n * import { ZamaSDK, indexedDBStorage, chromeSessionStorage } from \"@zama-fhe/sdk\";\n * import { createConfig } from \"@zama-fhe/sdk/viem\";\n *\n * const config = createConfig({\n * chains: [mySepolia],\n * publicClient,\n * walletClient,\n * relayers: { [mySepolia.id]: web() },\n * storage: indexedDBStorage, // encrypted transport key pair — persistent\n * permitStorage: chromeSessionStorage, // signed permits — ephemeral\n * });\n * const sdk = new ZamaSDK(config);\n * ```\n */\nexport class ChromeSessionStorage implements GenericStorage {\n /**\n * Retrieve a value by key.\n * @returns The stored value, or `null` if the key does not exist.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n const result = await chrome.storage.session.get(key);\n return (result[key] as T) ?? null;\n }\n\n /** Store a value under the given key, overwriting any existing entry. */\n async set(key: string, value: unknown): Promise<void> {\n await chrome.storage.session.set({ [key]: value });\n }\n\n /** Remove the entry for the given key (no-op if absent). */\n async delete(key: string): Promise<void> {\n await chrome.storage.session.remove(key);\n }\n}\n\n/** Default singleton for application-wide use. */\nexport const chromeSessionStorage = new ChromeSessionStorage();\n","import { getAddress, type Address } from \"viem\";\nimport { z } from \"zod/mini\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/types\";\nimport { checksummedAddress } from \"../schemas/primitives\";\nimport type { GenericLogger, GenericStorage } from \"../types\";\n\nconst CacheValueSchema = z.union([z.bigint(), z.boolean(), checksummedAddress]);\nconst CacheIndexSchema = z.array(z.string());\n\n/**\n * Storage-backed cache for decrypted FHE plaintext values.\n *\n * Each entry is keyed by `(requester, contractAddress, handle)` so different\n * signers cannot read each other's cached decryptions.\n *\n * @internal\n */\nexport class CachingService {\n readonly #storage: GenericStorage;\n readonly #logger: GenericLogger;\n readonly #decryptNamespace = \"zama:decrypt\";\n readonly #decryptKeysNamespace = `${this.#decryptNamespace}:keys`;\n #indexWriteQueue: Promise<void> = Promise.resolve();\n\n constructor(storage: GenericStorage, logger: GenericLogger) {\n this.#storage = storage;\n this.#logger = logger;\n }\n\n async get(\n requester: Address,\n contractAddress: Address,\n encryptedValue: EncryptedValue,\n ): Promise<ClearValue | null> {\n try {\n const key = this.#buildStorageKey(requester, contractAddress, encryptedValue);\n const value = await this.#storage.get(key);\n if (value === null) {\n return null;\n }\n const parsed = CacheValueSchema.safeParse(value);\n if (!parsed.success) {\n await this.delete(requester, contractAddress, encryptedValue);\n return null;\n }\n return parsed.data;\n } catch (error) {\n this.#logger.warn(\"CachingService.get failed\", { error });\n return null;\n }\n }\n\n async set(\n requester: Address,\n contractAddress: Address,\n encryptedValue: EncryptedValue,\n value: ClearValue,\n ): Promise<void> {\n try {\n const key = this.#buildStorageKey(requester, contractAddress, encryptedValue);\n await this.#storage.set<ClearValue>(key, value);\n this.#indexWriteQueue = this.#indexWriteQueue.then(() =>\n this.#addToIndex(key).catch((error) => {\n this.#logger.warn(\"CachingService index write failed\", { error });\n }),\n );\n await this.#indexWriteQueue;\n } catch (error) {\n this.#logger.warn(\"CachingService.set failed\", { error });\n }\n }\n\n async delete(\n requester: Address,\n contractAddress: Address,\n encryptedValue: EncryptedValue,\n ): Promise<void> {\n const key = this.#buildStorageKey(requester, contractAddress, encryptedValue);\n this.#indexWriteQueue = this.#indexWriteQueue.then(() =>\n this.#doDelete(key).catch((error) => {\n this.#logger.warn(\"CachingService.delete failed\", { error });\n }),\n );\n await this.#indexWriteQueue;\n }\n\n async clearForRequester(requester: Address): Promise<void> {\n this.#indexWriteQueue = this.#indexWriteQueue.then(() =>\n this.#doClearForRequester(requester).catch((error) => {\n this.#logger.warn(\"CachingService.clearForRequester failed\", { error });\n }),\n );\n await this.#indexWriteQueue;\n }\n\n async clearAll(): Promise<void> {\n this.#indexWriteQueue = this.#indexWriteQueue.then(() =>\n this.#doClearAll().catch((error) => {\n this.#logger.warn(\"CachingService.clearAll failed\", { error });\n }),\n );\n await this.#indexWriteQueue;\n }\n\n async #doDelete(key: string): Promise<void> {\n await this.#storage.delete(key).catch(() => {});\n const keys = await this.#readIndex();\n const remaining = keys.filter((k) => k !== key);\n if (remaining.length !== keys.length) {\n await this.#storage.set(this.#decryptKeysNamespace, remaining);\n }\n }\n\n async #doClearForRequester(requester: Address): Promise<void> {\n const checksumRequester = getAddress(requester);\n const prefix = `${this.#decryptNamespace}:${checksumRequester}:`;\n const keys = await this.#readIndex();\n const toRemove: string[] = [];\n const remaining: string[] = [];\n for (const k of keys) {\n if (k.startsWith(prefix)) {\n toRemove.push(k);\n } else {\n remaining.push(k);\n }\n }\n await Promise.all(toRemove.map((k) => this.#storage.delete(k).catch(() => {})));\n await this.#storage.set(this.#decryptKeysNamespace, remaining);\n }\n\n async #doClearAll(): Promise<void> {\n const keys = await this.#readIndex();\n await Promise.all(keys.map((k) => this.#storage.delete(k).catch(() => {})));\n await this.#storage.delete(this.#decryptKeysNamespace);\n }\n\n #buildStorageKey(\n requester: Address,\n contractAddress: Address,\n encryptedValue: EncryptedValue,\n ): string {\n return `${this.#decryptNamespace}:${getAddress(requester)}:${getAddress(contractAddress)}:${encryptedValue.toLowerCase()}`;\n }\n\n async #readIndex(): Promise<string[]> {\n const value = await this.#storage.get(this.#decryptKeysNamespace);\n if (value === null) {\n return [];\n }\n const parsed = CacheIndexSchema.safeParse(value);\n if (parsed.success) {\n return parsed.data;\n }\n await this.#storage.delete(this.#decryptKeysNamespace).catch(() => {});\n return [];\n }\n\n async #addToIndex(key: string): Promise<void> {\n const keys = await this.#readIndex();\n if (!keys.includes(key)) {\n keys.push(key);\n await this.#storage.set(this.#decryptKeysNamespace, keys);\n }\n }\n}\n","import type { Address, Hex } from \"viem\";\nimport { DecryptionFailedError } from \"../errors\";\nimport { checksum } from \"../schemas/primitives\";\nimport type {\n Permission,\n SerializedTransportKeyPairWithPermissions,\n SerializedPermit,\n} from \"./types\";\n\n/**\n * The minimal permit material the decrypt seam needs. Delegation is already\n * encoded in the self-contained `serializedPermit`, so a delegated decrypt and\n * a normal decrypt resolve to the same shape — there is no separate delegated\n * variant.\n */\nexport interface ResolvedPermit {\n privateKey: Hex;\n publicKey: Hex;\n serializedPermit: SerializedPermit;\n}\n\n/**\n * Resolve the signed permit covering `contractAddress` from previously granted\n * credentials. Works uniformly for direct and delegated decryption: the\n * `@fhevm/sdk` signed permit bakes the delegator (if any) into its EIP-712\n * payload, so the decrypt call needs nothing beyond the transport key pair and\n * the serialized permit.\n *\n * @throws if no stored permit covers `contractAddress`. {@link DecryptionFailedError}\n */\nexport function resolvePermit(\n credentials: SerializedTransportKeyPairWithPermissions,\n contractAddress: Address,\n): ResolvedPermit {\n const permission = findPermissionFor(credentials, contractAddress);\n if (!permission) {\n throw new DecryptionFailedError(`No permit covers contract ${contractAddress} after allow()`);\n }\n return {\n privateKey: credentials.keypair.privateKey,\n publicKey: credentials.keypair.publicKey,\n serializedPermit: permission.serializedPermit,\n };\n}\n\nfunction findPermissionFor(\n credentials: SerializedTransportKeyPairWithPermissions,\n contractAddress: Address,\n): Permission | undefined {\n const target = checksum(contractAddress);\n return credentials.permissions.find((permission) =>\n permission.contractAddresses.includes(target),\n );\n}\n","import type { ParseTransportKeyPairReturnType } from \"@fhevm/sdk/actions/chain\";\nimport type { DecryptValuesReturnType } from \"@fhevm/sdk/actions/decrypt\";\nimport { getAddress, type Address } from \"viem\";\nimport type { ChainRouter } from \"../chains/router\";\nimport type { CredentialService } from \"../credentials/credential-service\";\nimport { resolvePermit } from \"../credentials/decrypt-permit\";\nimport type { SerializedTransportKeyPairWithPermissions } from \"../credentials/types\";\nimport {\n type DecryptErrorContext,\n DecryptionFailedError,\n DelegationNotPropagatedError,\n isFatalBatchError,\n RevokedKmsContextError,\n RpcRateLimitError,\n SigningFailedError,\n wrapDecryptError,\n ZamaError,\n} from \"../errors\";\nimport type { ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { ZamaSDKEvents } from \"../events/sdk-events\";\nimport type { EncryptedInput } from \"../query/user-decrypt\";\nimport type { ClearValue, EncryptedValue, FhevmRelayerOptions } from \"../relayer/types\";\nimport { pLimit } from \"../utils/concurrency\";\nimport { chunkHandlesByBitBudget, isEncryptedValueZero } from \"../utils/handles\";\nimport {\n extractRetryAfter,\n isInvalidTransportKeyPairMessage,\n isRpcRateLimitError,\n toError,\n} from \"../utils\";\nimport type { CachingService } from \"./caching-service\";\nimport type { DelegationService } from \"./delegation-service\";\n\n/**\n * How long the delegated-decrypt path keeps retrying while a freshly granted\n * delegation propagates to the gateway. Propagation usually completes within\n * ~10 blocks (a few seconds); this ceiling absorbs a briefly lagging gateway\n * without turning a genuine outage into a long hang.\n */\nconst DELEGATION_PROPAGATION_RETRY_BUDGET_MS = 30_000;\n/** Delay between propagation retries. */\nconst DELEGATION_PROPAGATION_RETRY_INTERVAL_MS = 2_000;\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** Options shared by the delegated-decrypt entry points. */\nexport interface DelegatedDecryptOptions {\n /**\n * Ride out the gateway propagation window: when a just-granted delegation\n * has not yet synced, the delegated decrypt is retried (bounded, ~30s) until\n * it lands instead of throwing {@link DelegationNotPropagatedError}. Defaults\n * to `true`. Pass `false` to fail fast on the first not-propagated response.\n */\n waitForPropagation?: boolean;\n}\n\ninterface DecryptionStrategy {\n requesterAddress: Address;\n /**\n * Delegator whose permit scope this decrypt reads; undefined on the direct\n * path. The single delegation discriminator: it also selects the delegated\n * error classification and the ACL actor (delegator, or the requester when\n * direct).\n */\n delegator?: Address;\n validate?: (contractAddresses: readonly Address[]) => Promise<void>;\n errorMessage: string;\n}\n\n/** One decrypt-relayer request: a contract's handles chunked to the bit budget. */\ninterface DecryptRequest {\n contractAddress: Address;\n encryptedValues: EncryptedValue[];\n}\n\n/** Tracks the evict-and-regrant allowance across retried decrypt attempts. */\ninterface RecoveryBudget {\n spent: boolean;\n}\n\n/** Per-handle outcome of a batch decrypt: the decrypted value, or a per-item error. */\nexport interface BatchDecryptItem {\n /** The encrypted value (handle) being decrypted. */\n encryptedValue: EncryptedValue;\n /** Address of the contract the handle belongs to. */\n contractAddress: Address;\n /** Decrypted clear value; set when this item succeeded. */\n value?: ClearValue;\n /** Error for this item; set when this item failed. */\n error?: ZamaError;\n}\n\n/** Result of a batch decrypt: one entry per requested handle, in input order. */\nexport interface BatchDecryptResult {\n /** Per-handle outcomes. */\n items: BatchDecryptItem[];\n}\n\n/** @internal */\nexport class DecryptionService {\n readonly #cache: CachingService;\n readonly #credentialService: CredentialService;\n readonly #delegationService: DelegationService;\n readonly #router: ChainRouter;\n readonly #emitEvent: (input: ZamaSDKEventInput) => void;\n\n constructor({\n cache,\n credentialService,\n delegationService,\n router,\n emitEvent,\n }: {\n cache: CachingService;\n credentialService: CredentialService;\n delegationService: DelegationService;\n router: ChainRouter;\n emitEvent: (input: ZamaSDKEventInput) => void;\n }) {\n this.#cache = cache;\n this.#credentialService = credentialService;\n this.#delegationService = delegationService;\n this.#router = router;\n this.#emitEvent = emitEvent;\n }\n\n async decryptValues(\n handles: EncryptedInput[],\n signerAddress: Address,\n opts?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<Record<EncryptedValue, ClearValue>> {\n const normalizedSigner = getAddress(signerAddress);\n return this.#decrypt(\n handles,\n { requesterAddress: normalizedSigner, errorMessage: \"Failed to decrypt encrypted values\" },\n opts,\n );\n }\n\n async delegatedDecryptValues(\n encryptedInputs: EncryptedInput[],\n delegatorAddress: Address,\n delegateAddress: Address,\n accountAddress: Address,\n opts?: DelegatedDecryptOptions,\n ): Promise<Record<EncryptedValue, ClearValue>> {\n const normalizedDelegator = getAddress(delegatorAddress);\n const normalizedDelegate = getAddress(delegateAddress);\n // One evict-and-regrant across the whole propagation-retry loop, not one\n // per attempt: each retry would otherwise re-arm the recovery and spend a\n // fresh wallet prompt per 2s attempt while the upstream validity cache\n // keeps serving the revoked context.\n const recovery: RecoveryBudget = { spent: false };\n return this.#withPropagationRetry(opts?.waitForPropagation ?? true, () =>\n this.#decrypt(\n encryptedInputs,\n {\n requesterAddress: getAddress(accountAddress),\n delegator: normalizedDelegator,\n validate: (contractAddresses) =>\n this.#assertAllDelegationsActive(contractAddresses, {\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n }),\n errorMessage: \"Failed to decrypt delegated encrypted values\",\n },\n undefined,\n recovery,\n ),\n );\n }\n\n /**\n * Absorb the gateway propagation window on the delegated path: retry `attempt`\n * (bounded by {@link DELEGATION_PROPAGATION_RETRY_BUDGET_MS}) while it fails\n * with a transient {@link DelegationNotPropagatedError}. Every other error —\n * including a missing/expired grant surfaced by the pre-check — throws\n * immediately, and passing `waitForPropagation: false` disables the retry so\n * the first not-propagated response propagates unchanged.\n */\n async #withPropagationRetry<T>(\n waitForPropagation: boolean,\n attempt: () => Promise<T>,\n ): Promise<T> {\n // Fixed-interval polling across the budget: e.g. 30s / 2s = 15 gaps, so 16\n // attempts. Bounded (no open-ended loop) and deterministic under fake timers.\n const maxAttempts =\n Math.floor(\n DELEGATION_PROPAGATION_RETRY_BUDGET_MS / DELEGATION_PROPAGATION_RETRY_INTERVAL_MS,\n ) + 1;\n let lastError: unknown;\n for (let i = 0; i < maxAttempts; i++) {\n try {\n return await attempt();\n } catch (error) {\n lastError = error;\n const canRetry =\n i < maxAttempts - 1 &&\n waitForPropagation &&\n error instanceof DelegationNotPropagatedError;\n if (!canRetry) {\n throw error;\n }\n await sleep(DELEGATION_PROPAGATION_RETRY_INTERVAL_MS);\n }\n }\n throw lastError;\n }\n\n async delegatedBatchDecryptHandlesAs({\n encryptedInputs,\n delegatorAddress,\n delegateAddress,\n accountAddress,\n maxConcurrency = 5,\n waitForPropagation = true,\n }: {\n encryptedInputs: EncryptedInput[];\n delegatorAddress: Address;\n delegateAddress: Address;\n accountAddress: Address;\n maxConcurrency?: number;\n waitForPropagation?: boolean;\n }): Promise<BatchDecryptResult> {\n const items: BatchDecryptItem[] = encryptedInputs.map((h) => ({\n encryptedValue: h.encryptedValue,\n contractAddress: getAddress(h.contractAddress),\n }));\n if (items.length === 0) {\n return { items };\n }\n const normalizedAccount = getAddress(accountAddress);\n\n try {\n const decrypted = await this.delegatedDecryptValues(\n items.map(({ encryptedValue, contractAddress }) => ({ encryptedValue, contractAddress })),\n delegatorAddress,\n delegateAddress,\n normalizedAccount,\n { waitForPropagation },\n );\n for (const item of items) {\n this.#setHandleResult(item, decrypted);\n }\n return { items };\n } catch (error) {\n if (isFatalBatchError(error)) {\n throw error;\n }\n if (items.length === 1) {\n const [item = this.#missingBatchItem()] = items;\n item.error = this.#toZamaError(error, \"Failed to decrypt delegated encrypted values\", {\n isDelegated: true,\n contractAddress: item.contractAddress,\n account: getAddress(delegatorAddress),\n });\n return { items };\n }\n }\n\n // `pLimit` cannot cancel calls that already started. The shared flag stops\n // the queued items from starting once a fatal error (e.g. an RPC rate\n // limit) is seen, instead of re-hitting the failing endpoint.\n let aborted = false;\n let fatal: unknown;\n await pLimit(\n items.map((item) => async () => {\n if (aborted) {\n return;\n }\n try {\n // The batch attempt above already rode out the propagation window for\n // the whole set; fail fast here so a still-unsynced delegation records\n // a per-item error instead of each item re-spending the full budget.\n const decrypted = await this.delegatedDecryptValues(\n [{ encryptedValue: item.encryptedValue, contractAddress: item.contractAddress }],\n delegatorAddress,\n delegateAddress,\n normalizedAccount,\n { waitForPropagation: false },\n );\n this.#setHandleResult(item, decrypted);\n } catch (error) {\n if (isFatalBatchError(error)) {\n aborted = true;\n fatal ??= error;\n return;\n }\n item.error = this.#toZamaError(error, \"Failed to decrypt delegated encrypted values\", {\n isDelegated: true,\n contractAddress: item.contractAddress,\n account: getAddress(delegatorAddress),\n });\n }\n }),\n maxConcurrency,\n );\n\n if (fatal !== undefined) {\n throw fatal;\n }\n\n return { items };\n }\n\n /**\n * Run a user (or delegated-user) decrypt for one contract: rebuild the\n * `@fhevm/sdk` transport key pair and signed permit from the resolved permit,\n * then decrypt. The delegation, if any, is encoded in the permit — both paths\n * share this call. Returns the positional clear values for `encryptedValues`.\n */\n async #decryptValues(\n credentials: SerializedTransportKeyPairWithPermissions,\n contractAddress: Address,\n encryptedValues: EncryptedValue[],\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<DecryptValuesReturnType> {\n const permit = resolvePermit(credentials, contractAddress);\n let transportKeyPair: ParseTransportKeyPairReturnType;\n try {\n transportKeyPair = await this.#router.relayer.parseTransportKeyPair({\n publicKey: permit.publicKey,\n privateKey: permit.privateKey,\n tkmsVersion: credentials.keypair.tkmsVersion,\n });\n } catch (error) {\n // Stale key pair the relayer can't re-derive (post KMS/TKMS rotation):\n // evict it so the next resolveCredentials regenerates and re-signs.\n // wrapDecryptError maps the raw message to InvalidTransportKeyPairError.\n if (error instanceof Error && isInvalidTransportKeyPairMessage(error.message)) {\n await this.#credentialService.evictTransportKeyPair();\n }\n throw error;\n }\n const signedPermit = await this.#router.relayer.parseSignedDecryptionPermit({\n transportKeyPair,\n serializedPermit: permit.serializedPermit,\n });\n return this.#router.relayer.decryptValues({\n transportKeyPair,\n signedPermit,\n encryptedValues,\n contractAddress,\n options,\n });\n }\n\n async #decrypt(\n handles: EncryptedInput[],\n strategy: DecryptionStrategy,\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n recovery: RecoveryBudget = { spent: false },\n ): Promise<Record<EncryptedValue, ClearValue>> {\n if (handles.length === 0) {\n return {};\n }\n\n const normalized = handles.map((h) => ({\n encryptedValue: h.encryptedValue,\n contractAddress: getAddress(h.contractAddress),\n }));\n const result: Record<EncryptedValue, ClearValue> = {};\n const nonZero: EncryptedInput[] = [];\n\n for (const h of normalized) {\n if (isEncryptedValueZero(h.encryptedValue)) {\n result[h.encryptedValue] = 0n;\n } else {\n nonZero.push(h);\n }\n }\n\n if (nonZero.length === 0) {\n return result;\n }\n\n const allContracts = Array.from(new Set(normalized.map((h) => h.contractAddress)));\n const nonZeroContracts = Array.from(new Set(nonZero.map((h) => h.contractAddress)));\n if (strategy.validate) {\n try {\n await strategy.validate(nonZeroContracts);\n } catch (error) {\n // The delegation pre-check makes on-chain reads too; classify a throttled\n // RPC here as well so delegated decrypt branches deterministically.\n if (isRpcRateLimitError(error)) {\n throw this.#rpcRateLimitError(error, \"the delegation pre-check\");\n }\n throw error;\n }\n }\n\n const uncached: EncryptedInput[] = [];\n for (const h of nonZero) {\n const cached = await this.#cache.get(\n strategy.requesterAddress,\n h.contractAddress,\n h.encryptedValue,\n );\n if (cached !== null) {\n result[h.encryptedValue] = cached;\n } else {\n uncached.push(h);\n }\n }\n\n if (uncached.length === 0) {\n return result;\n }\n\n let credentials = await this.#credentialService.grantPermit(allContracts, strategy.delegator);\n\n const byContract = new Map<Address, EncryptedValue[]>();\n for (const h of uncached) {\n const existing = byContract.get(h.contractAddress);\n if (existing) {\n existing.push(h.encryptedValue);\n } else {\n byContract.set(h.contractAddress, [h.encryptedValue]);\n }\n }\n\n // Split each contract's handles to stay under the relayer's per-request\n // cleartext-bit budget — a contract with many/wide handles becomes\n // several relayer calls instead of one oversized, rejected call.\n const requests: DecryptRequest[] = [];\n for (const [contractAddress, encryptedValues] of byContract) {\n for (const chunk of chunkHandlesByBitBudget(encryptedValues)) {\n requests.push({ contractAddress, encryptedValues: chunk });\n }\n }\n\n const t0 = Date.now();\n const uncachedEncryptedValues = uncached.map((h) => h.encryptedValue);\n try {\n this.#emitEvent({\n type: ZamaSDKEvents.DecryptStart,\n encryptedValues: uncachedEncryptedValues,\n });\n\n try {\n await this.#runDecryptRequests(strategy, credentials, requests, result, options);\n } catch (error) {\n if (!(error instanceof RevokedKmsContextError) || recovery.spent) {\n throw error;\n }\n // Identify the permits this attempt used: if they are already gone from\n // the store, a sibling decrypt recovered the scope and re-signing would\n // cost a second prompt for nothing.\n const staleSignatures = credentials.permissions.map((p) => p.serializedPermit.signature);\n // Re-grant under the current context and retry the still-unresolved\n // chunks once; a second revoked failure surfaces instead of looping\n // into the upstream 15-minute validity cache. Spent is set before\n // awaiting so a failing re-grant cannot re-arm the budget.\n recovery.spent = true;\n try {\n credentials = await this.#credentialService.recoverPermits(\n allContracts,\n strategy.delegator,\n staleSignatures,\n );\n } catch (recoveryError) {\n // A re-grant the signer cannot complete must not mask the revocation:\n // the caller's remedy is a new permit, not a signing fix. A user\n // rejecting the prompt stays a rejection.\n if (recoveryError instanceof SigningFailedError) {\n throw new RevokedKmsContextError(\n \"The permit's KMS context has been revoked on-chain and the automatic re-grant \" +\n \"failed, so the decrypt cannot proceed. Establish a new permit for this scope \" +\n \"and retry.\",\n { cause: recoveryError },\n );\n }\n throw recoveryError;\n }\n await this.#runDecryptRequests(\n strategy,\n credentials,\n requests.filter(({ encryptedValues }) =>\n encryptedValues.some((encryptedValue) => result[encryptedValue] === undefined),\n ),\n result,\n options,\n );\n }\n\n const uncachedResult: Record<EncryptedValue, ClearValue> = {};\n for (const encryptedValue of uncachedEncryptedValues) {\n const value = result[encryptedValue];\n if (value !== undefined) {\n uncachedResult[encryptedValue] = value;\n }\n }\n this.#emitEvent({\n type: ZamaSDKEvents.DecryptEnd,\n durationMs: Date.now() - t0,\n encryptedValues: uncachedEncryptedValues,\n result: uncachedResult,\n });\n return result;\n } catch (error) {\n // Per-contract failures are already classified into a typed ZamaError whose\n // `cause` is the original failure; surface that original in the observability\n // event so monitoring keeps the root-cause message.\n const original =\n error instanceof ZamaError && error.cause instanceof Error ? error.cause : error;\n this.#emitEvent({\n type: ZamaSDKEvents.DecryptError,\n error: toError(original),\n durationMs: Date.now() - t0,\n encryptedValues: uncachedEncryptedValues,\n });\n // The per-contract wrap above already classified these; this is a passthrough\n // for them plus a fallback for any non-contract failure (e.g. caching).\n throw wrapDecryptError(error, strategy.errorMessage, {\n isDelegated: strategy.delegator !== undefined,\n });\n }\n }\n\n /**\n * Fan the decrypt requests out (bounded concurrency), writing clear values\n * into `result` and the cache as each settles. Every request is settled\n * before anything is thrown: pLimit rejects on the first settled failure\n * while siblings are still in flight, which would let a sibling's earlier\n * failure hide a revoked-context revert from the recovery decision and let\n * the retry race workers still writing into `result`. Among the settled\n * failures, a {@link RevokedKmsContextError} is surfaced in preference to\n * whichever happened to settle first, so the self-heal always sees it.\n */\n async #runDecryptRequests(\n strategy: DecryptionStrategy,\n credentials: SerializedTransportKeyPairWithPermissions,\n requests: DecryptRequest[],\n result: Record<EncryptedValue, ClearValue>,\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<void> {\n const outcomes = await pLimit(\n requests.map(({ contractAddress, encryptedValues }) => async (): Promise<unknown> => {\n try {\n await this.#decryptRequest(\n strategy,\n credentials,\n contractAddress,\n encryptedValues,\n result,\n options,\n );\n return undefined;\n } catch (error) {\n return error;\n }\n }),\n 5,\n );\n const failures = outcomes.filter((outcome) => outcome !== undefined);\n if (failures.length > 0) {\n throw failures.find((failure) => failure instanceof RevokedKmsContextError) ?? failures[0];\n }\n }\n\n /** Decrypt one contract's chunk of handles into `result` (and the cache). */\n async #decryptRequest(\n strategy: DecryptionStrategy,\n credentials: SerializedTransportKeyPairWithPermissions,\n contractAddress: Address,\n encryptedValues: EncryptedValue[],\n result: Record<EncryptedValue, ClearValue>,\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<void> {\n // Classify per contract so a not-entitled / relayer failure carries the\n // exact contract + ACL actor. Already-typed errors pass straight through.\n let decrypted: DecryptValuesReturnType;\n try {\n decrypted = await this.#decryptValues(credentials, contractAddress, encryptedValues, options);\n } catch (error) {\n throw wrapDecryptError(error, strategy.errorMessage, {\n isDelegated: strategy.delegator !== undefined,\n contractAddress,\n account: strategy.delegator ?? strategy.requesterAddress,\n });\n }\n\n // `decryptValues` returns clear values positionally aligned with the\n // requested `encryptedValues`; zip them back into the handle→value map.\n for (let i = 0; i < encryptedValues.length; i++) {\n const encryptedValue = encryptedValues[i];\n const value = decrypted[i]?.value;\n if (encryptedValue === undefined || value === undefined) {\n continue;\n }\n result[encryptedValue] = value;\n await this.#cache.set(strategy.requesterAddress, contractAddress, encryptedValue, value);\n }\n\n const missing = encryptedValues.filter(\n (encryptedValue) => result[encryptedValue] === undefined,\n );\n if (missing.length > 0) {\n throw new DecryptionFailedError(\n `${strategy.errorMessage}: relayer returned no clear value for ${missing.length} of ${encryptedValues.length} handle(s) on ${contractAddress}`,\n {\n cause: new AggregateError(\n missing.map(\n (encryptedValue) =>\n new DecryptionFailedError(\n `No clear value for handle ${encryptedValue} on ${contractAddress}`,\n ),\n ),\n `${missing.length} handle(s) missing a clear value on ${contractAddress}`,\n ),\n },\n );\n }\n }\n\n /** Build an `RpcRateLimitError` for a throttled on-chain read. */\n #rpcRateLimitError(error: unknown, context: string): RpcRateLimitError {\n return new RpcRateLimitError(`RPC provider rate-limited ${context}; retry with backoff.`, {\n cause: error,\n retryAfter: extractRetryAfter(error),\n });\n }\n\n #setHandleResult(item: BatchDecryptItem, decrypted: Record<EncryptedValue, ClearValue>): void {\n const value = decrypted[item.encryptedValue];\n if (value === undefined) {\n item.error = new DecryptionFailedError(\n `Batch delegated decryption returned no value for encrypted value ${item.encryptedValue} on contract ${item.contractAddress}`,\n );\n return;\n }\n item.value = value;\n }\n\n #toZamaError(error: unknown, fallbackMessage: string, ctx?: DecryptErrorContext): ZamaError {\n return error instanceof ZamaError ? error : wrapDecryptError(error, fallbackMessage, ctx);\n }\n\n #missingBatchItem(): never {\n throw new DecryptionFailedError(\"Batch delegated decryption invariant failed: missing item\");\n }\n\n async #assertAllDelegationsActive(\n contractAddresses: readonly Address[],\n { delegatorAddress, delegateAddress }: { delegatorAddress: Address; delegateAddress: Address },\n ): Promise<void> {\n const inactive = await this.#delegationService.findInactiveDelegations(\n contractAddresses,\n delegatorAddress,\n delegateAddress,\n );\n if (inactive.size === 0) {\n return;\n }\n for (const error of inactive.values()) {\n throw error;\n }\n }\n}\n","import type { ZamaError } from \"./base\";\nimport { extractRevertErrorName } from \"./revert\";\nimport {\n AclPausedError,\n DelegationContractIsSelfError,\n DelegationCooldownError,\n DelegationDelegateEqualsContractError,\n DelegationExpirationTooSoonError,\n DelegationExpiryUnchangedError,\n DelegationNotFoundError,\n DelegationSelfNotAllowedError,\n} from \"./delegation\";\n\n/** ACL error name -> typed SDK error mapping. */\nconst ACL_ERROR_MAP = {\n AlreadyDelegatedOrRevokedInSameBlock: (cause) =>\n new DelegationCooldownError(\n \"Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.\",\n { cause },\n ),\n SenderCannotBeContractAddress: (cause) =>\n new DelegationContractIsSelfError(\"The contract address cannot be the caller address.\", {\n cause,\n }),\n EnforcedPause: (cause) =>\n new AclPausedError(\n \"The ACL contract is paused. Delegation operations are temporarily disabled.\",\n { cause },\n ),\n SenderCannotBeDelegate: (cause) =>\n new DelegationSelfNotAllowedError(\"Cannot delegate to yourself (delegate === msg.sender).\", {\n cause,\n }),\n DelegateCannotBeContractAddress: (cause) =>\n new DelegationDelegateEqualsContractError(\n \"Delegate address cannot be the same as the contract address.\",\n { cause },\n ),\n ExpirationDateBeforeOneHour: (cause) =>\n new DelegationExpirationTooSoonError(\"Expiration date must be at least 1 hour in the future.\", {\n cause,\n }),\n ExpirationDateAlreadySetToSameValue: (cause) =>\n new DelegationExpiryUnchangedError(\"The new expiration date is the same as the current one.\", {\n cause,\n }),\n NotDelegatedYet: (cause) =>\n new DelegationNotFoundError(\"Cannot revoke: no active delegation exists.\", { cause }),\n} satisfies Record<string, (cause: unknown) => ZamaError>;\n\nfunction isAclRevertName(name: string): name is keyof typeof ACL_ERROR_MAP {\n return Object.hasOwn(ACL_ERROR_MAP, name);\n}\n\n/**\n * Map known ACL Solidity revert error names to typed ZamaError subclasses.\n * Prefers viem's structured `error.cause.data.errorName` when available,\n * falling back to string-includes matching on the error message.\n * Returns `null` if the revert reason is not recognized.\n * @internal\n */\nexport function matchAclRevert(error: unknown, mappedCause: unknown): ZamaError | null {\n // Prefer structured error data from viem's ContractFunctionRevertedError\n const errorName = extractRevertErrorName(error);\n if (errorName && isAclRevertName(errorName)) {\n return ACL_ERROR_MAP[errorName](mappedCause);\n }\n\n // Fallback: string matching for non-viem RPC providers\n const message = error instanceof Error ? error.message : String(error);\n for (const [name, factory] of Object.entries(ACL_ERROR_MAP)) {\n if (message.includes(name)) {\n return factory(mappedCause);\n }\n }\n\n return null;\n}\n","import { getAddress, type Address } from \"viem\";\nimport {\n delegateForUserDecryptionContract,\n getDelegationExpiryContract,\n MAX_UINT64,\n revokeDelegationContract,\n} from \"../contracts\";\nimport {\n DelegationDelegateEqualsContractError,\n DelegationExpirationTooSoonError,\n DelegationExpiredError,\n DelegationExpiryUnchangedError,\n DelegationNotFoundError,\n DelegationSelfNotAllowedError,\n TransactionRevertedError,\n} from \"../errors\";\nimport { matchAclRevert } from \"../errors/acl-revert\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport type { ChainRouter } from \"../chains/router\";\nimport type {\n GenericLogger,\n GenericProvider,\n GenericSigner,\n TransactionResult,\n WriteContractConfig,\n} from \"../types\";\nimport { submitTransaction } from \"../utils/submit-transaction\";\n\ntype AclTransactionOperation = Extract<\n TransactionOperation,\n \"delegateDecryption\" | \"revokeDelegation\"\n>;\n\n/** Delegation activity and expiry, resolved from a single expiry read. */\nexport interface DelegationStatus {\n /** Whether the delegation is currently active (exists and not expired). */\n isActive: boolean;\n /** Unix timestamp (seconds) when the delegation expires; `0n` if none exists. */\n expiryTimestamp: bigint;\n}\n\n/** @internal */\nexport class DelegationService {\n readonly #router: ChainRouter;\n readonly #provider: GenericProvider;\n readonly #emitEvent: (input: ZamaSDKEventInput, tokenAddress?: Address) => void;\n readonly #logger: GenericLogger;\n\n constructor({\n provider,\n router,\n emitEvent = () => {},\n logger,\n }: {\n provider: GenericProvider;\n router: ChainRouter;\n logger: GenericLogger;\n emitEvent?: (input: ZamaSDKEventInput, tokenAddress?: Address) => void;\n }) {\n this.#provider = provider;\n this.#router = router;\n this.#logger = logger;\n this.#emitEvent = emitEvent;\n }\n\n async delegateDecryption(\n signer: GenericSigner,\n {\n contractAddress,\n delegateAddress,\n delegatorAddress,\n expirationDate,\n }: {\n contractAddress: Address;\n delegateAddress: Address;\n delegatorAddress: Address;\n expirationDate?: Date;\n },\n ): Promise<TransactionResult> {\n if (expirationDate && expirationDate.getTime() < Date.now() + 3600_000) {\n throw new DelegationExpirationTooSoonError(\n \"Expiration date must be at least 1 hour in the future\",\n );\n }\n\n const normalizedContract = getAddress(contractAddress);\n const normalizedDelegate = getAddress(delegateAddress);\n const normalizedDelegator = getAddress(delegatorAddress);\n\n if (normalizedDelegate === normalizedDelegator) {\n throw new DelegationSelfNotAllowedError(\n \"Cannot delegate to yourself (delegate === msg.sender).\",\n );\n }\n\n if (normalizedDelegate === normalizedContract) {\n throw new DelegationDelegateEqualsContractError(\n `Delegate address cannot be the same as the contract address (${normalizedContract}).`,\n );\n }\n\n const acl = this.#router.relayer.chain.aclContractAddress;\n const expDate = expirationDate\n ? BigInt(Math.floor(expirationDate.getTime() / 1000))\n : MAX_UINT64;\n\n let currentExpiry: bigint;\n try {\n currentExpiry = await this.getDelegationExpiry({\n contractAddress: normalizedContract,\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n });\n } catch (error) {\n this.#logger.warn(\"delegateDecryption: pre-flight expiry check failed\", { error });\n currentExpiry = -1n;\n }\n if (currentExpiry === expDate) {\n throw new DelegationExpiryUnchangedError(\n `The new expiration date (${expDate}) is the same as the current one. No on-chain change needed.`,\n );\n }\n\n return this.#submitAclTransaction({\n operation: \"delegateDecryption\",\n signer,\n contractAddress: normalizedContract,\n config: delegateForUserDecryptionContract(\n acl,\n normalizedDelegate,\n normalizedContract,\n expDate,\n ),\n });\n }\n\n async revokeDelegation(\n signer: GenericSigner,\n {\n contractAddress,\n delegateAddress,\n delegatorAddress,\n }: { contractAddress: Address; delegateAddress: Address; delegatorAddress: Address },\n ): Promise<TransactionResult> {\n const normalizedContract = getAddress(contractAddress);\n const normalizedDelegate = getAddress(delegateAddress);\n const normalizedDelegator = getAddress(delegatorAddress);\n const acl = this.#router.relayer.chain.aclContractAddress;\n\n let currentExpiry: bigint;\n try {\n currentExpiry = await this.getDelegationExpiry({\n contractAddress: normalizedContract,\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n });\n } catch (error) {\n this.#logger.warn(\"revokeDelegation: pre-flight expiry check failed\", { error });\n currentExpiry = 1n;\n }\n if (currentExpiry === 0n) {\n throw new DelegationNotFoundError(\n `No active delegation found for delegate ${normalizedDelegate} on contract ${normalizedContract}.`,\n );\n }\n\n return this.#submitAclTransaction({\n operation: \"revokeDelegation\",\n signer,\n contractAddress: normalizedContract,\n config: revokeDelegationContract(acl, normalizedDelegate, normalizedContract),\n });\n }\n\n async isDelegated(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<boolean> {\n return (await this.getStatus(params)).isActive;\n }\n\n /**\n * Resolve activity and expiry together from a single {@link getDelegationExpiry} read,\n * instead of two separate round trips through {@link isDelegated} and\n * {@link getDelegationExpiry}.\n */\n async getStatus(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<DelegationStatus> {\n const expiryTimestamp = await this.getDelegationExpiry(params);\n if (expiryTimestamp === 0n) {\n return { isActive: false, expiryTimestamp };\n }\n if (expiryTimestamp === MAX_UINT64) {\n return { isActive: true, expiryTimestamp };\n }\n const now = await this.#provider.getBlockTimestamp();\n return { isActive: expiryTimestamp > now, expiryTimestamp };\n }\n\n async getDelegationExpiry({\n contractAddress,\n delegatorAddress,\n delegateAddress,\n }: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<bigint> {\n const acl = this.#router.relayer.chain.aclContractAddress;\n return this.#provider.readContract(\n getDelegationExpiryContract(\n acl,\n getAddress(delegatorAddress),\n getAddress(delegateAddress),\n getAddress(contractAddress),\n ),\n );\n }\n\n async #submitAclTransaction({\n operation,\n signer,\n contractAddress,\n config,\n }: {\n operation: AclTransactionOperation;\n signer: GenericSigner;\n contractAddress: Address;\n config: WriteContractConfig;\n }): Promise<TransactionResult> {\n try {\n return await submitTransaction({\n operation,\n signer,\n provider: this.#provider,\n config,\n emit: (input) => this.#emitEvent(input, contractAddress),\n logger: this.#logger,\n });\n } catch (error) {\n this.#throwAclRevertIfMatched(error);\n throw error;\n }\n }\n\n #throwAclRevertIfMatched(error: unknown): void {\n if (!(error instanceof TransactionRevertedError)) {\n return;\n }\n const mapped = matchAclRevert(error.cause ?? error, error);\n if (mapped) {\n throw mapped;\n }\n }\n\n async findInactiveDelegations(\n contractAddresses: readonly Address[],\n delegatorAddress: Address,\n delegateAddress: Address,\n ): Promise<Map<Address, DelegationNotFoundError | DelegationExpiredError>> {\n const inactive = new Map<Address, DelegationNotFoundError | DelegationExpiredError>();\n await Promise.all(\n contractAddresses.map(async (contractAddress) => {\n try {\n await this.assertDelegationActive(contractAddress, delegatorAddress, delegateAddress);\n } catch (error) {\n if (error instanceof DelegationNotFoundError || error instanceof DelegationExpiredError) {\n const normalizedContract = getAddress(contractAddress);\n inactive.set(normalizedContract, error);\n return;\n }\n throw error;\n }\n }),\n );\n return inactive;\n }\n\n async assertDelegationActive(\n contractAddress: Address,\n delegatorAddress: Address,\n delegateAddress: Address,\n ): Promise<void> {\n const normalizedContract = getAddress(contractAddress);\n const normalizedDelegator = getAddress(delegatorAddress);\n const normalizedDelegate = getAddress(delegateAddress);\n const { isActive, expiryTimestamp } = await this.getStatus({\n contractAddress: normalizedContract,\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n });\n if (isActive) {\n return;\n }\n if (expiryTimestamp === 0n) {\n throw new DelegationNotFoundError(\n `No active delegation from ${normalizedDelegator} to ${normalizedDelegate} for ${normalizedContract}`,\n );\n }\n throw new DelegationExpiredError(\n `Delegation from ${normalizedDelegator} to ${normalizedDelegate} for ${normalizedContract} has expired`,\n );\n }\n}\n","import { getAddress } from \"viem\";\nimport type { ChainRouter } from \"../chains/router\";\nimport { wrapEncryptError } from \"../errors\";\nimport type { ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { ZamaSDKEvents } from \"../events/sdk-events\";\nimport type { EncryptParams, EncryptResult, FhevmRelayerOptions } from \"../relayer/types\";\nimport { toError } from \"../utils\";\n\nexport class EncryptionService {\n readonly #router: ChainRouter;\n readonly #emitEvent: (\n input: ZamaSDKEventInput,\n tokenAddress?: EncryptParams[\"contractAddress\"],\n ) => void;\n\n constructor({\n router,\n emitEvent,\n }: {\n router: ChainRouter;\n emitEvent: (input: ZamaSDKEventInput, tokenAddress?: EncryptParams[\"contractAddress\"]) => void;\n }) {\n this.#router = router;\n this.#emitEvent = emitEvent;\n }\n\n async encryptValues(\n params: EncryptParams,\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<EncryptResult> {\n const t0 = Date.now();\n const normalizedContractAddress = getAddress(params.contractAddress);\n try {\n this.#emitEvent({ type: ZamaSDKEvents.EncryptStart }, normalizedContractAddress);\n const result = await this.#router.relayer.encryptValues({ ...params, options });\n this.#emitEvent(\n { type: ZamaSDKEvents.EncryptEnd, durationMs: Date.now() - t0 },\n normalizedContractAddress,\n );\n return result;\n } catch (error) {\n this.#emitEvent(\n { type: ZamaSDKEvents.EncryptError, error: toError(error), durationMs: Date.now() - t0 },\n normalizedContractAddress,\n );\n throw wrapEncryptError(error, \"Encryption failed\");\n }\n }\n}\n","import type { CredentialService } from \"../credentials/credential-service\";\nimport type { ChainRouter } from \"../chains/router\";\nimport type {\n GenericLogger,\n GenericSigner,\n WalletAccountChange,\n WalletAccountListener,\n} from \"../types\";\nimport { swallow } from \"../utils\";\nimport type { CachingService } from \"./caching-service\";\n\nexport type LifecycleServiceOptions = {\n signer?: GenericSigner;\n router: ChainRouter;\n cachingService: CachingService;\n credentialService?: CredentialService;\n logger: GenericLogger;\n};\n\n/**\n * Owns signer-lifecycle wiring for {@link ZamaSDK}: subscribes to the signer's\n * wallet-account store on construction, runs the SDK-side cleanup (credential\n * rotation, decrypt-cache invalidation, relayer chain switch) on every change,\n * then fans out to external listeners. Unsubscribes on {@link dispose}.\n *\n * @internal — consumed by ZamaSDK; not part of the public surface.\n */\nexport class LifecycleService {\n readonly #signer: GenericSigner | undefined;\n readonly #router: ChainRouter;\n readonly #cachingService: CachingService;\n readonly #credentialService: CredentialService | undefined;\n readonly #logger: GenericLogger;\n readonly #walletAccountListeners = new Set<WalletAccountListener>();\n #unsubscribeSigner?: () => void;\n\n constructor(opts: LifecycleServiceOptions) {\n this.#signer = opts.signer;\n this.#router = opts.router;\n this.#cachingService = opts.cachingService;\n this.#credentialService = opts.credentialService;\n this.#logger = opts.logger;\n if (this.#signer) {\n this.#unsubscribeSigner = this.#signer.walletAccount.subscribe((change) => {\n this.#handleWalletAccountChange(change).catch((error) => {\n this.#logger.warn(\"wallet account handler failed\", { error });\n });\n });\n }\n }\n\n onWalletAccountChange(listener: WalletAccountListener): () => void {\n this.#walletAccountListeners.add(listener);\n return () => {\n this.#walletAccountListeners.delete(listener);\n };\n }\n\n dispose(): void {\n this.#unsubscribeSigner?.();\n this.#unsubscribeSigner = undefined;\n this.#walletAccountListeners.clear();\n }\n\n async #handleWalletAccountChange(change: WalletAccountChange): Promise<void> {\n const prev = change.previous;\n const next = change.next;\n // switchChain runs first so credential cleanup, decrypt-cache invalidation,\n // and external listeners observe the router on next.chainId. Downstream\n // keypair warming (driven by listeners — see ZamaProvider) therefore\n // dispatches against the wallet chain rather than chains[0]. Switching to a\n // chain with no configured backend does not throw here — the router tracks\n // it and the next relayer op surfaces a ConfigurationError — so `swallow`\n // is defensive only. It suspends one microtask for error containment, not\n // for I/O; ChainRouter.switchChain is synchronous.\n const nextChainId = next?.chainId;\n if (nextChainId !== undefined) {\n await swallow(\n \"switch relayer chain\",\n () => this.#router.switchChain(nextChainId),\n this.#logger,\n );\n }\n const credentialService = this.#credentialService;\n if (credentialService) {\n await swallow(\n \"credential wallet account change\",\n () => credentialService.handleWalletAccountChange(prev, next),\n this.#logger,\n );\n }\n if (prev) {\n await swallow(\n \"clear decrypt cache\",\n () => this.#cachingService.clearForRequester(prev.address),\n this.#logger,\n );\n }\n await Promise.all(\n Array.from(this.#walletAccountListeners, (listener) =>\n swallow(\"wallet account listener\", () => listener(change), this.#logger),\n ),\n );\n }\n}\n","import { size } from \"viem\";\nimport { z } from \"zod/mini\";\nimport type {\n ApproveUnderlyingRequest,\n ConfidentialTransferFromRequest,\n ConfidentialTransferRequest,\n DelegateDecryptionRequest,\n FinalizeUnwrapRequest,\n PrepareOptions,\n PrepareTransactionRequest,\n RevokeDelegationRequest,\n SetOperatorRequest,\n TransferAndCallRequest,\n UnwrapAllRequest,\n UnwrapRequest,\n WrapRequest,\n WriteContractConfig,\n} from \"../types\";\nimport { checksummedAddress, hex, unixSeconds } from \"./primitives\";\n\n/**\n * {@link ConfidentialTransferRequest} schema.\n * @internal\n */\nexport const confidentialTransferRequest = z.object({\n kind: z.literal(\"ConfidentialTransfer\"),\n from: checksummedAddress,\n token: checksummedAddress,\n to: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<ConfidentialTransferRequest>;\n\n/**\n * {@link ConfidentialTransferFromRequest} schema.\n * @internal\n */\nexport const confidentialTransferFromRequest = z.object({\n kind: z.literal(\"ConfidentialTransferFrom\"),\n from: checksummedAddress,\n token: checksummedAddress,\n owner: checksummedAddress,\n to: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<ConfidentialTransferFromRequest>;\n\n/**\n * {@link SetOperatorRequest} schema. `until` is a required unix timestamp\n * (seconds); pass `0 < until < now` to revoke.\n * @internal\n */\nexport const setOperatorRequest = z.object({\n kind: z.literal(\"SetOperator\"),\n from: checksummedAddress,\n token: checksummedAddress,\n operator: checksummedAddress,\n until: unixSeconds,\n}) satisfies z.ZodMiniType<SetOperatorRequest>;\n\n/**\n * {@link UnwrapRequest} schema.\n * @internal\n */\nexport const unwrapRequest = z.object({\n kind: z.literal(\"Unwrap\"),\n from: checksummedAddress,\n token: checksummedAddress,\n to: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<UnwrapRequest>;\n\n/**\n * {@link UnwrapAllRequest} schema.\n * @internal\n */\nexport const unwrapAllRequest = z.object({\n kind: z.literal(\"UnwrapAll\"),\n from: checksummedAddress,\n token: checksummedAddress,\n to: checksummedAddress,\n}) satisfies z.ZodMiniType<UnwrapAllRequest>;\n\n/**\n * {@link FinalizeUnwrapRequest} schema.\n * @internal\n */\nexport const finalizeUnwrapRequest = z.object({\n kind: z.literal(\"FinalizeUnwrap\"),\n from: checksummedAddress,\n wrapper: checksummedAddress,\n unwrapRequestIdOrAmount: hex,\n}) satisfies z.ZodMiniType<FinalizeUnwrapRequest>;\n\n/**\n * {@link ApproveUnderlyingRequest} schema.\n * @internal\n */\nexport const approveUnderlyingRequest = z.object({\n kind: z.literal(\"ApproveUnderlying\"),\n from: checksummedAddress,\n underlying: checksummedAddress,\n spender: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<ApproveUnderlyingRequest>;\n\n/**\n * {@link WrapRequest} schema.\n * @internal\n */\nexport const wrapRequest = z.object({\n kind: z.literal(\"Wrap\"),\n from: checksummedAddress,\n wrapper: checksummedAddress,\n to: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<WrapRequest>;\n\n/**\n * `TransferAndCall` recipient payload: `0x` (self-shield to the sender) or a\n * raw 20-byte address. The wrapper's receiver hook does\n * `to = data.length < 20 ? from : address(bytes20(data))`, so any other\n * non-empty value (e.g. a 32-byte ABI-encoded address) is truncated to its\n * first 20 bytes — minting the shielded funds to a garbage address. Reject\n * those rather than let the funds go astray; omit for a self-shield.\n */\nconst recipientData = hex.check(\n z.refine(\n (data) => data === \"0x\" || size(data) === 20,\n 'TransferAndCall.recipientData must be \"0x\" (self-shield to the sender) or a raw 20-byte address, ' +\n \"not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address\",\n ),\n);\n\n/**\n * {@link TransferAndCallRequest} schema. `recipientData` is 20 raw bytes or `0x`.\n * @internal\n */\nexport const transferAndCallRequest = z.object({\n kind: z.literal(\"TransferAndCall\"),\n from: checksummedAddress,\n underlying: checksummedAddress,\n wrapper: checksummedAddress,\n amount: z.bigint(),\n recipientData: z.optional(recipientData),\n}) satisfies z.ZodMiniType<TransferAndCallRequest>;\n\n/**\n * {@link DelegateDecryptionRequest} schema. Input takes an optional\n * `expirationDate` (a `Date`); the parsed output is the on-chain `uint64`\n * expiry — seconds since epoch, or `MAX_UINT64` (\"permanent\") when omitted —\n * so callers never hand-roll the encoding.\n *\n * The ≥1h-in-the-future expiry check and the self/contract guards live in the\n * `#buildDelegateDecryption` builder (they throw domain-specific delegation\n * errors this schema can't).\n * @internal\n */\nexport const delegateDecryptionRequest = z.object({\n kind: z.literal(\"DelegateDecryption\"),\n from: checksummedAddress,\n contractAddress: checksummedAddress,\n delegateAddress: checksummedAddress,\n expirationDate: z.optional(z.date()),\n}) satisfies z.ZodMiniType<DelegateDecryptionRequest>;\n\n/**\n * {@link RevokeDelegationRequest} schema.\n * @internal\n */\nexport const revokeDelegationRequest = z.object({\n kind: z.literal(\"RevokeDelegation\"),\n from: checksummedAddress,\n contractAddress: checksummedAddress,\n delegateAddress: checksummedAddress,\n}) satisfies z.ZodMiniType<RevokeDelegationRequest>;\n\n/**\n * Discriminated union (on `kind`) of every offline `prepare` request. Backs\n * both the {@link PrepareTransactionRequest} type and the runtime validation\n * in `OfflineService.prepare`.\n * @internal\n */\nexport const prepareTransactionRequest = z.discriminatedUnion(\"kind\", [\n confidentialTransferRequest,\n confidentialTransferFromRequest,\n setOperatorRequest,\n unwrapRequest,\n unwrapAllRequest,\n finalizeUnwrapRequest,\n approveUnderlyingRequest,\n wrapRequest,\n transferAndCallRequest,\n delegateDecryptionRequest,\n revokeDelegationRequest,\n]) satisfies z.ZodMiniType<PrepareTransactionRequest>;\n\n/**\n * {@link PrepareFees} schema. `maxFeePerGas` and `maxPriorityFeePerGas` live in\n * one object so they can only be supplied together — pinning a cap (the total\n * fee) while the tip is estimated can produce a tip above the cap and fail\n * serialization. Both legs are validated as `bigint` so a JS caller (no\n * compiler) can't slip a `number` into the frozen, signed payload.\n * @internal\n */\nexport const fees = z.strictObject({ maxFeePerGas: z.bigint(), maxPriorityFeePerGas: z.bigint() });\n\n/**\n * {@link PrepareOptions} schema. All fields are optional; omitted ones fall\n * back to the provider's live chain-state defaults.\n * @internal\n */\nexport const prepareOptions = z.object({\n nonce: z.optional(z.int().check(z.nonnegative())),\n gasLimit: z.optional(z.bigint()),\n fees: z.optional(fees),\n}) satisfies z.ZodMiniType<PrepareOptions>;\n\n/**\n * `WriteContractConfig` schema. `abi` and `args` are validated only as\n * arrays — their element shapes are the ABI-typed `TAbi`/`TFunctionName`\n * generics the runtime can't check — so this guards the structural envelope\n * (address, function name, the two arrays, optional `value`/`gas`) a provider's\n * tx-builder consumes.\n * @internal\n */\nexport const writeContractConfig = z.object({\n address: checksummedAddress,\n abi: z.array(z.unknown()),\n functionName: z.string(),\n args: z.array(z.unknown()),\n value: z.optional(z.bigint()),\n gas: z.optional(z.bigint()),\n}) satisfies z.ZodMiniType<WriteContractConfig>;\n\n/**\n * Schema for the argument object of `GenericProvider.prepareTransaction`:\n * the originating `from` wallet, the write-contract `calldata`, and the\n * optional chain-state overrides. Extends {@link prepareOptions} so the\n * `nonce`/`gasLimit`/`fees` legs stay in lockstep with the per-call overrides.\n *\n * `from` is EIP-55 checksummed on parse (the custodian keys off it), so the\n * validated output can flow straight into the prepared handoff.\n * @internal\n */\nexport const prepareTransactionParams = z.extend(prepareOptions, {\n from: checksummedAddress,\n calldata: writeContractConfig,\n});\n","import type { Address } from \"viem\";\nimport type { ChainRouter } from \"../chains/router\";\nimport {\n approveContract,\n confidentialBalanceOfContract,\n confidentialTransferContract,\n confidentialTransferFromContract,\n delegateForUserDecryptionContract,\n finalizeUnwrapContract,\n MAX_UINT64,\n revokeDelegationContract,\n setOperatorContract,\n transferAndCallContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n} from \"../contracts\";\nimport {\n ConfigurationError,\n DelegationDelegateEqualsContractError,\n DelegationExpirationTooSoonError,\n DelegationSelfNotAllowedError,\n EncryptionFailedError,\n wrapDecryptError,\n} from \"../errors\";\nimport type { ZamaSDKEventInput } from \"../events/sdk-events\";\nimport {\n approveUnderlyingRequest,\n confidentialTransferFromRequest,\n confidentialTransferRequest,\n delegateDecryptionRequest,\n finalizeUnwrapRequest,\n prepareOptions,\n prepareTransactionParams,\n revokeDelegationRequest,\n setOperatorRequest,\n transferAndCallRequest,\n unwrapAllRequest,\n unwrapRequest,\n wrapRequest,\n} from \"../schemas/offline\";\nimport type {\n ApproveUnderlyingRequest,\n ConfidentialTransferFromRequest,\n ConfidentialTransferRequest,\n DelegateDecryptionRequest,\n FinalizeUnwrapRequest,\n GenericProvider,\n PreparedFor,\n PrepareOptions,\n PrepareTransactionRequest,\n RevokeDelegationRequest,\n SetOperatorRequest,\n TransactionKind,\n TransferAndCallRequest,\n UnwrapAllRequest,\n UnwrapRequest,\n WrapRequest,\n} from \"../types\";\nimport { assertBigint } from \"../utils/assertions\";\nimport { parseSchema } from \"../validation\";\nimport type { EncryptionService } from \"./encryption-service\";\n\n/**\n * Configuration for {@link OfflineService}.\n *\n * @internal\n */\nexport interface OfflineServiceConfig {\n readonly provider: GenericProvider;\n readonly router: ChainRouter;\n readonly encryption: EncryptionService;\n readonly emitEvent: (input: ZamaSDKEventInput, tokenAddress?: Address) => void;\n}\n\n/**\n * Offline-signing pipeline. Builds an RLP-encoded unsigned transaction that\n * the caller signs **and** publishes out-of-process — for institutional\n * custody, HSM ceremonies, and policy-engine workflows where signing cannot\n * happen synchronously in a single Promise.\n *\n * Atomic call sites ({@link Token.confidentialTransfer}, etc.) keep their\n * `signer.writeContract` path; this service is the parallel route where the\n * caller signs `prepared.unsignedTx` externally (HSM, custody API, policy\n * engine) and publishes the signed bytes through its own channel.\n *\n * Owned by {@link ZamaSDK}.\n *\n * @internal\n */\nexport class OfflineService {\n readonly #provider: GenericProvider;\n readonly #router: ChainRouter;\n readonly #encryption: EncryptionService;\n\n constructor(config: OfflineServiceConfig) {\n this.#provider = config.provider;\n this.#router = config.router;\n this.#encryption = config.encryption;\n }\n\n // ── prepare ─────────────────────────────────────────────────────────────\n\n /**\n * Build the offline-signing payload for the given transaction request:\n * an RLP-encoded unsigned transaction the caller signs externally (an HSM,\n * custody API, or any out-of-process signer) and publishes through its own\n * channel.\n *\n * Decryption permits are not transactions — acquire them via\n * `sdk.permits.grantPermit`, which signs with the configured signer\n * (including an out-of-process custody signer).\n */\n async prepare<K extends TransactionKind>(\n request: Extract<PrepareTransactionRequest, { kind: K }>,\n options?: PrepareOptions,\n ): Promise<PreparedFor<K>> {\n if (options) {\n options = parseSchema(prepareOptions, options);\n }\n\n // The prepared tx's contract addresses and encrypted inputs are bound to\n // the SDK's configured chain; if the provider is on a different chain it\n // would bake that chain's id into a tx carrying wrong-chain addresses.\n // No signer here (offline is signer-less), so guard router vs provider\n // directly rather than through requireChainAlignment.\n const providerChainId = await this.#provider.getChainId();\n const expectedChainId = this.#router.chain.id;\n if (providerChainId !== expectedChainId) {\n throw new ConfigurationError(\n `Offline.prepare: provider is on chain ${providerChainId} but the SDK is configured for chain ${expectedChainId}. ` +\n `The prepared transaction's contract addresses and encrypted inputs are bound to chain ${expectedChainId} — point the provider at the same chain.`,\n );\n }\n\n const calldata = await this.#buildCalldata(request);\n const params = {\n calldata,\n from: request.from,\n nonce: options?.nonce,\n gasLimit: options?.gasLimit,\n fees: options?.fees,\n };\n const parsed = parseSchema(prepareTransactionParams, params);\n const unsignedTx = await this.#provider.prepareTransaction(parsed);\n return { kind: request.kind, unsignedTx, from: parsed.from } satisfies PreparedFor<K>;\n }\n\n // ── internals ──────────────────────────────────────────────────────────\n\n async #buildCalldata(\n request: PrepareTransactionRequest,\n ): Promise<{\n readonly address: Address;\n readonly abi: readonly unknown[];\n readonly functionName: string;\n readonly args: readonly unknown[];\n }> {\n switch (request.kind) {\n case \"ConfidentialTransfer\":\n return this.#buildConfidentialTransfer(request);\n case \"ConfidentialTransferFrom\":\n return this.#buildConfidentialTransferFrom(request);\n case \"SetOperator\":\n return this.#buildSetOperator(request);\n case \"Unwrap\":\n return this.#buildUnwrap(request);\n case \"UnwrapAll\":\n return this.#buildUnwrapAll(request);\n case \"FinalizeUnwrap\":\n return this.#buildFinalizeUnwrap(request);\n case \"ApproveUnderlying\":\n return this.#buildApproveUnderlying(request);\n case \"Wrap\":\n return this.#buildWrap(request);\n case \"TransferAndCall\":\n return this.#buildTransferAndCall(request);\n case \"DelegateDecryption\":\n return this.#buildDelegateDecryption(request);\n case \"RevokeDelegation\":\n return this.#buildRevokeDelegation(request);\n default: {\n const unhandled: { kind: string } = request;\n throw new ConfigurationError(\n `OfflineService.prepare: unsupported transaction kind '${unhandled.kind}'.`,\n );\n }\n }\n }\n\n async #buildConfidentialTransfer(\n request: ConfidentialTransferRequest,\n ): Promise<ReturnType<typeof confidentialTransferContract>> {\n request = parseSchema(confidentialTransferRequest, request);\n const { encryptedValues, inputProof } = await this.#encryption.encryptValues({\n values: [{ value: request.amount, type: \"euint64\" }],\n contractAddress: request.token,\n userAddress: request.from,\n });\n const handle = encryptedValues[0];\n if (!handle) {\n throw new EncryptionFailedError(\"Encryption returned no handles for ConfidentialTransfer\");\n }\n return confidentialTransferContract(request.token, request.to, handle, inputProof);\n }\n\n async #buildConfidentialTransferFrom(\n request: ConfidentialTransferFromRequest,\n ): Promise<ReturnType<typeof confidentialTransferFromContract>> {\n request = parseSchema(confidentialTransferFromRequest, request);\n // The encrypted input's proof binds to the tx sender (fhevm verifies it\n // against `msg.sender`), which for `transferFrom` is the operator == the\n // `from` wallet that signs and broadcasts — not the `owner` being debited.\n const { encryptedValues, inputProof } = await this.#encryption.encryptValues({\n values: [{ value: request.amount, type: \"euint64\" }],\n contractAddress: request.token,\n userAddress: request.from,\n });\n const handle = encryptedValues[0];\n if (!handle) {\n throw new EncryptionFailedError(\n \"Encryption returned no handles for ConfidentialTransferFrom\",\n );\n }\n return confidentialTransferFromContract(\n request.token,\n request.owner,\n request.to,\n handle,\n inputProof,\n );\n }\n\n #buildSetOperator(request: SetOperatorRequest): ReturnType<typeof setOperatorContract> {\n request = parseSchema(setOperatorRequest, request);\n return setOperatorContract(request.token, request.operator, request.until);\n }\n\n async #buildUnwrap(request: UnwrapRequest): Promise<ReturnType<typeof unwrapContract>> {\n request = parseSchema(unwrapRequest, request);\n const { encryptedValues, inputProof } = await this.#encryption.encryptValues({\n values: [{ value: request.amount, type: \"euint64\" }],\n contractAddress: request.token,\n userAddress: request.from,\n });\n const handle = encryptedValues[0];\n if (!handle) {\n throw new EncryptionFailedError(\"Encryption returned no handles for Unwrap\");\n }\n return unwrapContract(request.token, request.from, request.to, handle, inputProof);\n }\n\n async #buildUnwrapAll(\n request: UnwrapAllRequest,\n ): Promise<ReturnType<typeof unwrapFromBalanceContract>> {\n request = parseSchema(unwrapAllRequest, request);\n const balanceHandle = await this.#provider.readContract(\n confidentialBalanceOfContract(request.token, request.from),\n );\n return unwrapFromBalanceContract(request.token, request.from, request.to, balanceHandle);\n }\n\n async #buildFinalizeUnwrap(\n request: FinalizeUnwrapRequest,\n ): Promise<ReturnType<typeof finalizeUnwrapContract>> {\n request = parseSchema(finalizeUnwrapRequest, request);\n const decrypted = await this.#router.relayer\n .decryptPublicValuesWithSignatures({ encryptedValues: [request.unwrapRequestIdOrAmount] })\n .catch((error: unknown) => {\n throw wrapDecryptError(error, \"Public decryption failed during FinalizeUnwrap\");\n });\n const raw = decrypted.clearValues[0]?.value;\n assertBigint(raw, \"FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue\");\n return finalizeUnwrapContract(\n request.wrapper,\n request.unwrapRequestIdOrAmount,\n raw,\n decrypted.checkSignaturesArgs.decryptionProof,\n );\n }\n\n #buildApproveUnderlying(request: ApproveUnderlyingRequest): ReturnType<typeof approveContract> {\n request = parseSchema(approveUnderlyingRequest, request);\n return approveContract(request.underlying, request.spender, request.amount);\n }\n\n #buildWrap(request: WrapRequest): ReturnType<typeof wrapContract> {\n request = parseSchema(wrapRequest, request);\n return wrapContract(request.wrapper, request.to, request.amount);\n }\n\n #buildTransferAndCall(\n request: TransferAndCallRequest,\n ): ReturnType<typeof transferAndCallContract> {\n request = parseSchema(transferAndCallRequest, request);\n return transferAndCallContract(\n request.underlying,\n request.wrapper,\n request.amount,\n request.recipientData,\n );\n }\n\n #buildDelegateDecryption(\n request: DelegateDecryptionRequest,\n ): ReturnType<typeof delegateForUserDecryptionContract> {\n request = parseSchema(delegateDecryptionRequest, request);\n // Expiry ≥1h out: an expiry under 1h lands already-expired (or nearly so),\n // and the offline payload is signed/broadcast later, eating into that\n // margin further. Checked against the pre-parse `Date` (the schema\n // transforms it into the on-chain uint64 below).\n if (request.expirationDate && request.expirationDate.getTime() < Date.now() + 3_600_000) {\n throw new DelegationExpirationTooSoonError(\n \"Expiration date must be at least 1 hour in the future\",\n );\n }\n if (request.delegateAddress === request.from) {\n throw new DelegationSelfNotAllowedError(\n \"Cannot delegate to yourself (delegate === msg.sender).\",\n );\n }\n if (request.delegateAddress === request.contractAddress) {\n throw new DelegationDelegateEqualsContractError(\n `Delegate address cannot be the same as the contract address (${request.contractAddress}).`,\n );\n }\n const expirationDate = request.expirationDate\n ? BigInt(Math.floor(request.expirationDate.getTime() / 1000))\n : MAX_UINT64;\n return delegateForUserDecryptionContract(\n this.#router.chain.aclContractAddress,\n request.delegateAddress,\n request.contractAddress,\n expirationDate,\n );\n }\n\n #buildRevokeDelegation(\n request: RevokeDelegationRequest,\n ): ReturnType<typeof revokeDelegationContract> {\n request = parseSchema(revokeDelegationRequest, request);\n return revokeDelegationContract(\n this.#router.chain.aclContractAddress,\n request.delegateAddress,\n request.contractAddress,\n );\n }\n}\n","import type { Address } from \"viem\";\nimport type { ChainRouter } from \"./chains/router\";\nimport type { ZamaConfig } from \"./config/types\";\nimport { CredentialService } from \"./credentials/credential-service\";\nimport { DerivationSecretHolder } from \"./credentials/keypair-wrapping\";\nimport { DerivationSecretSchema } from \"./credentials/schemas\";\nimport { ConfigurationError } from \"./errors\";\nimport type { ZamaSDKEvent, ZamaSDKEventInput, ZamaSDKEventListener } from \"./events/sdk-events\";\nimport { Decryption } from \"./namespaces/decryption\";\nimport { Delegations } from \"./namespaces/delegations\";\nimport { Offline } from \"./namespaces/offline\";\nimport { Permits } from \"./namespaces/permits\";\nimport type { EncryptParams, FhevmRelayerOptions, RelayerSDK } from \"./relayer/types\";\nimport { CachingService } from \"./services/caching-service\";\nimport { DecryptionService } from \"./services/decryption-service\";\nimport { DelegationService } from \"./services/delegation-service\";\nimport { EncryptionService } from \"./services/encryption-service\";\nimport { LifecycleService } from \"./services/lifecycle-service\";\nimport { OfflineService } from \"./services/offline-service\";\nimport { Token } from \"./token/token\";\nimport { WrappedToken } from \"./token/wrapped-token\";\nimport type {\n GenericLogger,\n GenericProvider,\n GenericSigner,\n GenericStorage,\n WalletAccountListener,\n} from \"./types\";\nimport { parseSchema } from \"./validation\";\nimport { WrappersRegistry } from \"./wrappers-registry\";\n\n/** Instance-level options that are deliberately not part of the shareable config object. */\nexport interface ZamaSDKOptions {\n /**\n * Encrypts the transport key pair's private half at rest. Headless environments only\n * (CLI tools, servers, agents); the constructor rejects it in browser contexts. Supply\n * at least 32 random bytes, or a string of at least 64 characters, from a CSPRNG or\n * secrets manager. The SDK copies a Uint8Array secret and zeroizes its own copy after\n * key import; it never touches your buffer, so zeroize yours after construction.\n * The SDK never persists or exposes this value. Omit for the default:\n * plaintext at rest, security delegated to the storage backend.\n */\n transportKeyPairDerivationSecret?: string | Uint8Array;\n}\n\n/**\n * Omitting the option means cleartext-at-rest by choice; passing it as `undefined` means the\n * caller asked for wrapping and the value went missing, so it must fail instead of downgrading.\n */\nfunction assertDerivationSecretNotUnset(options: ZamaSDKOptions): void {\n if (\n !Object.hasOwn(options, \"transportKeyPairDerivationSecret\") ||\n options.transportKeyPairDerivationSecret !== undefined\n ) {\n return;\n }\n throw new ConfigurationError(\n \"transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.\",\n );\n}\n\n/**\n * Wrapping only helps where no platform keystore protects the store, which is the headless\n * case. `importScripts` catches a browser worker, where `window` and `document` are absent.\n */\nfunction assertDerivationSecretHeadless(secret: string | Uint8Array | undefined): void {\n if (secret === undefined) {\n return;\n }\n const { importScripts } = globalThis as { importScripts?: unknown };\n const headless =\n typeof window === \"undefined\" &&\n typeof document === \"undefined\" &&\n typeof importScripts !== \"function\";\n if (headless) {\n return;\n }\n throw new ConfigurationError(\n \"transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.\",\n );\n}\n\n/**\n * Copies a `Uint8Array` secret so the holder only ever zeroizes the SDK's own buffer, and\n * a caller zeroizing theirs cannot corrupt later wraps. Strings are immutable, so no copy.\n */\nfunction derivationSecretHolder(\n secret: string | Uint8Array | undefined,\n): DerivationSecretHolder | undefined {\n if (secret === undefined) {\n return undefined;\n }\n const parsed = parseSchema(DerivationSecretSchema, secret);\n return new DerivationSecretHolder(typeof parsed === \"string\" ? parsed : new Uint8Array(parsed));\n}\n\n/**\n * ZamaSDK — composes a RelayerSDK with contract abstraction.\n *\n * Exposes domain namespaces for permits, delegations, decryption, offline\n * signing, and tokens, plus an unchanged registry, a top-level `encrypt`, and\n * lifecycle methods. Internal `*Service` classes do the work; the namespace\n * classes own SDK-level guards (chain alignment, signer requirement, event\n * emission).\n */\nexport class ZamaSDK {\n readonly #router: ChainRouter;\n /** Read-only chain access used for all contract reads. */\n readonly provider: GenericProvider;\n /** Wallet signer used for write operations, or `undefined` when the SDK is read-only. */\n readonly signer: GenericSigner | undefined;\n /** Storage for cached permits and transport key pairs. */\n readonly storage: GenericStorage;\n /**\n * A {@link WrappersRegistry} instance auto-configured for the current chain.\n * Uses built-in defaults from chain configs, and the SDK's `registryTTL` if configured.\n */\n readonly registry: WrappersRegistry;\n /** Permit and keypair management. */\n readonly permits: Permits;\n /** On-chain decryption-delegation management. */\n readonly delegations: Delegations;\n /** FHE decryption (user, delegated user, public). */\n readonly decryption: Decryption;\n /** Offline-signing pipeline: `prepare` builds an unsigned tx the caller signs and broadcasts out-of-process — for HSM, policy-engine, and cross-process custody workflows. */\n readonly offline: Offline;\n readonly #registryTTL: number;\n readonly #registryAddresses: Record<number, Address>;\n readonly #onEvent: ZamaSDKEventListener;\n readonly #logger: GenericLogger;\n readonly #cachingService: CachingService;\n readonly #lifecycleService: LifecycleService;\n readonly #encryptionService: EncryptionService;\n readonly #decryptionService: DecryptionService | undefined;\n readonly #credentialService: CredentialService;\n readonly #delegationService: DelegationService;\n readonly #offlineService: OfflineService;\n\n constructor(config: ZamaConfig, options: ZamaSDKOptions = {}) {\n assertDerivationSecretNotUnset(options);\n assertDerivationSecretHeadless(options.transportKeyPairDerivationSecret);\n // Constructor-local on purpose: neither the raw secret nor the holder may become a field.\n const derivationSecret = derivationSecretHolder(options.transportKeyPairDerivationSecret);\n\n this.#router = config.router;\n this.provider = config.provider;\n this.signer = config.signer;\n this.storage = config.storage;\n this.#onEvent = config.onEvent ?? function () {};\n this.#logger = config.logger;\n this.#cachingService = new CachingService(config.storage, this.#logger);\n this.#delegationService = new DelegationService({\n provider: this.provider,\n router: config.router,\n emitEvent: this.emitEvent.bind(this),\n logger: this.#logger,\n });\n\n const registryAddresses: Record<number, Address> = {};\n for (const chain of config.chains) {\n if (chain.registryAddress) {\n registryAddresses[chain.id] = chain.registryAddress;\n }\n }\n this.registry = new WrappersRegistry({\n provider: this.provider,\n registryAddresses,\n registryTTL: config.registryTTL,\n });\n this.#registryAddresses = registryAddresses;\n this.#registryTTL = config.registryTTL;\n\n // CredentialService is always constructed (with optional signer) so\n // public-decrypt / encryption flows and pre-wallet-connect construction\n // work; permit-signing methods require a signer and throw without one.\n this.#credentialService = new CredentialService({\n router: config.router,\n signer: config.signer,\n transportKeyPairTTL: config.transportKeyPairTTL,\n permitTTL: config.permitTTL,\n scope: config.transportKeyPairScope,\n derivationSecret,\n storage: this.storage,\n permitStorage: config.permitStorage,\n logger: this.#logger,\n emitEvent: this.emitEvent.bind(this),\n });\n if (config.signer) {\n this.#decryptionService = new DecryptionService({\n cache: this.#cachingService,\n credentialService: this.#credentialService,\n delegationService: this.#delegationService,\n router: config.router,\n emitEvent: this.emitEvent.bind(this),\n });\n }\n this.#encryptionService = new EncryptionService({\n router: config.router,\n emitEvent: this.emitEvent.bind(this),\n });\n this.#lifecycleService = new LifecycleService({\n signer: config.signer,\n router: config.router,\n cachingService: this.#cachingService,\n credentialService: this.#credentialService,\n logger: this.#logger,\n });\n this.#offlineService = new OfflineService({\n provider: this.provider,\n router: config.router,\n encryption: this.#encryptionService,\n emitEvent: (input, tokenAddress) => this.emitEvent(input, tokenAddress),\n });\n\n this.permits = new Permits({\n signer: this.signer,\n provider: this.provider,\n cachingService: this.#cachingService,\n credentialService: this.#credentialService,\n logger: this.#logger,\n emitEvent: this.emitEvent.bind(this),\n });\n this.delegations = new Delegations({\n signer: this.signer,\n provider: this.provider,\n delegationService: this.#delegationService,\n });\n this.decryption = new Decryption({\n signer: this.signer,\n provider: this.provider,\n router: config.router,\n decryptionService: this.#decryptionService,\n });\n this.offline = new Offline(this.#offlineService, this.#credentialService);\n }\n\n /**\n * Subscribe to wallet account transitions.\n *\n * @param listener - Called on each transition with a {@link WalletAccountChange} carrying\n * `previous` and `next` wallet account snapshots; either may be `undefined` for\n * connect and disconnect transitions.\n * @returns An unsubscribe function; calling it removes the listener.\n *\n * @internal\n */\n onWalletAccountChange(listener: WalletAccountListener): () => void {\n return this.#lifecycleService.onWalletAccountChange(listener);\n }\n\n /**\n * The SDK-wide logger, exposed so contract abstractions ({@link Token},\n * {@link WrappedToken}) can route their best-effort failures through the\n * same sink. Silent by default.\n *\n * @internal\n */\n get logger(): GenericLogger {\n return this.#logger;\n }\n\n /**\n * The single-chain relayer backend for the **currently active** chain.\n */\n get relayer(): RelayerSDK {\n return this.#router.relayer;\n }\n\n /**\n * Emit a structured SDK event into the unified SDK event stream.\n *\n * Listener exceptions are caught and logged so that a misbehaving subscriber\n * can never corrupt SDK operations.\n *\n * Application code should subscribe via the `onEvent` config option, never\n * call this directly.\n *\n * @internal\n */\n emitEvent(input: ZamaSDKEventInput, tokenAddress?: Address): void {\n try {\n this.#onEvent({ ...input, tokenAddress, timestamp: Date.now() } as ZamaSDKEvent);\n } catch (error) {\n this.#logger.warn(`${input.type} event listener silently failed`, { error });\n }\n }\n\n /**\n * Create a {@link WrappersRegistry} instance bound to this SDK's provider.\n * Inherits the registry addresses derived from the SDK's chain configs, so\n * the result is consistent with {@link ZamaSDK.registry}.\n *\n * @param registryAddresses - Optional per-chain overrides for this registry instance.\n * @returns A {@link WrappersRegistry} instance.\n *\n * @example\n * ```ts\n * // Addresses resolved from the SDK's chain configs\n * const registry = sdk.createWrappersRegistry();\n *\n * // Hardhat or custom chain — override per chain for this registry instance\n * const registry = sdk.createWrappersRegistry({ [31337]: \"0xYourRegistry\" });\n *\n * const pairs = await registry.getTokenPairs();\n * ```\n */\n createWrappersRegistry(registryAddresses?: Record<number, Address>): WrappersRegistry {\n return new WrappersRegistry({\n provider: this.provider,\n registryAddresses: { ...this.#registryAddresses, ...registryAddresses },\n registryTTL: this.#registryTTL,\n });\n }\n\n /**\n * Encrypt one or more plaintext values into FHE ciphertexts.\n *\n * @param params - Typed FHE inputs, the target contract address, and the user address.\n * @returns External encrypted values and the input proof for on-chain submission.\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n *\n * @example\n * ```ts\n * const { encryptedValues, inputProof } = await sdk.encrypt({\n * values: [{ value: 1000n, type: \"euint64\" }],\n * contractAddress: \"0xToken\",\n * userAddress: \"0xUser\",\n * });\n * ```\n */\n async encrypt(params: EncryptParams, options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">) {\n return this.#encryptionService.encryptValues(params, options);\n }\n\n /**\n * Create a high-level ERC-20-style interface for an ERC-7984 confidential token.\n * Supports balance queries, transfers, operator approvals, and decryption.\n *\n * For ERC-7984 wrappers (shield/unshield/allowance), use {@link createWrappedToken} instead.\n *\n * @param address - The confidential token contract address.\n * @returns A {@link Token} instance bound to this SDK.\n *\n * @example\n * ```ts\n * const token = sdk.createToken(cUSDT);\n * const balance = await token.balanceOf(userAddress);\n * ```\n */\n createToken(address: Address): Token {\n return new Token(this, address);\n }\n\n /**\n * Create a high-level interface for an ERC-7984 wrapper token.\n * Extends {@link Token} with shield/unshield/allowance/finalize-unwrap operations.\n *\n * @param address - The wrapper token contract address.\n * @returns A {@link WrappedToken} instance bound to this SDK.\n *\n * @example\n * ```ts\n * const wrapped = sdk.createWrappedToken(wUSDT);\n * await wrapped.shield(1_000_000n);\n * ```\n */\n createWrappedToken(address: Address): WrappedToken {\n return new WrappedToken(this, address);\n }\n\n /**\n * Release the SDK-owned resources: signer lifecycle subscriptions and the\n * relayer backend's resources, an encrypt worker included. Call this when the\n * SDK instance is being replaced (e.g. React provider unmount or a Strict Mode\n * remount). Work already in flight runs to completion, and the instance stays\n * usable: the next encryption spawns a fresh worker.\n */\n dispose(): void {\n this.#lifecycleService.dispose();\n this.#router.dispose();\n }\n\n /**\n * {@link dispose} plus the signer's own disposal. Call this when the SDK is no\n * longer needed (e.g. on shutdown). Work already in flight runs to completion.\n */\n terminate(): void {\n this.dispose();\n this.signer?.dispose?.();\n }\n\n /**\n * Implements the TC39 Explicit Resource Management protocol.\n * Calls {@link terminate} when the `using` binding goes out of scope,\n * unsubscribing signer events and releasing the relayer's resources.\n *\n * @example\n * ```ts\n * {\n * using sdk = new ZamaSDK({ relayer, provider, signer, storage });\n * await sdk.permits.grantPermit([cUSDT]);\n * const balance = await sdk.createToken(cUSDT).balanceOf(userAddress);\n * } // sdk.terminate() called automatically here\n * ```\n */\n [Symbol.dispose](): void {\n this.terminate();\n }\n}\n"],"mappings":"udAqJA,SAAgB,EACd,EACA,EAGe,CACf,GAAI,aAAiBA,EAAAA,EAAW,CAE9B,IAAM,EAAU,EAAS,EAAM,MAC/B,GAAI,EACF,OAAO,EAAQ,CAAK,CAExB,CACA,OAAO,EAAS,IAAI,CAAK,CAC3B,CChJA,IAAa,EAAb,cAAsCC,EAAAA,CAAU,CAE9C,eAEA,gBAEA,QAEA,YACE,EACA,EACA,CACA,MACEC,EAAAA,EAAc,YACd,WAAW,EAAK,QAAQ,8CAA8C,EAAK,eAAe,eACzE,EAAK,gBAAgB,yHAEtC,CACF,EACA,KAAK,KAAO,mBACZ,KAAK,eAAiB,EAAK,eAC3B,KAAK,gBAAkB,EAAK,gBAC5B,KAAK,QAAU,EAAK,OACtB,CACF,ECrCa,EAAb,cAAmDC,EAAAA,CAAU,CAC3D,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,yBAA0B,EAAS,CAAO,EAC9D,KAAK,KAAO,+BACd,CACF,EAGa,EAAb,cAA6CD,EAAAA,CAAU,CACrD,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,mBAAoB,EAAS,CA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,OAAO,KAAKJ,GAAQ,OACtB,CAaA,UAAU,EAA0B,EAA8B,CAChE,GAAI,CACF,KAAKG,GAAS,CAAE,GAAG,EAAO,eAAc,UAAW,KAAK,IAAI,CAAE,CAAiB,CACjF,OAAS,EAAO,CACd,KAAKC,GAAQ,KAAK,GAAG,EAAM,KAAK,iCAAkC,CAAE,OAAM,CAAC,CAC7E,CACF,CAqBA,uBAAuB,EAA+D,CACpF,OAAO,IAAIQ,EAAAA,EAAiB,CAC1B,SAAU,KAAK,SACf,kBAAmB,CAAE,GAAG,KAAKV,GAAoB,GAAG,CAAkB,EACtE,YAAa,KAAKD,EACpB,CAAC,CACH,CAkBA,MAAM,QAAQ,EAAuB,EAA2D,CAC9F,OAAO,KAAKM,GAAmB,cAAc,EAAQ,CAAO,CAC9D,CAiBA,YAAY,EAAyB,CACnC,OAAO,IAAIO,EAAAA,EAAM,KAAM,CAAO,CAChC,CAeA,mBAAmB,EAAgC,CACjD,OAAO,IAAIC,EAAAA,EAAa,KAAM,CAAO,CACvC,CASA,SAAgB,CACd,KAAKT,GAAkB,QAAQ,EAC/B,KAAKN,GAAQ,QAAQ,CACvB,CAMA,WAAkB,CAChB,KAAK,QAAQ,EACb,KAAK,QAAQ,UAAU,CACzB,CAgBA,CAAC,OAAO,UAAiB,CACvB,KAAK,UAAU,CACjB,CACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["ZamaError","ZamaError","ZamaErrorCode","ZamaError","ZamaErrorCode","DecryptionFailedError","NoCiphertextError","RelayerRequestFailedError","SigningRejectedError","SigningFailedError","RpcRateLimitError","InvalidTransportKeyPairError","RevokedKmsContextError","isInvalidTransportKeyPairMessage","isRevokedKmsContextError","isNotEntitledMessage","parseHandleFromMessage","hasStructuredRpcRateLimitSignal","extractRetryAfter","extractHttpStatus","isRpcRateLimitError","isRelayerError","isRelayerTimeoutError","ZamaError","extractHttpStatus","isRelayerTimeoutError","isRelayerError","RelayerRequestFailedError","extractRetryAfter","EncryptionFailedError","buildZamaConfig","#signer","#provider","#cachingService","#credentialService","#logger","#emitEvent","requireConfigured","ZamaSDKEvents","#requireCredentialService","requireChainAlignment","#failPermit","#clearDecryptCacheForRequester","requireAlignedWalletAccount","swallow","#signer","#provider","#delegationService","requireConfigured","#requireSigner","requireAlignedWalletAccount","#signer","#provider","#router","#decryptionService","requireConfigured","#requireDecryptionService","requireAlignedWalletAccount","#offlineService","#credentialService","z","checksummedAddress","#storage","#logger","#decryptNamespace","#decryptKeysNamespace","#buildStorageKey","#indexWriteQueue","#addToIndex","#doDelete","#doClearForRequester","#doClearAll","#readIndex","DecryptionFailedError","checksum","#cache","#credentialService","#delegationService","#router","#emitEvent","#decrypt","#withPropagationRetry","#assertAllDelegationsActive","#setHandleResult","isFatalBatchError","#missingBatchItem","#toZamaError","pLimit","#decryptValues","isInvalidTransportKeyPairMessage","isEncryptedValueZero","isRpcRateLimitError","#rpcRateLimitError","chunkHandlesByBitBudget","ZamaSDKEvents","#runDecryptRequests","RevokedKmsContextError","SigningFailedError","ZamaError","toError","#decryptRequest","DecryptionFailedError","RpcRateLimitError","extractRetryAfter","extractRevertErrorName","#router","#provider","#emitEvent","#logger","#warnIfWildcardAlreadyCoversDelegate","#submitAclTransaction","#needsBlockTimestamp","#resolveStatus","submitTransaction","#throwAclRevertIfMatched","TransactionRevertedError","#router","#emitEvent","ZamaSDKEvents","toError","#signer","#router","#cachingService","#credentialService","#logger","#walletAccountListeners","#unsubscribeSigner","#handleWalletAccountChange","swallow","z","checksummedAddress","unixSeconds","hex","#provider","#router","#encryption","parseSchema","ConfigurationError","#buildCalldata","#buildConfidentialTransfer","#buildConfidentialTransferFrom","#buildSetOperator","#buildUnwrap","#buildUnwrapAll","#buildFinalizeUnwrap","#buildApproveUnderlying","#buildWrap","#buildTransferAndCall","#buildDelegateDecryption","#buildRevokeDelegation","unhandled","EncryptionFailedError","confidentialTransferContract","confidentialTransferFromContract","setOperatorContract","unwrapContract","confidentialBalanceOfContract","unwrapFromBalanceContract","finalizeUnwrapContract","approveContract","wrapContract","transferAndCallContract","ConfigurationError","parseSchema","DerivationSecretSchema","DerivationSecretHolder","#router","#registryTTL","#registryAddresses","#onEvent","#logger","#cachingService","#lifecycleService","#encryptionService","#decryptionService","#credentialService","#delegationService","#offlineService","WrappersRegistry","CredentialService","Token","WrappedToken"],"sources":["../../src/errors/match.ts","../../src/errors/entitlement.ts","../../src/errors/delegation.ts","../../src/errors/decrypt.ts","../../src/errors/encrypt.ts","../../src/abi/acl.abi.ts","../../src/contracts/acl.ts","../../src/contracts/constants.ts","../../src/config/create.ts","../../src/namespaces/permits.ts","../../src/namespaces/delegations.ts","../../src/namespaces/decryption.ts","../../src/namespaces/offline.ts","../../src/storage/chrome-session-storage.ts","../../src/services/caching-service.ts","../../src/credentials/decrypt-permit.ts","../../src/services/decryption-service.ts","../../src/errors/acl-revert.ts","../../src/services/delegation-service.ts","../../src/services/encryption-service.ts","../../src/services/lifecycle-service.ts","../../src/schemas/offline.ts","../../src/services/offline-service.ts","../../src/zama-sdk.ts"],"sourcesContent":["import { ZamaError } from \"./base\";\nimport type { ZamaErrorCode } from \"./base\";\nimport type { ChainMismatchError } from \"./chain\";\nimport type {\n KeyWrappingError,\n NoCiphertextError,\n PreparedPermitChainMismatchError,\n PreparedPermitExpiredError,\n TransportKeyPairChangedError,\n TransportKeyPairExpiredError,\n InvalidTransportKeyPairError,\n RevokedKmsContextError,\n} from \"./credential\";\nimport type {\n AclPausedError,\n DelegationContractIsSelfError,\n DelegationCooldownError,\n DelegationDelegateEqualsContractError,\n DelegationDelegateCannotBeWildcardError,\n DelegationExpirationTooSoonError,\n DelegationExpiredError,\n DelegationExpiryUnchangedError,\n DelegationNotFoundError,\n DelegationNotPropagatedError,\n DelegationSelfNotAllowedError,\n} from \"./delegation\";\nimport type {\n DecryptionFailedError,\n EncryptionFailedError,\n EncryptOffloadUnavailableError,\n} from \"./encryption\";\nimport type {\n BalanceCheckUnavailableError,\n ERC20ReadFailedError,\n InsufficientAllowanceError,\n InsufficientConfidentialBalanceError,\n InsufficientERC20BalanceError,\n} from \"./balance\";\nimport type { ConfigurationError, RelayerRequestFailedError } from \"./relayer\";\nimport type { NotEntitledError } from \"./entitlement\";\nimport type { RpcRateLimitError } from \"./rpc\";\nimport type {\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n WalletNotConnectedError,\n} from \"./signer\";\nimport type { SigningFailedError, SigningRejectedError } from \"./signing\";\nimport type { TransactionRevertedError } from \"./transaction\";\nimport type { UnshieldAlreadyFinalizedError } from \"./unshield\";\n\n/**\n * Maps each {@link ZamaErrorCode} to the error class thrown with that code, so\n * {@link matchZamaError} handlers receive the matched subtype instead of the base\n * `ZamaError`.\n */\nexport interface ErrorForCode {\n /** Thrown for {@link ZamaErrorCode.SigningRejected}. */\n [ZamaErrorCode.SigningRejected]: SigningRejectedError;\n /** Thrown for {@link ZamaErrorCode.SigningFailed}. */\n [ZamaErrorCode.SigningFailed]: SigningFailedError;\n /** Thrown for {@link ZamaErrorCode.EncryptionFailed}. */\n [ZamaErrorCode.EncryptionFailed]: EncryptionFailedError;\n /** Thrown for {@link ZamaErrorCode.DecryptionFailed}. */\n [ZamaErrorCode.DecryptionFailed]: DecryptionFailedError;\n /** Thrown for {@link ZamaErrorCode.EncryptOffloadUnavailable}. */\n [ZamaErrorCode.EncryptOffloadUnavailable]: EncryptOffloadUnavailableError;\n /** Thrown for {@link ZamaErrorCode.TransactionReverted}. */\n [ZamaErrorCode.TransactionReverted]: TransactionRevertedError;\n /** Thrown for {@link ZamaErrorCode.TransportKeyPairExpired}. */\n [ZamaErrorCode.TransportKeyPairExpired]: TransportKeyPairExpiredError;\n /** Thrown for {@link ZamaErrorCode.InvalidTransportKeyPair}. */\n [ZamaErrorCode.InvalidTransportKeyPair]: InvalidTransportKeyPairError;\n /** Thrown for {@link ZamaErrorCode.RevokedKmsContext}. */\n [ZamaErrorCode.RevokedKmsContext]: RevokedKmsContextError;\n /** Thrown for {@link ZamaErrorCode.NoCiphertext}. */\n [ZamaErrorCode.NoCiphertext]: NoCiphertextError;\n /** Thrown for {@link ZamaErrorCode.RelayerRequestFailed}. */\n [ZamaErrorCode.RelayerRequestFailed]: RelayerRequestFailedError;\n /** Thrown for {@link ZamaErrorCode.NotEntitled}. */\n [ZamaErrorCode.NotEntitled]: NotEntitledError;\n /** Thrown for {@link ZamaErrorCode.RpcRateLimited}. */\n [ZamaErrorCode.RpcRateLimited]: RpcRateLimitError;\n /** Thrown for {@link ZamaErrorCode.Configuration}. */\n [ZamaErrorCode.Configuration]: ConfigurationError;\n /** Thrown for {@link ZamaErrorCode.DelegationSelfNotAllowed}. */\n [ZamaErrorCode.DelegationSelfNotAllowed]: DelegationSelfNotAllowedError;\n /** Thrown for {@link ZamaErrorCode.DelegationCooldown}. */\n [ZamaErrorCode.DelegationCooldown]: DelegationCooldownError;\n /** Thrown for {@link ZamaErrorCode.DelegationNotFound}. */\n [ZamaErrorCode.DelegationNotFound]: DelegationNotFoundError;\n /** Thrown for {@link ZamaErrorCode.DelegationExpired}. */\n [ZamaErrorCode.DelegationExpired]: DelegationExpiredError;\n /** Thrown for {@link ZamaErrorCode.InsufficientConfidentialBalance}. */\n [ZamaErrorCode.InsufficientConfidentialBalance]: InsufficientConfidentialBalanceError;\n /** Thrown for {@link ZamaErrorCode.InsufficientERC20Balance}. */\n [ZamaErrorCode.InsufficientERC20Balance]: InsufficientERC20BalanceError;\n /** Thrown for {@link ZamaErrorCode.InsufficientAllowance}. */\n [ZamaErrorCode.InsufficientAllowance]: InsufficientAllowanceError;\n /** Thrown for {@link ZamaErrorCode.BalanceCheckUnavailable}. */\n [ZamaErrorCode.BalanceCheckUnavailable]: BalanceCheckUnavailableError;\n /** Thrown for {@link ZamaErrorCode.ERC20ReadFailed}. */\n [ZamaErrorCode.ERC20ReadFailed]: ERC20ReadFailedError;\n /** Thrown for {@link ZamaErrorCode.DelegationExpiryUnchanged}. */\n [ZamaErrorCode.DelegationExpiryUnchanged]: DelegationExpiryUnchangedError;\n /** Thrown for {@link ZamaErrorCode.DelegationDelegateEqualsContract}. */\n [ZamaErrorCode.DelegationDelegateEqualsContract]: DelegationDelegateEqualsContractError;\n /** Thrown for {@link ZamaErrorCode.DelegationDelegateCannotBeWildcard}. */\n [ZamaErrorCode.DelegationDelegateCannotBeWildcard]: DelegationDelegateCannotBeWildcardError;\n /** Thrown for {@link ZamaErrorCode.DelegationContractIsSelf}. */\n [ZamaErrorCode.DelegationContractIsSelf]: DelegationContractIsSelfError;\n /** Thrown for {@link ZamaErrorCode.AclPaused}. */\n [ZamaErrorCode.AclPaused]: AclPausedError;\n /** Thrown for {@link ZamaErrorCode.DelegationExpirationTooSoon}. */\n [ZamaErrorCode.DelegationExpirationTooSoon]: DelegationExpirationTooSoonError;\n /** Thrown for {@link ZamaErrorCode.DelegationNotPropagated}. */\n [ZamaErrorCode.DelegationNotPropagated]: DelegationNotPropagatedError;\n /** Thrown for {@link ZamaErrorCode.ChainMismatch}. */\n [ZamaErrorCode.ChainMismatch]: ChainMismatchError;\n /** Thrown for {@link ZamaErrorCode.SignerNotConfigured}. */\n [ZamaErrorCode.SignerNotConfigured]: SignerNotConfiguredError;\n /** Thrown for {@link ZamaErrorCode.WalletNotConnected}. */\n [ZamaErrorCode.WalletNotConnected]: WalletNotConnectedError;\n /** Thrown for {@link ZamaErrorCode.WalletAccountNotReady}. */\n [ZamaErrorCode.WalletAccountNotReady]: WalletAccountNotReadyError;\n /** Thrown for {@link ZamaErrorCode.KeyWrappingFailed}. */\n [ZamaErrorCode.KeyWrappingFailed]: KeyWrappingError;\n /** Thrown for {@link ZamaErrorCode.TransportKeyPairChanged}. */\n [ZamaErrorCode.TransportKeyPairChanged]: TransportKeyPairChangedError;\n /** Thrown for {@link ZamaErrorCode.PreparedPermitChainMismatch}. */\n [ZamaErrorCode.PreparedPermitChainMismatch]: PreparedPermitChainMismatchError;\n /** Thrown for {@link ZamaErrorCode.PreparedPermitExpired}. */\n [ZamaErrorCode.PreparedPermitExpired]: PreparedPermitExpiredError;\n /** Thrown for {@link ZamaErrorCode.UnshieldAlreadyFinalized}. */\n [ZamaErrorCode.UnshieldAlreadyFinalized]: UnshieldAlreadyFinalizedError;\n}\n\n/**\n * Pattern-match on a {@link ZamaError} by its error code. Each handler receives the\n * error class for its code, so subclass fields are available without a cast.\n * Falls through to the `_` wildcard handler if no specific handler matches.\n * Returns `undefined` if the error is not a `ZamaError` and no `_` handler is provided.\n *\n * @example\n * ```ts\n * matchZamaError(error, {\n * SIGNING_REJECTED: () => toast(\"Please approve in wallet\"),\n * INSUFFICIENT_CONFIDENTIAL_BALANCE: (e) => toast(`Need ${e.requested}, have ${e.available}`),\n * RELAYER_REQUEST_FAILED: (e) => toast(`Relayer failed (${e.statusCode})`),\n * _: () => toast(\"Unknown error\"),\n * });\n * ```\n */\nexport function matchZamaError<R>(\n error: unknown,\n handlers: { [K in ZamaErrorCode]?: (error: ErrorForCode[K]) => R } & {\n _?: (error: unknown) => R;\n },\n): R | undefined {\n if (error instanceof ZamaError) {\n // `error.code` narrows the handler at runtime; the cast bridges the per-code param types.\n const handler = handlers[error.code] as ((error: ZamaError) => R) | undefined;\n if (handler) {\n return handler(error);\n }\n }\n return handlers._?.(error);\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * The signer (or delegator) lacks ACL permission to decrypt the encrypted value —\n * `persistAllowed` returned `false`. Terminal and **non-retryable**: the fix is\n * an on-chain grant (`FHE.allow`), or for indexers, to wait for a backfill once\n * the grant lands. Distinct from transient failures like {@link RpcRateLimitError}.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof NotEntitledError) {\n * // don't retry — wait for an ACL grant / backfill\n * }\n * }\n * ```\n */\nexport class NotEntitledError extends ZamaError {\n /** The encrypted value the actor is not entitled to decrypt. */\n readonly encryptedValue: string;\n /** The contract the encrypted value belongs to. */\n readonly contractAddress: string;\n /** The actor (signer or delegator) that lacks ACL permission. */\n readonly account: string;\n\n constructor(\n args: { encryptedValue: string; contractAddress: string; account: string },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.NotEntitled,\n `Account ${args.account} is not entitled to decrypt encrypted value ${args.encryptedValue} ` +\n `on contract ${args.contractAddress}. This is not a transient failure — ` +\n `the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,\n options,\n );\n this.name = \"NotEntitledError\";\n this.encryptedValue = args.encryptedValue;\n this.contractAddress = args.contractAddress;\n this.account = args.account;\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n// Delegation errors — thrown by SDK pre-flight checks and by delegation\n// transaction callsites when they map ACL Solidity revert reasons.\n\n/** Delegation cannot target self (delegate === msg.sender). */\nexport class DelegationSelfNotAllowedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationSelfNotAllowed, message, options);\n this.name = \"DelegationSelfNotAllowedError\";\n }\n}\n\n/** Only one delegate/revoke per (delegator, delegate, contract) per block. */\nexport class DelegationCooldownError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationCooldown, message, options);\n this.name = \"DelegationCooldownError\";\n }\n}\n\n/** No active delegation found for this (delegator, delegate, contract) tuple. */\nexport class DelegationNotFoundError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationNotFound, message, options);\n this.name = \"DelegationNotFoundError\";\n }\n}\n\n/** The delegation has expired. */\nexport class DelegationExpiredError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationExpired, message, options);\n this.name = \"DelegationExpiredError\";\n }\n}\n\n/** The new expiration date equals the current one. */\nexport class DelegationExpiryUnchangedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationExpiryUnchanged, message, options);\n this.name = \"DelegationExpiryUnchangedError\";\n }\n}\n\n/** Delegate address cannot be the contract address. */\nexport class DelegationDelegateEqualsContractError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationDelegateEqualsContract, message, options);\n this.name = \"DelegationDelegateEqualsContractError\";\n }\n}\n\n/** Delegate address cannot be the wildcard address — it's only valid as `contractAddress`. */\nexport class DelegationDelegateCannotBeWildcardError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationDelegateCannotBeWildcard, message, options);\n this.name = \"DelegationDelegateCannotBeWildcardError\";\n }\n}\n\n/** Contract address cannot be the sender address. */\nexport class DelegationContractIsSelfError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationContractIsSelf, message, options);\n this.name = \"DelegationContractIsSelfError\";\n }\n}\n\n/** The ACL contract is paused. */\nexport class AclPausedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.AclPaused, message, options);\n this.name = \"AclPausedError\";\n }\n}\n\n/** Expiration date is too soon (must be at least 1 hour in the future). */\nexport class DelegationExpirationTooSoonError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationExpirationTooSoon, message, options);\n this.name = \"DelegationExpirationTooSoonError\";\n }\n}\n\n/**\n * Delegation exists on L1 but hasn't propagated to the gateway yet.\n *\n * After calling `delegateForUserDecryption()`, the delegation is recorded on-chain\n * immediately. However, the gateway (deployed on Arbitrum) must sync this state\n * via cross-chain event propagation, which usually completes within ~10 blocks\n * (a few seconds).\n *\n * Calling `decryptBalanceAs` during this window will fail because the gateway's\n * `isHandleDelegatedForUserDecryption()` check reads from its own synced copy\n * of the ACL state, which hasn't been updated yet.\n *\n * **You rarely need to handle this directly:** the delegated-decrypt path rides\n * out the propagation window with a bounded internal retry (~30s), so a decrypt\n * issued right after the grant simply waits for sync. This error only surfaces\n * if the window outlasts the retry budget, or when retries are disabled via\n * `waitForPropagation: false`.\n *\n * **Note:** This error is raised as a best-effort heuristic — when a delegated\n * decryption receives an HTTP 500 from the relayer, the most likely cause is a\n * propagation delay. However, the same status code can occur if the gateway or\n * relayer experiences an unrelated internal error.\n */\nexport class DelegationNotPropagatedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DelegationNotPropagated, message, options);\n this.name = \"DelegationNotPropagatedError\";\n }\n}\n","import type { ZamaError } from \"./base\";\nimport { DecryptionFailedError } from \"./encryption\";\nimport {\n InvalidTransportKeyPairError,\n NoCiphertextError,\n RevokedKmsContextError,\n} from \"./credential\";\nimport { RelayerRequestFailedError } from \"./relayer\";\nimport { DelegationNotPropagatedError } from \"./delegation\";\nimport { NotEntitledError } from \"./entitlement\";\nimport { RpcRateLimitError } from \"./rpc\";\nimport { SigningRejectedError, SigningFailedError } from \"./signing\";\nimport {\n extractHttpStatus,\n extractRetryAfter,\n hasStructuredRpcRateLimitSignal,\n isInvalidTransportKeyPairMessage,\n isNotEntitledMessage,\n isRelayerError,\n isRelayerTimeoutError,\n isRevokedKmsContextError,\n isRpcRateLimitError,\n parseHandleFromMessage,\n} from \"../utils/error\";\n\n/**\n * Context the caller supplies so a not-entitled / delegation failure can be\n * mapped precisely. The request context (`contractAddress` / `account`) is not\n * present on the raw error, so it is injected here.\n */\nexport interface DecryptErrorContext {\n isDelegated?: boolean;\n contractAddress?: string;\n /** The ACL actor (signer, or delegator for delegated decrypt). */\n account?: string;\n}\n\n/**\n * Every typed SDK error `wrapDecryptError` may see on its way in (from a prior\n * classification, a worker rethrow, or a caller-level retry) and must pass\n * through unchanged rather than collapse into terminal `DecryptionFailedError`.\n * A single source of truth for the early-return check below and for the\n * `errors.test.ts` \"every typed cause passes through unchanged\" test — so a\n * class dropped from this array is caught by that test instead of silently\n * falling through to the generic fallback.\n *\n * This is a fixed, decrypt-scoped subset of the taxonomy maintained by hand\n * (unlike {@link RETRYABLE_BY_CODE} in `base.ts`, it has no `Complete<>` tie\n * to `ZamaErrorCode`) — a new decrypt-path error class must be added here\n * explicitly, since there's no compiler check forcing it.\n */\nexport const DECRYPT_PASSTHROUGH_ERROR_TYPES = [\n DecryptionFailedError,\n NoCiphertextError,\n RelayerRequestFailedError,\n DelegationNotPropagatedError,\n SigningRejectedError,\n SigningFailedError,\n NotEntitledError,\n RpcRateLimitError,\n InvalidTransportKeyPairError,\n RevokedKmsContextError,\n] as const;\n\n/**\n * The single decryption-error classifier. Maps a caught error to the right typed\n * SDK error: not-entitled (ACL), consumer RPC rate-limit, NoCiphertext (400),\n * DelegationNotPropagated (delegated 500 *or* a delegated ACL denial, which is\n * transient), RelayerRequestFailed (other HTTP), or the generic DecryptionFailed\n * fallback.\n *\n * Errors that are already typed SDK errors are returned as-is so callers can\n * still match the original cause. All structured signals (codes, status, cause\n * chain) are read from the error itself.\n */\nexport function wrapDecryptError(\n error: unknown,\n fallbackMessage: string,\n ctx: DecryptErrorContext = {},\n): ZamaError {\n if (DECRYPT_PASSTHROUGH_ERROR_TYPES.some((ErrorType) => error instanceof ErrorType)) {\n return error as ZamaError;\n }\n\n const message = error instanceof Error ? error.message : fallbackMessage;\n\n // Stale transport key pair the relayer can't re-derive (post KMS/TKMS rotation).\n // Typed so the decrypt path can evict the vault entry and regenerate on retry.\n if (error instanceof Error && isInvalidTransportKeyPairMessage(error.message)) {\n return new InvalidTransportKeyPairError(error.message, { cause: error });\n }\n\n // The permit's KMS context was revoked on-chain (InvalidKmsContext revert).\n // Typed so the decrypt path can evict the dead permit, re-grant, and retry once.\n if (isRevokedKmsContextError(error)) {\n return new RevokedKmsContextError(\n \"The permit's KMS context has been revoked on-chain, so the permit is no longer usable. \" +\n \"The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry \" +\n \"failed the same way. The on-chain validity check is cached for up to 15 minutes, so a \" +\n \"just-revoked context can keep failing across that window. Retry after the window; the \" +\n \"SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.\",\n { cause: error },\n );\n }\n\n // Actor not entitled (ACL). The relayer throws a message-only Error; the handle\n // is parseable from it and the contract/account come from the request context\n // the caller holds.\n if (error instanceof Error && isNotEntitledMessage(error.message)) {\n // On the delegated path the \"not entitled\" verdict comes from the\n // *delegator's* `persistAllowed` L1 read, which has no staleness tolerance:\n // it returns false *transiently* when the delegation has just landed or the\n // consumer's RPC serves a lagging block. Terminal `NotEntitledError` (\"never\n // retry\") would be the wrong signal for that propagation window, so — mirroring\n // the delegated-500 branch below — surface the retryable\n // `DelegationNotPropagatedError` instead. A direct signer denial (non-\n // delegated) stays terminal `NotEntitledError`.\n if (ctx.isDelegated) {\n return new DelegationNotPropagatedError(\n \"Delegated decryption was denied by the on-chain ACL check. \" +\n \"This is most commonly caused by the delegation not having propagated yet, or by the \" +\n \"RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few \" +\n \"seconds) and the SDK retries across that window; seeing this means it did not sync in time. \" +\n \"Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may \" +\n \"genuinely lack the on-chain ACL grant.\",\n { cause: error },\n );\n }\n return new NotEntitledError(\n {\n encryptedValue: parseHandleFromMessage(error.message) ?? \"\",\n contractAddress: ctx.contractAddress ?? \"\",\n account: ctx.account ?? \"\",\n },\n { cause: error },\n );\n }\n\n // Consumer's RPC provider throttling an on-chain read. An unambiguous\n // structured signal (-32005 / viem `status: 429`) wins over any HTTP status;\n // relayer-origin errors are `@fhevm/sdk` `Relayer*` classes and are excluded by\n // `isRelayerError`, staying RelayerRequestFailedError below.\n if (hasStructuredRpcRateLimitSignal(error)) {\n return new RpcRateLimitError(message, { cause: error, retryAfter: extractRetryAfter(error) });\n }\n\n const statusCode = extractHttpStatus(error);\n\n // A message-only throttle (\"Too Many Requests\" / \"rate limit\") is trusted only\n // when no HTTP status is present — otherwise the status classification (e.g. a\n // relayer error whose body mentions a rate limit) takes precedence.\n if (statusCode === undefined && isRpcRateLimitError(error)) {\n return new RpcRateLimitError(message, { cause: error, retryAfter: extractRetryAfter(error) });\n }\n\n if (statusCode === 400) {\n return new NoCiphertextError(\n error instanceof Error ? error.message : \"No ciphertext for this account\",\n { cause: error },\n );\n }\n\n if (ctx.isDelegated && statusCode === 500) {\n return new DelegationNotPropagatedError(\n \"Delegated decryption failed with a server error. \" +\n \"This is most commonly caused by the delegation not having propagated to the gateway yet. \" +\n \"Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries \" +\n \"across that window; seeing this means it did not sync in time — retry shortly. \" +\n \"If the error persists, the gateway or relayer may be experiencing an unrelated issue.\",\n { cause: error },\n );\n }\n\n if (isRelayerError(error) || statusCode !== undefined) {\n return new RelayerRequestFailedError(message, statusCode, {\n cause: error,\n retryAfter: extractRetryAfter(error),\n // A relayer timeout carries no HTTP status but is safe to retry; force\n // `retryable` so it isn't misclassified as terminal. Other relayer errors\n // fall back to the status-based default (429 → retryable).\n retryable: isRelayerTimeoutError(error) || undefined,\n });\n }\n\n return new DecryptionFailedError(fallbackMessage, { cause: error });\n}\n","import {\n extractHttpStatus,\n extractRetryAfter,\n isRelayerError,\n isRelayerTimeoutError,\n} from \"../utils/error\";\nimport { ZamaError } from \"./base\";\nimport { EncryptionFailedError } from \"./encryption\";\nimport { RelayerRequestFailedError } from \"./relayer\";\n\n/**\n * Inspect a caught encryption error for an `@fhevm/sdk` relayer origin or HTTP\n * status code and return the appropriate typed SDK error. Relayer transport\n * failures without a status, plus HTTP failures from the relayer or an\n * intermediary such as Cloudflare/Kong, surface as\n * {@link RelayerRequestFailedError} instead of collapsing into a generic\n * {@link EncryptionFailedError}.\n *\n * Errors that are already typed SDK errors are returned as-is so callers can\n * still match the original cause.\n *\n * The relayer's HTTP status may surface as `status` or `statusCode` anywhere in\n * the cause chain; {@link extractHttpStatus} walks the chain for either, mirroring\n * {@link wrapDecryptError}.\n */\nexport function wrapEncryptError(error: unknown, fallbackMessage: string): ZamaError {\n if (error instanceof ZamaError) {\n return error;\n }\n\n const statusCode = extractHttpStatus(error);\n // A relayer timeout carries no HTTP status but is safe to retry — surface it as\n // a retryable RelayerRequestFailedError rather than a terminal EncryptionFailed.\n const isTimeout = isRelayerTimeoutError(error);\n\n if (statusCode !== undefined || isRelayerError(error)) {\n return new RelayerRequestFailedError(\n error instanceof Error ? error.message : fallbackMessage,\n statusCode,\n { cause: error, retryAfter: extractRetryAfter(error), retryable: isTimeout || undefined },\n );\n }\n\n return new EncryptionFailedError(fallbackMessage, { cause: error });\n}\n","// DO NOT EDIT: generated by `pnpm abi:build` from\n// contracts/out/Impl.sol/IACL.json.\n// Regenerate after `pnpm contracts:build`; `pnpm abi:check` enforces this in CI.\nexport const aclAbi = [\n {\n type: \"function\",\n name: \"allow\",\n inputs: [\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"allowForDecryption\",\n inputs: [{ name: \"handlesList\", type: \"bytes32[]\", internalType: \"bytes32[]\" }],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"allowTransient\",\n inputs: [\n { name: \"ciphertext\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"cleanTransientStorage\",\n inputs: [],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"delegateForUserDecryption\",\n inputs: [\n { name: \"delegate\", type: \"address\", internalType: \"address\" },\n { name: \"contractAddress\", type: \"address\", internalType: \"address\" },\n { name: \"expirationDate\", type: \"uint64\", internalType: \"uint64\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getUserDecryptionDelegationExpirationDate\",\n inputs: [\n { name: \"delegator\", type: \"address\", internalType: \"address\" },\n { name: \"delegate\", type: \"address\", internalType: \"address\" },\n { name: \"contractAddress\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint64\", internalType: \"uint64\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAccountDenied\",\n inputs: [{ name: \"account\", type: \"address\", internalType: \"address\" }],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAllowed\",\n inputs: [\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAllowedForDecryption\",\n inputs: [{ name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" }],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isHandleDelegatedForUserDecryption\",\n inputs: [\n { name: \"delegator\", type: \"address\", internalType: \"address\" },\n { name: \"delegate\", type: \"address\", internalType: \"address\" },\n { name: \"contractAddress\", type: \"address\", internalType: \"address\" },\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"multicall\",\n inputs: [{ name: \"data\", type: \"bytes[]\", internalType: \"bytes[]\" }],\n outputs: [{ name: \"results\", type: \"bytes[]\", internalType: \"bytes[]\" }],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"persistAllowed\",\n inputs: [\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"revokeDelegationForUserDecryption\",\n inputs: [\n { name: \"delegate\", type: \"address\", internalType: \"address\" },\n { name: \"contractAddress\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n] as const;\n","import type { Address } from \"viem\";\nimport { aclAbi } from \"../abi/acl.abi\";\n\n/**\n * Returns the contract config to delegate user decryption rights.\n *\n * @example\n * ```ts\n * const txHash = await signer.writeContract(\n * delegateForUserDecryptionContract(aclAddress, delegateAddress, contractAddress, expirationDate),\n * );\n * ```\n */\nexport function delegateForUserDecryptionContract(\n aclAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n expirationDate: bigint,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"delegateForUserDecryption\",\n args: [delegateAddress, contractAddress, expirationDate],\n } as const;\n}\n\n/**\n * Returns the contract config to revoke a user decryption delegation.\n *\n * @example\n * ```ts\n * const txHash = await signer.writeContract(\n * revokeDelegationContract(aclAddress, delegateAddress, contractAddress),\n * );\n * ```\n */\nexport function revokeDelegationContract(\n aclAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"revokeDelegationForUserDecryption\",\n args: [delegateAddress, contractAddress],\n } as const;\n}\n\n/**\n * Returns the contract config to read the delegation expiry date.\n *\n * @example\n * ```ts\n * const expiry = await provider.readContract(\n * getDelegationExpiryContract(aclAddress, delegatorAddress, delegateAddress, contractAddress),\n * );\n * ```\n */\nexport function getDelegationExpiryContract(\n aclAddress: Address,\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"getUserDecryptionDelegationExpirationDate\",\n args: [delegatorAddress, delegateAddress, contractAddress],\n } as const;\n}\n\n/**\n * Returns the contract config to check if a specific handle is delegated.\n *\n * @example\n * ```ts\n * const isDelegated = await provider.readContract(\n * isHandleDelegatedContract(aclAddress, delegatorAddress, delegateAddress, contractAddress, handle),\n * );\n * ```\n */\nexport function isHandleDelegatedContract(\n aclAddress: Address,\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n handle: `0x${string}`,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, handle],\n } as const;\n}\n","/** uint64 max — represents a permanent (no-expiry) delegation. */\nexport const MAX_UINT64 = 2n ** 64n - 1n;\n\n// Duplicated rather than imported: @fhevm/sdk computes the same value\n// internally but doesn't export it from any public entry point.\n/**\n * `contractAddress` covering every confidential contract with a single\n * delegation.\n */\nexport const WILDCARD_CONTRACT = \"0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF\" as const;\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"./build\";\nimport type { ZamaConfig, ZamaConfigGeneric } from \"./types\";\n\n/**\n * Create a {@link ZamaConfig} from a custom {@link GenericSigner} and\n * {@link GenericProvider}. Use this when the built-in adapter paths\n * (`@zama-fhe/sdk/viem`, `@zama-fhe/sdk/ethers`, `@zama-fhe/react-sdk/wagmi`)\n * don't cover your setup — e.g. a server-side relayer that implements\n * `GenericSigner` directly.\n *\n * @example\n * ```ts\n * import { createConfig, memoryStorage } from \"@zama-fhe/sdk\";\n * import { web } from \"@zama-fhe/sdk/web\";\n * import { sepolia } from \"@zama-fhe/sdk/chains\";\n *\n * const config = createConfig({\n * chains: [sepolia],\n * signer: myCustomSigner,\n * provider: myCustomProvider,\n * storage: memoryStorage,\n * relayers: { [sepolia.id]: web() },\n * });\n * const sdk = new ZamaSDK(config);\n * ```\n */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigGeneric<TChains>,\n): ZamaConfig {\n return buildZamaConfig(params.signer, params.provider, params);\n}\n","import { getAddress, type Address, type Hex } from \"viem\";\nimport type { CredentialService } from \"../credentials/credential-service\";\nimport type { PreparedPermit } from \"../credentials/types\";\nimport { requireConfigured } from \"../errors\";\nimport type { PermitOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { ZamaSDKEvents } from \"../events/sdk-events\";\nimport type { CachingService } from \"../services/caching-service\";\nimport type { GenericLogger, GenericProvider, GenericSigner } from \"../types\";\nimport { swallow } from \"../utils\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\n\n/**\n * Public namespace for permit and transport-key-pair management.\n *\n * Exposed as `sdk.permits`. Owns the SDK-level guards (chain alignment, empty-array\n * short-circuit, decrypt-cache invalidation) and delegates the actual work to the\n * internal {@link CredentialService}.\n *\n * The namespace is named `permits` because the user-facing concept is the signed-permit\n * store. The transport key pair is invisible plumbing — there is no `getTransportKeyPair()`\n * surfaced; the key pair exists to sign permits and is created automatically when needed.\n * {@link clear} wipes both the permit store and the transport key pair (permits\n * cascade-delete with the key pair).\n *\n * When `transportKeyPairScope` is configured (opt-in shared-tenant scope for B2B2C/WaaS\n * operators), {@link clear} and {@link revokePermits} stay signer-level only — they never\n * touch the shared key pair. {@link revokeTransportKeyPair} is the distinct,\n * operator-level operation for that.\n */\nexport class Permits {\n readonly #signer: GenericSigner | undefined;\n readonly #provider: GenericProvider;\n readonly #cachingService: CachingService;\n readonly #credentialService: CredentialService | undefined;\n readonly #logger: GenericLogger;\n readonly #emitEvent: (input: ZamaSDKEventInput) => void;\n\n /** @internal */\n constructor(opts: {\n signer: GenericSigner | undefined;\n provider: GenericProvider;\n cachingService: CachingService;\n credentialService: CredentialService | undefined;\n logger: GenericLogger;\n emitEvent: (input: ZamaSDKEventInput) => void;\n }) {\n this.#signer = opts.signer;\n this.#provider = opts.provider;\n this.#cachingService = opts.cachingService;\n this.#credentialService = opts.credentialService;\n this.#logger = opts.logger;\n this.#emitEvent = opts.emitEvent;\n }\n\n #requireCredentialService(operation: string): CredentialService {\n return requireConfigured(this.#credentialService, operation);\n }\n\n /**\n * Emit a {@link ZamaSDKEvents.PermitError} event for a pre-flight guard\n * failure (no signer/CredentialService configured, chain mismatch) and\n * rethrow the same error unchanged. These guards run in this namespace\n * layer, before {@link CredentialService} (and its own equivalent choke\n * point) is ever reached, so without this they'd be invisible to `onEvent`\n * regardless of what CredentialService itself emits.\n *\n * Only for the pre-flight guards below — never wrap a delegated\n * `CredentialService` call in this, since that call already emits\n * internally on failure; doing it here too would double-emit.\n */\n #failPermit(operation: PermitOperation, error: unknown): never {\n this.#emitEvent({\n type: ZamaSDKEvents.PermitError,\n operation,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n throw error;\n }\n\n /**\n * Sign and store an EIP-712 permit authorizing direct decryption for the\n * given contract addresses.\n *\n * Idempotent: if a permit covering the requested set already exists, no\n * wallet prompt occurs. Otherwise the SDK chunks the uncovered subset into\n * groups of ≤10 contracts and prompts once per chunk; partial mid-flight\n * rejection is preserved (already-signed chunks are persisted before the\n * next prompt).\n *\n * @param contracts - Contract addresses to authorize.\n * @throws if `transportKeyPairDerivationSecret` is configured and the keypair fails to wrap or\n * unwrap. {@link KeyWrappingError}\n */\n async grantPermit(contracts: Address[]): Promise<void> {\n if (contracts.length === 0) {\n return;\n }\n let service: CredentialService;\n try {\n service = this.#requireCredentialService(\"grantPermit\");\n await requireChainAlignment(\"grantPermit\", this.#signer, this.#provider);\n } catch (error) {\n this.#failPermit(\"grantPermit\", error);\n }\n await service.grantPermit(contracts);\n }\n\n /**\n * Sign and store an EIP-712 delegation permit authorizing decryption on\n * behalf of `delegator`. Same idempotence/chunking semantics as {@link grantPermit}.\n *\n * @param delegator - The address that delegated decryption rights to the connected signer.\n * @param contracts - Contract addresses to authorize.\n * @throws if `transportKeyPairDerivationSecret` is configured and the keypair fails to wrap or\n * unwrap. {@link KeyWrappingError}\n */\n async grantDelegationPermit(delegator: Address, contracts: Address[]): Promise<void> {\n if (contracts.length === 0) {\n return;\n }\n let service: CredentialService;\n try {\n service = this.#requireCredentialService(\"grantDelegationPermit\");\n await requireChainAlignment(\"grantDelegationPermit\", this.#signer, this.#provider);\n } catch (error) {\n this.#failPermit(\"grantDelegationPermit\", error);\n }\n await service.grantPermit(contracts, delegator);\n }\n\n /**\n * Pure store lookup: is there a permit covering `contracts`?\n * No wallet prompt, no transport key pair generation. Returns `false` when no signer\n * is configured, or when `transportKeyPairDerivationSecret` is configured and the stored keypair\n * fails to unwrap. Does not swallow other errors (e.g. a failing storage backend), which\n * propagate normally.\n */\n async hasPermit(contracts: Address[]): Promise<boolean> {\n if (!this.#credentialService) {\n return false;\n }\n return this.#credentialService.hasPermit(contracts);\n }\n\n /**\n * Pure store lookup for a delegation permit. Never throws when the stored keypair\n * fails to unwrap, reporting no permit instead; other errors still propagate.\n *\n * @param delegator - The address that delegated decryption rights to the connected signer.\n * @param contracts - Contract addresses to check.\n * @returns `true` if cached delegation permits cover all requested contracts.\n */\n async hasDelegationPermit(delegator: Address, contracts: Address[]): Promise<boolean> {\n if (!this.#credentialService) {\n return false;\n }\n return this.#credentialService.hasPermit(contracts, delegator);\n }\n\n /**\n * Best-effort transport-key-pair prefetch for the connected signer.\n *\n * Optional latency optimization: decrypt and permit flows remain correct\n * without it because they lazily create the transport key pair when needed.\n *\n * Silent no-op when no signer is configured or no wallet account is\n * available. The transport key pair is generated through the relayer dispatcher's\n * currently active chain — see {@link LifecycleService}, which calls\n * `switchChain` before fanning the wallet-account change out to listeners,\n * so any downstream caller (including React adapters) observes the\n * dispatcher on the wallet chain by the time it invokes warmup.\n *\n * Not for pre-warming a shared `transportKeyPairScope`: this call's wallet-account\n * precondition doesn't conceptually apply to a scope-wide key, and would silently\n * no-op precisely when an operator is most likely to be calling it (no end-user\n * connected yet). Use {@link warmTransportKeyPairScope} instead.\n *\n * @throws if `transportKeyPairDerivationSecret` is configured and the keypair fails to wrap or\n * unwrap. {@link KeyWrappingError}\n */\n async warmTransportKeyPair(): Promise<void> {\n const service = this.#credentialService;\n if (!service) {\n return;\n }\n const account = this.#signer?.walletAccount.getSnapshot();\n if (!account) {\n return;\n }\n await service.warmTransportKeyPair(account.address);\n }\n\n /**\n * Offline permit flow, phase 2: verify and persist the signature an\n * out-of-process signer produced for a `sdk.offline.preparePermit` payload.\n *\n * No wallet account required: the permit is scoped by `prepared.signerAddress`\n * (and `prepared.delegatorAddress`, if present), not a connected signer.\n *\n * @param prepared - The payload `sdk.offline.preparePermit` returned.\n * @param signature - The 65-byte `eth_signTypedData_v4` signature over `prepared.eip712`.\n * @throws if `prepared` doesn't match the `PreparedPermit` shape (e.g. it crossed a\n * process boundary and was corrupted). {@link ConfigurationError}\n * @throws if the chain embedded in `prepared.eip712` doesn't match the active chain. {@link PreparedPermitChainMismatchError}\n * @throws if the permit's validity window has already elapsed. {@link PreparedPermitExpiredError}\n * @throws if the transport key pair changed since prepare. {@link TransportKeyPairChangedError}\n * @throws if the signature is invalid or malformed. {@link SigningFailedError}\n */\n async registerPermit(prepared: PreparedPermit, signature: Hex): Promise<void> {\n let service: CredentialService;\n try {\n service = this.#requireCredentialService(\"registerPermit\");\n } catch (error) {\n this.#failPermit(\"registerPermit\", error);\n }\n await service.registerPermit(prepared, signature);\n await this.#clearDecryptCacheForRequester(prepared.signerAddress);\n }\n\n /**\n * Wipe FHE permits for the current signer.\n *\n * - With no argument: every permit referencing this signer is removed across\n * all chains and delegators. The transport key pair survives — use {@link clear} to\n * also wipe the transport key pair.\n * - With a contract list: every signed permit in the direct-decrypt scope\n * (current chain) whose immutable payload touches any listed address is\n * removed. Delegation permits are not touched in this mode.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n */\n async revokePermits(contracts?: Address[]): Promise<void> {\n const service = this.#requireCredentialService(\"revokePermits\");\n const account = await requireAlignedWalletAccount(\n \"revokePermits\",\n this.#signer,\n this.#provider,\n );\n const signerAddress = getAddress(account.address);\n try {\n await service.revokePermits(contracts);\n } finally {\n await this.#clearDecryptCacheForRequester(signerAddress);\n }\n }\n\n /**\n * Wipe the transport key pair for the current signer and cascade-delete every permit\n * (across chains and delegators) referencing it.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n */\n async clear(): Promise<void> {\n const service = this.#requireCredentialService(\"clear\");\n const account = await requireAlignedWalletAccount(\"clear\", this.#signer, this.#provider);\n const signerAddress = getAddress(account.address);\n try {\n await service.clearCredentials();\n } finally {\n await this.#clearDecryptCacheForRequester(signerAddress);\n }\n }\n\n async #clearDecryptCacheForRequester(signerAddress: Address): Promise<void> {\n await swallow(\n \"clear decrypt cache\",\n () => this.#cachingService.clearForRequester(signerAddress),\n this.#logger,\n );\n }\n\n /**\n * Revoke the shared transport key pair for `transportKeyPairScope`. Storage-only,\n * operator-level action: no wallet account or signer needs to be connected.\n *\n * Deletes the shared key pair; every permit in the scope embeds its public key, so\n * they're all treated as stale on next access. Signer-level {@link clear} never does\n * this — it only ever wipes the calling signer's own permits.\n *\n * Not best-effort, unlike most credential-store writes: a storage failure rejects\n * instead of being logged and swallowed. This is the primitive an operator reaches\n * for on suspected key compromise — a resolved promise must mean the key pair is\n * actually gone.\n *\n * Stops the SDK from reissuing or reusing the deleted key — does not revoke any\n * permit already issued under it. A permit is a self-contained, bearer-style EIP-712\n * signature the relayer accepts independently of this SDK; one exfiltrated alongside\n * the key remains usable until its own `permitTTL` expiry regardless of this call.\n *\n * @param scopeId - Must match the configured `transportKeyPairScope`, as a guard\n * against revoking the wrong scope by mistake.\n * @throws if no scope is configured, or `scopeId` doesn't match it. {@link ConfigurationError}\n * @throws if the underlying storage delete fails.\n */\n async revokeTransportKeyPair(scopeId: string): Promise<void> {\n const service = this.#requireCredentialService(\"revokeTransportKeyPair\");\n await service.revokeTransportKeyPair(scopeId);\n }\n\n /**\n * Warm the shared transport key pair for `transportKeyPairScope` — the pre-warm\n * counterpart to {@link revokeTransportKeyPair}. Storage-only, operator-level action:\n * no wallet account or signer needs to be connected. Prefer this over\n * {@link warmTransportKeyPair} for a scoped key pair: unlike that method, this never\n * silently no-ops for lack of a connected wallet, because a scope-wide key was never\n * tied to one in the first place.\n *\n * @param scopeId - Must match the configured `transportKeyPairScope`, as a guard\n * against warming the wrong scope by mistake.\n * @throws if no scope is configured, or `scopeId` doesn't match it. {@link ConfigurationError}\n * @throws if `transportKeyPairDerivationSecret` is configured and the keypair fails to wrap or\n * unwrap. {@link KeyWrappingError}\n */\n async warmTransportKeyPairScope(scopeId: string): Promise<void> {\n const service = this.#requireCredentialService(\"warmTransportKeyPairScope\");\n await service.warmTransportKeyPairScope(scopeId);\n }\n}\n","import type { Address } from \"viem\";\nimport type { DelegationService, DelegationStatus } from \"../services/delegation-service\";\nimport type { GenericProvider, GenericSigner, TransactionResult } from \"../types\";\nimport { requireAlignedWalletAccount } from \"../utils/alignment\";\nimport { requireConfigured } from \"../errors\";\n\n/**\n * Public namespace for on-chain decryption-delegation management.\n *\n * Exposed as `sdk.delegations`. Owns the SDK-level guards (signer requirement, chain\n * alignment, delegator address resolution from the wallet account) and delegates the\n * actual work to the internal {@link DelegationService}.\n *\n * Delegation operations write to the host chain ACL; after a delegation is mined,\n * the gateway syncs the ACL state via cross-chain event propagation — usually\n * within ~10 blocks (a few seconds). Delegated decryption rides out that window\n * with a bounded internal retry, so callers can decrypt right after granting.\n */\nexport class Delegations {\n readonly #signer: GenericSigner | undefined;\n readonly #provider: GenericProvider;\n readonly #delegationService: DelegationService;\n\n /** @internal */\n constructor(opts: {\n signer: GenericSigner | undefined;\n provider: GenericProvider;\n delegationService: DelegationService;\n }) {\n this.#signer = opts.signer;\n this.#provider = opts.provider;\n this.#delegationService = opts.delegationService;\n }\n\n #requireSigner(operation: string): GenericSigner {\n return requireConfigured(this.#signer, operation);\n }\n\n /**\n * Delegate decryption rights for a confidential contract to another address.\n * Calls `ACL.delegateForUserDecryption()` on-chain.\n *\n * The delegation is recorded on L1 immediately, but the gateway must sync the\n * ACL state via cross-chain event propagation — usually within ~10 blocks (a\n * few seconds). You do not need to wait: delegated decryption rides out that\n * window with a bounded internal retry, so you can decrypt right after this\n * resolves.\n *\n * @param contractAddress - The confidential contract address to delegate on, or\n * {@link WILDCARD_CONTRACT} to cover every contract with a single delegation.\n * @param delegateAddress - Address to delegate decryption rights to.\n * @param expirationDate - Optional expiration date (defaults to permanent delegation via `uint64.max`).\n * @returns The transaction hash and mined receipt.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if `expirationDate` is less than 1 hour in the future. {@link DelegationExpirationTooSoonError}\n * @throws if the delegate equals the connected wallet. {@link DelegationSelfNotAllowedError}\n * @throws if the delegate is the wildcard address. {@link DelegationDelegateCannotBeWildcardError}\n * @throws if the delegate equals the contract address. {@link DelegationDelegateEqualsContractError}\n * @throws if the new expiry equals the current one. {@link DelegationExpiryUnchangedError}\n * @throws if the delegation transaction reverts. {@link TransactionRevertedError}\n */\n async delegateDecryption({\n contractAddress,\n delegateAddress,\n expirationDate,\n }: {\n contractAddress: Address;\n delegateAddress: Address;\n expirationDate?: Date;\n }): Promise<TransactionResult> {\n const signer = this.#requireSigner(\"delegateDecryption\");\n const account = await requireAlignedWalletAccount(\n \"delegateDecryption\",\n this.#signer,\n this.#provider,\n );\n return this.#delegationService.delegateDecryption(signer, {\n contractAddress,\n delegateAddress,\n delegatorAddress: account.address,\n expirationDate,\n });\n }\n\n /**\n * Revoke decryption delegation for a confidential contract.\n * Calls `ACL.revokeDelegationForUserDecryption()` on-chain.\n *\n * @param contractAddress - The confidential contract address to revoke delegation on.\n * @param delegateAddress - Address to revoke delegation from.\n * @returns The transaction hash and mined receipt.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if no delegation exists for this (delegator, delegate, contract) tuple. {@link DelegationNotFoundError}\n * @throws if the revocation transaction reverts. {@link TransactionRevertedError}\n */\n async revokeDelegation({\n contractAddress,\n delegateAddress,\n }: {\n contractAddress: Address;\n delegateAddress: Address;\n }): Promise<TransactionResult> {\n const signer = this.#requireSigner(\"revokeDelegation\");\n const account = await requireAlignedWalletAccount(\n \"revokeDelegation\",\n this.#signer,\n this.#provider,\n );\n return this.#delegationService.revokeDelegation(signer, {\n contractAddress,\n delegateAddress,\n delegatorAddress: account.address,\n });\n }\n\n /**\n * Check whether a delegation is active for the given contract address.\n *\n * Signer-independent: works without a configured signer.\n *\n * @param contractAddress - The confidential contract address.\n * @param delegatorAddress - The address that granted the delegation.\n * @param delegateAddress - The address that received delegation rights.\n * @returns `true` if the delegation exists and has not expired.\n */\n async isActive(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<boolean> {\n return this.#delegationService.isDelegated(params);\n }\n\n /**\n * Get the expiration timestamp of a delegation for the given contract.\n *\n * Signer-independent: works without a configured signer.\n *\n * @param contractAddress - The confidential contract address.\n * @param delegatorAddress - The address that granted the delegation.\n * @param delegateAddress - The address that received delegation rights.\n * @returns Unix timestamp as bigint. `0n` = no delegation. `2^64 - 1` = permanent.\n */\n async getExpiry(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<bigint> {\n return this.#delegationService.getDelegationExpiry(params);\n }\n\n /**\n * Get activity and expiry together in a single on-chain read, instead of\n * calling {@link isActive} and {@link getExpiry} separately.\n *\n * Signer-independent: works without a configured signer.\n *\n * @param contractAddress - The confidential contract address.\n * @param delegatorAddress - The address that granted the delegation.\n * @param delegateAddress - The address that received delegation rights.\n * @returns `{ isActive, expiryTimestamp }` — activity and the raw expiry timestamp together.\n */\n async getStatus(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<DelegationStatus> {\n return this.#delegationService.getStatus(params);\n }\n}\n","import type { Address } from \"viem\";\nimport { requireConfigured, wrapDecryptError } from \"../errors\";\nimport type { EncryptedInput } from \"../query/user-decrypt\";\nimport type { ChainRouter } from \"../chains/router\";\nimport type {\n ClearValue,\n DecryptPublicValuesResult,\n EncryptedValue,\n FhevmRelayerOptions,\n} from \"../relayer/types\";\nimport type {\n BatchDecryptResult,\n DecryptionService,\n DelegatedDecryptOptions,\n} from \"../services/decryption-service\";\nimport type { GenericProvider, GenericSigner } from \"../types\";\nimport { requireAlignedWalletAccount } from \"../utils/alignment\";\nimport { assertNonNullable } from \"../utils\";\n\n/**\n * Public namespace for FHE decryption — the canonical way to decrypt.\n *\n * Exposed as `sdk.decryption`. Prefer these methods over the low-level\n * `sdk.relayer.decryptValues` / `decryptPublicValues`: they\n * assemble the credential bundle (transport key pair, EIP-712 permit) for you,\n * cache results, and wrap relayer errors. Reach for `sdk.relayer.*` only when\n * you must control credential assembly by hand.\n *\n * Owns the SDK-level guards (signer requirement on\n * `decryptValues` and `delegatedDecryptValues`, empty-array\n * short-circuit on `decryptPublicValues`, relayer error wrapping) and delegates the\n * actual work to the internal {@link DecryptionService} or the relayer directly for\n * `decryptPublicValues`.\n *\n * **Mixed signer requirement:** `decryptValues` and\n * `delegatedDecryptValues` need a configured signer; `decryptPublicValues`\n * does not. Each method documents its requirement in its JSDoc.\n *\n * **Request chunking:** decrypt requests are split internally to stay under\n * the relayer's 2048-cleartext-bit per-request budget — callers never need to\n * size batches themselves.\n */\nexport class Decryption {\n readonly #signer: GenericSigner | undefined;\n readonly #provider: GenericProvider;\n readonly #router: ChainRouter;\n readonly #decryptionService: DecryptionService | undefined;\n\n /** @internal */\n constructor(opts: {\n signer: GenericSigner | undefined;\n provider: GenericProvider;\n router: ChainRouter;\n decryptionService: DecryptionService | undefined;\n }) {\n this.#signer = opts.signer;\n this.#provider = opts.provider;\n this.#router = opts.router;\n this.#decryptionService = opts.decryptionService;\n }\n\n #requireDecryptionService(operation: string): DecryptionService {\n return requireConfigured(this.#decryptionService, operation);\n }\n\n /**\n * Decrypt one or more FHE encrypted values. Results are cached — repeated calls\n * for the same encrypted value skip the relayer round-trip.\n *\n * Zero encrypted values are mapped to `0n` without hitting the relayer.\n * Events (`DecryptStart/End/Error`) are emitted uniformly.\n * Relayer errors are wrapped into typed SDK errors.\n *\n * @param encryptedInput - Encrypted values to decrypt, each paired with its contract address.\n * @param options - Per-call `signal` and `timeout` forwarded to the relayer round-trip.\n * @returns A record mapping each encrypted value to its decrypted clear-text value.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n *\n * @example\n * ```ts\n * const values = await sdk.decryption.decryptValues([\n * { encryptedValue: balance, contractAddress: cUSDT },\n * ]);\n * console.log(values[balance]); // 1000n\n * ```\n */\n async decryptValues(\n encryptedInput: EncryptedInput[],\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<Record<EncryptedValue, ClearValue>> {\n const service = this.#requireDecryptionService(\"decryptValues\");\n const account = await requireAlignedWalletAccount(\n \"decryptValues\",\n this.#signer,\n this.#provider,\n );\n return service.decryptValues(encryptedInput, account.address, options);\n }\n\n /**\n * Decrypt one or more FHE encrypted values using delegated credentials.\n *\n * Mirrors {@link decryptValues} with delegated credentials — same caching and\n * zero-value short-circuit. Before reading from cache or calling the relayer,\n * every non-zero encrypted value's contract must have an active delegation from the\n * delegator to the connected signer; missing or expired delegations fail fast.\n *\n * @param encryptedInputs - FHE encrypted values paired with their contract addresses.\n * @param delegatorAddress - The address that granted delegation rights.\n * @param accountAddress - Address used as the cache key's \"requester\"\n * dimension. Defaults to `delegatorAddress`. Pass the actual account address\n * when decrypting on behalf of someone whose balance is stored under a\n * different address (e.g. `decryptBalanceAs` with an explicit `accountAddress`).\n * @param options - Delegated-decrypt options. By default the call rides out the\n * gateway propagation window ({@link DelegatedDecryptOptions.waitForPropagation});\n * pass `{ waitForPropagation: false }` to fail fast instead.\n * @returns Map of encrypted value → clear-text value.\n *\n * @example\n * ```ts\n * const values = await sdk.decryption.delegatedDecryptValues([\n * { encryptedValue: balance, contractAddress: tokenAddr },\n * ], delegatorAddr);\n * console.log(values[balance]); // 1000n\n * ```\n */\n async delegatedDecryptValues(\n encryptedInputs: EncryptedInput[],\n delegatorAddress: Address,\n accountAddress: Address = delegatorAddress,\n options?: DelegatedDecryptOptions,\n ): Promise<Record<EncryptedValue, ClearValue>> {\n const service = this.#requireDecryptionService(\"delegatedDecryptValues\");\n const account = await requireAlignedWalletAccount(\n \"delegatedDecryptValues\",\n this.#signer,\n this.#provider,\n );\n return service.delegatedDecryptValues(\n encryptedInputs,\n delegatorAddress,\n account.address,\n accountAddress,\n options,\n );\n }\n\n /**\n * Publicly decrypt one or more FHE encrypted values.\n *\n * Signer-independent: works without a configured signer.\n * Returns the decryption proof alongside the clear-text values so callers\n * can submit on-chain finalization transactions (e.g. `finalizeUnwrap`).\n *\n * @param encryptedValues - FHE encrypted values to decrypt publicly.\n * @param options - Per-call `signal` and `timeout` forwarded to the relayer round-trip.\n * @returns Clear-text values, ABI-encoded values, and the decryption proof.\n *\n * @example\n * ```ts\n * const { clearValues, decryptionProof, abiEncodedClearValues } =\n * await sdk.decryption.decryptPublicValues([encryptedValue]);\n * ```\n */\n async decryptPublicValues(\n encryptedValues: EncryptedValue[],\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<DecryptPublicValuesResult> {\n if (encryptedValues.length === 0) {\n return { clearValues: {}, decryptionProof: \"0x\", abiEncodedClearValues: \"0x\" };\n }\n\n try {\n const result = await this.#router.relayer.decryptPublicValuesWithSignatures({\n encryptedValues,\n options,\n });\n const clearValues: Record<EncryptedValue, ClearValue> = {};\n result.checkSignaturesArgs.handlesList.forEach((handle, i) => {\n assertNonNullable(result.clearValues[i], `result.clearValues[${i}]`);\n clearValues[handle] = result.clearValues[i].value;\n });\n return {\n clearValues,\n abiEncodedClearValues: result.checkSignaturesArgs.abiEncodedCleartexts,\n decryptionProof: result.checkSignaturesArgs.decryptionProof,\n };\n } catch (error) {\n throw wrapDecryptError(error, \"Public decryption failed\");\n }\n }\n\n /**\n * Batch-decrypt delegated encrypted values with per-entry error isolation.\n *\n * Attempts a single batch request first. If the batch fails with a non-fatal\n * error (e.g. one entry is invalid), falls back to per-entry decryption so\n * healthy entries still resolve. Each item in the result carries either a\n * decrypted value or an error — callers decide how to surface partial failures.\n *\n * @param encryptedInputs - FHE encrypted values paired with their contract addresses.\n * @param delegatorAddress - The address that granted delegation rights.\n * @param accountAddress - The account on whose behalf decryption is performed. Defaults to `delegatorAddress`.\n * @param maxConcurrency - Maximum parallel decrypt calls during per-entry fallback.\n * @param waitForPropagation - Ride out the gateway propagation window on the\n * initial batch attempt (default `true`). See {@link DelegatedDecryptOptions.waitForPropagation}.\n * @returns Per-entry results, each with a value or an error.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws A failure that affects the whole session (rejected signature, RPC\n * rate limit, revoked KMS context) rejects the call instead of landing in a\n * per-entry error.\n *\n * @example\n * ```ts\n * const result = await sdk.decryption.delegatedBatchDecryptValues({\n * encryptedInputs: [\n * { encryptedValue: encryptedValue1, contractAddress: tokenA },\n * { encryptedValue: encryptedValue2, contractAddress: tokenB },\n * ],\n * delegatorAddress: \"0xDelegator\",\n * maxConcurrency: 5,\n * });\n * for (const item of result.items) {\n * if (item.error) console.error(item.encryptedValue, item.error);\n * else console.log(item.encryptedValue, item.value);\n * }\n * ```\n */\n async delegatedBatchDecryptValues({\n encryptedInputs,\n delegatorAddress,\n accountAddress = delegatorAddress,\n maxConcurrency,\n waitForPropagation,\n }: {\n encryptedInputs: EncryptedInput[];\n delegatorAddress: Address;\n accountAddress?: Address;\n maxConcurrency?: number;\n } & DelegatedDecryptOptions): Promise<BatchDecryptResult> {\n const service = this.#requireDecryptionService(\"delegatedBatchDecryptValues\");\n const account = await requireAlignedWalletAccount(\n \"delegatedBatchDecryptValues\",\n this.#signer,\n this.#provider,\n );\n return service.delegatedBatchDecryptHandlesAs({\n encryptedInputs,\n delegatorAddress,\n delegateAddress: account.address,\n accountAddress,\n maxConcurrency,\n waitForPropagation,\n });\n }\n}\n","import type { CredentialService } from \"../credentials/credential-service\";\nimport type { PreparedPermit, PreparePermitRequest } from \"../credentials/types\";\nimport type { OfflineService } from \"../services/offline-service\";\nimport type {\n PreparedFor,\n PrepareOptions,\n PrepareTransactionRequest,\n TransactionKind,\n} from \"../types\";\n\n/**\n * Namespace for the offline-signing pipeline —\n * `prepare → [external sign + self-publish]` — for institutional custody, HSM\n * ceremonies, and policy-engine workflows where signing runs out-of-process and\n * cannot happen synchronously in a single Promise.\n */\nexport class Offline {\n readonly #offlineService: OfflineService;\n readonly #credentialService: CredentialService;\n\n /** @internal */\n constructor(offlineService: OfflineService, credentialService: CredentialService) {\n this.#offlineService = offlineService;\n this.#credentialService = credentialService;\n }\n\n /**\n * Build an RLP-encoded unsigned transaction for the given request. The\n * caller signs it externally — via an HSM ceremony, an out-of-process\n * custodian, or any signer holding the key — and broadcasts the signed bytes\n * through its own channel.\n *\n * Signer-optional: works without a configured signer (canonical shape for\n * cross-process custody — the back-end signer service consumes\n * `prepared.unsignedTx` and returns signed bytes).\n *\n * @remarks\n * `request.from` is only a declaration — the SDK does not prove the caller\n * controls it, and an EIP-1559 unsigned tx carries no `from` field at all\n * (the on-chain sender is whichever key signs the bytes). Point `from` at\n * the account the custodian will sign with; custodians enforce key-control\n * at sign time — a signing request for a key the credential can't use fails\n * there — so a mismatched `from` cannot make the custodian sign from an\n * account you don't control. Verifying control of `from` up front is still\n * the application's responsibility.\n */\n prepare<K extends TransactionKind>(\n request: Extract<PrepareTransactionRequest, { kind: K }>,\n options?: PrepareOptions,\n ): Promise<PreparedFor<K>> {\n return this.#offlineService.prepare(request, options);\n }\n\n /**\n * Build the offline-signing payload for a decryption permit: the unsigned\n * EIP-712 typed data plus everything `sdk.permits.registerPermit` needs to\n * verify and persist the signature an out-of-process signer returns for it.\n *\n * Not a `prepare()` transaction kind: a permit is not a transaction —\n * nothing is broadcast, and registering the signature is a local operation,\n * not a relayer round-trip.\n *\n * Signer-optional, like {@link prepare}: `request.signer` is an explicit\n * address, not a connected wallet account. Building the typed data still\n * reads the chain's KMS signers context on-chain — signer-offline, not\n * network-offline.\n *\n * One permit per call: unlike `sdk.permits.grantPermit`, this never widens\n * an existing permit or chunks over 10 contracts — `request.contracts` maps\n * to exactly one signature.\n *\n * @throws if `request.contracts` is empty or exceeds 10 addresses, `request.delegator`\n * equals `request.signer`, or `request.durationDays` exceeds the V1 permit maximum\n * of 365 days. {@link ConfigurationError}\n * @throws if a concurrent `permits.revokeTransportKeyPair()` rotates the transport key\n * pair while this call is generating one. {@link TransportKeyPairChangedError}\n */\n preparePermit(request: PreparePermitRequest): Promise<PreparedPermit> {\n return this.#credentialService.preparePermit(request);\n }\n}\n","import type { GenericStorage } from \"../types\";\n\n/** Minimal chrome.storage.session typings (avoids depending on @types/chrome). */\ndeclare const chrome: {\n storage: {\n session: {\n get(key: string): Promise<Record<string, unknown>>;\n set(items: Record<string, unknown>): Promise<void>;\n remove(key: string): Promise<void>;\n };\n };\n};\n\n/**\n * {@link GenericStorage} backed by `chrome.storage.session`.\n *\n * Use this in MV3 web extensions so the wallet signature survives\n * service worker restarts and is shared across popup, background,\n * and content script contexts.\n *\n * @example\n * ```ts\n * import { ZamaSDK, indexedDBStorage, chromeSessionStorage } from \"@zama-fhe/sdk\";\n * import { createConfig } from \"@zama-fhe/sdk/viem\";\n *\n * const config = createConfig({\n * chains: [mySepolia],\n * publicClient,\n * walletClient,\n * relayers: { [mySepolia.id]: web() },\n * storage: indexedDBStorage, // encrypted transport key pair — persistent\n * permitStorage: chromeSessionStorage, // signed permits — ephemeral\n * });\n * const sdk = new ZamaSDK(config);\n * ```\n */\nexport class ChromeSessionStorage implements GenericStorage {\n /**\n * Retrieve a value by key.\n * @returns The stored value, or `null` if the key does not exist.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n const result = await chrome.storage.session.get(key);\n return (result[key] as T) ?? null;\n }\n\n /** Store a value under the given key, overwriting any existing entry. */\n async set(key: string, value: unknown): Promise<void> {\n await chrome.storage.session.set({ [key]: value });\n }\n\n /** Remove the entry for the given key (no-op if absent). */\n async delete(key: string): Promise<void> {\n await chrome.storage.session.remove(key);\n }\n}\n\n/** Default singleton for application-wide use. */\nexport const chromeSessionStorage = new ChromeSessionStorage();\n","import { getAddress, type Address } from \"viem\";\nimport { z } from \"zod/mini\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/types\";\nimport { checksummedAddress } from \"../schemas/primitives\";\nimport type { GenericLogger, GenericStorage } from \"../types\";\n\nconst CacheValueSchema = z.union([z.bigint(), z.boolean(), checksummedAddress]);\nconst CacheIndexSchema = z.array(z.string());\n\n/**\n * Storage-backed cache for decrypted FHE plaintext values.\n *\n * Each entry is keyed by `(requester, contractAddress, handle)` so different\n * signers cannot read each other's cached decryptions.\n *\n * @internal\n */\nexport class CachingService {\n readonly #storage: GenericStorage;\n readonly #logger: GenericLogger;\n readonly #decryptNamespace = \"zama:decrypt\";\n readonly #decryptKeysNamespace = `${this.#decryptNamespace}:keys`;\n #indexWriteQueue: Promise<void> = Promise.resolve();\n\n constructor(storage: GenericStorage, logger: GenericLogger) {\n this.#storage = storage;\n this.#logger = logger;\n }\n\n async get(\n requester: Address,\n contractAddress: Address,\n encryptedValue: EncryptedValue,\n ): Promise<ClearValue | null> {\n try {\n const key = this.#buildStorageKey(requester, contractAddress, encryptedValue);\n const value = await this.#storage.get(key);\n if (value === null) {\n return null;\n }\n const parsed = CacheValueSchema.safeParse(value);\n if (!parsed.success) {\n await this.delete(requester, contractAddress, encryptedValue);\n return null;\n }\n return parsed.data;\n } catch (error) {\n this.#logger.warn(\"CachingService.get failed\", { error });\n return null;\n }\n }\n\n async set(\n requester: Address,\n contractAddress: Address,\n encryptedValue: EncryptedValue,\n value: ClearValue,\n ): Promise<void> {\n try {\n const key = this.#buildStorageKey(requester, contractAddress, encryptedValue);\n await this.#storage.set<ClearValue>(key, value);\n this.#indexWriteQueue = this.#indexWriteQueue.then(() =>\n this.#addToIndex(key).catch((error) => {\n this.#logger.warn(\"CachingService index write failed\", { error });\n }),\n );\n await this.#indexWriteQueue;\n } catch (error) {\n this.#logger.warn(\"CachingService.set failed\", { error });\n }\n }\n\n async delete(\n requester: Address,\n contractAddress: Address,\n encryptedValue: EncryptedValue,\n ): Promise<void> {\n const key = this.#buildStorageKey(requester, contractAddress, encryptedValue);\n this.#indexWriteQueue = this.#indexWriteQueue.then(() =>\n this.#doDelete(key).catch((error) => {\n this.#logger.warn(\"CachingService.delete failed\", { error });\n }),\n );\n await this.#indexWriteQueue;\n }\n\n async clearForRequester(requester: Address): Promise<void> {\n this.#indexWriteQueue = this.#indexWriteQueue.then(() =>\n this.#doClearForRequester(requester).catch((error) => {\n this.#logger.warn(\"CachingService.clearForRequester failed\", { error });\n }),\n );\n await this.#indexWriteQueue;\n }\n\n async clearAll(): Promise<void> {\n this.#indexWriteQueue = this.#indexWriteQueue.then(() =>\n this.#doClearAll().catch((error) => {\n this.#logger.warn(\"CachingService.clearAll failed\", { error });\n }),\n );\n await this.#indexWriteQueue;\n }\n\n async #doDelete(key: string): Promise<void> {\n await this.#storage.delete(key).catch(() => {});\n const keys = await this.#readIndex();\n const remaining = keys.filter((k) => k !== key);\n if (remaining.length !== keys.length) {\n await this.#storage.set(this.#decryptKeysNamespace, remaining);\n }\n }\n\n async #doClearForRequester(requester: Address): Promise<void> {\n const checksumRequester = getAddress(requester);\n const prefix = `${this.#decryptNamespace}:${checksumRequester}:`;\n const keys = await this.#readIndex();\n const toRemove: string[] = [];\n const remaining: string[] = [];\n for (const k of keys) {\n if (k.startsWith(prefix)) {\n toRemove.push(k);\n } else {\n remaining.push(k);\n }\n }\n await Promise.all(toRemove.map((k) => this.#storage.delete(k).catch(() => {})));\n await this.#storage.set(this.#decryptKeysNamespace, remaining);\n }\n\n async #doClearAll(): Promise<void> {\n const keys = await this.#readIndex();\n await Promise.all(keys.map((k) => this.#storage.delete(k).catch(() => {})));\n await this.#storage.delete(this.#decryptKeysNamespace);\n }\n\n #buildStorageKey(\n requester: Address,\n contractAddress: Address,\n encryptedValue: EncryptedValue,\n ): string {\n return `${this.#decryptNamespace}:${getAddress(requester)}:${getAddress(contractAddress)}:${encryptedValue.toLowerCase()}`;\n }\n\n async #readIndex(): Promise<string[]> {\n const value = await this.#storage.get(this.#decryptKeysNamespace);\n if (value === null) {\n return [];\n }\n const parsed = CacheIndexSchema.safeParse(value);\n if (parsed.success) {\n return parsed.data;\n }\n await this.#storage.delete(this.#decryptKeysNamespace).catch(() => {});\n return [];\n }\n\n async #addToIndex(key: string): Promise<void> {\n const keys = await this.#readIndex();\n if (!keys.includes(key)) {\n keys.push(key);\n await this.#storage.set(this.#decryptKeysNamespace, keys);\n }\n }\n}\n","import type { Address, Hex } from \"viem\";\nimport { DecryptionFailedError } from \"../errors\";\nimport { checksum } from \"../schemas/primitives\";\nimport type {\n Permission,\n SerializedTransportKeyPairWithPermissions,\n SerializedPermit,\n} from \"./types\";\n\n/**\n * The minimal permit material the decrypt seam needs. Delegation is already\n * encoded in the self-contained `serializedPermit`, so a delegated decrypt and\n * a normal decrypt resolve to the same shape — there is no separate delegated\n * variant.\n */\nexport interface ResolvedPermit {\n privateKey: Hex;\n publicKey: Hex;\n serializedPermit: SerializedPermit;\n}\n\n/**\n * Resolve the signed permit covering `contractAddress` from previously granted\n * credentials. Works uniformly for direct and delegated decryption: the\n * `@fhevm/sdk` signed permit bakes the delegator (if any) into its EIP-712\n * payload, so the decrypt call needs nothing beyond the transport key pair and\n * the serialized permit.\n *\n * @throws if no stored permit covers `contractAddress`. {@link DecryptionFailedError}\n */\nexport function resolvePermit(\n credentials: SerializedTransportKeyPairWithPermissions,\n contractAddress: Address,\n): ResolvedPermit {\n const permission = findPermissionFor(credentials, contractAddress);\n if (!permission) {\n throw new DecryptionFailedError(`No permit covers contract ${contractAddress} after allow()`);\n }\n return {\n privateKey: credentials.keypair.privateKey,\n publicKey: credentials.keypair.publicKey,\n serializedPermit: permission.serializedPermit,\n };\n}\n\nfunction findPermissionFor(\n credentials: SerializedTransportKeyPairWithPermissions,\n contractAddress: Address,\n): Permission | undefined {\n const target = checksum(contractAddress);\n return credentials.permissions.find((permission) =>\n permission.contractAddresses.includes(target),\n );\n}\n","import type { ParseTransportKeyPairReturnType } from \"@fhevm/sdk/actions/chain\";\nimport type { DecryptValuesReturnType } from \"@fhevm/sdk/actions/decrypt\";\nimport { getAddress, type Address } from \"viem\";\nimport type { ChainRouter } from \"../chains/router\";\nimport type { CredentialService } from \"../credentials/credential-service\";\nimport { resolvePermit } from \"../credentials/decrypt-permit\";\nimport type { SerializedTransportKeyPairWithPermissions } from \"../credentials/types\";\nimport {\n type DecryptErrorContext,\n DecryptionFailedError,\n DelegationNotPropagatedError,\n isFatalBatchError,\n RevokedKmsContextError,\n RpcRateLimitError,\n SigningFailedError,\n wrapDecryptError,\n ZamaError,\n} from \"../errors\";\nimport type { ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { ZamaSDKEvents } from \"../events/sdk-events\";\nimport type { EncryptedInput } from \"../query/user-decrypt\";\nimport type { ClearValue, EncryptedValue, FhevmRelayerOptions } from \"../relayer/types\";\nimport { pLimit } from \"../utils/concurrency\";\nimport { chunkHandlesByBitBudget, isEncryptedValueZero } from \"../utils/handles\";\nimport {\n extractRetryAfter,\n isInvalidTransportKeyPairMessage,\n isRpcRateLimitError,\n toError,\n} from \"../utils\";\nimport type { CachingService } from \"./caching-service\";\nimport type { DelegationService } from \"./delegation-service\";\n\n/**\n * How long the delegated-decrypt path keeps retrying while a freshly granted\n * delegation propagates to the gateway. Propagation usually completes within\n * ~10 blocks (a few seconds); this ceiling absorbs a briefly lagging gateway\n * without turning a genuine outage into a long hang.\n */\nconst DELEGATION_PROPAGATION_RETRY_BUDGET_MS = 30_000;\n/** Delay between propagation retries. */\nconst DELEGATION_PROPAGATION_RETRY_INTERVAL_MS = 2_000;\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** Options shared by the delegated-decrypt entry points. */\nexport interface DelegatedDecryptOptions {\n /**\n * Ride out the gateway propagation window: when a just-granted delegation\n * has not yet synced, the delegated decrypt is retried (bounded, ~30s) until\n * it lands instead of throwing {@link DelegationNotPropagatedError}. Defaults\n * to `true`. Pass `false` to fail fast on the first not-propagated response.\n */\n waitForPropagation?: boolean;\n}\n\ninterface DecryptionStrategy {\n requesterAddress: Address;\n /**\n * Delegator whose permit scope this decrypt reads; undefined on the direct\n * path. The single delegation discriminator: it also selects the delegated\n * error classification and the ACL actor (delegator, or the requester when\n * direct).\n */\n delegator?: Address;\n validate?: (contractAddresses: readonly Address[]) => Promise<void>;\n errorMessage: string;\n}\n\n/** One decrypt-relayer request: a contract's handles chunked to the bit budget. */\ninterface DecryptRequest {\n contractAddress: Address;\n encryptedValues: EncryptedValue[];\n}\n\n/** Tracks the evict-and-regrant allowance across retried decrypt attempts. */\ninterface RecoveryBudget {\n spent: boolean;\n}\n\n/** Per-handle outcome of a batch decrypt: the decrypted value, or a per-item error. */\nexport interface BatchDecryptItem {\n /** The encrypted value (handle) being decrypted. */\n encryptedValue: EncryptedValue;\n /** Address of the contract the handle belongs to. */\n contractAddress: Address;\n /** Decrypted clear value; set when this item succeeded. */\n value?: ClearValue;\n /** Error for this item; set when this item failed. */\n error?: ZamaError;\n}\n\n/** Result of a batch decrypt: one entry per requested handle, in input order. */\nexport interface BatchDecryptResult {\n /** Per-handle outcomes. */\n items: BatchDecryptItem[];\n}\n\n/** @internal */\nexport class DecryptionService {\n readonly #cache: CachingService;\n readonly #credentialService: CredentialService;\n readonly #delegationService: DelegationService;\n readonly #router: ChainRouter;\n readonly #emitEvent: (input: ZamaSDKEventInput) => void;\n\n constructor({\n cache,\n credentialService,\n delegationService,\n router,\n emitEvent,\n }: {\n cache: CachingService;\n credentialService: CredentialService;\n delegationService: DelegationService;\n router: ChainRouter;\n emitEvent: (input: ZamaSDKEventInput) => void;\n }) {\n this.#cache = cache;\n this.#credentialService = credentialService;\n this.#delegationService = delegationService;\n this.#router = router;\n this.#emitEvent = emitEvent;\n }\n\n async decryptValues(\n handles: EncryptedInput[],\n signerAddress: Address,\n opts?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<Record<EncryptedValue, ClearValue>> {\n const normalizedSigner = getAddress(signerAddress);\n return this.#decrypt(\n handles,\n { requesterAddress: normalizedSigner, errorMessage: \"Failed to decrypt encrypted values\" },\n opts,\n );\n }\n\n async delegatedDecryptValues(\n encryptedInputs: EncryptedInput[],\n delegatorAddress: Address,\n delegateAddress: Address,\n accountAddress: Address,\n opts?: DelegatedDecryptOptions,\n ): Promise<Record<EncryptedValue, ClearValue>> {\n const normalizedDelegator = getAddress(delegatorAddress);\n const normalizedDelegate = getAddress(delegateAddress);\n // One evict-and-regrant across the whole propagation-retry loop, not one\n // per attempt: each retry would otherwise re-arm the recovery and spend a\n // fresh wallet prompt per 2s attempt while the upstream validity cache\n // keeps serving the revoked context.\n const recovery: RecoveryBudget = { spent: false };\n return this.#withPropagationRetry(opts?.waitForPropagation ?? true, () =>\n this.#decrypt(\n encryptedInputs,\n {\n requesterAddress: getAddress(accountAddress),\n delegator: normalizedDelegator,\n validate: (contractAddresses) =>\n this.#assertAllDelegationsActive(contractAddresses, {\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n }),\n errorMessage: \"Failed to decrypt delegated encrypted values\",\n },\n undefined,\n recovery,\n ),\n );\n }\n\n /**\n * Absorb the gateway propagation window on the delegated path: retry `attempt`\n * (bounded by {@link DELEGATION_PROPAGATION_RETRY_BUDGET_MS}) while it fails\n * with a transient {@link DelegationNotPropagatedError}. Every other error —\n * including a missing/expired grant surfaced by the pre-check — throws\n * immediately, and passing `waitForPropagation: false` disables the retry so\n * the first not-propagated response propagates unchanged.\n */\n async #withPropagationRetry<T>(\n waitForPropagation: boolean,\n attempt: () => Promise<T>,\n ): Promise<T> {\n // Fixed-interval polling across the budget: e.g. 30s / 2s = 15 gaps, so 16\n // attempts. Bounded (no open-ended loop) and deterministic under fake timers.\n const maxAttempts =\n Math.floor(\n DELEGATION_PROPAGATION_RETRY_BUDGET_MS / DELEGATION_PROPAGATION_RETRY_INTERVAL_MS,\n ) + 1;\n let lastError: unknown;\n for (let i = 0; i < maxAttempts; i++) {\n try {\n return await attempt();\n } catch (error) {\n lastError = error;\n const canRetry =\n i < maxAttempts - 1 &&\n waitForPropagation &&\n error instanceof DelegationNotPropagatedError;\n if (!canRetry) {\n throw error;\n }\n await sleep(DELEGATION_PROPAGATION_RETRY_INTERVAL_MS);\n }\n }\n throw lastError;\n }\n\n async delegatedBatchDecryptHandlesAs({\n encryptedInputs,\n delegatorAddress,\n delegateAddress,\n accountAddress,\n maxConcurrency = 5,\n waitForPropagation = true,\n }: {\n encryptedInputs: EncryptedInput[];\n delegatorAddress: Address;\n delegateAddress: Address;\n accountAddress: Address;\n maxConcurrency?: number;\n waitForPropagation?: boolean;\n }): Promise<BatchDecryptResult> {\n const items: BatchDecryptItem[] = encryptedInputs.map((h) => ({\n encryptedValue: h.encryptedValue,\n contractAddress: getAddress(h.contractAddress),\n }));\n if (items.length === 0) {\n return { items };\n }\n const normalizedAccount = getAddress(accountAddress);\n\n try {\n const decrypted = await this.delegatedDecryptValues(\n items.map(({ encryptedValue, contractAddress }) => ({ encryptedValue, contractAddress })),\n delegatorAddress,\n delegateAddress,\n normalizedAccount,\n { waitForPropagation },\n );\n for (const item of items) {\n this.#setHandleResult(item, decrypted);\n }\n return { items };\n } catch (error) {\n if (isFatalBatchError(error)) {\n throw error;\n }\n if (items.length === 1) {\n const [item = this.#missingBatchItem()] = items;\n item.error = this.#toZamaError(error, \"Failed to decrypt delegated encrypted values\", {\n isDelegated: true,\n contractAddress: item.contractAddress,\n account: getAddress(delegatorAddress),\n });\n return { items };\n }\n }\n\n // `pLimit` cannot cancel calls that already started. The shared flag stops\n // the queued items from starting once a fatal error (e.g. an RPC rate\n // limit) is seen, instead of re-hitting the failing endpoint.\n let aborted = false;\n let fatal: unknown;\n await pLimit(\n items.map((item) => async () => {\n if (aborted) {\n return;\n }\n try {\n // The batch attempt above already rode out the propagation window for\n // the whole set; fail fast here so a still-unsynced delegation records\n // a per-item error instead of each item re-spending the full budget.\n const decrypted = await this.delegatedDecryptValues(\n [{ encryptedValue: item.encryptedValue, contractAddress: item.contractAddress }],\n delegatorAddress,\n delegateAddress,\n normalizedAccount,\n { waitForPropagation: false },\n );\n this.#setHandleResult(item, decrypted);\n } catch (error) {\n if (isFatalBatchError(error)) {\n aborted = true;\n fatal ??= error;\n return;\n }\n item.error = this.#toZamaError(error, \"Failed to decrypt delegated encrypted values\", {\n isDelegated: true,\n contractAddress: item.contractAddress,\n account: getAddress(delegatorAddress),\n });\n }\n }),\n maxConcurrency,\n );\n\n if (fatal !== undefined) {\n throw fatal;\n }\n\n return { items };\n }\n\n /**\n * Run a user (or delegated-user) decrypt for one contract: rebuild the\n * `@fhevm/sdk` transport key pair and signed permit from the resolved permit,\n * then decrypt. The delegation, if any, is encoded in the permit — both paths\n * share this call. Returns the positional clear values for `encryptedValues`.\n */\n async #decryptValues(\n credentials: SerializedTransportKeyPairWithPermissions,\n contractAddress: Address,\n encryptedValues: EncryptedValue[],\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<DecryptValuesReturnType> {\n const permit = resolvePermit(credentials, contractAddress);\n let transportKeyPair: ParseTransportKeyPairReturnType;\n try {\n transportKeyPair = await this.#router.relayer.parseTransportKeyPair({\n publicKey: permit.publicKey,\n privateKey: permit.privateKey,\n tkmsVersion: credentials.keypair.tkmsVersion,\n });\n } catch (error) {\n // Stale key pair the relayer can't re-derive (post KMS/TKMS rotation):\n // evict it so the next resolveCredentials regenerates and re-signs.\n // wrapDecryptError maps the raw message to InvalidTransportKeyPairError.\n if (error instanceof Error && isInvalidTransportKeyPairMessage(error.message)) {\n await this.#credentialService.evictTransportKeyPair();\n }\n throw error;\n }\n const signedPermit = await this.#router.relayer.parseSignedDecryptionPermit({\n transportKeyPair,\n serializedPermit: permit.serializedPermit,\n });\n return this.#router.relayer.decryptValues({\n transportKeyPair,\n signedPermit,\n encryptedValues,\n contractAddress,\n options,\n });\n }\n\n async #decrypt(\n handles: EncryptedInput[],\n strategy: DecryptionStrategy,\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n recovery: RecoveryBudget = { spent: false },\n ): Promise<Record<EncryptedValue, ClearValue>> {\n if (handles.length === 0) {\n return {};\n }\n\n const normalized = handles.map((h) => ({\n encryptedValue: h.encryptedValue,\n contractAddress: getAddress(h.contractAddress),\n }));\n const result: Record<EncryptedValue, ClearValue> = {};\n const nonZero: EncryptedInput[] = [];\n\n for (const h of normalized) {\n if (isEncryptedValueZero(h.encryptedValue)) {\n result[h.encryptedValue] = 0n;\n } else {\n nonZero.push(h);\n }\n }\n\n if (nonZero.length === 0) {\n return result;\n }\n\n const allContracts = Array.from(new Set(normalized.map((h) => h.contractAddress)));\n const nonZeroContracts = Array.from(new Set(nonZero.map((h) => h.contractAddress)));\n if (strategy.validate) {\n try {\n await strategy.validate(nonZeroContracts);\n } catch (error) {\n // The delegation pre-check makes on-chain reads too; classify a throttled\n // RPC here as well so delegated decrypt branches deterministically.\n if (isRpcRateLimitError(error)) {\n throw this.#rpcRateLimitError(error, \"the delegation pre-check\");\n }\n throw error;\n }\n }\n\n const uncached: EncryptedInput[] = [];\n for (const h of nonZero) {\n const cached = await this.#cache.get(\n strategy.requesterAddress,\n h.contractAddress,\n h.encryptedValue,\n );\n if (cached !== null) {\n result[h.encryptedValue] = cached;\n } else {\n uncached.push(h);\n }\n }\n\n if (uncached.length === 0) {\n return result;\n }\n\n let credentials = await this.#credentialService.grantPermit(allContracts, strategy.delegator);\n\n const byContract = new Map<Address, EncryptedValue[]>();\n for (const h of uncached) {\n const existing = byContract.get(h.contractAddress);\n if (existing) {\n existing.push(h.encryptedValue);\n } else {\n byContract.set(h.contractAddress, [h.encryptedValue]);\n }\n }\n\n // Split each contract's handles to stay under the relayer's per-request\n // cleartext-bit budget — a contract with many/wide handles becomes\n // several relayer calls instead of one oversized, rejected call.\n const requests: DecryptRequest[] = [];\n for (const [contractAddress, encryptedValues] of byContract) {\n for (const chunk of chunkHandlesByBitBudget(encryptedValues)) {\n requests.push({ contractAddress, encryptedValues: chunk });\n }\n }\n\n const t0 = Date.now();\n const uncachedEncryptedValues = uncached.map((h) => h.encryptedValue);\n try {\n this.#emitEvent({\n type: ZamaSDKEvents.DecryptStart,\n encryptedValues: uncachedEncryptedValues,\n });\n\n try {\n await this.#runDecryptRequests(strategy, credentials, requests, result, options);\n } catch (error) {\n if (!(error instanceof RevokedKmsContextError) || recovery.spent) {\n throw error;\n }\n // Identify the permits this attempt used: if they are already gone from\n // the store, a sibling decrypt recovered the scope and re-signing would\n // cost a second prompt for nothing.\n const staleSignatures = credentials.permissions.map((p) => p.serializedPermit.signature);\n // Re-grant under the current context and retry the still-unresolved\n // chunks once; a second revoked failure surfaces instead of looping\n // into the upstream 15-minute validity cache. Spent is set before\n // awaiting so a failing re-grant cannot re-arm the budget.\n recovery.spent = true;\n try {\n credentials = await this.#credentialService.recoverPermits(\n allContracts,\n strategy.delegator,\n staleSignatures,\n );\n } catch (recoveryError) {\n // A re-grant the signer cannot complete must not mask the revocation:\n // the caller's remedy is a new permit, not a signing fix. A user\n // rejecting the prompt stays a rejection.\n if (recoveryError instanceof SigningFailedError) {\n throw new RevokedKmsContextError(\n \"The permit's KMS context has been revoked on-chain and the automatic re-grant \" +\n \"failed, so the decrypt cannot proceed. Establish a new permit for this scope \" +\n \"and retry.\",\n { cause: recoveryError },\n );\n }\n throw recoveryError;\n }\n await this.#runDecryptRequests(\n strategy,\n credentials,\n requests.filter(({ encryptedValues }) =>\n encryptedValues.some((encryptedValue) => result[encryptedValue] === undefined),\n ),\n result,\n options,\n );\n }\n\n const uncachedResult: Record<EncryptedValue, ClearValue> = {};\n for (const encryptedValue of uncachedEncryptedValues) {\n const value = result[encryptedValue];\n if (value !== undefined) {\n uncachedResult[encryptedValue] = value;\n }\n }\n this.#emitEvent({\n type: ZamaSDKEvents.DecryptEnd,\n durationMs: Date.now() - t0,\n encryptedValues: uncachedEncryptedValues,\n result: uncachedResult,\n });\n return result;\n } catch (error) {\n // Per-contract failures are already classified into a typed ZamaError whose\n // `cause` is the original failure; surface that original in the observability\n // event so monitoring keeps the root-cause message.\n const original =\n error instanceof ZamaError && error.cause instanceof Error ? error.cause : error;\n this.#emitEvent({\n type: ZamaSDKEvents.DecryptError,\n error: toError(original),\n durationMs: Date.now() - t0,\n encryptedValues: uncachedEncryptedValues,\n });\n // The per-contract wrap above already classified these; this is a passthrough\n // for them plus a fallback for any non-contract failure (e.g. caching).\n throw wrapDecryptError(error, strategy.errorMessage, {\n isDelegated: strategy.delegator !== undefined,\n });\n }\n }\n\n /**\n * Fan the decrypt requests out (bounded concurrency), writing clear values\n * into `result` and the cache as each settles. Every request is settled\n * before anything is thrown: pLimit rejects on the first settled failure\n * while siblings are still in flight, which would let a sibling's earlier\n * failure hide a revoked-context revert from the recovery decision and let\n * the retry race workers still writing into `result`. Among the settled\n * failures, a {@link RevokedKmsContextError} is surfaced in preference to\n * whichever happened to settle first, so the self-heal always sees it.\n */\n async #runDecryptRequests(\n strategy: DecryptionStrategy,\n credentials: SerializedTransportKeyPairWithPermissions,\n requests: DecryptRequest[],\n result: Record<EncryptedValue, ClearValue>,\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<void> {\n const outcomes = await pLimit(\n requests.map(({ contractAddress, encryptedValues }) => async (): Promise<unknown> => {\n try {\n await this.#decryptRequest(\n strategy,\n credentials,\n contractAddress,\n encryptedValues,\n result,\n options,\n );\n return undefined;\n } catch (error) {\n return error;\n }\n }),\n 5,\n );\n const failures = outcomes.filter((outcome) => outcome !== undefined);\n if (failures.length > 0) {\n throw failures.find((failure) => failure instanceof RevokedKmsContextError) ?? failures[0];\n }\n }\n\n /** Decrypt one contract's chunk of handles into `result` (and the cache). */\n async #decryptRequest(\n strategy: DecryptionStrategy,\n credentials: SerializedTransportKeyPairWithPermissions,\n contractAddress: Address,\n encryptedValues: EncryptedValue[],\n result: Record<EncryptedValue, ClearValue>,\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<void> {\n // Classify per contract so a not-entitled / relayer failure carries the\n // exact contract + ACL actor. Already-typed errors pass straight through.\n let decrypted: DecryptValuesReturnType;\n try {\n decrypted = await this.#decryptValues(credentials, contractAddress, encryptedValues, options);\n } catch (error) {\n throw wrapDecryptError(error, strategy.errorMessage, {\n isDelegated: strategy.delegator !== undefined,\n contractAddress,\n account: strategy.delegator ?? strategy.requesterAddress,\n });\n }\n\n // `decryptValues` returns clear values positionally aligned with the\n // requested `encryptedValues`; zip them back into the handle→value map.\n for (let i = 0; i < encryptedValues.length; i++) {\n const encryptedValue = encryptedValues[i];\n const value = decrypted[i]?.value;\n if (encryptedValue === undefined || value === undefined) {\n continue;\n }\n result[encryptedValue] = value;\n await this.#cache.set(strategy.requesterAddress, contractAddress, encryptedValue, value);\n }\n\n const missing = encryptedValues.filter(\n (encryptedValue) => result[encryptedValue] === undefined,\n );\n if (missing.length > 0) {\n throw new DecryptionFailedError(\n `${strategy.errorMessage}: relayer returned no clear value for ${missing.length} of ${encryptedValues.length} handle(s) on ${contractAddress}`,\n {\n cause: new AggregateError(\n missing.map(\n (encryptedValue) =>\n new DecryptionFailedError(\n `No clear value for handle ${encryptedValue} on ${contractAddress}`,\n ),\n ),\n `${missing.length} handle(s) missing a clear value on ${contractAddress}`,\n ),\n },\n );\n }\n }\n\n /** Build an `RpcRateLimitError` for a throttled on-chain read. */\n #rpcRateLimitError(error: unknown, context: string): RpcRateLimitError {\n return new RpcRateLimitError(`RPC provider rate-limited ${context}; retry with backoff.`, {\n cause: error,\n retryAfter: extractRetryAfter(error),\n });\n }\n\n #setHandleResult(item: BatchDecryptItem, decrypted: Record<EncryptedValue, ClearValue>): void {\n const value = decrypted[item.encryptedValue];\n if (value === undefined) {\n item.error = new DecryptionFailedError(\n `Batch delegated decryption returned no value for encrypted value ${item.encryptedValue} on contract ${item.contractAddress}`,\n );\n return;\n }\n item.value = value;\n }\n\n #toZamaError(error: unknown, fallbackMessage: string, ctx?: DecryptErrorContext): ZamaError {\n return error instanceof ZamaError ? error : wrapDecryptError(error, fallbackMessage, ctx);\n }\n\n #missingBatchItem(): never {\n throw new DecryptionFailedError(\"Batch delegated decryption invariant failed: missing item\");\n }\n\n async #assertAllDelegationsActive(\n contractAddresses: readonly Address[],\n { delegatorAddress, delegateAddress }: { delegatorAddress: Address; delegateAddress: Address },\n ): Promise<void> {\n const inactive = await this.#delegationService.findInactiveDelegations(\n contractAddresses,\n delegatorAddress,\n delegateAddress,\n );\n if (inactive.size === 0) {\n return;\n }\n for (const error of inactive.values()) {\n throw error;\n }\n }\n}\n","import type { ZamaError } from \"./base\";\nimport { extractRevertErrorName } from \"./revert\";\nimport {\n AclPausedError,\n DelegationContractIsSelfError,\n DelegationCooldownError,\n DelegationDelegateCannotBeWildcardError,\n DelegationDelegateEqualsContractError,\n DelegationExpirationTooSoonError,\n DelegationExpiryUnchangedError,\n DelegationNotFoundError,\n DelegationSelfNotAllowedError,\n} from \"./delegation\";\n\n/** ACL error name -> typed SDK error mapping. */\nconst ACL_ERROR_MAP = {\n AlreadyDelegatedOrRevokedInSameBlock: (cause) =>\n new DelegationCooldownError(\n \"Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.\",\n { cause },\n ),\n SenderCannotBeContractAddress: (cause) =>\n new DelegationContractIsSelfError(\"The contract address cannot be the caller address.\", {\n cause,\n }),\n EnforcedPause: (cause) =>\n new AclPausedError(\n \"The ACL contract is paused. Delegation operations are temporarily disabled.\",\n { cause },\n ),\n SenderCannotBeDelegate: (cause) =>\n new DelegationSelfNotAllowedError(\"Cannot delegate to yourself (delegate === msg.sender).\", {\n cause,\n }),\n DelegateCannotBeContractAddress: (cause) =>\n new DelegationDelegateEqualsContractError(\n \"Delegate address cannot be the same as the contract address.\",\n { cause },\n ),\n DelegateCannotBeWildcard: (cause) =>\n new DelegationDelegateCannotBeWildcardError(\n \"Delegate address cannot be the wildcard address; it can only be used as the contract address.\",\n { cause },\n ),\n ExpirationDateBeforeOneHour: (cause) =>\n new DelegationExpirationTooSoonError(\"Expiration date must be at least 1 hour in the future.\", {\n cause,\n }),\n ExpirationDateAlreadySetToSameValue: (cause) =>\n new DelegationExpiryUnchangedError(\"The new expiration date is the same as the current one.\", {\n cause,\n }),\n NotDelegatedYet: (cause) =>\n new DelegationNotFoundError(\"Cannot revoke: no active delegation exists.\", { cause }),\n} satisfies Record<string, (cause: unknown) => ZamaError>;\n\nfunction isAclRevertName(name: string): name is keyof typeof ACL_ERROR_MAP {\n return Object.hasOwn(ACL_ERROR_MAP, name);\n}\n\n/**\n * Map known ACL Solidity revert error names to typed ZamaError subclasses.\n * Prefers viem's structured `error.cause.data.errorName` when available,\n * falling back to string-includes matching on the error message.\n * Returns `null` if the revert reason is not recognized.\n * @internal\n */\nexport function matchAclRevert(error: unknown, mappedCause: unknown): ZamaError | null {\n // Prefer structured error data from viem's ContractFunctionRevertedError\n const errorName = extractRevertErrorName(error);\n if (errorName && isAclRevertName(errorName)) {\n return ACL_ERROR_MAP[errorName](mappedCause);\n }\n\n // Fallback: string matching for non-viem RPC providers\n const message = error instanceof Error ? error.message : String(error);\n for (const [name, factory] of Object.entries(ACL_ERROR_MAP)) {\n if (message.includes(name)) {\n return factory(mappedCause);\n }\n }\n\n return null;\n}\n","import { getAddress, type Address } from \"viem\";\nimport {\n delegateForUserDecryptionContract,\n getDelegationExpiryContract,\n MAX_UINT64,\n revokeDelegationContract,\n WILDCARD_CONTRACT,\n} from \"../contracts\";\nimport {\n DelegationDelegateCannotBeWildcardError,\n DelegationDelegateEqualsContractError,\n DelegationExpirationTooSoonError,\n DelegationExpiredError,\n DelegationExpiryUnchangedError,\n DelegationNotFoundError,\n DelegationSelfNotAllowedError,\n TransactionRevertedError,\n} from \"../errors\";\nimport { matchAclRevert } from \"../errors/acl-revert\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport type { ChainRouter } from \"../chains/router\";\nimport type {\n GenericLogger,\n GenericProvider,\n GenericSigner,\n TransactionResult,\n WriteContractConfig,\n} from \"../types\";\nimport { submitTransaction } from \"../utils/submit-transaction\";\n\ntype AclTransactionOperation = Extract<\n TransactionOperation,\n \"delegateDecryption\" | \"revokeDelegation\"\n>;\n\n/** Delegation activity and expiry, resolved from the active contract or wildcard grant. */\nexport interface DelegationStatus {\n /** Whether the delegation is currently active (exists and not expired). */\n isActive: boolean;\n /** Unix timestamp (seconds) when the delegation expires; `0n` if none exists. */\n expiryTimestamp: bigint;\n}\n\n/** @internal */\nexport class DelegationService {\n readonly #router: ChainRouter;\n readonly #provider: GenericProvider;\n readonly #emitEvent: (input: ZamaSDKEventInput, tokenAddress?: Address) => void;\n readonly #logger: GenericLogger;\n\n constructor({\n provider,\n router,\n emitEvent = () => {},\n logger,\n }: {\n provider: GenericProvider;\n router: ChainRouter;\n logger: GenericLogger;\n emitEvent?: (input: ZamaSDKEventInput, tokenAddress?: Address) => void;\n }) {\n this.#provider = provider;\n this.#router = router;\n this.#logger = logger;\n this.#emitEvent = emitEvent;\n }\n\n async delegateDecryption(\n signer: GenericSigner,\n {\n contractAddress,\n delegateAddress,\n delegatorAddress,\n expirationDate,\n }: {\n contractAddress: Address;\n delegateAddress: Address;\n delegatorAddress: Address;\n expirationDate?: Date;\n },\n ): Promise<TransactionResult> {\n if (expirationDate && expirationDate.getTime() < Date.now() + 3600_000) {\n throw new DelegationExpirationTooSoonError(\n \"Expiration date must be at least 1 hour in the future\",\n );\n }\n\n const normalizedContract = getAddress(contractAddress);\n const normalizedDelegate = getAddress(delegateAddress);\n const normalizedDelegator = getAddress(delegatorAddress);\n\n if (normalizedDelegate === normalizedDelegator) {\n throw new DelegationSelfNotAllowedError(\n \"Cannot delegate to yourself (delegate === msg.sender).\",\n );\n }\n\n if (normalizedDelegate === getAddress(WILDCARD_CONTRACT)) {\n throw new DelegationDelegateCannotBeWildcardError(\n \"Delegate address cannot be the wildcard address; it can only be used as the contract address.\",\n );\n }\n\n if (normalizedDelegate === normalizedContract) {\n throw new DelegationDelegateEqualsContractError(\n `Delegate address cannot be the same as the contract address (${normalizedContract}).`,\n );\n }\n\n const acl = this.#router.relayer.chain.aclContractAddress;\n const expDate = expirationDate\n ? BigInt(Math.floor(expirationDate.getTime() / 1000))\n : MAX_UINT64;\n\n let currentExpiry: bigint;\n try {\n currentExpiry = await this.getDelegationExpiry({\n contractAddress: normalizedContract,\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n });\n } catch (error) {\n this.#logger.warn(\"delegateDecryption: pre-flight expiry check failed\", { error });\n currentExpiry = -1n;\n }\n if (currentExpiry === expDate) {\n throw new DelegationExpiryUnchangedError(\n `The new expiration date (${expDate}) is the same as the current one. No on-chain change needed.`,\n );\n }\n\n if (normalizedContract !== getAddress(WILDCARD_CONTRACT)) {\n await this.#warnIfWildcardAlreadyCoversDelegate({\n contractAddress: normalizedContract,\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n });\n }\n\n return this.#submitAclTransaction({\n operation: \"delegateDecryption\",\n signer,\n contractAddress: normalizedContract,\n config: delegateForUserDecryptionContract(\n acl,\n normalizedDelegate,\n normalizedContract,\n expDate,\n ),\n });\n }\n\n async revokeDelegation(\n signer: GenericSigner,\n {\n contractAddress,\n delegateAddress,\n delegatorAddress,\n }: { contractAddress: Address; delegateAddress: Address; delegatorAddress: Address },\n ): Promise<TransactionResult> {\n const normalizedContract = getAddress(contractAddress);\n const normalizedDelegate = getAddress(delegateAddress);\n const normalizedDelegator = getAddress(delegatorAddress);\n const acl = this.#router.relayer.chain.aclContractAddress;\n\n let currentExpiry: bigint;\n try {\n currentExpiry = await this.getDelegationExpiry({\n contractAddress: normalizedContract,\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n });\n } catch (error) {\n this.#logger.warn(\"revokeDelegation: pre-flight expiry check failed\", { error });\n currentExpiry = 1n;\n }\n if (currentExpiry === 0n) {\n throw new DelegationNotFoundError(\n `No active delegation found for delegate ${normalizedDelegate} on contract ${normalizedContract}.`,\n );\n }\n\n return this.#submitAclTransaction({\n operation: \"revokeDelegation\",\n signer,\n contractAddress: normalizedContract,\n config: revokeDelegationContract(acl, normalizedDelegate, normalizedContract),\n });\n }\n\n async isDelegated(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<boolean> {\n return (await this.getStatus(params)).isActive;\n }\n\n /**\n * Resolve activity and expiry, falling back to the delegate's {@link WILDCARD_CONTRACT}\n * grant when the per-contract row isn't active — the raw expiry getter is a per-contract\n * read, so a wildcard-only grant would otherwise read as \"no delegation\" for every contract.\n */\n async getStatus(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<DelegationStatus> {\n const normalizedContract = getAddress(params.contractAddress);\n const isWildcardQuery = normalizedContract === WILDCARD_CONTRACT;\n\n const [contractExpiry, wildcardExpiry] = await Promise.all([\n this.getDelegationExpiry(params),\n isWildcardQuery\n ? Promise.resolve(0n)\n : this.getDelegationExpiry({ ...params, contractAddress: WILDCARD_CONTRACT }),\n ]);\n\n const now =\n this.#needsBlockTimestamp(contractExpiry) || this.#needsBlockTimestamp(wildcardExpiry)\n ? await this.#provider.getBlockTimestamp()\n : undefined;\n\n const contractStatus = this.#resolveStatus(contractExpiry, now);\n if (contractStatus.isActive) {\n return contractStatus;\n }\n const wildcardStatus = this.#resolveStatus(wildcardExpiry, now);\n if (wildcardStatus.isActive) {\n return wildcardStatus;\n }\n return contractExpiry >= wildcardExpiry ? contractStatus : wildcardStatus;\n }\n\n /**\n * Advisory only — mixing wildcard and per-contract delegations to the same\n * delegate is valid on-chain, so this never blocks the write.\n */\n async #warnIfWildcardAlreadyCoversDelegate(params: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<void> {\n try {\n const { isActive } = await this.getStatus({ ...params, contractAddress: WILDCARD_CONTRACT });\n if (isActive) {\n this.#logger.warn(\n `delegateDecryption: ${params.delegateAddress} already holds an active wildcard ` +\n `delegation from ${params.delegatorAddress}; this grant for ${params.contractAddress} is redundant.`,\n );\n }\n } catch (error) {\n this.#logger.warn(\"delegateDecryption: wildcard redundancy check failed\", { error });\n }\n }\n\n #needsBlockTimestamp(expiryTimestamp: bigint): boolean {\n return expiryTimestamp !== 0n && expiryTimestamp !== MAX_UINT64;\n }\n\n #resolveStatus(expiryTimestamp: bigint, now: bigint | undefined): DelegationStatus {\n if (expiryTimestamp === 0n) {\n return { isActive: false, expiryTimestamp };\n }\n if (expiryTimestamp === MAX_UINT64) {\n return { isActive: true, expiryTimestamp };\n }\n return { isActive: now !== undefined && expiryTimestamp > now, expiryTimestamp };\n }\n\n async getDelegationExpiry({\n contractAddress,\n delegatorAddress,\n delegateAddress,\n }: {\n contractAddress: Address;\n delegatorAddress: Address;\n delegateAddress: Address;\n }): Promise<bigint> {\n const acl = this.#router.relayer.chain.aclContractAddress;\n return this.#provider.readContract(\n getDelegationExpiryContract(\n acl,\n getAddress(delegatorAddress),\n getAddress(delegateAddress),\n getAddress(contractAddress),\n ),\n );\n }\n\n async #submitAclTransaction({\n operation,\n signer,\n contractAddress,\n config,\n }: {\n operation: AclTransactionOperation;\n signer: GenericSigner;\n contractAddress: Address;\n config: WriteContractConfig;\n }): Promise<TransactionResult> {\n try {\n return await submitTransaction({\n operation,\n signer,\n provider: this.#provider,\n config,\n emit: (input) => this.#emitEvent(input, contractAddress),\n logger: this.#logger,\n });\n } catch (error) {\n this.#throwAclRevertIfMatched(error);\n throw error;\n }\n }\n\n #throwAclRevertIfMatched(error: unknown): void {\n if (!(error instanceof TransactionRevertedError)) {\n return;\n }\n const mapped = matchAclRevert(error.cause ?? error, error);\n if (mapped) {\n throw mapped;\n }\n }\n\n async findInactiveDelegations(\n contractAddresses: readonly Address[],\n delegatorAddress: Address,\n delegateAddress: Address,\n ): Promise<Map<Address, DelegationNotFoundError | DelegationExpiredError>> {\n const inactive = new Map<Address, DelegationNotFoundError | DelegationExpiredError>();\n await Promise.all(\n contractAddresses.map(async (contractAddress) => {\n try {\n await this.assertDelegationActive(contractAddress, delegatorAddress, delegateAddress);\n } catch (error) {\n if (error instanceof DelegationNotFoundError || error instanceof DelegationExpiredError) {\n const normalizedContract = getAddress(contractAddress);\n inactive.set(normalizedContract, error);\n return;\n }\n throw error;\n }\n }),\n );\n return inactive;\n }\n\n async assertDelegationActive(\n contractAddress: Address,\n delegatorAddress: Address,\n delegateAddress: Address,\n ): Promise<void> {\n const normalizedContract = getAddress(contractAddress);\n const normalizedDelegator = getAddress(delegatorAddress);\n const normalizedDelegate = getAddress(delegateAddress);\n const { isActive, expiryTimestamp } = await this.getStatus({\n contractAddress: normalizedContract,\n delegatorAddress: normalizedDelegator,\n delegateAddress: normalizedDelegate,\n });\n if (isActive) {\n return;\n }\n if (expiryTimestamp === 0n) {\n throw new DelegationNotFoundError(\n `No active delegation from ${normalizedDelegator} to ${normalizedDelegate} for ${normalizedContract}`,\n );\n }\n throw new DelegationExpiredError(\n `Delegation from ${normalizedDelegator} to ${normalizedDelegate} for ${normalizedContract} has expired`,\n );\n }\n}\n","import { getAddress } from \"viem\";\nimport type { ChainRouter } from \"../chains/router\";\nimport { wrapEncryptError } from \"../errors\";\nimport type { ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { ZamaSDKEvents } from \"../events/sdk-events\";\nimport type { EncryptParams, EncryptResult, FhevmRelayerOptions } from \"../relayer/types\";\nimport { toError } from \"../utils\";\n\nexport class EncryptionService {\n readonly #router: ChainRouter;\n readonly #emitEvent: (\n input: ZamaSDKEventInput,\n tokenAddress?: EncryptParams[\"contractAddress\"],\n ) => void;\n\n constructor({\n router,\n emitEvent,\n }: {\n router: ChainRouter;\n emitEvent: (input: ZamaSDKEventInput, tokenAddress?: EncryptParams[\"contractAddress\"]) => void;\n }) {\n this.#router = router;\n this.#emitEvent = emitEvent;\n }\n\n async encryptValues(\n params: EncryptParams,\n options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">,\n ): Promise<EncryptResult> {\n const t0 = Date.now();\n const normalizedContractAddress = getAddress(params.contractAddress);\n try {\n this.#emitEvent({ type: ZamaSDKEvents.EncryptStart }, normalizedContractAddress);\n const result = await this.#router.relayer.encryptValues({ ...params, options });\n this.#emitEvent(\n { type: ZamaSDKEvents.EncryptEnd, durationMs: Date.now() - t0 },\n normalizedContractAddress,\n );\n return result;\n } catch (error) {\n this.#emitEvent(\n { type: ZamaSDKEvents.EncryptError, error: toError(error), durationMs: Date.now() - t0 },\n normalizedContractAddress,\n );\n throw wrapEncryptError(error, \"Encryption failed\");\n }\n }\n}\n","import type { CredentialService } from \"../credentials/credential-service\";\nimport type { ChainRouter } from \"../chains/router\";\nimport type {\n GenericLogger,\n GenericSigner,\n WalletAccountChange,\n WalletAccountListener,\n} from \"../types\";\nimport { swallow } from \"../utils\";\nimport type { CachingService } from \"./caching-service\";\n\nexport type LifecycleServiceOptions = {\n signer?: GenericSigner;\n router: ChainRouter;\n cachingService: CachingService;\n credentialService?: CredentialService;\n logger: GenericLogger;\n};\n\n/**\n * Owns signer-lifecycle wiring for {@link ZamaSDK}: subscribes to the signer's\n * wallet-account store on construction, runs the SDK-side cleanup (credential\n * rotation, decrypt-cache invalidation, relayer chain switch) on every change,\n * then fans out to external listeners. Unsubscribes on {@link dispose}.\n *\n * @internal — consumed by ZamaSDK; not part of the public surface.\n */\nexport class LifecycleService {\n readonly #signer: GenericSigner | undefined;\n readonly #router: ChainRouter;\n readonly #cachingService: CachingService;\n readonly #credentialService: CredentialService | undefined;\n readonly #logger: GenericLogger;\n readonly #walletAccountListeners = new Set<WalletAccountListener>();\n #unsubscribeSigner?: () => void;\n\n constructor(opts: LifecycleServiceOptions) {\n this.#signer = opts.signer;\n this.#router = opts.router;\n this.#cachingService = opts.cachingService;\n this.#credentialService = opts.credentialService;\n this.#logger = opts.logger;\n if (this.#signer) {\n this.#unsubscribeSigner = this.#signer.walletAccount.subscribe((change) => {\n this.#handleWalletAccountChange(change).catch((error) => {\n this.#logger.warn(\"wallet account handler failed\", { error });\n });\n });\n }\n }\n\n onWalletAccountChange(listener: WalletAccountListener): () => void {\n this.#walletAccountListeners.add(listener);\n return () => {\n this.#walletAccountListeners.delete(listener);\n };\n }\n\n dispose(): void {\n this.#unsubscribeSigner?.();\n this.#unsubscribeSigner = undefined;\n this.#walletAccountListeners.clear();\n }\n\n async #handleWalletAccountChange(change: WalletAccountChange): Promise<void> {\n const prev = change.previous;\n const next = change.next;\n // switchChain runs first so credential cleanup, decrypt-cache invalidation,\n // and external listeners observe the router on next.chainId. Downstream\n // keypair warming (driven by listeners — see ZamaProvider) therefore\n // dispatches against the wallet chain rather than chains[0]. Switching to a\n // chain with no configured backend does not throw here — the router tracks\n // it and the next relayer op surfaces a ConfigurationError — so `swallow`\n // is defensive only. It suspends one microtask for error containment, not\n // for I/O; ChainRouter.switchChain is synchronous.\n const nextChainId = next?.chainId;\n if (nextChainId !== undefined) {\n await swallow(\n \"switch relayer chain\",\n () => this.#router.switchChain(nextChainId),\n this.#logger,\n );\n }\n const credentialService = this.#credentialService;\n if (credentialService) {\n await swallow(\n \"credential wallet account change\",\n () => credentialService.handleWalletAccountChange(prev, next),\n this.#logger,\n );\n }\n if (prev) {\n await swallow(\n \"clear decrypt cache\",\n () => this.#cachingService.clearForRequester(prev.address),\n this.#logger,\n );\n }\n await Promise.all(\n Array.from(this.#walletAccountListeners, (listener) =>\n swallow(\"wallet account listener\", () => listener(change), this.#logger),\n ),\n );\n }\n}\n","import { size } from \"viem\";\nimport { z } from \"zod/mini\";\nimport type {\n ApproveUnderlyingRequest,\n ConfidentialTransferFromRequest,\n ConfidentialTransferRequest,\n DelegateDecryptionRequest,\n FinalizeUnwrapRequest,\n PrepareOptions,\n PrepareTransactionRequest,\n RevokeDelegationRequest,\n SetOperatorRequest,\n TransferAndCallRequest,\n UnwrapAllRequest,\n UnwrapRequest,\n WrapRequest,\n WriteContractConfig,\n} from \"../types\";\nimport { checksummedAddress, hex, unixSeconds } from \"./primitives\";\n\n/**\n * {@link ConfidentialTransferRequest} schema.\n * @internal\n */\nexport const confidentialTransferRequest = z.object({\n kind: z.literal(\"ConfidentialTransfer\"),\n from: checksummedAddress,\n token: checksummedAddress,\n to: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<ConfidentialTransferRequest>;\n\n/**\n * {@link ConfidentialTransferFromRequest} schema.\n * @internal\n */\nexport const confidentialTransferFromRequest = z.object({\n kind: z.literal(\"ConfidentialTransferFrom\"),\n from: checksummedAddress,\n token: checksummedAddress,\n owner: checksummedAddress,\n to: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<ConfidentialTransferFromRequest>;\n\n/**\n * {@link SetOperatorRequest} schema. `until` is a required unix timestamp\n * (seconds); pass `0 < until < now` to revoke.\n * @internal\n */\nexport const setOperatorRequest = z.object({\n kind: z.literal(\"SetOperator\"),\n from: checksummedAddress,\n token: checksummedAddress,\n operator: checksummedAddress,\n until: unixSeconds,\n}) satisfies z.ZodMiniType<SetOperatorRequest>;\n\n/**\n * {@link UnwrapRequest} schema.\n * @internal\n */\nexport const unwrapRequest = z.object({\n kind: z.literal(\"Unwrap\"),\n from: checksummedAddress,\n token: checksummedAddress,\n to: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<UnwrapRequest>;\n\n/**\n * {@link UnwrapAllRequest} schema.\n * @internal\n */\nexport const unwrapAllRequest = z.object({\n kind: z.literal(\"UnwrapAll\"),\n from: checksummedAddress,\n token: checksummedAddress,\n to: checksummedAddress,\n}) satisfies z.ZodMiniType<UnwrapAllRequest>;\n\n/**\n * {@link FinalizeUnwrapRequest} schema.\n * @internal\n */\nexport const finalizeUnwrapRequest = z.object({\n kind: z.literal(\"FinalizeUnwrap\"),\n from: checksummedAddress,\n wrapper: checksummedAddress,\n unwrapRequestIdOrAmount: hex,\n}) satisfies z.ZodMiniType<FinalizeUnwrapRequest>;\n\n/**\n * {@link ApproveUnderlyingRequest} schema.\n * @internal\n */\nexport const approveUnderlyingRequest = z.object({\n kind: z.literal(\"ApproveUnderlying\"),\n from: checksummedAddress,\n underlying: checksummedAddress,\n spender: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<ApproveUnderlyingRequest>;\n\n/**\n * {@link WrapRequest} schema.\n * @internal\n */\nexport const wrapRequest = z.object({\n kind: z.literal(\"Wrap\"),\n from: checksummedAddress,\n wrapper: checksummedAddress,\n to: checksummedAddress,\n amount: z.bigint(),\n}) satisfies z.ZodMiniType<WrapRequest>;\n\n/**\n * `TransferAndCall` recipient payload: `0x` (self-shield to the sender) or a\n * raw 20-byte address. The wrapper's receiver hook does\n * `to = data.length < 20 ? from : address(bytes20(data))`, so any other\n * non-empty value (e.g. a 32-byte ABI-encoded address) is truncated to its\n * first 20 bytes — minting the shielded funds to a garbage address. Reject\n * those rather than let the funds go astray; omit for a self-shield.\n */\nconst recipientData = hex.check(\n z.refine(\n (data) => data === \"0x\" || size(data) === 20,\n 'TransferAndCall.recipientData must be \"0x\" (self-shield to the sender) or a raw 20-byte address, ' +\n \"not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address\",\n ),\n);\n\n/**\n * {@link TransferAndCallRequest} schema. `recipientData` is 20 raw bytes or `0x`.\n * @internal\n */\nexport const transferAndCallRequest = z.object({\n kind: z.literal(\"TransferAndCall\"),\n from: checksummedAddress,\n underlying: checksummedAddress,\n wrapper: checksummedAddress,\n amount: z.bigint(),\n recipientData: z.optional(recipientData),\n}) satisfies z.ZodMiniType<TransferAndCallRequest>;\n\n/**\n * {@link DelegateDecryptionRequest} schema. Input takes an optional\n * `expirationDate` (a `Date`); the parsed output is the on-chain `uint64`\n * expiry — seconds since epoch, or `MAX_UINT64` (\"permanent\") when omitted —\n * so callers never hand-roll the encoding.\n *\n * The ≥1h-in-the-future expiry check and the self/contract guards live in the\n * `#buildDelegateDecryption` builder (they throw domain-specific delegation\n * errors this schema can't).\n * @internal\n */\nexport const delegateDecryptionRequest = z.object({\n kind: z.literal(\"DelegateDecryption\"),\n from: checksummedAddress,\n contractAddress: checksummedAddress,\n delegateAddress: checksummedAddress,\n expirationDate: z.optional(z.date()),\n}) satisfies z.ZodMiniType<DelegateDecryptionRequest>;\n\n/**\n * {@link RevokeDelegationRequest} schema.\n * @internal\n */\nexport const revokeDelegationRequest = z.object({\n kind: z.literal(\"RevokeDelegation\"),\n from: checksummedAddress,\n contractAddress: checksummedAddress,\n delegateAddress: checksummedAddress,\n}) satisfies z.ZodMiniType<RevokeDelegationRequest>;\n\n/**\n * Discriminated union (on `kind`) of every offline `prepare` request. Backs\n * both the {@link PrepareTransactionRequest} type and the runtime validation\n * in `OfflineService.prepare`.\n * @internal\n */\nexport const prepareTransactionRequest = z.discriminatedUnion(\"kind\", [\n confidentialTransferRequest,\n confidentialTransferFromRequest,\n setOperatorRequest,\n unwrapRequest,\n unwrapAllRequest,\n finalizeUnwrapRequest,\n approveUnderlyingRequest,\n wrapRequest,\n transferAndCallRequest,\n delegateDecryptionRequest,\n revokeDelegationRequest,\n]) satisfies z.ZodMiniType<PrepareTransactionRequest>;\n\n/**\n * {@link PrepareFees} schema. `maxFeePerGas` and `maxPriorityFeePerGas` live in\n * one object so they can only be supplied together — pinning a cap (the total\n * fee) while the tip is estimated can produce a tip above the cap and fail\n * serialization. Both legs are validated as `bigint` so a JS caller (no\n * compiler) can't slip a `number` into the frozen, signed payload.\n * @internal\n */\nexport const fees = z.strictObject({ maxFeePerGas: z.bigint(), maxPriorityFeePerGas: z.bigint() });\n\n/**\n * {@link PrepareOptions} schema. All fields are optional; omitted ones fall\n * back to the provider's live chain-state defaults.\n * @internal\n */\nexport const prepareOptions = z.object({\n nonce: z.optional(z.int().check(z.nonnegative())),\n gasLimit: z.optional(z.bigint()),\n fees: z.optional(fees),\n}) satisfies z.ZodMiniType<PrepareOptions>;\n\n/**\n * `WriteContractConfig` schema. `abi` and `args` are validated only as\n * arrays — their element shapes are the ABI-typed `TAbi`/`TFunctionName`\n * generics the runtime can't check — so this guards the structural envelope\n * (address, function name, the two arrays, optional `value`/`gas`) a provider's\n * tx-builder consumes.\n * @internal\n */\nexport const writeContractConfig = z.object({\n address: checksummedAddress,\n abi: z.array(z.unknown()),\n functionName: z.string(),\n args: z.array(z.unknown()),\n value: z.optional(z.bigint()),\n gas: z.optional(z.bigint()),\n}) satisfies z.ZodMiniType<WriteContractConfig>;\n\n/**\n * Schema for the argument object of `GenericProvider.prepareTransaction`:\n * the originating `from` wallet, the write-contract `calldata`, and the\n * optional chain-state overrides. Extends {@link prepareOptions} so the\n * `nonce`/`gasLimit`/`fees` legs stay in lockstep with the per-call overrides.\n *\n * `from` is EIP-55 checksummed on parse (the custodian keys off it), so the\n * validated output can flow straight into the prepared handoff.\n * @internal\n */\nexport const prepareTransactionParams = z.extend(prepareOptions, {\n from: checksummedAddress,\n calldata: writeContractConfig,\n});\n","import type { Address } from \"viem\";\nimport type { ChainRouter } from \"../chains/router\";\nimport {\n approveContract,\n confidentialBalanceOfContract,\n confidentialTransferContract,\n confidentialTransferFromContract,\n delegateForUserDecryptionContract,\n finalizeUnwrapContract,\n MAX_UINT64,\n revokeDelegationContract,\n setOperatorContract,\n transferAndCallContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n} from \"../contracts\";\nimport {\n ConfigurationError,\n DelegationDelegateEqualsContractError,\n DelegationExpirationTooSoonError,\n DelegationSelfNotAllowedError,\n EncryptionFailedError,\n wrapDecryptError,\n} from \"../errors\";\nimport type { ZamaSDKEventInput } from \"../events/sdk-events\";\nimport {\n approveUnderlyingRequest,\n confidentialTransferFromRequest,\n confidentialTransferRequest,\n delegateDecryptionRequest,\n finalizeUnwrapRequest,\n prepareOptions,\n prepareTransactionParams,\n revokeDelegationRequest,\n setOperatorRequest,\n transferAndCallRequest,\n unwrapAllRequest,\n unwrapRequest,\n wrapRequest,\n} from \"../schemas/offline\";\nimport type {\n ApproveUnderlyingRequest,\n ConfidentialTransferFromRequest,\n ConfidentialTransferRequest,\n DelegateDecryptionRequest,\n FinalizeUnwrapRequest,\n GenericProvider,\n PreparedFor,\n PrepareOptions,\n PrepareTransactionRequest,\n RevokeDelegationRequest,\n SetOperatorRequest,\n TransactionKind,\n TransferAndCallRequest,\n UnwrapAllRequest,\n UnwrapRequest,\n WrapRequest,\n} from \"../types\";\nimport { assertBigint } from \"../utils/assertions\";\nimport { parseSchema } from \"../validation\";\nimport type { EncryptionService } from \"./encryption-service\";\n\n/**\n * Configuration for {@link OfflineService}.\n *\n * @internal\n */\nexport interface OfflineServiceConfig {\n readonly provider: GenericProvider;\n readonly router: ChainRouter;\n readonly encryption: EncryptionService;\n readonly emitEvent: (input: ZamaSDKEventInput, tokenAddress?: Address) => void;\n}\n\n/**\n * Offline-signing pipeline. Builds an RLP-encoded unsigned transaction that\n * the caller signs **and** publishes out-of-process — for institutional\n * custody, HSM ceremonies, and policy-engine workflows where signing cannot\n * happen synchronously in a single Promise.\n *\n * Atomic call sites ({@link Token.confidentialTransfer}, etc.) keep their\n * `signer.writeContract` path; this service is the parallel route where the\n * caller signs `prepared.unsignedTx` externally (HSM, custody API, policy\n * engine) and publishes the signed bytes through its own channel.\n *\n * Owned by {@link ZamaSDK}.\n *\n * @internal\n */\nexport class OfflineService {\n readonly #provider: GenericProvider;\n readonly #router: ChainRouter;\n readonly #encryption: EncryptionService;\n\n constructor(config: OfflineServiceConfig) {\n this.#provider = config.provider;\n this.#router = config.router;\n this.#encryption = config.encryption;\n }\n\n // ── prepare ─────────────────────────────────────────────────────────────\n\n /**\n * Build the offline-signing payload for the given transaction request:\n * an RLP-encoded unsigned transaction the caller signs externally (an HSM,\n * custody API, or any out-of-process signer) and publishes through its own\n * channel.\n *\n * Decryption permits are not transactions — acquire them via\n * `sdk.permits.grantPermit`, which signs with the configured signer\n * (including an out-of-process custody signer).\n */\n async prepare<K extends TransactionKind>(\n request: Extract<PrepareTransactionRequest, { kind: K }>,\n options?: PrepareOptions,\n ): Promise<PreparedFor<K>> {\n if (options) {\n options = parseSchema(prepareOptions, options);\n }\n\n // The prepared tx's contract addresses and encrypted inputs are bound to\n // the SDK's configured chain; if the provider is on a different chain it\n // would bake that chain's id into a tx carrying wrong-chain addresses.\n // No signer here (offline is signer-less), so guard router vs provider\n // directly rather than through requireChainAlignment.\n const providerChainId = await this.#provider.getChainId();\n const expectedChainId = this.#router.chain.id;\n if (providerChainId !== expectedChainId) {\n throw new ConfigurationError(\n `Offline.prepare: provider is on chain ${providerChainId} but the SDK is configured for chain ${expectedChainId}. ` +\n `The prepared transaction's contract addresses and encrypted inputs are bound to chain ${expectedChainId} — point the provider at the same chain.`,\n );\n }\n\n const calldata = await this.#buildCalldata(request);\n const params = {\n calldata,\n from: request.from,\n nonce: options?.nonce,\n gasLimit: options?.gasLimit,\n fees: options?.fees,\n };\n const parsed = parseSchema(prepareTransactionParams, params);\n const unsignedTx = await this.#provider.prepareTransaction(parsed);\n return { kind: request.kind, unsignedTx, from: parsed.from } satisfies PreparedFor<K>;\n }\n\n // ── internals ──────────────────────────────────────────────────────────\n\n async #buildCalldata(\n request: PrepareTransactionRequest,\n ): Promise<{\n readonly address: Address;\n readonly abi: readonly unknown[];\n readonly functionName: string;\n readonly args: readonly unknown[];\n }> {\n switch (request.kind) {\n case \"ConfidentialTransfer\":\n return this.#buildConfidentialTransfer(request);\n case \"ConfidentialTransferFrom\":\n return this.#buildConfidentialTransferFrom(request);\n case \"SetOperator\":\n return this.#buildSetOperator(request);\n case \"Unwrap\":\n return this.#buildUnwrap(request);\n case \"UnwrapAll\":\n return this.#buildUnwrapAll(request);\n case \"FinalizeUnwrap\":\n return this.#buildFinalizeUnwrap(request);\n case \"ApproveUnderlying\":\n return this.#buildApproveUnderlying(request);\n case \"Wrap\":\n return this.#buildWrap(request);\n case \"TransferAndCall\":\n return this.#buildTransferAndCall(request);\n case \"DelegateDecryption\":\n return this.#buildDelegateDecryption(request);\n case \"RevokeDelegation\":\n return this.#buildRevokeDelegation(request);\n default: {\n const unhandled: { kind: string } = request;\n throw new ConfigurationError(\n `OfflineService.prepare: unsupported transaction kind '${unhandled.kind}'.`,\n );\n }\n }\n }\n\n async #buildConfidentialTransfer(\n request: ConfidentialTransferRequest,\n ): Promise<ReturnType<typeof confidentialTransferContract>> {\n request = parseSchema(confidentialTransferRequest, request);\n const { encryptedValues, inputProof } = await this.#encryption.encryptValues({\n values: [{ value: request.amount, type: \"euint64\" }],\n contractAddress: request.token,\n userAddress: request.from,\n });\n const handle = encryptedValues[0];\n if (!handle) {\n throw new EncryptionFailedError(\"Encryption returned no handles for ConfidentialTransfer\");\n }\n return confidentialTransferContract(request.token, request.to, handle, inputProof);\n }\n\n async #buildConfidentialTransferFrom(\n request: ConfidentialTransferFromRequest,\n ): Promise<ReturnType<typeof confidentialTransferFromContract>> {\n request = parseSchema(confidentialTransferFromRequest, request);\n // The encrypted input's proof binds to the tx sender (fhevm verifies it\n // against `msg.sender`), which for `transferFrom` is the operator == the\n // `from` wallet that signs and broadcasts — not the `owner` being debited.\n const { encryptedValues, inputProof } = await this.#encryption.encryptValues({\n values: [{ value: request.amount, type: \"euint64\" }],\n contractAddress: request.token,\n userAddress: request.from,\n });\n const handle = encryptedValues[0];\n if (!handle) {\n throw new EncryptionFailedError(\n \"Encryption returned no handles for ConfidentialTransferFrom\",\n );\n }\n return confidentialTransferFromContract(\n request.token,\n request.owner,\n request.to,\n handle,\n inputProof,\n );\n }\n\n #buildSetOperator(request: SetOperatorRequest): ReturnType<typeof setOperatorContract> {\n request = parseSchema(setOperatorRequest, request);\n return setOperatorContract(request.token, request.operator, request.until);\n }\n\n async #buildUnwrap(request: UnwrapRequest): Promise<ReturnType<typeof unwrapContract>> {\n request = parseSchema(unwrapRequest, request);\n const { encryptedValues, inputProof } = await this.#encryption.encryptValues({\n values: [{ value: request.amount, type: \"euint64\" }],\n contractAddress: request.token,\n userAddress: request.from,\n });\n const handle = encryptedValues[0];\n if (!handle) {\n throw new EncryptionFailedError(\"Encryption returned no handles for Unwrap\");\n }\n return unwrapContract(request.token, request.from, request.to, handle, inputProof);\n }\n\n async #buildUnwrapAll(\n request: UnwrapAllRequest,\n ): Promise<ReturnType<typeof unwrapFromBalanceContract>> {\n request = parseSchema(unwrapAllRequest, request);\n const balanceHandle = await this.#provider.readContract(\n confidentialBalanceOfContract(request.token, request.from),\n );\n return unwrapFromBalanceContract(request.token, request.from, request.to, balanceHandle);\n }\n\n async #buildFinalizeUnwrap(\n request: FinalizeUnwrapRequest,\n ): Promise<ReturnType<typeof finalizeUnwrapContract>> {\n request = parseSchema(finalizeUnwrapRequest, request);\n const decrypted = await this.#router.relayer\n .decryptPublicValuesWithSignatures({ encryptedValues: [request.unwrapRequestIdOrAmount] })\n .catch((error: unknown) => {\n throw wrapDecryptError(error, \"Public decryption failed during FinalizeUnwrap\");\n });\n const raw = decrypted.clearValues[0]?.value;\n assertBigint(raw, \"FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue\");\n return finalizeUnwrapContract(\n request.wrapper,\n request.unwrapRequestIdOrAmount,\n raw,\n decrypted.checkSignaturesArgs.decryptionProof,\n );\n }\n\n #buildApproveUnderlying(request: ApproveUnderlyingRequest): ReturnType<typeof approveContract> {\n request = parseSchema(approveUnderlyingRequest, request);\n return approveContract(request.underlying, request.spender, request.amount);\n }\n\n #buildWrap(request: WrapRequest): ReturnType<typeof wrapContract> {\n request = parseSchema(wrapRequest, request);\n return wrapContract(request.wrapper, request.to, request.amount);\n }\n\n #buildTransferAndCall(\n request: TransferAndCallRequest,\n ): ReturnType<typeof transferAndCallContract> {\n request = parseSchema(transferAndCallRequest, request);\n return transferAndCallContract(\n request.underlying,\n request.wrapper,\n request.amount,\n request.recipientData,\n );\n }\n\n #buildDelegateDecryption(\n request: DelegateDecryptionRequest,\n ): ReturnType<typeof delegateForUserDecryptionContract> {\n request = parseSchema(delegateDecryptionRequest, request);\n // Expiry ≥1h out: an expiry under 1h lands already-expired (or nearly so),\n // and the offline payload is signed/broadcast later, eating into that\n // margin further. Checked against the pre-parse `Date` (the schema\n // transforms it into the on-chain uint64 below).\n if (request.expirationDate && request.expirationDate.getTime() < Date.now() + 3_600_000) {\n throw new DelegationExpirationTooSoonError(\n \"Expiration date must be at least 1 hour in the future\",\n );\n }\n if (request.delegateAddress === request.from) {\n throw new DelegationSelfNotAllowedError(\n \"Cannot delegate to yourself (delegate === msg.sender).\",\n );\n }\n if (request.delegateAddress === request.contractAddress) {\n throw new DelegationDelegateEqualsContractError(\n `Delegate address cannot be the same as the contract address (${request.contractAddress}).`,\n );\n }\n const expirationDate = request.expirationDate\n ? BigInt(Math.floor(request.expirationDate.getTime() / 1000))\n : MAX_UINT64;\n return delegateForUserDecryptionContract(\n this.#router.chain.aclContractAddress,\n request.delegateAddress,\n request.contractAddress,\n expirationDate,\n );\n }\n\n #buildRevokeDelegation(\n request: RevokeDelegationRequest,\n ): ReturnType<typeof revokeDelegationContract> {\n request = parseSchema(revokeDelegationRequest, request);\n return revokeDelegationContract(\n this.#router.chain.aclContractAddress,\n request.delegateAddress,\n request.contractAddress,\n );\n }\n}\n","import type { Address } from \"viem\";\nimport type { ChainRouter } from \"./chains/router\";\nimport type { ZamaConfig } from \"./config/types\";\nimport { CredentialService } from \"./credentials/credential-service\";\nimport { DerivationSecretHolder } from \"./credentials/keypair-wrapping\";\nimport { DerivationSecretSchema } from \"./credentials/schemas\";\nimport { ConfigurationError } from \"./errors\";\nimport type { ZamaSDKEvent, ZamaSDKEventInput, ZamaSDKEventListener } from \"./events/sdk-events\";\nimport { Decryption } from \"./namespaces/decryption\";\nimport { Delegations } from \"./namespaces/delegations\";\nimport { Offline } from \"./namespaces/offline\";\nimport { Permits } from \"./namespaces/permits\";\nimport type { EncryptParams, FhevmRelayerOptions, RelayerSDK } from \"./relayer/types\";\nimport { CachingService } from \"./services/caching-service\";\nimport { DecryptionService } from \"./services/decryption-service\";\nimport { DelegationService } from \"./services/delegation-service\";\nimport { EncryptionService } from \"./services/encryption-service\";\nimport { LifecycleService } from \"./services/lifecycle-service\";\nimport { OfflineService } from \"./services/offline-service\";\nimport { Token } from \"./token/token\";\nimport { WrappedToken } from \"./token/wrapped-token\";\nimport type {\n GenericLogger,\n GenericProvider,\n GenericSigner,\n GenericStorage,\n WalletAccountListener,\n} from \"./types\";\nimport { parseSchema } from \"./validation\";\nimport { WrappersRegistry } from \"./wrappers-registry\";\n\n/** Instance-level options that are deliberately not part of the shareable config object. */\nexport interface ZamaSDKOptions {\n /**\n * Encrypts the transport key pair's private half at rest. Headless environments only\n * (CLI tools, servers, agents); the constructor rejects it in browser contexts. Supply\n * at least 32 random bytes, or a string of at least 64 characters, from a CSPRNG or\n * secrets manager. The SDK copies a Uint8Array secret and zeroizes its own copy after\n * key import; it never touches your buffer, so zeroize yours after construction.\n * The SDK never persists or exposes this value. Omit for the default:\n * plaintext at rest, security delegated to the storage backend.\n */\n transportKeyPairDerivationSecret?: string | Uint8Array;\n}\n\n/**\n * Omitting the option means cleartext-at-rest by choice; passing it as `undefined` means the\n * caller asked for wrapping and the value went missing, so it must fail instead of downgrading.\n */\nfunction assertDerivationSecretNotUnset(options: ZamaSDKOptions): void {\n if (\n !Object.hasOwn(options, \"transportKeyPairDerivationSecret\") ||\n options.transportKeyPairDerivationSecret !== undefined\n ) {\n return;\n }\n throw new ConfigurationError(\n \"transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.\",\n );\n}\n\n/**\n * Wrapping only helps where no platform keystore protects the store, which is the headless\n * case. `importScripts` catches a browser worker, where `window` and `document` are absent.\n */\nfunction assertDerivationSecretHeadless(secret: string | Uint8Array | undefined): void {\n if (secret === undefined) {\n return;\n }\n const { importScripts } = globalThis as { importScripts?: unknown };\n const headless =\n typeof window === \"undefined\" &&\n typeof document === \"undefined\" &&\n typeof importScripts !== \"function\";\n if (headless) {\n return;\n }\n throw new ConfigurationError(\n \"transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.\",\n );\n}\n\n/**\n * Copies a `Uint8Array` secret so the holder only ever zeroizes the SDK's own buffer, and\n * a caller zeroizing theirs cannot corrupt later wraps. Strings are immutable, so no copy.\n */\nfunction derivationSecretHolder(\n secret: string | Uint8Array | undefined,\n): DerivationSecretHolder | undefined {\n if (secret === undefined) {\n return undefined;\n }\n const parsed = parseSchema(DerivationSecretSchema, secret);\n return new DerivationSecretHolder(typeof parsed === \"string\" ? parsed : new Uint8Array(parsed));\n}\n\n/**\n * ZamaSDK — composes a RelayerSDK with contract abstraction.\n *\n * Exposes domain namespaces for permits, delegations, decryption, offline\n * signing, and tokens, plus an unchanged registry, a top-level `encrypt`, and\n * lifecycle methods. Internal `*Service` classes do the work; the namespace\n * classes own SDK-level guards (chain alignment, signer requirement, event\n * emission).\n */\nexport class ZamaSDK {\n readonly #router: ChainRouter;\n /** Read-only chain access used for all contract reads. */\n readonly provider: GenericProvider;\n /** Wallet signer used for write operations, or `undefined` when the SDK is read-only. */\n readonly signer: GenericSigner | undefined;\n /** Storage for cached permits and transport key pairs. */\n readonly storage: GenericStorage;\n /**\n * A {@link WrappersRegistry} instance auto-configured for the current chain.\n * Uses built-in defaults from chain configs, and the SDK's `registryTTL` if configured.\n */\n readonly registry: WrappersRegistry;\n /** Permit and keypair management. */\n readonly permits: Permits;\n /** On-chain decryption-delegation management. */\n readonly delegations: Delegations;\n /** FHE decryption (user, delegated user, public). */\n readonly decryption: Decryption;\n /** Offline-signing pipeline: `prepare` builds an unsigned tx the caller signs and broadcasts out-of-process — for HSM, policy-engine, and cross-process custody workflows. */\n readonly offline: Offline;\n readonly #registryTTL: number;\n readonly #registryAddresses: Record<number, Address>;\n readonly #onEvent: ZamaSDKEventListener;\n readonly #logger: GenericLogger;\n readonly #cachingService: CachingService;\n readonly #lifecycleService: LifecycleService;\n readonly #encryptionService: EncryptionService;\n readonly #decryptionService: DecryptionService | undefined;\n readonly #credentialService: CredentialService;\n readonly #delegationService: DelegationService;\n readonly #offlineService: OfflineService;\n\n constructor(config: ZamaConfig, options: ZamaSDKOptions = {}) {\n assertDerivationSecretNotUnset(options);\n assertDerivationSecretHeadless(options.transportKeyPairDerivationSecret);\n // Constructor-local on purpose: neither the raw secret nor the holder may become a field.\n const derivationSecret = derivationSecretHolder(options.transportKeyPairDerivationSecret);\n\n this.#router = config.router;\n this.provider = config.provider;\n this.signer = config.signer;\n this.storage = config.storage;\n this.#onEvent = config.onEvent ?? function () {};\n this.#logger = config.logger;\n this.#cachingService = new CachingService(config.storage, this.#logger);\n this.#delegationService = new DelegationService({\n provider: this.provider,\n router: config.router,\n emitEvent: this.emitEvent.bind(this),\n logger: this.#logger,\n });\n\n const registryAddresses: Record<number, Address> = {};\n for (const chain of config.chains) {\n if (chain.registryAddress) {\n registryAddresses[chain.id] = chain.registryAddress;\n }\n }\n this.registry = new WrappersRegistry({\n provider: this.provider,\n registryAddresses,\n registryTTL: config.registryTTL,\n });\n this.#registryAddresses = registryAddresses;\n this.#registryTTL = config.registryTTL;\n\n // CredentialService is always constructed (with optional signer) so\n // public-decrypt / encryption flows and pre-wallet-connect construction\n // work; permit-signing methods require a signer and throw without one.\n this.#credentialService = new CredentialService({\n router: config.router,\n signer: config.signer,\n transportKeyPairTTL: config.transportKeyPairTTL,\n permitTTL: config.permitTTL,\n scope: config.transportKeyPairScope,\n derivationSecret,\n storage: this.storage,\n permitStorage: config.permitStorage,\n logger: this.#logger,\n emitEvent: this.emitEvent.bind(this),\n });\n if (config.signer) {\n this.#decryptionService = new DecryptionService({\n cache: this.#cachingService,\n credentialService: this.#credentialService,\n delegationService: this.#delegationService,\n router: config.router,\n emitEvent: this.emitEvent.bind(this),\n });\n }\n this.#encryptionService = new EncryptionService({\n router: config.router,\n emitEvent: this.emitEvent.bind(this),\n });\n this.#lifecycleService = new LifecycleService({\n signer: config.signer,\n router: config.router,\n cachingService: this.#cachingService,\n credentialService: this.#credentialService,\n logger: this.#logger,\n });\n this.#offlineService = new OfflineService({\n provider: this.provider,\n router: config.router,\n encryption: this.#encryptionService,\n emitEvent: (input, tokenAddress) => this.emitEvent(input, tokenAddress),\n });\n\n this.permits = new Permits({\n signer: this.signer,\n provider: this.provider,\n cachingService: this.#cachingService,\n credentialService: this.#credentialService,\n logger: this.#logger,\n emitEvent: this.emitEvent.bind(this),\n });\n this.delegations = new Delegations({\n signer: this.signer,\n provider: this.provider,\n delegationService: this.#delegationService,\n });\n this.decryption = new Decryption({\n signer: this.signer,\n provider: this.provider,\n router: config.router,\n decryptionService: this.#decryptionService,\n });\n this.offline = new Offline(this.#offlineService, this.#credentialService);\n }\n\n /**\n * Subscribe to wallet account transitions.\n *\n * @param listener - Called on each transition with a {@link WalletAccountChange} carrying\n * `previous` and `next` wallet account snapshots; either may be `undefined` for\n * connect and disconnect transitions.\n * @returns An unsubscribe function; calling it removes the listener.\n *\n * @internal\n */\n onWalletAccountChange(listener: WalletAccountListener): () => void {\n return this.#lifecycleService.onWalletAccountChange(listener);\n }\n\n /**\n * The SDK-wide logger, exposed so contract abstractions ({@link Token},\n * {@link WrappedToken}) can route their best-effort failures through the\n * same sink. Silent by default.\n *\n * @internal\n */\n get logger(): GenericLogger {\n return this.#logger;\n }\n\n /**\n * The single-chain relayer backend for the **currently active** chain.\n */\n get relayer(): RelayerSDK {\n return this.#router.relayer;\n }\n\n /**\n * Emit a structured SDK event into the unified SDK event stream.\n *\n * Listener exceptions are caught and logged so that a misbehaving subscriber\n * can never corrupt SDK operations.\n *\n * Application code should subscribe via the `onEvent` config option, never\n * call this directly.\n *\n * @internal\n */\n emitEvent(input: ZamaSDKEventInput, tokenAddress?: Address): void {\n try {\n this.#onEvent({ ...input, tokenAddress, timestamp: Date.now() } as ZamaSDKEvent);\n } catch (error) {\n this.#logger.warn(`${input.type} event listener silently failed`, { error });\n }\n }\n\n /**\n * Create a {@link WrappersRegistry} instance bound to this SDK's provider.\n * Inherits the registry addresses derived from the SDK's chain configs, so\n * the result is consistent with {@link ZamaSDK.registry}.\n *\n * @param registryAddresses - Optional per-chain overrides for this registry instance.\n * @returns A {@link WrappersRegistry} instance.\n *\n * @example\n * ```ts\n * // Addresses resolved from the SDK's chain configs\n * const registry = sdk.createWrappersRegistry();\n *\n * // Hardhat or custom chain — override per chain for this registry instance\n * const registry = sdk.createWrappersRegistry({ [31337]: \"0xYourRegistry\" });\n *\n * const pairs = await registry.getTokenPairs();\n * ```\n */\n createWrappersRegistry(registryAddresses?: Record<number, Address>): WrappersRegistry {\n return new WrappersRegistry({\n provider: this.provider,\n registryAddresses: { ...this.#registryAddresses, ...registryAddresses },\n registryTTL: this.#registryTTL,\n });\n }\n\n /**\n * Encrypt one or more plaintext values into FHE ciphertexts.\n *\n * @param params - Typed FHE inputs, the target contract address, and the user address.\n * @returns External encrypted values and the input proof for on-chain submission.\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n *\n * @example\n * ```ts\n * const { encryptedValues, inputProof } = await sdk.encrypt({\n * values: [{ value: 1000n, type: \"euint64\" }],\n * contractAddress: \"0xToken\",\n * userAddress: \"0xUser\",\n * });\n * ```\n */\n async encrypt(params: EncryptParams, options?: Pick<FhevmRelayerOptions, \"signal\" | \"timeout\">) {\n return this.#encryptionService.encryptValues(params, options);\n }\n\n /**\n * Create a high-level ERC-20-style interface for an ERC-7984 confidential token.\n * Supports balance queries, transfers, operator approvals, and decryption.\n *\n * For ERC-7984 wrappers (shield/unshield/allowance), use {@link createWrappedToken} instead.\n *\n * @param address - The confidential token contract address.\n * @returns A {@link Token} instance bound to this SDK.\n *\n * @example\n * ```ts\n * const token = sdk.createToken(cUSDT);\n * const balance = await token.balanceOf(userAddress);\n * ```\n */\n createToken(address: Address): Token {\n return new Token(this, address);\n }\n\n /**\n * Create a high-level interface for an ERC-7984 wrapper token.\n * Extends {@link Token} with shield/unshield/allowance/finalize-unwrap operations.\n *\n * @param address - The wrapper token contract address.\n * @returns A {@link WrappedToken} instance bound to this SDK.\n *\n * @example\n * ```ts\n * const wrapped = sdk.createWrappedToken(wUSDT);\n * await wrapped.shield(1_000_000n);\n * ```\n */\n createWrappedToken(address: Address): WrappedToken {\n return new WrappedToken(this, address);\n }\n\n /**\n * Release the SDK-owned resources: signer lifecycle subscriptions and the\n * relayer backend's resources, an encrypt worker included. Call this when the\n * SDK instance is being replaced (e.g. React provider unmount or a Strict Mode\n * remount). Work already in flight runs to completion, and the instance stays\n * usable: the next encryption spawns a fresh worker.\n */\n dispose(): void {\n this.#lifecycleService.dispose();\n this.#router.dispose();\n }\n\n /**\n * {@link dispose} plus the signer's own disposal. Call this when the SDK is no\n * longer needed (e.g. on shutdown). Work already in flight runs to completion.\n */\n terminate(): void {\n this.dispose();\n this.signer?.dispose?.();\n }\n\n /**\n * Implements the TC39 Explicit Resource Management protocol.\n * Calls {@link terminate} when the `using` binding goes out of scope,\n * unsubscribing signer events and releasing the relayer's resources.\n *\n * @example\n * ```ts\n * {\n * using sdk = new ZamaSDK({ relayer, provider, signer, storage });\n * await sdk.permits.grantPermit([cUSDT]);\n * const balance = await sdk.createToken(cUSDT).balanceOf(userAddress);\n * } // sdk.terminate() called automatically here\n * ```\n */\n [Symbol.dispose](): void {\n this.terminate();\n }\n}\n"],"mappings":"udAwJA,SAAgB,EACd,EACA,EAGe,CACf,GAAI,aAAiBA,EAAAA,EAAW,CAE9B,IAAM,EAAU,EAAS,EAAM,MAC/B,GAAI,EACF,OAAO,EAAQ,CAAK,CAExB,CACA,OAAO,EAAS,IAAI,CAAK,CAC3B,CCnJA,IAAa,EAAb,cAAsCC,EAAAA,CAAU,CAE9C,eAEA,gBAEA,QAEA,YACE,EACA,EACA,CACA,MACEC,EAAAA,EAAc,YACd,WAAW,EAAK,QAAQ,8CAA8C,EAAK,eAAe,eACzE,EAAK,gBAAgB,yHAEtC,CACF,EACA,KAAK,KAAO,mBACZ,KAAK,eAAiB,EAAK,eAC3B,KAAK,gBAAkB,EAAK,gBAC5B,KAAK,QAAU,EAAK,OACtB,CACF,ECrCa,EAAb,cAAmDC,EAAAA,CAAU,CAC3D,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,yBAA0B,EAAS,CAAO,EAC9D,KAAK,KAAO,+BACd,CACF,EAGa,EAAb,cAA6CD,EAAAA,CAAU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