@zama-fhe/sdk 3.7.1 → 3.8.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/chains.cjs +1 -1
  4. package/dist/cjs/chains.cjs.map +1 -1
  5. package/dist/cjs/ethers/index.cjs +1 -1
  6. package/dist/cjs/ethers/index.cjs.map +1 -1
  7. package/dist/cjs/fatal-batch.cjs +2 -0
  8. package/dist/cjs/fatal-batch.cjs.map +1 -0
  9. package/dist/cjs/fhevm-relayer.cjs +1 -1
  10. package/dist/cjs/fhevm-relayer.cjs.map +1 -1
  11. package/dist/cjs/index.cjs +1 -1
  12. package/dist/cjs/index.cjs.map +1 -1
  13. package/dist/cjs/internal/index.cjs +2 -0
  14. package/dist/cjs/internal/index.cjs.map +1 -0
  15. package/dist/cjs/invalidation.cjs +1 -1
  16. package/dist/cjs/invalidation.cjs.map +1 -1
  17. package/dist/cjs/node/index.cjs +1 -1
  18. package/dist/cjs/node/index.cjs.map +1 -1
  19. package/dist/cjs/query/index.cjs +1 -1
  20. package/dist/cjs/query/index.cjs.map +1 -1
  21. package/dist/cjs/relayer.cjs +1 -1
  22. package/dist/cjs/relayer.cjs.map +1 -1
  23. package/dist/cjs/signing.cjs +2 -0
  24. package/dist/cjs/signing.cjs.map +1 -0
  25. package/dist/cjs/telemetry.cjs +1 -1
  26. package/dist/cjs/telemetry.cjs.map +1 -1
  27. package/dist/cjs/token.cjs +1 -1
  28. package/dist/cjs/token.cjs.map +1 -1
  29. package/dist/cjs/typed-data.cjs +2 -0
  30. package/dist/cjs/typed-data.cjs.map +1 -0
  31. package/dist/cjs/vaults/index.cjs +1 -1
  32. package/dist/cjs/vaults/index.cjs.map +1 -1
  33. package/dist/cjs/viem/index.cjs +1 -1
  34. package/dist/cjs/viem/index.cjs.map +1 -1
  35. package/dist/cjs/web/index.cjs +1 -1
  36. package/dist/cjs/web/index.cjs.map +1 -1
  37. package/dist/cjs/wrapped-token.cjs +1 -1
  38. package/dist/cjs/wrapped-token.cjs.map +1 -1
  39. package/dist/cjs/wrappers-registry.cjs +1 -1
  40. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  41. package/dist/esm/base-signer-BG19z5lh.js +2 -0
  42. package/dist/esm/base-signer-BG19z5lh.js.map +1 -0
  43. package/dist/esm/{base-signer-BxIDBDTF.d.ts → base-signer-CNqEVbj7.d.ts} +2 -2
  44. package/dist/esm/chains/index.d.ts +1 -1
  45. package/dist/esm/chains/index.js +1 -1
  46. package/dist/esm/chains-CefvVW4j.js +2 -0
  47. package/dist/esm/chains-CefvVW4j.js.map +1 -0
  48. package/dist/esm/cleartext/index.d.ts +2 -2
  49. package/dist/esm/cleartext/index.js +1 -1
  50. package/dist/esm/{cleartext-DBZq4E1O.js → cleartext-Bc7FpeXr.js} +2 -2
  51. package/dist/esm/{cleartext-DBZq4E1O.js.map → cleartext-Bc7FpeXr.js.map} +1 -1
  52. package/dist/esm/{cleartext-BnTAN4-g.d.ts → cleartext-BcM98zhR.d.ts} +2 -2
  53. package/dist/esm/encrypt-worker-client-9SUUIpLM.d.ts +19 -0
  54. package/dist/esm/{encryption-6AVd-82z.js → encryption-ieCO6J5r.js} +2 -2
  55. package/dist/esm/{encryption-6AVd-82z.js.map → encryption-ieCO6J5r.js.map} +1 -1
  56. package/dist/esm/ethers/index.d.ts +4 -4
  57. package/dist/esm/ethers/index.js +1 -1
  58. package/dist/esm/ethers/index.js.map +1 -1
  59. package/dist/esm/fatal-batch-CI1pes1q.js +2 -0
  60. package/dist/esm/fatal-batch-CI1pes1q.js.map +1 -0
  61. package/dist/esm/fhevm-relayer-tbPMdPw-.js +8 -0
  62. package/dist/esm/{fhevm-relayer-BEQ31nmT.js.map → fhevm-relayer-tbPMdPw-.js.map} +1 -1
  63. package/dist/esm/{index-BlY7CCPB.d.ts → index-BNA1OOfi.d.ts} +7 -7
  64. package/dist/esm/{index-CD2sMpst.d.ts → index-BwANiTpY.d.ts} +1421 -864
  65. package/dist/esm/{index-D1Wtji3m.d.ts → index-COgydmiZ.d.ts} +5 -2
  66. package/dist/esm/{index-fsWBYM8S.d.ts → index-DwwNymCc.d.ts} +7 -6
  67. package/dist/esm/index.d.ts +9 -9
  68. package/dist/esm/index.js +1 -1
  69. package/dist/esm/index.js.map +1 -1
  70. package/dist/esm/internal/index.d.ts +34 -0
  71. package/dist/esm/internal/index.js +2 -0
  72. package/dist/esm/internal/index.js.map +1 -0
  73. package/dist/esm/{invalidation-BgFjmXeQ.js → invalidation-CzspPBR7.js} +2 -2
  74. package/dist/esm/invalidation-CzspPBR7.js.map +1 -0
  75. package/dist/esm/node/index.d.ts +4 -4
  76. package/dist/esm/node/index.js +1 -1
  77. package/dist/esm/node/index.js.map +1 -1
  78. package/dist/esm/query/index.d.ts +5 -5
  79. package/dist/esm/query/index.js +1 -1
  80. package/dist/esm/query/index.js.map +1 -1
  81. package/dist/esm/{relayer-C3jVhqSK.js → relayer-ov8b_HOu.js} +2 -2
  82. package/dist/esm/{relayer-C3jVhqSK.js.map → relayer-ov8b_HOu.js.map} +1 -1
  83. package/dist/esm/signing-CneT-WIV.js +2 -0
  84. package/dist/esm/signing-CneT-WIV.js.map +1 -0
  85. package/dist/esm/telemetry-B3iGCWLv.js +2 -0
  86. package/dist/esm/telemetry-B3iGCWLv.js.map +1 -0
  87. package/dist/esm/token-DlsiZmg5.js +2 -0
  88. package/dist/esm/token-DlsiZmg5.js.map +1 -0
  89. package/dist/esm/typed-data-eAgGr9V-.js +2 -0
  90. package/dist/esm/typed-data-eAgGr9V-.js.map +1 -0
  91. package/dist/esm/{types-Dc1fpXWt.d.ts → types-BQHRdNY-.d.ts} +3 -3
  92. package/dist/esm/{types-C2ccCjoA.d.ts → types-D-rp-sGq.d.ts} +3 -3
  93. package/dist/esm/{types-CHepK8MK.d.ts → types-hWhlvqxC.d.ts} +33 -12
  94. package/dist/esm/{validation-ClSvPh6P.js → validation-ChQwNxaY.js} +2 -2
  95. package/dist/esm/{validation-ClSvPh6P.js.map → validation-ChQwNxaY.js.map} +1 -1
  96. package/dist/esm/vaults/index.d.ts +31 -327
  97. package/dist/esm/vaults/index.js +1 -1
  98. package/dist/esm/vaults/index.js.map +1 -1
  99. package/dist/esm/viem/index.d.ts +4 -4
  100. package/dist/esm/viem/index.js +1 -1
  101. package/dist/esm/viem/index.js.map +1 -1
  102. package/dist/esm/web/index.d.ts +2 -17
  103. package/dist/esm/web/index.js +1 -1
  104. package/dist/esm/web/index.js.map +1 -1
  105. package/dist/esm/wrapped-token-C8eKid8W.js +2 -0
  106. package/dist/esm/wrapped-token-C8eKid8W.js.map +1 -0
  107. package/dist/esm/wrappers-registry-DnYVQ02R.js +2 -0
  108. package/dist/esm/wrappers-registry-DnYVQ02R.js.map +1 -0
  109. package/package.json +15 -1
  110. package/dist/cjs/erc165.cjs +0 -2
  111. package/dist/cjs/erc165.cjs.map +0 -1
  112. package/dist/esm/base-signer-ClrhHzbm.js +0 -2
  113. package/dist/esm/base-signer-ClrhHzbm.js.map +0 -1
  114. package/dist/esm/chains-BwlDI944.js +0 -2
  115. package/dist/esm/chains-BwlDI944.js.map +0 -1
  116. package/dist/esm/erc165-BAd2z3ay.js +0 -2
  117. package/dist/esm/erc165-BAd2z3ay.js.map +0 -1
  118. package/dist/esm/fhevm-relayer-BEQ31nmT.js +0 -8
  119. package/dist/esm/invalidation-BgFjmXeQ.js.map +0 -1
  120. package/dist/esm/telemetry-CBSzrmab.js +0 -2
  121. package/dist/esm/telemetry-CBSzrmab.js.map +0 -1
  122. package/dist/esm/token-CTvEGQmH.js +0 -2
  123. package/dist/esm/token-CTvEGQmH.js.map +0 -1
  124. package/dist/esm/wrapped-token-IDUEFpZx.js +0 -2
  125. package/dist/esm/wrapped-token-IDUEFpZx.js.map +0 -1
  126. package/dist/esm/wrappers-registry-Cm3JJeqx.js +0 -2
  127. package/dist/esm/wrappers-registry-Cm3JJeqx.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"token-CTvEGQmH.js","names":["#requireSigner","submitSdkTransaction"],"sources":["../../src/errors/rpc.ts","../../src/errors/chain.ts","../../src/errors/balance.ts","../../src/errors/fatal-batch.ts","../../src/utils/fhe-type.ts","../../src/utils/handles.ts","../../src/utils/alignment.ts","../../src/utils/assert-balance.ts","../../src/utils/concurrency.ts","../../src/utils/submit-transaction.ts","../../src/token/token.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * The consumer's RPC provider rate-limited an on-chain read the SDK performs\n * during decryption (e.g. the ACL check) — HTTP 429 or JSON-RPC `-32005`. An\n * RPC-endpoint problem, **not** a decryption/entitlement failure, and safe to\n * **retry**. Kept distinct from the relayer's own back-pressure\n * ({@link RelayerRequestFailedError}).\n *\n * Backoff for chain RPC is owned by the consumer's transport: viem/ethers\n * already honor the `Retry-After` header and retry internally before this error\n * surfaces, so it is configured on the transport you pass via `chain.network`\n * (not re-implemented here).\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof RpcRateLimitError) {\n * // back off and retry; consider a higher-throughput RPC endpoint\n * }\n * }\n * ```\n */\nexport class RpcRateLimitError extends ZamaError {\n /**\n * Suggested delay before retrying, in **seconds**, when a numeric `retryAfter`\n * is present on the error. Usually `undefined` for chain RPC: the `Retry-After`\n * header is consumed by the consumer's viem/ethers transport (which owns the\n * backoff), not surfaced here — see the class doc.\n */\n readonly retryAfter: number | undefined;\n\n constructor(message: string, options?: ErrorOptions & { retryAfter?: number }) {\n const { retryAfter, ...errorOptions } = options ?? {};\n super(ZamaErrorCode.RpcRateLimited, message, errorOptions);\n this.name = \"RpcRateLimitError\";\n this.retryAfter = retryAfter;\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * Thrown when the signer and provider are connected to different chains at the\n * start of a write operation.\n *\n * Every write method runs a chain-alignment pre-flight check. If\n * `signer.getChainId()` and `provider.getChainId()` return different values,\n * this error is thrown before any RPC mutation is attempted.\n *\n * @example\n * ```ts\n * try {\n * await token.shield(1000n);\n * } catch (e) {\n * if (e instanceof ChainMismatchError) {\n * console.error(\n * `Signer is on chain ${e.signerChainId} but provider is on chain ${e.providerChainId}`,\n * );\n * }\n * }\n * ```\n */\nexport class ChainMismatchError extends ZamaError {\n /** Name of the operation that triggered the check. */\n readonly operation: string;\n /** Chain ID the signer is connected to. */\n readonly signerChainId: number;\n /** Chain ID the provider is connected to. */\n readonly providerChainId: number;\n\n constructor(\n {\n operation,\n signerChainId,\n providerChainId,\n }: { operation: string; signerChainId: number; providerChainId: number },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.ChainMismatch,\n `Operation \"${operation}\" requires signer and provider to be on the same chain, ` +\n `but signer is on chain ${signerChainId} and provider is on chain ${providerChainId}.`,\n options,\n );\n this.name = \"ChainMismatchError\";\n this.operation = operation;\n this.signerChainId = signerChainId;\n this.providerChainId = providerChainId;\n }\n}\n","import type { Address } from \"viem\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Structured details shared by balance-related errors. */\nexport interface BalanceErrorDetails {\n /** Amount the caller requested, in the token's base units. */\n readonly requested: bigint;\n /** Amount available at the time of the check, in the token's base units. */\n readonly available: bigint;\n /** Address of the token contract involved. */\n readonly token: Address;\n}\n\n/** Confidential (cToken) balance is insufficient for the requested operation. */\nexport class InsufficientConfidentialBalanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The available balance at the time of the check. */\n readonly available: bigint;\n /** The token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientConfidentialBalance, message, options);\n this.name = \"InsufficientConfidentialBalanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** ERC-20 balance is insufficient for the requested shield amount. */\nexport class InsufficientERC20BalanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The available balance at the time of the check. */\n readonly available: bigint;\n /** The ERC-20 token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientERC20Balance, message, options);\n this.name = \"InsufficientERC20BalanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** ERC-20 allowance granted to the wrapper is insufficient for the requested wrap amount. */\nexport class InsufficientAllowanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The allowance available at the time of the check. */\n readonly available: bigint;\n /** The underlying ERC-20 token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientAllowance, message, options);\n this.name = \"InsufficientAllowanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** Balance validation could not be performed (no cached credentials and decryption not possible). */\nexport class BalanceCheckUnavailableError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.BalanceCheckUnavailable, message, options);\n this.name = \"BalanceCheckUnavailableError\";\n }\n}\n\n/** A public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\nexport class ERC20ReadFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.ERC20ReadFailed, message, options);\n this.name = \"ERC20ReadFailedError\";\n }\n}\n","import { KeyWrappingError, RevokedKmsContextError } from \"./credential\";\nimport { ConfigurationError } from \"./relayer\";\nimport { RpcRateLimitError } from \"./rpc\";\nimport { SigningRejectedError, SigningFailedError } from \"./signing\";\n\n/**\n * Returns `true` for errors that should abort an entire batch operation\n * rather than be recorded per-item — wallet signature rejected, signing\n * infrastructure broken, SDK misconfigured, the RPC provider throttling, or\n * transport key pair wrapping unusable for the whole session (wrong or missing\n * `transportKeyPairDerivationSecret`, `crypto.subtle` unavailable).\n * These are systemic failures that won't recover within the same call; for a\n * rate-limit in particular, the per-item retry loop would only amplify the\n * throttle by re-hitting the already-rate-limited endpoint. A revoked KMS\n * context is likewise batch-wide: every item's permit shares the dead context,\n * and the per-item loop would trigger one evict-and-regrant wallet prompt per\n * item instead of the one the batch attempt already spent.\n *\n * Callers iterating over a batch (e.g. per-token decrypt) should rethrow when\n * this predicate is true so the whole batch aborts, and record the error\n * per-item otherwise.\n */\nexport function isFatalBatchError(error: unknown): boolean {\n return (\n error instanceof SigningRejectedError ||\n error instanceof SigningFailedError ||\n error instanceof ConfigurationError ||\n error instanceof RpcRateLimitError ||\n error instanceof KeyWrappingError ||\n error instanceof RevokedKmsContextError\n );\n}\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import type { EncryptedValue } from \"../relayer/types\";\nimport { encryptionBitsFromFheTypeId, isFheTypeId } from \"./fhe-type\";\n\n/** All-zero encrypted-value sentinel — a 32-byte zero handle representing the cleartext value `0`. */\nexport const ZERO_ENCRYPTED_VALUE =\n \"0x0000000000000000000000000000000000000000000000000000000000000000\" as const;\n\n/**\n * Check whether an encrypted value represents the zero value.\n */\nexport function isEncryptedValueZero(encryptedValue: string): boolean {\n return encryptedValue === ZERO_ENCRYPTED_VALUE || encryptedValue === \"0x\";\n}\n\n/**\n * Per-request cleartext-bit budget enforced by the KMS gateway, mirrored from\n * `@fhevm/sdk`'s `MAX_KMS_DECRYPT_DECRYPTION_BIT_LIMIT` (protocol-level constant,\n * not imported — see {@link MAX_CONTRACTS_PER_PERMIT} for why). Internal: decrypt\n * requests are chunked to respect it automatically, so callers never need this value.\n */\nexport const MAX_DECRYPTION_REQUEST_BITS = 2048;\n\n/** Max encryption bit width among all currently-known FHE types (euint256). */\nconst MAX_KNOWN_ENCRYPTION_BITS = 256;\n\n/**\n * Cleartext bit cost of decrypting a single handle, derived from its FHE\n * type (encoded at bits 8-15 of the handle — the same layout `@fhevm/sdk`'s\n * `FhevmHandle` decodes, byte 30 of the 32-byte handle).\n *\n * Falls back to {@link MAX_KNOWN_ENCRYPTION_BITS} for an unrecognized type\n * byte, or for a value that isn't parseable hex at all, instead of throwing.\n * A real on-chain handle is always well-formed with a valid type byte, so\n * this fallback only ever fires for synthetic test/placeholder handles —\n * deliberately more permissive than the relayer's own strict validation so\n * chunking stays safe without requiring every test fixture to encode a real\n * FHE handle. Do not tighten this to match relayer semantics.\n */\nexport function encryptionBitsForHandle(encryptedValue: EncryptedValue): number {\n let handleValue: bigint;\n try {\n handleValue = BigInt(encryptedValue);\n } catch {\n return MAX_KNOWN_ENCRYPTION_BITS;\n }\n const typeByte = Number((handleValue >> 8n) & 0xffn);\n return isFheTypeId(typeByte) ? encryptionBitsFromFheTypeId(typeByte) : MAX_KNOWN_ENCRYPTION_BITS;\n}\n\n/**\n * Split `handles` into groups whose cumulative cleartext-bit cost never\n * exceeds `maxBits`, preserving input order. Unlike {@link chunkContracts}\n * (fixed-size slices), a greedy accumulate-until-exceeded walk is required\n * since per-handle cost varies by FHE type. A handle whose own cost exceeds\n * `maxBits` still gets a solo chunk — always makes forward progress.\n */\nexport function chunkHandlesByBitBudget(\n handles: readonly EncryptedValue[],\n maxBits: number = MAX_DECRYPTION_REQUEST_BITS,\n): EncryptedValue[][] {\n const chunks: EncryptedValue[][] = [];\n let current: EncryptedValue[] = [];\n let currentBits = 0;\n\n for (const handle of handles) {\n const bits = encryptionBitsForHandle(handle);\n if (current.length > 0 && currentBits + bits > maxBits) {\n chunks.push(current);\n current = [];\n currentBits = 0;\n }\n current.push(handle);\n currentBits += bits;\n }\n if (current.length > 0) {\n chunks.push(current);\n }\n return chunks;\n}\n","import {\n ChainMismatchError,\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n} from \"../errors\";\nimport type { GenericProvider, GenericSigner, WalletAccount } from \"../types\";\n\n/**\n * Pre-flight guard for signer-required operations. Resolves the connected\n * wallet account (refreshing once if the signer reports it isn't ready) and\n * verifies the signer's chain matches the provider's.\n *\n * @internal\n */\nexport async function requireAlignedWalletAccount(\n operation: string,\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n): Promise<WalletAccount> {\n if (!signer) {\n throw new SignerNotConfiguredError(operation);\n }\n let account: WalletAccount;\n try {\n account = signer.requireWalletAccount(operation);\n } catch (error) {\n if (!(error instanceof WalletAccountNotReadyError) || !signer.refreshWalletAccount) {\n throw error;\n }\n await signer.refreshWalletAccount();\n account = signer.requireWalletAccount(operation);\n }\n const providerChainId = await provider.getChainId();\n if (account.chainId !== providerChainId) {\n throw new ChainMismatchError({ operation, signerChainId: account.chainId, providerChainId });\n }\n return account;\n}\n\n/**\n * Variant of {@link requireAlignedWalletAccount} that returns only the aligned\n * chain ID. Useful when a write path only needs to ensure signer/provider\n * coherence and doesn't otherwise consume the account.\n *\n * @internal\n */\nexport async function requireChainAlignment(\n operation: string,\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n): Promise<number> {\n return (await requireAlignedWalletAccount(operation, signer, provider)).chainId;\n}\n","import type { Address } from \"viem\";\nimport { getAddress } from \"viem\";\nimport {\n BalanceCheckUnavailableError,\n InsufficientConfidentialBalanceError,\n ZamaError,\n} from \"../errors\";\nimport type { GenericProvider, GenericSigner } from \"../types\";\nimport { requireAlignedWalletAccount } from \"./alignment\";\n\n/**\n * Pre-flight for a write that would silently move zero on a short balance:\n * decrypt the connected account's balance on `tokenAddress` and throw if it\n * is below `amount`. Decrypting can prompt for a permit signature when none\n * is cached. A failure that is not already a typed SDK error surfaces as\n * {@link BalanceCheckUnavailableError}.\n *\n * @internal\n */\nexport async function assertConfidentialBalance(params: {\n operation: string;\n tokenAddress: Address;\n amount: bigint;\n signer: GenericSigner | undefined;\n provider: GenericProvider;\n readBalance: (owner: Address) => Promise<bigint>;\n}): Promise<void> {\n const { operation, tokenAddress, amount, signer, provider, readBalance } = params;\n if (amount === 0n) {\n return;\n }\n\n let balance: bigint;\n try {\n const account = await requireAlignedWalletAccount(operation, signer, provider);\n balance = await readBalance(getAddress(account.address));\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new BalanceCheckUnavailableError(`Balance validation failed (token: ${tokenAddress})`, {\n cause: error,\n });\n }\n\n if (balance < amount) {\n throw new InsufficientConfidentialBalanceError(\n `Insufficient confidential balance: requested ${amount}, available ${balance} (token: ${tokenAddress})`,\n { requested: amount, available: balance, token: tokenAddress },\n );\n }\n}\n","/**\n * Execute an array of async thunks with bounded concurrency.\n * Defaults to `Infinity` (equivalent to `Promise.all`).\n */\nexport async function pLimit<T>(\n fns: (() => Promise<T>)[],\n maxConcurrency = Infinity,\n): Promise<T[]> {\n if (Number.isFinite(maxConcurrency) && maxConcurrency <= 0) {\n throw new Error(\"maxConcurrency must be a positive number\");\n }\n if (!Number.isFinite(maxConcurrency) || maxConcurrency >= fns.length) {\n return Promise.all(fns.map((f) => f()));\n }\n\n const results: T[] = Array.from({ length: fns.length });\n let index = 0;\n\n async function worker() {\n while (index < fns.length) {\n const i = index++;\n if (fns[i]) {\n results[i] = await fns[i]();\n }\n }\n }\n\n await Promise.all(Array.from({ length: maxConcurrency }, worker));\n return results;\n}\n","import type { Hex } from \"viem\";\nimport { TransactionRevertedError, ZamaError } from \"../errors\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { transactionOperationMetadata, ZamaSDKEvents } from \"../events/sdk-events\";\nimport type {\n GenericLogger,\n GenericProvider,\n GenericSigner,\n TransactionResult,\n WriteContractConfig,\n} from \"../types\";\nimport { swallow } from \"./swallow\";\n\n/**\n * Shared write-transaction pipeline for SDK calls that submit a transaction.\n *\n * On success: writes the tx, emits the per-operation submitted event from\n * {@link transactionOperationMetadata}, fires `onSubmitted`, waits for the\n * receipt, and returns `{ txHash, receipt }`.\n *\n * On failure: emits a {@link ZamaSDKEvents.TransactionError} event with the\n * transaction-level error it will throw, then throws it. Existing `ZamaError`\n * instances are rethrown as-is; all other failures are wrapped in\n * `TransactionRevertedError` with the original error as `cause`.\n */\nexport async function submitTransaction(params: {\n operation: TransactionOperation;\n signer: GenericSigner;\n provider: GenericProvider;\n config: WriteContractConfig;\n emit: (input: ZamaSDKEventInput) => void;\n onSubmitted?: (txHash: Hex) => void;\n logger: GenericLogger;\n}): Promise<TransactionResult> {\n const { operation, signer, provider, config, emit, onSubmitted, logger } = params;\n const metadata = transactionOperationMetadata[operation];\n\n try {\n const txHash = await signer.writeContract(config);\n emit(metadata.submittedEvent(txHash));\n void swallow(`${operation}: onSubmitted`, () => onSubmitted?.(txHash), logger);\n const receipt = await provider.waitForTransactionReceipt(txHash);\n return { txHash, receipt };\n } catch (error) {\n const failure =\n error instanceof ZamaError\n ? error\n : new TransactionRevertedError(`Transaction failed during ${operation}`, { cause: error });\n\n emit({ type: ZamaSDKEvents.TransactionError, operation, error: failure });\n throw failure;\n }\n}\n","import { type Address, getAddress, type Hex } from \"viem\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferAndCallContract,\n confidentialTransferContract,\n confidentialTransferFromAndCallContract,\n confidentialTransferFromContract,\n decimalsContract,\n ERC7984_INTERFACE_ID,\n ERC7984_WRAPPER_INTERFACE_ID,\n isOperatorContract,\n nameContract,\n setOperatorContract,\n supportsInterfaceContract,\n symbolContract,\n} from \"../contracts\";\nimport {\n ConfigurationError,\n DecryptionFailedError,\n EncryptionFailedError,\n isFatalBatchError,\n requireConfigured,\n ZamaError,\n} from \"../errors\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { toError } from \"../utils\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\nimport { assertConfidentialBalance } from \"../utils/assert-balance\";\nimport type { TelemetryOperation } from \"../telemetry\";\nimport { assertBigint } from \"../utils/assertions\";\nimport { pLimit } from \"../utils/concurrency\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport { submitTransaction as submitSdkTransaction } from \"../utils/submit-transaction\";\nimport { swallow } from \"../utils/swallow\";\nimport type {\n GenericSigner,\n TransactionResult,\n TransferCallbacks,\n TransferOptions,\n WriteContractConfig,\n} from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\n\n/** Options for {@link Token.batchDecryptBalancesAs}. */\nexport interface BatchDecryptAsOptions {\n /** The address of the account that delegated decryption rights. */\n delegatorAddress: Address;\n /** Pre-fetched encrypted values. When omitted, they are fetched from the chain. */\n encryptedValues?: EncryptedValue[];\n /**\n * The account whose on-chain balance to read. Defaults to the delegator\n * address, which is the common case (the delegator grants permission to\n * decrypt their own balance). Only set this when the account differs\n * from the delegator.\n *\n * Matches the `account` parameter of `confidentialBalanceOf(account)` on-chain.\n */\n accountAddress?: Address;\n /** Maximum number of concurrent decrypt calls. Default: 10. */\n maxConcurrency?: number;\n /** Called when decryption fails for a single token. Return a fallback bigint. */\n onError?: (error: Error, address: Address) => bigint;\n}\n\n/** Result of {@link Token.batchBalancesOf}. */\nexport interface BatchBalancesResult {\n /** Successfully decrypted balances, keyed by token address. */\n results: Map<Address, bigint>;\n /** Per-token errors for tokens that failed to decrypt. */\n errors: Map<Address, ZamaError>;\n}\n\n/**\n * High-level interface for an ERC-7984 confidential token.\n * Hides FHE complexity (encryption, decryption, EIP-712 signing) behind\n * familiar ERC-20-like methods.\n *\n * For ERC-7984 wrappers (shield/unshield), use {@link WrappedToken} instead —\n * it extends `Token` with wrapper-specific operations.\n *\n * Decryption, credentials, caching, and event emission are handled by the\n * owning {@link ZamaSDK} — this class only exposes token-scoped helpers\n * that delegate to `sdk.decryption.decryptValues` and `sdk.permits.grantPermit`.\n */\nexport class Token {\n /** The SDK instance this token operates through. */\n readonly sdk: ZamaSDK;\n /** Checksummed address of the confidential token contract. */\n readonly address: Address;\n\n constructor(sdk: ZamaSDK, address: Address) {\n this.sdk = sdk;\n this.address = getAddress(address);\n }\n\n /** Resolve `sdk.signer` or throw {@link SignerNotConfiguredError} tagged with `operation`. */\n #requireSigner(operation: string): GenericSigner {\n return requireConfigured(this.sdk.signer, operation);\n }\n\n // METADATA\n\n /** Read the token name from the contract. */\n async name(): Promise<string> {\n return this.sdk.provider.readContract(nameContract(this.address));\n }\n\n /** Read the token symbol from the contract. */\n async symbol(): Promise<string> {\n return this.sdk.provider.readContract(symbolContract(this.address));\n }\n\n /** Read the token decimals from the contract. */\n async decimals(): Promise<number> {\n return this.sdk.provider.readContract(decimalsContract(this.address));\n }\n\n // ERC-165 DISCOVERY\n\n /**\n * ERC-165 check for {@link ERC7984_INTERFACE_ID} support.\n *\n * @returns `true` if the contract implements the ERC-7984 confidential token interface.\n */\n async isConfidential(): Promise<boolean> {\n return this.sdk.provider.readContract(\n supportsInterfaceContract(this.address, ERC7984_INTERFACE_ID),\n );\n }\n\n /**\n * ERC-165 check for IERC7984ERC20Wrapper support.\n *\n * @returns `true` if the contract implements the ERC-7984 wrapper interface\n * ({@link ERC7984_WRAPPER_INTERFACE_ID}, `0x1f1c62b2`).\n */\n async isWrapper(): Promise<boolean> {\n return this.sdk.provider.readContract(\n supportsInterfaceContract(this.address, ERC7984_WRAPPER_INTERFACE_ID),\n );\n }\n\n // BALANCES\n\n /**\n * Decrypt and return the plaintext balance for the given owner.\n * Acquires FHE credentials via a wallet signature if none are cached.\n *\n * @param owner - Balance owner address.\n * @returns The decrypted plaintext balance as a bigint.\n * @throws if FHE decryption fails. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balance = await token.balanceOf(\"0xOwner\");\n * ```\n */\n async balanceOf(owner: Address): Promise<bigint> {\n return this.decryptBalance(owner, \"balance-of\");\n }\n\n /**\n * {@link balanceOf} with the telemetry label of the public method that needs the balance.\n *\n * @internal\n */\n async decryptBalance(owner: Address, telemetryOperation: TelemetryOperation): Promise<bigint> {\n const ownerAddress = getAddress(owner);\n const encryptedValue = await this.readConfidentialBalanceOf(ownerAddress);\n const result = await this.sdk.decryption.decryptValues(\n [{ encryptedValue, contractAddress: this.address }],\n { operation: telemetryOperation },\n );\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(`Decryption returned no value for ${encryptedValue}`);\n }\n assertBigint(value, \"balanceOf: result[encryptedValue]\");\n return value;\n }\n\n /**\n * Return the raw encrypted balance without decrypting.\n *\n * @param owner - Balance owner address.\n * @returns The encrypted balance as a hex string.\n *\n * @example\n * ```ts\n * const encryptedValue = await token.confidentialBalanceOf(\"0xOwner\");\n * ```\n */\n async confidentialBalanceOf(owner: Address): Promise<EncryptedValue> {\n return this.readConfidentialBalanceOf(getAddress(owner));\n }\n\n /**\n * Decrypt the balance of a delegator using delegated decryption credentials.\n * The connected signer acts as the delegatee who has been granted permission\n * by the delegator to decrypt their balance.\n *\n * Clear values are cached in storage keyed by `(account, token, encryptedValue)`.\n * Because every on-chain balance change produces a new encrypted value,\n * stale cache entries are never served. Cache write failures are silently\n * ignored — they do not affect the returned value.\n *\n * @param delegatorAddress - The address of the account that delegated decryption rights.\n * @param accountAddress - The account whose on-chain balance to read. Defaults\n * to the delegator address.\n * @returns The decrypted plaintext balance as a bigint.\n * @throws if no active delegation exists. {@link DelegationNotFoundError}\n * @throws if the delegation has expired. {@link DelegationExpiredError}\n * @throws if delegated decryption fails. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balance = await token.decryptBalanceAs({\n * delegatorAddress: \"0xDelegator\",\n * });\n * ```\n */\n async decryptBalanceAs({\n delegatorAddress,\n accountAddress,\n }: {\n delegatorAddress: Address;\n accountAddress?: Address;\n }): Promise<bigint> {\n await requireChainAlignment(\"decryptBalanceAs\", this.sdk.signer, this.sdk.provider);\n const normalizedDelegator = getAddress(delegatorAddress);\n const normalizedAccount = accountAddress ? getAddress(accountAddress) : normalizedDelegator;\n\n const encryptedValue = await this.readConfidentialBalanceOf(normalizedAccount);\n if (isEncryptedValueZero(encryptedValue)) {\n return 0n;\n }\n\n const result = await this.sdk.decryption.delegatedDecryptValues(\n [{ encryptedValue, contractAddress: this.address }],\n normalizedDelegator,\n normalizedAccount,\n { operation: \"decrypt-balance-as\" },\n );\n\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(\n `Delegated decryption returned no value for ${encryptedValue}`,\n );\n }\n assertBigint(value, \"decryptBalanceAs: result[encryptedValue]\");\n return value;\n }\n\n // BATCH STATICS\n\n /**\n * Decrypt confidential balances for multiple tokens in parallel, returning\n * successes and per-token errors separately. Pre-authorizes all token\n * addresses in a single wallet signature, then delegates each decrypt to\n * `sdk.decryption.decryptValues`.\n *\n * Tokens that fail to decrypt land in `errors`; the batch keeps going.\n *\n * @param tokens - Array of {@link Token} instances bound to the same SDK.\n * @param owner - Balance owner address.\n * @returns `{ results, errors }` partitioning the per-token outcomes.\n * @throws A failure that affects the whole session (rejected signature,\n * misconfiguration, RPC rate limit, key unwrapping failure, revoked KMS\n * context) rejects the call instead of landing in `errors`.\n *\n * @example\n * ```ts\n * const { results, errors } = await Token.batchBalancesOf(tokens, owner);\n * ```\n */\n static async batchBalancesOf(tokens: Token[], owner: Address): Promise<BatchBalancesResult> {\n const results = new Map<Address, bigint>();\n const errors = new Map<Address, ZamaError>();\n if (tokens.length === 0) {\n return { results, errors };\n }\n\n const sdk = Token.assertSameSdk(tokens);\n // Fail fast on chain mismatch before prompting the wallet for a signature.\n await requireChainAlignment(\"batchBalancesOf\", sdk.signer, sdk.provider);\n // Pre-authorize the full token set in one wallet signature so subsequent\n // per-token decryptValues calls reuse the cached credentials.\n await sdk.permits.grantPermit(tokens.map((t) => t.address));\n\n // `pLimit` cannot cancel calls that already started. The shared flag stops\n // the queued tokens from starting once a fatal error is seen, so they do\n // not each trigger their own recovery wallet prompt.\n let aborted = false;\n let fatal: unknown;\n\n const outcomes = await pLimit(\n tokens.map((t) => async () => {\n if (aborted) {\n return { status: \"aborted\" as const };\n }\n try {\n return {\n status: \"fulfilled\" as const,\n value: await t.decryptBalance(owner, \"batch-balances-of\"),\n };\n } catch (reason) {\n // A fatal error (rejected signature, revoked KMS context, rate\n // limit) would fail every token: stop the batch.\n if (isFatalBatchError(reason)) {\n aborted = true;\n fatal ??= reason;\n return { status: \"aborted\" as const };\n }\n return { status: \"rejected\" as const, reason };\n }\n }),\n 5,\n );\n\n // Some tokens were never attempted after the abort, so a partial result\n // would be wrong: reject the whole call.\n if (fatal !== undefined) {\n throw fatal;\n }\n\n for (let i = 0; i < tokens.length; i++) {\n const tokenAddress = tokens[i]!.address;\n const outcome = outcomes[i]!;\n if (outcome.status === \"aborted\") {\n continue;\n }\n if (outcome.status === \"fulfilled\") {\n results.set(tokenAddress, outcome.value);\n } else {\n const reason = outcome.reason;\n const error =\n reason instanceof ZamaError\n ? reason\n : new DecryptionFailedError(toError(reason).message, { cause: reason });\n errors.set(tokenAddress, error);\n }\n }\n\n // Total failure: surface the first error so callers know nothing decrypted.\n if (errors.size === tokens.length) {\n const firstError = errors.values().next().value;\n throw firstError ?? new DecryptionFailedError(\"All token balance decryptions failed\");\n }\n\n return { results, errors };\n }\n\n /**\n * Batch decrypt confidential balances as a delegate across multiple tokens.\n * Mirrors {@link batchBalancesOf} but uses delegated credentials.\n *\n * **Error handling:** If a per-token decryption fails and no `onError` callback\n * is provided, errors are collected and thrown as an aggregated\n * `DecryptionFailedError`. When the relayer returns no value for an encrypted value,\n * a `DecryptionFailedError` is thrown for that token (never silently returns `0n`).\n * Pass `onError: () => 0n` to opt into the silent zero behavior.\n *\n * @param tokens - Array of Token instances to decrypt balances for.\n * @param options - Delegated decryption configuration.\n * @returns A Map from token address to decrypted balance.\n * @throws if no active delegation exists. {@link DelegationNotFoundError}\n * @throws if the delegation has expired. {@link DelegationExpiredError}\n * @throws if any decryption fails and no `onError` is provided. {@link DecryptionFailedError}\n * @throws A failure that affects the whole session (rejected signature, RPC\n * rate limit, revoked KMS context) rejects the call even when `onError` is\n * provided.\n *\n * @example\n * ```ts\n * const balances = await Token.batchDecryptBalancesAs(tokens, {\n * delegatorAddress: \"0xDelegator\",\n * onError: (err, addr) => { console.error(addr, err); return 0n; },\n * });\n * ```\n */\n static async batchDecryptBalancesAs(\n tokens: Token[],\n options: BatchDecryptAsOptions,\n ): Promise<Map<Address, bigint>> {\n if (tokens.length === 0) {\n return new Map();\n }\n\n const sdk = Token.assertSameSdk(tokens);\n const results = new Map<Address, bigint>();\n const errors = new Map<Address, ZamaError>();\n const normalizedAccount = options.accountAddress\n ? getAddress(options.accountAddress)\n : getAddress(options.delegatorAddress);\n const maxConcurrency = options.maxConcurrency ?? 10;\n if (options.encryptedValues && tokens.length !== options.encryptedValues.length) {\n throw new DecryptionFailedError(\n `tokens.length (${tokens.length}) must equal encryptedValues.length (${options.encryptedValues.length})`,\n );\n }\n const resolvedEncryptedValues =\n options.encryptedValues ??\n (await Token.readBalanceHandlesBatch(tokens, normalizedAccount, errors, maxConcurrency));\n\n const decryptRequests: Array<{ token: Token; encryptedValue: EncryptedValue }> = [];\n for (const [index, token] of tokens.entries()) {\n const encryptedValue = resolvedEncryptedValues[index];\n if (!encryptedValue || errors.has(token.address)) {\n continue;\n }\n if (isEncryptedValueZero(encryptedValue)) {\n // Zero balance → skip the relayer; no decryption needed.\n results.set(token.address, 0n);\n } else {\n decryptRequests.push({ token, encryptedValue });\n }\n }\n\n if (decryptRequests.length > 0) {\n const decrypted = await sdk.decryption.delegatedBatchDecryptValues({\n encryptedInputs: decryptRequests.map(({ token, encryptedValue }) => ({\n encryptedValue,\n contractAddress: token.address,\n })),\n delegatorAddress: options.delegatorAddress,\n accountAddress: options.accountAddress,\n maxConcurrency,\n operation: \"batch-decrypt-balances-as\",\n });\n\n for (const [index, item] of decrypted.items.entries()) {\n const request = decryptRequests[index];\n if (!request) {\n continue;\n }\n if (item.error) {\n errors.set(request.token.address, item.error);\n continue;\n }\n const value = item.value;\n if (value === undefined) {\n errors.set(\n request.token.address,\n new DecryptionFailedError(\n `Batch delegated decryption returned no value for ${item.encryptedValue} on token ${request.token.address}`,\n ),\n );\n continue;\n }\n assertBigint(value, \"batchDecryptBalancesAs: result[encryptedValue]\");\n results.set(request.token.address, value);\n }\n }\n\n if (errors.size === 0) {\n return results;\n }\n\n if (options.onError) {\n const callbackErrors: Array<{ address: Address; error: Error }> = [];\n for (const [address, error] of errors) {\n try {\n results.set(address, options.onError(error, address));\n } catch (callbackError) {\n callbackErrors.push({ address, error: toError(callbackError) });\n }\n }\n if (callbackErrors.length > 0) {\n const message = callbackErrors\n .map(({ address, error }) => `${address}: ${error.message}`)\n .join(\"; \");\n throw new DecryptionFailedError(\n `Batch delegated decryption onError callback failed for ${callbackErrors.length} token(s): ${message}`,\n { cause: callbackErrors[0]?.error },\n );\n }\n return results;\n }\n\n const errorEntries = Array.from(errors.entries());\n const message = errorEntries.map(([addr, e]) => `${addr}: ${e.message}`).join(\"; \");\n throw new DecryptionFailedError(\n `Batch delegated decryption failed for ${errors.size} token(s): ${message}`,\n { cause: errorEntries[0]?.[1] },\n );\n }\n\n private static async readBalanceHandlesBatch(\n tokens: Token[],\n accountAddress: Address,\n errors: Map<Address, ZamaError>,\n maxConcurrency: number,\n ): Promise<Array<EncryptedValue | undefined>> {\n // `pLimit` cannot cancel calls that already started. The shared flag stops\n // the queued tokens from re-hitting an endpoint that already failed for\n // the whole batch.\n let aborted = false;\n let fatal: unknown;\n\n const outcomes = await pLimit(\n tokens.map((token) => async () => {\n if (aborted) {\n return { status: \"aborted\" as const };\n }\n try {\n return {\n status: \"fulfilled\" as const,\n value: await token.readConfidentialBalanceOf(accountAddress),\n };\n } catch (reason) {\n if (isFatalBatchError(reason)) {\n aborted = true;\n fatal ??= reason;\n return { status: \"aborted\" as const };\n }\n return { status: \"rejected\" as const, reason };\n }\n }),\n maxConcurrency,\n );\n\n if (fatal !== undefined) {\n throw fatal;\n }\n\n const encryptedValues: Array<EncryptedValue | undefined> = [];\n for (const [index, token] of tokens.entries()) {\n const outcome = outcomes[index];\n if (!outcome || outcome.status === \"aborted\") {\n continue;\n }\n if (outcome.status === \"fulfilled\") {\n encryptedValues[index] = outcome.value;\n continue;\n }\n errors.set(\n token.address,\n outcome.reason instanceof ZamaError\n ? outcome.reason\n : new DecryptionFailedError(toError(outcome.reason).message, { cause: outcome.reason }),\n );\n }\n return encryptedValues;\n }\n\n // WRITE OPERATIONS\n\n /**\n * Confidential transfer. Encrypts the amount via FHE, then calls the contract.\n *\n * By default, the SDK validates the confidential balance before submitting.\n * If a cached plaintext balance exists it is used; otherwise, if credentials\n * are cached, it decrypts on the fly. Set `skipBalanceCheck: true` to bypass\n * this validation (e.g. for smart wallets).\n *\n * @param to - Recipient address.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param options - Optional: `skipBalanceCheck` (default `false`).\n * @returns The transaction hash and mined receipt.\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}\n * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransfer(\"0xRecipient\", 1000n);\n * ```\n */\n async confidentialTransfer(\n to: Address,\n amount: bigint,\n options?: TransferOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransfer\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransfer\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const { skipBalanceCheck = false, onEncryptComplete, onTransferSubmitted } = options ?? {};\n\n const normalizedTo = getAddress(to);\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount, \"confidential-transfer\");\n }\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt(\n {\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n },\n { operation: \"confidential-transfer\" },\n );\n void swallow(\"transfer: onEncryptComplete\", () => onEncryptComplete?.(), this.sdk.logger);\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transfer\",\n config: confidentialTransferContract(\n this.address,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n ),\n onSubmitted: onTransferSubmitted,\n });\n }\n\n /**\n * Operator encrypted transfer on behalf of another address.\n * The caller must be an approved operator for `from`.\n *\n * @param from - The address to transfer from (caller must be an approved operator).\n * @param to - Recipient address.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferFrom(\"0xFrom\", \"0xTo\", 500n);\n * ```\n */\n async confidentialTransferFrom(\n from: Address,\n to: Address,\n amount: bigint,\n callbacks?: TransferCallbacks,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferFrom\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransferFrom\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const normalizedFrom = getAddress(from);\n const normalizedTo = getAddress(to);\n\n // The input proof is verified against msg.sender, so it binds to the caller, not `from`.\n const { encryptedValues, inputProof } = await this.sdk.encrypt(\n {\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n },\n { operation: \"confidential-transfer-from\" },\n );\n void swallow(\n \"transferFrom: onEncryptComplete\",\n () => callbacks?.onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferFrom\",\n config: confidentialTransferFromContract(\n this.address,\n normalizedFrom,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n ),\n onSubmitted: callbacks?.onTransferSubmitted,\n });\n }\n\n /**\n * ERC-7984 `confidentialTransferAndCall`: encrypted transfer that also invokes\n * the recipient's receiver hook (`onConfidentialTransferReceived`) in a single\n * transaction. The caller crafts the opaque `data` payload — the SDK does not\n * encode, validate, or interpret it.\n *\n * Balance validation follows the same rules as {@link Token.confidentialTransfer}.\n *\n * @param to - Recipient address. Must implement the ERC-7984 receiver hook.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param data - Opaque bytes forwarded to the recipient's receiver hook.\n * @param options - Optional: `skipBalanceCheck` (default `false`).\n * @returns The transaction hash and mined receipt.\n *\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}\n * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferAndCall(\n * \"0xRecipient\",\n * 1000n,\n * \"0xabcd\", // caller-encoded payload forwarded to the receiver hook\n * );\n * ```\n */\n async confidentialTransferAndCall(\n to: Address,\n amount: bigint,\n data: Hex,\n options?: TransferOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferAndCall\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransferAndCall\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const { skipBalanceCheck = false, onEncryptComplete, onTransferSubmitted } = options ?? {};\n\n const normalizedTo = getAddress(to);\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount, \"confidential-transfer-and-call\");\n }\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt(\n {\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n },\n { operation: \"confidential-transfer-and-call\" },\n );\n void swallow(\n \"transferAndCall: onEncryptComplete\",\n () => onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferAndCall\",\n config: confidentialTransferAndCallContract(\n this.address,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n data,\n ),\n onSubmitted: onTransferSubmitted,\n });\n }\n\n /**\n * ERC-7984 `confidentialTransferFromAndCall`: operator-initiated encrypted\n * transfer that also invokes the recipient's receiver hook in a single\n * transaction. The caller must be an approved operator for `from` and crafts\n * the opaque `data` payload — the SDK does not encode or interpret it.\n *\n * @param from - The address to transfer from (caller must be an approved operator).\n * @param to - Recipient address. Must implement the ERC-7984 receiver hook.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param data - Opaque bytes forwarded to the recipient's receiver hook.\n * @param callbacks - Optional progress callbacks.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferFromAndCall(\n * \"0xFrom\",\n * \"0xRecipient\",\n * 500n,\n * \"0xabcd\",\n * );\n * ```\n */\n async confidentialTransferFromAndCall(\n from: Address,\n to: Address,\n amount: bigint,\n data: Hex,\n callbacks?: TransferCallbacks,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferFromAndCall\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransferFromAndCall\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const normalizedFrom = getAddress(from);\n const normalizedTo = getAddress(to);\n\n // The input proof is verified against msg.sender, so it binds to the caller, not `from`.\n const { encryptedValues, inputProof } = await this.sdk.encrypt(\n {\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n },\n { operation: \"confidential-transfer-from-and-call\" },\n );\n void swallow(\n \"transferFromAndCall: onEncryptComplete\",\n () => callbacks?.onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferFromAndCall\",\n config: confidentialTransferFromAndCallContract(\n this.address,\n normalizedFrom,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n data,\n ),\n onSubmitted: callbacks?.onTransferSubmitted,\n });\n }\n\n // OPERATOR APPROVAL\n\n /**\n * Set operator approval for the confidential token.\n * Defaults to 1 hour from now if `until` is not specified.\n *\n * @param operator - The address to set as an operator.\n * @param until - Optional Unix timestamp for approval expiry. Defaults to now + 1 hour.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.setOperator(\"0xOperator\");\n * ```\n */\n async setOperator(operator: Address, until?: number): Promise<TransactionResult> {\n this.#requireSigner(\"setOperator\");\n await requireChainAlignment(\"setOperator\", this.sdk.signer, this.sdk.provider);\n const normalizedOperator = getAddress(operator);\n return this.submitTransaction({\n operation: \"setOperator\",\n config: setOperatorContract(this.address, normalizedOperator, until),\n });\n }\n\n /**\n * Check if a spender is an approved operator for a given holder.\n *\n * @param holder - The token holder address.\n * @param spender - The address to check operator approval for.\n * @returns `true` if the spender is an approved operator for the holder.\n *\n * @example\n * ```ts\n * if (await token.isOperator(\"0xHolder\", \"0xSpender\")) {\n * // spender can call transferFrom on behalf of holder\n * }\n * ```\n */\n async isOperator(holder: Address, spender: Address): Promise<boolean> {\n return this.sdk.provider.readContract(\n isOperatorContract(this.address, getAddress(holder), getAddress(spender)),\n );\n }\n\n // PROTECTED HELPERS\n\n /**\n * Read the on-chain encrypted balance for a given owner.\n *\n * @internal\n */\n protected async readConfidentialBalanceOf(owner: Address): Promise<EncryptedValue> {\n return await this.sdk.provider.readContract(confidentialBalanceOfContract(this.address, owner));\n }\n\n /**\n * Pre-flight the connected account's balance on this token before a write\n * that would otherwise move zero on a short balance.\n *\n * @internal\n */\n protected async assertConfidentialBalance(\n amount: bigint,\n telemetryOperation: TelemetryOperation,\n ): Promise<void> {\n return assertConfidentialBalance({\n operation: \"assertConfidentialBalance\",\n tokenAddress: this.address,\n amount,\n signer: this.sdk.signer,\n provider: this.sdk.provider,\n readBalance: (owner) => this.decryptBalance(owner, telemetryOperation),\n });\n }\n\n /**\n * Emit a token-scoped event through the owning {@link ZamaSDK} so that\n * subscribers see a unified stream.\n *\n * @internal\n */\n protected emit(input: ZamaSDKEventInput): void {\n this.sdk.emitEvent(input, this.address);\n }\n\n /**\n * Submit a token-scoped write transaction through the shared SDK transaction\n * pipeline. Callers keep pre-flight and operation-specific work local.\n *\n * @internal\n */\n protected async submitTransaction(params: {\n operation: TransactionOperation;\n config: WriteContractConfig;\n onSubmitted?: (txHash: Hex) => void;\n }): Promise<TransactionResult> {\n const { operation, config, onSubmitted } = params;\n return submitSdkTransaction({\n operation,\n signer: this.#requireSigner(operation),\n provider: this.sdk.provider,\n config,\n emit: (input) => this.emit(input),\n onSubmitted,\n logger: this.sdk.logger,\n });\n }\n\n /** Verify all tokens share the same SDK instance and return it. */\n private static assertSameSdk(tokens: Token[]): ZamaSDK {\n const sdk = tokens[0]!.sdk;\n for (let i = 1; i < tokens.length; i++) {\n if (tokens[i]!.sdk !== sdk) {\n throw new ConfigurationError(\n \"All tokens in a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,CAAE,MAAQ,EACrB,MAAM,IAAI,EACR,sEACF,EAGJ,OAAO,CACT,CACF"}
