@zama-fhe/sdk 3.7.0-alpha.2 → 3.7.0-beta.2

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 (102) 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/erc165.cjs +2 -0
  6. package/dist/cjs/erc165.cjs.map +1 -0
  7. package/dist/cjs/ethers/index.cjs +1 -1
  8. package/dist/cjs/ethers/index.cjs.map +1 -1
  9. package/dist/cjs/fhevm-relayer.cjs +2 -2
  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/invalidation.cjs +2 -0
  14. package/dist/cjs/invalidation.cjs.map +1 -0
  15. package/dist/cjs/primitives.cjs +2 -0
  16. package/dist/cjs/primitives.cjs.map +1 -0
  17. package/dist/cjs/query/index.cjs +1 -1
  18. package/dist/cjs/query/index.cjs.map +1 -1
  19. package/dist/cjs/relayer.cjs +1 -1
  20. package/dist/cjs/relayer.cjs.map +1 -1
  21. package/dist/cjs/token.cjs +1 -1
  22. package/dist/cjs/token.cjs.map +1 -1
  23. package/dist/cjs/vaults/index.cjs +2 -0
  24. package/dist/cjs/vaults/index.cjs.map +1 -0
  25. package/dist/cjs/viem/index.cjs +1 -1
  26. package/dist/cjs/viem/index.cjs.map +1 -1
  27. package/dist/cjs/wrapped-token.cjs +2 -0
  28. package/dist/cjs/wrapped-token.cjs.map +1 -0
  29. package/dist/cjs/wrappers-registry.cjs +1 -1
  30. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  31. package/dist/esm/base-signer-D5Cwv7yb.js +2 -0
  32. package/dist/esm/base-signer-D5Cwv7yb.js.map +1 -0
  33. package/dist/esm/{base-signer-S2Ogf6L4.d.ts → base-signer-DIYZwDnc.d.ts} +2 -2
  34. package/dist/esm/chains/index.d.ts +1 -1
  35. package/dist/esm/chains/index.js +1 -1
  36. package/dist/esm/chains-ByyCdrrd.js +2 -0
  37. package/dist/esm/chains-ByyCdrrd.js.map +1 -0
  38. package/dist/esm/cleartext/index.d.ts +2 -2
  39. package/dist/esm/cleartext/index.js +1 -1
  40. package/dist/esm/{cleartext-pv2blbFU.d.ts → cleartext-3HOk1BAg.d.ts} +2 -2
  41. package/dist/esm/{cleartext-DcbDCDXj.js → cleartext-PCpNqRGV.js} +2 -2
  42. package/dist/esm/{cleartext-DcbDCDXj.js.map → cleartext-PCpNqRGV.js.map} +1 -1
  43. package/dist/esm/encrypt.worker.js +51 -51
  44. package/dist/esm/{encryption-DJljZ2oV.js → encryption-BKoalB4o.js} +2 -2
  45. package/dist/esm/{encryption-DJljZ2oV.js.map → encryption-BKoalB4o.js.map} +1 -1
  46. package/dist/esm/erc165-DbMOt-s6.js +2 -0
  47. package/dist/esm/erc165-DbMOt-s6.js.map +1 -0
  48. package/dist/esm/ethers/index.d.ts +5 -5
  49. package/dist/esm/ethers/index.js +1 -1
  50. package/dist/esm/ethers/index.js.map +1 -1
  51. package/dist/esm/fhevm-relayer-CtrnKjJf.js +8 -0
  52. package/dist/esm/fhevm-relayer-CtrnKjJf.js.map +1 -0
  53. package/dist/esm/{index-tfvbrVa2.d.ts → index-BHrjck_q.d.ts} +4 -4
  54. package/dist/esm/{index-DRrrBtMX.d.ts → index-DJYq1rAB.d.ts} +989 -1874
  55. package/dist/esm/{index-Gk1S0gjO.d.ts → index-ijgDL4IC.d.ts} +1 -14
  56. package/dist/esm/index.d.ts +8 -108
  57. package/dist/esm/index.js +1 -1
  58. package/dist/esm/index.js.map +1 -1
  59. package/dist/esm/invalidation-BgFjmXeQ.js +2 -0
  60. package/dist/esm/invalidation-BgFjmXeQ.js.map +1 -0
  61. package/dist/esm/invalidation-CJ-pzOUG.d.ts +46 -0
  62. package/dist/esm/node/index.d.ts +4 -4
  63. package/dist/esm/node/index.js +1 -1
  64. package/dist/esm/primitives-Cym-3HKa.js +2 -0
  65. package/dist/esm/primitives-Cym-3HKa.js.map +1 -0
  66. package/dist/esm/query/index.d.ts +495 -4
  67. package/dist/esm/query/index.js +1 -1
  68. package/dist/esm/query/index.js.map +1 -1
  69. package/dist/esm/relayer-CVKO9GmQ.js +2 -0
  70. package/dist/esm/relayer-CVKO9GmQ.js.map +1 -0
  71. package/dist/esm/token-CRJ8eCr7.js +2 -0
  72. package/dist/esm/token-CRJ8eCr7.js.map +1 -0
  73. package/dist/esm/{types-BOyFfG7D.d.ts → types-Bz5-wHPv.d.ts} +23 -43
  74. package/dist/esm/{types-BRIpBy9n.d.ts → types-CI6BtpB7.d.ts} +3 -3
  75. package/dist/esm/{types-OXQqX_kH.d.ts → types-v0_sfkli.d.ts} +3 -3
  76. package/dist/esm/{validation-DWe2k89s.js → validation-BRu06AM_.js} +2 -2
  77. package/dist/esm/{validation-DWe2k89s.js.map → validation-BRu06AM_.js.map} +1 -1
  78. package/dist/esm/vaults/index.d.ts +13833 -0
  79. package/dist/esm/vaults/index.js +2 -0
  80. package/dist/esm/vaults/index.js.map +1 -0
  81. package/dist/esm/viem/index.d.ts +5 -5
  82. package/dist/esm/viem/index.js +1 -1
  83. package/dist/esm/viem/index.js.map +1 -1
  84. package/dist/esm/web/index.d.ts +1 -1
  85. package/dist/esm/web/index.js +1 -1
  86. package/dist/esm/wrapped-token-BOtzaSAY.js +2 -0
  87. package/dist/esm/wrapped-token-BOtzaSAY.js.map +1 -0
  88. package/dist/esm/wrappers-registry-Cm3JJeqx.js +2 -0
  89. package/dist/esm/wrappers-registry-Cm3JJeqx.js.map +1 -0
  90. package/package.json +19 -5
  91. package/dist/esm/base-signer--sBO2qJp.js +0 -2
  92. package/dist/esm/base-signer--sBO2qJp.js.map +0 -1
  93. package/dist/esm/chains-DEpKup1n.js +0 -2
  94. package/dist/esm/chains-DEpKup1n.js.map +0 -1
  95. package/dist/esm/fhevm-relayer-CPmCytDX.js +0 -8
  96. package/dist/esm/fhevm-relayer-CPmCytDX.js.map +0 -1
  97. package/dist/esm/relayer-B6Zo6EkX.js +0 -2
  98. package/dist/esm/relayer-B6Zo6EkX.js.map +0 -1
  99. package/dist/esm/token-BMQ6xlrk.js +0 -2
  100. package/dist/esm/token-BMQ6xlrk.js.map +0 -1
  101. package/dist/esm/wrappers-registry-BfQr2QHn.js +0 -2
  102. package/dist/esm/wrappers-registry-BfQr2QHn.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["eventTopic","topicToAddress","wordToBytes32","#vault","#fromToken","#toToken","isEncryptedValueZero","DecryptionFailedError","#requireSigner","requireAlignedWalletAccount","#assertJoinableBalance","EncryptionFailedError","#submitTransaction","TransactionRevertedError","requireChainAlignment","#resolveTarget","SignerNotConfiguredError","#inputToken","#fromTokenInstance","Token","assertConfidentialBalance","submitSdkTransaction","#expectedVaultAddress","#vaultAddress","#resolveVaultAddress","#cAsset","WrappedToken","#cShare","#ensureOperator","ConfigurationError","SignerNotConfiguredError","filterQueryOptions","filterQueryOptions","filterQueryOptions"],"sources":["../../../src/vaults/abi/vault-batcher.abi.ts","../../../src/vaults/contracts/vault-batcher.ts","../../../src/vaults/events.ts","../../../src/vaults/types.ts","../../../src/vaults/vault-batcher.ts","../../../src/vaults/vault.ts","../../../src/vaults/query/query-keys.ts","../../../src/vaults/query/invalidation.ts","../../../src/vaults/query/current-batch-id.ts","../../../src/vaults/query/batch-state.ts","../../../src/vaults/query/time-until-dispatchable.ts","../../../src/vaults/query/deposit.ts","../../../src/vaults/query/redeem.ts","../../../src/vaults/query/join.ts","../../../src/vaults/query/claim.ts","../../../src/vaults/query/quit.ts","../../../src/vaults/query/recover.ts","../../../src/vaults/query/dispatch-batch.ts"],"sourcesContent":["/**\n * ABI for the deposit and redeem vault batchers, which share one interface.\n * Owner-only writes and the relayer-driven `dispatchBatchCallback` are omitted;\n * every custom error is kept so reverts decode to a name.\n */\nexport const vaultBatcherAbi = [\n {\n type: \"function\",\n name: \"batchCallbackDeadline\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"batchCreatedAt\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"batchDispatchedAt\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"batchMaxSlippageBps\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint16\", internalType: \"uint16\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"batchMinBatchAge\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"batchState\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint8\", internalType: \"enum BatcherConfidential.BatchState\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"callbackDeadline\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"claim\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"euint64\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"currentBatchId\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"deposits\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"euint64\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"dispatchBatch\",\n inputs: [],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"exchangeRate\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint64\", internalType: \"uint64\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"exchangeRateDecimals\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint8\", internalType: \"uint8\" }],\n stateMutability: \"pure\",\n },\n {\n type: \"function\",\n name: \"fromToken\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract IERC7984ERC20Wrapper\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"join\",\n inputs: [\n { name: \"beneficiary\", type: \"address\", internalType: \"address\" },\n { name: \"encryptedAmount\", type: \"bytes32\", internalType: \"externalEuint64\" },\n { name: \"inputProof\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [{ name: \"joined\", type: \"bytes32\", internalType: \"euint64\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"maxSlippageBps\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint16\", internalType: \"uint16\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"minBatchAge\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"paused\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"quit\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"euint64\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"recover\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"refunded\", type: \"bytes32\", internalType: \"euint64\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"toToken\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract IERC7984ERC20Wrapper\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"totalDeposits\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"euint64\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"unwrapRequestId\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"vault\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract IERC4626\" }],\n stateMutability: \"view\",\n },\n {\n type: \"event\",\n name: \"BatchCanceled\",\n inputs: [{ name: \"batchId\", type: \"uint256\", indexed: true, internalType: \"uint256\" }],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"BatchDispatched\",\n inputs: [{ name: \"batchId\", type: \"uint256\", indexed: true, internalType: \"uint256\" }],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"BatchFinalized\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", indexed: true, internalType: \"uint256\" },\n { name: \"exchangeRate\", type: \"uint64\", indexed: false, internalType: \"uint64\" },\n ],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"Claimed\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", indexed: true, internalType: \"uint256\" },\n { name: \"account\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"amount\", type: \"bytes32\", indexed: false, internalType: \"euint64\" },\n ],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"Joined\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", indexed: true, internalType: \"uint256\" },\n { name: \"account\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"amount\", type: \"bytes32\", indexed: false, internalType: \"euint64\" },\n ],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"Quit\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", indexed: true, internalType: \"uint256\" },\n { name: \"account\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"amount\", type: \"bytes32\", indexed: false, internalType: \"euint64\" },\n ],\n anonymous: false,\n },\n {\n type: \"error\",\n name: \"BatchNonexistent\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n },\n {\n type: \"error\",\n name: \"BatchTooYoung\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"elapsed\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"required\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n {\n type: \"error\",\n name: \"BatchUnexpectedState\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"current\", type: \"uint8\", internalType: \"enum BatcherConfidential.BatchState\" },\n { name: \"expectedStates\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n },\n { type: \"error\", name: \"DuplicateUnderlyingTokens\", inputs: [] },\n { type: \"error\", name: \"EnforcedPause\", inputs: [] },\n { type: \"error\", name: \"ExpectedPause\", inputs: [] },\n {\n type: \"error\",\n name: \"IntermediateStepToTokenBalanceChanged\",\n inputs: [{ name: \"batchId\", type: \"uint256\", internalType: \"uint256\" }],\n },\n { type: \"error\", name: \"InvalidBeneficiary\", inputs: [] },\n { type: \"error\", name: \"InvalidCallbackDeadline\", inputs: [] },\n {\n type: \"error\",\n name: \"InvalidExchangeRate\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"totalDeposits\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"exchangeRate\", type: \"uint64\", internalType: \"uint64\" },\n ],\n },\n { type: \"error\", name: \"InvalidKMSSignatures\", inputs: [] },\n { type: \"error\", name: \"InvalidMaxSlippageBps\", inputs: [] },\n { type: \"error\", name: \"InvalidMinBatchAge\", inputs: [] },\n { type: \"error\", name: \"InvalidTokenRate\", inputs: [] },\n {\n type: \"error\",\n name: \"InvalidWrapperToken\",\n inputs: [{ name: \"token\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"OwnableInvalidOwner\",\n inputs: [{ name: \"owner\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"OwnableUnauthorizedAccount\",\n inputs: [{ name: \"account\", type: \"address\", internalType: \"address\" }],\n },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n {\n type: \"error\",\n name: \"RouteAssetMismatch\",\n inputs: [\n { name: \"actualAsset\", type: \"address\", internalType: \"address\" },\n { name: \"expectedAsset\", type: \"address\", internalType: \"address\" },\n ],\n },\n {\n type: \"error\",\n name: \"RouteShareMismatch\",\n inputs: [\n { name: \"actualShare\", type: \"address\", internalType: \"address\" },\n { name: \"expectedShare\", type: \"address\", internalType: \"address\" },\n ],\n },\n {\n type: \"error\",\n name: \"SafeCastOverflowedUintDowncast\",\n inputs: [\n { name: \"bits\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n {\n type: \"error\",\n name: \"SafeERC20FailedOperation\",\n inputs: [{ name: \"token\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"SenderNotAllowedToUseHandle\",\n inputs: [\n { name: \"handle\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"sender\", type: \"address\", internalType: \"address\" },\n ],\n },\n {\n type: \"error\",\n name: \"SlippageExceeded\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"actual\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"minimum\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { type: \"error\", name: \"Unauthorized\", inputs: [] },\n { type: \"error\", name: \"ZamaProtocolUnsupported\", inputs: [] },\n {\n type: \"error\",\n name: \"ZeroDeposits\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"account\", type: \"address\", internalType: \"address\" },\n ],\n },\n] as const;\n","import type { Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../../relayer/types\";\nimport { vaultBatcherAbi } from \"../abi/vault-batcher.abi\";\n\n/** Returns the contract config to join the currently open batch with an encrypted amount. */\nexport function joinContract(\n batcher: Address,\n beneficiary: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"join\",\n args: [beneficiary, encryptedAmount, inputProof],\n } as const;\n}\n\n/** Returns the contract config to claim a finalized batch's output on behalf of `account`. Permissionless. */\nexport function claimContract(batcher: Address, batchId: bigint, account: Address) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"claim\",\n args: [batchId, account],\n } as const;\n}\n\n/** Returns the contract config to withdraw the caller's own deposit from a pending or canceled batch. */\nexport function quitContract(batcher: Address, batchId: bigint) {\n return { address: batcher, abi: vaultBatcherAbi, functionName: \"quit\", args: [batchId] } as const;\n}\n\n/** Returns the contract config to refund `account`'s deposit in a canceled batch. Permissionless — the refund goes to `account`, not the caller. */\nexport function recoverContract(batcher: Address, batchId: bigint, account: Address) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"recover\",\n args: [batchId, account],\n } as const;\n}\n\n/** Returns the contract config to close the current batch and kick off decryption. Permissionless. */\nexport function dispatchBatchContract(batcher: Address) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"dispatchBatch\",\n args: [],\n } as const;\n}\n\n/** Returns the contract config to read the id of the currently open batch. */\nexport function currentBatchIdContract(batcher: Address) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"currentBatchId\",\n args: [],\n } as const;\n}\n\n/** Returns the contract config to read a batch's lifecycle state (the contract's `BatchState` enum). */\nexport function batchStateContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"batchState\",\n args: [batchId],\n } as const;\n}\n\n/** Returns the contract config to read a batch's encrypted aggregate deposit amount. */\nexport function totalDepositsContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"totalDeposits\",\n args: [batchId],\n } as const;\n}\n\n/** Returns the contract config to read one account's encrypted deposit within a batch. */\nexport function depositsContract(batcher: Address, batchId: bigint, account: Address) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"deposits\",\n args: [batchId, account],\n } as const;\n}\n\n/** Returns the contract config to read the underlying ERC-4626 vault address. */\nexport function vaultContract(batcher: Address) {\n return { address: batcher, abi: vaultBatcherAbi, functionName: \"vault\", args: [] } as const;\n}\n\n/** Returns the contract config to read the confidential token this batcher accepts as input. */\nexport function fromTokenContract(batcher: Address) {\n return { address: batcher, abi: vaultBatcherAbi, functionName: \"fromToken\", args: [] } as const;\n}\n\n/** Returns the contract config to read the confidential token this batcher pays out. */\nexport function toTokenContract(batcher: Address) {\n return { address: batcher, abi: vaultBatcherAbi, functionName: \"toToken\", args: [] } as const;\n}\n\n/** Returns the contract config to read the batcher's current minimum-batch-age policy. */\nexport function minBatchAgeContract(batcher: Address) {\n return { address: batcher, abi: vaultBatcherAbi, functionName: \"minBatchAge\", args: [] } as const;\n}\n\n/** Returns the contract config to read the minimum age pinned to one batch when it opened. */\nexport function batchMinBatchAgeContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"batchMinBatchAge\",\n args: [batchId],\n } as const;\n}\n\n/** Returns the contract config to read the batcher's current callback-deadline policy. */\nexport function callbackDeadlineContract(batcher: Address) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"callbackDeadline\",\n args: [],\n } as const;\n}\n\n/** Returns the contract config to read the callback deadline pinned to one batch when it opened. */\nexport function batchCallbackDeadlineContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"batchCallbackDeadline\",\n args: [batchId],\n } as const;\n}\n\n/** Returns the contract config to read the Unix timestamp a batch was opened at. */\nexport function batchCreatedAtContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"batchCreatedAt\",\n args: [batchId],\n } as const;\n}\n\n/** Returns the contract config to read the Unix timestamp a batch was dispatched at, or 0 if not yet dispatched. */\nexport function batchDispatchedAtContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"batchDispatchedAt\",\n args: [batchId],\n } as const;\n}\n\n/** Returns the contract config to read a finalized batch's exchange rate, or 0 while unfinalized. */\nexport function exchangeRateContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"exchangeRate\",\n args: [batchId],\n } as const;\n}\n\n/** Returns the contract config to read the number of decimals the exchange rate is scaled by. */\nexport function exchangeRateDecimalsContract(batcher: Address) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"exchangeRateDecimals\",\n args: [],\n } as const;\n}\n\n/** Returns the contract config to read whether the batcher is paused (blocking joins and dispatch). */\nexport function pausedContract(batcher: Address) {\n return { address: batcher, abi: vaultBatcherAbi, functionName: \"paused\", args: [] } as const;\n}\n","import { getAddress, type Address } from \"viem\";\nimport { eventTopic, topicToAddress, wordToBytes32 } from \"../events/log-decoding\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport type { RawLog } from \"../types/transaction\";\n\n/**\n * Vault batcher event topic0 constants (keccak256 of the canonical Solidity\n * signature). Pass to `getLogs({ topics: [Object.values(VaultTopics)] })`.\n */\nexport const VaultTopics = {\n /** `Joined(uint256 indexed batchId, address indexed account, euint64 amount)` */\n Joined: eventTopic(\"Joined(uint256,address,bytes32)\"),\n} as const;\n\n/** A decoded `Joined` event. */\nexport interface JoinedEvent {\n /** The batch the join landed in. */\n batchId: bigint;\n /** The account credited — the beneficiary a join named, which may not be the caller. */\n account: Address;\n /** The encrypted amount credited, which can be zero when the pull transferred nothing. */\n confidentialAmount: EncryptedValue;\n}\n\n/**\n * Joined(uint256 indexed batchId, address indexed account, euint64 amount)\n * Indexed: batchId (topics[1]), account (topics[2])\n * Data: amount (bytes32)\n */\nexport function decodeJoined(log: RawLog): JoinedEvent | null {\n const [topic, batchId, account] = log.topics;\n if (topic !== VaultTopics.Joined || batchId === undefined || account === undefined) {\n return null;\n }\n\n return {\n batchId: BigInt(batchId),\n account: topicToAddress(account),\n confidentialAmount: wordToBytes32(log.data, 0),\n };\n}\n\n/**\n * Filters on `batcher`, and on `account` when given, rather than taking the\n * first match: one transaction can join several batchers and credit several\n * beneficiaries, so an unfiltered search can return someone else's batch id.\n * Logs carrying no emitter address are kept, since some adapters omit it.\n */\nexport function findJoined(\n logs: readonly RawLog[],\n batcher: Address,\n account?: Address,\n): JoinedEvent | null {\n const normalizedAccount = account ? getAddress(account) : undefined;\n for (const log of logs) {\n if (log.address !== undefined && getAddress(log.address) !== batcher) {\n continue;\n }\n const event = decodeJoined(log);\n if (!event) {\n continue;\n }\n if (normalizedAccount !== undefined && event.account !== normalizedAccount) {\n continue;\n }\n return event;\n }\n return null;\n}\n","import type { Address } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport type { TransactionResult } from \"../types\";\n\n/**\n * A batch's lifecycle state. The numbers mirror the batcher contract's own\n * enum, so they are part of the on-chain contract, not an arbitrary encoding.\n */\nexport const BatchState = {\n /** Open: accepts joins and quits. Always the batcher's `currentBatchId`. */\n Pending: 0,\n /** Closed; the aggregate amount is being decrypted. No user action is possible. */\n Dispatched: 1,\n /** Settled with an exchange rate — the only state in which `claim` succeeds. */\n Finalized: 2,\n /** The route failed or the callback deadline passed; `quit` refunds the original deposit. */\n Canceled: 3,\n} as const;\n\n/** Union of all {@link BatchState} values. */\nexport type BatchState = (typeof BatchState)[keyof typeof BatchState];\n\n/** Addresses that make up one confidential vault. */\nexport interface VaultAddresses {\n /**\n * The ERC-4626 vault contract that holds the underlying asset and issues\n * shares. Optional — both batchers report it on chain. Passing it does not\n * skip that read: it is verified against what the batchers report.\n */\n vault?: Address;\n /** The batcher users join to deposit the confidential underlying asset into the vault. */\n depositBatcher: Address;\n /** The batcher users join to redeem confidential shares back into the underlying asset. */\n redeemBatcher: Address;\n}\n\n/** Options for {@link VaultBatcher.join}. */\nexport interface JoinOptions {\n /**\n * Skip the confidential-balance pre-flight before joining — for accounts\n * whose balance the connected signer cannot decrypt, such as smart wallets.\n */\n skipBalanceCheck?: boolean;\n}\n\n/** Options for {@link Vault.deposit} and {@link Vault.redeem}. */\nexport interface VaultJoinOptions extends JoinOptions {\n /**\n * Account credited in the batch. Defaults to the connected wallet address.\n *\n * Set this to join on behalf of another account — but note that the\n * beneficiary, not the caller, then owns the position: only they can\n * {@link VaultBatcher.quit} it, and {@link VaultBatcher.claim} pays out to\n * them.\n */\n beneficiary?: Address;\n /**\n * Unix timestamp until which the batcher's operator grant on the joined\n * token is valid. Only used when a grant isn't already active. Defaults to\n * `Token.setOperator`'s own default (now + 1 hour).\n */\n operatorUntil?: number;\n}\n\n/** What the batcher reported for a successful join. */\nexport interface JoinResult extends TransactionResult {\n /** The batch the join landed in. */\n batchId: bigint;\n /** The account credited — the beneficiary, which may not be the caller. */\n beneficiary: Address;\n /**\n * The encrypted amount actually credited, which is **not** always the amount\n * requested: an ERC-7984 transfer moves zero rather than reverting when the\n * balance is short. Decrypt it to confirm the join landed in full.\n */\n confidentialJoinedAmount: EncryptedValue;\n}\n","import { getAddress, type Address } from \"viem\";\nimport {\n DecryptionFailedError,\n EncryptionFailedError,\n SignerNotConfiguredError,\n TransactionRevertedError,\n} from \"../errors\";\nimport type { TransactionOperation } from \"../events/sdk-events\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { Token } from \"../token\";\nimport type { GenericSigner, TransactionResult, WriteContractConfig } from \"../types\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\nimport { assertConfidentialBalance } from \"../utils/assert-balance\";\nimport { assertBigint } from \"../utils/assertions\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport { submitTransaction as submitSdkTransaction } from \"../utils/submit-transaction\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport {\n batchCallbackDeadlineContract,\n batchCreatedAtContract,\n batchDispatchedAtContract,\n batchMinBatchAgeContract,\n batchStateContract,\n callbackDeadlineContract,\n claimContract,\n currentBatchIdContract,\n depositsContract,\n dispatchBatchContract,\n exchangeRateContract,\n exchangeRateDecimalsContract,\n fromTokenContract,\n joinContract,\n minBatchAgeContract,\n pausedContract,\n quitContract,\n recoverContract,\n toTokenContract,\n totalDepositsContract,\n vaultContract,\n} from \"./contracts\";\nimport { findJoined } from \"./events\";\nimport { BatchState, type JoinOptions, type JoinResult } from \"./types\";\n\n/**\n * Safe to cache forever: the addresses a batcher reports are set at deploy\n * time and never change.\n */\nfunction memoizeAddressRead(read: () => Promise<Address>): () => Promise<Address> {\n let cached: Address | undefined;\n let pending: Promise<Address> | null = null;\n return () => {\n if (cached !== undefined) {\n return Promise.resolve(cached);\n }\n if (!pending) {\n pending = read()\n .then((value) => {\n cached = value;\n pending = null;\n return value;\n })\n .catch((error) => {\n pending = null;\n throw error;\n });\n }\n return pending;\n };\n}\n\n/**\n * One on-chain batcher contract: it pools participants' encrypted amounts,\n * dispatches only the decrypted aggregate through the underlying ERC-4626\n * vault, and lets each participant claim their share. A vault has one batcher\n * per direction, so construct one instance for deposits and one for redeems.\n *\n * The lifecycle is `join` → `dispatchBatch` → `claim`, but finalization\n * between the last two is driven by the relayer, not by the caller: a batch\n * is claimable only once it reaches {@link BatchState.Finalized}, which can be\n * well after dispatch.\n */\nexport class VaultBatcher {\n /** The SDK instance this batcher reads and writes through. */\n readonly sdk: ZamaSDK;\n /** Checksummed address of the batcher contract. */\n readonly address: Address;\n\n readonly #vault: () => Promise<Address>;\n readonly #fromToken: () => Promise<Address>;\n readonly #toToken: () => Promise<Address>;\n\n // One instance, so repeated joins reuse the token's decrypted-balance cache.\n #fromTokenInstance: Promise<Token> | null = null;\n\n constructor(sdk: ZamaSDK, address: Address) {\n this.sdk = sdk;\n this.address = getAddress(address);\n this.#vault = memoizeAddressRead(() => sdk.provider.readContract(vaultContract(this.address)));\n this.#fromToken = memoizeAddressRead(() =>\n sdk.provider.readContract(fromTokenContract(this.address)),\n );\n this.#toToken = memoizeAddressRead(() =>\n sdk.provider.readContract(toTokenContract(this.address)),\n );\n }\n\n // READS\n\n /**\n * The underlying ERC-4626 vault. Share price (`convertToShares`,\n * `convertToAssets`, `totalAssets`) is read from it directly, not from the\n * batcher. Resolved once and cached.\n */\n async vault(): Promise<Address> {\n return this.#vault();\n }\n\n /**\n * The confidential token this batcher accepts as input (e.g. shares for a\n * redeem batcher). Resolved once and cached.\n */\n async fromToken(): Promise<Address> {\n return this.#fromToken();\n }\n\n /**\n * The confidential token this batcher pays out (e.g. shares for a\n * deposit batcher). Resolved once and cached.\n */\n async toToken(): Promise<Address> {\n return this.#toToken();\n }\n\n /** The id of the currently open (not-yet-dispatched) batch. */\n async currentBatchId(): Promise<bigint> {\n return this.sdk.provider.readContract(currentBatchIdContract(this.address));\n }\n\n /**\n * A batch's lifecycle state. See {@link BatchState} for which operation each\n * state allows.\n *\n * @throws Reverts on chain with `BatchNonexistent` for an id above\n * {@link currentBatchId} — batch ids start at 1.\n */\n async batchState(batchId: bigint): Promise<BatchState> {\n // The ABI types this uint8 enum as a plain `number`.\n const state = await this.sdk.provider.readContract(batchStateContract(this.address, batchId));\n return state as BatchState;\n }\n\n /** Whether the batcher is paused. While paused, `join` and `dispatchBatch` revert; `quit` and `claim` still work. */\n async paused(): Promise<boolean> {\n return this.sdk.provider.readContract(pausedContract(this.address));\n }\n\n /**\n * The policy for batches opened from now on. Dispatch of an existing batch\n * is gated on {@link batchMinBatchAge} instead.\n */\n async minBatchAge(): Promise<bigint> {\n return this.sdk.provider.readContract(minBatchAgeContract(this.address));\n }\n\n /** The minimum age in seconds pinned to `batchId` when it opened — the value dispatch enforces. */\n async batchMinBatchAge(batchId: bigint): Promise<bigint> {\n return this.sdk.provider.readContract(batchMinBatchAgeContract(this.address, batchId));\n }\n\n /**\n * How long a dispatched batch may wait for its decryption callback before it\n * is canceled — seconds, not a timestamp, despite the name. Applies to\n * batches opened from now on; for an existing batch use\n * {@link batchCallbackDeadline}.\n */\n async callbackDeadline(): Promise<bigint> {\n return this.sdk.provider.readContract(callbackDeadlineContract(this.address));\n }\n\n /**\n * The callback deadline pinned to `batchId` when it opened. Add it to\n * {@link batchDispatchedAt} for the timestamp that batch must finalize by.\n */\n async batchCallbackDeadline(batchId: bigint): Promise<bigint> {\n return this.sdk.provider.readContract(batchCallbackDeadlineContract(this.address, batchId));\n }\n\n /** The Unix timestamp (seconds) at which a batch was opened. */\n async batchCreatedAt(batchId: bigint): Promise<bigint> {\n return this.sdk.provider.readContract(batchCreatedAtContract(this.address, batchId));\n }\n\n /** The Unix timestamp (seconds) at which a batch was dispatched, or `0` if it hasn't been yet. */\n async batchDispatchedAt(batchId: bigint): Promise<bigint> {\n return this.sdk.provider.readContract(batchDispatchedAtContract(this.address, batchId));\n }\n\n /**\n * A finalized batch's exchange rate, scaled by\n * {@link exchangeRateDecimals}; `0` until the batch finalizes. A claim pays\n * out `deposit * exchangeRate / 10 ** exchangeRateDecimals`, rounded down.\n */\n async exchangeRate(batchId: bigint): Promise<bigint> {\n return this.sdk.provider.readContract(exchangeRateContract(this.address, batchId));\n }\n\n /** The number of decimals {@link exchangeRate} is scaled by. */\n async exchangeRateDecimals(): Promise<number> {\n return this.sdk.provider.readContract(exchangeRateDecimalsContract(this.address));\n }\n\n /**\n * Seconds until `batchId` becomes eligible for dispatch, `0` once it already\n * is — the earliest possible moment, not a promise anyone will dispatch\n * then. `null` once the batch has left {@link BatchState.Pending} and can\n * never be dispatched again.\n *\n * Measured against the chain's block timestamp and the batch's own pinned\n * minimum age, so neither local clock drift nor a mid-flight policy change\n * desyncs the countdown.\n */\n async timeUntilDispatchable(batchId: bigint): Promise<bigint | null> {\n const [state, createdAt, minAge, now] = await Promise.all([\n this.batchState(batchId),\n this.batchCreatedAt(batchId),\n this.batchMinBatchAge(batchId),\n this.sdk.provider.getBlockTimestamp(),\n ]);\n if (state !== BatchState.Pending) {\n return null;\n }\n const eligibleAt = createdAt + minAge;\n return eligibleAt > now ? eligibleAt - now : 0n;\n }\n\n /** The encrypted aggregate amount joined into a batch, without decrypting it. */\n async confidentialTotalDeposits(batchId: bigint): Promise<EncryptedValue> {\n return this.sdk.provider.readContract(totalDepositsContract(this.address, batchId));\n }\n\n /** The encrypted amount `account` joined into a batch, without decrypting it. */\n async confidentialDepositOf(batchId: bigint, account: Address): Promise<EncryptedValue> {\n return this.sdk.provider.readContract(\n depositsContract(this.address, batchId, getAddress(account)),\n );\n }\n\n /**\n * Decrypt and return the plaintext amount `account` joined into a batch.\n * Acquires FHE credentials via a wallet signature if none are cached.\n */\n async depositOf(batchId: bigint, account: Address): Promise<bigint> {\n const normalizedAccount = getAddress(account);\n const encryptedValue = await this.confidentialDepositOf(batchId, normalizedAccount);\n if (isEncryptedValueZero(encryptedValue)) {\n return 0n;\n }\n const result = await this.sdk.decryption.decryptValues([\n { encryptedValue, contractAddress: this.address },\n ]);\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(`Decryption returned no value for ${encryptedValue}`);\n }\n assertBigint(value, \"depositOf: result[encryptedValue]\");\n return value;\n }\n\n // WRITES\n\n /**\n * Join the currently open batch with a plaintext amount, encrypted via FHE\n * automatically. Once someone calls {@link dispatchBatch} and the relayer\n * finalizes it, call {@link claim} to receive the output.\n *\n * @param amount - The plaintext amount to contribute; encrypted before submission.\n * @param beneficiary - Recipient of the batch's eventual output. Defaults to the connected wallet account.\n *\n * @remarks\n * The batcher must already hold an ERC-7984 operator grant from the caller,\n * or it cannot pull the amount. A join with too little balance still\n * succeeds on chain and credits nothing, so the amount is checked against\n * the caller's confidential balance first; `confidentialJoinedAmount` is the\n * authoritative record of what actually landed.\n *\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 */\n async join(amount: bigint, beneficiary?: Address, options?: JoinOptions): Promise<JoinResult> {\n this.#requireSigner(\"join\");\n const account = await requireAlignedWalletAccount(\"join\", this.sdk.signer, this.sdk.provider);\n const userAddress = getAddress(account.address);\n const resolvedBeneficiary = beneficiary ? getAddress(beneficiary) : userAddress;\n\n if (!options?.skipBalanceCheck) {\n await this.#assertJoinableBalance(amount);\n }\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress,\n });\n\n const encryptedAmount = encryptedValues[0];\n if (!encryptedAmount) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n const result = await this.#submitTransaction(\n \"vault:join\",\n joinContract(this.address, resolvedBeneficiary, encryptedAmount, inputProof),\n );\n\n const joined = findJoined(result.receipt.logs, this.address, resolvedBeneficiary);\n if (!joined) {\n throw new TransactionRevertedError(\n `No Joined event for ${resolvedBeneficiary} from batcher ${this.address} found in the join receipt`,\n );\n }\n return {\n ...result,\n batchId: joined.batchId,\n beneficiary: joined.account,\n confidentialJoinedAmount: joined.confidentialAmount,\n };\n }\n\n /**\n * Withdraw the caller's own deposit from a batch, returning it to their\n * confidential balance on `fromToken`.\n *\n * Legal in two states: {@link BatchState.Pending} (undo a join before\n * dispatch) and {@link BatchState.Canceled} (take the deposit back after a\n * batch failed to finalize).\n *\n * Refunds the caller only. To refund someone else's deposit in a canceled\n * batch, use {@link recover}.\n */\n async quit(batchId: bigint): Promise<TransactionResult> {\n this.#requireSigner(\"quit\");\n await requireChainAlignment(\"quit\", this.sdk.signer, this.sdk.provider);\n return this.#submitTransaction(\"vault:quit\", quitContract(this.address, batchId));\n }\n\n /**\n * Refund `account`'s deposit in a canceled batch on their behalf.\n * Permissionless — anyone can call this, and the refund always goes to\n * `account`, never to the caller.\n *\n * Only legal once the batch reaches {@link BatchState.Canceled}; before that,\n * a participant undoes their own join with {@link quit}.\n *\n * @param account - The depositor to refund. Defaults to the connected wallet account.\n */\n async recover(batchId: bigint, account?: Address): Promise<TransactionResult> {\n const target = await this.#resolveTarget(\"recover\", account);\n return this.#submitTransaction(\"vault:recover\", recoverContract(this.address, batchId, target));\n }\n\n /**\n * Claim a finalized batch's output for `account`. Permissionless — anyone\n * can call this on another account's behalf, and the output always goes to\n * `account`, never to the caller. The amount is not returned; read it as a\n * balance on the batcher's {@link toToken}.\n *\n * Only legal once the batch reaches {@link BatchState.Finalized}; on a\n * canceled batch use {@link quit} or {@link recover} instead.\n *\n * @param account - The account to claim for. Defaults to the connected wallet account.\n */\n async claim(batchId: bigint, account?: Address): Promise<TransactionResult> {\n const target = await this.#resolveTarget(\"claim\", account);\n return this.#submitTransaction(\"vault:claim\", claimContract(this.address, batchId, target));\n }\n\n /**\n * Close the current batch once it has reached its pinned minimum age and\n * kick off decryption of its aggregate amount. Permissionless — any\n * account with a configured signer can call this, not just participants.\n * Reverts while the batcher is {@link paused}.\n */\n async dispatchBatch(): Promise<TransactionResult> {\n this.#requireSigner(\"dispatchBatch\");\n await requireChainAlignment(\"dispatchBatch\", this.sdk.signer, this.sdk.provider);\n return this.#submitTransaction(\"vault:dispatchBatch\", dispatchBatchContract(this.address));\n }\n\n // INTERNAL\n\n #requireSigner(operation: string): GenericSigner {\n if (!this.sdk.signer) {\n throw new SignerNotConfiguredError(operation);\n }\n return this.sdk.signer;\n }\n\n async #inputToken(): Promise<Token> {\n this.#fromTokenInstance ??= this.fromToken()\n .then((address) => new Token(this.sdk, address))\n .catch((error: unknown) => {\n this.#fromTokenInstance = null;\n throw error;\n });\n return this.#fromTokenInstance;\n }\n\n async #assertJoinableBalance(amount: bigint): Promise<void> {\n const token = await this.#inputToken();\n return assertConfidentialBalance({\n operation: \"join\",\n tokenAddress: token.address,\n amount,\n signer: this.sdk.signer,\n provider: this.sdk.provider,\n readBalance: (owner) => token.balanceOf(owner),\n });\n }\n\n /**\n * Chain alignment is verified even when `account` is someone else's: the\n * connected signer still submits the transaction.\n */\n async #resolveTarget(operation: string, account: Address | undefined): Promise<Address> {\n this.#requireSigner(operation);\n if (account) {\n await requireChainAlignment(operation, this.sdk.signer, this.sdk.provider);\n return getAddress(account);\n }\n const aligned = await requireAlignedWalletAccount(\n operation,\n this.sdk.signer,\n this.sdk.provider,\n );\n return getAddress(aligned.address);\n }\n\n async #submitTransaction(\n operation: TransactionOperation,\n config: WriteContractConfig,\n ): Promise<TransactionResult> {\n return submitSdkTransaction({\n operation,\n signer: this.#requireSigner(operation),\n provider: this.sdk.provider,\n config,\n emit: (input) => this.sdk.emitEvent(input, this.address),\n logger: this.sdk.logger,\n });\n }\n}\n\n/**\n * Create a {@link VaultBatcher} bound to `sdk` for the batcher contract at `address`.\n *\n * @example\n * ```ts\n * import { createVaultBatcher } from \"@zama-fhe/sdk/vaults\";\n *\n * const depositBatcher = createVaultBatcher(sdk, \"0xDepositBatcher\");\n * const { batchId } = await depositBatcher.join(1_000_000n);\n * ```\n */\nexport function createVaultBatcher(sdk: ZamaSDK, address: Address): VaultBatcher {\n return new VaultBatcher(sdk, address);\n}\n","import { getAddress, type Address } from \"viem\";\nimport { ConfigurationError, SignerNotConfiguredError } from \"../errors\";\nimport { WrappedToken } from \"../token\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { JoinResult, VaultAddresses, VaultJoinOptions } from \"./types\";\nimport { VaultBatcher } from \"./vault-batcher\";\n\n/**\n * A confidential ERC-4626 vault: one deposit batcher and one redeem batcher\n * behind ERC-4626-style `deposit` and `redeem` methods.\n *\n * Claiming, quitting and batch state live on the two batchers directly —\n * `vault.depositBatcher.claim(batchId)`.\n */\nexport class Vault {\n /** The SDK instance this vault reads and writes through. */\n readonly sdk: ZamaSDK;\n /** Joined by deposits of the underlying asset. */\n readonly depositBatcher: VaultBatcher;\n /** Joined by share redemptions. */\n readonly redeemBatcher: VaultBatcher;\n\n // The promise is cached, not just the resolved value, so concurrent callers\n // share one lookup and end up with the same instance.\n #vaultAddress: Promise<Address> | null = null;\n #cAsset: Promise<WrappedToken> | null = null;\n #cShare: Promise<WrappedToken> | null = null;\n\n readonly #expectedVaultAddress: Address | undefined;\n\n constructor(sdk: ZamaSDK, addresses: VaultAddresses) {\n this.sdk = sdk;\n this.#expectedVaultAddress = addresses.vault ? getAddress(addresses.vault) : undefined;\n this.depositBatcher = new VaultBatcher(sdk, addresses.depositBatcher);\n this.redeemBatcher = new VaultBatcher(sdk, addresses.redeemBatcher);\n }\n\n /**\n * The underlying ERC-4626 vault contract, read from both batchers rather\n * than trusted from configuration. Resolved once and cached.\n *\n * @throws if the batchers report different vaults, or either disagrees with\n * an `addresses.vault` passed to the constructor — a mismatched pair would\n * settle deposits and redemptions against different vaults.\n * {@link ConfigurationError}\n */\n async vaultAddress(): Promise<Address> {\n this.#vaultAddress ??= this.#resolveVaultAddress().catch((error: unknown) => {\n this.#vaultAddress = null;\n throw error;\n });\n return this.#vaultAddress;\n }\n\n /**\n * The confidential wrapper of the vault's underlying asset — the token\n * deposits are paid in. Resolved once and cached.\n */\n async cAsset(): Promise<WrappedToken> {\n this.#cAsset ??= this.depositBatcher\n .fromToken()\n .then((address) => new WrappedToken(this.sdk, address))\n .catch((error: unknown) => {\n this.#cAsset = null;\n throw error;\n });\n return this.#cAsset;\n }\n\n /**\n * The confidential share token this vault issues. Resolved once and cached.\n *\n * Read from the redeem batcher, which is the contract that actually pulls\n * these shares and so decides which token a redemption must grant on.\n */\n async cShare(): Promise<WrappedToken> {\n this.#cShare ??= this.redeemBatcher\n .fromToken()\n .then((address) => new WrappedToken(this.sdk, address))\n .catch((error: unknown) => {\n this.#cShare = null;\n throw error;\n });\n return this.#cShare;\n }\n\n /**\n * Deposit a plaintext amount of the underlying confidential asset,\n * joining the current deposit batch. Grants the deposit batcher an\n * ERC-7984 operator approval on the deposit token first, unless one is\n * already active.\n *\n * @param amount - The plaintext amount to deposit.\n * @throws before any approval is granted, if the batchers do not agree on\n * the vault. {@link ConfigurationError}\n */\n async deposit(amount: bigint, options?: VaultJoinOptions): Promise<JoinResult> {\n const [, token] = await Promise.all([this.vaultAddress(), this.cAsset()]);\n await this.#ensureOperator(\n \"deposit\",\n token,\n this.depositBatcher.address,\n options?.operatorUntil,\n );\n return this.depositBatcher.join(amount, options?.beneficiary, {\n skipBalanceCheck: options?.skipBalanceCheck,\n });\n }\n\n /**\n * Join the current redeem batch, which the vault later settles into the\n * underlying asset at the batch's exchange rate. Grants the redeem batcher\n * an ERC-7984 operator approval on the share token first, unless one is\n * already active.\n *\n * @param amount - The plaintext amount of shares — ERC-4626 `redeem`, not\n * `withdraw`, so this is denominated in shares, never in assets.\n * @throws before any approval is granted, if the batchers do not agree on\n * the vault. {@link ConfigurationError}\n */\n async redeem(amount: bigint, options?: VaultJoinOptions): Promise<JoinResult> {\n const [, token] = await Promise.all([this.vaultAddress(), this.cShare()]);\n await this.#ensureOperator(\"redeem\", token, this.redeemBatcher.address, options?.operatorUntil);\n return this.redeemBatcher.join(amount, options?.beneficiary, {\n skipBalanceCheck: options?.skipBalanceCheck,\n });\n }\n\n async #resolveVaultAddress(): Promise<Address> {\n const [depositVault, redeemVault] = await Promise.all([\n this.depositBatcher.vault(),\n this.redeemBatcher.vault(),\n ]);\n if (getAddress(depositVault) !== getAddress(redeemVault)) {\n throw new ConfigurationError(\n `Vault batchers point at different ERC-4626 vaults: deposit batcher ${this.depositBatcher.address} reports ${depositVault}, redeem batcher ${this.redeemBatcher.address} reports ${redeemVault}`,\n );\n }\n const onChain = getAddress(depositVault);\n if (this.#expectedVaultAddress !== undefined && this.#expectedVaultAddress !== onChain) {\n throw new ConfigurationError(\n `Configured vault address ${this.#expectedVaultAddress} does not match the ${onChain} both batchers report`,\n );\n }\n return onChain;\n }\n\n /**\n * The batcher pulls with `confidentialTransferFrom`, which ERC-7984 rejects\n * unless the batcher is already an operator of the caller.\n */\n async #ensureOperator(\n operation: string,\n token: WrappedToken,\n operator: Address,\n until: number | undefined,\n ): Promise<void> {\n if (!this.sdk.signer) {\n throw new SignerNotConfiguredError(operation);\n }\n const account = this.sdk.signer.requireWalletAccount(operation);\n const alreadyApproved = await token.isOperator(account.address, operator);\n if (!alreadyApproved) {\n await token.setOperator(operator, until);\n }\n }\n}\n\n/**\n * Create a {@link Vault} bound to `sdk` for the deposit/redeem batchers at `addresses`.\n *\n * @example\n * ```ts\n * import { createVault } from \"@zama-fhe/sdk/vaults\";\n *\n * const vault = createVault(sdk, {\n * depositBatcher: \"0xDepositBatcher\",\n * redeemBatcher: \"0xRedeemBatcher\",\n * });\n * const { batchId } = await vault.deposit(1_000_000n);\n * // …once the batch is dispatched and reaches BatchState.Finalized:\n * await vault.depositBatcher.claim(batchId);\n * ```\n */\nexport function createVault(sdk: ZamaSDK, addresses: VaultAddresses): Vault {\n return new Vault(sdk, addresses);\n}\n","import { getAddress, type Address } from \"viem\";\n\n/**\n * Query keys for the vaults module.\n *\n * A `batcher(...)` key is a prefix of every `batch(...)` key for that batcher,\n * so invalidating it clears all of them at once.\n */\nexport const vaultQueryKeys = {\n currentBatchId: {\n batcher: (batcherAddress: Address) =>\n [\"zama.vault.currentBatchId\", { batcherAddress: getAddress(batcherAddress) }] as const,\n },\n batchState: {\n batcher: (batcherAddress: Address) =>\n [\"zama.vault.batchState\", { batcherAddress: getAddress(batcherAddress) }] as const,\n batch: (batcherAddress: Address, batchId: bigint | undefined) =>\n [\"zama.vault.batchState\", { batcherAddress: getAddress(batcherAddress), batchId }] as const,\n },\n timeUntilDispatchable: {\n batcher: (batcherAddress: Address) =>\n [\"zama.vault.timeUntilDispatchable\", { batcherAddress: getAddress(batcherAddress) }] as const,\n batch: (batcherAddress: Address, batchId: bigint | undefined) =>\n [\n \"zama.vault.timeUntilDispatchable\",\n { batcherAddress: getAddress(batcherAddress), batchId },\n ] as const,\n },\n};\n","import type { Address } from \"viem\";\nimport { invalidateBalanceQueries, type QueryClientLike } from \"../../query/invalidation\";\nimport { vaultQueryKeys } from \"./query-keys\";\n\n/** Invalidates every cached batch read for a batcher. */\nexport function invalidateBatchQueries(\n queryClient: QueryClientLike,\n batcherAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: vaultQueryKeys.currentBatchId.batcher(batcherAddress),\n });\n void queryClient.invalidateQueries({\n queryKey: vaultQueryKeys.batchState.batcher(batcherAddress),\n });\n void queryClient.invalidateQueries({\n queryKey: vaultQueryKeys.timeUntilDispatchable.batcher(batcherAddress),\n });\n}\n\n/** Invalidates the caches affected by a join: the input token's balance, and the batcher's batch reads. */\nexport function invalidateAfterJoin(\n queryClient: QueryClientLike,\n params: { batcherAddress: Address; fromToken: Address },\n): void {\n invalidateBalanceQueries(queryClient, params.fromToken);\n invalidateBatchQueries(queryClient, params.batcherAddress);\n}\n\n/** Invalidates the caches affected by a quit or recover: the input token's balance and the batcher's batch reads. */\nexport function invalidateAfterQuit(\n queryClient: QueryClientLike,\n params: { batcherAddress: Address; fromToken: Address },\n): void {\n invalidateBalanceQueries(queryClient, params.fromToken);\n invalidateBatchQueries(queryClient, params.batcherAddress);\n}\n\n/** Invalidates the caches affected by a claim: the output token's balance. */\nexport function invalidateAfterClaim(\n queryClient: QueryClientLike,\n params: { toToken: Address },\n): void {\n invalidateBalanceQueries(queryClient, params.toToken);\n}\n\n/** Invalidates the caches affected by a dispatch: a new batch opens and the old one leaves `Pending`. */\nexport function invalidateAfterDispatchBatch(\n queryClient: QueryClientLike,\n batcherAddress: Address,\n): void {\n invalidateBatchQueries(queryClient, batcherAddress);\n}\n","import type { QueryFactoryOptions } from \"../../query/factory-types\";\nimport { filterQueryOptions } from \"../../query/utils\";\nimport type { VaultBatcher } from \"../vault-batcher\";\nimport { vaultQueryKeys } from \"./query-keys\";\n\n/** Configuration for {@link currentBatchIdQueryOptions}. */\nexport interface CurrentBatchIdQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Query options for a batcher's currently open batch id. */\nexport function currentBatchIdQueryOptions(\n batcher: VaultBatcher,\n config: CurrentBatchIdQueryConfig = {},\n): QueryFactoryOptions<\n bigint,\n Error,\n bigint,\n ReturnType<typeof vaultQueryKeys.currentBatchId.batcher>\n> {\n const queryOpts = config.query ?? {};\n\n return {\n ...filterQueryOptions(queryOpts),\n queryKey: vaultQueryKeys.currentBatchId.batcher(batcher.address),\n queryFn: async () => batcher.currentBatchId(),\n enabled: queryOpts.enabled !== false,\n };\n}\n","import { assertNonNullable } from \"../../utils/assertions\";\nimport type { QueryFactoryOptions } from \"../../query/factory-types\";\nimport { filterQueryOptions } from \"../../query/utils\";\nimport type { BatchState } from \"../types\";\nimport type { VaultBatcher } from \"../vault-batcher\";\nimport { vaultQueryKeys } from \"./query-keys\";\n\n/** Configuration for {@link batchStateQueryOptions}. */\nexport interface BatchStateQueryConfig {\n /** Batch to read the state of; the query stays disabled until provided. */\n batchId?: bigint;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Query options for a batch's lifecycle state — see {@link BatchState}. */\nexport function batchStateQueryOptions(\n batcher: VaultBatcher,\n config: BatchStateQueryConfig = {},\n): QueryFactoryOptions<\n BatchState,\n Error,\n BatchState,\n ReturnType<typeof vaultQueryKeys.batchState.batch>\n> {\n const queryOpts = config.query ?? {};\n\n return {\n ...filterQueryOptions(queryOpts),\n queryKey: vaultQueryKeys.batchState.batch(batcher.address, config.batchId),\n queryFn: async (context) => {\n const [, { batchId }] = context.queryKey;\n assertNonNullable(batchId, \"batchStateQueryOptions: batchId\");\n return batcher.batchState(batchId);\n },\n enabled: config.batchId !== undefined && queryOpts.enabled !== false,\n };\n}\n","import type { QueryFactoryOptions } from \"../../query/factory-types\";\nimport { filterQueryOptions } from \"../../query/utils\";\nimport { assertNonNullable } from \"../../utils/assertions\";\nimport type { VaultBatcher } from \"../vault-batcher\";\nimport { vaultQueryKeys } from \"./query-keys\";\n\n/** Configuration for {@link timeUntilDispatchableQueryOptions}. */\nexport interface TimeUntilDispatchableQueryConfig {\n /** Batch to check; the query stays disabled until provided. */\n batchId?: bigint;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/**\n * Query options for the seconds remaining until a batch can be dispatched, or\n * `null` once the batch has left `Pending` and can no longer be dispatched —\n * see {@link VaultBatcher.timeUntilDispatchable}.\n */\nexport function timeUntilDispatchableQueryOptions(\n batcher: VaultBatcher,\n config: TimeUntilDispatchableQueryConfig = {},\n): QueryFactoryOptions<\n bigint | null,\n Error,\n bigint | null,\n ReturnType<typeof vaultQueryKeys.timeUntilDispatchable.batch>\n> {\n const queryOpts = config.query ?? {};\n\n return {\n ...filterQueryOptions(queryOpts),\n queryKey: vaultQueryKeys.timeUntilDispatchable.batch(batcher.address, config.batchId),\n queryFn: async (context) => {\n const [, { batchId }] = context.queryKey;\n assertNonNullable(batchId, \"timeUntilDispatchableQueryOptions: batchId\");\n return batcher.timeUntilDispatchable(batchId);\n },\n enabled: config.batchId !== undefined && queryOpts.enabled !== false,\n };\n}\n","import type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"../../query/factory-types\";\nimport type { Vault } from \"../vault\";\nimport type { JoinResult, VaultJoinOptions } from \"../types\";\n\n/** Variables for {@link depositMutationOptions}. */\nexport interface DepositParams extends VaultJoinOptions {\n /** Plaintext amount to deposit. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link Vault.deposit | depositing} into a vault. */\nexport function depositMutationOptions(\n vault: Vault,\n): MutationFactoryOptions<readonly [\"zama.vault.deposit\", Address], DepositParams, JoinResult> {\n return {\n mutationKey: [\"zama.vault.deposit\", vault.depositBatcher.address] as const,\n mutationFn: async ({ amount, ...rest }) => vault.deposit(amount, rest),\n };\n}\n","import type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"../../query/factory-types\";\nimport type { Vault } from \"../vault\";\nimport type { JoinResult, VaultJoinOptions } from \"../types\";\n\n/** Variables for {@link redeemMutationOptions}. */\nexport interface RedeemParams extends VaultJoinOptions {\n /** Plaintext amount of shares to redeem. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link Vault.redeem | redeeming shares}. */\nexport function redeemMutationOptions(\n vault: Vault,\n): MutationFactoryOptions<readonly [\"zama.vault.redeem\", Address], RedeemParams, JoinResult> {\n return {\n mutationKey: [\"zama.vault.redeem\", vault.redeemBatcher.address] as const,\n mutationFn: async ({ amount, ...rest }) => vault.redeem(amount, rest),\n };\n}\n","import type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"../../query/factory-types\";\nimport type { JoinOptions, JoinResult } from \"../types\";\nimport type { VaultBatcher } from \"../vault-batcher\";\n\n/** Variables for {@link joinMutationOptions}. */\nexport interface JoinParams extends JoinOptions {\n /** Plaintext amount to contribute to the batch. */\n amount: bigint;\n /** Recipient of the batch's eventual output. Defaults to the connected wallet account. */\n beneficiary?: Address;\n}\n\n/**\n * Builds TanStack Query mutation options for {@link VaultBatcher.join | joining} a batch directly.\n * Low-level — most apps should use `depositMutationOptions` / `redeemMutationOptions` instead.\n */\nexport function joinMutationOptions(\n batcher: VaultBatcher,\n): MutationFactoryOptions<readonly [\"zama.vault.join\", Address], JoinParams, JoinResult> {\n return {\n mutationKey: [\"zama.vault.join\", batcher.address] as const,\n mutationFn: async ({ amount, beneficiary, ...options }) =>\n batcher.join(amount, beneficiary, options),\n };\n}\n","import type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"../../query/factory-types\";\nimport type { TransactionResult } from \"../../types\";\nimport type { VaultBatcher } from \"../vault-batcher\";\n\n/** Variables for {@link claimMutationOptions}. */\nexport interface ClaimParams {\n /** The finalized batch to claim from. */\n batchId: bigint;\n /** The account to claim for. Defaults to the connected wallet account. */\n account?: Address;\n}\n\n/** Builds TanStack Query mutation options for {@link VaultBatcher.claim | claiming} a finalized batch. */\nexport function claimMutationOptions(\n batcher: VaultBatcher,\n): MutationFactoryOptions<readonly [\"zama.vault.claim\", Address], ClaimParams, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.claim\", batcher.address] as const,\n mutationFn: async ({ batchId, account }) => batcher.claim(batchId, account),\n };\n}\n","import type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"../../query/factory-types\";\nimport type { TransactionResult } from \"../../types\";\nimport type { VaultBatcher } from \"../vault-batcher\";\n\n/** Variables for {@link quitMutationOptions}. */\nexport interface QuitParams {\n /** The pending or canceled batch to withdraw the caller's own deposit from. */\n batchId: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link VaultBatcher.quit | withdrawing a deposit} from a pending or canceled batch. */\nexport function quitMutationOptions(\n batcher: VaultBatcher,\n): MutationFactoryOptions<readonly [\"zama.vault.quit\", Address], QuitParams, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.quit\", batcher.address] as const,\n mutationFn: async ({ batchId }) => batcher.quit(batchId),\n };\n}\n","import type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"../../query/factory-types\";\nimport type { TransactionResult } from \"../../types\";\nimport type { VaultBatcher } from \"../vault-batcher\";\n\n/** Variables for {@link recoverMutationOptions}. */\nexport interface RecoverParams {\n /** The canceled batch holding the deposit. */\n batchId: bigint;\n /** The depositor to refund. Defaults to the connected wallet account. */\n account?: Address;\n}\n\n/** Builds TanStack Query mutation options for {@link VaultBatcher.recover | refunding a deposit} in a canceled batch on the depositor's behalf. */\nexport function recoverMutationOptions(\n batcher: VaultBatcher,\n): MutationFactoryOptions<\n readonly [\"zama.vault.recover\", Address],\n RecoverParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.vault.recover\", batcher.address] as const,\n mutationFn: async ({ batchId, account }) => batcher.recover(batchId, account),\n };\n}\n","import type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"../../query/factory-types\";\nimport type { TransactionResult } from \"../../types\";\nimport type { VaultBatcher } from \"../vault-batcher\";\n\n/** Builds TanStack Query mutation options for {@link VaultBatcher.dispatchBatch | dispatching} the current batch. Permissionless — takes no variables. */\nexport function dispatchBatchMutationOptions(\n batcher: VaultBatcher,\n): MutationFactoryOptions<readonly [\"zama.vault.dispatchBatch\", Address], void, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.dispatchBatch\", batcher.address] as const,\n mutationFn: async () => batcher.dispatchBatch(),\n };\n}\n"],"mappings":"iTAKA,MAAa,EAAkB,CAC7B,CACE,KAAM,WACN,KAAM,wBACN,OAAQ,CAAC,CAAE,KAAM,UAAW,KAAM,UAAW,aAAc,SAAU,CAAC,EACtE,QAAS,CAAC,CAAE,KAAM,GAAI,KAAM,UAAW,aAAc,SAAU,CAAC,EAChE,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,iBACN,OAAQ,CAAC,CAAE,KAAM,UAAW,KAAM,UAAW,aAAc,SAAU,CAAC,EACtE,QAAS,CAAC,CAAE,KAAM,GAAI,KAAM,UAAW,aAAc,SAAU,CAAC,EAChE,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,oBACN,OAAQ,CAAC,CAAE,KAAM,UAAW,KAAM,UAAW,aAAc,SAAU,CAAC,EACtE,QAAS,CAAC,CAAE,KAAM,GAAI,KAAM,UAAW,aAAc,SAAU,CAAC,EAChE,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,sBACN,OAA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AAa,GAAG,KAC3C,EAAQ,KAAK,EAAQ,EAAa,CAAO,CAC7C,CACF,CCXA,SAAgB,EACd,EACgG,CAChG,MAAO,CACL,YAAa,CAAC,mBAAoB,EAAQ,OAAO,EACjD,WAAY,MAAO,CAAE,UAAS,aAAc,EAAQ,MAAM,EAAS,CAAO,CAC5E,CACF,CCTA,SAAgB,EACd,EAC8F,CAC9F,MAAO,CACL,YAAa,CAAC,kBAAmB,EAAQ,OAAO,EAChD,WAAY,MAAO,CAAE,aAAc,EAAQ,KAAK,CAAO,CACzD,CACF,CCLA,SAAgB,EACd,EAKA,CACA,MAAO,CACL,YAAa,CAAC,qBAAsB,EAAQ,OAAO,EACnD,WAAY,MAAO,CAAE,UAAS,aAAc,EAAQ,QAAQ,EAAS,CAAO,CAC9E,CACF,CCnBA,SAAgB,GACd,EACiG,CACjG,MAAO,CACL,YAAa,CAAC,2BAA4B,EAAQ,OAAO,EACzD,WAAY,SAAY,EAAQ,cAAc,CAChD,CACF"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../wrappers-registry.cjs"),t=require("../base-signer.cjs"),n=require("../eip1193-subscribe.cjs");let r=require("viem");var i=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){return this.#e.readContract(e)}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getBlockTimestamp(){return(await this.#e.getBlock()).timestamp}async prepareTransaction(t){let{from:n,calldata:i}=t,a=(0,r.encodeFunctionData)({abi:i.abi,functionName:i.functionName,args:i.args}),o=this.#e.getChainId(),s=t.nonce===void 0?this.#e.getTransactionCount({address:n,blockTag:`pending`}):Promise.resolve(t.nonce),c=t.gasLimit===void 0?i.gas??this.#e.estimateGas({account:n,to:i.address,data:a,value:i.value??0n}).catch(t=>{throw new e.it(`ViemProvider.prepareTransaction: gas estimation reverted for ${i.functionName} on ${i.address}`,{cause:t})}):Promise.resolve(t.gasLimit),l=t.fees??this.#e.estimateFeesPerGas(),[u,d,f,p]=await Promise.all([o,s,c,l]);return(0,r.serializeTransaction)({type:`eip1559`,chainId:u,nonce:d,to:i.address,data:a,value:i.value??0n,gas:f,maxFeePerGas:p.maxFeePerGas,maxPriorityFeePerGas:p.maxPriorityFeePerGas})}};function a(e){let t=(e.primaryType?e.types[e.primaryType]:void 0)??[],n={...e.message};for(let{name:e,type:r}of t)/^uint\d*$/.test(r)&&(n[e]=BigInt(n[e]));return n}function o(e){if(!(!e.account||!e.chain))return{address:(0,r.getAddress)(e.account.address),chainId:e.chain.id}}var s=class extends t.t{#e;#t;#n;constructor(e){super(o(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(t){if(!this.#e.account)throw new e.nt(t);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`),{EIP712Domain:r,...i}=e.types;return t.signTypedData({account:n,primaryType:e.primaryType,types:i,domain:e.domain,message:a(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?n.t({provider:this.#t,getInitialWalletAccount:()=>o(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function c(e){return t.i(new s({walletClient:e.walletClient,ethereum:e.ethereum}),new i({publicClient:e.publicClient}),e)}function l(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function u(t,n,r){return t.readContract(e.S(n,r))}function d(t,n){return t.readContract(e.N(n))}function f(t,n,r){return t.readContract(e.m(n,r))}function p(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.T(n,r,i,a)})}function m(t,n,r,i,a,o){return t.writeContract({chain:t.chain,account:l(t),...e.P(n,r,i,a,o)})}function h(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.F(n,r,i,a)})}function g(t,n,r,i,a){return t.writeContract({chain:t.chain,account:l(t),...e.O(n,r,i,a)})}function _(t,n,r,i){return t.writeContract({chain:t.chain,account:l(t),...e.M(n,r,i)})}function v(t,n,r,i){return t.writeContract({chain:t.chain,account:l(t),...e.L(n,r,i)})}function y(t,n){return t.readContract(e.i(n))}function b(t,n){return t.readContract(e.a(n))}function x(t,n,r,i){return t.readContract(e.o(n,r,i))}function S(t,n,r){return t.readContract(e.r(n,r))}function C(t,n,r){return t.readContract(e.t(n,r))}function w(t,n,r){return t.readContract(e.n(n,r))}function T(t,n,r){return t.readContract(e.s(n,r))}exports.BaseSigner=t.t,exports.ViemProvider=i,exports.ViemSigner=s,exports.ZamaSDKEvents=e.Z,exports.createConfig=c,exports.readConfidentialBalanceOfContract=u,exports.readConfidentialTokenAddressContract=C,exports.readIsConfidentialTokenValidContract=T,exports.readSupportsInterfaceContract=f,exports.readTokenAddressContract=w,exports.readTokenPairContract=S,exports.readTokenPairsContract=y,exports.readTokenPairsLengthContract=b,exports.readTokenPairsSliceContract=x,exports.readUnderlyingTokenContract=d,exports.writeConfidentialTransferContract=p,exports.writeFinalizeUnwrapContract=g,exports.writeSetOperatorContract=_,exports.writeUnwrapContract=m,exports.writeUnwrapFromBalanceContract=h,exports.writeWrapContract=v;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../erc165.cjs"),t=require("../base-signer.cjs"),n=require("../wrappers-registry.cjs"),r=require("../eip1193-subscribe.cjs");let i=require("viem");var a=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){return this.#e.readContract(e)}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getBlockTimestamp(){return(await this.#e.getBlock()).timestamp}async prepareTransaction(t){let{from:n,calldata:r}=t,a=(0,i.encodeFunctionData)({abi:r.abi,functionName:r.functionName,args:r.args}),o=this.#e.getChainId(),s=t.nonce===void 0?this.#e.getTransactionCount({address:n,blockTag:`pending`}):Promise.resolve(t.nonce),c=t.gasLimit===void 0?r.gas??this.#e.estimateGas({account:n,to:r.address,data:a,value:r.value??0n}).catch(t=>{throw new e.z(`ViemProvider.prepareTransaction: gas estimation reverted for ${r.functionName} on ${r.address}`,{cause:t})}):Promise.resolve(t.gasLimit),l=t.fees??this.#e.estimateFeesPerGas(),[u,d,f,p]=await Promise.all([o,s,c,l]);return(0,i.serializeTransaction)({type:`eip1559`,chainId:u,nonce:d,to:r.address,data:a,value:r.value??0n,gas:f,maxFeePerGas:p.maxFeePerGas,maxPriorityFeePerGas:p.maxPriorityFeePerGas})}};function o(e){let t=(e.primaryType?e.types[e.primaryType]:void 0)??[],n={...e.message};for(let{name:e,type:r}of t)/^uint\d*$/.test(r)&&(n[e]=BigInt(n[e]));return n}function s(e){if(!(!e.account||!e.chain))return{address:(0,i.getAddress)(e.account.address),chainId:e.chain.id}}var c=class extends t.t{#e;#t;#n;constructor(e){super(s(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(t){if(!this.#e.account)throw new e.L(t);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`),{EIP712Domain:r,...i}=e.types;return t.signTypedData({account:n,primaryType:e.primaryType,types:i,domain:e.domain,message:o(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?r.t({provider:this.#t,getInitialWalletAccount:()=>s(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function l(e){return t.i(new c({walletClient:e.walletClient,ethereum:e.ethereum}),new a({publicClient:e.publicClient}),e)}function u(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function d(t,n,r){return t.readContract(e.h(n,r))}function f(t,n){return t.readContract(e.E(n))}function p(t,n,r){return t.readContract(e.s(n,r))}function m(t,n,r,i,a){return t.writeContract({chain:t.chain,account:u(t),...e.v(n,r,i,a)})}function h(t,n,r,i,a,o){return t.writeContract({chain:t.chain,account:u(t),...e.D(n,r,i,a,o)})}function g(t,n,r,i,a){return t.writeContract({chain:t.chain,account:u(t),...e.O(n,r,i,a)})}function _(t,n,r,i,a){return t.writeContract({chain:t.chain,account:u(t),...e.x(n,r,i,a)})}function v(t,n,r,i){return t.writeContract({chain:t.chain,account:u(t),...e.T(n,r,i)})}function y(t,n,r,i){return t.writeContract({chain:t.chain,account:u(t),...e.A(n,r,i)})}function b(e,t){return e.readContract(n.i(t))}function x(e,t){return e.readContract(n.a(t))}function S(e,t,r,i){return e.readContract(n.o(t,r,i))}function C(e,t,r){return e.readContract(n.r(t,r))}function w(e,t,r){return e.readContract(n.t(t,r))}function T(e,t,r){return e.readContract(n.n(t,r))}function E(e,t,r){return e.readContract(n.s(t,r))}exports.BaseSigner=t.t,exports.ViemProvider=a,exports.ViemSigner=c,exports.ZamaSDKEvents=e.M,exports.createConfig=l,exports.readConfidentialBalanceOfContract=d,exports.readConfidentialTokenAddressContract=w,exports.readIsConfidentialTokenValidContract=E,exports.readSupportsInterfaceContract=p,exports.readTokenAddressContract=T,exports.readTokenPairContract=C,exports.readTokenPairsContract=b,exports.readTokenPairsLengthContract=x,exports.readTokenPairsSliceContract=S,exports.readUnderlyingTokenContract=f,exports.writeConfidentialTransferContract=m,exports.writeFinalizeUnwrapContract=_,exports.writeSetOperatorContract=v,exports.writeUnwrapContract=h,exports.writeUnwrapFromBalanceContract=g,exports.writeWrapContract=y;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#publicClient","TransactionRevertedError","BaseSigner","#walletClient","#ethereum","#unsubscribeProvider","#subscribeToProvider","WalletNotConnectedError","#requireAccount","eip1193Subscribe","buildZamaConfig","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/viem/viem-provider.ts","../../../src/viem/viem-signer.ts","../../../src/viem/config.ts","../../../src/viem/contracts.ts"],"sourcesContent":["import {\n encodeFunctionData,\n serializeTransaction,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\n\n/** Configuration for {@link ViemProvider}. */\nexport interface ViemProviderConfig {\n /** A viem `PublicClient` backing all read operations. */\n publicClient: PublicClient;\n}\n\n/**\n * Read-only {@link GenericProvider} backed by a viem `PublicClient`.\n *\n * Use this for integrations that only need public chain reads before the user has Pair with a\n * {@link ViemSigner} when wallet authority is required; the two can share a transport or point at\n * independent RPCs.\n *\n * @example\n * ```ts\n * const publicClient = createPublicClient({ chain: sepolia, transport: http(ALCHEMY_URL) });\n * const provider = new ViemProvider({ publicClient });\n * ```\n */\nexport class ViemProvider implements GenericProvider {\n readonly #publicClient: PublicClient;\n\n constructor(config: ViemProviderConfig) {\n this.#publicClient = config.publicClient;\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n return this.#publicClient.getChainId();\n }\n\n /** Execute a read-only call and return the decoded result. */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return this.#publicClient.readContract(config);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n return this.#publicClient.waitForTransactionReceipt({ hash });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#publicClient.getBlock();\n return block.timestamp;\n }\n\n /** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */\n async prepareTransaction<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(args: {\n from: Address;\n calldata: WriteContractConfig<TAbi, TFunctionName, TArgs>;\n nonce?: number;\n gasLimit?: bigint;\n fees?: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint };\n }): Promise<Hex> {\n const { from, calldata } = args;\n const data = encodeFunctionData({\n abi: calldata.abi as Abi,\n functionName: calldata.functionName as string,\n args: calldata.args as readonly unknown[],\n });\n // Wrap the estimateGas leg so a pre-flight revert (the most common\n // prepareTransaction failure) surfaces as a typed error with the\n // function name + cause. Other legs propagate as-is — failures there\n // (chainId, nonce, fee data) are rare and usually self-explanatory.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const chainIdPromise = this.#publicClient.getChainId();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#publicClient.getTransactionCount({ address: from, blockTag: \"pending\" });\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#publicClient\n .estimateGas({ account: from, to: calldata.address, data, value: calldata.value ?? 0n })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `ViemProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feesPromise = args.fees ?? this.#publicClient.estimateFeesPerGas();\n const [chainId, nonce, gas, fees] = await Promise.all([\n chainIdPromise,\n noncePromise,\n gasPromise,\n feesPromise,\n ]);\n return serializeTransaction({\n type: \"eip1559\",\n chainId,\n nonce,\n to: calldata.address,\n data,\n value: calldata.value ?? 0n,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n });\n }\n}\n","import type {\n Account,\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n EIP1193Provider,\n WalletClient,\n Hex,\n} from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { writeContract } from \"viem/actions\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\n\n/**\n * Configuration for {@link ViemSigner}.\n *\n * The optional `ethereum` field is needed for `subscribe()` (EIP-1193\n * `accountsChanged` / `disconnect` events). It cannot be auto-extracted from\n * `walletClient` because viem's `custom(ethereum)` transport captures the\n * provider in a closure and does **not** expose `on` / `removeListener` on\n * `walletClient.transport`.\n *\n * If you omit `ethereum`, `subscribe()` returns a no-op. For automatic\n * wallet lifecycle handling, consider using `WagmiSigner` instead.\n */\nexport interface ViemSignerConfig {\n /** Wallet client for signing and write operations. */\n walletClient: WalletClient;\n /** Raw EIP-1193 provider enabling wallet lifecycle events; omit for a no-op `subscribe()`. */\n ethereum?: EIP1193Provider;\n}\n\n// viem requires uint values as bigints, but the KMS permit message carries them\n// as decimal strings. Convert by declared field type rather than by name so every\n// permit version is covered (V1 `durationDays`, V2 `durationSeconds`, ...).\nfunction messageWithBigIntUints(typedData: EIP712TypedData): Record<string, unknown> {\n const fields = (typedData.primaryType ? typedData.types[typedData.primaryType] : undefined) ?? [];\n const message: Record<string, unknown> = { ...typedData.message };\n for (const { name, type } of fields) {\n if (/^uint\\d*$/.test(type)) {\n message[name] = BigInt(message[name] as string | number | bigint);\n }\n }\n return message;\n}\n\nfunction walletAccountFromWalletClient(walletClient: WalletClient): WalletAccount | undefined {\n if (!walletClient.account || !walletClient.chain) {\n return undefined;\n }\n const address = getAddress(walletClient.account.address);\n return { address, chainId: walletClient.chain.id };\n}\n\n/**\n * {@link GenericSigner} backed by a viem `WalletClient` for EIP-712 signing and\n * write transactions. Pass `ethereum` in {@link ViemSignerConfig} to track\n * wallet lifecycle events.\n */\nexport class ViemSigner extends BaseSigner {\n readonly #walletClient: WalletClient;\n readonly #ethereum?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n\n constructor(config: ViemSignerConfig) {\n super(walletAccountFromWalletClient(config.walletClient));\n this.#walletClient = config.walletClient;\n this.#ethereum = config.ethereum;\n this.#unsubscribeProvider = this.#subscribeToProvider();\n }\n\n #requireAccount(operation: string): { walletClient: WalletClient; account: Account } {\n if (!this.#walletClient.account) {\n throw new WalletNotConnectedError(operation);\n }\n return { walletClient: this.#walletClient, account: this.#walletClient.account };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"signTypedData\");\n const { EIP712Domain: _, ...sigTypes } = typedData.types;\n return walletClient.signTypedData({\n account,\n primaryType: typedData.primaryType,\n types: sigTypes,\n domain: typedData.domain,\n message: messageWithBigIntUints(typedData),\n // Cast: EIP712TypedData is structural (`Eip712Like`), so viem cannot correlate primaryType/types/message and the inferred `message` collapses to `never`.\n } as Parameters<typeof walletClient.signTypedData>[0]);\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"writeContract\");\n return walletClient.writeContract({\n chain: walletClient.chain,\n account,\n ...config,\n } as Parameters<typeof writeContract>[1]);\n }\n\n #subscribeToProvider(): () => void {\n if (!this.#ethereum) {\n return () => {};\n }\n return eip1193Subscribe({\n provider: this.#ethereum,\n getInitialWalletAccount: () => walletAccountFromWalletClient(this.#walletClient),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n}\n","import type { FheChain } from \"../chains\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { buildZamaConfig } from \"../config/build\";\nimport { ViemProvider } from \"./viem-provider\";\nimport { ViemSigner } from \"./viem-signer\";\nimport type { ZamaConfigViem } from \"./types\";\n\n/** Create a {@link ZamaConfig} from viem clients. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigViem<TChains>,\n): ZamaConfig {\n const signer = new ViemSigner({ walletClient: params.walletClient, ethereum: params.ethereum });\n const provider = new ViemProvider({ publicClient: params.publicClient });\n return buildZamaConfig(signer, provider, params);\n}\n","import type { PublicClient, WalletClient, Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\n// ── Helpers ────────────────────────────────────────────────\n\nfunction requireAccount(client: WalletClient) {\n if (!client.account) {\n throw new TypeError(\"WalletClient has no account\");\n }\n return client.account;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via a viem client. */\nexport function readConfidentialBalanceOfContract(\n client: PublicClient,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return client.readContract(confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via a viem client. */\nexport function readUnderlyingTokenContract(client: PublicClient, wrapperAddress: Address) {\n return client.readContract(underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via a viem client. */\nexport function readSupportsInterfaceContract(\n client: PublicClient,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return client.readContract(supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via a viem wallet client. */\nexport function writeConfidentialTransferContract(\n client: WalletClient,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via a viem wallet client. */\nexport function writeUnwrapContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via a viem wallet client. */\nexport function writeUnwrapFromBalanceContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance),\n });\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via a viem wallet client. */\nexport function writeFinalizeUnwrapContract(\n client: WalletClient,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n });\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via a viem wallet client. */\nexport function writeSetOperatorContract(\n client: WalletClient,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...setOperatorContract(tokenAddress, operator, until),\n });\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via a viem wallet client. */\nexport function writeWrapContract(\n client: WalletClient,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...wrapContract(wrapperAddress, to, amount),\n });\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via a viem client. */\nexport function readTokenPairsContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via a viem client. */\nexport function readTokenPairsLengthContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via a viem client. */\nexport function readTokenPairsSliceContract(\n client: PublicClient,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return client.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via a viem client. */\nexport function readTokenPairContract(client: PublicClient, registry: Address, index: bigint) {\n return client.readContract(getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via a viem client. */\nexport function readConfidentialTokenAddressContract(\n client: PublicClient,\n registry: Address,\n tokenAddress: Address,\n) {\n return client.readContract(getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via a viem client. */\nexport function readTokenAddressContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via a viem client. */\nexport function readIsConfidentialTokenValidContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"2MAyCA,IAAa,EAAb,KAAqD,CACnD,GAEA,YAAY,EAA4B,CACtC,KAAKA,GAAgB,EAAO,YAC9B,CAGA,MAAM,YAA8B,CAClC,OAAO,KAAKA,GAAc,WAAW,CACvC,CAGA,MAAM,aAKJ,EACkF,CAClF,OAAO,KAAKA,GAAc,aAAa,CAAM,CAC/C,CAGA,MAAM,0BAA0B,EAAwC,CACtE,OAAO,KAAKA,GAAc,0BAA0B,CAAE,MAAK,CAAC,CAC9D,CAGA,MAAM,mBAAqC,CAEzC,OAAO,MADa,KAAKA,GAAc,SAAS,EAAA,CACnC,SACf,CAGA,MAAM,mBAIJ,EAMe,CACf,GAAM,CAAE,OAAM,YAAa,EACrB,GAAA,EAAA,EAAA,mBAAA,CAA0B,CAC9B,IAAK,EAAS,IACd,aAAc,EAAS,aACvB,KAAM,EAAS,IACjB,CAAC,EAOK,EAAiB,KAAKA,GAAc,WAAW,EAC/C,EACJ,EAAK,QAAU,IAAA,GAEX,KAAKA,GAAc,oBAAoB,CAAE,QAAS,EAAM,SAAU,SAAU,CAAC,EAD7E,QAAQ,QAAQ,EAAK,KAAK,EAE1B,EACJ,EAAK,WAAa,IAAA,GAEb,EAAS,KACV,KAAKA,GACF,YAAY,CAAE,QAAS,EAAM,GAAI,EAAS,QAAS,OAAM,MAAO,EAAS,OAAS,EAAG,CAAC,CAAC,CACvF,MAAO,GAAmB,CACzB,MAAM,IAAIC,EAAAA,GACR,gEAAgE,EAAS,aAAa,MAAM,EAAS,UACrG,CAAE,MAAO,CAAM,CACjB,CACF,CAA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CACrF,CAGA,SAAgB,EAAsB,EAAsB,EAAmB,EAAe,CAC5F,OAAO,EAAO,aAAaC,EAAAA,EAAqB,EAAU,CAAK,CAAC,CAClE,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAoC,EAAU,CAAY,CAAC,CACxF,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAwB,EAAU,CAAwB,CAAC,CACxF,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAiC,EAAU,CAAwB,CAAC,CACjG"}
1
+ {"version":3,"file":"index.cjs","names":["#publicClient","TransactionRevertedError","BaseSigner","#walletClient","#ethereum","#unsubscribeProvider","#subscribeToProvider","WalletNotConnectedError","#requireAccount","eip1193Subscribe","buildZamaConfig","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/viem/viem-provider.ts","../../../src/viem/viem-signer.ts","../../../src/viem/config.ts","../../../src/viem/contracts.ts"],"sourcesContent":["import {\n encodeFunctionData,\n serializeTransaction,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\n\n/** Configuration for {@link ViemProvider}. */\nexport interface ViemProviderConfig {\n /** A viem `PublicClient` backing all read operations. */\n publicClient: PublicClient;\n}\n\n/**\n * Read-only {@link GenericProvider} backed by a viem `PublicClient`.\n *\n * Use this for integrations that only need public chain reads before the user has Pair with a\n * {@link ViemSigner} when wallet authority is required; the two can share a transport or point at\n * independent RPCs.\n *\n * @example\n * ```ts\n * const publicClient = createPublicClient({ chain: sepolia, transport: http(ALCHEMY_URL) });\n * const provider = new ViemProvider({ publicClient });\n * ```\n */\nexport class ViemProvider implements GenericProvider {\n readonly #publicClient: PublicClient;\n\n constructor(config: ViemProviderConfig) {\n this.#publicClient = config.publicClient;\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n return this.#publicClient.getChainId();\n }\n\n /** Execute a read-only call and return the decoded result. */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return this.#publicClient.readContract(config);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n return this.#publicClient.waitForTransactionReceipt({ hash });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#publicClient.getBlock();\n return block.timestamp;\n }\n\n /** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */\n async prepareTransaction<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(args: {\n from: Address;\n calldata: WriteContractConfig<TAbi, TFunctionName, TArgs>;\n nonce?: number;\n gasLimit?: bigint;\n fees?: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint };\n }): Promise<Hex> {\n const { from, calldata } = args;\n const data = encodeFunctionData({\n abi: calldata.abi as Abi,\n functionName: calldata.functionName as string,\n args: calldata.args as readonly unknown[],\n });\n // Wrap the estimateGas leg so a pre-flight revert (the most common\n // prepareTransaction failure) surfaces as a typed error with the\n // function name + cause. Other legs propagate as-is — failures there\n // (chainId, nonce, fee data) are rare and usually self-explanatory.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const chainIdPromise = this.#publicClient.getChainId();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#publicClient.getTransactionCount({ address: from, blockTag: \"pending\" });\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#publicClient\n .estimateGas({ account: from, to: calldata.address, data, value: calldata.value ?? 0n })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `ViemProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feesPromise = args.fees ?? this.#publicClient.estimateFeesPerGas();\n const [chainId, nonce, gas, fees] = await Promise.all([\n chainIdPromise,\n noncePromise,\n gasPromise,\n feesPromise,\n ]);\n return serializeTransaction({\n type: \"eip1559\",\n chainId,\n nonce,\n to: calldata.address,\n data,\n value: calldata.value ?? 0n,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n });\n }\n}\n","import type {\n Account,\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n EIP1193Provider,\n WalletClient,\n Hex,\n} from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { writeContract } from \"viem/actions\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\n\n/**\n * Configuration for {@link ViemSigner}.\n *\n * The optional `ethereum` field is needed for `subscribe()` (EIP-1193\n * `accountsChanged` / `disconnect` events). It cannot be auto-extracted from\n * `walletClient` because viem's `custom(ethereum)` transport captures the\n * provider in a closure and does **not** expose `on` / `removeListener` on\n * `walletClient.transport`.\n *\n * If you omit `ethereum`, `subscribe()` returns a no-op. For automatic\n * wallet lifecycle handling, consider using `WagmiSigner` instead.\n */\nexport interface ViemSignerConfig {\n /** Wallet client for signing and write operations. */\n walletClient: WalletClient;\n /** Raw EIP-1193 provider enabling wallet lifecycle events; omit for a no-op `subscribe()`. */\n ethereum?: EIP1193Provider;\n}\n\n// viem requires uint values as bigints, but the KMS permit message carries them\n// as decimal strings. Convert by declared field type rather than by name so every\n// permit version is covered (V1 `durationDays`, V2 `durationSeconds`, ...).\nfunction messageWithBigIntUints(typedData: EIP712TypedData): Record<string, unknown> {\n const fields = (typedData.primaryType ? typedData.types[typedData.primaryType] : undefined) ?? [];\n const message: Record<string, unknown> = { ...typedData.message };\n for (const { name, type } of fields) {\n if (/^uint\\d*$/.test(type)) {\n message[name] = BigInt(message[name] as string | number | bigint);\n }\n }\n return message;\n}\n\nfunction walletAccountFromWalletClient(walletClient: WalletClient): WalletAccount | undefined {\n if (!walletClient.account || !walletClient.chain) {\n return undefined;\n }\n const address = getAddress(walletClient.account.address);\n return { address, chainId: walletClient.chain.id };\n}\n\n/**\n * {@link GenericSigner} backed by a viem `WalletClient` for EIP-712 signing and\n * write transactions. Pass `ethereum` in {@link ViemSignerConfig} to track\n * wallet lifecycle events.\n */\nexport class ViemSigner extends BaseSigner {\n readonly #walletClient: WalletClient;\n readonly #ethereum?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n\n constructor(config: ViemSignerConfig) {\n super(walletAccountFromWalletClient(config.walletClient));\n this.#walletClient = config.walletClient;\n this.#ethereum = config.ethereum;\n this.#unsubscribeProvider = this.#subscribeToProvider();\n }\n\n #requireAccount(operation: string): { walletClient: WalletClient; account: Account } {\n if (!this.#walletClient.account) {\n throw new WalletNotConnectedError(operation);\n }\n return { walletClient: this.#walletClient, account: this.#walletClient.account };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"signTypedData\");\n const { EIP712Domain: _, ...sigTypes } = typedData.types;\n return walletClient.signTypedData({\n account,\n primaryType: typedData.primaryType,\n types: sigTypes,\n domain: typedData.domain,\n message: messageWithBigIntUints(typedData),\n // Cast: EIP712TypedData is structural (`Eip712Like`), so viem cannot correlate primaryType/types/message and the inferred `message` collapses to `never`.\n } as Parameters<typeof walletClient.signTypedData>[0]);\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"writeContract\");\n return walletClient.writeContract({\n chain: walletClient.chain,\n account,\n ...config,\n } as Parameters<typeof writeContract>[1]);\n }\n\n #subscribeToProvider(): () => void {\n if (!this.#ethereum) {\n return () => {};\n }\n return eip1193Subscribe({\n provider: this.#ethereum,\n getInitialWalletAccount: () => walletAccountFromWalletClient(this.#walletClient),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n}\n","import type { FheChain } from \"../chains\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { buildZamaConfig } from \"../config/build\";\nimport { ViemProvider } from \"./viem-provider\";\nimport { ViemSigner } from \"./viem-signer\";\nimport type { ZamaConfigViem } from \"./types\";\n\n/** Create a {@link ZamaConfig} from viem clients. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigViem<TChains>,\n): ZamaConfig {\n const signer = new ViemSigner({ walletClient: params.walletClient, ethereum: params.ethereum });\n const provider = new ViemProvider({ publicClient: params.publicClient });\n return buildZamaConfig(signer, provider, params);\n}\n","import type { PublicClient, WalletClient, Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\n// ── Helpers ────────────────────────────────────────────────\n\nfunction requireAccount(client: WalletClient) {\n if (!client.account) {\n throw new TypeError(\"WalletClient has no account\");\n }\n return client.account;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via a viem client. */\nexport function readConfidentialBalanceOfContract(\n client: PublicClient,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return client.readContract(confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via a viem client. */\nexport function readUnderlyingTokenContract(client: PublicClient, wrapperAddress: Address) {\n return client.readContract(underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via a viem client. */\nexport function readSupportsInterfaceContract(\n client: PublicClient,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return client.readContract(supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via a viem wallet client. */\nexport function writeConfidentialTransferContract(\n client: WalletClient,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via a viem wallet client. */\nexport function writeUnwrapContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via a viem wallet client. */\nexport function writeUnwrapFromBalanceContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance),\n });\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via a viem wallet client. */\nexport function writeFinalizeUnwrapContract(\n client: WalletClient,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n });\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via a viem wallet client. */\nexport function writeSetOperatorContract(\n client: WalletClient,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...setOperatorContract(tokenAddress, operator, until),\n });\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via a viem wallet client. */\nexport function writeWrapContract(\n client: WalletClient,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...wrapContract(wrapperAddress, to, amount),\n });\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via a viem client. */\nexport function readTokenPairsContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via a viem client. */\nexport function readTokenPairsLengthContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via a viem client. */\nexport function readTokenPairsSliceContract(\n client: PublicClient,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return client.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via a viem client. */\nexport function readTokenPairContract(client: PublicClient, registry: Address, index: bigint) {\n return client.readContract(getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via a viem client. */\nexport function readConfidentialTokenAddressContract(\n client: PublicClient,\n registry: Address,\n tokenAddress: Address,\n) {\n return client.readContract(getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via a viem client. */\nexport function readTokenAddressContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via a viem client. */\nexport function readIsConfidentialTokenValidContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"sOAyCA,IAAa,EAAb,KAAqD,CACnD,GAEA,YAAY,EAA4B,CACtC,KAAKA,GAAgB,EAAO,YAC9B,CAGA,MAAM,YAA8B,CAClC,OAAO,KAAKA,GAAc,WAAW,CACvC,CAGA,MAAM,aAKJ,EACkF,CAClF,OAAO,KAAKA,GAAc,aAAa,CAAM,CAC/C,CAGA,MAAM,0BAA0B,EAAwC,CACtE,OAAO,KAAKA,GAAc,0BAA0B,CAAE,MAAK,C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AAuB,EAAS,EAAiB,EAAuB,CAAe,CAC5F,CAAC,CACH,CAGA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAO,cAAc,CAC1B,MAAO,EAAO,MACd,QAAS,EAAe,CAAM,EAC9B,GAAGC,EAAAA,EAAoB,EAAc,EAAU,CAAK,CACtD,CAAC,CACH,CAGA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAO,cAAc,CAC1B,MAAO,EAAO,MACd,QAAS,EAAe,CAAM,EAC9B,GAAGC,EAAAA,EAAa,EAAgB,EAAI,CAAM,CAC5C,CAAC,CACH,CAKA,SAAgB,EAAuB,EAAsB,EAAmB,CAC9E,OAAO,EAAO,aAAaC,EAAAA,EAAsB,CAAQ,CAAC,CAC5D,CAGA,SAAgB,EAA6B,EAAsB,EAAmB,CACpF,OAAO,EAAO,aAAaC,EAAAA,EAA4B,CAAQ,CAAC,CAClE,CAGA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAA2B,EAAU,EAAW,CAAO,CAAC,CACrF,CAGA,SAAgB,EAAsB,EAAsB,EAAmB,EAAe,CAC5F,OAAO,EAAO,aAAaC,EAAAA,EAAqB,EAAU,CAAK,CAAC,CAClE,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAoC,EAAU,CAAY,CAAC,CACxF,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAwB,EAAU,CAAwB,CAAC,CACxF,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAO,aAAaC,EAAAA,EAAiC,EAAU,CAAwB,CAAC,CACjG"}
@@ -0,0 +1,2 @@
1
+ const e=require("./relayer.cjs"),t=require("./erc165.cjs"),n=require("./encryption.cjs"),r=require("./token.cjs"),i=require("./primitives.cjs"),a=require("./assertions.cjs");let o=require("viem"),s=require("zod/mini");function c(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 l=class extends e.r{unwrapTxHash;unwrapRequestId;constructor(t,n,r){super(e.i.UnshieldAlreadyFinalized,t,r),this.name=`UnshieldAlreadyFinalizedError`,this.unwrapTxHash=n.unwrapTxHash,this.unwrapRequestId=n.unwrapRequestId}};const u=`InvalidUnwrapRequest`,d=(0,o.keccak256)((0,o.toBytes)(`${u}(bytes32)`)).slice(0,10);function f(e){for(let t=e;t instanceof Error;t=t.cause)if(c(t)===u||t.message.includes(u)||t.message.includes(d))return!0;return!1}const p=[{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 m(e,t,n,r=`0x`){return{address:e,abi:p,functionName:`transferAndCall`,args:[t,n,r]}}function h(e){return e.startsWith(`0x`)?e:`0x${e}`}function g(e){return(0,o.keccak256)((0,o.toBytes)(e))}function _(e){return(0,o.getAddress)(h(e.slice(-40)))}function v(e){return e}function y(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function b(e,t){return(0,o.getAddress)(h(y(e,t).slice(-40)))}function x(e,t){return BigInt(`0x`+y(e,t))}function S(e,t){return h(y(e,t))}const C={ConfidentialTransfer:g(`ConfidentialTransfer(address,address,bytes32)`),Wrap:g(`Wrap(address,uint256,bytes32)`),UnwrapRequested:g(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:g(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function w(e){return e.topics[0]!==C.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:_(e.topics[1]),to:_(e.topics[2]),encryptedAmount:v(e.topics[3])}}function T(e){return e.topics[0]!==C.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:_(e.topics[1]),roundedAmount:x(e.data,0),encryptedWrappedAmount:S(e.data,1)}}function E(e){return e.topics[0]!==C.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:_(e.topics[1]),unwrapRequestId:v(e.topics[2]),encryptedAmount:S(e.data,0)}}function D(e){return e.topics[0]!==C.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:_(e.topics[1]),unwrapRequestId:v(e.topics[2]),encryptedAmount:S(e.data,0),cleartextAmount:x(e.data,1)}}function O(e){return w(e)??T(e)??E(e)??D(e)}function k(e){let t=[];for(let n of e){let e=O(n);e&&t.push(e)}return t}function A(e){for(let t of e){let e=E(t);if(e)return e}return null}function j(e){for(let t of e){let e=T(t);if(e)return e}return null}const M=[C.ConfidentialTransfer,C.Wrap,C.UnwrapRequested,C.UnwrapFinalized],N={DelegatedForUserDecryption:g(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:g(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function P(e){return e.topics[0]!==N.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:_(e.topics[1]),delegate:_(e.topics[2]),contractAddress:b(e.data,0),delegationCounter:x(e.data,1),oldExpirationDate:x(e.data,2),newExpirationDate:x(e.data,3)}}function F(e){return e.topics[0]!==N.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:_(e.topics[1]),delegate:_(e.topics[2]),contractAddress:b(e.data,0),delegationCounter:x(e.data,1),oldExpirationDate:x(e.data,2)}}function I(e){return P(e)??F(e)}function L(e){let t=[];for(let n of e){let e=I(n);e&&t.push(e)}return t}function R(e){for(let t of e){let e=P(t);if(e)return e}return null}function z(e){for(let t of e){let e=F(t);if(e)return e}return null}const B=[N.DelegatedForUserDecryption,N.RevokedDelegationForUserDecryption];function V(e){return`zama:pending-unshield:${i.t(e)}`}const H=s.z.union([s.z.pipe(i.r,s.z.transform(e=>({unwrapTxHash:e}))),s.z.pipe(s.z.object({version:s.z.literal(1),unwrapTxHash:i.r,unwrapRequestId:s.z.optional(i.r)}),s.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function U(e,t,n,r){if(r===void 0){await e.set(V(t),n);return}await e.set(V(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function W(e,t){let n=V(t),r=await e.get(n);if(r==null)return null;let i=H.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function G(e,t){await e.delete(V(t))}var K=class extends r.t{#e;#t=null;#n=null;#r(e){try{return a.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.P(e,{cause:n})}}async underlying(){return this.#u()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#u();this.#n=await this.sdk.provider.readContract(t.o(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#u();return this.sdk.provider.readContract(t.c(n,(0,o.getAddress)(e),this.address))}async shield(n,i){let a=await r.a(`shield`,this.sdk.signer,this.sdk.provider),s=await this.isPayable(),c=await this.#u(),l=(0,o.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t.u(c,l))}catch(t){throw t instanceof e.r?t:new r.f(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e.S(t)})}if(u<n)throw new r.h(`Insufficient ERC-20 balance: requested ${n}, available ${u} (token: ${c})`,{requested:n,available:u,token:c});return s?this.#i(n,c,l,i):this.#a(n,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,o.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:m(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(n,i){this.#r(`wrap`);let a=await r.a(`wrap`,this.sdk.signer,this.sdk.provider),s=await this.#u(),c=(0,o.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t.u(s,c))}catch(t){throw t instanceof e.r?t:new r.f(`Could not read ERC-20 balance for wrap validation (token: ${s})`,{cause:e.S(t)})}if(l<n)throw new r.h(`Insufficient ERC-20 balance: requested ${n}, available ${l} (token: ${s})`,{requested:n,available:l,token:s});let u;try{u=await this.sdk.provider.readContract(t.c(s,c,this.address))}catch(t){throw t instanceof e.r?t:new r.f(`Could not read ERC-20 allowance for wrap validation (token: ${s})`,{cause:e.S(t)})}if(u<n)throw new r.p(`Insufficient allowance for wrap: requested ${n}, approved ${u}. Call approveUnderlying() first (token: ${s}).`,{requested:n,available:u,token:s});let d=i?.to?(0,o.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.A(this.address,d,n),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#f(e,i===`max`,r);let a=r?.to?(0,o.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.A(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let n=await r.a(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#u(),a=(0,o.getAddress)(n.address),s=e??2n**256n-1n;return s>0n&&await this.sdk.provider.readContract(t.c(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.l(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.l(i,this.address,s)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.j(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#d(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.j(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#d(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(n,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(n)}catch(n){throw n instanceof e.r?n:new t.z(`Failed to get unwrap receipt`,{cause:n})}let a=this.#o(i.logs);if(await this.#s(a))throw await this.#l(`resumeUnshield`),new l(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:n,unwrapRequestId:a});return this.#d(a,n,crypto.randomUUID(),r)}async getPendingUnshield(){let e=await W(this.sdk.storage,this.address);return e?await this.#c(e)?(await this.#l(`getPendingUnshield`),null):e.unwrapTxHash:null}async unwrap(e){this.#r(`unwrap`);let i=(0,o.getAddress)((await r.a(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:a,inputProof:s}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i}),[c]=a;if(!c)throw new n.r(`Encryption returned no encrypted values`);let l=await this.submitTransaction({operation:`unwrap`,config:t.D(this.address,i,i,c,s)});return{...l,unwrapRequestId:this.#o(l.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,o.getAddress)((await r.a(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),i=await this.readConfidentialBalanceOf(e);if(r.l(i))throw new n.t(`Cannot unshield: balance is zero`);let a=await this.submitTransaction({operation:`unwrapAll`,config:t.O(this.address,e,e,i)});return{...a,unwrapRequestId:this.#o(a.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await r.o(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e]),i=n.clearValues[e];return a.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.x(this.address,e,i,n.decryptionProof)})}#o(e){let n=A(e.filter(e=>e.address===void 0||(0,o.getAddress)(e.address)===this.address));if(!n)throw new t.z(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return n.unwrapRequestId}async#s(e){try{return await this.sdk.provider.readContract(t.k(this.address,e))===o.zeroAddress}catch{return!1}}async#c(e){let t=e.unwrapRequestId;if(t===void 0)try{let n=await this.sdk.provider.waitForTransactionReceipt(e.unwrapTxHash);t=this.#o(n.logs)}catch{return!1}return this.#s(t)}async#l(e){await t.j(`${e}: clearPendingUnshield`,()=>G(this.sdk.storage,this.address),this.sdk.logger)}async#u(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.E(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#d(e,n,r,i){this.emit({type:t.M.UnshieldPhase1Submitted,txHash:n,operationId:r}),await t.j(`unshield: savePendingUnshield`,()=>U(this.sdk.storage,this.address,n,e),this.sdk.logger),this.emit({type:t.M.UnshieldPhase2Started,operationId:r}),t.j(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.finalizeUnwrap(e)}catch(t){throw f(t)?(await this.#l(`unshield`),new l(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:n,unwrapRequestId:e},{cause:t})):t}return this.emit({type:t.M.UnshieldPhase2Submitted,txHash:a.txHash,operationId:r}),t.j(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#l(`unshield`),a}async#f(e,n,i){this.#r(`approveUnderlying`);let a=await this.#u(),s=(0,o.getAddress)((await r.a(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t.c(a,s,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.l(a,this.address,0n)});let l=n?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.l(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}};Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return j}});
2
+ //# sourceMappingURL=wrapped-token.cjs.map