@zama-fhe/sdk 3.9.0-beta.8 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) 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/index.cjs +1 -1
  4. package/dist/cjs/configs.cjs +2 -0
  5. package/dist/cjs/configs.cjs.map +1 -0
  6. package/dist/cjs/fhevm-relayer.cjs +2 -2
  7. package/dist/cjs/fhevm-relayer.cjs.map +1 -1
  8. package/dist/cjs/index.cjs +1 -1
  9. package/dist/cjs/index.cjs.map +1 -1
  10. package/dist/cjs/node/index.cjs +1 -1
  11. package/dist/cjs/node/index.cjs.map +1 -1
  12. package/dist/cjs/public-decrypt.cjs +2 -0
  13. package/dist/cjs/public-decrypt.cjs.map +1 -0
  14. package/dist/cjs/query/index.cjs +1 -1
  15. package/dist/cjs/query/index.cjs.map +1 -1
  16. package/dist/cjs/relayer.cjs.map +1 -1
  17. package/dist/cjs/telemetry.cjs +1 -1
  18. package/dist/cjs/telemetry.cjs.map +1 -1
  19. package/dist/cjs/unshield.cjs +2 -0
  20. package/dist/cjs/unshield.cjs.map +1 -0
  21. package/dist/cjs/vaults/index.cjs +1 -1
  22. package/dist/cjs/vaults/index.cjs.map +1 -1
  23. package/dist/esm/{base-signer-2YhJsgqC.d.ts → base-signer-C3_eu3aC.d.ts} +1 -1
  24. package/dist/esm/base-signer-CD9a2hyy.js +2 -0
  25. package/dist/esm/base-signer-CD9a2hyy.js.map +1 -0
  26. package/dist/esm/chains/index.d.ts +2 -2
  27. package/dist/esm/chains/index.js +1 -1
  28. package/dist/esm/cleartext/index.d.ts +2 -2
  29. package/dist/esm/cleartext/index.js +1 -1
  30. package/dist/esm/{cleartext-DVvSG0Fe.js → cleartext-Bmwhc1xE.js} +2 -2
  31. package/dist/esm/{cleartext-DVvSG0Fe.js.map → cleartext-Bmwhc1xE.js.map} +1 -1
  32. package/dist/esm/{cleartext-6kZuW_t0.d.ts → cleartext-BxZphbB4.d.ts} +1 -1
  33. package/dist/esm/configs-9EL-DJHq.js +2 -0
  34. package/dist/esm/configs-9EL-DJHq.js.map +1 -0
  35. package/dist/esm/{decryption-B9hsOs_w.d.ts → decryption-BvvhpFM2.d.ts} +10 -4
  36. package/dist/esm/{encrypt-worker-client-B0yd2zzT.d.ts → encrypt-worker-client-Dt_x4FZd.d.ts} +1 -1
  37. package/dist/esm/encrypt.worker.js +47 -45
  38. package/dist/esm/ethers/index.d.ts +4 -4
  39. package/dist/esm/ethers/index.js +1 -1
  40. package/dist/esm/fhevm-relayer-ClfJ8FQG.js +8 -0
  41. package/dist/esm/fhevm-relayer-ClfJ8FQG.js.map +1 -0
  42. package/dist/esm/{index-BVrcy8IY.d.ts → index-B7M2GEtA.d.ts} +6 -6
  43. package/dist/esm/{index-ZTcD9b_z.d.ts → index-BSkvEzGu.d.ts} +88 -12
  44. package/dist/esm/{index-acMNiL8q.d.ts → index-DTLVaNIj.d.ts} +3 -3
  45. package/dist/esm/index.d.ts +9 -9
  46. package/dist/esm/index.js +1 -1
  47. package/dist/esm/index.js.map +1 -1
  48. package/dist/esm/internal/index.d.ts +4 -4
  49. package/dist/esm/internal/index.js +1 -1
  50. package/dist/esm/{invalidation-IBiMIXGB.d.ts → invalidation-BpkhN3Qu.d.ts} +3 -1
  51. package/dist/esm/node/index.d.ts +4 -4
  52. package/dist/esm/node/index.js +1 -1
  53. package/dist/esm/node/index.js.map +1 -1
  54. package/dist/esm/public-decrypt-Bec9uoNY.js +2 -0
  55. package/dist/esm/public-decrypt-Bec9uoNY.js.map +1 -0
  56. package/dist/esm/query/index.d.ts +7 -7
  57. package/dist/esm/query/index.js +1 -1
  58. package/dist/esm/query/index.js.map +1 -1
  59. package/dist/esm/relayer-Cki3j_Ba.js.map +1 -1
  60. package/dist/esm/telemetry-B0ypjU_K.js +2 -0
  61. package/dist/esm/telemetry-B0ypjU_K.js.map +1 -0
  62. package/dist/esm/{types-CxkmFARM.d.ts → types-BGMWYQds.d.ts} +2 -2
  63. package/dist/esm/{types-BvfzKaVy.d.ts → types-CHA7Mcqr.d.ts} +1 -1
  64. package/dist/esm/{types-DDsT3eE9.d.ts → types-CoI5slhu.d.ts} +2 -2
  65. package/dist/esm/unshield-xO66p_da.js +2 -0
  66. package/dist/esm/unshield-xO66p_da.js.map +1 -0
  67. package/dist/esm/vaults/index.d.ts +20 -17
  68. package/dist/esm/vaults/index.js +1 -1
  69. package/dist/esm/vaults/index.js.map +1 -1
  70. package/dist/esm/viem/index.d.ts +4 -4
  71. package/dist/esm/viem/index.js +1 -1
  72. package/dist/esm/web/index.d.ts +2 -2
  73. package/dist/esm/web/index.js +1 -1
  74. package/package.json +13 -3
  75. package/dist/cjs/chains.cjs +0 -2
  76. package/dist/cjs/chains.cjs.map +0 -1
  77. package/dist/cjs/log-decoding.cjs +0 -2
  78. package/dist/cjs/log-decoding.cjs.map +0 -1
  79. package/dist/esm/base-signer-CteT6O7E.js +0 -2
  80. package/dist/esm/base-signer-CteT6O7E.js.map +0 -1
  81. package/dist/esm/chains-BQXSxIwU.js +0 -2
  82. package/dist/esm/chains-BQXSxIwU.js.map +0 -1
  83. package/dist/esm/fhevm-relayer-J_czn6Kj.js +0 -8
  84. package/dist/esm/fhevm-relayer-J_czn6Kj.js.map +0 -1
  85. package/dist/esm/log-decoding-Cl4zZCe8.js +0 -2
  86. package/dist/esm/log-decoding-Cl4zZCe8.js.map +0 -1
  87. package/dist/esm/telemetry-C5ta4GAC.js +0 -2
  88. package/dist/esm/telemetry-C5ta4GAC.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["ConfigurationError","isAddress","getAddress","getAbiItem","encodeAbiParameters","VaultBatcherPausedError","ConfigurationError","VaultBatcherReadFailedError","isContractCallError","eventTopic","getAddress","topicToAddress","encodeFunctionData","ConfigurationError","getAddress","VaultBatchNotDispatchedError","unwrapAmountContract","DecryptionFailedError","isEncryptedValueZero","VaultBatcherPausedError","confidentialTransferAndCallContract","submitTransaction","VaultJoinUnconfirmedError","BalanceCheckUnavailableError","assertConfidentialBalance","Token","EncryptionFailedError","isOperatorContract","setOperatorContract","SignerNotConfiguredError","requireWriteChain","ChainMismatchError","getAddress","zamaQueryKeys","require_alignment","require_token","require_relayer","require_encryption","require_log_decoding","require_query_keys","viem","defineVault","vault","defineVaultGroup","group","chainIdOf","target","scopeOf","where","first","vaultIds","batchersOf","direction","rest","listOf","entryOf","batcher","declared","isArray","unbounded","entry","value","requireAddress","address","lastBatchId","vaultBatcherAbi","claimContract","batchId","account","quitContract","dispatchBatchContract","currentBatchIdContract","batchStateContract","depositsContract","fromTokenContract","batchMinBatchAgeContract","batchCallbackDeadlineContract","batchCreatedAtContract","batchDispatchedAtContract","exchangeRateContract","exchangeRateDecimalsContract","pausedContract","closedContract","unwrapRequestIdContract","dispatchBatchCallbackContract","unwrapAmountCleartext","decryptionProof","vaultRouterAbi","routerJoinContract","router","legs","inputProof","ALLOCATION_PARAMETERS","encodeAllocationData","leg","BATCH_STATES","soonest","offers","a","b","left","right","pickNextBatch","open","offer","o","now","readNextBatches","read","provider","chainId","vaults","entries","offerOf","readBatchState","index","state","waitsOnPrevious","details","vaultId","readOffer","cause","paused","createdAt","minAge","blocked","isClosed","dispatchableAt","error","JOINED","takeJoinedBatchId","log","logs","topic","accountTopic","OPERATOR_APPROVAL_VALIDITY_SECONDS","ENCRYPT_OPERATION","JOIN_OPERATION","at","values","toCall","config","memberOf","candidate","nonEmpty","memoize","pending","cache","key","VaultClient","#sdk","sdk","#planJoin","input","options","batch","#planFinalize","requestId","wrapper","#read","#fromToken","handle","#requireProviderChain","cleartext","clearValues","#join","signer","#writeAccount","call","#send","depositor","dispatchedAt","deadline","rate","decimals","deposit","#memo","cancelsAt","member","actions","action","allowed","edge","base","next","status","joinTarget","chosen","route","#router","batchers","tokens","stray","#assertBalance","operation","join","joins","operatorApprovals","amounts","allocationOf","handles","routerProof","missing","#encrypt","#missingOperatorApprovals","asset","total","assetProof","data","encrypted","#encryptPerToken","planned","#signer","txHashes","last","prepared","event","batches","unconfirmed","id","chain","signerAccount","owner","balance","results","errors","encryptedValues","byLeg","spending","token","approved","operator","until","providerChainId","wallet","#reads","createVaultClient","KEEPER_POLL_MS","vaultQueryKeys","refetchAt","observedAt","batchRefetchInterval","untilEdge","batchQueryOptions","query","client","selected","selection","openBatchesRefetchInterval","waits","movesAt","openBatchesQueryOptions","invalidateAfterVaultAction","queryClient","joinMutation","depositMutationOptions","redeemMutationOptions","claimMutationOptions","quitMutationOptions","dispatchMutationOptions","finalizeMutationOptions"],"sources":["../../../src/vaults/config.ts","../../../src/vaults/abi/vault-batcher.abi.ts","../../../src/vaults/contracts/vault-batcher.ts","../../../src/vaults/abi/vault-router.abi.ts","../../../src/vaults/contracts/vault-router.ts","../../../src/vaults/next-batch.ts","../../../src/vaults/joined.ts","../../../src/vaults/client.ts","../../../src/vaults/query/index.ts"],"sourcesContent":["import { getAddress, isAddress, type Address } from \"viem\";\nimport { ConfigurationError } from \"../errors\";\nimport type { JoinDirection } from \"./types\";\n\n/** The most vaults a group may hold. */\nexport const MAX_GROUP_VAULTS = 8;\n\n/**\n * A batcher, with the last batch it takes joins in. Set `lastBatchId` only for\n * a batcher whose contract has no `closed()`.\n */\nexport interface BatcherEntry {\n /** The batcher's address. */\n readonly address: Address;\n /** The last batch joins may land in. Past it, joins go to the vault's other batchers. */\n readonly lastBatchId?: bigint;\n}\n\n/** The batchers of one vault direction: an address, or a list of addresses and {@link BatcherEntry} objects. A join or read throws on an empty list. */\nexport type Batchers = Address | readonly (Address | BatcherEntry)[];\n\n/**\n * A batcher that took joins while its `currentBatchId` was at most `lastBatchId`.\n *\n * @deprecated List the batchers as {@link Batchers} instead, a retired one as `{ address, lastBatchId }`.\n */\nexport type RetiredBatcher = BatcherEntry & { readonly lastBatchId: bigint };\n\n/**\n * Every batcher a vault has had in one direction. Read as the list\n * `[...retired, latest]`, so `latest` takes joins as soon as it is open, even\n * before a retired batcher reaches its `lastBatchId`.\n *\n * @deprecated List the batchers as {@link Batchers} instead.\n */\nexport interface BatcherHistory {\n /** Oldest first. */\n readonly retired: readonly RetiredBatcher[];\n /** The newest batcher. */\n readonly latest: Address;\n}\n\n/** One vault: its chain and the batchers each direction joins. */\nexport interface Vault<TVaultId extends string = string> {\n /** Names the vault in errors and query keys, and is what a group join passes as `vaultId`. */\n readonly id: TVaultId;\n /** The chain the vault's batchers are on. */\n readonly chainId: number;\n /**\n * The batchers each direction joins. A join reaches the open batch that is\n * dispatched next; paused and closed batchers take none.\n */\n readonly batchers: Readonly<Record<JoinDirection, Batchers | BatcherHistory>>;\n}\n\n/** Vaults that take deposits in one confidential asset, joined together. */\nexport interface VaultGroup<TGroupId extends string = string, TVaultId extends string = string> {\n /** Names the group in errors and query keys. */\n readonly id: TGroupId;\n /**\n * The vaults, in leg order, up to {@link MAX_GROUP_VAULTS}. They must be on one\n * chain, and their deposit batchers must take the same confidential asset.\n */\n readonly vaults: readonly [Vault<TVaultId>, Vault<TVaultId>, ...Vault<TVaultId>[]];\n}\n\n/** The vault ids of a group. */\nexport type VaultIdOf<TGroup extends VaultGroup> =\n TGroup extends VaultGroup<string, infer TVaultId> ? TVaultId : never;\n\n/**\n * Define a vault, keeping its id as a literal type. Returns `vault` as is and\n * checks nothing.\n *\n * @example\n * ```ts\n * export const ALPHA = defineVault({\n * id: \"alpha\",\n * chainId: 1,\n * batchers: { deposit: \"0xAlphaDeposit\", redeem: [\"0xAlphaRedeemA\", \"0xAlphaRedeemB\"] },\n * });\n * ```\n */\nexport function defineVault<const TVaultId extends string>(\n vault: Vault<TVaultId>,\n): Vault<TVaultId> {\n return vault;\n}\n\n/**\n * Define a group of vaults, keeping its ids as literal types, so a typo in\n * `vaultId` is a type error. Returns `group` as is and checks nothing.\n *\n * @example\n * ```ts\n * const ALPHA = defineVault({\n * id: \"alpha\",\n * chainId: 1,\n * batchers: { deposit: \"0xAlphaDeposit\", redeem: \"0xAlphaRedeem\" },\n * });\n * const BETA = defineVault({\n * id: \"beta\",\n * chainId: 1,\n * batchers: { deposit: \"0xBetaDeposit\", redeem: \"0xBetaRedeem\" },\n * });\n * export const STABLE = defineVaultGroup({ id: \"stable\", vaults: [ALPHA, BETA] });\n * ```\n */\nexport function defineVaultGroup<const TGroupId extends string, const TVaultId extends string>(\n group: VaultGroup<TGroupId, TVaultId>,\n): VaultGroup<TGroupId, TVaultId> {\n return group;\n}\n\n/**\n * The chain a vault, or every vault of a group, is on.\n *\n * @internal\n */\nexport function chainIdOf(target: Vault | VaultGroup): number {\n return \"vaults\" in target ? target.vaults[0].chainId : target.chainId;\n}\n\n/**\n * What a join or a read of `target` covers: every vault of a group, or a\n * vault on its own and no group.\n *\n * @internal\n * @throws if a group has more than {@link MAX_GROUP_VAULTS} vaults, mixes chains, or names a vault twice. {@link ConfigurationError}\n */\nexport function scopeOf(target: Vault | VaultGroup): {\n readonly group: VaultGroup | undefined;\n readonly vaults: readonly [Vault, ...Vault[]];\n readonly chainId: number;\n} {\n if (!(\"vaults\" in target)) {\n return { group: undefined, vaults: [target], chainId: target.chainId };\n }\n const where = `Vault group \"${target.id}\"`;\n const [first] = target.vaults;\n if (target.vaults.length > MAX_GROUP_VAULTS) {\n throw new ConfigurationError(\n `${where} has ${target.vaults.length} vaults, more than ${MAX_GROUP_VAULTS}`,\n );\n }\n const vaultIds = new Set<string>();\n for (const vault of target.vaults) {\n if (vault.chainId !== first.chainId) {\n throw new ConfigurationError(\n `${where} mixes chains: vault \"${vault.id}\" is on chain ${vault.chainId}, vault \"${first.id}\" on chain ${first.chainId}`,\n );\n }\n if (vaultIds.has(vault.id)) {\n throw new ConfigurationError(`${where} names vault \"${vault.id}\" twice`);\n }\n vaultIds.add(vault.id);\n }\n return { group: target, vaults: target.vaults, chainId: first.chainId };\n}\n\n/**\n * Every batcher of `vault` in `direction`, checksummed, in declared order. A\n * history lists its retired batchers, then `latest`.\n *\n * @internal\n * @throws if no batcher is listed, or an address or a `lastBatchId` is invalid. {@link ConfigurationError}\n */\nexport function batchersOf(\n vault: Vault,\n direction: JoinDirection,\n): readonly [BatcherEntry, ...BatcherEntry[]] {\n const where = `Vault \"${vault.id}\" ${direction} batcher`;\n const [first, ...rest] = listOf(vault.batchers[direction], where).map((batcher) =>\n entryOf(batcher, where),\n );\n if (first === undefined) {\n throw new ConfigurationError(`${where} list is empty`);\n }\n return [first, ...rest];\n}\n\nfunction listOf(\n declared: Batchers | BatcherHistory,\n where: string,\n): readonly (Address | BatcherEntry)[] {\n if (typeof declared === \"string\") {\n return [declared];\n }\n if (isArray(declared)) {\n return declared;\n }\n if (!(\"latest\" in declared)) {\n throw new ConfigurationError(`${where} must be an address or a list`);\n }\n // Without its lastBatchId, a retired batcher would read as live and keep taking joins.\n const unbounded = declared.retired.find((entry) => entry.lastBatchId === undefined);\n if (unbounded !== undefined) {\n throw new ConfigurationError(\n `${where} ${unbounded.address} has an invalid lastBatchId: undefined`,\n );\n }\n return [...declared.retired, declared.latest];\n}\n\n// `Array.isArray` does not narrow a readonly array out of a union.\nfunction isArray(value: unknown): value is readonly (Address | BatcherEntry)[] {\n return Array.isArray(value);\n}\n\nfunction entryOf(batcher: Address | BatcherEntry, where: string): BatcherEntry {\n if (typeof batcher === \"string\") {\n return { address: requireAddress(batcher, where) };\n }\n const address = requireAddress(batcher.address, where);\n const { lastBatchId } = batcher;\n if (lastBatchId === undefined) {\n return { address };\n }\n // A non-bigint can compare false and keep the batcher open past its last batch; a negative one closes it for good.\n if (typeof lastBatchId !== \"bigint\" || lastBatchId < 0n) {\n throw new ConfigurationError(\n `${where} ${address} has an invalid lastBatchId: ${String(lastBatchId)}`,\n );\n }\n return { address, lastBatchId };\n}\n\nfunction requireAddress(value: unknown, where: string): Address {\n if (typeof value !== \"string\" || !isAddress(value, { strict: false })) {\n throw new ConfigurationError(`${where} is not an address: ${String(value)}`);\n }\n return getAddress(value);\n}\n","/**\n * ABI for the deposit and redeem vault batchers, which share one interface.\n * Owner-only writes are omitted; every custom error is kept so reverts decode\n * 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: \"dispatchBatchCallback\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"unwrapAmountCleartext\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"decryptionProof\", type: \"bytes\", internalType: \"bytes\" },\n ],\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: \"closed\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\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 { vaultBatcherAbi } from \"../abi/vault-batcher.abi\";\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. */\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 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 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 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 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\n/** Returns the contract config to read whether the batcher is past its last batch. Batchers deployed before `closed()` revert. */\nexport function closedContract(batcher: Address) {\n return { address: batcher, abi: vaultBatcherAbi, functionName: \"closed\", args: [] } as const;\n}\n\n/** Returns the contract config to read the unwrap request a dispatched batch is waiting on. */\nexport function unwrapRequestIdContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"unwrapRequestId\",\n args: [batchId],\n } as const;\n}\n\n/**\n * Returns the contract config to settle a dispatched batch with the public decryption of its\n * aggregate amount, or to cancel it once its callback deadline has passed. Permissionless.\n */\nexport function dispatchBatchCallbackContract(\n batcher: Address,\n batchId: bigint,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"dispatchBatchCallback\",\n args: [batchId, unwrapAmountCleartext, decryptionProof],\n } as const;\n}\n","/**\n * ABI for the vault batcher router, which fans one submission out across\n * several batchers. Transcribed by hand from `IVaultBatcherConfidentialRouter`\n * in zama-ai/confidential-defi at tag `oz-audit-20261016` (commit `d7cd0c8e`),\n * so `abi:check` does not cover it: compare against that ref when the router\n * changes. `onConfidentialTransferReceived` is omitted because a token calls\n * it, not the SDK; the router's custom errors are kept so its reverts decode\n * to a name.\n */\nexport const vaultRouterAbi = [\n {\n type: \"function\",\n name: \"join\",\n inputs: [\n {\n name: \"legs\",\n type: \"tuple[]\",\n internalType: \"struct IVaultBatcherConfidentialRouter.Allocation[]\",\n components: [\n { name: \"batcher\", type: \"address\", internalType: \"address\" },\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"bytes32\", internalType: \"externalEuint64\" },\n ],\n },\n { name: \"inputProof\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"tokenWrapperRegistry\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ITokenWrapperRegistry\" }],\n stateMutability: \"view\",\n },\n { type: \"error\", name: \"InvalidTokenWrapperRegistry\", inputs: [] },\n { type: \"error\", name: \"MissingInputProof\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n { type: \"error\", name: \"ZamaProtocolUnsupported\", inputs: [] },\n {\n type: \"error\",\n name: \"UnlistedConfidentialToken\",\n inputs: [{ name: \"token\", type: \"address\", internalType: \"address\" }],\n },\n] as const;\n","import { encodeAbiParameters, getAbiItem, type Address, type Hex } from \"viem\";\nimport type { EncryptedValue } from \"../../relayer/types\";\nimport { vaultRouterAbi } from \"../abi/vault-router.abi\";\n\n/** One vault's share of a fan-out. */\nexport interface EncryptedAllocationLeg {\n readonly batcher: Address;\n /** The confidential token this leg spends. */\n readonly token: Address;\n /** Encrypted with the router as the verifying contract. */\n readonly amount: EncryptedValue;\n}\n\n/** Returns the contract config to pull every leg from the caller and join each named batcher. */\nexport function routerJoinContract(\n router: Address,\n legs: readonly EncryptedAllocationLeg[],\n inputProof: Hex,\n) {\n return {\n address: router,\n abi: vaultRouterAbi,\n functionName: \"join\",\n args: [legs, inputProof],\n } as const;\n}\n\n// The push path decodes `data` into `join`'s parameters, so take them from the ABI.\nconst ALLOCATION_PARAMETERS = getAbiItem({ abi: vaultRouterAbi, name: \"join\" }).inputs;\n\n/** The payload that lets one confidential transfer of the shared asset fund every leg. */\nexport function encodeAllocationData(\n legs: readonly EncryptedAllocationLeg[],\n inputProof: Hex,\n): Hex {\n return encodeAbiParameters(ALLOCATION_PARAMETERS, [legs.map((leg) => ({ ...leg })), inputProof]);\n}\n","import type { Address } from \"viem\";\nimport {\n ConfigurationError,\n VaultBatcherPausedError,\n VaultBatcherReadFailedError,\n} from \"../errors\";\nimport type { GenericProvider } from \"../types\";\nimport { isContractCallError } from \"../utils/error\";\nimport { batchersOf, type BatcherEntry, type Vault } from \"./config\";\nimport {\n batchCreatedAtContract,\n batchMinBatchAgeContract,\n batchStateContract,\n closedContract,\n currentBatchIdContract,\n pausedContract,\n} from \"./contracts\";\nimport type { BatchState, JoinDirection } from \"./types\";\n\n/** A join sent this close to its batch's due time can land after the dispatch and wait a whole cycle. */\nexport const JOIN_MARGIN_SECONDS = 60n;\n\n// The batcher's `BatchState` enum, in on-chain order.\nconst BATCH_STATES: readonly BatchState[] = [\"pending\", \"dispatched\", \"finalized\", \"canceled\"];\n\n/** What one batcher offers a join. */\nexport type BatcherOffer =\n | {\n readonly status: \"open\";\n readonly batcher: Address;\n readonly batchId: bigint;\n readonly dispatchableAt: bigint;\n /** The previous batch is still in flight, so this batch waits for it to settle before it is dispatched. */\n readonly blocked: boolean;\n }\n | {\n readonly status: \"paused\";\n readonly batcher: Address;\n readonly batchId: bigint;\n readonly dispatchableAt: bigint;\n }\n /** Closed on chain, or past its configured `lastBatchId`: it never takes a join again. */\n | { readonly status: \"closed\"; readonly batcher: Address };\n\nexport type OpenOffer = Extract<BatcherOffer, { status: \"open\" }>;\nexport type PausedOffer = Extract<BatcherOffer, { status: \"paused\" }>;\n\nfunction soonest(offers: readonly OpenOffer[]): OpenOffer | undefined {\n return [...offers].sort((a, b) => {\n if (a.dispatchableAt !== b.dispatchableAt) {\n return a.dispatchableAt < b.dispatchableAt ? -1 : 1;\n }\n // Same order on every client, so a tie does not split the joins.\n const [left, right] = [a.batcher.toLowerCase(), b.batcher.toLowerCase()];\n return left < right ? -1 : left > right ? 1 : 0;\n })[0];\n}\n\n/**\n * The batch a join reaches, or a paused batcher's batch when none is open; `undefined` when every batcher is closed.\n *\n * @internal\n */\nexport function pickNextBatch(\n offers: readonly BatcherOffer[],\n now: bigint,\n): OpenOffer | PausedOffer | undefined {\n const open = offers.filter((offer): offer is OpenOffer => offer.status === \"open\");\n return (\n soonest(open.filter((o) => !o.blocked && o.dispatchableAt >= now + JOIN_MARGIN_SECONDS)) ??\n soonest(open.filter((o) => o.blocked)) ??\n soonest(open) ??\n offers.find((offer): offer is PausedOffer => offer.status === \"paused\")\n );\n}\n\n/**\n * The batch a join into each vault reaches, in vault order, and the chain time it was picked at.\n *\n * @internal\n * @throws if a vault lists no batcher, or an address or `lastBatchId` is invalid. {@link ConfigurationError}\n * @throws if every batcher of a vault is closed. {@link VaultBatcherPausedError}\n * @throws if a batcher cannot be read. {@link VaultBatcherReadFailedError}\n */\nexport async function readNextBatches(\n provider: GenericProvider,\n chainId: number,\n vaults: readonly Vault[],\n direction: JoinDirection,\n): Promise<{\n readonly now: bigint;\n readonly next: readonly { readonly vault: Vault; readonly offer: OpenOffer | PausedOffer }[];\n}> {\n const [now, read] = await Promise.all([\n provider.getBlockTimestamp(chainId),\n Promise.all(\n vaults.map(async (vault) => {\n const entries = batchersOf(vault, direction);\n const offers = await Promise.all(\n entries.map((entry) => offerOf(provider, chainId, vault.id, entry)),\n );\n return { vault, entries, offers };\n }),\n ),\n ]);\n const next = read.map(({ vault, entries, offers }) => {\n const offer = pickNextBatch(offers, now);\n if (offer === undefined) {\n throw new VaultBatcherPausedError(\n `Every ${direction} batcher of vault \"${vault.id}\" is closed, so the vault takes no joins`,\n { batcher: entries[0].address, vaultId: vault.id },\n );\n }\n return { vault, offer };\n });\n return { now, next };\n}\n\n/**\n * The state of one batch.\n *\n * @internal\n * @throws if the batcher returns a state outside its enum. {@link ConfigurationError}\n */\nexport async function readBatchState(\n provider: GenericProvider,\n chainId: number,\n batcher: Address,\n batchId: bigint,\n): Promise<BatchState> {\n const index = await provider.readContract({ ...batchStateContract(batcher, batchId), chainId });\n const state = BATCH_STATES[index];\n if (state === undefined) {\n throw new ConfigurationError(\n `Batcher ${batcher} returned unknown batch state ${index} for batch ${batchId}; is it a vault batcher?`,\n );\n }\n return state;\n}\n\n/**\n * Whether the batch before `batchId` is still in flight, so `batchId` should not be dispatched yet.\n *\n * @internal\n */\nexport async function waitsOnPrevious(\n provider: GenericProvider,\n chainId: number,\n batcher: Address,\n batchId: bigint,\n): Promise<boolean> {\n return (\n batchId > 1n &&\n (await readBatchState(provider, chainId, batcher, batchId - 1n)) === \"dispatched\"\n );\n}\n\nasync function offerOf(\n provider: GenericProvider,\n chainId: number,\n vaultId: string,\n entry: BatcherEntry,\n): Promise<BatcherOffer> {\n const details = { batcher: entry.address, vaultId };\n const where = `vault \"${vaultId}\"`;\n try {\n // A stale read is most likely one block behind, so one more read settles it.\n const offer =\n (await readOffer(provider, chainId, entry)) ?? (await readOffer(provider, chainId, entry));\n if (offer !== undefined) {\n return offer;\n }\n } catch (cause) {\n // A provider on another chain, or a batcher that is not one, is a setup problem, not a read failure.\n if (cause instanceof ConfigurationError) {\n throw cause;\n }\n throw new VaultBatcherReadFailedError(\n `Could not read batcher ${entry.address} of ${where}`,\n details,\n { cause },\n );\n }\n throw new VaultBatcherReadFailedError(\n `Batcher ${entry.address} of ${where} has no open batch but is not closed; the RPC returned reads from different blocks`,\n details,\n { retryable: true },\n );\n}\n\n// `undefined` when the reads disagree: a current batch with no creation time on a batcher that is not closed.\nasync function readOffer(\n provider: GenericProvider,\n chainId: number,\n { address: batcher, lastBatchId }: BatcherEntry,\n): Promise<BatcherOffer | undefined> {\n const [paused, batchId] = await Promise.all([\n provider.readContract({ ...pausedContract(batcher), chainId }),\n provider.readContract({ ...currentBatchIdContract(batcher), chainId }),\n ]);\n if (lastBatchId !== undefined && batchId > lastBatchId) {\n return { status: \"closed\", batcher };\n }\n const [createdAt, minAge, blocked] = await Promise.all([\n provider.readContract({ ...batchCreatedAtContract(batcher, batchId), chainId }),\n provider.readContract({ ...batchMinBatchAgeContract(batcher, batchId), chainId }),\n paused ? false : waitsOnPrevious(provider, chainId, batcher, batchId),\n ]);\n // A closed batcher never opens its next batch. Otherwise, a node behind the one that\n // returned `batchId` has not seen the batch open yet.\n if (createdAt === 0n) {\n return (await isClosed(provider, chainId, batcher)) ? { status: \"closed\", batcher } : undefined;\n }\n const dispatchableAt = createdAt + minAge;\n return paused\n ? { status: \"paused\", batcher, batchId, dispatchableAt }\n : { status: \"open\", batcher, batchId, dispatchableAt, blocked };\n}\n\n// A batcher deployed before `closed()` reverts on it, and it never closes on chain either.\nasync function isClosed(\n provider: GenericProvider,\n chainId: number,\n batcher: Address,\n): Promise<boolean> {\n try {\n return await provider.readContract({ ...closedContract(batcher), chainId });\n } catch (error) {\n if (isContractCallError(error)) {\n return false;\n }\n throw error;\n }\n}\n","import { getAddress, type Address } from \"viem\";\nimport { eventTopic, topicToAddress } from \"../events/log-decoding\";\nimport type { RawLog } from \"../types/transaction\";\n\nconst JOINED = eventTopic(\"Joined(uint256,address,bytes32)\");\n\n/**\n * The batch id of the first `Joined` log of `batcher` for `account`, or `null` if there is none.\n * Removes that log from `logs`. A log with no emitter address matches any `batcher`.\n */\nexport function takeJoinedBatchId(\n logs: RawLog[],\n batcher: Address,\n account: Address,\n): bigint | null {\n for (const [index, log] of logs.entries()) {\n const [topic, batchId, accountTopic] = log.topics;\n if (\n topic !== JOINED ||\n batchId === undefined ||\n accountTopic === undefined ||\n // Some adapters omit the emitter address.\n (log.address !== undefined && getAddress(log.address) !== batcher) ||\n topicToAddress(accountTopic) !== account\n ) {\n continue;\n }\n logs.splice(index, 1);\n return BigInt(batchId);\n }\n return null;\n}\n","import { encodeFunctionData, getAddress, type Address, type Hex } from \"viem\";\nimport {\n confidentialTransferAndCallContract,\n isOperatorContract,\n setOperatorContract,\n unwrapAmountContract,\n} from \"../contracts\";\nimport {\n BalanceCheckUnavailableError,\n ChainMismatchError,\n ConfigurationError,\n DecryptionFailedError,\n EncryptionFailedError,\n SignerNotConfiguredError,\n VaultBatcherPausedError,\n VaultBatchNotDispatchedError,\n VaultJoinUnconfirmedError,\n} from \"../errors\";\nimport type { TransactionOperation } from \"../events/sdk-events\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport type { TelemetryOperation } from \"../telemetry\";\nimport { Token } from \"../token\";\nimport type {\n ContractAbi,\n GenericSigner,\n ReadContractArgs,\n ReadContractConfig,\n ReadFunctionName,\n TransactionResult,\n WriteContractConfig,\n} from \"../types\";\nimport { requireWriteChain } from \"../utils/alignment\";\nimport { assertConfidentialBalance } from \"../utils/assert-balance\";\nimport { assertBigint, assertNonNullable } from \"../utils/assertions\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport { submitTransaction } from \"../utils/submit-transaction\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport { scopeOf, type Vault, type VaultGroup, type VaultIdOf } from \"./config\";\nimport { readBatchState, readNextBatches, waitsOnPrevious } from \"./next-batch\";\nimport {\n batchCallbackDeadlineContract,\n batchCreatedAtContract,\n batchDispatchedAtContract,\n batchMinBatchAgeContract,\n claimContract,\n depositsContract,\n dispatchBatchCallbackContract,\n dispatchBatchContract,\n encodeAllocationData,\n exchangeRateContract,\n exchangeRateDecimalsContract,\n fromTokenContract,\n pausedContract,\n quitContract,\n routerJoinContract,\n unwrapRequestIdContract,\n} from \"./contracts\";\nimport { takeJoinedBatchId } from \"./joined\";\nimport type {\n Batch,\n BatchAction,\n BatchRef,\n BatcherRef,\n Call,\n JoinCall,\n JoinDirection,\n GroupJoinInput,\n GroupJoinOptions,\n JoinInput,\n JoinOptions,\n JoinOutcome,\n JoinRoute,\n OpenBatch,\n OperatorApprovalCall,\n PreparedFinalize,\n PreparedJoin,\n SendJoinOptions,\n VaultCall,\n VaultLeg,\n} from \"./types\";\n\n// A router pulls a share token only for its holder's join, so a year-long approval is safe.\nconst OPERATOR_APPROVAL_VALIDITY_SECONDS = 365n * 24n * 60n * 60n;\n\nconst ENCRYPT_OPERATION = {\n deposit: \"vault-deposit\",\n redeem: \"vault-redeem\",\n} as const satisfies Record<JoinDirection, TelemetryOperation>;\n\nconst JOIN_OPERATION = {\n direct: \"vault:join\",\n router: \"vault:routerJoin\",\n} as const satisfies Record<JoinRoute, TransactionOperation>;\n\n// Arrays built in leg order line up with the legs, so a gap is an SDK bug, not a user error.\nfunction at<T>(values: readonly T[], index: number): T {\n const value = values[index];\n assertNonNullable(value, `vault leg ${index}`);\n return value;\n}\n\nfunction toCall(config: WriteContractConfig): Call {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi,\n functionName: config.functionName,\n args: config.args,\n } as Parameters<typeof encodeFunctionData>[0]),\n value: 0n,\n };\n}\n\n/** A join as the client plans it: a vault on its own has no `vaultId`. */\ntype AnyJoinInput = JoinInput & { readonly vaultId?: string };\n\nfunction memberOf(group: VaultGroup, vaultId: string | undefined): Vault {\n const vault = group.vaults.find((candidate) => candidate.id === vaultId);\n if (vault === undefined) {\n throw new ConfigurationError(`Vault group \"${group.id}\" has no vault \"${vaultId}\"`);\n }\n return vault;\n}\n\nfunction nonEmpty<T>(values: readonly T[]): readonly [T, ...T[]] {\n const [first, ...rest] = values;\n assertNonNullable(first, \"vault calls\");\n return [first, ...rest];\n}\n\ninterface Planned<TCall> {\n readonly call: TCall;\n readonly config: WriteContractConfig;\n}\n\n// A failed memoized read is not cached, so the next call tries again.\nfunction memoize<T>(cache: Map<string, Promise<T>>, key: string, read: () => Promise<T>) {\n let pending = cache.get(key);\n if (pending === undefined) {\n pending = read().catch((error: unknown) => {\n cache.delete(key);\n throw error;\n });\n cache.set(key, pending);\n }\n return pending;\n}\n\n/** Reads confidential vault batches, and builds and sends vault transactions. */\nexport class VaultClient {\n readonly #sdk: ZamaSDK;\n\n readonly #reads = new Map<string, Promise<unknown>>();\n\n /** @internal Use {@link createVaultClient}. */\n constructor(sdk: ZamaSDK) {\n this.#sdk = sdk;\n }\n\n /**\n * Build a deposit into a vault on its own: one call to its deposit batcher.\n * Only `input.account` can send it. With `skipBalanceCheck`, check the\n * account's balance before sending.\n *\n * @throws if the provider is not on the vault's chain while a wallet is connected. {@link ChainMismatchError}\n * @throws if the provider is on another chain with no wallet connected, a vault lists no batcher, or a batcher address or `lastBatchId` is invalid. {@link ConfigurationError}\n * @throws if no batcher of a vault the join reaches is open, even with `skipBalanceCheck`. {@link VaultBatcherPausedError}\n * @throws if a batcher of a vault the join reaches cannot be read. {@link VaultBatcherReadFailedError}\n * @throws if the balance is less than `amount` and `skipBalanceCheck` is not set. {@link InsufficientConfidentialBalanceError}\n * @throws if `skipBalanceCheck` is not set and no signer is connected, `account` is not the signer's, or the balance cannot be read. {@link BalanceCheckUnavailableError}\n * @throws if encryption returns a different number of values than the join has legs. {@link EncryptionFailedError}\n */\n prepareDeposit(vault: Vault, input: JoinInput, options?: JoinOptions): Promise<PreparedJoin>;\n /**\n * Build a deposit into one vault of a group, with a leg for every vault.\n * With `route: \"direct\"`, send the calls as one atomic bundle, and with\n * `skipBalanceCheck`, decrypt every leg's token together: doing either for\n * only some legs shows which vault was chosen.\n *\n * @throws as the single-vault overload.\n * @throws also if the vault is not in the group, the group has more than `MAX_GROUP_VAULTS` vaults, mixes chains or names a vault twice, the deposit batchers take different assets, or, on the router route, the chain has no router. {@link ConfigurationError}\n */\n prepareDeposit<TGroup extends VaultGroup>(\n group: TGroup,\n input: GroupJoinInput<VaultIdOf<TGroup>>,\n options?: GroupJoinOptions,\n ): Promise<PreparedJoin>;\n async prepareDeposit(\n target: Vault | VaultGroup,\n input: AnyJoinInput,\n options?: GroupJoinOptions,\n ): Promise<PreparedJoin> {\n return (await this.#planJoin(\"deposit\", target, input, options)).prepared;\n }\n\n /**\n * Build a redemption of a vault's shares on its own: one call to its redeem\n * batcher. Only `input.account` can send it. With `skipBalanceCheck`, check\n * the account's share balance before sending.\n *\n * @throws as {@link prepareDeposit}.\n */\n prepareRedeem(vault: Vault, input: JoinInput, options?: JoinOptions): Promise<PreparedJoin>;\n /**\n * Build a redemption of the shares of one vault of a group, with a leg for\n * every vault. On the router route, `calls` starts with a year-long operator\n * approval on each share token the account has not approved. With\n * `route: \"direct\"`, send the calls as one atomic bundle, and with\n * `skipBalanceCheck`, decrypt every leg's token together: doing either for\n * only some legs shows which vault was chosen.\n *\n * @throws as {@link prepareDeposit} for a group, except that the batchers may take different tokens.\n */\n prepareRedeem<TGroup extends VaultGroup>(\n group: TGroup,\n input: GroupJoinInput<VaultIdOf<TGroup>>,\n options?: GroupJoinOptions,\n ): Promise<PreparedJoin>;\n async prepareRedeem(\n target: Vault | VaultGroup,\n input: AnyJoinInput,\n options?: GroupJoinOptions,\n ): Promise<PreparedJoin> {\n return (await this.#planJoin(\"redeem\", target, input, options)).prepared;\n }\n\n /**\n * Claim a finalized batch's output for `account`. Anyone may send it; the output always\n * goes to `account`. The output is the account's deposit times the batch's exchange rate,\n * rounded down; the deposit then reads as an encrypted zero.\n */\n prepareClaim(batch: BatchRef, account: Address): Call {\n return toCall(claimContract(getAddress(batch.batcher), batch.batchId, getAddress(account)));\n }\n\n /**\n * Take the sender's deposit back from a pending batch, or from a canceled\n * one. Only the depositor may send it, and it leaves the deposit as an\n * encrypted zero. After a group join, quit every leg of it: quitting only the\n * chosen one shows which vault was chosen.\n */\n prepareQuit(batch: BatchRef): Call {\n return toCall(quitContract(getAddress(batch.batcher), batch.batchId));\n }\n\n /** Close the batcher's open batch and start its decryption. Permissionless; reverts while too young or paused. */\n prepareDispatch(batch: BatcherRef): Call {\n return toCall(dispatchBatchContract(getAddress(batch.batcher)));\n }\n\n /**\n * Build the settlement of a dispatched batch with its publicly decrypted\n * amount. Permissionless. Past the batch's callback deadline the same call\n * cancels it instead.\n *\n * @throws if the batch is not dispatched. {@link VaultBatchNotDispatchedError}\n * @throws if the provider is not on the batch's chain while a wallet is connected. {@link ChainMismatchError}\n * @throws if the provider is not on the batch's chain with no wallet connected, or the batcher reports an unknown batch state. {@link ConfigurationError}\n * @throws if public decryption returns no value for the batch's handle. {@link DecryptionFailedError}\n */\n async prepareFinalize(batch: BatchRef): Promise<PreparedFinalize> {\n return (await this.#planFinalize(batch)).call;\n }\n\n async #planFinalize(batch: BatchRef): Promise<Planned<PreparedFinalize>> {\n const batcher = getAddress(batch.batcher);\n const [state, requestId, wrapper] = await Promise.all([\n readBatchState(this.#sdk.provider, batch.chainId, batcher, batch.batchId),\n this.#read(batch.chainId, unwrapRequestIdContract(batcher, batch.batchId)),\n this.#fromToken(batch.chainId, batcher),\n ]);\n // Outside `dispatched` the request is unset or spent, so the decryption would fail opaquely.\n if (state !== \"dispatched\") {\n throw new VaultBatchNotDispatchedError(\n `Batch ${batch.batchId} of batcher ${batcher} is ${state}, but only a dispatched batch can be finalized`,\n { batcher, batchId: batch.batchId, state },\n );\n }\n const handle = await this.#read(batch.chainId, unwrapAmountContract(wrapper, requestId));\n await this.#requireProviderChain(batch.chainId, \"vault finalize\");\n const { clearValues, decryptionProof } = await this.#sdk.decryption.decryptPublicValues(\n [handle],\n { operation: \"vault-finalize\" },\n );\n const cleartext = clearValues[handle];\n if (cleartext === undefined) {\n throw new DecryptionFailedError(`Public decryption returned no value for ${handle}`);\n }\n assertBigint(cleartext, \"finalize: clearValues[handle]\");\n const config = dispatchBatchCallbackContract(\n batcher,\n batch.batchId,\n cleartext,\n decryptionProof,\n );\n return {\n config,\n call: {\n chainId: batch.chainId,\n batcher,\n batchId: batch.batchId,\n unwrapAmountCleartext: cleartext,\n decryptionProof,\n call: toCall(config),\n },\n };\n }\n\n /**\n * Deposit into a vault on its own with the SDK's signer, for the signer's\n * account.\n *\n * @throws as {@link prepareDeposit}.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the vault's chain. {@link ChainMismatchError}\n * @throws if a transaction fails or reverts. {@link TransactionRevertedError}\n * @throws if the join was mined but its receipt does not confirm every leg; the join most likely\n * went through. {@link VaultJoinUnconfirmedError}\n */\n deposit(\n vault: Vault,\n input: Omit<JoinInput, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome>;\n /**\n * Deposit into one vault of a group with the SDK's signer, with a leg for\n * every vault.\n *\n * @throws as the single-vault overload, and as {@link prepareDeposit} for a group.\n */\n deposit<TGroup extends VaultGroup>(\n group: TGroup,\n input: Omit<GroupJoinInput<VaultIdOf<TGroup>>, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome>;\n async deposit(\n target: Vault | VaultGroup,\n input: Omit<AnyJoinInput, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome> {\n return this.#join(\"deposit\", target, input, options);\n }\n\n /**\n * Redeem a vault's shares on its own with the SDK's signer.\n *\n * @throws as {@link deposit}.\n */\n redeem(\n vault: Vault,\n input: Omit<JoinInput, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome>;\n /**\n * Redeem the shares of one vault of a group with the SDK's signer. It first\n * asks the wallet for each operator approval of the router the account lacks.\n *\n * @throws as {@link deposit} for a group, except that the batchers may take different tokens.\n */\n redeem<TGroup extends VaultGroup>(\n group: TGroup,\n input: Omit<GroupJoinInput<VaultIdOf<TGroup>>, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome>;\n async redeem(\n target: Vault | VaultGroup,\n input: Omit<AnyJoinInput, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome> {\n return this.#join(\"redeem\", target, input, options);\n }\n\n /**\n * Claim a finalized batch with the SDK's signer, for `account` (default: the signer).\n * The output is the account's deposit times the batch's exchange rate, rounded down;\n * the deposit then reads as an encrypted zero.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the batch's chain. {@link ChainMismatchError}\n * @throws if the transaction fails or reverts. {@link TransactionRevertedError}\n */\n async claim(batch: BatchRef, account?: Address): Promise<TransactionResult> {\n const signer = await this.#writeAccount(batch.chainId, \"claim\");\n const call = claimContract(\n getAddress(batch.batcher),\n batch.batchId,\n getAddress(account ?? signer),\n );\n return this.#send(call, \"vault:claim\");\n }\n\n /**\n * Quit a pending or canceled batch with the SDK's signer, which must be the depositor.\n * It leaves the deposit as an encrypted zero. After a group join, quit every leg of it:\n * quitting only the chosen one shows which vault was chosen.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the batch's chain. {@link ChainMismatchError}\n * @throws if the transaction fails or reverts. {@link TransactionRevertedError}\n */\n async quit(batch: BatchRef): Promise<TransactionResult> {\n await this.#writeAccount(batch.chainId, \"quit\");\n return this.#send(quitContract(getAddress(batch.batcher), batch.batchId), \"vault:quit\");\n }\n\n /**\n * Dispatch the batcher's open batch with the SDK's signer.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the batcher's chain. {@link ChainMismatchError}\n * @throws if the transaction fails or reverts. {@link TransactionRevertedError}\n */\n async dispatch(batch: BatcherRef): Promise<TransactionResult> {\n await this.#writeAccount(batch.chainId, \"dispatch\");\n return this.#send(dispatchBatchContract(getAddress(batch.batcher)), \"vault:dispatchBatch\");\n }\n\n /**\n * Finalize a dispatched batch with the SDK's signer.\n *\n * @throws as {@link prepareFinalize}.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the batch's chain. {@link ChainMismatchError}\n * @throws if the transaction fails or reverts. {@link TransactionRevertedError}\n */\n async finalize(batch: BatchRef): Promise<TransactionResult> {\n // Before the public decryption, so a wrong chain fails before the relayer round trip.\n await this.#writeAccount(batch.chainId, \"finalize\");\n return this.#send((await this.#planFinalize(batch)).config, \"vault:finalize\");\n }\n\n /**\n * One batch's state and timings, and what can be sent for it now. Pass\n * `account` to read its encrypted deposit and to list `claim` and `quit`.\n */\n async readBatch(batch: BatchRef, account?: Address): Promise<Batch> {\n const { chainId, batchId } = batch;\n const batcher = getAddress(batch.batcher);\n const depositor = account === undefined ? undefined : getAddress(account);\n const [\n state,\n createdAt,\n minAge,\n dispatchedAt,\n deadline,\n paused,\n rate,\n decimals,\n deposit,\n now,\n blocked,\n ] = await Promise.all([\n readBatchState(this.#sdk.provider, chainId, batcher, batchId),\n this.#read(chainId, batchCreatedAtContract(batcher, batchId)),\n this.#read(chainId, batchMinBatchAgeContract(batcher, batchId)),\n this.#read(chainId, batchDispatchedAtContract(batcher, batchId)),\n this.#read(chainId, batchCallbackDeadlineContract(batcher, batchId)),\n this.#read(chainId, pausedContract(batcher)),\n this.#read(chainId, exchangeRateContract(batcher, batchId)),\n this.#memo(`decimals:${chainId}:${batcher}`, () =>\n this.#read(chainId, exchangeRateDecimalsContract(batcher)),\n ),\n depositor === undefined\n ? null\n : this.#read(chainId, depositsContract(batcher, batchId, depositor)),\n this.#sdk.provider.getBlockTimestamp(chainId),\n waitsOnPrevious(this.#sdk.provider, chainId, batcher, batchId),\n ]);\n const dispatchableAt = createdAt + minAge;\n const cancelsAt = dispatchedAt + deadline;\n // A literal zero handle means the account never joined this batch.\n const member = deposit !== null && !isEncryptedValueZero(deposit);\n const actions = (\n [\n [\"claim\", member && state === \"finalized\"],\n [\"quit\", member && (state === \"pending\" || state === \"canceled\")],\n [\"dispatch\", state === \"pending\" && !paused && !blocked && dispatchableAt <= now],\n [\"finalize\", state === \"dispatched\"],\n ] as const\n ).flatMap(([action, allowed]): BatchAction[] => (allowed ? [action] : []));\n const edge = state === \"pending\" ? dispatchableAt : state === \"dispatched\" ? cancelsAt : null;\n const base = {\n chainId,\n batcher,\n batchId,\n createdAt,\n dispatchableAt,\n paused,\n deposit,\n actions,\n observedAt: now,\n nextChangeAt: edge !== null && edge > now ? edge : null,\n };\n switch (state) {\n case \"pending\":\n return { ...base, state };\n case \"finalized\":\n return { ...base, state, dispatchedAt, cancelsAt, exchangeRate: { rate, decimals } };\n default:\n return { ...base, state, dispatchedAt, cancelsAt };\n }\n }\n\n /**\n * The batch a join reaches now, for a vault or each vault of a group, with\n * when it can be dispatched. When no batcher of a vault is open, it is a\n * paused batcher's batch with `paused: true`.\n *\n * @throws if a vault lists no batcher, or an address or `lastBatchId` is invalid. {@link ConfigurationError}\n * @throws if every batcher of a vault is closed. {@link VaultBatcherPausedError}\n * @throws if a batcher cannot be read. {@link VaultBatcherReadFailedError}\n */\n async readOpenBatches(\n target: Vault | VaultGroup,\n direction: JoinDirection,\n ): Promise<readonly OpenBatch[]> {\n const { vaults, chainId } = scopeOf(target);\n const { now, next } = await readNextBatches(this.#sdk.provider, chainId, vaults, direction);\n return next.map(({ vault, offer: { status, batcher, batchId, dispatchableAt } }) => ({\n vaultId: vault.id,\n chainId,\n batcher,\n batchId,\n dispatchableAt,\n paused: status === \"paused\",\n observedAt: now,\n }));\n }\n\n async #planJoin(\n direction: JoinDirection,\n joinTarget: Vault | VaultGroup,\n input: AnyJoinInput,\n options: GroupJoinOptions | undefined,\n ): Promise<{ readonly prepared: PreparedJoin; readonly planned: readonly Planned<VaultCall>[] }> {\n const { group, vaults, chainId } = scopeOf(joinTarget);\n const chosen = group === undefined ? vaults[0] : memberOf(group, input.vaultId);\n const account = getAddress(input.account);\n const route: JoinRoute = group === undefined ? \"direct\" : (options?.route ?? \"router\");\n\n // Encryption runs on the provider's chain, so check it before anything prompts.\n await this.#requireProviderChain(chainId, `vault ${direction}`);\n const router = group !== undefined && route === \"router\" ? this.#router(group) : undefined;\n // A paused batcher reverts the whole join, so every leg needs an open batch.\n const { next } = await readNextBatches(this.#sdk.provider, chainId, vaults, direction);\n const batchers = next.map(({ vault, offer }) => {\n if (offer.status === \"paused\") {\n throw new VaultBatcherPausedError(\n group === undefined\n ? `Every ${direction} batcher of vault \"${vault.id}\" is paused or closed, so the vault cannot be joined until one resumes`\n : `Every ${direction} batcher of vault \"${vault.id}\" in group \"${group.id}\" is paused or closed, so no vault of the group can be joined until one resumes`,\n { batcher: offer.batcher, vaultId: vault.id },\n );\n }\n return offer.batcher;\n });\n const tokens = await Promise.all(batchers.map((batcher) => this.#fromToken(chainId, batcher)));\n const legs = nonEmpty(\n vaults.map((vault, index): VaultLeg => ({\n vaultId: vault.id,\n batcher: at(batchers, index),\n token: at(tokens, index),\n amount: vault === chosen ? input.amount : 0n,\n })),\n );\n const target = at(legs, vaults.indexOf(chosen));\n // A group deposits one asset: the router transfers it once and splits it into the legs.\n const stray = legs.find((leg) => direction === \"deposit\" && leg.token !== target.token);\n if (stray !== undefined) {\n throw new ConfigurationError(\n `Vault group \"${joinTarget.id}\" mixes deposit assets: vault \"${stray.vaultId}\" takes ${stray.token}, vault \"${target.vaultId}\" takes ${target.token}`,\n );\n }\n if (options?.skipBalanceCheck !== true) {\n await this.#assertBalance(direction, legs, target, account);\n }\n\n const operation = ENCRYPT_OPERATION[direction];\n const join = (config: WriteContractConfig, leg: VaultLeg): Planned<JoinCall> => ({\n config,\n call: { ...toCall(config), kind: \"join\", leg },\n });\n let joins: Planned<JoinCall>[];\n let operatorApprovals: Planned<OperatorApprovalCall>[] = [];\n if (router !== undefined) {\n const amounts = legs.map((leg) => leg.amount);\n const allocationOf = (handles: readonly EncryptedValue[]) =>\n legs.map((leg, index) => ({\n batcher: leg.batcher,\n token: leg.token,\n amount: at(handles, index),\n }));\n if (direction === \"redeem\") {\n // The router verifies the allocation, so its proof is bound to the router.\n const [[handles, routerProof], missing] = await Promise.all([\n this.#encrypt(router, account, amounts, operation),\n this.#missingOperatorApprovals(chainId, legs, account, router),\n ]);\n operatorApprovals = missing;\n joins = [join(routerJoinContract(router, allocationOf(handles), routerProof), target)];\n } else {\n // One proof per verifying contract: the router checks the allocation, the asset the total.\n const asset = target.token;\n const [[handles, routerProof], [[total], assetProof]] = await Promise.all([\n this.#encrypt(router, account, amounts, operation),\n this.#encrypt(asset, account, [input.amount], operation),\n ]);\n const data = encodeAllocationData(allocationOf(handles), routerProof);\n joins = [\n join(confidentialTransferAndCallContract(asset, router, total, assetProof, data), target),\n ];\n }\n } else {\n const encrypted = await this.#encryptPerToken(legs, account, operation);\n joins = legs.map((leg, index) => {\n const { handle, inputProof } = at(encrypted, index);\n return join(\n confidentialTransferAndCallContract(leg.token, leg.batcher, handle, inputProof, \"0x\"),\n leg,\n );\n });\n }\n\n // Operator approvals first: the router pulls under them.\n const planned: Planned<VaultCall>[] = [...operatorApprovals, ...joins];\n return {\n prepared: {\n direction,\n chainId,\n groupId: group?.id,\n vaultId: chosen.id,\n account,\n amount: input.amount,\n route,\n legs,\n calls: nonEmpty(planned.map(({ call }) => call)),\n },\n planned,\n };\n }\n\n async #join(\n direction: JoinDirection,\n target: Vault | VaultGroup,\n input: Omit<AnyJoinInput, \"account\">,\n options: SendJoinOptions | undefined,\n ): Promise<JoinOutcome> {\n const signer = this.#signer(direction);\n const { chainId } = scopeOf(target);\n const account = await this.#writeAccount(chainId, direction);\n const { prepared, planned } = await this.#planJoin(\n direction,\n target,\n { ...input, account },\n { skipBalanceCheck: options?.skipBalanceCheck },\n );\n const txHashes: Hex[] = [];\n let last: TransactionResult | undefined;\n for (const [index, { call, config }] of planned.entries()) {\n last = await submitTransaction({\n operation:\n call.kind === \"operatorApproval\" ? \"setOperator\" : JOIN_OPERATION[prepared.route],\n signer,\n provider: this.#sdk.provider,\n config,\n onSubmitted: index === planned.length - 1 ? options?.onJoinSubmitted : undefined,\n emit: (event) => this.#sdk.emitEvent(event, call.to),\n logger: this.#sdk.logger,\n });\n txHashes.push(last.txHash);\n }\n assertNonNullable(last, `vault ${direction}: last transaction`);\n // The join is the last call, so only its receipt holds the Joined logs.\n const logs = [...last.receipt.logs];\n const batches: (BatchRef & { vaultId: string })[] = [];\n const unconfirmed: string[] = [];\n for (const leg of prepared.legs) {\n const batchId = takeJoinedBatchId(logs, leg.batcher, account);\n if (batchId === null) {\n unconfirmed.push(leg.vaultId);\n } else {\n batches.push({ vaultId: leg.vaultId, chainId, batcher: leg.batcher, batchId });\n }\n }\n if (unconfirmed.length > 0) {\n throw new VaultJoinUnconfirmedError(\n `Transaction ${last.txHash} was mined, but its receipt has no Joined event for ${account} from the batcher of ${unconfirmed.map((id) => `vault \"${id}\"`).join(\", \")}${\"vaults\" in target ? ` in group \"${target.id}\"` : \"\"}`,\n { txHash: last.txHash, receipt: last.receipt, unconfirmedVaultIds: unconfirmed },\n );\n }\n return { batches, txHashes };\n }\n\n #router(group: VaultGroup): Address {\n const { chainId } = scopeOf(group);\n const router = this.#sdk.chains.find((chain) => chain.id === chainId)?.vaultRouterAddress;\n if (router === undefined) {\n throw new ConfigurationError(\n `Vault group \"${group.id}\" has ${group.vaults.length} vaults, but chain ${chainId} has no router; set vaultRouterAddress on the chain`,\n );\n }\n return getAddress(router);\n }\n\n // Fixed at deployment, so read once.\n #fromToken(chainId: number, batcher: Address): Promise<Address> {\n return this.#memo(`fromToken:${chainId}:${batcher}`, async () =>\n getAddress(await this.#read(chainId, fromTokenContract(batcher))),\n );\n }\n\n // A short balance joins every batch with nothing and still costs the transaction.\n async #assertBalance(\n direction: JoinDirection,\n legs: readonly VaultLeg[],\n target: VaultLeg,\n account: Address,\n ): Promise<void> {\n // Only the signer can decrypt its own balance; throwing keeps skipping the check explicit.\n const signerAccount = this.#sdk.signer?.walletAccount.getSnapshot()?.address;\n if (signerAccount === undefined || getAddress(signerAccount) !== account) {\n throw new BalanceCheckUnavailableError(\n `Cannot check the balance of ${account} for a vault ${direction}: ${\n signerAccount === undefined ? \"no signer is connected\" : \"the signer is another account\"\n }. Check it yourself, decrypting every leg's token together, and pass skipBalanceCheck: true`,\n );\n }\n await assertConfidentialBalance({\n operation: direction,\n tokenAddress: target.token,\n amount: target.amount,\n account,\n signer: this.#sdk.signer,\n provider: this.#sdk.provider,\n // Every leg's token is decrypted, not only the chosen one's: a lone decrypt would tell the relayer which vault was picked.\n readBalance: async (owner) => {\n const tokens = [...new Set(legs.map((leg) => leg.token))].map(\n (address) => new Token(this.#sdk, address),\n );\n const { results, errors } = await Token.batchBalancesOf(tokens, owner);\n const balance = results.get(target.token);\n if (balance === undefined) {\n throw (\n errors.get(target.token) ??\n new BalanceCheckUnavailableError(`Balance validation failed (token: ${target.token})`)\n );\n }\n return balance;\n },\n });\n }\n\n async #encrypt(\n contractAddress: Address,\n account: Address,\n values: readonly bigint[],\n operation: TelemetryOperation,\n ): Promise<readonly [readonly [EncryptedValue, ...EncryptedValue[]], Hex]> {\n const { encryptedValues, inputProof } = await this.#sdk.encrypt(\n {\n values: values.map((value) => ({ value, type: \"euint64\" as const })),\n contractAddress,\n userAddress: account,\n },\n { operation },\n );\n const [first, ...rest] = encryptedValues;\n if (first === undefined || encryptedValues.length !== values.length) {\n throw new EncryptionFailedError(\n `Encryption returned ${encryptedValues.length} values for ${values.length} legs`,\n );\n }\n return [[first, ...rest], inputProof];\n }\n\n // A transfer's proof is bound to the token it spends: one proof covers the legs that share a token.\n async #encryptPerToken(\n legs: readonly VaultLeg[],\n account: Address,\n operation: TelemetryOperation,\n ): Promise<{ readonly handle: EncryptedValue; readonly inputProof: Hex }[]> {\n const byLeg = new Map<VaultLeg, { handle: EncryptedValue; inputProof: Hex }>();\n await Promise.all(\n [...new Set(legs.map((leg) => leg.token))].map(async (token) => {\n const spending = legs.filter((leg) => leg.token === token);\n const [handles, inputProof] = await this.#encrypt(\n token,\n account,\n spending.map((leg) => leg.amount),\n operation,\n );\n spending.forEach((leg, index) =>\n byLeg.set(leg, { handle: at(handles, index), inputProof }),\n );\n }),\n );\n return legs.map((leg) => {\n const encrypted = byLeg.get(leg);\n assertNonNullable(encrypted, `vault leg ${leg.vaultId}`);\n return encrypted;\n });\n }\n\n async #missingOperatorApprovals(\n chainId: number,\n legs: readonly VaultLeg[],\n account: Address,\n operator: Address,\n ): Promise<Planned<OperatorApprovalCall>[]> {\n const approved = await Promise.all(\n legs.map((leg) => this.#read(chainId, isOperatorContract(leg.token, account, operator))),\n );\n const missing = legs.filter((_leg, index) => !approved[index]);\n if (missing.length === 0) {\n return [];\n }\n // The token compares the deadline against the block's time, not the local clock.\n const until =\n (await this.#sdk.provider.getBlockTimestamp(chainId)) + OPERATOR_APPROVAL_VALIDITY_SECONDS;\n return missing.map((leg) => {\n const config = setOperatorContract(leg.token, operator, Number(until));\n return {\n config,\n call: {\n ...toCall(config),\n kind: \"operatorApproval\",\n vaultId: leg.vaultId,\n operator,\n until,\n },\n };\n });\n }\n\n #signer(operation: string): GenericSigner {\n if (this.#sdk.signer === undefined) {\n throw new SignerNotConfiguredError(operation);\n }\n return this.#sdk.signer;\n }\n\n async #writeAccount(chainId: number, operation: string): Promise<Address> {\n const account = await requireWriteChain(\n `vault ${operation}`,\n this.#signer(operation),\n this.#sdk.provider,\n chainId,\n );\n return getAddress(account.address);\n }\n\n async #send(\n config: WriteContractConfig,\n operation: TransactionOperation,\n ): Promise<TransactionResult> {\n return submitTransaction({\n operation,\n signer: this.#signer(operation),\n provider: this.#sdk.provider,\n config,\n emit: (event) => this.#sdk.emitEvent(event, config.address),\n logger: this.#sdk.logger,\n });\n }\n\n async #requireProviderChain(chainId: number, operation: string): Promise<void> {\n const providerChainId = await this.#sdk.provider.getChainId();\n if (providerChainId === chainId) {\n return;\n }\n // A connected wallet gets the same error as a send, so an app has one \"switch chain\" case.\n const wallet = this.#sdk.signer?.walletAccount.getSnapshot();\n if (wallet !== undefined) {\n throw new ChainMismatchError({\n operation,\n signerChainId: wallet.chainId,\n providerChainId,\n targetChainId: chainId,\n });\n }\n throw new ConfigurationError(\n `Operation \"${operation}\" encrypts or decrypts on chain ${chainId}, but the provider is on chain ${providerChainId}`,\n );\n }\n\n #memo<T>(key: string, read: () => Promise<T>): Promise<T> {\n return memoize(this.#reads as Map<string, Promise<T>>, key, read);\n }\n\n #read<\n const TAbi extends ContractAbi,\n TFunctionName extends ReadFunctionName<TAbi>,\n const TArgs extends ReadContractArgs<TAbi, TFunctionName>,\n >(chainId: number, config: ReadContractConfig<TAbi, TFunctionName, TArgs>) {\n return this.#sdk.provider.readContract({ ...config, chainId });\n }\n}\n\n/**\n * A {@link VaultClient} bound to `sdk`. Reads nothing until first used.\n */\nexport function createVaultClient(sdk: ZamaSDK): VaultClient {\n return new VaultClient(sdk);\n}\n","import { getAddress, type Address } from \"viem\";\n// Keep the TanStack imports type-only, so the vaults barrel runs without TanStack Query.\nimport type { MutationFactoryOptions, QueryFactoryOptions } from \"../../query/factory-types\";\nimport type { QueryClientLike } from \"../../query/invalidation\";\nimport { zamaQueryKeys } from \"../../query/query-keys\";\nimport type { TransactionResult } from \"../../types\";\nimport { assertNonNullable } from \"../../utils/assertions\";\nimport type { VaultClient } from \"../client\";\nimport { chainIdOf, type Vault, type VaultGroup, type VaultIdOf } from \"../config\";\nimport { JOIN_MARGIN_SECONDS } from \"../next-batch\";\nimport type {\n Batch,\n BatchRef,\n BatcherRef,\n JoinDirection,\n JoinOutcome,\n OpenBatch,\n JoinInput,\n SendJoinOptions,\n} from \"../types\";\n\n/** How often a batch waiting for a keeper is read again. */\nconst KEEPER_POLL_MS = 15_000;\n\n// A timer delay above 2^31 - 1 ms overflows and fires at once.\nconst MAX_REFETCH_MS = 60 * 60 * 1000;\n\n/** Query keys for the vaults module. */\nexport const vaultQueryKeys = {\n /** A prefix of every vault key. */\n all: [\"zama.vault\"] as const,\n batch: (batch: BatchRef | undefined, account: Address | undefined) =>\n [\n \"zama.vault\",\n {\n kind: \"batch\",\n chainId: batch?.chainId,\n batcher: batch === undefined ? undefined : getAddress(batch.batcher),\n batchId: batch?.batchId,\n account: account === undefined ? undefined : getAddress(account),\n },\n ] as const,\n openBatches: (target: Vault | VaultGroup, direction: JoinDirection) =>\n [\n \"zama.vault\",\n {\n kind: \"openBatches\",\n chainId: chainIdOf(target),\n // A vault and a group may share an id, and read different batchers.\n scope: \"vaults\" in target ? \"group\" : \"vault\",\n id: target.id,\n direction,\n },\n ] as const,\n};\n\n/** Configuration for {@link batchQueryOptions}. */\nexport interface BatchQueryConfig {\n /** The query is disabled while this is `undefined`. */\n batch?: BatchRef;\n /** Read this account's deposit, and list `claim` and `quit` for it. */\n account?: Address;\n /** Set `enabled` to `false` to keep the query from running. */\n query?: { readonly enabled?: boolean };\n}\n\n// One second past chain time `at`, so the read lands after the change.\nfunction refetchAt(at: bigint, observedAt: bigint): number {\n return Math.min(Number(at - observedAt) * 1000 + 1000, MAX_REFETCH_MS);\n}\n\n/** How long to wait before reading a batch again, or `false` once it is finalized or canceled. */\nfunction batchRefetchInterval(read: Batch | undefined): number | false {\n if (read === undefined || read.state === \"finalized\" || read.state === \"canceled\") {\n return false;\n }\n if (read.nextChangeAt === null) {\n return KEEPER_POLL_MS;\n }\n const untilEdge = refetchAt(read.nextChangeAt, read.observedAt);\n // A dispatched batch waits for a settlement from the start, so it polls before its deadline too.\n return read.state === \"dispatched\" ? Math.min(untilEdge, KEEPER_POLL_MS) : untilEdge;\n}\n\n/**\n * Query options that read one batch with {@link VaultClient.readBatch}. They refetch when the\n * batch's `nextChangeAt` passes, and poll while it waits for a keeper; a `refetchInterval` passed\n * to `useQuery` replaces both.\n */\nexport function batchQueryOptions(\n client: VaultClient,\n config: BatchQueryConfig = {},\n): QueryFactoryOptions<Batch, Error, Batch, ReturnType<typeof vaultQueryKeys.batch>> {\n const { batch, account } = config;\n return {\n refetchInterval: (query) => batchRefetchInterval(query.state.data),\n queryKey: vaultQueryKeys.batch(batch, account),\n queryFn: async () => {\n assertNonNullable(batch, \"batchQueryOptions: batch\");\n return client.readBatch(batch, account);\n },\n enabled: batch !== undefined && config.query?.enabled !== false,\n };\n}\n\n/** Picks a group, or a vault on its own. */\nexport type VaultSelection =\n | { readonly group: VaultGroup; readonly vault?: never }\n | { readonly vault: Vault; readonly group?: never };\n\nfunction selected(selection: VaultSelection): Vault | VaultGroup {\n return selection.vault ?? selection.group;\n}\n\n/** Configuration for {@link openBatchesQueryOptions}. */\nexport type OpenBatchesQueryConfig = VaultSelection & {\n /** Whether the deposit or the redeem batchers are read. */\n direction: JoinDirection;\n};\n\n/**\n * Reads again one second after the soonest batch comes within {@link JOIN_MARGIN_SECONDS} of its\n * due time, when joins may move on, then every {@link KEEPER_POLL_MS} until a keeper dispatches it.\n * `false` while every vault is paused.\n */\nfunction openBatchesRefetchInterval(read: readonly OpenBatch[] | undefined): number | false {\n const waits = (read ?? [])\n .filter((batch) => !batch.paused)\n .map((batch) => {\n const movesAt = batch.dispatchableAt - JOIN_MARGIN_SECONDS;\n return movesAt > batch.observedAt ? refetchAt(movesAt, batch.observedAt) : KEEPER_POLL_MS;\n });\n return waits.length === 0 ? false : Math.min(...waits);\n}\n\n/**\n * Query options that read the open batch of every vault of a group, or of a vault on its own.\n * They refetch when a batch comes within a minute of its due time, and poll until a keeper\n * dispatches it; a `refetchInterval` passed to `useQuery` replaces both.\n */\nexport function openBatchesQueryOptions(\n client: VaultClient,\n config: OpenBatchesQueryConfig,\n): QueryFactoryOptions<\n readonly OpenBatch[],\n Error,\n readonly OpenBatch[],\n ReturnType<typeof vaultQueryKeys.openBatches>\n> {\n const target = selected(config);\n return {\n refetchInterval: (query) => openBatchesRefetchInterval(query.state.data),\n queryKey: vaultQueryKeys.openBatches(target, config.direction),\n queryFn: async () => client.readOpenBatches(target, config.direction),\n };\n}\n\n/** Invalidates every vault read and every confidential balance. */\nexport function invalidateAfterVaultAction(queryClient: QueryClientLike): void {\n void queryClient.invalidateQueries({ queryKey: vaultQueryKeys.all });\n void queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalance.all });\n void queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalances.all });\n}\n\n/** An amount for a vault of a group, picked by id, or for a vault on its own. */\nexport type JoinVariables<TGroup extends VaultGroup = VaultGroup> = Pick<JoinInput, \"amount\"> &\n SendJoinOptions &\n (\n | { readonly group: TGroup; readonly vaultId: VaultIdOf<TGroup>; readonly vault?: never }\n | { readonly vault: Vault; readonly vaultId?: never; readonly group?: never }\n );\n\nfunction joinMutation(client: VaultClient, direction: JoinDirection) {\n return {\n mutationKey: [`zama.vault.${direction}`] as const,\n mutationFn: async ({ skipBalanceCheck, onJoinSubmitted, amount, ...target }: JoinVariables) => {\n const options = { skipBalanceCheck, onJoinSubmitted };\n return target.vault === undefined\n ? client[direction](target.group, { vaultId: target.vaultId, amount }, options)\n : client[direction](target.vault, { amount }, options);\n },\n };\n}\n\n/** Mutation options over {@link VaultClient.deposit}. */\nexport function depositMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.deposit\"], JoinVariables, JoinOutcome> {\n return joinMutation(client, \"deposit\") as MutationFactoryOptions<\n readonly [\"zama.vault.deposit\"],\n JoinVariables,\n JoinOutcome\n >;\n}\n\n/** Mutation options over {@link VaultClient.redeem}. */\nexport function redeemMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.redeem\"], JoinVariables, JoinOutcome> {\n return joinMutation(client, \"redeem\") as MutationFactoryOptions<\n readonly [\"zama.vault.redeem\"],\n JoinVariables,\n JoinOutcome\n >;\n}\n\n/** Mutation options over {@link VaultClient.claim}. */\nexport function claimMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<\n readonly [\"zama.vault.claim\"],\n BatchRef & { readonly account?: Address },\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.vault.claim\"] as const,\n mutationFn: async ({ account, ...batch }) => client.claim(batch, account),\n };\n}\n\n/** Mutation options over {@link VaultClient.quit}. */\nexport function quitMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.quit\"], BatchRef, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.quit\"] as const,\n mutationFn: async (batch) => client.quit(batch),\n };\n}\n\n/** Mutation options over {@link VaultClient.dispatch}. */\nexport function dispatchMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.dispatch\"], BatcherRef, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.dispatch\"] as const,\n mutationFn: async (batch) => client.dispatch(batch),\n };\n}\n\n/** Mutation options over {@link VaultClient.finalize}. */\nexport function finalizeMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.finalize\"], BatchRef, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.finalize\"] as const,\n mutationFn: async (batch) => client.finalize(batch),\n };\n}\n"],"mappings":"A,kRAmFA,SAAgByC,EACd,EACiB,CACjB,OAAOC,CACT,CAqBA,SAAgBC,EACd,EACgC,CAChC,OAAOC,CACT,CAOA,SAAgBC,EAAU,EAAoC,CAC5D,MAAO,WAAYC,EAASA,EAAO,OAAO,EAAE,CAAC,QAAUA,EAAO,OAChE,CASA,SAAgBC,EAAQ,EAItB,CACA,GAAI,EAAE,WAAYD,GAChB,MAAO,CAAE,MAAO,IAAA,GAAW,OAAQ,CAACA,CAAM,EAAG,QAASA,EAAO,OAAQ,EAEvE,IAAME,EAAQ,gBAAgBF,EAAO,GAAG,GAClC,CAACG,GAASH,EAAO,OACvB,GAAIA,EAAO,OAAO,OAAA,EAChB,MAAM,IAAI9C,EAAAA,EACR,GAAGgD,EAAM,OAAOF,EAAO,OAAO,OAAO,qBACvC,EAEF,IAAMI,kBAAW,IAAI,IACrB,IAAK,IAAMR,KAASI,EAAO,OAAQ,CACjC,GAAIJ,EAAM,UAAYO,EAAM,QAC1B,MAAM,IAAIjD,EAAAA,EACR,GAAGgD,EAAM,wBAAwBN,EAAM,GAAG,gBAAgBA,EAAM,QAAQ,WAAWO,EAAM,GAAG,aAAaA,EAAM,SACjH,EAEF,GAAIC,EAAS,IAAIR,EAAM,EAAE,EACvB,MAAM,IAAI1C,EAAAA,EAAmB,GAAGgD,EAAM,gBAAgBN,EAAM,GAAG,QAAQ,EAEzEQ,EAAS,IAAIR,EAAM,EAAE,CACvB,CACA,MAAO,CAAE,MAAOI,EAAQ,OAAQA,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,QAAO,EAAG4G,CAAO,CACzD,CACF,CACF,CAGA,SAAgBqG,GACd,EACqF,CACrF,OAAOD,EAAaT,EAAQ,SAAS,CAKvC,CAGA,SAAgBW,GACd,EACoF,CACpF,OAAOF,EAAaT,EAAQ,QAAQ,CAKtC,CAGA,SAAgBY,GACd,EAKA,CACA,MAAO,CACL,YAAa,CAAC,kBAAkB,EAChC,WAAY,MAAO,CAAE,UAAS,GAAGtG,KAAY0F,EAAO,MAAM1F,EAAOvF,CAAO,CAC1E,CACF,CAGA,SAAgB8L,GACd,EACmF,CACnF,MAAO,CACL,YAAa,CAAC,iBAAiB,EAC/B,WAAY,KAAO,IAAUb,EAAO,KAAK1F,CAAK,CAChD,CACF,CAGA,SAAgBwG,GACd,EACyF,CACzF,MAAO,CACL,YAAa,CAAC,qBAAqB,EACnC,WAAY,KAAO,IAAUd,EAAO,SAAS1F,CAAK,CACpD,CACF,CAGA,SAAgByG,GACd,EACuF,CACvF,MAAO,CACL,YAAa,CAAC,qBAAqB,EACnC,WAAY,KAAO,IAAUf,EAAO,SAAS1F,CAAK,CACpD,CACF,C"}