@@ -1,2 +0,0 @@
1
- import{S as e,i as t,r as n}from"./relayer-C3jVhqSK.js";import{A as r,D as i,E as a,F as o,H as s,L as c,M as l,O as u,P as d,c as f,j as p,k as ee,l as m,o as te,u as h,x as ne}from"./erc165-BAd2z3ay.js";import{r as g,t as _}from"./encryption-6AVd-82z.js";import{a as v,f as y,h as b,l as re,o as x,p as ie,t as ae}from"./token-CTvEGQmH.js";import{r as S,t as oe}from"./primitives-Cym-3HKa.js";import{getAddress as C,keccak256 as w,toBytes as T,zeroAddress as se}from"viem";import{z as E}from"zod/mini";function D(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}var O=class extends n{unwrapTxHash;unwrapRequestId;constructor(e,n,r){super(t.UnshieldAlreadyFinalized,e,r),this.name=`UnshieldAlreadyFinalizedError`,this.unwrapTxHash=n.unwrapTxHash,this.unwrapRequestId=n.unwrapRequestId}};const k=`InvalidUnwrapRequest`,A=w(T(`${k}(bytes32)`)).slice(0,10);function j(e){for(let t=e;t instanceof Error;t=t.cause)if(D(t)===k||t.message.includes(k)||t.message.includes(A))return!0;return!1}const M=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function N(e,t,n,r=`0x`){return{address:e,abi:M,functionName:`transferAndCall`,args:[t,n,r]}}function P(e){return e.startsWith(`0x`)?e:`0x${e}`}function F(e){return w(T(e))}function I(e){return C(P(e.slice(-40)))}function L(e){return e}function R(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function z(e,t){return C(P(R(e,t).slice(-40)))}function B(e,t){return BigInt(`0x`+R(e,t))}function V(e,t){return P(R(e,t))}const H={ConfidentialTransfer:F(`ConfidentialTransfer(address,address,bytes32)`),Wrap:F(`Wrap(address,uint256,bytes32)`),UnwrapRequested:F(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:F(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function U(e){return e.topics[0]!==H.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:I(e.topics[1]),to:I(e.topics[2]),encryptedAmount:L(e.topics[3])}}function W(e){return e.topics[0]!==H.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:I(e.topics[1]),roundedAmount:B(e.data,0),encryptedWrappedAmount:V(e.data,1)}}function G(e){return e.topics[0]!==H.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:I(e.topics[1]),unwrapRequestId:L(e.topics[2]),encryptedAmount:V(e.data,0)}}function K(e){return e.topics[0]!==H.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:I(e.topics[1]),unwrapRequestId:L(e.topics[2]),encryptedAmount:V(e.data,0),cleartextAmount:B(e.data,1)}}function q(e){return U(e)??W(e)??G(e)??K(e)}function ce(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function J(e){for(let t of e){let e=G(t);if(e)return e}return null}function le(e){for(let t of e){let e=W(t);if(e)return e}return null}const ue=[H.ConfidentialTransfer,H.Wrap,H.UnwrapRequested,H.UnwrapFinalized],Y={DelegatedForUserDecryption:F(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:F(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:I(e.topics[1]),delegate:I(e.topics[2]),contractAddress:z(e.data,0),delegationCounter:B(e.data,1),oldExpirationDate:B(e.data,2),newExpirationDate:B(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:I(e.topics[1]),delegate:I(e.topics[2]),contractAddress:z(e.data,0),delegationCounter:B(e.data,1),oldExpirationDate:B(e.data,2)}}function Q(e){return X(e)??Z(e)}function de(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function fe(e){for(let t of e){let e=X(t);if(e)return e}return null}function pe(e){for(let t of e){let e=Z(t);if(e)return e}return null}const me=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];function $(e){return`zama:pending-unshield:${oe(e)}`}const he=E.union([E.pipe(S,E.transform(e=>({unwrapTxHash:e}))),E.pipe(E.object({version:E.literal(1),unwrapTxHash:S,unwrapRequestId:E.optional(S)}),E.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function ge(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function _e(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=he.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ve(e,t){await e.delete($(t))}var ye=class extends ae{#e;#t=null;#n=null;#r(e){try{return d(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new c(e,{cause:t})}}async underlying(){return this.#f()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#f();this.#n=await this.sdk.provider.readContract(te(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#f();return this.sdk.provider.readContract(f(t,C(e),this.address))}async shield(t,r){let i=await v(`shield`,this.sdk.signer,this.sdk.provider),a=await this.isPayable(),o=await this.#f(),s=C(i.address),c;try{c=await this.sdk.provider.readContract(h(o,s))}catch(t){throw t instanceof n?t:new y(`Could not read ERC-20 balance for shield validation (token: ${o})`,{cause:e(t)})}if(c<t)throw new b(`Insufficient ERC-20 balance: requested ${t}, available ${c} (token: ${o})`,{requested:t,available:c,token:o});return a?this.#i(t,o,s,r):this.#a(t,s,r)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?C(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:N(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(t,i){this.#r(`wrap`);let a=await v(`wrap`,this.sdk.signer,this.sdk.provider),o=await this.#f(),s=C(a.address),c;try{c=await this.sdk.provider.readContract(h(o,s))}catch(t){throw t instanceof n?t:new y(`Could not read ERC-20 balance for wrap validation (token: ${o})`,{cause:e(t)})}if(c<t)throw new b(`Insufficient ERC-20 balance: requested ${t}, available ${c} (token: ${o})`,{requested:t,available:c,token:o});let l;try{l=await this.sdk.provider.readContract(f(o,s,this.address))}catch(t){throw t instanceof n?t:new y(`Could not read ERC-20 allowance for wrap validation (token: ${o})`,{cause:e(t)})}if(l<t)throw new ie(`Insufficient allowance for wrap: requested ${t}, approved ${l}. Call approveUnderlying() first (token: ${o}).`,{requested:t,available:l,token:o});let u=i?.to?C(i.to):s;return this.submitTransaction({operation:`wrap`,config:r(this.address,u,t),onSubmitted:i?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let i=n?.approvalStrategy??`exact`;i!==`skip`&&await this.#m(e,i===`max`,n);let a=n?.to?C(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:r(this.address,a,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await v(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#f(),r=C(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(f(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:m(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:m(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.#o(e,`unshield`);return p(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#p(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return p(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#p(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let r;try{r=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof n?e:new s(`Failed to get unwrap receipt`,{cause:e})}let i=this.#c(r.logs);if(await this.#l(i))throw await this.#d(`resumeUnshield`),new O(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:i});return this.#p(i,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=await _e(this.sdk.storage,this.address);return e?await this.#u(e)?(await this.#d(`getPendingUnshield`),null):e.unwrapTxHash:null}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t){this.#r(`unwrap`);let n=C((await v(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:r,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:n},{operation:t}),[o]=r;if(!o)throw new g(`Encryption returned no encrypted values`);let s=await this.submitTransaction({operation:`unwrap`,config:i(this.address,n,n,o,a)});return{...s,unwrapRequestId:this.#c(s.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=C((await v(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),t=await this.readConfidentialBalanceOf(e);if(re(t))throw new _(`Cannot unshield: balance is zero`);let n=await this.submitTransaction({operation:`unwrapAll`,config:u(this.address,e,e,t)});return{...n,unwrapRequestId:this.#c(n.receipt.logs)}}async finalizeUnwrap(e){return this.#s(e,`finalize-unwrap`)}async#s(e,t){this.#r(`finalizeUnwrap`),await x(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e],{operation:t}),r=n.clearValues[e];return l(r,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:ne(this.address,e,r,n.decryptionProof)})}#c(e){let t=J(e.filter(e=>e.address===void 0||C(e.address)===this.address));if(!t)throw new s(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t.unwrapRequestId}async#l(e){try{return await this.sdk.provider.readContract(ee(this.address,e))===se}catch{return!1}}async#u(e){let t=e.unwrapRequestId;if(t===void 0)try{let n=await this.sdk.provider.waitForTransactionReceipt(e.unwrapTxHash);t=this.#c(n.logs)}catch{return!1}return this.#l(t)}async#d(e){await p(`${e}: clearPendingUnshield`,()=>ve(this.sdk.storage,this.address),this.sdk.logger)}async#f(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(a(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#p(e,t,n,r,i){this.emit({type:o.UnshieldPhase1Submitted,txHash:t,operationId:n}),await p(`unshield: savePendingUnshield`,()=>ge(this.sdk.storage,this.address,t,e),this.sdk.logger),this.emit({type:o.UnshieldPhase2Started,operationId:n}),p(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#s(e,i)}catch(n){throw j(n)?(await this.#d(`unshield`),new O(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:o.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),p(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#d(`unshield`),a}async#m(e,t,n){this.#r(`approveUnderlying`);let r=await this.#f(),i=C((await v(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),a=await this.sdk.provider.readContract(f(r,i,this.address));if(a>=e)return;a>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:m(r,this.address,0n)});let o=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:m(r,this.address,o),onSubmitted:n?.onApprovalSubmitted})}};export{N as C,V as S,D as T,pe as _,H as a,F as b,U as c,ce as d,Z as f,fe as g,W as h,ue as i,X as l,G as m,me as n,Q as o,K as p,Y as r,de as s,ye as t,q as u,J as v,O as w,I as x,le as y};
2
- //# sourceMappingURL=wrapped-token-IDUEFpZx.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wrapped-token-IDUEFpZx.js","names":["#getUnderlying","#isPayable","#shieldViaTransferAndCall","#shieldViaApproveAndWrap","#requireSigner","#ensureAllowance","#unwrap","#finalizeUnshield","#extractUnwrapRequestId","#isUnwrapRequestConsumed","#clearStoredPendingUnshield","#isPendingUnshieldConsumed","#finalizeUnwrap","#underlying","#underlyingPromise"],"sources":["../../src/errors/revert.ts","../../src/errors/unshield.ts","../../src/abi/erc1363.abi.ts","../../src/contracts/erc1363.ts","../../src/utils/hex.ts","../../src/events/log-decoding.ts","../../src/events/onchain-events.ts","../../src/token/pending-unshield.ts","../../src/token/wrapped-token.ts"],"sourcesContent":["/**\n * Extract the decoded custom error name from a viem ContractFunctionRevertedError,\n * or `null` when the error carries no structured revert data.\n * @internal\n */\nexport function extractRevertErrorName(error: unknown): string | null {\n if (!(error instanceof Error)) {\n return null;\n }\n const cause = error.cause;\n if (typeof cause !== \"object\" || cause === null || !(\"data\" in cause)) {\n return null;\n }\n const { data } = cause;\n if (typeof data !== \"object\" || data === null || !(\"errorName\" in data)) {\n return null;\n }\n return typeof data.errorName === \"string\" ? data.errorName : null;\n}\n","import { keccak256, toBytes, type Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\nimport { extractRevertErrorName } from \"./revert\";\n\n/** Structured details identifying the consumed unwrap request. */\nexport interface UnshieldAlreadyFinalizedDetails {\n /** Transaction hash of the original unwrap request. */\n readonly unwrapTxHash: Hex;\n /** Request identifier from the `UnwrapRequested` event. */\n readonly unwrapRequestId: EncryptedValue;\n}\n\n/**\n * The unwrap request was already finalized on-chain: the underlying ERC-20\n * tokens were delivered and there is nothing left to resume. The SDK clears\n * the persisted pending-unshield pointer before throwing, so treat this as a\n * success signal: refresh balances and dismiss any \"resume unshield\" prompt.\n */\nexport class UnshieldAlreadyFinalizedError extends ZamaError {\n /** Transaction hash of the original unwrap request. */\n readonly unwrapTxHash: Hex;\n /** Request identifier from the `UnwrapRequested` event. */\n readonly unwrapRequestId: EncryptedValue;\n\n constructor(message: string, details: UnshieldAlreadyFinalizedDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.UnshieldAlreadyFinalized, message, options);\n this.name = \"UnshieldAlreadyFinalizedError\";\n this.unwrapTxHash = details.unwrapTxHash;\n this.unwrapRequestId = details.unwrapRequestId;\n }\n}\n\nconst INVALID_UNWRAP_REQUEST = \"InvalidUnwrapRequest\";\nconst INVALID_UNWRAP_REQUEST_SELECTOR = keccak256(\n toBytes(`${INVALID_UNWRAP_REQUEST}(bytes32)`),\n).slice(0, 10);\n\n/**\n * True if `error` (or anything on its `cause` chain) is the wrapper's\n * `InvalidUnwrapRequest` custom revert. Prefers viem's structured\n * `cause.data.errorName`, falling back to message matching on the error name\n * and the raw 4-byte selector for non-viem providers.\n * @internal\n */\nexport function isInvalidUnwrapRequestRevert(error: unknown): boolean {\n for (let current = error; current instanceof Error; current = current.cause) {\n if (extractRevertErrorName(current) === INVALID_UNWRAP_REQUEST) {\n return true;\n }\n if (\n current.message.includes(INVALID_UNWRAP_REQUEST) ||\n current.message.includes(INVALID_UNWRAP_REQUEST_SELECTOR)\n ) {\n return true;\n }\n }\n return false;\n}\n","// DO NOT EDIT: generated by `pnpm abi:build` from\n// contracts/out/IERC1363.sol/IERC1363.json.\n// Regenerate after `pnpm contracts:build`; `pnpm abi:check` enforces this in CI.\nexport const erc1363Abi = [\n {\n type: \"function\",\n name: \"allowance\",\n inputs: [\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n { name: \"spender\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"approve\",\n inputs: [\n { name: \"spender\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"approveAndCall\",\n inputs: [\n { name: \"spender\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"approveAndCall\",\n inputs: [\n { name: \"spender\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"data\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"balanceOf\",\n inputs: [{ name: \"account\", type: \"address\", internalType: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"supportsInterface\",\n inputs: [{ name: \"interfaceId\", type: \"bytes4\", internalType: \"bytes4\" }],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"totalSupply\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"transfer\",\n inputs: [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferAndCall\",\n inputs: [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferAndCall\",\n inputs: [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"data\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferFrom\",\n inputs: [\n { name: \"from\", type: \"address\", internalType: \"address\" },\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferFromAndCall\",\n inputs: [\n { name: \"from\", type: \"address\", internalType: \"address\" },\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"data\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferFromAndCall\",\n inputs: [\n { name: \"from\", type: \"address\", internalType: \"address\" },\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"event\",\n name: \"Approval\",\n inputs: [\n { name: \"owner\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"spender\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"value\", type: \"uint256\", indexed: false, internalType: \"uint256\" },\n ],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"Transfer\",\n inputs: [\n { name: \"from\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"to\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"value\", type: \"uint256\", indexed: false, internalType: \"uint256\" },\n ],\n anonymous: false,\n },\n] as const;\n","import type { Address, Hex } from \"viem\";\nimport { erc1363Abi } from \"../abi/erc1363.abi\";\n\n/**\n * Returns the contract config for an ERC-1363 `transferAndCall`.\n *\n * @param tokenAddress - The ERC-20 token to transfer from (the underlying, not the wrapper).\n * @param to - The recipient of the ERC-20 transfer. In `Token.shield`, this is\n * the wrapper contract whose `onTransferReceived` callback mints\n * confidential tokens to the address encoded in `data`.\n * @param amount - The amount to transfer.\n * @param data - Raw 20-byte recipient address for shield-to-other (decoded by\n * the wrapper as `address(bytes20(data))`). Empty `0x` for self-shield —\n * the wrapper falls back to `from`.\n */\nexport function transferAndCallContract(\n tokenAddress: Address,\n to: Address,\n amount: bigint,\n data: Hex = \"0x\",\n) {\n return {\n address: tokenAddress,\n abi: erc1363Abi,\n functionName: \"transferAndCall\",\n args: [to, amount, data],\n } as const;\n}\n","import type { Hex } from \"viem\";\nimport { assertCondition } from \"./assertions\";\n\n/** Normalize a un-prefixed hex payload to a 0x-prefixed `Hex` value. */\nexport function prefixHex(value: string): Hex {\n return (value.startsWith(\"0x\") ? value : `0x${value}`) as Hex;\n}\n\n/** Convert a public `Hex` value back an unprefixed format. */\nexport function unprefixHex(value: Hex): string {\n assertCondition(value.startsWith(\"0x\"), `Expected 0x-prefixed hex, got: ${value}`);\n return value.slice(2);\n}\n","/**\n * Primitives for decoding raw EVM logs without an ABI decoder.\n *\n * @internal\n */\n\nimport { getAddress, keccak256, toBytes, type Address, type Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { prefixHex } from \"../utils\";\n\n/** Hashes the canonical signature — `Joined(uint256,address,bytes32)`, not the declaration with parameter names. */\nexport function eventTopic(signature: string): Hex {\n return keccak256(toBytes(signature));\n}\n\nexport function topicToAddress(topic: Hex): Address {\n return getAddress(prefixHex(topic.slice(-40)));\n}\n\nexport function topicToBytes32(topic: Hex): EncryptedValue {\n // EVM topics are already 32-byte 0x-prefixed hex — cast directly\n return topic as EncryptedValue;\n}\n\nexport function wordAt(data: Hex, index: number): string {\n // data starts with \"0x\", each word is 64 hex chars (32 bytes)\n const start = 2 + index * 64;\n const word = data.slice(start, start + 64);\n return word.length === 64 ? word : word.padEnd(64, \"0\");\n}\n\nexport function wordToAddress(data: Hex, index: number): Address {\n return getAddress(prefixHex(wordAt(data, index).slice(-40)));\n}\n\nexport function wordToBigInt(data: Hex, index: number): bigint {\n return BigInt(\"0x\" + wordAt(data, index));\n}\n\nexport function wordToBytes32(data: Hex, index: number): EncryptedValue {\n // wordAt returns exactly 64 hex chars — prefix and cast directly\n return prefixHex(wordAt(data, index)) as EncryptedValue;\n}\n","/**\n * Framework-agnostic event decoders for confidential token contracts.\n * Works with raw log data from any provider.\n */\n\nimport type { EncryptedValue } from \"../relayer/types\";\nimport type { Address } from \"viem\";\nimport type { RawLog } from \"../types/transaction\";\nimport {\n eventTopic,\n topicToAddress,\n topicToBytes32,\n wordToAddress,\n wordToBigInt,\n wordToBytes32,\n} from \"./log-decoding\";\nexport type { RawLog } from \"../types/transaction\";\n\n// ---------------------------------------------------------------------------\n// Event topic0 constants (keccak256 of canonical signature)\n// ---------------------------------------------------------------------------\n\n/**\n * Event topic0 constants (keccak256 of the canonical Solidity signature).\n * Pass to `getLogs({ topics: [Object.values(Topics)] })` to fetch all events.\n */\nexport const Topics = {\n /** `ConfidentialTransfer(address indexed from, address indexed to, bytes32 indexed amount)` */\n ConfidentialTransfer: eventTopic(\"ConfidentialTransfer(address,address,bytes32)\"),\n /** `Wrap(address indexed to, uint256 roundedAmount, euint64 encryptedWrappedAmount)` */\n Wrap: eventTopic(\"Wrap(address,uint256,bytes32)\"),\n /** `UnwrapRequested(address indexed receiver, bytes32 indexed unwrapRequestId, bytes32 amount)` */\n UnwrapRequested: eventTopic(\"UnwrapRequested(address,bytes32,bytes32)\"),\n /** `UnwrapFinalized(address indexed receiver, bytes32 indexed unwrapRequestId, bytes32 encryptedAmount, uint64 cleartextAmount)` */\n UnwrapFinalized: eventTopic(\"UnwrapFinalized(address,bytes32,bytes32,uint64)\"),\n} as const;\n\n// ---------------------------------------------------------------------------\n// Typed event interfaces\n// ---------------------------------------------------------------------------\n\n/** Decoded `ConfidentialTransfer` event — an encrypted token transfer. */\nexport interface ConfidentialTransferEvent {\n /** Event name discriminant. */\n readonly eventName: \"ConfidentialTransfer\";\n /** Sender address. */\n readonly from: Address;\n /** Receiver address. */\n readonly to: Address;\n /** FHE encrypted value for the transferred amount. */\n readonly encryptedAmount: EncryptedValue;\n}\n\n/**\n * Decoded `Wrap` event — an ERC-20 shield (wrap) operation. Emitted alongside a\n * `ConfidentialTransfer(from=zeroAddress, ...)`; `encryptedWrappedAmount` is the same FHE\n * handle that lands in `ConfidentialTransfer.encryptedAmount`.\n */\nexport interface WrapEvent {\n /** Event name discriminant. */\n readonly eventName: \"Wrap\";\n /** Receiver of the minted confidential tokens. */\n readonly to: Address;\n /** Cleartext underlying ERC-20 tokens deposited, rounded down to a multiple of the rate. */\n readonly roundedAmount: bigint;\n /** FHE encrypted value for the wrapped (minted) amount. */\n readonly encryptedWrappedAmount: EncryptedValue;\n}\n\n/** Decoded `UnwrapRequested` event — an unshield request submitted. */\nexport interface UnwrapRequestedEvent {\n /** Event name discriminant. */\n readonly eventName: \"UnwrapRequested\";\n /** Address that will receive the unwrapped ERC-20 tokens. */\n readonly receiver: Address;\n /** FHE encrypted value for the requested unshield amount. */\n readonly encryptedAmount: EncryptedValue;\n /** Request identifier from the `UnwrapRequested` event topic. */\n readonly unwrapRequestId: EncryptedValue;\n}\n\n/** Decoded `UnwrapFinalized` event — an unshield completed on-chain. */\nexport interface UnwrapFinalizedEvent {\n /** Event name discriminant. */\n readonly eventName: \"UnwrapFinalized\";\n /** Address receiving the unwrapped ERC-20 tokens. */\n readonly receiver: Address;\n /** FHE encrypted value of the burnt confidential balance. */\n readonly encryptedAmount: EncryptedValue;\n /** Cleartext amount of underlying ERC-20 tokens returned. */\n readonly cleartextAmount: bigint;\n /** Request identifier from the `UnwrapFinalized` event topic. */\n readonly unwrapRequestId: EncryptedValue;\n}\n\n/** Union of all decoded confidential token event types. */\nexport type OnChainEvent =\n | ConfidentialTransferEvent\n | WrapEvent\n | UnwrapRequestedEvent\n | UnwrapFinalizedEvent;\n\n// ---------------------------------------------------------------------------\n// Individual decoders\n// ---------------------------------------------------------------------------\n\n/**\n * ConfidentialTransfer(address indexed from, address indexed to, bytes32 indexed amount)\n * All 3 params indexed → topics[1..3], no data.\n */\nexport function decodeConfidentialTransfer(log: RawLog): ConfidentialTransferEvent | null {\n if (log.topics[0] !== Topics.ConfidentialTransfer) {\n return null;\n }\n if (log.topics.length < 4) {\n return null;\n }\n\n return {\n eventName: \"ConfidentialTransfer\",\n from: topicToAddress(log.topics[1]!),\n to: topicToAddress(log.topics[2]!),\n encryptedAmount: topicToBytes32(log.topics[3]!),\n };\n}\n\n/**\n * Wrap(address indexed to, uint256 roundedAmount, euint64 encryptedWrappedAmount)\n * Indexed: to (topics[1])\n * Data: roundedAmount (uint256), encryptedWrappedAmount (bytes32)\n */\nexport function decodeWrap(log: RawLog): WrapEvent | null {\n if (log.topics[0] !== Topics.Wrap) {\n return null;\n }\n if (log.topics.length < 2) {\n return null;\n }\n\n return {\n eventName: \"Wrap\",\n to: topicToAddress(log.topics[1]!),\n roundedAmount: wordToBigInt(log.data, 0),\n encryptedWrappedAmount: wordToBytes32(log.data, 1),\n };\n}\n\n/**\n * UnwrapRequested(address indexed receiver, bytes32 indexed unwrapRequestId, bytes32 amount)\n */\nexport function decodeUnwrapRequested(log: RawLog): UnwrapRequestedEvent | null {\n if (log.topics[0] !== Topics.UnwrapRequested) {\n return null;\n }\n if (log.topics.length < 3) {\n return null;\n }\n\n return {\n eventName: \"UnwrapRequested\",\n receiver: topicToAddress(log.topics[1]!),\n unwrapRequestId: topicToBytes32(log.topics[2]!),\n encryptedAmount: wordToBytes32(log.data, 0),\n };\n}\n\n/**\n * UnwrapFinalized(address indexed receiver, bytes32 indexed unwrapRequestId, bytes32 encryptedAmount, uint64 cleartextAmount)\n */\nexport function decodeUnwrapFinalized(log: RawLog): UnwrapFinalizedEvent | null {\n if (log.topics[0] !== Topics.UnwrapFinalized) {\n return null;\n }\n if (log.topics.length < 3) {\n return null;\n }\n\n return {\n eventName: \"UnwrapFinalized\",\n receiver: topicToAddress(log.topics[1]!),\n unwrapRequestId: topicToBytes32(log.topics[2]!),\n encryptedAmount: wordToBytes32(log.data, 0),\n cleartextAmount: wordToBigInt(log.data, 1),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Convenience helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Try all decoders on a single log and return the first match, or `null`.\n *\n * @example\n * ```ts\n * const event = decodeOnChainEvent(log);\n * if (event?.eventName === \"ConfidentialTransfer\") {\n * console.log(event.from, event.to);\n * }\n * ```\n */\nexport function decodeOnChainEvent(log: RawLog): OnChainEvent | null {\n return (\n decodeConfidentialTransfer(log) ??\n decodeWrap(log) ??\n decodeUnwrapRequested(log) ??\n decodeUnwrapFinalized(log)\n );\n}\n\n/**\n * Batch-decode an array of logs, skipping unrecognized entries.\n *\n * @example\n * ```ts\n * const events = decodeOnChainEvents(receipt.logs);\n * ```\n */\nexport function decodeOnChainEvents(logs: readonly RawLog[]): OnChainEvent[] {\n const events: OnChainEvent[] = [];\n for (const log of logs) {\n const event = decodeOnChainEvent(log);\n if (event) {\n events.push(event);\n }\n }\n return events;\n}\n\n/**\n * Find the first {@link UnwrapRequestedEvent} in a logs array.\n *\n * @example\n * ```ts\n * const event = findUnwrapRequested(receipt.logs);\n * if (event) console.log(event.receiver, event.encryptedAmount);\n * ```\n */\nexport function findUnwrapRequested(logs: readonly RawLog[]): UnwrapRequestedEvent | null {\n for (const log of logs) {\n const event = decodeUnwrapRequested(log);\n if (event) {\n return event;\n }\n }\n return null;\n}\n\n/**\n * Find the first {@link WrapEvent} in a logs array.\n *\n * @example\n * ```ts\n * const event = findWrap(receipt.logs);\n * if (event) console.log(event.to, event.roundedAmount);\n * ```\n */\nexport function findWrap(logs: readonly RawLog[]): WrapEvent | null {\n for (const log of logs) {\n const event = decodeWrap(log);\n if (event) {\n return event;\n }\n }\n return null;\n}\n\n/**\n * All confidential token event topic0 hashes.\n * Pass to `getLogs({ topics: [TOKEN_TOPICS] })` to fetch\n * all confidential token events in a single RPC call.\n */\nexport const TOKEN_TOPICS = [\n Topics.ConfidentialTransfer,\n Topics.Wrap,\n Topics.UnwrapRequested,\n Topics.UnwrapFinalized,\n] as const;\n\n// ---------------------------------------------------------------------------\n// ACL delegation event topic0 constants\n// ---------------------------------------------------------------------------\n\n/**\n * ACL delegation event topic0 constants (keccak256 of the canonical Solidity signature).\n * These are ACL events, NOT token events — they are emitted by the ACL contract.\n */\nexport const AclTopics = {\n /** `DelegatedForUserDecryption(address indexed delegator, address indexed delegate, address contractAddress, uint64 delegationCounter, uint64 oldExpirationDate, uint64 newExpirationDate)` */\n DelegatedForUserDecryption: eventTopic(\n \"DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)\",\n ),\n /** `RevokedDelegationForUserDecryption(address indexed delegator, address indexed delegate, address contractAddress, uint64 delegationCounter, uint64 oldExpirationDate)` */\n RevokedDelegationForUserDecryption: eventTopic(\n \"RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)\",\n ),\n} as const;\n\n// ---------------------------------------------------------------------------\n// ACL delegation event interfaces\n// ---------------------------------------------------------------------------\n\n/** Decoded `DelegatedForUserDecryption` event — a delegation was created or renewed. */\nexport interface DelegatedForUserDecryptionEvent {\n /** Event name discriminant. */\n readonly eventName: \"DelegatedForUserDecryption\";\n /** Address of the delegator (the account granting access). */\n readonly delegator: Address;\n /** Address of the delegate (the account receiving access). */\n readonly delegate: Address;\n /** Contract address the delegation applies to. */\n readonly contractAddress: Address;\n /** Monotonic delegation counter. */\n readonly delegationCounter: bigint;\n /** Previous expiration timestamp (0 if first delegation). */\n readonly oldExpirationDate: bigint;\n /** New expiration timestamp. */\n readonly newExpirationDate: bigint;\n}\n\n/** Decoded `RevokedDelegationForUserDecryption` event — a delegation was revoked. */\nexport interface RevokedDelegationForUserDecryptionEvent {\n /** Event name discriminant. */\n readonly eventName: \"RevokedDelegationForUserDecryption\";\n /** Address of the delegator. */\n readonly delegator: Address;\n /** Address of the delegate. */\n readonly delegate: Address;\n /** Contract address the revocation applies to. */\n readonly contractAddress: Address;\n /** Monotonic delegation counter. */\n readonly delegationCounter: bigint;\n /** Expiration date that was active before revocation. */\n readonly oldExpirationDate: bigint;\n}\n\n/** Union of all decoded ACL delegation event types. */\nexport type AclEvent = DelegatedForUserDecryptionEvent | RevokedDelegationForUserDecryptionEvent;\n\n// ---------------------------------------------------------------------------\n// ACL delegation event decoders\n// ---------------------------------------------------------------------------\n\n/**\n * DelegatedForUserDecryption(address indexed delegator, address indexed delegate,\n * address contractAddress, uint64 delegationCounter, uint64 oldExpirationDate, uint64 newExpirationDate)\n * Indexed: delegator (topics[1]), delegate (topics[2])\n * Data: contractAddress, delegationCounter, oldExpirationDate, newExpirationDate\n */\nexport function decodeDelegatedForUserDecryption(\n log: RawLog,\n): DelegatedForUserDecryptionEvent | null {\n if (log.topics[0] !== AclTopics.DelegatedForUserDecryption) {\n return null;\n }\n if (log.topics.length < 3) {\n return null;\n }\n\n return {\n eventName: \"DelegatedForUserDecryption\",\n delegator: topicToAddress(log.topics[1]!),\n delegate: topicToAddress(log.topics[2]!),\n contractAddress: wordToAddress(log.data, 0),\n delegationCounter: wordToBigInt(log.data, 1),\n oldExpirationDate: wordToBigInt(log.data, 2),\n newExpirationDate: wordToBigInt(log.data, 3),\n };\n}\n\n/**\n * RevokedDelegationForUserDecryption(address indexed delegator, address indexed delegate,\n * address contractAddress, uint64 delegationCounter, uint64 oldExpirationDate)\n * Indexed: delegator (topics[1]), delegate (topics[2])\n * Data: contractAddress, delegationCounter, oldExpirationDate\n */\nexport function decodeRevokedDelegationForUserDecryption(\n log: RawLog,\n): RevokedDelegationForUserDecryptionEvent | null {\n if (log.topics[0] !== AclTopics.RevokedDelegationForUserDecryption) {\n return null;\n }\n if (log.topics.length < 3) {\n return null;\n }\n\n return {\n eventName: \"RevokedDelegationForUserDecryption\",\n delegator: topicToAddress(log.topics[1]!),\n delegate: topicToAddress(log.topics[2]!),\n contractAddress: wordToAddress(log.data, 0),\n delegationCounter: wordToBigInt(log.data, 1),\n oldExpirationDate: wordToBigInt(log.data, 2),\n };\n}\n\n/**\n * Try all ACL delegation decoders on a single log and return the first match, or `null`.\n */\nexport function decodeAclEvent(log: RawLog): AclEvent | null {\n return decodeDelegatedForUserDecryption(log) ?? decodeRevokedDelegationForUserDecryption(log);\n}\n\n/**\n * Batch-decode an array of logs for ACL delegation events, skipping unrecognized entries.\n */\nexport function decodeAclEvents(logs: readonly RawLog[]): AclEvent[] {\n const events: AclEvent[] = [];\n for (const log of logs) {\n const event = decodeAclEvent(log);\n if (event) {\n events.push(event);\n }\n }\n return events;\n}\n\n/**\n * Find the first {@link DelegatedForUserDecryptionEvent} in a logs array.\n */\nexport function findDelegatedForUserDecryption(\n logs: readonly RawLog[],\n): DelegatedForUserDecryptionEvent | null {\n for (const log of logs) {\n const event = decodeDelegatedForUserDecryption(log);\n if (event) {\n return event;\n }\n }\n return null;\n}\n\n/**\n * Find the first {@link RevokedDelegationForUserDecryptionEvent} in a logs array.\n */\nexport function findRevokedDelegationForUserDecryption(\n logs: readonly RawLog[],\n): RevokedDelegationForUserDecryptionEvent | null {\n for (const log of logs) {\n const event = decodeRevokedDelegationForUserDecryption(log);\n if (event) {\n return event;\n }\n }\n return null;\n}\n\n/**\n * Both ACL delegation event topic0 hashes.\n * Pass to `getLogs({ topics: [ACL_TOPICS] })` to fetch\n * all delegation events in a single RPC call.\n */\nexport const ACL_TOPICS = [\n AclTopics.DelegatedForUserDecryption,\n AclTopics.RevokedDelegationForUserDecryption,\n] as const;\n","import type { Address, Hex } from \"viem\";\nimport { z } from \"zod/mini\";\nimport { checksum, hex } from \"../schemas/primitives\";\nimport type { GenericStorage } from \"../types\";\nimport type { EncryptedValue } from \"../relayer/types\";\n\nconst STORAGE_PREFIX = \"zama:pending-unshield:\";\nconst CURRENT_VERSION = 1;\n\n/**\n * Persisted state for an in-progress unshield request.\n * Used to resume an interrupted unshield after page reload.\n *\n * @internal\n */\nexport interface PendingUnshieldRequest {\n /** Transaction hash of the original unwrap call. */\n readonly unwrapTxHash: Hex;\n /**\n * Request identifier from the `UnwrapRequested` event.\n * Always populated for entries persisted by this SDK version; pass it as\n * `unwrapRequestId` to `finalizeUnwrap`. Absent only when re-loading a\n * pending unshield serialized by an older SDK version that did not\n * record this field — in that case pass the `encryptedAmount` from the\n * `UnwrapRequested` event to `finalizeUnwrap` instead.\n */\n readonly unwrapRequestId?: EncryptedValue;\n}\n\ninterface StoredPendingUnshieldRequest extends PendingUnshieldRequest {\n readonly version: typeof CURRENT_VERSION;\n}\n\nfunction storageKey(wrapperAddress: Address): string {\n return `${STORAGE_PREFIX}${checksum(wrapperAddress)}`;\n}\n\nconst PendingUnshieldRequestSchema = z.union([\n z.pipe(\n hex,\n z.transform((unwrapTxHash: Hex) => ({ unwrapTxHash })),\n ),\n z.pipe(\n z.object({\n version: z.literal(CURRENT_VERSION),\n unwrapTxHash: hex,\n unwrapRequestId: z.optional(hex),\n }),\n z.transform(\n ({\n unwrapTxHash,\n unwrapRequestId,\n }: {\n version: typeof CURRENT_VERSION;\n unwrapTxHash: Hex;\n unwrapRequestId?: Hex;\n }) => ({ unwrapTxHash, unwrapRequestId }),\n ),\n ),\n]);\n\n/**\n * Persist the unwrap tx hash so an interrupted unshield can be resumed later\n * (e.g. after a page reload).\n *\n * @internal\n */\nexport async function savePendingUnshield(\n storage: GenericStorage,\n wrapperAddress: Address,\n unwrapTxHash: Hex,\n unwrapRequestId?: EncryptedValue,\n): Promise<void> {\n if (unwrapRequestId === undefined) {\n await storage.set(storageKey(wrapperAddress), unwrapTxHash);\n return;\n }\n\n await storage.set(storageKey(wrapperAddress), {\n version: CURRENT_VERSION,\n unwrapTxHash,\n unwrapRequestId,\n } satisfies StoredPendingUnshieldRequest);\n}\n\n/**\n * Load a previously saved unwrap tx hash, or `null` if none exists.\n *\n * @internal\n */\nexport async function loadPendingUnshield(\n storage: GenericStorage,\n wrapperAddress: Address,\n): Promise<Hex | null> {\n const request = await loadPendingUnshieldRequest(storage, wrapperAddress);\n return request?.unwrapTxHash ?? null;\n}\n\n/**\n * Load a previously saved unwrap request, including `unwrapRequestId` when available.\n *\n * `resumeUnshield()` only needs `unwrapTxHash`: it reloads the transaction receipt and\n * rediscovers the right finalize input from the emitted `UnwrapRequested` event.\n * Use `unwrapRequestId` directly only for custom flows that call `finalizeUnwrap()`\n * without reloading the original unwrap receipt.\n *\n * @internal\n */\nexport async function loadPendingUnshieldRequest(\n storage: GenericStorage,\n wrapperAddress: Address,\n): Promise<PendingUnshieldRequest | null> {\n const key = storageKey(wrapperAddress);\n const value = await storage.get<Hex | StoredPendingUnshieldRequest>(key);\n if (value === null || value === undefined) {\n return null;\n }\n const parsed = PendingUnshieldRequestSchema.safeParse(value);\n if (!parsed.success) {\n await storage.delete(key);\n return null;\n }\n return parsed.data as PendingUnshieldRequest;\n}\n\n/**\n * Clear the saved unwrap tx hash after a successful finalization.\n *\n * @internal\n */\nexport async function clearPendingUnshield(\n storage: GenericStorage,\n wrapperAddress: Address,\n): Promise<void> {\n await storage.delete(storageKey(wrapperAddress));\n}\n","import { getAddress, zeroAddress, type Address, type Hex } from \"viem\";\nimport {\n allowanceContract,\n approveContract,\n balanceOfContract,\n finalizeUnwrapContract,\n isPayableTokenContract,\n transferAndCallContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n unwrapRequesterContract,\n wrapContract,\n} from \"../contracts\";\nimport {\n DecryptionFailedError,\n ERC20ReadFailedError,\n EncryptionFailedError,\n InsufficientAllowanceError,\n InsufficientERC20BalanceError,\n SignerNotConfiguredError,\n TransactionRevertedError,\n UnshieldAlreadyFinalizedError,\n ZamaError,\n} from \"../errors\";\nimport { isInvalidUnwrapRequestRevert } from \"../errors/unshield\";\nimport { findUnwrapRequested } from \"../events/onchain-events\";\nimport { ZamaSDKEvents } from \"../events/sdk-events\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport type {\n GenericSigner,\n ShieldCallbacks,\n ShieldOptions,\n TransactionResult,\n UnshieldCallbacks,\n UnshieldOptions,\n UnwrapResult,\n WrapOptions,\n} from \"../types\";\nimport type { RawLog } from \"../types/transaction\";\nimport { toError } from \"../utils\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\nimport { assertBigint, assertNonNullable } from \"../utils/assertions\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport type { TelemetryOperation } from \"../telemetry\";\nimport { swallow } from \"../utils/swallow\";\nimport {\n clearPendingUnshield,\n loadPendingUnshieldRequest,\n savePendingUnshield,\n type PendingUnshieldRequest,\n} from \"./pending-unshield\";\nimport { Token } from \"./token\";\n\n/**\n * Confidential ERC-20 wrapper (ERC-7984 ERC20Wrapper).\n *\n * Extends {@link Token} with wrapper-specific operations:\n * - `shield` / `unshield` — convert between the underlying ERC-20 and confidential balance\n * - `unwrap` / `unwrapAll` / `finalizeUnwrap` — low-level two-phase primitives\n * - `underlying` / `allowance` — wrapper reads\n *\n * `WrappedToken.address` is the wrapper contract address itself — the wrapper\n * IS the confidential token.\n */\nexport class WrappedToken extends Token {\n #underlying: Address | undefined;\n #underlyingPromise: Promise<Address> | null = null;\n #isPayable: boolean | null = null;\n\n /** Resolve `sdk.signer` or throw {@link SignerNotConfiguredError} tagged with `operation`. */\n #requireSigner(operation: string): GenericSigner {\n try {\n assertNonNullable(this.sdk.signer, \"WrappedToken.sdk.signer\");\n return this.sdk.signer;\n } catch (cause) {\n throw new SignerNotConfiguredError(operation, { cause });\n }\n }\n\n // WRAPPER READS\n\n /**\n * Read the underlying ERC-20 token address from the wrapper contract.\n *\n * @returns The underlying ERC-20 token address.\n */\n async underlying(): Promise<Address> {\n return this.#getUnderlying();\n }\n\n /**\n * Check whether the underlying ERC-20 supports ERC-1363 (payable token).\n * Result is cached per WrappedToken instance (negative results included):\n * once we know an underlying does not support ERC-1363, subsequent shields\n * go straight to the `approve` + `wrap` path without re-probing.\n */\n async isPayable(): Promise<boolean> {\n if (this.#isPayable !== null) {\n return this.#isPayable;\n }\n try {\n const underlying = await this.#getUnderlying();\n this.#isPayable = await this.sdk.provider.readContract(isPayableTokenContract(underlying));\n } catch {\n this.#isPayable = false;\n }\n return this.#isPayable;\n }\n\n /**\n * Read the ERC-20 allowance granted by `owner` to this wrapper for the\n * underlying token.\n *\n * @param owner - The owner address whose allowance to read.\n * @returns The current allowance as a bigint.\n */\n async allowance(owner: Address): Promise<bigint> {\n const underlying = await this.#getUnderlying();\n return this.sdk.provider.readContract(\n allowanceContract(underlying, getAddress(owner), this.address),\n );\n }\n\n // SHIELD (ERC-20 → confidential)\n\n /**\n * Shield public ERC-20 tokens into confidential tokens.\n *\n * The execution path is decided automatically by ERC-165 introspection on\n * the underlying ERC-20:\n * - **`transferAndCall`** (single tx): when the underlying supports\n * ERC-1363, no approval is required — the wrapper's `onTransferReceived`\n * callback mints confidential tokens directly. `approvalStrategy` is\n * **ignored** on this path. See {@link ShieldPath}.\n * - **`approveAndWrap`** (two-tx fallback): otherwise, an `approve` is\n * followed by a `wrap`. Approval is controlled by `approvalStrategy`\n * (`\"exact\"` by default, `\"max\"` for unlimited, `\"skip\"` to opt out).\n *\n * The ERC-20 balance is validated before submitting (public read, no\n * signing required) so the call works for all wallet types, including\n * smart wallets.\n *\n * @param amount - The plaintext amount to shield.\n * @param options - Optional: `approvalStrategy`, `to`, callbacks.\n * @returns The transaction hash and mined receipt.\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the ERC-20 balance is less than `amount`. {@link InsufficientERC20BalanceError}\n * @throws if the ERC-20 approval or shield transaction reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await wrappedToken.shield(1000n);\n * ```\n */\n async shield(amount: bigint, options?: ShieldOptions): Promise<TransactionResult> {\n const account = await requireAlignedWalletAccount(\"shield\", this.sdk.signer, this.sdk.provider);\n\n const isPayableToken = await this.isPayable();\n const underlying = await this.#getUnderlying();\n const userAddress = getAddress(account.address);\n\n // ERC-20 balance check always runs (public read, no signing needed, works for all wallet types)\n let erc20Balance: bigint;\n try {\n erc20Balance = await this.sdk.provider.readContract(\n balanceOfContract(underlying, userAddress),\n );\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new ERC20ReadFailedError(\n `Could not read ERC-20 balance for shield validation (token: ${underlying})`,\n { cause: toError(error) },\n );\n }\n if (erc20Balance < amount) {\n throw new InsufficientERC20BalanceError(\n `Insufficient ERC-20 balance: requested ${amount}, available ${erc20Balance} (token: ${underlying})`,\n { requested: amount, available: erc20Balance, token: underlying },\n );\n }\n\n if (isPayableToken) {\n return this.#shieldViaTransferAndCall(amount, underlying, userAddress, options);\n }\n return this.#shieldViaApproveAndWrap(amount, userAddress, options);\n }\n\n async #shieldViaTransferAndCall(\n amount: bigint,\n underlying: Address,\n userAddress: Address,\n options?: ShieldOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"shield\");\n const recipient = options?.to ? getAddress(options.to) : userAddress;\n // ERC7984ERC20Wrapper.onTransferReceived decodes the recipient via\n // `address(bytes20(data))` — i.e. the first 20 bytes of `data`. We pass\n // the raw 20-byte address (not ABI-encoded), and the empty payload `0x`\n // for self-shield so the wrapper falls back to `from`.\n const data: Hex = recipient === userAddress ? \"0x\" : recipient;\n\n return this.submitTransaction({\n operation: \"shield:transferAndCall\",\n config: transferAndCallContract(underlying, this.address, amount, data),\n onSubmitted: options?.onShieldSubmitted,\n });\n }\n\n /**\n * Wrap already-approved underlying ERC-20 into confidential tokens.\n *\n * Escape hatch for splitting shield across two signatures: call\n * {@link approveUnderlying} first, then `wrap`. Most callers should use\n * {@link shield}, which routes and orchestrates approval automatically.\n *\n * Validates the ERC-20 balance and the allowance granted to this wrapper\n * (public reads, no signing) and fails early with a clear error.\n *\n * @param amount - The plaintext amount to wrap.\n * @param options - Optional `to` recipient and `onWrapSubmitted` callback.\n * @returns The transaction hash and mined receipt.\n * @throws if reading the ERC-20 balance or allowance fails. {@link ERC20ReadFailedError}\n * @throws if the ERC-20 balance is less than `amount`. {@link InsufficientERC20BalanceError}\n * @throws if the allowance granted to the wrapper is less than `amount`. {@link InsufficientAllowanceError}\n *\n * @example\n * ```ts\n * await wrappedToken.approveUnderlying(1000n);\n * await wrappedToken.wrap(1000n);\n * ```\n */\n async wrap(amount: bigint, options?: WrapOptions): Promise<TransactionResult> {\n this.#requireSigner(\"wrap\");\n const account = await requireAlignedWalletAccount(\"wrap\", this.sdk.signer, this.sdk.provider);\n const underlying = await this.#getUnderlying();\n const userAddress = getAddress(account.address);\n\n let erc20Balance: bigint;\n try {\n erc20Balance = await this.sdk.provider.readContract(\n balanceOfContract(underlying, userAddress),\n );\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new ERC20ReadFailedError(\n `Could not read ERC-20 balance for wrap validation (token: ${underlying})`,\n { cause: toError(error) },\n );\n }\n if (erc20Balance < amount) {\n throw new InsufficientERC20BalanceError(\n `Insufficient ERC-20 balance: requested ${amount}, available ${erc20Balance} (token: ${underlying})`,\n { requested: amount, available: erc20Balance, token: underlying },\n );\n }\n\n let allowance: bigint;\n try {\n allowance = await this.sdk.provider.readContract(\n allowanceContract(underlying, userAddress, this.address),\n );\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new ERC20ReadFailedError(\n `Could not read ERC-20 allowance for wrap validation (token: ${underlying})`,\n { cause: toError(error) },\n );\n }\n if (allowance < amount) {\n throw new InsufficientAllowanceError(\n `Insufficient allowance for wrap: requested ${amount}, approved ${allowance}. Call approveUnderlying() first (token: ${underlying}).`,\n { requested: amount, available: allowance, token: underlying },\n );\n }\n\n const recipient = options?.to ? getAddress(options.to) : userAddress;\n return this.submitTransaction({\n operation: \"wrap\",\n config: wrapContract(this.address, recipient, amount),\n onSubmitted: options?.onWrapSubmitted,\n });\n }\n\n async #shieldViaApproveAndWrap(\n amount: bigint,\n userAddress: Address,\n options?: ShieldOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"shield\");\n const strategy = options?.approvalStrategy ?? \"exact\";\n if (strategy !== \"skip\") {\n await this.#ensureAllowance(amount, strategy === \"max\", options);\n }\n const recipient = options?.to ? getAddress(options.to) : userAddress;\n return this.submitTransaction({\n operation: \"shield:approveAndWrap\",\n config: wrapContract(this.address, recipient, amount),\n onSubmitted: options?.onShieldSubmitted,\n });\n }\n\n /**\n * Approve this wrapper contract to spend the underlying ERC-20.\n * Defaults to max uint256. Resets to zero first if there's an existing\n * non-zero allowance (required by tokens like USDT).\n *\n * @param amount - Optional approval amount. Defaults to max uint256.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * await wrappedToken.approveUnderlying(); // max approval\n * await wrappedToken.approveUnderlying(1000n); // exact amount\n * ```\n */\n async approveUnderlying(amount?: bigint): Promise<TransactionResult> {\n this.#requireSigner(\"approveUnderlying\");\n const account = await requireAlignedWalletAccount(\n \"approveUnderlying\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const underlying = await this.#getUnderlying();\n const userAddress = getAddress(account.address);\n\n const approvalAmount = amount ?? 2n ** 256n - 1n;\n\n if (approvalAmount > 0n) {\n const currentAllowance = await this.sdk.provider.readContract(\n allowanceContract(underlying, userAddress, this.address),\n );\n\n if (currentAllowance > 0n) {\n await this.submitTransaction({\n operation: \"approveUnderlying:reset\",\n config: approveContract(underlying, this.address, 0n),\n });\n }\n }\n\n return this.submitTransaction({\n operation: \"approveUnderlying\",\n config: approveContract(underlying, this.address, approvalAmount),\n });\n }\n\n // UNSHIELD (confidential → ERC-20)\n\n /**\n * Unshield a specific amount and finalize in one call.\n * Orchestrates: unshield → wait for receipt → parse event → finalize.\n *\n * By default, the SDK validates the confidential balance before submitting.\n * Set `skipBalanceCheck: true` to bypass this validation (e.g. for smart wallets).\n *\n * @param amount - The plaintext amount to unshield.\n * @param options - Optional: `skipBalanceCheck` (default `false`), callbacks.\n * @returns The finalize transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await wrappedToken.unshield(500n);\n * ```\n */\n async unshield(amount: bigint, options?: UnshieldOptions): Promise<TransactionResult> {\n const {\n skipBalanceCheck = false,\n onUnwrapSubmitted,\n onFinalizing,\n onFinalizeSubmitted,\n } = options ?? {};\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount, \"unshield\");\n }\n\n const callbacks: UnshieldCallbacks = { onFinalizing, onFinalizeSubmitted };\n const operationId = crypto.randomUUID();\n const unwrapResult = await this.#unwrap(amount, \"unshield\");\n void swallow(\n \"unshield: onUnwrapSubmitted\",\n () => onUnwrapSubmitted?.(unwrapResult.txHash),\n this.sdk.logger,\n );\n // Reuse the id the unwrap already decoded — no second receipt fetch or decode.\n return this.#finalizeUnshield(\n unwrapResult.unwrapRequestId,\n unwrapResult.txHash,\n operationId,\n callbacks,\n \"unshield\",\n );\n }\n\n /**\n * Unshield the entire balance and finalize in one call.\n * Orchestrates: unshieldAll → wait for receipt → parse event → finalize.\n *\n * @param callbacks - Optional progress callbacks for each phase.\n * @returns The finalize transaction hash and mined receipt.\n * @throws if the balance is zero. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const txHash = await wrappedToken.unshieldAll();\n * ```\n */\n async unshieldAll(callbacks?: UnshieldCallbacks): Promise<TransactionResult> {\n const operationId = crypto.randomUUID();\n const unwrapResult = await this.unwrapAll();\n void swallow(\n \"unshieldAll: onUnwrapSubmitted\",\n () => callbacks?.onUnwrapSubmitted?.(unwrapResult.txHash),\n this.sdk.logger,\n );\n // Reuse the id `unwrapAll()` already decoded — no second receipt fetch or decode.\n return this.#finalizeUnshield(\n unwrapResult.unwrapRequestId,\n unwrapResult.txHash,\n operationId,\n callbacks,\n \"unshield-all\",\n );\n }\n\n /**\n * Resume an in-progress unshield from an existing unwrap tx hash.\n * Useful when the user already submitted the unwrap but the finalize step\n * was interrupted (e.g. page reload, network error).\n *\n * @param unwrapTxHash - The transaction hash of the previously submitted unwrap.\n * @param callbacks - Optional progress callbacks.\n * @returns The finalize transaction hash and mined receipt.\n * @throws if the unwrap request was already finalized on-chain; the persisted\n * pending-unshield state is cleared first. {@link UnshieldAlreadyFinalizedError}\n *\n * @example\n * ```ts\n * const txHash = await wrappedToken.resumeUnshield(previousUnwrapTxHash);\n * ```\n */\n async resumeUnshield(\n unwrapTxHash: Hex,\n callbacks?: UnshieldCallbacks,\n ): Promise<TransactionResult> {\n // The only entry point that starts from a bare hash, so it's the only one\n // that has to fetch the receipt and decode the id from chain.\n let receipt;\n try {\n receipt = await this.sdk.provider.waitForTransactionReceipt(unwrapTxHash);\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new TransactionRevertedError(\"Failed to get unwrap receipt\", { cause: error });\n }\n const unwrapRequestId = this.#extractUnwrapRequestId(receipt.logs);\n if (await this.#isUnwrapRequestConsumed(unwrapRequestId)) {\n await this.#clearStoredPendingUnshield(\"resumeUnshield\");\n throw new UnshieldAlreadyFinalizedError(\n \"Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.\",\n { unwrapTxHash, unwrapRequestId },\n );\n }\n return this.#finalizeUnshield(\n unwrapRequestId,\n unwrapTxHash,\n crypto.randomUUID(),\n callbacks,\n \"resume-unshield\",\n );\n }\n\n /**\n * Return the unwrap tx hash of an unshield that was interrupted between its\n * two phases, or `null` if none is pending for this wrapper.\n *\n * The SDK persists this automatically when {@link unshield}/{@link unshieldAll}\n * submit phase 1, and clears it once phase 2 finalizes. Use the returned hash\n * to surface a \"resume\" affordance, then pass it to {@link resumeUnshield}.\n * Resuming is intentionally caller-driven — auto-resuming on load would fire a\n * wallet transaction unprompted.\n *\n * The pointer is verified on-chain before it is reported: if the unwrap\n * request was already finalized (e.g. the tab closed before the SDK could\n * clear storage), the stale pointer is cleared and `null` is returned. When\n * the verification read fails, the pointer is returned unverified: a\n * network error never deletes recovery state.\n *\n * @returns The pending unwrap tx hash, or `null`.\n *\n * @example\n * ```ts\n * const unwrapTxHash = await wrappedToken.getPendingUnshield();\n * if (unwrapTxHash) await wrappedToken.resumeUnshield(unwrapTxHash);\n * ```\n */\n async getPendingUnshield(): Promise<Hex | null> {\n const pending = await loadPendingUnshieldRequest(this.sdk.storage, this.address);\n if (!pending) {\n return null;\n }\n if (await this.#isPendingUnshieldConsumed(pending)) {\n await this.#clearStoredPendingUnshield(\"getPendingUnshield\");\n return null;\n }\n return pending.unwrapTxHash;\n }\n\n // UNSHIELD LOW-LEVEL PRIMITIVES\n\n /**\n * Request an unwrap for a specific amount. Encrypts the amount first.\n * Pass the result's `unwrapRequestId` to {@link finalizeUnwrap} once the\n * request is processed on-chain.\n *\n * @param amount - The plaintext amount to unwrap (encrypted automatically).\n * @returns The tx hash, mined receipt, and the `unwrapRequestId` for `finalizeUnwrap`.\n *\n * @example\n * ```ts\n * const result = await wrappedToken.unwrap(500n);\n * await wrappedToken.finalizeUnwrap(result.unwrapRequestId);\n * ```\n */\n async unwrap(amount: bigint): Promise<UnwrapResult> {\n return this.#unwrap(amount, \"unwrap\");\n }\n\n async #unwrap(amount: bigint, telemetryOperation: TelemetryOperation): Promise<UnwrapResult> {\n this.#requireSigner(\"unwrap\");\n const account = await requireAlignedWalletAccount(\"unwrap\", this.sdk.signer, this.sdk.provider);\n const userAddress = getAddress(account.address);\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt(\n { values: [{ value: amount, type: \"euint64\" }], contractAddress: this.address, userAddress },\n { operation: telemetryOperation },\n );\n\n const [encryptedAmount] = encryptedValues;\n if (!encryptedAmount) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n const result = await this.submitTransaction({\n operation: \"unwrap\",\n config: unwrapContract(this.address, userAddress, userAddress, encryptedAmount, inputProof),\n });\n\n return { ...result, unwrapRequestId: this.#extractUnwrapRequestId(result.receipt.logs) };\n }\n\n /**\n * Request an unwrap for the entire confidential balance.\n * Uses the on-chain encrypted balance directly (no encryption needed).\n * Throws if the balance is zero.\n *\n * @returns The tx hash, mined receipt, and the `unwrapRequestId` for `finalizeUnwrap`.\n * @throws if the balance is zero. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const result = await wrappedToken.unwrapAll();\n * await wrappedToken.finalizeUnwrap(result.unwrapRequestId);\n * ```\n */\n async unwrapAll(): Promise<UnwrapResult> {\n this.#requireSigner(\"unwrapAll\");\n const account = await requireAlignedWalletAccount(\n \"unwrapAll\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const userAddress = getAddress(account.address);\n const encryptedValue = await this.readConfidentialBalanceOf(userAddress);\n\n if (isEncryptedValueZero(encryptedValue)) {\n throw new DecryptionFailedError(\"Cannot unshield: balance is zero\");\n }\n\n const result = await this.submitTransaction({\n operation: \"unwrapAll\",\n config: unwrapFromBalanceContract(this.address, userAddress, userAddress, encryptedValue),\n });\n\n return { ...result, unwrapRequestId: this.#extractUnwrapRequestId(result.receipt.logs) };\n }\n\n /**\n * Complete an unwrap by fetching the public decryption proof and finalizing.\n * Call this once the unwrap request has been processed on-chain.\n *\n * @param unwrapRequestId - The `unwrapRequestId` from an {@link UnwrapResult}\n * (`result.unwrapRequestId`) returned by {@link unwrap} / {@link unwrapAll},\n * or one decoded from an `UnwrapRequested` event (e.g. when finalizing\n * across sessions).\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const { unwrapRequestId } = await wrappedToken.unwrap(500n);\n * await wrappedToken.finalizeUnwrap(unwrapRequestId);\n * ```\n */\n async finalizeUnwrap(unwrapRequestId: EncryptedValue): Promise<TransactionResult> {\n return this.#finalizeUnwrap(unwrapRequestId, \"finalize-unwrap\");\n }\n\n async #finalizeUnwrap(\n unwrapRequestId: EncryptedValue,\n telemetryOperation: TelemetryOperation,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"finalizeUnwrap\");\n await requireChainAlignment(\"finalizeUnwrap\", this.sdk.signer, this.sdk.provider);\n const result = await this.sdk.decryption.decryptPublicValues([unwrapRequestId], {\n operation: telemetryOperation,\n });\n const clearValue = result.clearValues[unwrapRequestId];\n assertBigint(clearValue, \"finalizeUnwrap: clearValue\");\n return this.submitTransaction({\n operation: \"finalizeUnwrap\",\n config: finalizeUnwrapContract(\n this.address,\n unwrapRequestId,\n clearValue,\n result.decryptionProof,\n ),\n });\n }\n\n // PRIVATE HELPERS\n\n /**\n * Decode the `unwrapRequestId` from an unwrap/unshield receipt's logs.\n * Only logs emitted by this wrapper count: a caller-supplied tx hash from a\n * different wrapper must fail here, not decode a foreign request id. Logs\n * without an emitter address (older custom adapters) are kept.\n * Throws when no matching `UnwrapRequested` event is found.\n */\n #extractUnwrapRequestId(logs: readonly RawLog[]): EncryptedValue {\n const ownLogs = logs.filter(\n (log) => log.address === undefined || getAddress(log.address) === this.address,\n );\n const event = findUnwrapRequested(ownLogs);\n if (!event) {\n throw new TransactionRevertedError(\n \"No UnwrapRequested event from this wrapper found in the unwrap receipt\",\n );\n }\n return event.unwrapRequestId;\n }\n\n /**\n * True only when the unwrap request is definitely gone. `unwrapRequester`\n * returns the zero address once finalize deletes the request, and the id\n * always comes from the unwrap tx's own `UnwrapRequested` event, so zero can\n * only mean \"already finalized\". A failed read returns `false`: the check\n * fails open, so a network error never heals recovery state.\n */\n async #isUnwrapRequestConsumed(unwrapRequestId: EncryptedValue): Promise<boolean> {\n try {\n const requester = await this.sdk.provider.readContract(\n unwrapRequesterContract(this.address, unwrapRequestId),\n );\n return requester === zeroAddress;\n } catch {\n return false;\n }\n }\n\n /**\n * Consumed-request check for a persisted pointer; legacy hash-only entries\n * re-derive the request id from the unwrap receipt.\n */\n async #isPendingUnshieldConsumed(pending: PendingUnshieldRequest): Promise<boolean> {\n let unwrapRequestId = pending.unwrapRequestId;\n if (unwrapRequestId === undefined) {\n try {\n const receipt = await this.sdk.provider.waitForTransactionReceipt(pending.unwrapTxHash);\n unwrapRequestId = this.#extractUnwrapRequestId(receipt.logs);\n } catch {\n return false;\n }\n }\n return this.#isUnwrapRequestConsumed(unwrapRequestId);\n }\n\n async #clearStoredPendingUnshield(operation: string): Promise<void> {\n await swallow(\n `${operation}: clearPendingUnshield`,\n () => clearPendingUnshield(this.sdk.storage, this.address),\n this.sdk.logger,\n );\n }\n\n async #getUnderlying(): Promise<Address> {\n if (this.#underlying !== undefined) {\n return this.#underlying;\n }\n if (!this.#underlyingPromise) {\n this.#underlyingPromise = this.sdk.provider\n .readContract(underlyingContract(this.address))\n .then((v) => {\n this.#underlying = v;\n this.#underlyingPromise = null;\n return v;\n })\n .catch((error) => {\n this.#underlyingPromise = null;\n throw error;\n });\n }\n return this.#underlyingPromise;\n }\n\n /**\n * Phase 2 of unshield, shared by {@link unshield}/{@link unshieldAll} (which\n * pass the id `unwrap`/`unwrapAll` already decoded) and {@link resumeUnshield}\n * (which decoded it from a fetched receipt). Persists the unwrap hash for\n * recovery, finalizes, then clears the persisted state.\n */\n async #finalizeUnshield(\n unwrapRequestId: EncryptedValue,\n unwrapTxHash: Hex,\n operationId: string,\n callbacks: UnshieldCallbacks | undefined,\n telemetryOperation: TelemetryOperation,\n ): Promise<TransactionResult> {\n this.emit({ type: ZamaSDKEvents.UnshieldPhase1Submitted, txHash: unwrapTxHash, operationId });\n await swallow(\n \"unshield: savePendingUnshield\",\n () => savePendingUnshield(this.sdk.storage, this.address, unwrapTxHash, unwrapRequestId),\n this.sdk.logger,\n );\n this.emit({ type: ZamaSDKEvents.UnshieldPhase2Started, operationId });\n void swallow(\"unshield: onFinalizing\", () => callbacks?.onFinalizing?.(), this.sdk.logger);\n let finalizeResult: TransactionResult;\n try {\n finalizeResult = await this.#finalizeUnwrap(unwrapRequestId, telemetryOperation);\n } catch (error) {\n // The id comes from this wrapper's own UnwrapRequested event and the only\n // transition to \"gone\" is a successful finalize, so this revert means a\n // concurrent finalize won the race (second tab, double click, third\n // party). The funds arrived; heal.\n if (!isInvalidUnwrapRequestRevert(error)) {\n throw error;\n }\n await this.#clearStoredPendingUnshield(\"unshield\");\n throw new UnshieldAlreadyFinalizedError(\n \"The unwrap request was finalized concurrently — the funds were already delivered.\",\n { unwrapTxHash, unwrapRequestId },\n { cause: error },\n );\n }\n this.emit({\n type: ZamaSDKEvents.UnshieldPhase2Submitted,\n txHash: finalizeResult.txHash,\n operationId,\n });\n void swallow(\n \"unshield: onFinalizeSubmitted\",\n () => callbacks?.onFinalizeSubmitted?.(finalizeResult.txHash),\n this.sdk.logger,\n );\n // Phase 2 landed: the persisted recovery state is no longer needed.\n await this.#clearStoredPendingUnshield(\"unshield\");\n return finalizeResult;\n }\n\n async #ensureAllowance(\n amount: bigint,\n maxApproval: boolean,\n callbacks?: ShieldCallbacks,\n ): Promise<void> {\n this.#requireSigner(\"approveUnderlying\");\n const underlying = await this.#getUnderlying();\n const account = await requireAlignedWalletAccount(\n \"approveUnderlying\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const userAddress = getAddress(account.address);\n const allowance = await this.sdk.provider.readContract(\n allowanceContract(underlying, userAddress, this.address),\n );\n\n if (allowance >= amount) {\n return;\n }\n\n // Reset to zero first when there's an existing non-zero allowance.\n // Required by non-standard tokens like USDT, and also mitigates the\n // ERC-20 approve race condition for all tokens.\n if (allowance > 0n) {\n await this.submitTransaction({\n operation: \"approveUnderlying:reset\",\n config: approveContract(underlying, this.address, 0n),\n });\n }\n\n const approvalAmount = maxApproval ? 2n ** 256n - 1n : amount;\n\n await this.submitTransaction({\n operation: \"approveUnderlying\",\n config: approveContract(underlying, this.address, approvalAmount),\n onSubmitted: callbacks?.onApprovalSubmitted,\n });\n }\n}\n"],"mappings":"wfAKA,SAAgB,EAAuB,EAA+B,CACpE,GAAI,EAAE,aAAiB,OACrB,OAAO,KAET,IAAM,EAAQ,EAAM,MACpB,GAAI,OAAO,GAAU,WAAY,GAAkB,EAAE,SAAU,GAC7D,OAAO,KAET,GAAM,CAAE,QAAS,EAIjB,OAHI,OAAO,GAAS,WAAY,GAAiB,EAAE,cAAe,GACzD,KAEF,OAAO,EAAK,WAAc,SAAW,EAAK,UAAY,IAC/D,CCCA,IAAa,EAAb,cAAmD,CAAU,CAE3D,aAEA,gBAEA,YAAY,EAAiB,EAA0C,EAAwB,CAC7F,MAAM,EAAc,yBAA0B,EAAS,CAAO,EAC9D,KAAK,KAAO,gCACZ,KAAK,aAAe,EAAQ,aAC5B,KAAK,gBAAkB,EAAQ,eACjC,CACF,EAEA,M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gB,EAAY,KAAK,QAAS,EAAE,CACtD,CAAC,EAGH,IAAM,EAAiB,EAAc,IAAM,KAAO,GAAK,EAEvD,MAAM,KAAK,kBAAkB,CAC3B,UAAW,oBACX,OAAQ,EAAgB,EAAY,KAAK,QAAS,CAAc,EAChE,YAAa,GAAW,mBAC1B,CAAC,CACH,CACF"}
@@ -1,2 +0,0 @@
1
- const e=[{inputs:[],name:`getTokenConfidentialTokenPairs`,outputs:[{components:[{internalType:`address`,name:`tokenAddress`,type:`address`},{internalType:`address`,name:`confidentialTokenAddress`,type:`address`},{internalType:`bool`,name:`isValid`,type:`bool`}],internalType:`struct ConfidentialTokenWrappersRegistry.TokenWrapperPair[]`,name:``,type:`tuple[]`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getTokenConfidentialTokenPairsLength`,outputs:[{internalType:`uint256`,name:``,type:`uint256`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint256`,name:`fromIndex`,type:`uint256`},{internalType:`uint256`,name:`toIndex`,type:`uint256`}],name:`getTokenConfidentialTokenPairsSlice`,outputs:[{components:[{internalType:`address`,name:`tokenAddress`,type:`address`},{internalType:`address`,name:`confidentialTokenAddress`,type:`address`},{internalType:`bool`,name:`isValid`,type:`bool`}],internalType:`struct ConfidentialTokenWrappersRegistry.TokenWrapperPair[]`,name:``,type:`tuple[]`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint256`,name:`index`,type:`uint256`}],name:`getTokenConfidentialTokenPair`,outputs:[{components:[{internalType:`address`,name:`tokenAddress`,type:`address`},{internalType:`address`,name:`confidentialTokenAddress`,type:`address`},{internalType:`bool`,name:`isValid`,type:`bool`}],internalType:`struct ConfidentialTokenWrappersRegistry.TokenWrapperPair`,name:``,type:`tuple`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`tokenAddress`,type:`address`}],name:`getConfidentialTokenAddress`,outputs:[{internalType:`bool`,name:``,type:`bool`},{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`confidentialTokenAddress`,type:`address`}],name:`getTokenAddress`,outputs:[{internalType:`bool`,name:``,type:`bool`},{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`confidentialTokenAddress`,type:`address`}],name:`isConfidentialTokenValid`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`initialOwner`,type:`address`}],name:`initialize`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`tokenAddress`,type:`address`},{internalType:`address`,name:`confidentialTokenAddress`,type:`address`}],name:`registerConfidentialToken`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`confidentialTokenAddress`,type:`address`}],name:`revokeConfidentialToken`,outputs:[],stateMutability:`nonpayable`,type:`function`}];function t(t){return{address:t,abi:e,functionName:`getTokenConfidentialTokenPairs`,args:[]}}function n(t){return{address:t,abi:e,functionName:`getTokenConfidentialTokenPairsLength`,args:[]}}function r(t,n,r){return{address:t,abi:e,functionName:`getTokenConfidentialTokenPairsSlice`,args:[n,r]}}function i(t,n){return{address:t,abi:e,functionName:`getTokenConfidentialTokenPair`,args:[n]}}function a(t,n){return{address:t,abi:e,functionName:`getConfidentialTokenAddress`,args:[n]}}function o(t,n){return{address:t,abi:e,functionName:`getTokenAddress`,args:[n]}}function s(t,n){return{address:t,abi:e,functionName:`isConfidentialTokenValid`,args:[n]}}export{n as a,t as i,o as n,r as o,i as r,s,a as t};
2
- //# sourceMappingURL=wrappers-registry-Cm3JJeqx.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wrappers-registry-Cm3JJeqx.js","names":[],"sources":["../../src/contracts/wrappers-registry.ts"],"sourcesContent":["import type { Address } from \"viem\";\n\nexport const wrappersRegistryAbi = [\n {\n inputs: [],\n name: \"getTokenConfidentialTokenPairs\",\n outputs: [\n {\n components: [\n { internalType: \"address\", name: \"tokenAddress\", type: \"address\" },\n { internalType: \"address\", name: \"confidentialTokenAddress\", type: \"address\" },\n { internalType: \"bool\", name: \"isValid\", type: \"bool\" },\n ],\n internalType: \"struct ConfidentialTokenWrappersRegistry.TokenWrapperPair[]\",\n name: \"\",\n type: \"tuple[]\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"getTokenConfidentialTokenPairsLength\",\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"uint256\", name: \"fromIndex\", type: \"uint256\" },\n { internalType: \"uint256\", name: \"toIndex\", type: \"uint256\" },\n ],\n name: \"getTokenConfidentialTokenPairsSlice\",\n outputs: [\n {\n components: [\n { internalType: \"address\", name: \"tokenAddress\", type: \"address\" },\n { internalType: \"address\", name: \"confidentialTokenAddress\", type: \"address\" },\n { internalType: \"bool\", name: \"isValid\", type: \"bool\" },\n ],\n internalType: \"struct ConfidentialTokenWrappersRegistry.TokenWrapperPair[]\",\n name: \"\",\n type: \"tuple[]\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"uint256\", name: \"index\", type: \"uint256\" }],\n name: \"getTokenConfidentialTokenPair\",\n outputs: [\n {\n components: [\n { internalType: \"address\", name: \"tokenAddress\", type: \"address\" },\n { internalType: \"address\", name: \"confidentialTokenAddress\", type: \"address\" },\n { internalType: \"bool\", name: \"isValid\", type: \"bool\" },\n ],\n internalType: \"struct ConfidentialTokenWrappersRegistry.TokenWrapperPair\",\n name: \"\",\n type: \"tuple\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"address\", name: \"tokenAddress\", type: \"address\" }],\n name: \"getConfidentialTokenAddress\",\n outputs: [\n { internalType: \"bool\", name: \"\", type: \"bool\" },\n { internalType: \"address\", name: \"\", type: \"address\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"address\", name: \"confidentialTokenAddress\", type: \"address\" }],\n name: \"getTokenAddress\",\n outputs: [\n { internalType: \"bool\", name: \"\", type: \"bool\" },\n { internalType: \"address\", name: \"\", type: \"address\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"address\", name: \"confidentialTokenAddress\", type: \"address\" }],\n name: \"isConfidentialTokenValid\",\n outputs: [{ internalType: \"bool\", name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"address\", name: \"initialOwner\", type: \"address\" }],\n name: \"initialize\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"address\", name: \"tokenAddress\", type: \"address\" },\n { internalType: \"address\", name: \"confidentialTokenAddress\", type: \"address\" },\n ],\n name: \"registerConfidentialToken\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"address\", name: \"confidentialTokenAddress\", type: \"address\" }],\n name: \"revokeConfidentialToken\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n] as const;\n\n/** A registered plain-token / confidential-token pairing from the wrappers registry. */\nexport interface TokenWrapperPair {\n /** Address of the underlying public ERC-20 token. */\n readonly tokenAddress: Address;\n /** Address of the paired confidential (ERC-7984) token. */\n readonly confidentialTokenAddress: Address;\n /** Whether the pairing is currently valid (registered and not revoked). */\n readonly isValid: boolean;\n}\n\n/** Extended pair with on-chain metadata for both tokens. */\nexport interface TokenWrapperPairWithMetadata extends TokenWrapperPair {\n /** On-chain metadata of the underlying public ERC-20 token. */\n readonly underlying: {\n readonly name: string;\n readonly symbol: string;\n readonly decimals: number;\n readonly totalSupply: bigint;\n };\n /** On-chain metadata of the confidential token. */\n readonly confidential: {\n readonly name: string;\n readonly symbol: string;\n readonly decimals: number;\n };\n}\n\n/** Paginated result set modeled after standard API pagination. */\nexport interface PaginatedResult<T> {\n /** Items on the current page. */\n readonly items: readonly T[];\n /** Total number of items across all pages. */\n readonly total: number;\n /** One-based index of the current page. */\n readonly page: number;\n /** Maximum number of items per page. */\n readonly pageSize: number;\n}\n\n/**\n * Returns the contract config to fetch all token wrapper pairs.\n *\n * @example\n * ```ts\n * const pairs = await client.readContract(\n * getTokenPairsContract(registryAddress),\n * );\n * ```\n */\nexport function getTokenPairsContract(registry: Address) {\n return {\n address: registry,\n abi: wrappersRegistryAbi,\n functionName: \"getTokenConfidentialTokenPairs\",\n args: [],\n } as const;\n}\n\n/**\n * Returns the contract config to get the number of token wrapper pairs.\n *\n * @example\n * ```ts\n * const length = await client.readContract(\n * getTokenPairsLengthContract(registryAddress),\n * );\n * ```\n */\nexport function getTokenPairsLengthContract(registry: Address) {\n return {\n address: registry,\n abi: wrappersRegistryAbi,\n functionName: \"getTokenConfidentialTokenPairsLength\",\n args: [],\n } as const;\n}\n\n/**\n * Returns the contract config to fetch a slice of token wrapper pairs.\n *\n * @example\n * ```ts\n * const pairs = await client.readContract(\n * getTokenPairsSliceContract(registryAddress, 0n, 10n),\n * );\n * ```\n */\nexport function getTokenPairsSliceContract(registry: Address, fromIndex: bigint, toIndex: bigint) {\n return {\n address: registry,\n abi: wrappersRegistryAbi,\n functionName: \"getTokenConfidentialTokenPairsSlice\",\n args: [fromIndex, toIndex],\n } as const;\n}\n\n/**\n * Returns the contract config to fetch a single token wrapper pair by index.\n *\n * @example\n * ```ts\n * const pair = await client.readContract(\n * getTokenPairContract(registryAddress, 0n),\n * );\n * ```\n */\nexport function getTokenPairContract(registry: Address, index: bigint) {\n return {\n address: registry,\n abi: wrappersRegistryAbi,\n functionName: \"getTokenConfidentialTokenPair\",\n args: [index],\n } as const;\n}\n\n/**\n * Returns the contract config to look up the confidential token for a given plain token.\n *\n * @example\n * ```ts\n * const [isValid, confidentialToken] = await client.readContract(\n * getConfidentialTokenAddressContract(registryAddress, tokenAddress),\n * );\n * // isValid=false + confidentialToken=zeroAddress → not registered\n * // isValid=false + confidentialToken=nonZeroAddress → registered but revoked\n * // isValid=true + confidentialToken=nonZeroAddress → registered and valid\n * ```\n */\nexport function getConfidentialTokenAddressContract(registry: Address, tokenAddress: Address) {\n return {\n address: registry,\n abi: wrappersRegistryAbi,\n functionName: \"getConfidentialTokenAddress\",\n args: [tokenAddress],\n } as const;\n}\n\n/**\n * Returns the contract config to look up the plain token for a given confidential token.\n *\n * @example\n * ```ts\n * const [isValid, token] = await client.readContract(\n * getTokenAddressContract(registryAddress, confidentialTokenAddress),\n * );\n * // isValid=false + token=zeroAddress → not registered\n * // isValid=false + token=nonZeroAddress → registered but revoked\n * // isValid=true + token=nonZeroAddress → registered and valid\n * ```\n */\nexport function getTokenAddressContract(registry: Address, confidentialTokenAddress: Address) {\n return {\n address: registry,\n abi: wrappersRegistryAbi,\n functionName: \"getTokenAddress\",\n args: [confidentialTokenAddress],\n } as const;\n}\n\n/**\n * Returns the contract config to check if a confidential token is valid.\n *\n * @example\n * ```ts\n * const isValid = await client.readContract(\n * isConfidentialTokenValidContract(registryAddress, confidentialTokenAddress),\n * );\n * ```\n */\nexport function isConfidentialTokenValidContract(\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return {\n address: registry,\n abi: wrappersRegistryAbi,\n functionName: \"isConfidentialTokenValid\",\n args: [confidentialTokenAddress],\n } as const;\n}\n"],"mappings":"AAEA,MAAa,EAAsB,CACjC,CACE,OAAQ,CAAC,EACT,KAAM,iCACN,QAAS,CACP,CACE,WAAY,CACV,CAAE,aAAc,UAAW,KAAM,eAAgB,KAAM,SAAU,EACjE,CAAE,aAAc,UAAW,KAAM,2BAA4B,KAAM,SAAU,EAC7E,CAAE,aAAc,OAAQ,KAAM,UAAW,KAAM,MAAO,CACxD,EACA,aAAc,8DACd,KAAM,GACN,KAAM,SACR,CACF,EACA,gBAAiB,OACjB,KAAM,UACR,EACA,CACE,OAAQ,CAAC,EACT,KAAM,uCACN,QAAS,CAAC,CAAE,aAAc,UAAW,KAAM,GA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