1
+ {"version":3,"file":"index.cjs","names":["ConfigurationError","isAddress","getAddress","getAbiItem","encodeAbiParameters","ConfigurationError","zeroHash","VaultBatcherReadFailedError","isContractCallError","eventTopic","getAddress","topicToAddress","encodeFunctionData","ConfigurationError","VaultBatcherPausedError","getAddress","VaultBatchNotDispatchedError","unwrapAmountContract","decryptPublicUint","isEncryptedValueZero","confidentialTransferAndCallContract","submitTransaction","VaultJoinUnconfirmedError","BalanceCheckUnavailableError","assertConfidentialBalance","Token","EncryptionFailedError","isOperatorContract","setOperatorContract","SignerNotConfiguredError","requireWriteChain","ChainMismatchError","getAddress","zamaQueryKeys","require_alignment","require_token","require_relayer","require_encryption","require_public_decrypt","require_query_keys","viem","defineVault","vault","defineVaultGroup","group","chainIdOf","target","scopeOf","where","first","vaultIds","batchersOf","direction","rest","listOf","entryOf","batcher","declared","isArray","unbounded","entry","value","requireAddress","address","lastBatchId","vaultBatcherAbi","claimContract","batchId","account","quitContract","dispatchBatchContract","currentBatchIdContract","batchStateContract","depositsContract","fromTokenContract","batchMinBatchAgeContract","batchCallbackDeadlineContract","batchCreatedAtContract","batchDispatchedAtContract","exchangeRateContract","exchangeRateDecimalsContract","pausedContract","closedContract","unwrapRequestIdContract","dispatchBatchCallbackContract","unwrapAmountCleartext","decryptionProof","vaultRouterAbi","routerJoinContract","router","legs","inputProof","ALLOCATION_PARAMETERS","encodeAllocationData","leg","BATCH_STATES","soonest","offers","a","b","left","right","pickNextBatch","open","offer","o","now","readNextBatches","read","provider","chainId","vaults","entries","offerOf","readBatchState","index","state","waitsOnPrevious","previous","details","vaultId","readOffer","cause","paused","createdAt","minAge","blocked","isClosed","dispatchableAt","error","JOINED","takeJoinedBatchId","log","logs","topic","accountTopic","OPERATOR_APPROVAL_VALIDITY_SECONDS","ENCRYPT_OPERATION","JOIN_OPERATION","at","values","toCall","config","memberOf","candidate","noOpenBatcher","why","nonEmpty","memoize","pending","cache","key","VaultClient","#sdk","sdk","#planJoin","input","options","batch","#planFinalize","requestId","wrapper","#read","#fromToken","handle","#requireProviderChain","#join","signer","#writeAccount","call","#send","depositor","dispatchedAt","deadline","rate","decimals","deposit","#memo","cancelsAt","member","actions","action","allowed","edge","base","batches","next","status","joinTarget","chosen","route","#router","mine","stray","#assertBalance","operation","join","joins","operatorApprovals","amounts","allocationOf","handles","routerProof","missing","#encrypt","#missingOperatorApprovals","asset","total","assetProof","data","encrypted","#encryptPerToken","planned","#signer","txHashes","last","prepared","event","unconfirmed","id","chain","signerAccount","tokens","owner","balance","results","errors","encryptedValues","byLeg","spending","token","approved","operator","until","providerChainId","wallet","#reads","createVaultClient","KEEPER_POLL_MS","vaultQueryKeys","refetchAt","observedAt","batchRefetchInterval","untilEdge","batchQueryOptions","query","client","selected","selection","openBatchesRefetchInterval","waits","movesAt","openBatchesQueryOptions","invalidateAfterVaultAction","queryClient","joinMutation","depositMutationOptions","redeemMutationOptions","claimMutationOptions","quitMutationOptions","dispatchMutationOptions","finalizeMutationOptions"],"sources":["../../../src/vaults/config.ts","../../../src/vaults/abi/vault-batcher.abi.ts","../../../src/vaults/contracts/vault-batcher.ts","../../../src/vaults/abi/vault-router.abi.ts","../../../src/vaults/contracts/vault-router.ts","../../../src/vaults/next-batch.ts","../../../src/vaults/joined.ts","../../../src/vaults/client.ts","../../../src/vaults/query/index.ts"],"sourcesContent":["import { getAddress, isAddress, type Address } from \"viem\";\nimport { ConfigurationError } from \"../errors\";\nimport type { JoinDirection } from \"./types\";\n\n/** The most vaults a group may hold. */\nexport const MAX_GROUP_VAULTS = 4;\n\n/**\n * A batcher, with the last batch it takes joins in. Set `lastBatchId` only for\n * a batcher whose contract has no `closed()`.\n */\nexport interface BatcherEntry {\n /** The batcher's address. */\n readonly address: Address;\n /** The last batch joins may land in. Past it, joins go to the vault's other batchers. */\n readonly lastBatchId?: bigint;\n}\n\n/** The batchers of one vault direction: an address, or a list of addresses and {@link BatcherEntry} objects. A join or read throws on an empty list. */\nexport type Batchers = Address | readonly (Address | BatcherEntry)[];\n\n/**\n * A batcher that took joins while its `currentBatchId` was at most `lastBatchId`.\n *\n * @deprecated List the batchers as {@link Batchers} instead, a retired one as `{ address, lastBatchId }`.\n */\nexport type RetiredBatcher = BatcherEntry & { readonly lastBatchId: bigint };\n\n/**\n * Every batcher a vault has had in one direction. Read as the list\n * `[...retired, latest]`, so `latest` takes joins as soon as it is open, even\n * before a retired batcher reaches its `lastBatchId`.\n *\n * @deprecated List the batchers as {@link Batchers} instead.\n */\nexport interface BatcherHistory {\n /** Oldest first. */\n readonly retired: readonly RetiredBatcher[];\n /** The newest batcher. */\n readonly latest: Address;\n}\n\n/** One vault: its chain and the batchers each direction joins. */\nexport interface Vault<TVaultId extends string = string> {\n /** Names the vault in errors and query keys, and is what a group join passes as `vaultId`. */\n readonly id: TVaultId;\n /** The chain the vault's batchers are on. */\n readonly chainId: number;\n /**\n * The batchers each direction joins. A join reaches the open batch that is\n * dispatched next; paused and closed batchers take none.\n */\n readonly batchers: Readonly<Record<JoinDirection, Batchers | BatcherHistory>>;\n}\n\n/** Vaults that take deposits in one confidential asset, joined together. */\nexport interface VaultGroup<TGroupId extends string = string, TVaultId extends string = string> {\n /** Names the group in errors and query keys. */\n readonly id: TGroupId;\n /**\n * The vaults, in leg order, up to {@link MAX_GROUP_VAULTS}. They must be on one\n * chain, and their deposit batchers must take the same confidential asset.\n */\n readonly vaults: readonly [Vault<TVaultId>, Vault<TVaultId>, ...Vault<TVaultId>[]];\n}\n\n/** The vault ids of a group. */\nexport type VaultIdOf<TGroup extends VaultGroup> =\n TGroup extends VaultGroup<string, infer TVaultId> ? TVaultId : never;\n\n/**\n * Define a vault, keeping its id as a literal type. Returns `vault` as is and\n * checks nothing.\n *\n * @example\n * ```ts\n * export const ALPHA = defineVault({\n * id: \"alpha\",\n * chainId: 1,\n * batchers: { deposit: \"0xAlphaDeposit\", redeem: [\"0xAlphaRedeemA\", \"0xAlphaRedeemB\"] },\n * });\n * ```\n */\nexport function defineVault<const TVaultId extends string>(\n vault: Vault<TVaultId>,\n): Vault<TVaultId> {\n return vault;\n}\n\n/**\n * Define a group of vaults, keeping its ids as literal types, so a typo in\n * `vaultId` is a type error. Returns `group` as is and checks nothing.\n *\n * @example\n * ```ts\n * const ALPHA = defineVault({\n * id: \"alpha\",\n * chainId: 1,\n * batchers: { deposit: \"0xAlphaDeposit\", redeem: \"0xAlphaRedeem\" },\n * });\n * const BETA = defineVault({\n * id: \"beta\",\n * chainId: 1,\n * batchers: { deposit: \"0xBetaDeposit\", redeem: \"0xBetaRedeem\" },\n * });\n * export const STABLE = defineVaultGroup({ id: \"stable\", vaults: [ALPHA, BETA] });\n * ```\n */\nexport function defineVaultGroup<const TGroupId extends string, const TVaultId extends string>(\n group: VaultGroup<TGroupId, TVaultId>,\n): VaultGroup<TGroupId, TVaultId> {\n return group;\n}\n\n/**\n * The chain a vault, or every vault of a group, is on.\n *\n * @internal\n */\nexport function chainIdOf(target: Vault | VaultGroup): number {\n return \"vaults\" in target ? target.vaults[0].chainId : target.chainId;\n}\n\n/**\n * What a join or a read of `target` covers: every vault of a group, or a\n * vault on its own and no group.\n *\n * @internal\n * @throws if a group has more than {@link MAX_GROUP_VAULTS} vaults, mixes chains, or names a vault twice. {@link ConfigurationError}\n */\nexport function scopeOf(target: Vault | VaultGroup): {\n readonly group: VaultGroup | undefined;\n readonly vaults: readonly [Vault, ...Vault[]];\n readonly chainId: number;\n} {\n if (!(\"vaults\" in target)) {\n return { group: undefined, vaults: [target], chainId: target.chainId };\n }\n const where = `Vault group \"${target.id}\"`;\n const [first] = target.vaults;\n if (target.vaults.length > MAX_GROUP_VAULTS) {\n throw new ConfigurationError(\n `${where} has ${target.vaults.length} vaults, more than ${MAX_GROUP_VAULTS}`,\n );\n }\n const vaultIds = new Set<string>();\n for (const vault of target.vaults) {\n if (vault.chainId !== first.chainId) {\n throw new ConfigurationError(\n `${where} mixes chains: vault \"${vault.id}\" is on chain ${vault.chainId}, vault \"${first.id}\" on chain ${first.chainId}`,\n );\n }\n if (vaultIds.has(vault.id)) {\n throw new ConfigurationError(`${where} names vault \"${vault.id}\" twice`);\n }\n vaultIds.add(vault.id);\n }\n return { group: target, vaults: target.vaults, chainId: first.chainId };\n}\n\n/**\n * Every batcher of `vault` in `direction`, checksummed, in declared order. A\n * history lists its retired batchers, then `latest`.\n *\n * @internal\n * @throws if no batcher is listed, or an address or a `lastBatchId` is invalid. {@link ConfigurationError}\n */\nexport function batchersOf(\n vault: Vault,\n direction: JoinDirection,\n): readonly [BatcherEntry, ...BatcherEntry[]] {\n const where = `Vault \"${vault.id}\" ${direction} batcher`;\n const [first, ...rest] = listOf(vault.batchers[direction], where).map((batcher) =>\n entryOf(batcher, where),\n );\n if (first === undefined) {\n throw new ConfigurationError(`${where} list is empty`);\n }\n return [first, ...rest];\n}\n\nfunction listOf(\n declared: Batchers | BatcherHistory,\n where: string,\n): readonly (Address | BatcherEntry)[] {\n if (typeof declared === \"string\") {\n return [declared];\n }\n if (isArray(declared)) {\n return declared;\n }\n if (!(\"latest\" in declared)) {\n throw new ConfigurationError(`${where} must be an address or a list`);\n }\n // Without its lastBatchId, a retired batcher would read as live and keep taking joins.\n const unbounded = declared.retired.find((entry) => entry.lastBatchId === undefined);\n if (unbounded !== undefined) {\n throw new ConfigurationError(\n `${where} ${unbounded.address} has an invalid lastBatchId: undefined`,\n );\n }\n return [...declared.retired, declared.latest];\n}\n\n// `Array.isArray` does not narrow a readonly array out of a union.\nfunction isArray(value: unknown): value is readonly (Address | BatcherEntry)[] {\n return Array.isArray(value);\n}\n\nfunction entryOf(batcher: Address | BatcherEntry, where: string): BatcherEntry {\n if (typeof batcher === \"string\") {\n return { address: requireAddress(batcher, where) };\n }\n const address = requireAddress(batcher.address, where);\n const { lastBatchId } = batcher;\n if (lastBatchId === undefined) {\n return { address };\n }\n // A non-bigint can compare false and keep the batcher open past its last batch; a negative one closes it for good.\n if (typeof lastBatchId !== \"bigint\" || lastBatchId < 0n) {\n throw new ConfigurationError(\n `${where} ${address} has an invalid lastBatchId: ${String(lastBatchId)}`,\n );\n }\n return { address, lastBatchId };\n}\n\nfunction requireAddress(value: unknown, where: string): Address {\n if (typeof value !== \"string\" || !isAddress(value, { strict: false })) {\n throw new ConfigurationError(`${where} is not an address: ${String(value)}`);\n }\n return getAddress(value);\n}\n","/**\n * ABI for the deposit and redeem vault batchers, which share one interface.\n * Owner-only writes are omitted; every custom error is kept so reverts decode\n * 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: \"dispatchBatchCallback\",\n inputs: [\n { name: \"batchId\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"unwrapAmountCleartext\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"decryptionProof\", type: \"bytes\", internalType: \"bytes\" },\n ],\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: \"closed\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\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 { vaultBatcherAbi } from \"../abi/vault-batcher.abi\";\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. */\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 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 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 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 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\n/** Returns the contract config to read whether the batcher is past its last batch. Batchers deployed before `closed()` revert. */\nexport function closedContract(batcher: Address) {\n return { address: batcher, abi: vaultBatcherAbi, functionName: \"closed\", args: [] } as const;\n}\n\n/** Returns the contract config to read the unwrap request a dispatched batch is waiting on. */\nexport function unwrapRequestIdContract(batcher: Address, batchId: bigint) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"unwrapRequestId\",\n args: [batchId],\n } as const;\n}\n\n/**\n * Returns the contract config to settle a dispatched batch with the public decryption of its\n * aggregate amount, or to cancel it once its callback deadline has passed. Permissionless.\n */\nexport function dispatchBatchCallbackContract(\n batcher: Address,\n batchId: bigint,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return {\n address: batcher,\n abi: vaultBatcherAbi,\n functionName: \"dispatchBatchCallback\",\n args: [batchId, unwrapAmountCleartext, decryptionProof],\n } as const;\n}\n","/**\n * ABI for the vault batcher router, which fans one submission out across\n * several batchers. Transcribed by hand from `IVaultBatcherConfidentialRouter`\n * in zama-ai/confidential-defi at tag `oz-audit-20261016` (commit `d7cd0c8e`),\n * so `abi:check` does not cover it: compare against that ref when the router\n * changes. `onConfidentialTransferReceived` is omitted because a token calls\n * it, not the SDK; the router's custom errors are kept so its reverts decode\n * to a name.\n */\nexport const vaultRouterAbi = [\n {\n type: \"function\",\n name: \"join\",\n inputs: [\n {\n name: \"legs\",\n type: \"tuple[]\",\n internalType: \"struct IVaultBatcherConfidentialRouter.Allocation[]\",\n components: [\n { name: \"batcher\", type: \"address\", internalType: \"address\" },\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"bytes32\", internalType: \"externalEuint64\" },\n ],\n },\n { name: \"inputProof\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"tokenWrapperRegistry\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ITokenWrapperRegistry\" }],\n stateMutability: \"view\",\n },\n { type: \"error\", name: \"InvalidTokenWrapperRegistry\", inputs: [] },\n { type: \"error\", name: \"MissingInputProof\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n { type: \"error\", name: \"ZamaProtocolUnsupported\", inputs: [] },\n {\n type: \"error\",\n name: \"UnlistedConfidentialToken\",\n inputs: [{ name: \"token\", type: \"address\", internalType: \"address\" }],\n },\n] as const;\n","import { encodeAbiParameters, getAbiItem, type Address, type Hex } from \"viem\";\nimport type { EncryptedValue } from \"../../relayer/types\";\nimport { vaultRouterAbi } from \"../abi/vault-router.abi\";\n\n/** One vault's share of a fan-out. */\nexport interface EncryptedAllocationLeg {\n readonly batcher: Address;\n /** The confidential token this leg spends. */\n readonly token: Address;\n /** Encrypted with the router as the verifying contract. */\n readonly amount: EncryptedValue;\n}\n\n/** Returns the contract config to pull every leg from the caller and join each named batcher. */\nexport function routerJoinContract(\n router: Address,\n legs: readonly EncryptedAllocationLeg[],\n inputProof: Hex,\n) {\n return {\n address: router,\n abi: vaultRouterAbi,\n functionName: \"join\",\n args: [legs, inputProof],\n } as const;\n}\n\n// The push path decodes `data` into `join`'s parameters, so take them from the ABI.\nconst ALLOCATION_PARAMETERS = getAbiItem({ abi: vaultRouterAbi, name: \"join\" }).inputs;\n\n/** The payload that lets one confidential transfer of the shared asset fund every leg. */\nexport function encodeAllocationData(\n legs: readonly EncryptedAllocationLeg[],\n inputProof: Hex,\n): Hex {\n return encodeAbiParameters(ALLOCATION_PARAMETERS, [legs.map((leg) => ({ ...leg })), inputProof]);\n}\n","import { zeroHash, type Address } from \"viem\";\nimport { ConfigurationError, VaultBatcherReadFailedError } from \"../errors\";\nimport type { GenericProvider } from \"../types\";\nimport { isContractCallError } from \"../utils/error\";\nimport { batchersOf, type BatcherEntry, type Vault } from \"./config\";\nimport {\n batchCreatedAtContract,\n batchMinBatchAgeContract,\n batchStateContract,\n closedContract,\n currentBatchIdContract,\n pausedContract,\n unwrapRequestIdContract,\n} from \"./contracts\";\nimport type { BatchState, JoinDirection } from \"./types\";\n\n/** A join sent this close to its batch's due time can land after the dispatch and wait a whole cycle. */\nexport const JOIN_MARGIN_SECONDS = 60n;\n\n// The batcher's `BatchState` enum, in on-chain order.\nconst BATCH_STATES: readonly BatchState[] = [\"pending\", \"dispatched\", \"finalized\", \"canceled\"];\n\n/** What one batcher offers a join. */\nexport type BatcherOffer =\n | {\n readonly status: \"open\";\n readonly batcher: Address;\n readonly batchId: bigint;\n readonly dispatchableAt: bigint;\n /** The previous batch is still in flight, so this batch waits for it to settle before it is dispatched. */\n readonly blocked: boolean;\n }\n | {\n readonly status: \"paused\";\n readonly batcher: Address;\n readonly batchId: bigint;\n readonly dispatchableAt: bigint;\n }\n /** Closed on chain, or past its configured `lastBatchId`: it never takes a join again. */\n | { readonly status: \"closed\"; readonly batcher: Address };\n\nexport type OpenOffer = Extract<BatcherOffer, { status: \"open\" }>;\nexport type PausedOffer = Extract<BatcherOffer, { status: \"paused\" }>;\n\nfunction soonest(offers: readonly OpenOffer[]): OpenOffer | undefined {\n return [...offers].sort((a, b) => {\n if (a.dispatchableAt !== b.dispatchableAt) {\n return a.dispatchableAt < b.dispatchableAt ? -1 : 1;\n }\n // Same order on every client, so a tie does not split the joins.\n const [left, right] = [a.batcher.toLowerCase(), b.batcher.toLowerCase()];\n return left < right ? -1 : left > right ? 1 : 0;\n })[0];\n}\n\n/**\n * The batch a join reaches, or a paused batcher's batch when none is open; `undefined` when every batcher is closed.\n *\n * @internal\n */\nexport function pickNextBatch(\n offers: readonly BatcherOffer[],\n now: bigint,\n): OpenOffer | PausedOffer | undefined {\n const open = offers.filter((offer): offer is OpenOffer => offer.status === \"open\");\n return (\n soonest(open.filter((o) => !o.blocked && o.dispatchableAt >= now + JOIN_MARGIN_SECONDS)) ??\n soonest(open.filter((o) => o.blocked)) ??\n soonest(open) ??\n offers.find((offer): offer is PausedOffer => offer.status === \"paused\")\n );\n}\n\n/**\n * The batch a join into each vault reaches, in vault order, and the chain time it was picked at.\n * A vault whose batchers are all closed reads as closed, naming its first batcher.\n *\n * @internal\n * @throws if a vault lists no batcher, or an address or `lastBatchId` is invalid. {@link ConfigurationError}\n * @throws if a batcher cannot be read. {@link VaultBatcherReadFailedError}\n */\nexport async function readNextBatches(\n provider: GenericProvider,\n chainId: number,\n vaults: readonly Vault[],\n direction: JoinDirection,\n): Promise<{\n readonly now: bigint;\n readonly next: readonly { readonly vault: Vault; readonly offer: BatcherOffer }[];\n}> {\n const [now, read] = await Promise.all([\n provider.getBlockTimestamp(chainId),\n Promise.all(\n vaults.map(async (vault) => {\n const entries = batchersOf(vault, direction);\n const offers = await Promise.all(\n entries.map((entry) => offerOf(provider, chainId, vault.id, entry)),\n );\n return { vault, entries, offers };\n }),\n ),\n ]);\n const next = read.map(({ vault, entries, offers }) => ({\n vault,\n offer: pickNextBatch(offers, now) ?? { status: \"closed\" as const, batcher: entries[0].address },\n }));\n return { now, next };\n}\n\n/**\n * The state of one batch.\n *\n * @internal\n * @throws if the batcher returns a state outside its enum. {@link ConfigurationError}\n */\nexport async function readBatchState(\n provider: GenericProvider,\n chainId: number,\n batcher: Address,\n batchId: bigint,\n): Promise<BatchState> {\n const index = await provider.readContract({ ...batchStateContract(batcher, batchId), chainId });\n const state = BATCH_STATES[index];\n if (state === undefined) {\n throw new ConfigurationError(\n `Batcher ${batcher} returned unknown batch state ${index} for batch ${batchId}; is it a vault batcher?`,\n );\n }\n return state;\n}\n\n/**\n * Whether the batch before `batchId` is still in flight, so `batchId` should not be dispatched yet.\n *\n * @internal\n */\nexport async function waitsOnPrevious(\n provider: GenericProvider,\n chainId: number,\n batcher: Address,\n batchId: bigint,\n): Promise<boolean> {\n if (batchId <= 1n) {\n return false;\n }\n const previous = batchId - 1n;\n // As `dispatchBatch` does: a batcher whose ids start past 1 has no batch before its first, and\n // `batchState` reverts on one, while its unwrap request reads zero.\n const unwrapRequestId = await provider.readContract({\n ...unwrapRequestIdContract(batcher, previous),\n chainId,\n });\n return (\n unwrapRequestId !== zeroHash &&\n (await readBatchState(provider, chainId, batcher, previous)) === \"dispatched\"\n );\n}\n\nasync function offerOf(\n provider: GenericProvider,\n chainId: number,\n vaultId: string,\n entry: BatcherEntry,\n): Promise<BatcherOffer> {\n const details = { batcher: entry.address, vaultId };\n const where = `vault \"${vaultId}\"`;\n try {\n // A stale read is most likely one block behind, so one more read settles it.\n const offer =\n (await readOffer(provider, chainId, entry)) ?? (await readOffer(provider, chainId, entry));\n if (offer !== undefined) {\n return offer;\n }\n } catch (cause) {\n // A provider on another chain, or a batcher that is not one, is a setup problem, not a read failure.\n if (cause instanceof ConfigurationError) {\n throw cause;\n }\n throw new VaultBatcherReadFailedError(\n `Could not read batcher ${entry.address} of ${where}`,\n details,\n { cause },\n );\n }\n throw new VaultBatcherReadFailedError(\n `Batcher ${entry.address} of ${where} has no open batch but is not closed; the RPC returned reads from different blocks`,\n details,\n { retryable: true },\n );\n}\n\n// `undefined` when the reads disagree: a current batch with no creation time on a batcher that is not closed.\nasync function readOffer(\n provider: GenericProvider,\n chainId: number,\n { address: batcher, lastBatchId }: BatcherEntry,\n): Promise<BatcherOffer | undefined> {\n const [paused, batchId] = await Promise.all([\n provider.readContract({ ...pausedContract(batcher), chainId }),\n provider.readContract({ ...currentBatchIdContract(batcher), chainId }),\n ]);\n if (lastBatchId !== undefined && batchId > lastBatchId) {\n return { status: \"closed\", batcher };\n }\n const [createdAt, minAge, blocked] = await Promise.all([\n provider.readContract({ ...batchCreatedAtContract(batcher, batchId), chainId }),\n provider.readContract({ ...batchMinBatchAgeContract(batcher, batchId), chainId }),\n paused ? false : waitsOnPrevious(provider, chainId, batcher, batchId),\n ]);\n // A closed batcher never opens its next batch. Otherwise, a node behind the one that\n // returned `batchId` has not seen the batch open yet.\n if (createdAt === 0n) {\n return (await isClosed(provider, chainId, batcher)) ? { status: \"closed\", batcher } : undefined;\n }\n const dispatchableAt = createdAt + minAge;\n return paused\n ? { status: \"paused\", batcher, batchId, dispatchableAt }\n : { status: \"open\", batcher, batchId, dispatchableAt, blocked };\n}\n\n// A batcher deployed before `closed()` reverts on it, and it never closes on chain either.\nasync function isClosed(\n provider: GenericProvider,\n chainId: number,\n batcher: Address,\n): Promise<boolean> {\n try {\n return await provider.readContract({ ...closedContract(batcher), chainId });\n } catch (error) {\n if (isContractCallError(error)) {\n return false;\n }\n throw error;\n }\n}\n","import { getAddress, type Address } from \"viem\";\nimport { eventTopic, topicToAddress } from \"../events/log-decoding\";\nimport type { RawLog } from \"../types/transaction\";\n\nconst JOINED = eventTopic(\"Joined(uint256,address,bytes32)\");\n\n/**\n * The batch id of the first `Joined` log of `batcher` for `account`, or `null` if there is none.\n * Removes that log from `logs`. A log with no emitter address matches any `batcher`.\n */\nexport function takeJoinedBatchId(\n logs: RawLog[],\n batcher: Address,\n account: Address,\n): bigint | null {\n for (const [index, log] of logs.entries()) {\n const [topic, batchId, accountTopic] = log.topics;\n if (\n topic !== JOINED ||\n batchId === undefined ||\n accountTopic === undefined ||\n // Some adapters omit the emitter address.\n (log.address !== undefined && getAddress(log.address) !== batcher) ||\n topicToAddress(accountTopic) !== account\n ) {\n continue;\n }\n logs.splice(index, 1);\n return BigInt(batchId);\n }\n return null;\n}\n","import { encodeFunctionData, getAddress, type Address, type Hex } from \"viem\";\nimport {\n confidentialTransferAndCallContract,\n isOperatorContract,\n setOperatorContract,\n unwrapAmountContract,\n} from \"../contracts\";\nimport {\n BalanceCheckUnavailableError,\n ChainMismatchError,\n ConfigurationError,\n EncryptionFailedError,\n SignerNotConfiguredError,\n VaultBatcherPausedError,\n VaultBatchNotDispatchedError,\n VaultJoinUnconfirmedError,\n} from \"../errors\";\nimport type { TransactionOperation } from \"../events/sdk-events\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport type { TelemetryOperation } from \"../telemetry\";\nimport { Token } from \"../token\";\nimport type {\n ContractAbi,\n GenericSigner,\n ReadContractArgs,\n ReadContractConfig,\n ReadFunctionName,\n TransactionResult,\n WriteContractConfig,\n} from \"../types\";\nimport { decryptPublicUint } from \"../relayer/public-decrypt\";\nimport { requireWriteChain } from \"../utils/alignment\";\nimport { assertConfidentialBalance } from \"../utils/assert-balance\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport { submitTransaction } from \"../utils/submit-transaction\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport { scopeOf, type Vault, type VaultGroup, type VaultIdOf } from \"./config\";\nimport { readBatchState, readNextBatches, waitsOnPrevious } from \"./next-batch\";\nimport {\n batchCallbackDeadlineContract,\n batchCreatedAtContract,\n batchDispatchedAtContract,\n batchMinBatchAgeContract,\n claimContract,\n depositsContract,\n dispatchBatchCallbackContract,\n dispatchBatchContract,\n encodeAllocationData,\n exchangeRateContract,\n exchangeRateDecimalsContract,\n fromTokenContract,\n pausedContract,\n quitContract,\n routerJoinContract,\n unwrapRequestIdContract,\n} from \"./contracts\";\nimport { takeJoinedBatchId } from \"./joined\";\nimport type {\n Batch,\n BatchAction,\n BatchRef,\n BatcherRef,\n Call,\n JoinCall,\n JoinDirection,\n GroupJoinInput,\n GroupJoinOptions,\n JoinInput,\n JoinOptions,\n JoinOutcome,\n JoinRoute,\n OpenBatch,\n OperatorApprovalCall,\n PreparedFinalize,\n PreparedJoin,\n SendJoinOptions,\n VaultCall,\n VaultLeg,\n} from \"./types\";\n\n// A router pulls a share token only for its holder's join, so a year-long approval is safe.\nconst OPERATOR_APPROVAL_VALIDITY_SECONDS = 365n * 24n * 60n * 60n;\n\nconst ENCRYPT_OPERATION = {\n deposit: \"vault-deposit\",\n redeem: \"vault-redeem\",\n} as const satisfies Record<JoinDirection, TelemetryOperation>;\n\nconst JOIN_OPERATION = {\n direct: \"vault:join\",\n router: \"vault:routerJoin\",\n} as const satisfies Record<JoinRoute, TransactionOperation>;\n\n// Arrays built in leg order line up with the legs, so a gap is an SDK bug, not a user error.\nfunction at<T>(values: readonly T[], index: number): T {\n const value = values[index];\n assertNonNullable(value, `vault leg ${index}`);\n return value;\n}\n\nfunction toCall(config: WriteContractConfig): Call {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi,\n functionName: config.functionName,\n args: config.args,\n } as Parameters<typeof encodeFunctionData>[0]),\n value: 0n,\n };\n}\n\n/** A join as the client plans it: a vault on its own has no `vaultId`. */\ntype AnyJoinInput = JoinInput & { readonly vaultId?: string };\n\nfunction memberOf(group: VaultGroup, vaultId: string | undefined): Vault {\n const vault = group.vaults.find((candidate) => candidate.id === vaultId);\n if (vault === undefined) {\n throw new ConfigurationError(`Vault group \"${group.id}\" has no vault \"${vaultId}\"`);\n }\n return vault;\n}\n\n/** Why a vault with no open batcher takes no join: a closed batcher never resumes, a paused one can. */\nfunction noOpenBatcher(\n direction: JoinDirection,\n vault: Vault,\n offer: { readonly status: \"paused\" | \"closed\"; readonly batcher: Address },\n group?: VaultGroup,\n): VaultBatcherPausedError {\n const where = group === undefined ? \"\" : ` in group \"${group.id}\"`;\n const why =\n offer.status === \"closed\"\n ? \"is closed, so the vault takes no joins\"\n : \"is paused or closed, so the vault cannot be joined until one resumes\";\n return new VaultBatcherPausedError(\n `Every ${direction} batcher of vault \"${vault.id}\"${where} ${why}`,\n { batcher: offer.batcher, vaultId: vault.id },\n );\n}\n\nfunction nonEmpty<T>(values: readonly T[]): readonly [T, ...T[]] {\n const [first, ...rest] = values;\n assertNonNullable(first, \"vault calls\");\n return [first, ...rest];\n}\n\ninterface Planned<TCall> {\n readonly call: TCall;\n readonly config: WriteContractConfig;\n}\n\n// A failed memoized read is not cached, so the next call tries again.\nfunction memoize<T>(cache: Map<string, Promise<T>>, key: string, read: () => Promise<T>) {\n let pending = cache.get(key);\n if (pending === undefined) {\n pending = read().catch((error: unknown) => {\n cache.delete(key);\n throw error;\n });\n cache.set(key, pending);\n }\n return pending;\n}\n\n/** Reads confidential vault batches, and builds and sends vault transactions. */\nexport class VaultClient {\n readonly #sdk: ZamaSDK;\n\n readonly #reads = new Map<string, Promise<unknown>>();\n\n /** @internal Use {@link createVaultClient}. */\n constructor(sdk: ZamaSDK) {\n this.#sdk = sdk;\n }\n\n /**\n * Build a deposit into a vault on its own: one call to its deposit batcher.\n * Only `input.account` can send it. With `skipBalanceCheck`, check the\n * account's balance before sending.\n *\n * @throws if the provider is not on the vault's chain while a wallet is connected. {@link ChainMismatchError}\n * @throws if the provider is on another chain with no wallet connected, a vault lists no batcher, or a batcher address or `lastBatchId` is invalid. {@link ConfigurationError}\n * @throws if no batcher of the vault is open, even with `skipBalanceCheck`. {@link VaultBatcherPausedError}\n * @throws if a batcher of any vault of the target cannot be read. {@link VaultBatcherReadFailedError}\n * @throws if the balance is less than `amount` and `skipBalanceCheck` is not set. {@link InsufficientConfidentialBalanceError}\n * @throws if `skipBalanceCheck` is not set and no signer is connected, `account` is not the signer's, or the balance cannot be read. {@link BalanceCheckUnavailableError}\n * @throws if encryption returns a different number of values than the join has legs. {@link EncryptionFailedError}\n */\n prepareDeposit(vault: Vault, input: JoinInput, options?: JoinOptions): Promise<PreparedJoin>;\n /**\n * Build a deposit into one vault of a group, with a leg for every vault\n * that takes joins. A vault whose batchers are all paused or closed gets no\n * leg; when it is the chosen vault, this throws {@link VaultBatcherPausedError}.\n * With `route: \"direct\"`, send the calls as one atomic bundle, and with\n * `skipBalanceCheck`, decrypt every leg's token together: doing either for\n * only some legs shows which vault was chosen.\n *\n * @throws as the single-vault overload.\n * @throws also if the vault is not in the group, the group has more than `MAX_GROUP_VAULTS` vaults, mixes chains or names a vault twice, the deposit batchers take different assets, or, on the router route, the chain has no router. {@link ConfigurationError}\n */\n prepareDeposit<TGroup extends VaultGroup>(\n group: TGroup,\n input: GroupJoinInput<VaultIdOf<TGroup>>,\n options?: GroupJoinOptions,\n ): Promise<PreparedJoin>;\n async prepareDeposit(\n target: Vault | VaultGroup,\n input: AnyJoinInput,\n options?: GroupJoinOptions,\n ): Promise<PreparedJoin> {\n return (await this.#planJoin(\"deposit\", target, input, options)).prepared;\n }\n\n /**\n * Build a redemption of a vault's shares on its own: one call to its redeem\n * batcher. Only `input.account` can send it. With `skipBalanceCheck`, check\n * the account's share balance before sending.\n *\n * @throws as {@link prepareDeposit}.\n */\n prepareRedeem(vault: Vault, input: JoinInput, options?: JoinOptions): Promise<PreparedJoin>;\n /**\n * Build a redemption of the shares of one vault of a group, with a leg for\n * every vault that takes joins, as {@link prepareDeposit}. On the router\n * route, `calls` starts with a year-long operator approval on each share\n * token the account has not approved. With `route: \"direct\"`, send the calls\n * as one atomic bundle, and with `skipBalanceCheck`, decrypt every leg's\n * token together: doing either for only some legs shows which vault was chosen.\n *\n * @throws as {@link prepareDeposit} for a group, except that the batchers may take different tokens.\n */\n prepareRedeem<TGroup extends VaultGroup>(\n group: TGroup,\n input: GroupJoinInput<VaultIdOf<TGroup>>,\n options?: GroupJoinOptions,\n ): Promise<PreparedJoin>;\n async prepareRedeem(\n target: Vault | VaultGroup,\n input: AnyJoinInput,\n options?: GroupJoinOptions,\n ): Promise<PreparedJoin> {\n return (await this.#planJoin(\"redeem\", target, input, options)).prepared;\n }\n\n /**\n * Claim a finalized batch's output for `account`. Anyone may send it; the output always\n * goes to `account`. The output is the account's deposit times the batch's exchange rate,\n * rounded down; the deposit then reads as an encrypted zero.\n */\n prepareClaim(batch: BatchRef, account: Address): Call {\n return toCall(claimContract(getAddress(batch.batcher), batch.batchId, getAddress(account)));\n }\n\n /**\n * Take the sender's deposit back from a pending batch, or from a canceled\n * one. Only the depositor may send it, and it leaves the deposit as an\n * encrypted zero. After a group join, quit every leg of it: quitting only the\n * chosen one shows which vault was chosen.\n */\n prepareQuit(batch: BatchRef): Call {\n return toCall(quitContract(getAddress(batch.batcher), batch.batchId));\n }\n\n /** Close the batcher's open batch and start its decryption. Permissionless; reverts while too young or paused. */\n prepareDispatch(batch: BatcherRef): Call {\n return toCall(dispatchBatchContract(getAddress(batch.batcher)));\n }\n\n /**\n * Build the settlement of a dispatched batch with its publicly decrypted\n * amount. Permissionless. Past the batch's callback deadline the same call\n * cancels it instead.\n *\n * @throws if the batch is not dispatched. {@link VaultBatchNotDispatchedError}\n * @throws if the provider is not on the batch's chain while a wallet is connected. {@link ChainMismatchError}\n * @throws if the provider is not on the batch's chain with no wallet connected, or the batcher reports an unknown batch state. {@link ConfigurationError}\n * @throws if public decryption of the batch's unwrap amount fails. {@link DecryptionFailedError}\n */\n async prepareFinalize(batch: BatchRef): Promise<PreparedFinalize> {\n return (await this.#planFinalize(batch)).call;\n }\n\n async #planFinalize(batch: BatchRef): Promise<Planned<PreparedFinalize>> {\n const batcher = getAddress(batch.batcher);\n const [state, requestId, wrapper] = await Promise.all([\n readBatchState(this.#sdk.provider, batch.chainId, batcher, batch.batchId),\n this.#read(batch.chainId, unwrapRequestIdContract(batcher, batch.batchId)),\n this.#fromToken(batch.chainId, batcher),\n ]);\n // Outside `dispatched` the request is unset or spent, so the decryption would fail opaquely.\n if (state !== \"dispatched\") {\n throw new VaultBatchNotDispatchedError(\n `Batch ${batch.batchId} of batcher ${batcher} is ${state}, but only a dispatched batch can be finalized`,\n { batcher, batchId: batch.batchId, state },\n );\n }\n const handle = await this.#read(batch.chainId, unwrapAmountContract(wrapper, requestId));\n await this.#requireProviderChain(batch.chainId, \"vault finalize\");\n const { value, decryptionProof } = await decryptPublicUint(this.#sdk.relayer, handle, {\n operation: \"vault-finalize\",\n });\n const config = dispatchBatchCallbackContract(batcher, batch.batchId, value, decryptionProof);\n return {\n config,\n call: {\n chainId: batch.chainId,\n batcher,\n batchId: batch.batchId,\n unwrapAmountCleartext: value,\n decryptionProof,\n call: toCall(config),\n },\n };\n }\n\n /**\n * Deposit into a vault on its own with the SDK's signer, for the signer's\n * account.\n *\n * @throws as {@link prepareDeposit}.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the vault's chain. {@link ChainMismatchError}\n * @throws if a transaction fails or reverts. {@link TransactionRevertedError}\n * @throws if the join was mined but its receipt does not confirm every leg; the join most likely\n * went through. {@link VaultJoinUnconfirmedError}\n */\n deposit(\n vault: Vault,\n input: Omit<JoinInput, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome>;\n /**\n * Deposit into one vault of a group with the SDK's signer, with a leg for\n * every vault that takes joins, as {@link prepareDeposit}.\n *\n * @throws as the single-vault overload, and as {@link prepareDeposit} for a group.\n */\n deposit<TGroup extends VaultGroup>(\n group: TGroup,\n input: Omit<GroupJoinInput<VaultIdOf<TGroup>>, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome>;\n async deposit(\n target: Vault | VaultGroup,\n input: Omit<AnyJoinInput, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome> {\n return this.#join(\"deposit\", target, input, options);\n }\n\n /**\n * Redeem a vault's shares on its own with the SDK's signer.\n *\n * @throws as {@link deposit}.\n */\n redeem(\n vault: Vault,\n input: Omit<JoinInput, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome>;\n /**\n * Redeem the shares of one vault of a group with the SDK's signer. It first\n * asks the wallet for each operator approval of the router the account lacks.\n *\n * @throws as {@link deposit} for a group, except that the batchers may take different tokens.\n */\n redeem<TGroup extends VaultGroup>(\n group: TGroup,\n input: Omit<GroupJoinInput<VaultIdOf<TGroup>>, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome>;\n async redeem(\n target: Vault | VaultGroup,\n input: Omit<AnyJoinInput, \"account\">,\n options?: SendJoinOptions,\n ): Promise<JoinOutcome> {\n return this.#join(\"redeem\", target, input, options);\n }\n\n /**\n * Claim a finalized batch with the SDK's signer, for `account` (default: the signer).\n * The output is the account's deposit times the batch's exchange rate, rounded down;\n * the deposit then reads as an encrypted zero.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the batch's chain. {@link ChainMismatchError}\n * @throws if the transaction fails or reverts. {@link TransactionRevertedError}\n */\n async claim(batch: BatchRef, account?: Address): Promise<TransactionResult> {\n const signer = await this.#writeAccount(batch.chainId, \"claim\");\n const call = claimContract(\n getAddress(batch.batcher),\n batch.batchId,\n getAddress(account ?? signer),\n );\n return this.#send(call, \"vault:claim\");\n }\n\n /**\n * Quit a pending or canceled batch with the SDK's signer, which must be the depositor.\n * It leaves the deposit as an encrypted zero. After a group join, quit every leg of it:\n * quitting only the chosen one shows which vault was chosen.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the batch's chain. {@link ChainMismatchError}\n * @throws if the transaction fails or reverts. {@link TransactionRevertedError}\n */\n async quit(batch: BatchRef): Promise<TransactionResult> {\n await this.#writeAccount(batch.chainId, \"quit\");\n return this.#send(quitContract(getAddress(batch.batcher), batch.batchId), \"vault:quit\");\n }\n\n /**\n * Dispatch the batcher's open batch with the SDK's signer.\n *\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the batcher's chain. {@link ChainMismatchError}\n * @throws if the transaction fails or reverts. {@link TransactionRevertedError}\n */\n async dispatch(batch: BatcherRef): Promise<TransactionResult> {\n await this.#writeAccount(batch.chainId, \"dispatch\");\n return this.#send(dispatchBatchContract(getAddress(batch.batcher)), \"vault:dispatchBatch\");\n }\n\n /**\n * Finalize a dispatched batch with the SDK's signer.\n *\n * @throws as {@link prepareFinalize}.\n * @throws if no signer is configured. {@link SignerNotConfiguredError}\n * @throws if the wallet is not on the provider's chain or on the batch's chain. {@link ChainMismatchError}\n * @throws if the transaction fails or reverts. {@link TransactionRevertedError}\n */\n async finalize(batch: BatchRef): Promise<TransactionResult> {\n // Before the public decryption, so a wrong chain fails before the relayer round trip.\n await this.#writeAccount(batch.chainId, \"finalize\");\n return this.#send((await this.#planFinalize(batch)).config, \"vault:finalize\");\n }\n\n /**\n * One batch's state and timings, and what can be sent for it now. Pass\n * `account` to read its encrypted deposit and to list `claim` and `quit`.\n */\n async readBatch(batch: BatchRef, account?: Address): Promise<Batch> {\n const { chainId, batchId } = batch;\n const batcher = getAddress(batch.batcher);\n const depositor = account === undefined ? undefined : getAddress(account);\n const [\n state,\n createdAt,\n minAge,\n dispatchedAt,\n deadline,\n paused,\n rate,\n decimals,\n deposit,\n now,\n blocked,\n ] = await Promise.all([\n readBatchState(this.#sdk.provider, chainId, batcher, batchId),\n this.#read(chainId, batchCreatedAtContract(batcher, batchId)),\n this.#read(chainId, batchMinBatchAgeContract(batcher, batchId)),\n this.#read(chainId, batchDispatchedAtContract(batcher, batchId)),\n this.#read(chainId, batchCallbackDeadlineContract(batcher, batchId)),\n this.#read(chainId, pausedContract(batcher)),\n this.#read(chainId, exchangeRateContract(batcher, batchId)),\n this.#memo(`decimals:${chainId}:${batcher}`, () =>\n this.#read(chainId, exchangeRateDecimalsContract(batcher)),\n ),\n depositor === undefined\n ? null\n : this.#read(chainId, depositsContract(batcher, batchId, depositor)),\n this.#sdk.provider.getBlockTimestamp(chainId),\n waitsOnPrevious(this.#sdk.provider, chainId, batcher, batchId),\n ]);\n const dispatchableAt = createdAt + minAge;\n const cancelsAt = dispatchedAt + deadline;\n // A literal zero handle means the account never joined this batch.\n const member = deposit !== null && !isEncryptedValueZero(deposit);\n const actions = (\n [\n [\"claim\", member && state === \"finalized\"],\n [\"quit\", member && (state === \"pending\" || state === \"canceled\")],\n [\"dispatch\", state === \"pending\" && !paused && !blocked && dispatchableAt <= now],\n [\"finalize\", state === \"dispatched\"],\n ] as const\n ).flatMap(([action, allowed]): BatchAction[] => (allowed ? [action] : []));\n const edge = state === \"pending\" ? dispatchableAt : state === \"dispatched\" ? cancelsAt : null;\n const base = {\n chainId,\n batcher,\n batchId,\n createdAt,\n dispatchableAt,\n paused,\n deposit,\n actions,\n observedAt: now,\n nextChangeAt: edge !== null && edge > now ? edge : null,\n };\n switch (state) {\n case \"pending\":\n return { ...base, state };\n case \"finalized\":\n return { ...base, state, dispatchedAt, cancelsAt, exchangeRate: { rate, decimals } };\n default:\n return { ...base, state, dispatchedAt, cancelsAt };\n }\n }\n\n /**\n * The batch a join reaches now, for a vault or each vault of a group, with\n * when it can be dispatched. When no batcher of a vault is open, it is a\n * paused batcher's batch with `paused: true`. A group member whose batchers\n * are all closed is left out, since it never takes a join again.\n *\n * @throws if a vault lists no batcher, or an address or `lastBatchId` is invalid. {@link ConfigurationError}\n * @throws if every batcher of a vault on its own, or of every vault of a group, is closed. {@link VaultBatcherPausedError}\n * @throws if a batcher cannot be read. {@link VaultBatcherReadFailedError}\n */\n async readOpenBatches(\n target: Vault | VaultGroup,\n direction: JoinDirection,\n ): Promise<readonly OpenBatch[]> {\n const { group, vaults, chainId } = scopeOf(target);\n const { now, next } = await readNextBatches(this.#sdk.provider, chainId, vaults, direction);\n const batches = next.flatMap(({ vault, offer }): OpenBatch[] => {\n if (offer.status === \"closed\") {\n if (group !== undefined) {\n return [];\n }\n throw noOpenBatcher(direction, vault, offer);\n }\n const { status, batcher, batchId, dispatchableAt } = offer;\n return [\n {\n vaultId: vault.id,\n chainId,\n batcher,\n batchId,\n dispatchableAt,\n paused: status === \"paused\",\n observedAt: now,\n },\n ];\n });\n if (group !== undefined && batches.length === 0) {\n const { vault, offer } = at(next, 0);\n throw new VaultBatcherPausedError(\n `Every ${direction} batcher of every vault in group \"${group.id}\" is closed, so the group takes no joins`,\n { batcher: offer.batcher, vaultId: vault.id },\n );\n }\n return batches;\n }\n\n async #planJoin(\n direction: JoinDirection,\n joinTarget: Vault | VaultGroup,\n input: AnyJoinInput,\n options: GroupJoinOptions | undefined,\n ): Promise<{ readonly prepared: PreparedJoin; readonly planned: readonly Planned<VaultCall>[] }> {\n const { group, vaults, chainId } = scopeOf(joinTarget);\n const chosen = group === undefined ? vaults[0] : memberOf(group, input.vaultId);\n const account = getAddress(input.account);\n const route: JoinRoute = group === undefined ? \"direct\" : (options?.route ?? \"router\");\n\n // Encryption runs on the provider's chain, so check it before anything prompts.\n await this.#requireProviderChain(chainId, `vault ${direction}`);\n const router = group !== undefined && route === \"router\" ? this.#router(group) : undefined;\n // A paused batcher reverts the whole join, so a member with no open batch gets no leg;\n // that reveals nothing, since it takes joins from no one.\n const { next } = await readNextBatches(this.#sdk.provider, chainId, vaults, direction);\n const mine = next.find(({ vault }) => vault === chosen);\n assertNonNullable(mine, `vault ${chosen.id}`);\n if (mine.offer.status !== \"open\") {\n throw noOpenBatcher(direction, chosen, mine.offer, group);\n }\n const legs = nonEmpty(\n await Promise.all(\n next.flatMap(({ vault, offer }) =>\n offer.status === \"open\"\n ? [\n this.#fromToken(chainId, offer.batcher).then((token): VaultLeg => ({\n vaultId: vault.id,\n batcher: offer.batcher,\n token,\n amount: vault === chosen ? input.amount : 0n,\n })),\n ]\n : [],\n ),\n ),\n );\n const target = legs.find((leg) => leg.vaultId === chosen.id);\n assertNonNullable(target, `vault leg ${chosen.id}`);\n // A group deposits one asset: the router transfers it once and splits it into the legs.\n const stray = legs.find((leg) => direction === \"deposit\" && leg.token !== target.token);\n if (stray !== undefined) {\n throw new ConfigurationError(\n `Vault group \"${joinTarget.id}\" mixes deposit assets: vault \"${stray.vaultId}\" takes ${stray.token}, vault \"${target.vaultId}\" takes ${target.token}`,\n );\n }\n if (options?.skipBalanceCheck !== true) {\n await this.#assertBalance(direction, legs, target, account);\n }\n\n const operation = ENCRYPT_OPERATION[direction];\n const join = (config: WriteContractConfig, leg: VaultLeg): Planned<JoinCall> => ({\n config,\n call: { ...toCall(config), kind: \"join\", leg },\n });\n let joins: Planned<JoinCall>[];\n let operatorApprovals: Planned<OperatorApprovalCall>[] = [];\n if (router !== undefined) {\n const amounts = legs.map((leg) => leg.amount);\n const allocationOf = (handles: readonly EncryptedValue[]) =>\n legs.map((leg, index) => ({\n batcher: leg.batcher,\n token: leg.token,\n amount: at(handles, index),\n }));\n if (direction === \"redeem\") {\n // The router verifies the allocation, so its proof is bound to the router.\n const [[handles, routerProof], missing] = await Promise.all([\n this.#encrypt(router, account, amounts, operation),\n this.#missingOperatorApprovals(chainId, legs, account, router),\n ]);\n operatorApprovals = missing;\n joins = [join(routerJoinContract(router, allocationOf(handles), routerProof), target)];\n } else {\n // One proof per verifying contract: the router checks the allocation, the asset the total.\n const asset = target.token;\n const [[handles, routerProof], [[total], assetProof]] = await Promise.all([\n this.#encrypt(router, account, amounts, operation),\n this.#encrypt(asset, account, [input.amount], operation),\n ]);\n const data = encodeAllocationData(allocationOf(handles), routerProof);\n joins = [\n join(confidentialTransferAndCallContract(asset, router, total, assetProof, data), target),\n ];\n }\n } else {\n const encrypted = await this.#encryptPerToken(legs, account, operation);\n joins = legs.map((leg, index) => {\n const { handle, inputProof } = at(encrypted, index);\n return join(\n confidentialTransferAndCallContract(leg.token, leg.batcher, handle, inputProof, \"0x\"),\n leg,\n );\n });\n }\n\n // Operator approvals first: the router pulls under them.\n const planned: Planned<VaultCall>[] = [...operatorApprovals, ...joins];\n return {\n prepared: {\n direction,\n chainId,\n groupId: group?.id,\n vaultId: chosen.id,\n account,\n amount: input.amount,\n route,\n legs,\n calls: nonEmpty(planned.map(({ call }) => call)),\n },\n planned,\n };\n }\n\n async #join(\n direction: JoinDirection,\n target: Vault | VaultGroup,\n input: Omit<AnyJoinInput, \"account\">,\n options: SendJoinOptions | undefined,\n ): Promise<JoinOutcome> {\n const signer = this.#signer(direction);\n const { chainId } = scopeOf(target);\n const account = await this.#writeAccount(chainId, direction);\n const { prepared, planned } = await this.#planJoin(\n direction,\n target,\n { ...input, account },\n { skipBalanceCheck: options?.skipBalanceCheck },\n );\n const txHashes: Hex[] = [];\n let last: TransactionResult | undefined;\n for (const [index, { call, config }] of planned.entries()) {\n last = await submitTransaction({\n operation:\n call.kind === \"operatorApproval\" ? \"setOperator\" : JOIN_OPERATION[prepared.route],\n signer,\n provider: this.#sdk.provider,\n config,\n onSubmitted: index === planned.length - 1 ? options?.onJoinSubmitted : undefined,\n emit: (event) => this.#sdk.emitEvent(event, call.to),\n logger: this.#sdk.logger,\n });\n txHashes.push(last.txHash);\n }\n assertNonNullable(last, `vault ${direction}: last transaction`);\n // The join is the last call, so only its receipt holds the Joined logs.\n const logs = [...last.receipt.logs];\n const batches: (BatchRef & { vaultId: string })[] = [];\n const unconfirmed: string[] = [];\n for (const leg of prepared.legs) {\n const batchId = takeJoinedBatchId(logs, leg.batcher, account);\n if (batchId === null) {\n unconfirmed.push(leg.vaultId);\n } else {\n batches.push({ vaultId: leg.vaultId, chainId, batcher: leg.batcher, batchId });\n }\n }\n if (unconfirmed.length > 0) {\n throw new VaultJoinUnconfirmedError(\n `Transaction ${last.txHash} was mined, but its receipt has no Joined event for ${account} from the batcher of ${unconfirmed.map((id) => `vault \"${id}\"`).join(\", \")}${\"vaults\" in target ? ` in group \"${target.id}\"` : \"\"}`,\n { txHash: last.txHash, receipt: last.receipt, unconfirmedVaultIds: unconfirmed },\n );\n }\n return { batches, txHashes };\n }\n\n #router(group: VaultGroup): Address {\n const { chainId } = scopeOf(group);\n const router = this.#sdk.chains.find((chain) => chain.id === chainId)?.vaultRouterAddress;\n if (router === undefined) {\n throw new ConfigurationError(\n `Vault group \"${group.id}\" has ${group.vaults.length} vaults, but chain ${chainId} has no router; set vaultRouterAddress on the chain`,\n );\n }\n return getAddress(router);\n }\n\n // Fixed at deployment, so read once.\n #fromToken(chainId: number, batcher: Address): Promise<Address> {\n return this.#memo(`fromToken:${chainId}:${batcher}`, async () =>\n getAddress(await this.#read(chainId, fromTokenContract(batcher))),\n );\n }\n\n // A short balance joins every batch with nothing and still costs the transaction.\n async #assertBalance(\n direction: JoinDirection,\n legs: readonly VaultLeg[],\n target: VaultLeg,\n account: Address,\n ): Promise<void> {\n // Only the signer can decrypt its own balance; throwing keeps skipping the check explicit.\n const signerAccount = this.#sdk.signer?.walletAccount.getSnapshot()?.address;\n if (signerAccount === undefined || getAddress(signerAccount) !== account) {\n throw new BalanceCheckUnavailableError(\n `Cannot check the balance of ${account} for a vault ${direction}: ${\n signerAccount === undefined ? \"no signer is connected\" : \"the signer is another account\"\n }. Check it yourself, decrypting every leg's token together, and pass skipBalanceCheck: true`,\n );\n }\n await assertConfidentialBalance({\n operation: direction,\n tokenAddress: target.token,\n amount: target.amount,\n account,\n signer: this.#sdk.signer,\n provider: this.#sdk.provider,\n // Every leg's token is decrypted, not only the chosen one's: a lone decrypt would tell the relayer which vault was picked.\n readBalance: async (owner) => {\n const tokens = [...new Set(legs.map((leg) => leg.token))].map(\n (address) => new Token(this.#sdk, address),\n );\n const { results, errors } = await Token.batchBalancesOf(tokens, owner);\n const balance = results.get(target.token);\n if (balance === undefined) {\n throw (\n errors.get(target.token) ??\n new BalanceCheckUnavailableError(`Balance validation failed (token: ${target.token})`)\n );\n }\n return balance;\n },\n });\n }\n\n async #encrypt(\n contractAddress: Address,\n account: Address,\n values: readonly bigint[],\n operation: TelemetryOperation,\n ): Promise<readonly [readonly [EncryptedValue, ...EncryptedValue[]], Hex]> {\n const { encryptedValues, inputProof } = await this.#sdk.encrypt(\n {\n values: values.map((value) => ({ value, type: \"euint64\" as const })),\n contractAddress,\n userAddress: account,\n },\n { operation },\n );\n const [first, ...rest] = encryptedValues;\n if (first === undefined || encryptedValues.length !== values.length) {\n throw new EncryptionFailedError(\n `Encryption returned ${encryptedValues.length} values for ${values.length} legs`,\n );\n }\n return [[first, ...rest], inputProof];\n }\n\n // A transfer's proof is bound to the token it spends: one proof covers the legs that share a token.\n async #encryptPerToken(\n legs: readonly VaultLeg[],\n account: Address,\n operation: TelemetryOperation,\n ): Promise<{ readonly handle: EncryptedValue; readonly inputProof: Hex }[]> {\n const byLeg = new Map<VaultLeg, { handle: EncryptedValue; inputProof: Hex }>();\n await Promise.all(\n [...new Set(legs.map((leg) => leg.token))].map(async (token) => {\n const spending = legs.filter((leg) => leg.token === token);\n const [handles, inputProof] = await this.#encrypt(\n token,\n account,\n spending.map((leg) => leg.amount),\n operation,\n );\n spending.forEach((leg, index) =>\n byLeg.set(leg, { handle: at(handles, index), inputProof }),\n );\n }),\n );\n return legs.map((leg) => {\n const encrypted = byLeg.get(leg);\n assertNonNullable(encrypted, `vault leg ${leg.vaultId}`);\n return encrypted;\n });\n }\n\n async #missingOperatorApprovals(\n chainId: number,\n legs: readonly VaultLeg[],\n account: Address,\n operator: Address,\n ): Promise<Planned<OperatorApprovalCall>[]> {\n const approved = await Promise.all(\n legs.map((leg) => this.#read(chainId, isOperatorContract(leg.token, account, operator))),\n );\n const missing = legs.filter((_leg, index) => !approved[index]);\n if (missing.length === 0) {\n return [];\n }\n // The token compares the deadline against the block's time, not the local clock.\n const until =\n (await this.#sdk.provider.getBlockTimestamp(chainId)) + OPERATOR_APPROVAL_VALIDITY_SECONDS;\n return missing.map((leg) => {\n const config = setOperatorContract(leg.token, operator, Number(until));\n return {\n config,\n call: {\n ...toCall(config),\n kind: \"operatorApproval\",\n vaultId: leg.vaultId,\n operator,\n until,\n },\n };\n });\n }\n\n #signer(operation: string): GenericSigner {\n if (this.#sdk.signer === undefined) {\n throw new SignerNotConfiguredError(operation);\n }\n return this.#sdk.signer;\n }\n\n async #writeAccount(chainId: number, operation: string): Promise<Address> {\n const account = await requireWriteChain(\n `vault ${operation}`,\n this.#signer(operation),\n this.#sdk.provider,\n chainId,\n );\n return getAddress(account.address);\n }\n\n async #send(\n config: WriteContractConfig,\n operation: TransactionOperation,\n ): Promise<TransactionResult> {\n return submitTransaction({\n operation,\n signer: this.#signer(operation),\n provider: this.#sdk.provider,\n config,\n emit: (event) => this.#sdk.emitEvent(event, config.address),\n logger: this.#sdk.logger,\n });\n }\n\n async #requireProviderChain(chainId: number, operation: string): Promise<void> {\n const providerChainId = await this.#sdk.provider.getChainId();\n if (providerChainId === chainId) {\n return;\n }\n // A connected wallet gets the same error as a send, so an app has one \"switch chain\" case.\n const wallet = this.#sdk.signer?.walletAccount.getSnapshot();\n if (wallet !== undefined) {\n throw new ChainMismatchError({\n operation,\n signerChainId: wallet.chainId,\n providerChainId,\n targetChainId: chainId,\n });\n }\n throw new ConfigurationError(\n `Operation \"${operation}\" encrypts or decrypts on chain ${chainId}, but the provider is on chain ${providerChainId}`,\n );\n }\n\n #memo<T>(key: string, read: () => Promise<T>): Promise<T> {\n return memoize(this.#reads as Map<string, Promise<T>>, key, read);\n }\n\n #read<\n const TAbi extends ContractAbi,\n TFunctionName extends ReadFunctionName<TAbi>,\n const TArgs extends ReadContractArgs<TAbi, TFunctionName>,\n >(chainId: number, config: ReadContractConfig<TAbi, TFunctionName, TArgs>) {\n return this.#sdk.provider.readContract({ ...config, chainId });\n }\n}\n\n/**\n * A {@link VaultClient} bound to `sdk`. Reads nothing until first used.\n */\nexport function createVaultClient(sdk: ZamaSDK): VaultClient {\n return new VaultClient(sdk);\n}\n","import { getAddress, type Address } from \"viem\";\n// Keep the TanStack imports type-only, so the vaults barrel runs without TanStack Query.\nimport type { MutationFactoryOptions, QueryFactoryOptions } from \"../../query/factory-types\";\nimport type { QueryClientLike } from \"../../query/invalidation\";\nimport { zamaQueryKeys } from \"../../query/query-keys\";\nimport type { TransactionResult } from \"../../types\";\nimport { assertNonNullable } from \"../../utils/assertions\";\nimport type { VaultClient } from \"../client\";\nimport { chainIdOf, type Vault, type VaultGroup, type VaultIdOf } from \"../config\";\nimport { JOIN_MARGIN_SECONDS } from \"../next-batch\";\nimport type {\n Batch,\n BatchRef,\n BatcherRef,\n JoinDirection,\n JoinOutcome,\n OpenBatch,\n JoinInput,\n SendJoinOptions,\n} from \"../types\";\n\n/** How often a batch waiting for a keeper is read again. */\nconst KEEPER_POLL_MS = 15_000;\n\n// A timer delay above 2^31 - 1 ms overflows and fires at once.\nconst MAX_REFETCH_MS = 60 * 60 * 1000;\n\n/** Query keys for the vaults module. */\nexport const vaultQueryKeys = {\n /** A prefix of every vault key. */\n all: [\"zama.vault\"] as const,\n batch: (batch: BatchRef | undefined, account: Address | undefined) =>\n [\n \"zama.vault\",\n {\n kind: \"batch\",\n chainId: batch?.chainId,\n batcher: batch === undefined ? undefined : getAddress(batch.batcher),\n batchId: batch?.batchId,\n account: account === undefined ? undefined : getAddress(account),\n },\n ] as const,\n openBatches: (target: Vault | VaultGroup, direction: JoinDirection) =>\n [\n \"zama.vault\",\n {\n kind: \"openBatches\",\n chainId: chainIdOf(target),\n // A vault and a group may share an id, and read different batchers.\n scope: \"vaults\" in target ? \"group\" : \"vault\",\n id: target.id,\n direction,\n },\n ] as const,\n};\n\n/** Configuration for {@link batchQueryOptions}. */\nexport interface BatchQueryConfig {\n /** The query is disabled while this is `undefined`. */\n batch?: BatchRef;\n /** Read this account's deposit, and list `claim` and `quit` for it. */\n account?: Address;\n /** Set `enabled` to `false` to keep the query from running. */\n query?: { readonly enabled?: boolean };\n}\n\n// One second past chain time `at`, so the read lands after the change.\nfunction refetchAt(at: bigint, observedAt: bigint): number {\n return Math.min(Number(at - observedAt) * 1000 + 1000, MAX_REFETCH_MS);\n}\n\n/** How long to wait before reading a batch again, or `false` once it is finalized or canceled. */\nfunction batchRefetchInterval(read: Batch | undefined): number | false {\n if (read === undefined || read.state === \"finalized\" || read.state === \"canceled\") {\n return false;\n }\n if (read.nextChangeAt === null) {\n return KEEPER_POLL_MS;\n }\n const untilEdge = refetchAt(read.nextChangeAt, read.observedAt);\n // A dispatched batch waits for a settlement from the start, so it polls before its deadline too.\n return read.state === \"dispatched\" ? Math.min(untilEdge, KEEPER_POLL_MS) : untilEdge;\n}\n\n/**\n * Query options that read one batch with {@link VaultClient.readBatch}. They refetch when the\n * batch's `nextChangeAt` passes, and poll while it waits for a keeper; a `refetchInterval` passed\n * to `useQuery` replaces both.\n */\nexport function batchQueryOptions(\n client: VaultClient,\n config: BatchQueryConfig = {},\n): QueryFactoryOptions<Batch, Error, Batch, ReturnType<typeof vaultQueryKeys.batch>> {\n const { batch, account } = config;\n return {\n refetchInterval: (query) => batchRefetchInterval(query.state.data),\n queryKey: vaultQueryKeys.batch(batch, account),\n queryFn: async () => {\n assertNonNullable(batch, \"batchQueryOptions: batch\");\n return client.readBatch(batch, account);\n },\n enabled: batch !== undefined && config.query?.enabled !== false,\n };\n}\n\n/** Picks a group, or a vault on its own. */\nexport type VaultSelection =\n | { readonly group: VaultGroup; readonly vault?: never }\n | { readonly vault: Vault; readonly group?: never };\n\nfunction selected(selection: VaultSelection): Vault | VaultGroup {\n return selection.vault ?? selection.group;\n}\n\n/** Configuration for {@link openBatchesQueryOptions}. */\nexport type OpenBatchesQueryConfig = VaultSelection & {\n /** Whether the deposit or the redeem batchers are read. */\n direction: JoinDirection;\n};\n\n/**\n * Reads again one second after the soonest batch comes within {@link JOIN_MARGIN_SECONDS} of its\n * due time, when joins may move on, then every {@link KEEPER_POLL_MS} until a keeper dispatches it.\n * `false` while no batch is open.\n */\nfunction openBatchesRefetchInterval(read: readonly OpenBatch[] | undefined): number | false {\n const waits = (read ?? [])\n .filter((batch) => !batch.paused)\n .map((batch) => {\n const movesAt = batch.dispatchableAt - JOIN_MARGIN_SECONDS;\n return movesAt > batch.observedAt ? refetchAt(movesAt, batch.observedAt) : KEEPER_POLL_MS;\n });\n return waits.length === 0 ? false : Math.min(...waits);\n}\n\n/**\n * Query options that read the open batch of each vault of a group that is not closed, or of a vault on its own.\n * They refetch when a batch comes within a minute of its due time, and poll until a keeper\n * dispatches it; a `refetchInterval` passed to `useQuery` replaces both.\n */\nexport function openBatchesQueryOptions(\n client: VaultClient,\n config: OpenBatchesQueryConfig,\n): QueryFactoryOptions<\n readonly OpenBatch[],\n Error,\n readonly OpenBatch[],\n ReturnType<typeof vaultQueryKeys.openBatches>\n> {\n const target = selected(config);\n return {\n refetchInterval: (query) => openBatchesRefetchInterval(query.state.data),\n queryKey: vaultQueryKeys.openBatches(target, config.direction),\n queryFn: async () => client.readOpenBatches(target, config.direction),\n };\n}\n\n/** Invalidates every vault read and every confidential balance. */\nexport function invalidateAfterVaultAction(queryClient: QueryClientLike): void {\n void queryClient.invalidateQueries({ queryKey: vaultQueryKeys.all });\n void queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalance.all });\n void queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalances.all });\n}\n\n/** An amount for a vault of a group, picked by id, or for a vault on its own. */\nexport type JoinVariables<TGroup extends VaultGroup = VaultGroup> = Pick<JoinInput, \"amount\"> &\n SendJoinOptions &\n (\n | { readonly group: TGroup; readonly vaultId: VaultIdOf<TGroup>; readonly vault?: never }\n | { readonly vault: Vault; readonly vaultId?: never; readonly group?: never }\n );\n\nfunction joinMutation(client: VaultClient, direction: JoinDirection) {\n return {\n mutationKey: [`zama.vault.${direction}`] as const,\n mutationFn: async ({ skipBalanceCheck, onJoinSubmitted, amount, ...target }: JoinVariables) => {\n const options = { skipBalanceCheck, onJoinSubmitted };\n return target.vault === undefined\n ? client[direction](target.group, { vaultId: target.vaultId, amount }, options)\n : client[direction](target.vault, { amount }, options);\n },\n };\n}\n\n/** Mutation options over {@link VaultClient.deposit}. */\nexport function depositMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.deposit\"], JoinVariables, JoinOutcome> {\n return joinMutation(client, \"deposit\") as MutationFactoryOptions<\n readonly [\"zama.vault.deposit\"],\n JoinVariables,\n JoinOutcome\n >;\n}\n\n/** Mutation options over {@link VaultClient.redeem}. */\nexport function redeemMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.redeem\"], JoinVariables, JoinOutcome> {\n return joinMutation(client, \"redeem\") as MutationFactoryOptions<\n readonly [\"zama.vault.redeem\"],\n JoinVariables,\n JoinOutcome\n >;\n}\n\n/** Mutation options over {@link VaultClient.claim}. */\nexport function claimMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<\n readonly [\"zama.vault.claim\"],\n BatchRef & { readonly account?: Address },\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.vault.claim\"] as const,\n mutationFn: async ({ account, ...batch }) => client.claim(batch, account),\n };\n}\n\n/** Mutation options over {@link VaultClient.quit}. */\nexport function quitMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.quit\"], BatchRef, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.quit\"] as const,\n mutationFn: async (batch) => client.quit(batch),\n };\n}\n\n/** Mutation options over {@link VaultClient.dispatch}. */\nexport function dispatchMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.dispatch\"], BatcherRef, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.dispatch\"] as const,\n mutationFn: async (batch) => client.dispatch(batch),\n };\n}\n\n/** Mutation options over {@link VaultClient.finalize}. */\nexport function finalizeMutationOptions(\n client: VaultClient,\n): MutationFactoryOptions<readonly [\"zama.vault.finalize\"], BatchRef, TransactionResult> {\n return {\n mutationKey: [\"zama.vault.finalize\"] as const,\n mutationFn: async (batch) => client.finalize(batch),\n };\n}\n"],"mappings":"A,oRAmFA,SAAgByC,EACd,EACiB,CACjB,OAAOC,CACT,CAqBA,SAAgBC,EACd,EACgC,CAChC,OAAOC,CACT,CAOA,SAAgBC,EAAU,EAAoC,CAC5D,MAAO,WAAYC,EAASA,EAAO,OAAO,EAAE,CAAC,QAAUA,EAAO,OAChE,CASA,SAAgBC,EAAQ,EAItB,CACA,GAAI,EAAE,WAAYD,GAChB,MAAO,CAAE,MAAO,IAAA,GAAW,OAAQ,CAACA,CAAM,EAAG,QAASA,EAAO,OAAQ,EAEvE,IAAME,EAAQ,gBAAgBF,EAAO,GAAG,GAClC,CAACG,GAASH,EAAO,OACvB,GAAIA,EAAO,OAAO,OAAA,EAChB,MAAM,IAAI9C,EAAAA,EACR,GAAGgD,EAAM,OAAOF,EAAO,OAAO,OAAO,qBACvC,EAEF,IAAMI,kBAAW,IAAI,IACrB,IAAK,IAAMR,KAASI,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