@zama-fhe/sdk 3.9.0-beta.2 → 3.9.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/log-decoding.cjs +1 -1
- package/dist/cjs/log-decoding.cjs.map +1 -1
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/telemetry.cjs +1 -1
- package/dist/cjs/vaults/index.cjs +1 -1
- package/dist/cjs/vaults/index.cjs.map +1 -1
- package/dist/esm/{alignment-o-YIndFR.js → alignment-CLfJMQqN.js} +2 -2
- package/dist/esm/{alignment-o-YIndFR.js.map → alignment-CLfJMQqN.js.map} +1 -1
- package/dist/esm/{base-signer-BVBWrRK7.js → base-signer-D6Xtjbg3.js} +2 -2
- package/dist/esm/{base-signer-BVBWrRK7.js.map → base-signer-D6Xtjbg3.js.map} +1 -1
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-DpegFXH0.js → cleartext-Na06vUVn.js} +2 -2
- package/dist/esm/{cleartext-DpegFXH0.js.map → cleartext-Na06vUVn.js.map} +1 -1
- package/dist/esm/{decryption-Cp8calaa.d.ts → decryption-_KeIzen9.d.ts} +34 -10
- package/dist/esm/{encryption-BT886Jlj.js → encryption-B-uikunQ.js} +2 -2
- package/dist/esm/{encryption-BT886Jlj.js.map → encryption-B-uikunQ.js.map} +1 -1
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/{fatal-batch-BYeHrf0V.js → fatal-batch-CWhfEMv9.js} +2 -2
- package/dist/esm/{fatal-batch-BYeHrf0V.js.map → fatal-batch-CWhfEMv9.js.map} +1 -1
- package/dist/esm/{fhevm-relayer-DARth6zP.js → fhevm-relayer-D_T116vA.js} +2 -2
- package/dist/esm/{fhevm-relayer-DARth6zP.js.map → fhevm-relayer-D_T116vA.js.map} +1 -1
- package/dist/esm/{index-CI6f4jxt.d.ts → index-D3eHf-xC.d.ts} +1 -1
- package/dist/esm/index.d.ts +3 -3
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/internal/index.d.ts +1 -1
- package/dist/esm/internal/index.js +1 -1
- package/dist/esm/log-decoding-OI42RdDN.js +2 -0
- package/dist/esm/log-decoding-OI42RdDN.js.map +1 -0
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/query/index.d.ts +2 -2
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/relayer-BuZxFm5d.js +2 -0
- package/dist/esm/relayer-BuZxFm5d.js.map +1 -0
- package/dist/esm/{signing-CVEOw21I.js → signing-CJBcqlEl.js} +2 -2
- package/dist/esm/{signing-CVEOw21I.js.map → signing-CJBcqlEl.js.map} +1 -1
- package/dist/esm/{telemetry-BqgBoFtC.js → telemetry-DDxj4jDq.js} +2 -2
- package/dist/esm/{telemetry-BqgBoFtC.js.map → telemetry-DDxj4jDq.js.map} +1 -1
- package/dist/esm/{token-AXsOIUDB.js → token-4vv7uAoV.js} +2 -2
- package/dist/esm/{token-AXsOIUDB.js.map → token-4vv7uAoV.js.map} +1 -1
- package/dist/esm/{validation-CZfDLOUh.js → validation-dG3aQPUa.js} +2 -2
- package/dist/esm/{validation-CZfDLOUh.js.map → validation-dG3aQPUa.js.map} +1 -1
- package/dist/esm/vaults/index.d.ts +52 -17
- package/dist/esm/vaults/index.js +1 -1
- package/dist/esm/vaults/index.js.map +1 -1
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/web/index.js +1 -1
- package/package.json +1 -1
- package/dist/esm/log-decoding-ZthqwHOv.js +0 -2
- package/dist/esm/log-decoding-ZthqwHOv.js.map +0 -1
- package/dist/esm/relayer-nWfQAlo7.js +0 -2
- package/dist/esm/relayer-nWfQAlo7.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./relayer.cjs");let t=require("viem");var n=class extends e.r{batcher;vaultId;constructor(t,n,r){super(e.i.VaultBatcherPaused,t,r),this.name=`VaultBatcherPausedError`,this.batcher=n.batcher,this.vaultId=n.vaultId}},r=class extends e.r{batcher;batchId;state;constructor(t,n,r){super(e.i.VaultBatchNotDispatched,t,r),this.name=`VaultBatchNotDispatchedError`,this.batcher=n.batcher,this.batchId=n.batchId,this.state=n.state}},
|
|
1
|
+
const e=require("./relayer.cjs");let t=require("viem");var n=class extends e.r{batcher;vaultId;constructor(t,n,r){super(e.i.VaultBatcherPaused,t,r),this.name=`VaultBatcherPausedError`,this.batcher=n.batcher,this.vaultId=n.vaultId}},r=class extends e.r{batcher;vaultId;constructor(t,n,r){super(e.i.VaultBatcherReadFailed,t,{...r,retryable:r?.retryable??(e.a(r?.cause)||e.y(r?.cause))}),this.name=`VaultBatcherReadFailedError`,this.batcher=n.batcher,this.vaultId=n.vaultId}},i=class extends e.r{batcher;batchId;state;constructor(t,n,r){super(e.i.VaultBatchNotDispatched,t,r),this.name=`VaultBatchNotDispatchedError`,this.batcher=n.batcher,this.batchId=n.batchId,this.state=n.state}},a=class extends e.r{txHash;receipt;unconfirmedVaultIds;constructor(t,n,r){super(e.i.VaultJoinUnconfirmed,t,r),this.name=`VaultJoinUnconfirmedError`,this.txHash=n.txHash,this.receipt=n.receipt,this.unconfirmedVaultIds=n.unconfirmedVaultIds}};function o(e){return e.startsWith(`0x`)?e:`0x${e}`}function s(e){return(0,t.keccak256)((0,t.toBytes)(e))}function c(e){return(0,t.getAddress)(o(e.slice(-40)))}function l(e){return e}function u(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function d(e,n){return(0,t.getAddress)(o(u(e,n).slice(-40)))}function f(e,t){return BigInt(`0x`+u(e,t))}function p(e,t){return o(u(e,t))}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return a}});
|
|
2
2
|
//# sourceMappingURL=log-decoding.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log-decoding.cjs","names":["ZamaError","ZamaErrorCode","keccak256","toBytes","getAddress","require_relayer","viem","VaultBatcherPausedError","message","options","details","VaultBatchNotDispatchedError","VaultJoinUnconfirmedError","prefixHex","value","eventTopic","signature","topicToAddress","topic","topicToBytes32","wordAt","start","index","word","data","wordToAddress","wordToBigInt","wordToBytes32"],"sources":["../../src/errors/vaults.ts","../../src/utils/hex.ts","../../src/events/log-decoding.ts"],"sourcesContent":["import type { Address, Hex } from \"viem\";\nimport type { TransactionReceipt } from \"../types/transaction\";\nimport type { BatchState } from \"../vaults/types\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** What a {@link VaultBatcherPausedError} carries. */\nexport interface VaultBatcherPausedDetails {\n /**
|
|
1
|
+
{"version":3,"file":"log-decoding.cjs","names":["ZamaError","ZamaErrorCode","isRetryable","isRpcRateLimitError","keccak256","toBytes","getAddress","require_relayer","viem","VaultBatcherPausedError","message","options","details","VaultBatcherReadFailedError","VaultBatchNotDispatchedError","VaultJoinUnconfirmedError","prefixHex","value","eventTopic","signature","topicToAddress","topic","topicToBytes32","wordAt","start","index","word","data","wordToAddress","wordToBigInt","wordToBytes32"],"sources":["../../src/errors/vaults.ts","../../src/utils/hex.ts","../../src/events/log-decoding.ts"],"sourcesContent":["import type { Address, Hex } from \"viem\";\nimport type { TransactionReceipt } from \"../types/transaction\";\nimport type { BatchState } from \"../vaults/types\";\nimport { isRpcRateLimitError } from \"../utils/error\";\nimport { isRetryable, ZamaError, ZamaErrorCode } from \"./base\";\n\n/** What a {@link VaultBatcherPausedError} carries. */\nexport interface VaultBatcherPausedDetails {\n /** A paused or closed batcher of the vault. */\n readonly batcher: Address;\n /** The vault whose leg needs the batcher. */\n readonly vaultId: string;\n}\n\n/** No batcher of a vault is open: each one is paused or closed. */\nexport class VaultBatcherPausedError extends ZamaError {\n /** A paused or closed batcher of the vault. */\n readonly batcher: Address;\n /** The vault whose leg needs the batcher. */\n readonly vaultId: string;\n\n constructor(message: string, details: VaultBatcherPausedDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.VaultBatcherPaused, message, options);\n this.name = \"VaultBatcherPausedError\";\n this.batcher = details.batcher;\n this.vaultId = details.vaultId;\n }\n}\n\n/** What a {@link VaultBatcherReadFailedError} carries. */\nexport interface VaultBatcherReadFailedDetails {\n /** The batcher that could not be read. */\n readonly batcher: Address;\n /** The vault that lists the batcher. */\n readonly vaultId: string;\n}\n\n/**\n * A batcher of a vault could not be read, so the SDK cannot tell which batch a join reaches.\n * Retryable when its `cause` is, or when RPC nodes returned reads from different blocks.\n */\nexport class VaultBatcherReadFailedError extends ZamaError {\n /** The batcher that could not be read. */\n readonly batcher: Address;\n /** The vault that lists the batcher. */\n readonly vaultId: string;\n\n constructor(\n message: string,\n details: VaultBatcherReadFailedDetails,\n options?: ErrorOptions & { retryable?: boolean },\n ) {\n super(ZamaErrorCode.VaultBatcherReadFailed, message, {\n ...options,\n // Providers pass an RPC rate limit through as a raw viem or ethers error, not an SDK one.\n retryable:\n options?.retryable ?? (isRetryable(options?.cause) || isRpcRateLimitError(options?.cause)),\n });\n this.name = \"VaultBatcherReadFailedError\";\n this.batcher = details.batcher;\n this.vaultId = details.vaultId;\n }\n}\n\n/** What a {@link VaultBatchNotDispatchedError} carries. */\nexport interface VaultBatchNotDispatchedDetails {\n /** The batcher the batch belongs to. */\n readonly batcher: Address;\n /** The batch that was to be finalized. */\n readonly batchId: bigint;\n /** The state the batch is in instead. */\n readonly state: BatchState;\n}\n\n/** The batch to finalize is not dispatched. */\nexport class VaultBatchNotDispatchedError extends ZamaError {\n /** The batcher the batch belongs to. */\n readonly batcher: Address;\n /** The batch that was to be finalized. */\n readonly batchId: bigint;\n /** The state the batch is in instead. */\n readonly state: BatchState;\n\n constructor(message: string, details: VaultBatchNotDispatchedDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.VaultBatchNotDispatched, message, options);\n this.name = \"VaultBatchNotDispatchedError\";\n this.batcher = details.batcher;\n this.batchId = details.batchId;\n this.state = details.state;\n }\n}\n\n/** What a {@link VaultJoinUnconfirmedError} carries. */\nexport interface VaultJoinUnconfirmedDetails {\n /** The mined join transaction. */\n readonly txHash: Hex;\n /** Its receipt, to inspect the logs. */\n readonly receipt: TransactionReceipt;\n /** The vaults whose `Joined` log the SDK could not match. Not a list of legs that did not join. */\n readonly unconfirmedVaultIds: readonly string[];\n}\n\n/**\n * A join was mined, but the SDK could not match a `Joined` log to every leg.\n */\nexport class VaultJoinUnconfirmedError extends ZamaError {\n /** The mined join transaction. */\n readonly txHash: Hex;\n /** Its receipt, to inspect the logs. */\n readonly receipt: TransactionReceipt;\n /** The vaults whose `Joined` log the SDK could not match. Not a list of legs that did not join. */\n readonly unconfirmedVaultIds: readonly string[];\n\n constructor(message: string, details: VaultJoinUnconfirmedDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.VaultJoinUnconfirmed, message, options);\n this.name = \"VaultJoinUnconfirmedError\";\n this.txHash = details.txHash;\n this.receipt = details.receipt;\n this.unconfirmedVaultIds = details.unconfirmedVaultIds;\n }\n}\n","import type { Hex } from \"viem\";\nimport { assertCondition } from \"./assertions\";\n\n/** Normalize a un-prefixed hex payload to a 0x-prefixed `Hex` value. */\nexport function prefixHex(value: string): Hex {\n return (value.startsWith(\"0x\") ? value : `0x${value}`) as Hex;\n}\n\n/** Convert a public `Hex` value back an unprefixed format. */\nexport function unprefixHex(value: Hex): string {\n assertCondition(value.startsWith(\"0x\"), `Expected 0x-prefixed hex, got: ${value}`);\n return value.slice(2);\n}\n","/**\n * Primitives for decoding raw EVM logs without an ABI decoder.\n *\n * @internal\n */\n\nimport { getAddress, keccak256, toBytes, type Address, type Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { prefixHex } from \"../utils\";\n\n/** Hashes the canonical signature — `Joined(uint256,address,bytes32)`, not the declaration with parameter names. */\nexport function eventTopic(signature: string): Hex {\n return keccak256(toBytes(signature));\n}\n\nexport function topicToAddress(topic: Hex): Address {\n return getAddress(prefixHex(topic.slice(-40)));\n}\n\nexport function topicToBytes32(topic: Hex): EncryptedValue {\n // EVM topics are already 32-byte 0x-prefixed hex — cast directly\n return topic as EncryptedValue;\n}\n\nexport function wordAt(data: Hex, index: number): string {\n // data starts with \"0x\", each word is 64 hex chars (32 bytes)\n const start = 2 + index * 64;\n const word = data.slice(start, start + 64);\n return word.length === 64 ? word : word.padEnd(64, \"0\");\n}\n\nexport function wordToAddress(data: Hex, index: number): Address {\n return getAddress(prefixHex(wordAt(data, index).slice(-40)));\n}\n\nexport function wordToBigInt(data: Hex, index: number): bigint {\n return BigInt(\"0x\" + wordAt(data, index));\n}\n\nexport function wordToBytes32(data: Hex, index: number): EncryptedValue {\n // wordAt returns exactly 64 hex chars — prefix and cast directly\n return prefixHex(wordAt(data, index)) as EncryptedValue;\n}\n"],"mappings":"A,uDAeA,IAAaS,EAAb,cAA6CT,EAAAA,CAAU,CAErD,QAEA,QAEA,YAAY,EAAiB,EAAoC,EAAwB,CACvF,MAAMC,EAAAA,EAAc,mBAAoBS,EAASC,CAAO,EACxD,KAAK,KAAO,0BACZ,KAAK,QAAUC,EAAQ,QACvB,KAAK,QAAUA,EAAQ,OACzB,CACF,EAcaC,EAAb,cAAiDb,EAAAA,CAAU,CAEzD,QAEA,QAEA,YACE,EACA,EACA,EACA,CACA,MAAMC,EAAAA,EAAc,uBAAwBS,EAAS,CACnD,GAAGC,EAEH,UAC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SAAgBE,EAAc,EAAW,EAAwB,CAC/D,OAAA,EAAOtB,EAAAA,WAAAA,CAAWU,EAAUO,EAAOI,EAAMF,CAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAC7D,CAEA,SAAgBI,EAAa,EAAW,EAAuB,CAC7D,OAAO,OAAO,KAAON,EAAOI,EAAMF,CAAK,CAAC,CAC1C,CAEA,SAAgBK,EAAc,EAAW,EAA+B,CAEtE,OAAOd,EAAUO,EAAOI,EAAMF,CAAK,CAAC,CACtC,C"}
|
package/dist/cjs/relayer.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function t(e){
|
|
1
|
+
function e(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function t(e){return i(e,n)!==void 0}function n(e){if(e.name===`ContractFunctionRevertedError`||e.name===`ContractFunctionZeroDataError`||e.code===`CALL_EXCEPTION`)return!0;if(typeof e.message!=`string`)return!1;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}const r=[`cause`,`error`,`info`];function i(e,t,n=6){if(n<0||typeof e!=`object`||!e)return;let a=e;if(t(a))return a;for(let e of r){let r=a[e];if(typeof r==`object`&&r){let e=i(r,t,n-1);if(e)return e}}}function a(e){if(e.code===-32005||e.status===429||e.code===429)return!0;if(e.code===`SERVER_ERROR`&&typeof e.info==`object`&&e.info!==null){let t=e.info.responseStatus;if(typeof t==`string`&&/^\s*429\b/.test(t))return!0}return!1}function o(e){if(a(e))return!0;if(typeof e.message==`string`){let t=e.message.toLowerCase();return t.includes(`too many requests`)||t.includes(`rate limit`)||t.includes(`rate-limit`)}return!1}function s(e){return i(e,e=>typeof e.name==`string`&&e.name.startsWith(`Relayer`))!==void 0}function c(e){return i(e,e=>e.name===`RelayerTimeoutError`)!==void 0}function l(e){return!s(e)&&i(e,o)!==void 0}function u(e){return!s(e)&&i(e,a)!==void 0}function d(e){return e.toLowerCase().includes(`is not authorized to decrypt handle`)}function f(e){return e.toLowerCase().includes(`invalid transportkeypair`)}const p=[`data`,`raw`,`signature`];function m(e,t,n){for(let n of p){let r=e[n];if(typeof r==`string`&&r.toLowerCase().startsWith(t))return!0}if(typeof e.message==`string`){let r=e.message.toLowerCase();return r.includes(t)||r.includes(n)}return!1}function h(e,t,n){let r=t.toLowerCase(),a=n.toLowerCase();return i(e,e=>m(e,r,a))!==void 0}function g(e){return h(e,`0x77ddbe81`,`InvalidKmsContext`)}function _(e){return/handle (0x[0-9a-fA-F]{64})/.exec(e)?.[1]}function v(e){if(e==null)return;let t=e.trim();if(t!==``){if(/^\d+$/.test(t))return Number(t);if(/[a-zA-Z]/.test(t)){let e=Date.parse(t);if(!Number.isNaN(e))return Math.max(0,Math.round((e-Date.now())/1e3))}}}function y(e){if(typeof e!=`object`||!e)return;let t=e.get;if(typeof t==`function`)return v(t.call(e,`Retry-After`))}function b(e){let t=e.response;if(typeof t==`object`&&t)return y(t.headers)}function x(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function S(e){return x(e.retryAfter)?e.retryAfter:b(e)}function C(e){let t=i(e,e=>S(e)!==void 0);return t?S(t):void 0}function w(e){let t=i(e,e=>typeof e.statusCode==`number`||typeof e.status==`number`);if(t)return typeof t.statusCode==`number`?t.statusCode:t.status}function T(e){let t=i(e,e=>typeof e.code==`number`&&e.code!==-1);return t?t.code:void 0}function E(e){return e instanceof Error&&e.name!==`Error`?e.name:void 0}const D={SigningRejected:`SIGNING_REJECTED`,SigningFailed:`SIGNING_FAILED`,EncryptionFailed:`ENCRYPTION_FAILED`,DecryptionFailed:`DECRYPTION_FAILED`,EncryptOffloadUnavailable:`ENCRYPT_OFFLOAD_UNAVAILABLE`,TransactionReverted:`TRANSACTION_REVERTED`,HcuBlockLimitExceeded:`HCU_BLOCK_LIMIT_EXCEEDED`,HcuTransactionLimitExceeded:`HCU_TRANSACTION_LIMIT_EXCEEDED`,TransportKeyPairExpired:`KEYPAIR_EXPIRED`,InvalidTransportKeyPair:`INVALID_KEYPAIR`,RevokedKmsContext:`REVOKED_KMS_CONTEXT`,NoCiphertext:`NO_CIPHERTEXT`,RelayerRequestFailed:`RELAYER_REQUEST_FAILED`,NotEntitled:`NOT_ENTITLED`,RpcRateLimited:`RPC_RATE_LIMITED`,Configuration:`CONFIGURATION`,DelegationSelfNotAllowed:`DELEGATION_SELF_NOT_ALLOWED`,DelegationCooldown:`DELEGATION_COOLDOWN`,DelegationNotFound:`DELEGATION_NOT_FOUND`,DelegationExpired:`DELEGATION_EXPIRED`,InsufficientConfidentialBalance:`INSUFFICIENT_CONFIDENTIAL_BALANCE`,InsufficientERC20Balance:`INSUFFICIENT_ERC20_BALANCE`,InsufficientAllowance:`INSUFFICIENT_ALLOWANCE`,BalanceCheckUnavailable:`BALANCE_CHECK_UNAVAILABLE`,ERC20ReadFailed:`ERC20_READ_FAILED`,DelegationExpiryUnchanged:`DELEGATION_EXPIRY_UNCHANGED`,DelegationDelegateEqualsContract:`DELEGATION_DELEGATE_EQUALS_CONTRACT`,DelegationDelegateCannotBeWildcard:`DELEGATION_DELEGATE_CANNOT_BE_WILDCARD`,DelegationContractIsSelf:`DELEGATION_CONTRACT_IS_SELF`,AclPaused:`ACL_PAUSED`,DelegationExpirationTooSoon:`DELEGATION_EXPIRATION_TOO_SOON`,DelegationNotPropagated:`DELEGATION_NOT_PROPAGATED`,ChainMismatch:`CHAIN_MISMATCH`,SignerNotConfigured:`SIGNER_NOT_CONFIGURED`,WalletNotConnected:`WALLET_NOT_CONNECTED`,WalletAccountNotReady:`WALLET_ACCOUNT_NOT_READY`,KeyWrappingFailed:`KEY_WRAPPING_FAILED`,TransportKeyPairChanged:`TRANSPORT_KEY_PAIR_CHANGED`,PreparedPermitChainMismatch:`PREPARED_PERMIT_CHAIN_MISMATCH`,PreparedPermitExpired:`PREPARED_PERMIT_EXPIRED`,UnshieldAlreadyFinalized:`UNSHIELD_ALREADY_FINALIZED`,VaultBatcherPaused:`VAULT_BATCHER_PAUSED`,VaultBatcherReadFailed:`VAULT_BATCHER_READ_FAILED`,VaultBatchNotDispatched:`VAULT_BATCH_NOT_DISPATCHED`,VaultJoinUnconfirmed:`VAULT_JOIN_UNCONFIRMED`},O={[D.SigningRejected]:!1,[D.SigningFailed]:!1,[D.EncryptionFailed]:!1,[D.DecryptionFailed]:!1,[D.EncryptOffloadUnavailable]:!1,[D.TransactionReverted]:!1,[D.HcuBlockLimitExceeded]:!0,[D.HcuTransactionLimitExceeded]:!1,[D.TransportKeyPairExpired]:!1,[D.InvalidTransportKeyPair]:!1,[D.RevokedKmsContext]:!1,[D.NoCiphertext]:!1,[D.RelayerRequestFailed]:!1,[D.NotEntitled]:!1,[D.RpcRateLimited]:!0,[D.Configuration]:!1,[D.DelegationSelfNotAllowed]:!1,[D.DelegationCooldown]:!0,[D.DelegationNotFound]:!1,[D.DelegationExpired]:!1,[D.InsufficientConfidentialBalance]:!1,[D.InsufficientERC20Balance]:!1,[D.InsufficientAllowance]:!1,[D.BalanceCheckUnavailable]:!1,[D.ERC20ReadFailed]:!1,[D.DelegationExpiryUnchanged]:!1,[D.DelegationDelegateEqualsContract]:!1,[D.DelegationDelegateCannotBeWildcard]:!1,[D.DelegationContractIsSelf]:!1,[D.AclPaused]:!1,[D.DelegationExpirationTooSoon]:!1,[D.DelegationNotPropagated]:!0,[D.ChainMismatch]:!1,[D.SignerNotConfigured]:!1,[D.WalletNotConnected]:!1,[D.WalletAccountNotReady]:!0,[D.KeyWrappingFailed]:!1,[D.TransportKeyPairChanged]:!1,[D.PreparedPermitChainMismatch]:!1,[D.PreparedPermitExpired]:!1,[D.UnshieldAlreadyFinalized]:!1,[D.VaultBatcherPaused]:!1,[D.VaultBatcherReadFailed]:!1,[D.VaultBatchNotDispatched]:!1,[D.VaultJoinUnconfirmed]:!1};var k=class extends Error{code;retryable;constructor(e,t,n){super(t,n),Object.setPrototypeOf(this,new.target.prototype),this.name=`ZamaError`,this.code=e,this.retryable=n?.retryable??O[e]}};function A(e){return e instanceof k&&e.retryable}function j(e){if(!A(e)||!(`retryAfter`in e))return;let t=e.retryAfter;return x(t)?t:void 0}var M=class extends k{statusCode;retryAfter;constructor(e,t,n){let r=n?.retryable??t===429;super(D.RelayerRequestFailed,e,{...n,retryable:r}),this.name=`RelayerRequestFailedError`,this.statusCode=t,this.retryAfter=r?n?.retryAfter:void 0}},N=class extends k{constructor(e,t){super(D.Configuration,e,t),this.name=`ConfigurationError`}};Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return l}});
|
|
2
2
|
//# sourceMappingURL=relayer.cjs.map
|
package/dist/cjs/relayer.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relayer.cjs","names":["toError","error","isContractCallError","msg","NESTED_ERROR_KEYS","findInErrorChain","depth","node","predicate","key","next","found","nodeHasStructuredRateLimit","responseStatus","nodeIsRpcRateLimit","isRelayerError","isRelayerTimeoutError","isRpcRateLimitError","hasStructuredRpcRateLimitSignal","isNotEntitledMessage","message","isInvalidTransportKeyPairMessage","REVERT_DATA_KEYS","nodeHasRevert","value","selector","name","hasRevert","lowerSelector","lowerName","isRevokedKmsContextError","parseHandleFromMessage","parseRetryAfterHeader","trimmed","dateMs","readRetryAfterHeader","headers","get","retryAfterFromHeader","response","isValidRetryAfterSeconds","retryAfterFromNode","extractRetryAfter","n","extractHttpStatus","extractRpcErrorCode","extractWalletErrorName","ZamaErrorCode","RETRYABLE_BY_CODE","ZamaError","options","code","isRetryable","retryAfterSeconds","retryAfter","RelayerRequestFailedError","retryable","statusCode","ConfigurationError"],"sources":["../../src/utils/error.ts","../../src/errors/base.ts","../../src/errors/relayer.ts"],"sourcesContent":["/** Coerce an unknown caught value to an Error instance. */\nexport function toError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n return new Error(String(error.message));\n }\n return new Error(String(error));\n}\n\n/**\n * Returns true if the error is a contract call revert (as opposed to a network/transport error).\n * Detects viem's ContractFunctionExecutionError / ContractFunctionRevertedError\n * and ethers' CALL_EXCEPTION.\n */\nexport function isContractCallError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n // viem: ContractFunctionExecutionError, ContractFunctionRevertedError\n if (\n error.name === \"ContractFunctionExecutionError\" ||\n error.name === \"ContractFunctionRevertedError\"\n ) {\n return true;\n }\n // ethers: error.code === \"CALL_EXCEPTION\"\n if (\"code\" in error && error.code === \"CALL_EXCEPTION\") {\n return true;\n }\n // Fallback: common revert message patterns from various providers\n const msg = error.message.toLowerCase();\n return msg.includes(\"execution reverted\") || msg.includes(\"call revert exception\");\n}\n\n/** JSON-RPC error code providers use for rate limiting (\"limit exceeded\"). */\nconst JSON_RPC_LIMIT_EXCEEDED = -32005;\n\n/** Properties that may nest a lower-level cause across viem / ethers / fetch. */\nconst NESTED_ERROR_KEYS = [\"cause\", \"error\", \"info\"] as const;\n\n/**\n * Walk an error and its nested causes (`cause` / `error` / `info`, as used by\n * viem, ethers, and fetch wrappers), applying `predicate` to each object node.\n * Returns the first node for which `predicate` returns true, or `undefined`.\n * Depth-bounded to avoid pathological / cyclic structures.\n */\nfunction findInErrorChain(\n error: unknown,\n predicate: (node: Record<string, unknown>) => boolean,\n depth = 6,\n): Record<string, unknown> | undefined {\n if (depth < 0 || error === null || error === undefined || typeof error !== \"object\") {\n return undefined;\n }\n const node = error as Record<string, unknown>;\n if (predicate(node)) {\n return node;\n }\n for (const key of NESTED_ERROR_KEYS) {\n const next = node[key];\n if (next !== undefined && next !== null && typeof next === \"object\") {\n const found = findInErrorChain(next, predicate, depth - 1);\n if (found) {\n return found;\n }\n }\n }\n return undefined;\n}\n\n// ============================================================================\n// Classification detectors\n// ============================================================================\n\n/**\n * Structured (unambiguous) consumer rate-limit signal across the RPC providers\n * the SDK reads through:\n * - JSON-RPC `-32005` (\"limit exceeded\");\n * - viem-style numeric `status: 429`, and viem's own `shouldRetry` shape where\n * the JSON-RPC error `code` is `429`;\n * - ethers' 429, which surfaces as `code: \"SERVER_ERROR\"` with the status only\n * in `info.responseStatus` (a string like `\"429 Too Many Requests\"`) and no\n * numeric top-level status — the leading code is parsed out of it.\n *\n * Deliberately NOT `statusCode: 429` — that is the relayer / node-fetch HTTP\n * shape, which stays {@link RelayerRequestFailedError} (SDK-236), so a relayer\n * 429 is never mistaken for a consumer-RPC throttle.\n */\nfunction nodeHasStructuredRateLimit(node: Record<string, unknown>): boolean {\n if (node.code === JSON_RPC_LIMIT_EXCEEDED || node.status === 429 || node.code === 429) {\n return true;\n }\n // ethers: `code: \"SERVER_ERROR\"`, status lives in `info.responseStatus`.\n if (node.code === \"SERVER_ERROR\" && typeof node.info === \"object\" && node.info !== null) {\n const responseStatus = (node.info as Record<string, unknown>).responseStatus;\n if (typeof responseStatus === \"string\" && /^\\s*429\\b/.test(responseStatus)) {\n return true;\n }\n }\n return false;\n}\n\nfunction nodeIsRpcRateLimit(node: Record<string, unknown>): boolean {\n if (nodeHasStructuredRateLimit(node)) {\n return true;\n }\n // Message fallback for providers without a structured code. Deliberately\n // narrow (specific throttling phrases, no bare \"429\") to avoid false positives\n // that would turn a terminal error into a retryable one.\n if (typeof node.message === \"string\") {\n const msg = node.message.toLowerCase();\n return (\n msg.includes(\"too many requests\") || msg.includes(\"rate limit\") || msg.includes(\"rate-limit\")\n );\n }\n return false;\n}\n\n/**\n * True when a failure originates from `@fhevm/sdk`'s relayer transport. Every\n * relayer error it throws — `RelayerResponseStatusError`, `RelayerResponseApiError`,\n * `RelayerMaxRetryError`, `RelayerTimeoutError`, … — carries the `Relayer` `name`\n * prefix. Such errors stay the relayer's domain ({@link RelayerRequestFailedError}\n * / SDK-236), never {@link RpcRateLimitError}, even on a 429 (which `@fhevm/sdk`\n * retries internally, honoring `Retry-After`, before surfacing).\n */\nexport function isRelayerError(error: unknown): boolean {\n return (\n findInErrorChain(\n error,\n (node) => typeof node.name === \"string\" && node.name.startsWith(\"Relayer\"),\n ) !== undefined\n );\n}\n\n/**\n * True when the failure is an `@fhevm/sdk` relayer *timeout* (`RelayerTimeoutError`,\n * thrown when a request exceeds the relayer's global deadline without a verdict).\n * Unlike a terminal 4xx/5xx, the operation itself is safe to retry, so callers map\n * it to a {@link RelayerRequestFailedError} with `retryable: true` — mirroring the\n * former `WorkerTimeoutError`, which was likewise documented retryable.\n */\nexport function isRelayerTimeoutError(error: unknown): boolean {\n return findInErrorChain(error, (node) => node.name === \"RelayerTimeoutError\") !== undefined;\n}\n\n/**\n * True if the error is the consumer's RPC provider throttling an on-chain read\n * (HTTP 429 / JSON-RPC -32005). Relayer-originated 429s are excluded.\n */\nexport function isRpcRateLimitError(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeIsRpcRateLimit) !== undefined;\n}\n\n/**\n * Like {@link isRpcRateLimitError} but only matches an unambiguous **structured**\n * signal (`-32005` or a viem `status: 429`), ignoring message text. The classifier\n * promotes this ahead of any HTTP status, while a message-only throttle is only\n * trusted when no status is present — so a relayer HTTP error whose body happens\n * to say \"rate limit\" still maps to {@link RelayerRequestFailedError}.\n */\nexport function hasStructuredRpcRateLimitSignal(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeHasStructuredRateLimit) !== undefined;\n}\n\n/**\n * Transport-error signatures of the consumer's own RPC client (viem / ethers).\n * The SDK's on-chain reads (the ACL `persistAllowed` pre-check) go through that\n * client, which already retries transport faults internally — so a failure\n * carrying one of these shapes must NOT be retried again by the SDK on top.\n */\nfunction nodeHasConsumerRpcSignature(node: Record<string, unknown>): boolean {\n // ethers transient transport codes.\n const code = node.code;\n if (code === \"NETWORK_ERROR\" || code === \"SERVER_ERROR\" || code === \"TIMEOUT\") {\n return true;\n }\n // viem transport error classes, matched by `name`.\n const name = node.name;\n return (\n name === \"HttpRequestError\" ||\n name === \"RpcRequestError\" ||\n name === \"TimeoutError\" ||\n name === \"WebSocketRequestError\"\n );\n}\n\n/**\n * True when a failure originates from the **consumer's RPC provider** (viem /\n * ethers) rather than the relayer. Keeps the SDK's relayer retry from\n * double-retrying transport faults the integrator's client already retried.\n * A relayer error (`Relayer*`) is never consumer-RPC.\n */\nexport function isConsumerRpcError(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n if (hasStructuredRpcRateLimitSignal(error)) {\n return true;\n }\n return findInErrorChain(error, nodeHasConsumerRpcSignature) !== undefined;\n}\n\n/**\n * `@fhevm/sdk`'s ACL gate (`checkPersistAllowed`) throws an `AclUserDecryptionError`\n * when the requesting actor isn't allowed: `User <a> is not authorized to decrypt\n * handle <h>!`. Matching that phrase is what lets {@link wrapDecryptError} surface\n * a typed NotEntitledError with the parsed handle.\n *\n * Deliberately excludes the sibling `Dapp contract <a> is not authorized to\n * **user** decrypt handle <h>!` — a dapp ACL misconfig, intentionally left to\n * DecryptionFailedError. The differentiator is the inserted \"user\": the actor\n * message reads \"…to decrypt handle\", the dapp message \"…to user decrypt handle\",\n * so keying on \"is not authorized to decrypt handle\" matches only the former.\n *\n * The `error.test.ts` drift guard reads the installed `@fhevm/sdk` source and\n * fails loudly if the message is reworded.\n */\nexport function isNotEntitledMessage(message: string): boolean {\n return message.toLowerCase().includes(\"is not authorized to decrypt handle\");\n}\n\n/**\n * `@fhevm/sdk`'s `verifyTkmsPublicKey` throws `invalid TransportKeyPairKeyPair`\n * when a stored transport key pair can't be re-derived under the current TKMS\n * version — the signal that the persisted key pair is stale (typically after a\n * KMS/TKMS rotation) and must be evicted and regenerated. Matching it lets the\n * signing and decrypt paths surface a typed {@link InvalidTransportKeyPairError}\n * and self-heal the vault entry.\n */\nexport function isInvalidTransportKeyPairMessage(message: string): boolean {\n return message.toLowerCase().includes(\"invalid transportkeypair\");\n}\n\n/**\n * 4-byte selector of `InvalidKmsContext(uint256)`, the revert ProtocolConfig\n * raises when the KMS signers read resolves an unknown or revoked context.\n * The `error.test.ts` drift guard recomputes it from the Solidity signature.\n */\nexport const INVALID_KMS_CONTEXT_SELECTOR = \"0x77ddbe81\";\n\n/** Revert-data fields across clients: viem's `raw`/`signature`, ethers' `data`. */\nconst REVERT_DATA_KEYS = [\"data\", \"raw\", \"signature\"] as const;\n\nfunction nodeHasRevert(node: Record<string, unknown>, selector: string, name: string): boolean {\n for (const key of REVERT_DATA_KEYS) {\n const value = node[key];\n if (typeof value === \"string\" && value.toLowerCase().startsWith(selector)) {\n return true;\n }\n }\n // Text-only fallback for wrappers that stringify the revert instead of\n // carrying the data fields above.\n if (typeof node.message === \"string\") {\n const msg = node.message.toLowerCase();\n return msg.includes(selector) || msg.includes(name);\n }\n return false;\n}\n\n/**\n * True when `error` or any nested cause reverts with the custom error\n * `selector`, or names the error in its message for providers that only\n * stringify the revert. Needs no ABI.\n */\nexport function hasRevert(error: unknown, selector: string, name: string): boolean {\n const lowerSelector = selector.toLowerCase();\n const lowerName = name.toLowerCase();\n return (\n findInErrorChain(error, (node) => nodeHasRevert(node, lowerSelector, lowerName)) !== undefined\n );\n}\n\n/**\n * True when a failure is the on-chain KMS signers read reverting with\n * `InvalidKmsContext`: the permit's KMS context has been revoked (or never\n * existed), so every permit signed under it is permanently dead. The decrypt\n * path uses this to evict the permit and re-grant under the current context.\n *\n * The installed `@fhevm/sdk` performs that read without the error in its ABI,\n * so the revert arrives as raw data; the selector is matched anywhere in the\n * cause chain, with a message fallback for text-only providers.\n */\nexport function isRevokedKmsContextError(error: unknown): boolean {\n return hasRevert(error, INVALID_KMS_CONTEXT_SELECTOR, \"InvalidKmsContext\");\n}\n\n/** Parse the on-chain handle out of the not-entitled message. */\nexport function parseHandleFromMessage(message: string): string | undefined {\n return /handle (0x[0-9a-fA-F]{64})/.exec(message)?.[1];\n}\n\n/**\n * Parse an HTTP `Retry-After` header value into **seconds** (the SDK's duration\n * unit and the header's own unit), or `undefined` when absent/unparseable. Per\n * RFC 9110 the value is either a non-negative number of seconds (`\"120\"`) or an\n * HTTP-date; a past date floors to `0`.\n */\nexport function parseRetryAfterHeader(value: string | null | undefined): number | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n const trimmed = value.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n // delta-seconds: a non-negative integer (already the unit we want).\n if (/^\\d+$/.test(trimmed)) {\n return Number(trimmed);\n }\n // HTTP-date — an IMF-fixdate always carries alphabetic day/month names, so\n // require a letter before deferring to the lenient Date.parse.\n if (/[a-zA-Z]/.test(trimmed)) {\n const dateMs = Date.parse(trimmed);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, Math.round((dateMs - Date.now()) / 1000));\n }\n }\n return undefined;\n}\n\n/** Read a `Retry-After` header (→ seconds) off a `Headers`-like object, if present. */\nexport function readRetryAfterHeader(headers: unknown): number | undefined {\n if (headers === null || typeof headers !== \"object\") {\n return undefined;\n }\n const get = (headers as { get?: unknown }).get;\n if (typeof get !== \"function\") {\n return undefined;\n }\n return parseRetryAfterHeader(\n (get as (name: string) => string | null).call(headers, \"Retry-After\"),\n );\n}\n\n/**\n * A node's **relayer** `Retry-After` header (seconds), read from a wrapped fetch\n * `Response` (the relayer's `cause.response.headers`). The SDK owns the\n * relayer fetch, so parsing the header there is legitimate.\n *\n * The viem/chain side (`HttpRequestError.headers`) is deliberately **not** read:\n * for consumer RPC the integrator's viem/ethers transport already honors\n * `Retry-After` in its own retry loop (and retries) before the error ever\n * surfaces, so re-reading it here would re-implement a transport concern.\n * Chain-RPC backoff is configured on the consumer's transport (`chain.network`).\n */\nfunction retryAfterFromHeader(node: Record<string, unknown>): number | undefined {\n const response = node.response;\n if (response !== null && typeof response === \"object\") {\n return readRetryAfterHeader((response as Record<string, unknown>).headers);\n }\n return undefined;\n}\n\n/**\n * True for a well-formed server-driven retry delay, in seconds: a finite,\n * positive number. Shared by the chain-walking extractor below and the public\n * {@link retryAfterSeconds} accessor (`errors/base.ts`), so a malformed value\n * (`0`, negative, `NaN`) is rejected the same way everywhere instead of being\n * handed unchanged to a `setTimeout` backoff.\n */\nexport function isValidRetryAfterSeconds(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0;\n}\n\n/**\n * A single node's server-driven retry delay (seconds): a numeric `retryAfter`\n * (a non-positive synthetic value is ignored), else a `Retry-After` header.\n */\nfunction retryAfterFromNode(node: Record<string, unknown>): number | undefined {\n if (isValidRetryAfterSeconds(node.retryAfter)) {\n return node.retryAfter;\n }\n return retryAfterFromHeader(node);\n}\n\n/**\n * Best-effort extraction of a server-driven retry delay, in **seconds**, from\n * anywhere in an error's cause chain. Reads a numeric `retryAfter` property and\n * the **relayer's** `Retry-After` header (`cause.response.headers`). The\n * consumer-RPC/chain side is intentionally not read — viem/ethers own that\n * backoff (see {@link retryAfterFromHeader}). `undefined` when absent.\n */\nexport function extractRetryAfter(error: unknown): number | undefined {\n const node = findInErrorChain(error, (n) => retryAfterFromNode(n) !== undefined);\n return node ? retryAfterFromNode(node) : undefined;\n}\n\n/**\n * Extract an HTTP status code from an error or anywhere in its cause chain.\n * Relayer SDK errors may carry a `status` or `statusCode` property; walking the\n * full chain (rather than just depth-1) keeps this in step with the other\n * chain-walking detectors and avoids a depth asymmetry between them.\n */\nexport function extractHttpStatus(error: unknown): number | undefined {\n const node = findInErrorChain(\n error,\n (n) => typeof n.statusCode === \"number\" || typeof n.status === \"number\",\n );\n if (!node) {\n return undefined;\n }\n return (typeof node.statusCode === \"number\" ? node.statusCode : node.status) as number;\n}\n\n/**\n * A JSON-RPC / EIP-1193 numeric error code (e.g. `4001` for user rejection, or a\n * wallet/provider code like `-32603`) found anywhere in a signing failure's cause\n * chain. Gives a signing error a structured, groupable field instead of leaving\n * the code buried in free-text `message` or an opaque nested `cause`.\n *\n * Skips `-1`: viem's own `UnknownRpcError` fallback code for errors it can't\n * classify, not an RPC-provided code. Reporting it as `rpcCode` would read as\n * a real (if odd) wallet error code, so the chain walk continues past it in\n * case a real code is nested deeper (e.g. in `cause`).\n */\nexport function extractRpcErrorCode(error: unknown): number | undefined {\n const node = findInErrorChain(error, (n) => typeof n.code === \"number\" && n.code !== -1);\n return node ? (node.code as number) : undefined;\n}\n\n/**\n * The `name` of the error class a signing failure was thrown as (e.g. viem's\n * `InvalidParamsRpcError`, an EIP-1193 `ProviderRpcError`) — a stable,\n * library-level classification an observability integration can group and alert\n * on. Deliberately reads only the top-level error, not the full cause chain: a\n * wallet's own internal error class name is inconsistent across wallets and\n * buried at an arbitrary depth, so it is not guessed at here — the full chain\n * remains available via the wrapped error's `cause` for manual inspection.\n */\nexport function extractWalletErrorName(error: unknown): string | undefined {\n return error instanceof Error && error.name !== \"Error\" ? error.name : undefined;\n}\n","import { isValidRetryAfterSeconds } from \"../utils/error\";\n\n/**\n * Typed error codes thrown by the SDK.\n * Use `error.code` or `instanceof` to programmatically handle specific failure modes.\n *\n * @example\n * ```ts\n * try {\n * await token.confidentialTransfer(\"0xTo\", 100n);\n * } catch (e) {\n * if (e instanceof SigningRejectedError) {\n * // User rejected the wallet signature\n * }\n * }\n * ```\n */\nexport const ZamaErrorCode = {\n /** User rejected the wallet signature prompt. */\n SigningRejected: \"SIGNING_REJECTED\",\n /** Wallet signature failed for a reason other than rejection. */\n SigningFailed: \"SIGNING_FAILED\",\n /** FHE encryption failed. */\n EncryptionFailed: \"ENCRYPTION_FAILED\",\n /** FHE decryption failed. */\n DecryptionFailed: \"DECRYPTION_FAILED\",\n /** Encryption offload was required (`offloadEncrypt: true`) but the worker is unavailable. */\n EncryptOffloadUnavailable: \"ENCRYPT_OFFLOAD_UNAVAILABLE\",\n /** On-chain transaction reverted. */\n TransactionReverted: \"TRANSACTION_REVERTED\",\n /** The block's FHE compute budget (HCU) is spent. Retryable: it resets every block. */\n HcuBlockLimitExceeded: \"HCU_BLOCK_LIMIT_EXCEEDED\",\n /** The transaction needs more FHE compute (HCU) than one transaction may use. */\n HcuTransactionLimitExceeded: \"HCU_TRANSACTION_LIMIT_EXCEEDED\",\n /** Transport key pair has expired and needs regeneration. */\n TransportKeyPairExpired: \"KEYPAIR_EXPIRED\",\n /** Relayer rejected transport key pair (stale, expired, or malformed). */\n InvalidTransportKeyPair: \"INVALID_KEYPAIR\",\n /** The permit's KMS context was revoked on-chain; the SDK's evict-and-regrant retry also failed. */\n RevokedKmsContext: \"REVOKED_KMS_CONTEXT\",\n /** No FHE ciphertext exists for this account (never shielded). */\n NoCiphertext: \"NO_CIPHERTEXT\",\n /** Relayer HTTP request failed. */\n RelayerRequestFailed: \"RELAYER_REQUEST_FAILED\",\n /** The configured signer/account is not entitled (ACL) to decrypt this encrypted value. Don't retry — wait for a grant. */\n NotEntitled: \"NOT_ENTITLED\",\n /** The consumer's RPC provider rate-limited an on-chain read (e.g. HTTP 429 / JSON-RPC -32005). Retryable. */\n RpcRateLimited: \"RPC_RATE_LIMITED\",\n /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\n Configuration: \"CONFIGURATION\",\n /** Delegation cannot target self (delegate === msg.sender). */\n DelegationSelfNotAllowed: \"DELEGATION_SELF_NOT_ALLOWED\",\n /** Only one delegate/revoke per (delegator, delegate, contract) per block. */\n DelegationCooldown: \"DELEGATION_COOLDOWN\",\n /** No active delegation found for this (delegator, delegate, contract) tuple. */\n DelegationNotFound: \"DELEGATION_NOT_FOUND\",\n /** The delegation has expired. */\n DelegationExpired: \"DELEGATION_EXPIRED\",\n /** Confidential (cToken) balance is insufficient for the requested operation. */\n InsufficientConfidentialBalance: \"INSUFFICIENT_CONFIDENTIAL_BALANCE\",\n /** ERC-20 balance is insufficient for the requested shield amount. */\n InsufficientERC20Balance: \"INSUFFICIENT_ERC20_BALANCE\",\n /** ERC-20 allowance granted to the wrapper is insufficient for the requested wrap amount. */\n InsufficientAllowance: \"INSUFFICIENT_ALLOWANCE\",\n /** Balance validation could not be performed (no cached credentials and decryption not possible). */\n BalanceCheckUnavailable: \"BALANCE_CHECK_UNAVAILABLE\",\n /** Public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\n ERC20ReadFailed: \"ERC20_READ_FAILED\",\n /** The new expiration date equals the current one — no on-chain change needed. */\n DelegationExpiryUnchanged: \"DELEGATION_EXPIRY_UNCHANGED\",\n /** Delegate address cannot be the contract address. */\n DelegationDelegateEqualsContract: \"DELEGATION_DELEGATE_EQUALS_CONTRACT\",\n /** Delegate address cannot be the wildcard address — it's only valid as `contractAddress`. */\n DelegationDelegateCannotBeWildcard: \"DELEGATION_DELEGATE_CANNOT_BE_WILDCARD\",\n /** Contract address cannot be the sender address. */\n DelegationContractIsSelf: \"DELEGATION_CONTRACT_IS_SELF\",\n /** The ACL contract is paused. */\n AclPaused: \"ACL_PAUSED\",\n /** Expiration date is too soon (must be at least 1 hour in the future). */\n DelegationExpirationTooSoon: \"DELEGATION_EXPIRATION_TOO_SOON\",\n /** Delegation exists on-chain but hasn't propagated to the gateway yet. */\n DelegationNotPropagated: \"DELEGATION_NOT_PROPAGATED\",\n /** Signer and provider are connected to different chains. */\n ChainMismatch: \"CHAIN_MISMATCH\",\n /** Operation requires a signer but none is configured. */\n SignerNotConfigured: \"SIGNER_NOT_CONFIGURED\",\n /** Operation requires a connected wallet account. */\n WalletNotConnected: \"WALLET_NOT_CONNECTED\",\n /** Wallet account discovery is still resolving. */\n WalletAccountNotReady: \"WALLET_ACCOUNT_NOT_READY\",\n /** Wrapping or unwrapping the transport private key with `transportKeyPairDerivationSecret` failed. */\n KeyWrappingFailed: \"KEY_WRAPPING_FAILED\",\n /** The transport key pair changed between `preparePermit` and `registerPermit`. */\n TransportKeyPairChanged: \"TRANSPORT_KEY_PAIR_CHANGED\",\n /** A prepared permit's `chainId` does not match the chain `registerPermit` is running against. */\n PreparedPermitChainMismatch: \"PREPARED_PERMIT_CHAIN_MISMATCH\",\n /** A prepared permit's validity window elapsed before its signature was registered. */\n PreparedPermitExpired: \"PREPARED_PERMIT_EXPIRED\",\n /** The unwrap request was already finalized on-chain; there is nothing left to resume. */\n UnshieldAlreadyFinalized: \"UNSHIELD_ALREADY_FINALIZED\",\n /** A batcher a vault join needs is paused. */\n VaultBatcherPaused: \"VAULT_BATCHER_PAUSED\",\n /** A batch to be finalized is not dispatched. */\n VaultBatchNotDispatched: \"VAULT_BATCH_NOT_DISPATCHED\",\n /** A vault join was mined, but its receipt does not confirm every leg. */\n VaultJoinUnconfirmed: \"VAULT_JOIN_UNCONFIRMED\",\n} as const;\n\n/** Union of all {@link ZamaErrorCode} string values. */\nexport type ZamaErrorCode = (typeof ZamaErrorCode)[keyof typeof ZamaErrorCode];\n\n/** Identity type that fails to instantiate unless `T` maps every {@link ZamaErrorCode} to a `boolean`. */\ntype Complete<T extends Record<ZamaErrorCode, boolean>> = T;\n\n/**\n * Default retryability for each {@link ZamaErrorCode}. `Complete` fails the build\n * if a new code is added without an entry here — the same exhaustiveness guard\n * `matchZamaError`'s `ErrorForCode` map uses (see `match.ts`) — so a new\n * transient (or terminal) cause can't silently default to the wrong signal.\n *\n * {@link RelayerRequestFailedError} is the one exception: its retryability\n * depends on the HTTP status (only a 429 is retryable), not just the code, so\n * it overrides this default via the constructor's `retryable` option instead\n * of being read from here.\n */\nconst RETRYABLE_BY_CODE: Complete<Record<ZamaErrorCode, boolean>> = {\n [ZamaErrorCode.SigningRejected]: false,\n [ZamaErrorCode.SigningFailed]: false,\n [ZamaErrorCode.EncryptionFailed]: false,\n [ZamaErrorCode.DecryptionFailed]: false,\n [ZamaErrorCode.EncryptOffloadUnavailable]: false, // the worker realm is unusable for this page; a retry hits the same environment\n [ZamaErrorCode.TransactionReverted]: false,\n [ZamaErrorCode.HcuBlockLimitExceeded]: true, // the block budget resets every block\n [ZamaErrorCode.HcuTransactionLimitExceeded]: false, // the same transaction costs the same HCU on every retry\n [ZamaErrorCode.TransportKeyPairExpired]: false,\n [ZamaErrorCode.InvalidTransportKeyPair]: false,\n [ZamaErrorCode.RevokedKmsContext]: false, // the retry already re-granted; a blind retry re-hits the stale validity cache\n [ZamaErrorCode.NoCiphertext]: false,\n [ZamaErrorCode.RelayerRequestFailed]: false, // conditional — see doc above\n [ZamaErrorCode.NotEntitled]: false,\n [ZamaErrorCode.RpcRateLimited]: true,\n [ZamaErrorCode.Configuration]: false,\n [ZamaErrorCode.DelegationSelfNotAllowed]: false,\n [ZamaErrorCode.DelegationCooldown]: true, // per-block timing gate, resolves on next-block retry\n [ZamaErrorCode.DelegationNotFound]: false,\n [ZamaErrorCode.DelegationExpired]: false,\n [ZamaErrorCode.InsufficientConfidentialBalance]: false,\n [ZamaErrorCode.InsufficientERC20Balance]: false,\n [ZamaErrorCode.InsufficientAllowance]: false, // terminal: caller must approve a larger allowance\n [ZamaErrorCode.BalanceCheckUnavailable]: false,\n [ZamaErrorCode.ERC20ReadFailed]: false, // conservative: conflates network (transient) and contract (terminal) faults, see class doc\n [ZamaErrorCode.DelegationExpiryUnchanged]: false,\n [ZamaErrorCode.DelegationDelegateEqualsContract]: false,\n [ZamaErrorCode.DelegationDelegateCannotBeWildcard]: false,\n [ZamaErrorCode.DelegationContractIsSelf]: false,\n [ZamaErrorCode.AclPaused]: false,\n [ZamaErrorCode.DelegationExpirationTooSoon]: false,\n [ZamaErrorCode.DelegationNotPropagated]: true,\n [ZamaErrorCode.ChainMismatch]: false,\n [ZamaErrorCode.SignerNotConfigured]: false,\n [ZamaErrorCode.WalletNotConnected]: false,\n [ZamaErrorCode.WalletAccountNotReady]: true, // async wallet-account discovery still resolving\n [ZamaErrorCode.KeyWrappingFailed]: false, // a transportKeyPairDerivationSecret mismatch or environment capability issue, not transient\n [ZamaErrorCode.TransportKeyPairChanged]: false, // caller must prepare the permit again against the current key pair\n [ZamaErrorCode.PreparedPermitChainMismatch]: false, // caller must register against the chain the permit was prepared for\n [ZamaErrorCode.PreparedPermitExpired]: false, // caller must prepare the permit again for a fresh validity window\n [ZamaErrorCode.UnshieldAlreadyFinalized]: false, // the funds already arrived; the stale pointer is cleared\n [ZamaErrorCode.VaultBatcherPaused]: false, // stays paused until the batcher is unpaused, not on retry\n [ZamaErrorCode.VaultBatchNotDispatched]: false, // a settled batch stays settled; a pending one waits for its dispatch\n [ZamaErrorCode.VaultJoinUnconfirmed]: false, // the transaction is mined; a retry would submit another\n};\n\n/**\n * Base error thrown by all SDK operations.\n * Carries a {@link ZamaErrorCode} for programmatic error handling.\n * Prefer catching specific subclasses (e.g. {@link EncryptionFailedError}).\n */\nexport class ZamaError extends Error {\n /** Machine-readable error code. */\n readonly code: ZamaErrorCode;\n\n /**\n * Whether the operation that threw this error is safe to retry. Defaults to\n * {@link RETRYABLE_BY_CODE}'s entry for `code`; only {@link RelayerRequestFailedError}\n * overrides it per-instance (its retryability depends on the HTTP status).\n * Prefer {@link isRetryable} over reading this directly, so a new `unknown`\n * caught value doesn't need an `instanceof ZamaError` check first.\n */\n readonly retryable: boolean;\n\n constructor(\n code: ZamaErrorCode,\n message: string,\n options?: ErrorOptions & { retryable?: boolean },\n ) {\n super(message, options);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"ZamaError\";\n this.code = code;\n this.retryable = options?.retryable ?? RETRYABLE_BY_CODE[code];\n }\n}\n\n/**\n * True if `error` is a {@link ZamaError} whose failure is transient and safe to\n * retry (rate-limited, back-pressured, a delegation still propagating or in\n * its per-block cooldown, or a wallet account still resolving).\n * Compiler-guaranteed to stay in sync with the\n * taxonomy: every {@link ZamaError} subclass declares its own retryability via\n * {@link ZamaError.retryable}, so a consumer never has to hardcode a set of\n * retryable codes.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (isRetryable(e)) {\n * // back off and retry (see retryAfterSeconds for a server-suggested delay)\n * } else {\n * throw e; // terminal — surface it\n * }\n * }\n * ```\n */\nexport function isRetryable(error: unknown): error is ZamaError & { retryable: true } {\n return error instanceof ZamaError && error.retryable;\n}\n\n/**\n * The server-suggested retry delay, in **seconds**, for a retryable\n * {@link ZamaError} — unifying the `retryAfter` field that today lives on\n * {@link RelayerRequestFailedError} and {@link RpcRateLimitError} only.\n * `undefined` when the error isn't retryable, or is retryable but carries no\n * server-driven delay (e.g. {@link DelegationNotPropagatedError} — retry that\n * with your own backoff).\n */\nexport function retryAfterSeconds(error: unknown): number | undefined {\n if (!isRetryable(error) || !(\"retryAfter\" in error)) {\n return undefined;\n }\n const retryAfter = (error as ZamaError & { retryAfter?: unknown }).retryAfter;\n return isValidRetryAfterSeconds(retryAfter) ? retryAfter : undefined;\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Relayer HTTP request failed. */\nexport class RelayerRequestFailedError extends ZamaError {\n /** HTTP status code from the relayer, if available. */\n readonly statusCode: number | undefined;\n\n /**\n * Server-driven retry delay in **seconds** (the SDK's duration unit and the\n * header's own unit), from the relayer's `Retry-After` header. Set only on\n * back-pressure (HTTP 429) responses that carry the header; `undefined`\n * otherwise. Implies {@link ZamaError.retryable}.\n */\n readonly retryAfter: number | undefined;\n\n constructor(\n message: string,\n statusCode?: number,\n options?: ErrorOptions & { retryAfter?: number; retryable?: boolean },\n ) {\n // Retryable on relayer back-pressure (HTTP 429) by default, or when the\n // caller forces it (a relayer timeout has no status but is safe to retry).\n const retryable = options?.retryable ?? statusCode === 429;\n super(ZamaErrorCode.RelayerRequestFailed, message, { ...options, retryable });\n this.name = \"RelayerRequestFailedError\";\n this.statusCode = statusCode;\n // Keep the two fields consistent: a delay only makes sense when retryable,\n // and only a 429 actually carries a server-supplied `Retry-After`.\n this.retryAfter = retryable ? options?.retryAfter : undefined;\n }\n}\n\n/** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\nexport class ConfigurationError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.Configuration, message, options);\n this.name = \"ConfigurationError\";\n }\n}\n"],"mappings":"AACA,SAAgBA,EAAQ,EAAuB,CAO7C,OANIC,aAAiB,MACZA,EAEL,OAAOA,GAAU,UAAYA,GAAkB,YAAaA,EACnD,MAAM,OAAOA,EAAM,OAAO,CAAC,EAE7B,MAAM,OAAOA,CAAK,CAAC,CAChC,CAOA,SAAgBC,EAAoB,EAAyB,CAC3D,GAAI,EAAED,aAAiB,OACrB,MAAO,GAUT,GANEA,EAAM,OAAS,kCACfA,EAAM,OAAS,iCAKb,SAAUA,GAASA,EAAM,OAAS,iBACpC,MAAO,GAGT,IAAME,EAAMF,EAAM,QAAQ,YAAY,EACtC,OAAOE,EAAI,SAAS,oBAAoB,GAAKA,EAAI,SAAS,uBAAuB,CACnF,CAGA,MAGMC,EAAoB,CAAC,QAAS,QAAS,MAAM,EAQnD,SAASC,EACP,EACA,EACA,EAAQ,EAC6B,CACrC,GAAIC,E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E,KAAK,KAAO,4BACZ,KAAK,WAAaO,EAGlB,KAAK,WAAaD,EAAYN,GAAS,WAAa,IAAA,EACtD,CACF,EAGaQ,EAAb,cAAwCT,CAAU,CAChD,YAAY,EAAiB,EAAwB,CACnD,MAAMF,EAAc,cAAe3B,EAAS8B,CAAO,EACnD,KAAK,KAAO,oBACd,CACF,E"}
|
|
1
|
+
{"version":3,"file":"relayer.cjs","names":["toError","error","isContractCallError","findInErrorChain","nodeIsContractRevert","node","msg","NESTED_ERROR_KEYS","depth","predicate","key","next","found","nodeHasStructuredRateLimit","responseStatus","nodeIsRpcRateLimit","isRelayerError","isRelayerTimeoutError","isRpcRateLimitError","hasStructuredRpcRateLimitSignal","isNotEntitledMessage","message","isInvalidTransportKeyPairMessage","REVERT_DATA_KEYS","nodeHasRevert","value","selector","name","hasRevert","lowerSelector","lowerName","isRevokedKmsContextError","parseHandleFromMessage","parseRetryAfterHeader","trimmed","dateMs","readRetryAfterHeader","headers","get","retryAfterFromHeader","response","isValidRetryAfterSeconds","retryAfterFromNode","extractRetryAfter","n","extractHttpStatus","extractRpcErrorCode","extractWalletErrorName","ZamaErrorCode","RETRYABLE_BY_CODE","ZamaError","options","code","isRetryable","retryAfterSeconds","retryAfter","RelayerRequestFailedError","retryable","statusCode","ConfigurationError"],"sources":["../../src/utils/error.ts","../../src/errors/base.ts","../../src/errors/relayer.ts"],"sourcesContent":["/** Coerce an unknown caught value to an Error instance. */\nexport function toError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n return new Error(String(error.message));\n }\n return new Error(String(error));\n}\n\n/**\n * Returns true if the error is a contract call revert (as opposed to a network/transport error).\n * Looks through the cause chain, since viem wraps every `readContract` failure, transport ones\n * included, in a `ContractFunctionExecutionError`.\n */\nexport function isContractCallError(error: unknown): boolean {\n return findInErrorChain(error, nodeIsContractRevert) !== undefined;\n}\n\nfunction nodeIsContractRevert(node: Record<string, unknown>): boolean {\n if (\n node.name === \"ContractFunctionRevertedError\" ||\n node.name === \"ContractFunctionZeroDataError\" ||\n node.code === \"CALL_EXCEPTION\"\n ) {\n return true;\n }\n // Fallback: common revert message patterns from various providers\n if (typeof node.message !== \"string\") {\n return false;\n }\n const msg = node.message.toLowerCase();\n return msg.includes(\"execution reverted\") || msg.includes(\"call revert exception\");\n}\n\n/** JSON-RPC error code providers use for rate limiting (\"limit exceeded\"). */\nconst JSON_RPC_LIMIT_EXCEEDED = -32005;\n\n/** Properties that may nest a lower-level cause across viem / ethers / fetch. */\nconst NESTED_ERROR_KEYS = [\"cause\", \"error\", \"info\"] as const;\n\n/**\n * Walk an error and its nested causes (`cause` / `error` / `info`, as used by\n * viem, ethers, and fetch wrappers), applying `predicate` to each object node.\n * Returns the first node for which `predicate` returns true, or `undefined`.\n * Depth-bounded to avoid pathological / cyclic structures.\n */\nfunction findInErrorChain(\n error: unknown,\n predicate: (node: Record<string, unknown>) => boolean,\n depth = 6,\n): Record<string, unknown> | undefined {\n if (depth < 0 || error === null || error === undefined || typeof error !== \"object\") {\n return undefined;\n }\n const node = error as Record<string, unknown>;\n if (predicate(node)) {\n return node;\n }\n for (const key of NESTED_ERROR_KEYS) {\n const next = node[key];\n if (next !== undefined && next !== null && typeof next === \"object\") {\n const found = findInErrorChain(next, predicate, depth - 1);\n if (found) {\n return found;\n }\n }\n }\n return undefined;\n}\n\n// ============================================================================\n// Classification detectors\n// ============================================================================\n\n/**\n * Structured (unambiguous) consumer rate-limit signal across the RPC providers\n * the SDK reads through:\n * - JSON-RPC `-32005` (\"limit exceeded\");\n * - viem-style numeric `status: 429`, and viem's own `shouldRetry` shape where\n * the JSON-RPC error `code` is `429`;\n * - ethers' 429, which surfaces as `code: \"SERVER_ERROR\"` with the status only\n * in `info.responseStatus` (a string like `\"429 Too Many Requests\"`) and no\n * numeric top-level status — the leading code is parsed out of it.\n *\n * Deliberately NOT `statusCode: 429` — that is the relayer / node-fetch HTTP\n * shape, which stays {@link RelayerRequestFailedError} (SDK-236), so a relayer\n * 429 is never mistaken for a consumer-RPC throttle.\n */\nfunction nodeHasStructuredRateLimit(node: Record<string, unknown>): boolean {\n if (node.code === JSON_RPC_LIMIT_EXCEEDED || node.status === 429 || node.code === 429) {\n return true;\n }\n // ethers: `code: \"SERVER_ERROR\"`, status lives in `info.responseStatus`.\n if (node.code === \"SERVER_ERROR\" && typeof node.info === \"object\" && node.info !== null) {\n const responseStatus = (node.info as Record<string, unknown>).responseStatus;\n if (typeof responseStatus === \"string\" && /^\\s*429\\b/.test(responseStatus)) {\n return true;\n }\n }\n return false;\n}\n\nfunction nodeIsRpcRateLimit(node: Record<string, unknown>): boolean {\n if (nodeHasStructuredRateLimit(node)) {\n return true;\n }\n // Message fallback for providers without a structured code. Deliberately\n // narrow (specific throttling phrases, no bare \"429\") to avoid false positives\n // that would turn a terminal error into a retryable one.\n if (typeof node.message === \"string\") {\n const msg = node.message.toLowerCase();\n return (\n msg.includes(\"too many requests\") || msg.includes(\"rate limit\") || msg.includes(\"rate-limit\")\n );\n }\n return false;\n}\n\n/**\n * True when a failure originates from `@fhevm/sdk`'s relayer transport. Every\n * relayer error it throws — `RelayerResponseStatusError`, `RelayerResponseApiError`,\n * `RelayerMaxRetryError`, `RelayerTimeoutError`, … — carries the `Relayer` `name`\n * prefix. Such errors stay the relayer's domain ({@link RelayerRequestFailedError}\n * / SDK-236), never {@link RpcRateLimitError}, even on a 429 (which `@fhevm/sdk`\n * retries internally, honoring `Retry-After`, before surfacing).\n */\nexport function isRelayerError(error: unknown): boolean {\n return (\n findInErrorChain(\n error,\n (node) => typeof node.name === \"string\" && node.name.startsWith(\"Relayer\"),\n ) !== undefined\n );\n}\n\n/**\n * True when the failure is an `@fhevm/sdk` relayer *timeout* (`RelayerTimeoutError`,\n * thrown when a request exceeds the relayer's global deadline without a verdict).\n * Unlike a terminal 4xx/5xx, the operation itself is safe to retry, so callers map\n * it to a {@link RelayerRequestFailedError} with `retryable: true` — mirroring the\n * former `WorkerTimeoutError`, which was likewise documented retryable.\n */\nexport function isRelayerTimeoutError(error: unknown): boolean {\n return findInErrorChain(error, (node) => node.name === \"RelayerTimeoutError\") !== undefined;\n}\n\n/**\n * True if the error is the consumer's RPC provider throttling an on-chain read\n * (HTTP 429 / JSON-RPC -32005). Relayer-originated 429s are excluded.\n */\nexport function isRpcRateLimitError(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeIsRpcRateLimit) !== undefined;\n}\n\n/**\n * Like {@link isRpcRateLimitError} but only matches an unambiguous **structured**\n * signal (`-32005` or a viem `status: 429`), ignoring message text. The classifier\n * promotes this ahead of any HTTP status, while a message-only throttle is only\n * trusted when no status is present — so a relayer HTTP error whose body happens\n * to say \"rate limit\" still maps to {@link RelayerRequestFailedError}.\n */\nexport function hasStructuredRpcRateLimitSignal(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeHasStructuredRateLimit) !== undefined;\n}\n\n/**\n * Transport-error signatures of the consumer's own RPC client (viem / ethers).\n * The SDK's on-chain reads (the ACL `persistAllowed` pre-check) go through that\n * client, which already retries transport faults internally — so a failure\n * carrying one of these shapes must NOT be retried again by the SDK on top.\n */\nfunction nodeHasConsumerRpcSignature(node: Record<string, unknown>): boolean {\n // ethers transient transport codes.\n const code = node.code;\n if (code === \"NETWORK_ERROR\" || code === \"SERVER_ERROR\" || code === \"TIMEOUT\") {\n return true;\n }\n // viem transport error classes, matched by `name`.\n const name = node.name;\n return (\n name === \"HttpRequestError\" ||\n name === \"RpcRequestError\" ||\n name === \"TimeoutError\" ||\n name === \"WebSocketRequestError\"\n );\n}\n\n/**\n * True when a failure originates from the **consumer's RPC provider** (viem /\n * ethers) rather than the relayer. Keeps the SDK's relayer retry from\n * double-retrying transport faults the integrator's client already retried.\n * A relayer error (`Relayer*`) is never consumer-RPC.\n */\nexport function isConsumerRpcError(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n if (hasStructuredRpcRateLimitSignal(error)) {\n return true;\n }\n return findInErrorChain(error, nodeHasConsumerRpcSignature) !== undefined;\n}\n\n/**\n * `@fhevm/sdk`'s ACL gate (`checkPersistAllowed`) throws an `AclUserDecryptionError`\n * when the requesting actor isn't allowed: `User <a> is not authorized to decrypt\n * handle <h>!`. Matching that phrase is what lets {@link wrapDecryptError} surface\n * a typed NotEntitledError with the parsed handle.\n *\n * Deliberately excludes the sibling `Dapp contract <a> is not authorized to\n * **user** decrypt handle <h>!` — a dapp ACL misconfig, intentionally left to\n * DecryptionFailedError. The differentiator is the inserted \"user\": the actor\n * message reads \"…to decrypt handle\", the dapp message \"…to user decrypt handle\",\n * so keying on \"is not authorized to decrypt handle\" matches only the former.\n *\n * The `error.test.ts` drift guard reads the installed `@fhevm/sdk` source and\n * fails loudly if the message is reworded.\n */\nexport function isNotEntitledMessage(message: string): boolean {\n return message.toLowerCase().includes(\"is not authorized to decrypt handle\");\n}\n\n/**\n * `@fhevm/sdk`'s `verifyTkmsPublicKey` throws `invalid TransportKeyPairKeyPair`\n * when a stored transport key pair can't be re-derived under the current TKMS\n * version — the signal that the persisted key pair is stale (typically after a\n * KMS/TKMS rotation) and must be evicted and regenerated. Matching it lets the\n * signing and decrypt paths surface a typed {@link InvalidTransportKeyPairError}\n * and self-heal the vault entry.\n */\nexport function isInvalidTransportKeyPairMessage(message: string): boolean {\n return message.toLowerCase().includes(\"invalid transportkeypair\");\n}\n\n/**\n * 4-byte selector of `InvalidKmsContext(uint256)`, the revert ProtocolConfig\n * raises when the KMS signers read resolves an unknown or revoked context.\n * The `error.test.ts` drift guard recomputes it from the Solidity signature.\n */\nexport const INVALID_KMS_CONTEXT_SELECTOR = \"0x77ddbe81\";\n\n/** Revert-data fields across clients: viem's `raw`/`signature`, ethers' `data`. */\nconst REVERT_DATA_KEYS = [\"data\", \"raw\", \"signature\"] as const;\n\nfunction nodeHasRevert(node: Record<string, unknown>, selector: string, name: string): boolean {\n for (const key of REVERT_DATA_KEYS) {\n const value = node[key];\n if (typeof value === \"string\" && value.toLowerCase().startsWith(selector)) {\n return true;\n }\n }\n // Text-only fallback for wrappers that stringify the revert instead of\n // carrying the data fields above.\n if (typeof node.message === \"string\") {\n const msg = node.message.toLowerCase();\n return msg.includes(selector) || msg.includes(name);\n }\n return false;\n}\n\n/**\n * True when `error` or any nested cause reverts with the custom error\n * `selector`, or names the error in its message for providers that only\n * stringify the revert. Needs no ABI.\n */\nexport function hasRevert(error: unknown, selector: string, name: string): boolean {\n const lowerSelector = selector.toLowerCase();\n const lowerName = name.toLowerCase();\n return (\n findInErrorChain(error, (node) => nodeHasRevert(node, lowerSelector, lowerName)) !== undefined\n );\n}\n\n/**\n * True when a failure is the on-chain KMS signers read reverting with\n * `InvalidKmsContext`: the permit's KMS context has been revoked (or never\n * existed), so every permit signed under it is permanently dead. The decrypt\n * path uses this to evict the permit and re-grant under the current context.\n *\n * The installed `@fhevm/sdk` performs that read without the error in its ABI,\n * so the revert arrives as raw data; the selector is matched anywhere in the\n * cause chain, with a message fallback for text-only providers.\n */\nexport function isRevokedKmsContextError(error: unknown): boolean {\n return hasRevert(error, INVALID_KMS_CONTEXT_SELECTOR, \"InvalidKmsContext\");\n}\n\n/** Parse the on-chain handle out of the not-entitled message. */\nexport function parseHandleFromMessage(message: string): string | undefined {\n return /handle (0x[0-9a-fA-F]{64})/.exec(message)?.[1];\n}\n\n/**\n * Parse an HTTP `Retry-After` header value into **seconds** (the SDK's duration\n * unit and the header's own unit), or `undefined` when absent/unparseable. Per\n * RFC 9110 the value is either a non-negative number of seconds (`\"120\"`) or an\n * HTTP-date; a past date floors to `0`.\n */\nexport function parseRetryAfterHeader(value: string | null | undefined): number | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n const trimmed = value.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n // delta-seconds: a non-negative integer (already the unit we want).\n if (/^\\d+$/.test(trimmed)) {\n return Number(trimmed);\n }\n // HTTP-date — an IMF-fixdate always carries alphabetic day/month names, so\n // require a letter before deferring to the lenient Date.parse.\n if (/[a-zA-Z]/.test(trimmed)) {\n const dateMs = Date.parse(trimmed);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, Math.round((dateMs - Date.now()) / 1000));\n }\n }\n return undefined;\n}\n\n/** Read a `Retry-After` header (→ seconds) off a `Headers`-like object, if present. */\nexport function readRetryAfterHeader(headers: unknown): number | undefined {\n if (headers === null || typeof headers !== \"object\") {\n return undefined;\n }\n const get = (headers as { get?: unknown }).get;\n if (typeof get !== \"function\") {\n return undefined;\n }\n return parseRetryAfterHeader(\n (get as (name: string) => string | null).call(headers, \"Retry-After\"),\n );\n}\n\n/**\n * A node's **relayer** `Retry-After` header (seconds), read from a wrapped fetch\n * `Response` (the relayer's `cause.response.headers`). The SDK owns the\n * relayer fetch, so parsing the header there is legitimate.\n *\n * The viem/chain side (`HttpRequestError.headers`) is deliberately **not** read:\n * for consumer RPC the integrator's viem/ethers transport already honors\n * `Retry-After` in its own retry loop (and retries) before the error ever\n * surfaces, so re-reading it here would re-implement a transport concern.\n * Chain-RPC backoff is configured on the consumer's transport (`chain.network`).\n */\nfunction retryAfterFromHeader(node: Record<string, unknown>): number | undefined {\n const response = node.response;\n if (response !== null && typeof response === \"object\") {\n return readRetryAfterHeader((response as Record<string, unknown>).headers);\n }\n return undefined;\n}\n\n/**\n * True for a well-formed server-driven retry delay, in seconds: a finite,\n * positive number. Shared by the chain-walking extractor below and the public\n * {@link retryAfterSeconds} accessor (`errors/base.ts`), so a malformed value\n * (`0`, negative, `NaN`) is rejected the same way everywhere instead of being\n * handed unchanged to a `setTimeout` backoff.\n */\nexport function isValidRetryAfterSeconds(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0;\n}\n\n/**\n * A single node's server-driven retry delay (seconds): a numeric `retryAfter`\n * (a non-positive synthetic value is ignored), else a `Retry-After` header.\n */\nfunction retryAfterFromNode(node: Record<string, unknown>): number | undefined {\n if (isValidRetryAfterSeconds(node.retryAfter)) {\n return node.retryAfter;\n }\n return retryAfterFromHeader(node);\n}\n\n/**\n * Best-effort extraction of a server-driven retry delay, in **seconds**, from\n * anywhere in an error's cause chain. Reads a numeric `retryAfter` property and\n * the **relayer's** `Retry-After` header (`cause.response.headers`). The\n * consumer-RPC/chain side is intentionally not read — viem/ethers own that\n * backoff (see {@link retryAfterFromHeader}). `undefined` when absent.\n */\nexport function extractRetryAfter(error: unknown): number | undefined {\n const node = findInErrorChain(error, (n) => retryAfterFromNode(n) !== undefined);\n return node ? retryAfterFromNode(node) : undefined;\n}\n\n/**\n * Extract an HTTP status code from an error or anywhere in its cause chain.\n * Relayer SDK errors may carry a `status` or `statusCode` property; walking the\n * full chain (rather than just depth-1) keeps this in step with the other\n * chain-walking detectors and avoids a depth asymmetry between them.\n */\nexport function extractHttpStatus(error: unknown): number | undefined {\n const node = findInErrorChain(\n error,\n (n) => typeof n.statusCode === \"number\" || typeof n.status === \"number\",\n );\n if (!node) {\n return undefined;\n }\n return (typeof node.statusCode === \"number\" ? node.statusCode : node.status) as number;\n}\n\n/**\n * A JSON-RPC / EIP-1193 numeric error code (e.g. `4001` for user rejection, or a\n * wallet/provider code like `-32603`) found anywhere in a signing failure's cause\n * chain. Gives a signing error a structured, groupable field instead of leaving\n * the code buried in free-text `message` or an opaque nested `cause`.\n *\n * Skips `-1`: viem's own `UnknownRpcError` fallback code for errors it can't\n * classify, not an RPC-provided code. Reporting it as `rpcCode` would read as\n * a real (if odd) wallet error code, so the chain walk continues past it in\n * case a real code is nested deeper (e.g. in `cause`).\n */\nexport function extractRpcErrorCode(error: unknown): number | undefined {\n const node = findInErrorChain(error, (n) => typeof n.code === \"number\" && n.code !== -1);\n return node ? (node.code as number) : undefined;\n}\n\n/**\n * The `name` of the error class a signing failure was thrown as (e.g. viem's\n * `InvalidParamsRpcError`, an EIP-1193 `ProviderRpcError`) — a stable,\n * library-level classification an observability integration can group and alert\n * on. Deliberately reads only the top-level error, not the full cause chain: a\n * wallet's own internal error class name is inconsistent across wallets and\n * buried at an arbitrary depth, so it is not guessed at here — the full chain\n * remains available via the wrapped error's `cause` for manual inspection.\n */\nexport function extractWalletErrorName(error: unknown): string | undefined {\n return error instanceof Error && error.name !== \"Error\" ? error.name : undefined;\n}\n","import { isValidRetryAfterSeconds } from \"../utils/error\";\n\n/**\n * Typed error codes thrown by the SDK.\n * Use `error.code` or `instanceof` to programmatically handle specific failure modes.\n *\n * @example\n * ```ts\n * try {\n * await token.confidentialTransfer(\"0xTo\", 100n);\n * } catch (e) {\n * if (e instanceof SigningRejectedError) {\n * // User rejected the wallet signature\n * }\n * }\n * ```\n */\nexport const ZamaErrorCode = {\n /** User rejected the wallet signature prompt. */\n SigningRejected: \"SIGNING_REJECTED\",\n /** Wallet signature failed for a reason other than rejection. */\n SigningFailed: \"SIGNING_FAILED\",\n /** FHE encryption failed. */\n EncryptionFailed: \"ENCRYPTION_FAILED\",\n /** FHE decryption failed. */\n DecryptionFailed: \"DECRYPTION_FAILED\",\n /** Encryption offload was required (`offloadEncrypt: true`) but the worker is unavailable. */\n EncryptOffloadUnavailable: \"ENCRYPT_OFFLOAD_UNAVAILABLE\",\n /** On-chain transaction reverted. */\n TransactionReverted: \"TRANSACTION_REVERTED\",\n /** The block's FHE compute budget (HCU) is spent. Retryable: it resets every block. */\n HcuBlockLimitExceeded: \"HCU_BLOCK_LIMIT_EXCEEDED\",\n /** The transaction needs more FHE compute (HCU) than one transaction may use. */\n HcuTransactionLimitExceeded: \"HCU_TRANSACTION_LIMIT_EXCEEDED\",\n /** Transport key pair has expired and needs regeneration. */\n TransportKeyPairExpired: \"KEYPAIR_EXPIRED\",\n /** Relayer rejected transport key pair (stale, expired, or malformed). */\n InvalidTransportKeyPair: \"INVALID_KEYPAIR\",\n /** The permit's KMS context was revoked on-chain; the SDK's evict-and-regrant retry also failed. */\n RevokedKmsContext: \"REVOKED_KMS_CONTEXT\",\n /** No FHE ciphertext exists for this account (never shielded). */\n NoCiphertext: \"NO_CIPHERTEXT\",\n /** Relayer HTTP request failed. */\n RelayerRequestFailed: \"RELAYER_REQUEST_FAILED\",\n /** The configured signer/account is not entitled (ACL) to decrypt this encrypted value. Don't retry — wait for a grant. */\n NotEntitled: \"NOT_ENTITLED\",\n /** The consumer's RPC provider rate-limited an on-chain read (e.g. HTTP 429 / JSON-RPC -32005). Retryable. */\n RpcRateLimited: \"RPC_RATE_LIMITED\",\n /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\n Configuration: \"CONFIGURATION\",\n /** Delegation cannot target self (delegate === msg.sender). */\n DelegationSelfNotAllowed: \"DELEGATION_SELF_NOT_ALLOWED\",\n /** Only one delegate/revoke per (delegator, delegate, contract) per block. */\n DelegationCooldown: \"DELEGATION_COOLDOWN\",\n /** No active delegation found for this (delegator, delegate, contract) tuple. */\n DelegationNotFound: \"DELEGATION_NOT_FOUND\",\n /** The delegation has expired. */\n DelegationExpired: \"DELEGATION_EXPIRED\",\n /** Confidential (cToken) balance is insufficient for the requested operation. */\n InsufficientConfidentialBalance: \"INSUFFICIENT_CONFIDENTIAL_BALANCE\",\n /** ERC-20 balance is insufficient for the requested shield amount. */\n InsufficientERC20Balance: \"INSUFFICIENT_ERC20_BALANCE\",\n /** ERC-20 allowance granted to the wrapper is insufficient for the requested wrap amount. */\n InsufficientAllowance: \"INSUFFICIENT_ALLOWANCE\",\n /** Balance validation could not be performed (no cached credentials and decryption not possible). */\n BalanceCheckUnavailable: \"BALANCE_CHECK_UNAVAILABLE\",\n /** Public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\n ERC20ReadFailed: \"ERC20_READ_FAILED\",\n /** The new expiration date equals the current one — no on-chain change needed. */\n DelegationExpiryUnchanged: \"DELEGATION_EXPIRY_UNCHANGED\",\n /** Delegate address cannot be the contract address. */\n DelegationDelegateEqualsContract: \"DELEGATION_DELEGATE_EQUALS_CONTRACT\",\n /** Delegate address cannot be the wildcard address — it's only valid as `contractAddress`. */\n DelegationDelegateCannotBeWildcard: \"DELEGATION_DELEGATE_CANNOT_BE_WILDCARD\",\n /** Contract address cannot be the sender address. */\n DelegationContractIsSelf: \"DELEGATION_CONTRACT_IS_SELF\",\n /** The ACL contract is paused. */\n AclPaused: \"ACL_PAUSED\",\n /** Expiration date is too soon (must be at least 1 hour in the future). */\n DelegationExpirationTooSoon: \"DELEGATION_EXPIRATION_TOO_SOON\",\n /** Delegation exists on-chain but hasn't propagated to the gateway yet. */\n DelegationNotPropagated: \"DELEGATION_NOT_PROPAGATED\",\n /** Signer and provider are connected to different chains. */\n ChainMismatch: \"CHAIN_MISMATCH\",\n /** Operation requires a signer but none is configured. */\n SignerNotConfigured: \"SIGNER_NOT_CONFIGURED\",\n /** Operation requires a connected wallet account. */\n WalletNotConnected: \"WALLET_NOT_CONNECTED\",\n /** Wallet account discovery is still resolving. */\n WalletAccountNotReady: \"WALLET_ACCOUNT_NOT_READY\",\n /** Wrapping or unwrapping the transport private key with `transportKeyPairDerivationSecret` failed. */\n KeyWrappingFailed: \"KEY_WRAPPING_FAILED\",\n /** The transport key pair changed between `preparePermit` and `registerPermit`. */\n TransportKeyPairChanged: \"TRANSPORT_KEY_PAIR_CHANGED\",\n /** A prepared permit's `chainId` does not match the chain `registerPermit` is running against. */\n PreparedPermitChainMismatch: \"PREPARED_PERMIT_CHAIN_MISMATCH\",\n /** A prepared permit's validity window elapsed before its signature was registered. */\n PreparedPermitExpired: \"PREPARED_PERMIT_EXPIRED\",\n /** The unwrap request was already finalized on-chain; there is nothing left to resume. */\n UnshieldAlreadyFinalized: \"UNSHIELD_ALREADY_FINALIZED\",\n /** No batcher of a vault is open: each one is paused or closed. */\n VaultBatcherPaused: \"VAULT_BATCHER_PAUSED\",\n /** A batcher of a vault could not be read, so the batch a join reaches is unknown. */\n VaultBatcherReadFailed: \"VAULT_BATCHER_READ_FAILED\",\n /** A batch to be finalized is not dispatched. */\n VaultBatchNotDispatched: \"VAULT_BATCH_NOT_DISPATCHED\",\n /** A vault join was mined, but its receipt does not confirm every leg. */\n VaultJoinUnconfirmed: \"VAULT_JOIN_UNCONFIRMED\",\n} as const;\n\n/** Union of all {@link ZamaErrorCode} string values. */\nexport type ZamaErrorCode = (typeof ZamaErrorCode)[keyof typeof ZamaErrorCode];\n\n/** Identity type that fails to instantiate unless `T` maps every {@link ZamaErrorCode} to a `boolean`. */\ntype Complete<T extends Record<ZamaErrorCode, boolean>> = T;\n\n/**\n * Default retryability for each {@link ZamaErrorCode}. `Complete` fails the build\n * if a new code is added without an entry here — the same exhaustiveness guard\n * `matchZamaError`'s `ErrorForCode` map uses (see `match.ts`) — so a new\n * transient (or terminal) cause can't silently default to the wrong signal.\n *\n * {@link RelayerRequestFailedError} and `VaultBatcherReadFailedError` are the\n * exceptions. The first depends on the HTTP status (only a 429 is retryable),\n * the second on its cause, so both override this default via the constructor's\n * `retryable` option instead of being read from here.\n */\nconst RETRYABLE_BY_CODE: Complete<Record<ZamaErrorCode, boolean>> = {\n [ZamaErrorCode.SigningRejected]: false,\n [ZamaErrorCode.SigningFailed]: false,\n [ZamaErrorCode.EncryptionFailed]: false,\n [ZamaErrorCode.DecryptionFailed]: false,\n [ZamaErrorCode.EncryptOffloadUnavailable]: false, // the worker realm is unusable for this page; a retry hits the same environment\n [ZamaErrorCode.TransactionReverted]: false,\n [ZamaErrorCode.HcuBlockLimitExceeded]: true, // the block budget resets every block\n [ZamaErrorCode.HcuTransactionLimitExceeded]: false, // the same transaction costs the same HCU on every retry\n [ZamaErrorCode.TransportKeyPairExpired]: false,\n [ZamaErrorCode.InvalidTransportKeyPair]: false,\n [ZamaErrorCode.RevokedKmsContext]: false, // the retry already re-granted; a blind retry re-hits the stale validity cache\n [ZamaErrorCode.NoCiphertext]: false,\n [ZamaErrorCode.RelayerRequestFailed]: false, // conditional — see doc above\n [ZamaErrorCode.NotEntitled]: false,\n [ZamaErrorCode.RpcRateLimited]: true,\n [ZamaErrorCode.Configuration]: false,\n [ZamaErrorCode.DelegationSelfNotAllowed]: false,\n [ZamaErrorCode.DelegationCooldown]: true, // per-block timing gate, resolves on next-block retry\n [ZamaErrorCode.DelegationNotFound]: false,\n [ZamaErrorCode.DelegationExpired]: false,\n [ZamaErrorCode.InsufficientConfidentialBalance]: false,\n [ZamaErrorCode.InsufficientERC20Balance]: false,\n [ZamaErrorCode.InsufficientAllowance]: false, // terminal: caller must approve a larger allowance\n [ZamaErrorCode.BalanceCheckUnavailable]: false,\n [ZamaErrorCode.ERC20ReadFailed]: false, // conservative: conflates network (transient) and contract (terminal) faults, see class doc\n [ZamaErrorCode.DelegationExpiryUnchanged]: false,\n [ZamaErrorCode.DelegationDelegateEqualsContract]: false,\n [ZamaErrorCode.DelegationDelegateCannotBeWildcard]: false,\n [ZamaErrorCode.DelegationContractIsSelf]: false,\n [ZamaErrorCode.AclPaused]: false,\n [ZamaErrorCode.DelegationExpirationTooSoon]: false,\n [ZamaErrorCode.DelegationNotPropagated]: true,\n [ZamaErrorCode.ChainMismatch]: false,\n [ZamaErrorCode.SignerNotConfigured]: false,\n [ZamaErrorCode.WalletNotConnected]: false,\n [ZamaErrorCode.WalletAccountNotReady]: true, // async wallet-account discovery still resolving\n [ZamaErrorCode.KeyWrappingFailed]: false, // a transportKeyPairDerivationSecret mismatch or environment capability issue, not transient\n [ZamaErrorCode.TransportKeyPairChanged]: false, // caller must prepare the permit again against the current key pair\n [ZamaErrorCode.PreparedPermitChainMismatch]: false, // caller must register against the chain the permit was prepared for\n [ZamaErrorCode.PreparedPermitExpired]: false, // caller must prepare the permit again for a fresh validity window\n [ZamaErrorCode.UnshieldAlreadyFinalized]: false, // the funds already arrived; the stale pointer is cleared\n [ZamaErrorCode.VaultBatcherPaused]: false, // stays paused until the batcher is unpaused, not on retry\n [ZamaErrorCode.VaultBatcherReadFailed]: false, // conditional: see doc above\n [ZamaErrorCode.VaultBatchNotDispatched]: false, // a settled batch stays settled; a pending one waits for its dispatch\n [ZamaErrorCode.VaultJoinUnconfirmed]: false, // the transaction is mined; a retry would submit another\n};\n\n/**\n * Base error thrown by all SDK operations.\n * Carries a {@link ZamaErrorCode} for programmatic error handling.\n * Prefer catching specific subclasses (e.g. {@link EncryptionFailedError}).\n */\nexport class ZamaError extends Error {\n /** Machine-readable error code. */\n readonly code: ZamaErrorCode;\n\n /**\n * Whether the operation that threw this error is safe to retry. Defaults to\n * {@link RETRYABLE_BY_CODE}'s entry for `code`; {@link RelayerRequestFailedError}\n * and `VaultBatcherReadFailedError` override it per instance.\n * Prefer {@link isRetryable} over reading this directly, so a new `unknown`\n * caught value doesn't need an `instanceof ZamaError` check first.\n */\n readonly retryable: boolean;\n\n constructor(\n code: ZamaErrorCode,\n message: string,\n options?: ErrorOptions & { retryable?: boolean },\n ) {\n super(message, options);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"ZamaError\";\n this.code = code;\n this.retryable = options?.retryable ?? RETRYABLE_BY_CODE[code];\n }\n}\n\n/**\n * True if `error` is a {@link ZamaError} whose failure is transient and safe to\n * retry (rate-limited, back-pressured, a delegation still propagating or in\n * its per-block cooldown, or a wallet account still resolving).\n * Compiler-guaranteed to stay in sync with the\n * taxonomy: every {@link ZamaError} subclass declares its own retryability via\n * {@link ZamaError.retryable}, so a consumer never has to hardcode a set of\n * retryable codes.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (isRetryable(e)) {\n * // back off and retry (see retryAfterSeconds for a server-suggested delay)\n * } else {\n * throw e; // terminal — surface it\n * }\n * }\n * ```\n */\nexport function isRetryable(error: unknown): error is ZamaError & { retryable: true } {\n return error instanceof ZamaError && error.retryable;\n}\n\n/**\n * The server-suggested retry delay, in **seconds**, for a retryable\n * {@link ZamaError} — unifying the `retryAfter` field that today lives on\n * {@link RelayerRequestFailedError} and {@link RpcRateLimitError} only.\n * `undefined` when the error isn't retryable, or is retryable but carries no\n * server-driven delay (e.g. {@link DelegationNotPropagatedError} — retry that\n * with your own backoff).\n */\nexport function retryAfterSeconds(error: unknown): number | undefined {\n if (!isRetryable(error) || !(\"retryAfter\" in error)) {\n return undefined;\n }\n const retryAfter = (error as ZamaError & { retryAfter?: unknown }).retryAfter;\n return isValidRetryAfterSeconds(retryAfter) ? retryAfter : undefined;\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Relayer HTTP request failed. */\nexport class RelayerRequestFailedError extends ZamaError {\n /** HTTP status code from the relayer, if available. */\n readonly statusCode: number | undefined;\n\n /**\n * Server-driven retry delay in **seconds** (the SDK's duration unit and the\n * header's own unit), from the relayer's `Retry-After` header. Set only on\n * back-pressure (HTTP 429) responses that carry the header; `undefined`\n * otherwise. Implies {@link ZamaError.retryable}.\n */\n readonly retryAfter: number | undefined;\n\n constructor(\n message: string,\n statusCode?: number,\n options?: ErrorOptions & { retryAfter?: number; retryable?: boolean },\n ) {\n // Retryable on relayer back-pressure (HTTP 429) by default, or when the\n // caller forces it (a relayer timeout has no status but is safe to retry).\n const retryable = options?.retryable ?? statusCode === 429;\n super(ZamaErrorCode.RelayerRequestFailed, message, { ...options, retryable });\n this.name = \"RelayerRequestFailedError\";\n this.statusCode = statusCode;\n // Keep the two fields consistent: a delay only makes sense when retryable,\n // and only a 429 actually carries a server-supplied `Retry-After`.\n this.retryAfter = retryable ? options?.retryAfter : undefined;\n }\n}\n\n/** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\nexport class ConfigurationError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.Configuration, message, options);\n this.name = \"ConfigurationError\";\n }\n}\n"],"mappings":"AACA,SAAgBA,EAAQ,EAAuB,CAO7C,OANIC,aAAiB,MACZA,EAEL,OAAOA,GAAU,UAAYA,GAAkB,YAAaA,EACnD,MAAM,OAAOA,EAAM,OAAO,CAAC,EAE7B,MAAM,OAAOA,CAAK,CAAC,CAChC,CAOA,SAAgBC,EAAoB,EAAyB,CAC3D,OAAOC,EAAiBF,EAAOG,CAAoB,IAAM,IAAA,EAC3D,CAEA,SAASA,EAAqB,EAAw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UA,SAAgBqD,EAAkB,EAAoC,CACpE,GAAI,CAACD,EAAYpD,CAAK,GAAK,EAAE,eAAgBA,GAC3C,OAEF,IAAMsD,EAActD,EAA+C,WACnE,OAAOwC,EAAyBc,CAAU,EAAIA,EAAa,IAAA,EAC7D,CCnPA,IAAaC,EAAb,cAA+CN,CAAU,CAEvD,WAQA,WAEA,YACE,EACA,EACA,EACA,CAGA,IAAMO,EAAYN,GAAS,WAAaO,IAAe,IACvD,MAAMV,EAAc,qBAAsB3B,EAAS,CAAE,GAAG8B,EAAS,WAAU,CAAC,EAC5E,KAAK,KAAO,4BACZ,KAAK,WAAaO,EAGlB,KAAK,WAAaD,EAAYN,GAAS,WAAa,IAAA,EACtD,CACF,EAGaQ,EAAb,cAAwCT,CAAU,CAChD,YAAY,EAAiB,EAAwB,CACnD,MAAMF,EAAc,cAAe3B,EAAS8B,CAAO,EACnD,KAAK,KAAO,oBACd,CACF,E"}
|
package/dist/cjs/telemetry.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
let e,t=!1;function n(n){e=Object.freeze({wasmAssetLoadMode:n.wasmAssetLoadMode,moduleVersions:n.moduleVersions,singleThread:n.singleThread,numberOfThreads:n.numberOfThreads,auth:n.auth}),t=n.locateFile!==void 0}function r(){return e}function i(){return t}function a(e,t){let{layer:n,daemonClient:r}=e.state,i=Object.entries({version:`3.9.0-beta.
|
|
1
|
+
let e,t=!1;function n(n){e=Object.freeze({wasmAssetLoadMode:n.wasmAssetLoadMode,moduleVersions:n.moduleVersions,singleThread:n.singleThread,numberOfThreads:n.numberOfThreads,auth:n.auth}),t=n.locateFile!==void 0}function r(){return e}function i(){return t}function a(e,t){let{layer:n,daemonClient:r}=e.state,i=Object.entries({version:`3.9.0-beta.4`,layer:n,...r===void 0?{runtime:e.runtime}:{runtime:`daemon`,client:r},...t!==void 0&&{operation:t}}),a=e=>Object.fromEntries(i.map(([t,n])=>[`${e}${t}`,n]));return e.mode===`query`?{query:a(`zama_sdk_`)}:{headers:a(`x-zama-sdk-`)}}function o(e,t){return Object.assign({},e,{operation:e?.operation??t})}function s(e){if(typeof e==`boolean`)return e?`header`:`off`;let t=typeof e==`string`?e.trim().toLowerCase():void 0;return t===`0`||t===`false`?`off`:t===`header`||t===`query`||t===`off`?t:void 0}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
|
2
2
|
//# sourceMappingURL=telemetry.cjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../alignment.cjs"),t=require("../token.cjs"),n=require("../relayer.cjs"),r=require("../encryption.cjs"),i=require("../log-decoding.cjs"),a=require("../query-keys.cjs");let o=require("viem");function s(e){return e}function c(e){return e}function l(e){return`vaults`in e?e.vaults[0].chainId:e.chainId}function u(e){if(!(`vaults`in e))return{group:void 0,vaults:[e],chainId:e.chainId};let t=`Vault group "${e.id}"`,[r]=e.vaults;if(e.vaults.length>8)throw new n.t(`${t} has ${e.vaults.length} vaults, more than 8`);let i=/* @__PURE__ */ new Set;for(let a of e.vaults){if(a.chainId!==r.chainId)throw new n.t(`${t} mixes chains: vault "${a.id}" is on chain ${a.chainId}, vault "${r.id}" on chain ${r.chainId}`);if(i.has(a.id))throw new n.t(`${t} names vault "${a.id}" twice`);i.add(a.id)}return{group:e,vaults:e.vaults,chainId:r.chainId}}function d(e,t){let r=e.batchers[t],i=`Vault "${e.id}" ${t} batcher`;return typeof r==`string`?{retired:[],latest:f(r,i)}:{retired:r.retired.map(e=>{if(typeof e.lastBatchId!=`bigint`||e.lastBatchId<0n)throw new n.t(`${i} has a retired batcher with an invalid lastBatchId: ${String(e.lastBatchId)}`);return{address:f(e.address,i),lastBatchId:e.lastBatchId}}),latest:f(r.latest,i)}}function f(e,t){if(typeof e!=`string`||!(0,o.isAddress)(e,{strict:!1}))throw new n.t(`${t} is not an address: ${String(e)}`);return(0,o.getAddress)(e)}const p=[{type:`function`,name:`batchCallbackDeadline`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchCreatedAt`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchDispatchedAt`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchMaxSlippageBps`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint16`,internalType:`uint16`}],stateMutability:`view`},{type:`function`,name:`batchMinBatchAge`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchState`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint8`,internalType:`enum BatcherConfidential.BatchState`}],stateMutability:`view`},{type:`function`,name:`callbackDeadline`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`claim`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`currentBatchId`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`deposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`dispatchBatch`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`dispatchBatchCallback`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`unwrapAmountCleartext`,type:`uint64`,internalType:`uint64`},{name:`decryptionProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`exchangeRate`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`exchangeRateDecimals`,inputs:[],outputs:[{name:``,type:`uint8`,internalType:`uint8`}],stateMutability:`pure`},{type:`function`,name:`fromToken`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC7984ERC20Wrapper`}],stateMutability:`view`},{type:`function`,name:`join`,inputs:[{name:`beneficiary`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`joined`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`maxSlippageBps`,inputs:[],outputs:[{name:``,type:`uint16`,internalType:`uint16`}],stateMutability:`view`},{type:`function`,name:`minBatchAge`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`paused`,inputs:[],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`quit`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`recover`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:`refunded`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`toToken`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC7984ERC20Wrapper`}],stateMutability:`view`},{type:`function`,name:`totalDeposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`unwrapRequestId`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`vault`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC4626`}],stateMutability:`view`},{type:`event`,name:`BatchCanceled`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`BatchDispatched`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`BatchFinalized`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`exchangeRate`,type:`uint64`,indexed:!1,internalType:`uint64`}],anonymous:!1},{type:`event`,name:`Claimed`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Joined`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Quit`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`error`,name:`BatchNonexistent`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`BatchTooYoung`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`elapsed`,type:`uint256`,internalType:`uint256`},{name:`required`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`BatchUnexpectedState`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`current`,type:`uint8`,internalType:`enum BatcherConfidential.BatchState`},{name:`expectedStates`,type:`bytes32`,internalType:`bytes32`}]},{type:`error`,name:`DuplicateUnderlyingTokens`,inputs:[]},{type:`error`,name:`EnforcedPause`,inputs:[]},{type:`error`,name:`ExpectedPause`,inputs:[]},{type:`error`,name:`IntermediateStepToTokenBalanceChanged`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`InvalidBeneficiary`,inputs:[]},{type:`error`,name:`InvalidCallbackDeadline`,inputs:[]},{type:`error`,name:`InvalidExchangeRate`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`totalDeposits`,type:`uint256`,internalType:`uint256`},{name:`exchangeRate`,type:`uint64`,internalType:`uint64`}]},{type:`error`,name:`InvalidKMSSignatures`,inputs:[]},{type:`error`,name:`InvalidMaxSlippageBps`,inputs:[]},{type:`error`,name:`InvalidMinBatchAge`,inputs:[]},{type:`error`,name:`InvalidTokenRate`,inputs:[]},{type:`error`,name:`InvalidWrapperToken`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableInvalidOwner`,inputs:[{name:`owner`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableUnauthorizedAccount`,inputs:[{name:`account`,type:`address`,internalType:`address`}]},{type:`error`,name:`ReentrancyGuardReentrantCall`,inputs:[]},{type:`error`,name:`RouteAssetMismatch`,inputs:[{name:`actualAsset`,type:`address`,internalType:`address`},{name:`expectedAsset`,type:`address`,internalType:`address`}]},{type:`error`,name:`RouteShareMismatch`,inputs:[{name:`actualShare`,type:`address`,internalType:`address`},{name:`expectedShare`,type:`address`,internalType:`address`}]},{type:`error`,name:`SafeCastOverflowedUintDowncast`,inputs:[{name:`bits`,type:`uint8`,internalType:`uint8`},{name:`value`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`SafeERC20FailedOperation`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`SenderNotAllowedToUseHandle`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`sender`,type:`address`,internalType:`address`}]},{type:`error`,name:`SlippageExceeded`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`actual`,type:`uint256`,internalType:`uint256`},{name:`minimum`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`Unauthorized`,inputs:[]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]},{type:`error`,name:`ZeroDeposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}]}];function m(e,t,n){return{address:e,abi:p,functionName:`claim`,args:[t,n]}}function h(e,t){return{address:e,abi:p,functionName:`quit`,args:[t]}}function g(e){return{address:e,abi:p,functionName:`dispatchBatch`,args:[]}}function _(e){return{address:e,abi:p,functionName:`currentBatchId`,args:[]}}function v(e,t){return{address:e,abi:p,functionName:`batchState`,args:[t]}}function y(e,t,n){return{address:e,abi:p,functionName:`deposits`,args:[t,n]}}function b(e){return{address:e,abi:p,functionName:`fromToken`,args:[]}}function x(e,t){return{address:e,abi:p,functionName:`batchMinBatchAge`,args:[t]}}function S(e,t){return{address:e,abi:p,functionName:`batchCallbackDeadline`,args:[t]}}function C(e,t){return{address:e,abi:p,functionName:`batchCreatedAt`,args:[t]}}function w(e,t){return{address:e,abi:p,functionName:`batchDispatchedAt`,args:[t]}}function T(e,t){return{address:e,abi:p,functionName:`exchangeRate`,args:[t]}}function E(e){return{address:e,abi:p,functionName:`exchangeRateDecimals`,args:[]}}function D(e){return{address:e,abi:p,functionName:`paused`,args:[]}}function O(e,t){return{address:e,abi:p,functionName:`unwrapRequestId`,args:[t]}}function k(e,t,n,r){return{address:e,abi:p,functionName:`dispatchBatchCallback`,args:[t,n,r]}}const A=[{type:`function`,name:`join`,inputs:[{name:`legs`,type:`tuple[]`,internalType:`struct IVaultBatcherConfidentialRouter.Allocation[]`,components:[{name:`batcher`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`externalEuint64`}]},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`tokenWrapperRegistry`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract ITokenWrapperRegistry`}],stateMutability:`view`},{type:`error`,name:`InvalidTokenWrapperRegistry`,inputs:[]},{type:`error`,name:`MissingInputProof`,inputs:[]},{type:`error`,name:`ReentrancyGuardReentrantCall`,inputs:[]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]},{type:`error`,name:`UnlistedConfidentialToken`,inputs:[{name:`token`,type:`address`,internalType:`address`}]}];function j(e,t,n){return{address:e,abi:A,functionName:`join`,args:[t,n]}}const M=(0,o.getAbiItem)({abi:A,name:`join`}).inputs;function N(e,t){return(0,o.encodeAbiParameters)(M,[e.map(e=>({...e})),t])}const P=i.t(`Joined(uint256,address,bytes32)`);function F(e,t,n){for(let[r,a]of e.entries()){let[s,c,l]=a.topics;if(!(s!==P||c===void 0||l===void 0||a.address!==void 0&&(0,o.getAddress)(a.address)!==t||i.n(l)!==n))return e.splice(r,1),BigInt(c)}return null}const I=365n*24n*60n*60n,L=[`pending`,`dispatched`,`finalized`,`canceled`],R={deposit:`vault-deposit`,redeem:`vault-redeem`},z={direct:`vault:join`,router:`vault:routerJoin`};function B(t,n){let r=t[n];return e.z(r,`vault leg ${n}`),r}function V(e){return{to:e.address,data:(0,o.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),value:0n}}function H(e,t){let r=e.vaults.find(e=>e.id===t);if(r===void 0)throw new n.t(`Vault group "${e.id}" has no vault "${t}"`);return r}function U(t){let[n,...r]=t;return e.z(n,`vault calls`),[n,...r]}function W(e,t,n){let r=e.get(t);return r===void 0&&(r=n().catch(n=>{throw e.delete(t),n}),e.set(t,r)),r}var G=class{#e;#t=/* @__PURE__ */ new Map;constructor(e){this.#e=e}async prepareDeposit(e,t,n){return(await this.#r(`deposit`,e,t,n)).prepared}async prepareRedeem(e,t,n){return(await this.#r(`redeem`,e,t,n)).prepared}prepareClaim(e,t){return V(m((0,o.getAddress)(e.batcher),e.batchId,(0,o.getAddress)(t)))}prepareQuit(e){return V(h((0,o.getAddress)(e.batcher),e.batchId))}prepareDispatch(e){return V(g((0,o.getAddress)(e.batcher)))}async prepareFinalize(e){return(await this.#n(e)).call}async#n(t){let n=(0,o.getAddress)(t.batcher),[a,s,c]=await Promise.all([this.#p(t.chainId,n,t.batchId),this.#y(t.chainId,O(n,t.batchId)),this.#s(t.chainId,n)]);if(a!==`dispatched`)throw new i.s(`Batch ${t.batchId} of batcher ${n} is ${a}, but only a dispatched batch can be finalized`,{batcher:n,batchId:t.batchId,state:a});let l=await this.#y(t.chainId,e.j(c,s));await this.#_(t.chainId,`vault finalize`);let{clearValues:u,decryptionProof:d}=await this.#e.decryption.decryptPublicValues([l],{operation:`vault-finalize`}),f=u[l];if(f===void 0)throw new r.t(`Public decryption returned no value for ${l}`);e.L(f,`finalize: clearValues[handle]`);let p=k(n,t.batchId,f,d);return{config:p,call:{chainId:t.chainId,batcher:n,batchId:t.batchId,unwrapAmountCleartext:f,decryptionProof:d,call:V(p)}}}async deposit(e,t,n){return this.#i(`deposit`,e,t,n)}async redeem(e,t,n){return this.#i(`redeem`,e,t,n)}async claim(e,t){let n=await this.#h(e.chainId,`claim`),r=m((0,o.getAddress)(e.batcher),e.batchId,(0,o.getAddress)(t??n));return this.#g(r,`vault:claim`)}async quit(e){return await this.#h(e.chainId,`quit`),this.#g(h((0,o.getAddress)(e.batcher),e.batchId),`vault:quit`)}async dispatch(e){return await this.#h(e.chainId,`dispatch`),this.#g(g((0,o.getAddress)(e.batcher)),`vault:dispatchBatch`)}async finalize(e){return await this.#h(e.chainId,`finalize`),this.#g((await this.#n(e)).config,`vault:finalize`)}async readBatch(e,n){let{chainId:r,batchId:i}=e,a=(0,o.getAddress)(e.batcher),s=n===void 0?void 0:(0,o.getAddress)(n),[c,l,u,d,f,p,m,h,g,_]=await Promise.all([this.#p(r,a,i),this.#y(r,C(a,i)),this.#y(r,x(a,i)),this.#y(r,w(a,i)),this.#y(r,S(a,i)),this.#y(r,D(a)),this.#y(r,T(a,i)),this.#v(`decimals:${r}:${a}`,()=>this.#y(r,E(a))),s===void 0?null:this.#y(r,y(a,i,s)),this.#e.provider.getBlockTimestamp(r)]),v=l+u,b=d+f,O=g!==null&&!t.c(g),k=[[`claim`,O&&c===`finalized`],[`quit`,O&&(c===`pending`||c===`canceled`)],[`dispatch`,c===`pending`&&!p&&v<=_],[`finalize`,c===`dispatched`]].flatMap(([e,t])=>t?[e]:[]),A=c===`pending`?v:c===`dispatched`?b:null,j={chainId:r,batcher:a,batchId:i,createdAt:l,dispatchableAt:v,paused:p,deposit:g,actions:k,observedAt:_,nextChangeAt:A!==null&&A>_?A:null};switch(c){case`pending`:return{...j,state:c};case`finalized`:return{...j,state:c,dispatchedAt:d,cancelsAt:b,exchangeRate:{rate:m,decimals:h}};default:return{...j,state:c,dispatchedAt:d,cancelsAt:b}}}async readOpenBatches(e,t){let{vaults:n,chainId:r}=u(e),[i,a]=await Promise.all([this.#e.provider.getBlockTimestamp(r),Promise.all(n.map(async e=>{let n=await this.#a(e,t),[i,a]=await Promise.all([this.#y(r,_(n)),this.#y(r,D(n))]),[o,s]=await Promise.all([this.#y(r,C(n,i)),this.#y(r,x(n,i))]);return{vaultId:e.id,chainId:r,batcher:n,batchId:i,dispatchableAt:o+s,paused:a}}))]);return a.map(e=>({...e,observedAt:i}))}async#r(t,r,i,a){let{group:s,vaults:c,chainId:l}=u(r),d=s===void 0?c[0]:H(s,i.vaultId),f=(0,o.getAddress)(i.account),p=s===void 0?`direct`:a?.route??`router`;await this.#_(l,`vault ${t}`);let m=s!==void 0&&p===`router`?this.#o(s):void 0,h=await Promise.all(c.map(e=>this.#a(e,t))),[g]=await Promise.all([Promise.all(h.map(e=>this.#s(l,e))),this.#c(l,s,c,h)]),_=U(c.map((e,t)=>({vaultId:e.id,batcher:B(h,t),token:B(g,t),amount:e===d?i.amount:0n}))),v=B(_,c.indexOf(d)),y=_.find(e=>t===`deposit`&&e.token!==v.token);if(y!==void 0)throw new n.t(`Vault group "${r.id}" mixes deposit assets: vault "${y.vaultId}" takes ${y.token}, vault "${v.vaultId}" takes ${v.token}`);a?.skipBalanceCheck!==!0&&await this.#l(t,_,v,f);let b=R[t],x=(e,t)=>({config:e,call:{...V(e),kind:`join`,leg:t}}),S,C=[];if(m!==void 0){let n=_.map(e=>e.amount),r=e=>_.map((t,n)=>({batcher:t.batcher,token:t.token,amount:B(e,n)}));if(t===`redeem`){let[[e,t],i]=await Promise.all([this.#u(m,f,n,b),this.#f(l,_,f,m)]);C=i,S=[x(j(m,r(e),t),v)]}else{let t=v.token,[[a,o],[[s],c]]=await Promise.all([this.#u(m,f,n,b),this.#u(t,f,[i.amount],b)]),l=N(r(a),o);S=[x(e.x(t,m,s,c,l),v)]}}else{let t=await this.#d(_,f,b);S=_.map((n,r)=>{let{handle:i,inputProof:a}=B(t,r);return x(e.x(n.token,n.batcher,i,a,`0x`),n)})}let w=[...C,...S];return{prepared:{direction:t,chainId:l,groupId:s?.id,vaultId:d.id,account:f,amount:i.amount,route:p,legs:_,calls:U(w.map(({call:e})=>e))},planned:w}}async#i(n,r,a,o){let s=this.#m(n),{chainId:c}=u(r),l=await this.#h(c,n),{prepared:d,planned:f}=await this.#r(n,r,{...a,account:l},{skipBalanceCheck:o?.skipBalanceCheck}),p=[],m;for(let[e,{call:n,config:r}]of f.entries())m=await t.n({operation:n.kind===`operatorApproval`?`setOperator`:z[d.route],signer:s,provider:this.#e.provider,config:r,onSubmitted:e===f.length-1?o?.onJoinSubmitted:void 0,emit:e=>this.#e.emitEvent(e,n.to),logger:this.#e.logger}),p.push(m.txHash);e.z(m,`vault ${n}: last transaction`);let h=[...m.receipt.logs],g=[],_=[];for(let e of d.legs){let t=F(h,e.batcher,l);t===null?_.push(e.vaultId):g.push({vaultId:e.vaultId,chainId:c,batcher:e.batcher,batchId:t})}if(_.length>0)throw new i.l(`Transaction ${m.txHash} was mined, but its receipt has no Joined event for ${l} from the batcher of ${_.map(e=>`vault "${e}"`).join(`, `)}${`vaults`in r?` in group "${r.id}"`:``}`,{txHash:m.txHash,receipt:m.receipt,unconfirmedVaultIds:_});return{batches:g,txHashes:p}}async#a(e,t){let n=d(e,t),r=await Promise.all(n.retired.map(t=>this.#y(e.chainId,_(t.address))));return n.retired.find((e,t)=>B(r,t)<=e.lastBatchId)?.address??n.latest}#o(e){let{chainId:t}=u(e),r=this.#e.chains.find(e=>e.id===t)?.vaultRouterAddress;if(r===void 0)throw new n.t(`Vault group "${e.id}" has ${e.vaults.length} vaults, but chain ${t} has no router; set vaultRouterAddress on the chain`);return(0,o.getAddress)(r)}#s(e,t){return this.#v(`fromToken:${e}:${t}`,async()=>(0,o.getAddress)(await this.#y(e,b(t))))}async#c(e,t,n,r){let a=(await Promise.all(r.map(t=>this.#y(e,D(t))))).indexOf(!0);if(a!==-1){let e=B(n,a),o=B(r,a);throw new i.c(t===void 0?`Batcher ${o} of vault "${e.id}" is paused, so the vault cannot be joined until it resumes`:`Batcher ${o} of vault "${e.id}" in group "${t.id}" is paused, so no vault of the group can be joined until it resumes`,{batcher:o,vaultId:e.id})}}async#l(e,n,r,i){let a=this.#e.signer?.walletAccount.getSnapshot()?.address;if(a===void 0||(0,o.getAddress)(a)!==i)throw new t.l(`Cannot check the balance of ${i} for a vault ${e}: ${a===void 0?`no signer is connected`:`the signer is another account`}. Check it yourself, decrypting every leg's token together, and pass skipBalanceCheck: true`);await t.a({operation:e,tokenAddress:r.token,amount:r.amount,account:i,signer:this.#e.signer,provider:this.#e.provider,readBalance:async e=>{let i=[...new Set(n.map(e=>e.token))].map(e=>new t.t(this.#e,e)),{results:a,errors:o}=await t.t.batchBalancesOf(i,e),s=a.get(r.token);if(s===void 0)throw o.get(r.token)??new t.l(`Balance validation failed (token: ${r.token})`);return s}})}async#u(e,t,n,i){let{encryptedValues:a,inputProof:o}=await this.#e.encrypt({values:n.map(e=>({value:e,type:`euint64`})),contractAddress:e,userAddress:t},{operation:i}),[s,...c]=a;if(s===void 0||a.length!==n.length)throw new r.r(`Encryption returned ${a.length} values for ${n.length} legs`);return[[s,...c],o]}async#d(t,n,r){let i=/* @__PURE__ */ new Map;return await Promise.all([...new Set(t.map(e=>e.token))].map(async e=>{let a=t.filter(t=>t.token===e),[o,s]=await this.#u(e,n,a.map(e=>e.amount),r);a.forEach((e,t)=>i.set(e,{handle:B(o,t),inputProof:s}))})),t.map(t=>{let n=i.get(t);return e.z(n,`vault leg ${t.vaultId}`),n})}async#f(t,n,r,i){let a=await Promise.all(n.map(n=>this.#y(t,e.D(n.token,r,i)))),o=n.filter((e,t)=>!a[t]);if(o.length===0)return[];let s=await this.#e.provider.getBlockTimestamp(t)+I;return o.map(t=>{let n=e.k(t.token,i,Number(s));return{config:n,call:{...V(n),kind:`operatorApproval`,vaultId:t.vaultId,operator:i,until:s}}})}async#p(e,t,r){let i=await this.#y(e,v(t,r)),a=L[i];if(a===void 0)throw new n.t(`Batcher ${t} returned unknown batch state ${i} for batch ${r}; is it a vault batcher?`);return a}#m(t){if(this.#e.signer===void 0)throw new e.H(t);return this.#e.signer}async#h(t,n){let r=await e.i(`vault ${n}`,this.#m(n),this.#e.provider,t);return(0,o.getAddress)(r.address)}async#g(e,n){return t.n({operation:n,signer:this.#m(n),provider:this.#e.provider,config:e,emit:t=>this.#e.emitEvent(t,e.address),logger:this.#e.logger})}async#_(t,r){let i=await this.#e.provider.getChainId();if(i===t)return;let a=this.#e.signer?.walletAccount.getSnapshot();throw a===void 0?new n.t(`Operation "${r}" encrypts or decrypts on chain ${t}, but the provider is on chain ${i}`):new e.q({operation:r,signerChainId:a.chainId,providerChainId:i,targetChainId:t})}#v(e,t){return W(this.#t,e,t)}#y(e,t){return this.#e.provider.readContract({...t,chainId:e})}};function K(e){return new G(e)}const q=15e3,J={all:[`zama.vault`],batch:(e,t)=>[`zama.vault`,{kind:`batch`,chainId:e?.chainId,batcher:e===void 0?void 0:(0,o.getAddress)(e.batcher),batchId:e?.batchId,account:t===void 0?void 0:(0,o.getAddress)(t)}],openBatches:(e,t)=>[`zama.vault`,{kind:`openBatches`,chainId:l(e),scope:`vaults`in e?`group`:`vault`,id:e.id,direction:t}]};function Y(e){if(e===void 0||e.state===`finalized`||e.state===`canceled`)return!1;if(e.nextChangeAt===null)return q;let t=Math.min(Number(e.nextChangeAt-e.observedAt)*1e3+1e3,36e5);return e.state===`dispatched`?Math.min(t,q):t}function X(t,n={}){let{batch:r,account:i}=n;return{refetchInterval:e=>Y(e.state.data),queryKey:J.batch(r,i),queryFn:async()=>(e.z(r,`batchQueryOptions: batch`),t.readBatch(r,i)),enabled:r!==void 0&&n.query?.enabled!==!1}}function Z(e){return e.vault??e.group}function Q(e,t){let n=Z(t);return{queryKey:J.openBatches(n,t.direction),queryFn:async()=>e.readOpenBatches(n,t.direction)}}function ee(e){e.invalidateQueries({queryKey:J.all}),e.invalidateQueries({queryKey:a.t.confidentialBalance.all}),e.invalidateQueries({queryKey:a.t.confidentialBalances.all})}function $(e,t){return{mutationKey:[`zama.vault.${t}`],mutationFn:async({skipBalanceCheck:n,onJoinSubmitted:r,amount:i,...a})=>{let o={skipBalanceCheck:n,onJoinSubmitted:r};return a.vault===void 0?e[t](a.group,{vaultId:a.vaultId,amount:i},o):e[t](a.vault,{amount:i},o)}}}function te(e){return $(e,`deposit`)}function ne(e){return $(e,`redeem`)}function re(e){return{mutationKey:[`zama.vault.claim`],mutationFn:async({account:t,...n})=>e.claim(n,t)}}function ie(e){return{mutationKey:[`zama.vault.quit`],mutationFn:async t=>e.quit(t)}}function ae(e){return{mutationKey:[`zama.vault.dispatch`],mutationFn:async t=>e.dispatch(t)}}function oe(e){return{mutationKey:[`zama.vault.finalize`],mutationFn:async t=>e.finalize(t)}}exports.MAX_GROUP_VAULTS=8,exports.batchQueryOptions=X,exports.claimMutationOptions=re,exports.createVaultClient=K,exports.defineVault=s,exports.defineVaultGroup=c,exports.depositMutationOptions=te,exports.dispatchMutationOptions=ae,exports.finalizeMutationOptions=oe,exports.invalidateAfterVaultAction=ee,exports.openBatchesQueryOptions=Q,exports.quitMutationOptions=ie,exports.redeemMutationOptions=ne,exports.vaultQueryKeys=J;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../alignment.cjs"),t=require("../token.cjs"),n=require("../relayer.cjs"),r=require("../encryption.cjs"),i=require("../log-decoding.cjs"),a=require("../query-keys.cjs");let o=require("viem");function s(e){return e}function c(e){return e}function l(e){return`vaults`in e?e.vaults[0].chainId:e.chainId}function u(e){if(!(`vaults`in e))return{group:void 0,vaults:[e],chainId:e.chainId};let t=`Vault group "${e.id}"`,[r]=e.vaults;if(e.vaults.length>8)throw new n.t(`${t} has ${e.vaults.length} vaults, more than 8`);let i=/* @__PURE__ */ new Set;for(let a of e.vaults){if(a.chainId!==r.chainId)throw new n.t(`${t} mixes chains: vault "${a.id}" is on chain ${a.chainId}, vault "${r.id}" on chain ${r.chainId}`);if(i.has(a.id))throw new n.t(`${t} names vault "${a.id}" twice`);i.add(a.id)}return{group:e,vaults:e.vaults,chainId:r.chainId}}function d(e,t){let r=`Vault "${e.id}" ${t} batcher`,[i,...a]=f(e.batchers[t],r).map(e=>m(e,r));if(i===void 0)throw new n.t(`${r} list is empty`);return[i,...a]}function f(e,t){if(typeof e==`string`)return[e];if(p(e))return e;if(!(`latest`in e))throw new n.t(`${t} must be an address or a list`);let r=e.retired.find(e=>e.lastBatchId===void 0);if(r!==void 0)throw new n.t(`${t} ${r.address} has an invalid lastBatchId: undefined`);return[...e.retired,e.latest]}function p(e){return Array.isArray(e)}function m(e,t){if(typeof e==`string`)return{address:h(e,t)};let r=h(e.address,t),{lastBatchId:i}=e;if(i===void 0)return{address:r};if(typeof i!=`bigint`||i<0n)throw new n.t(`${t} ${r} has an invalid lastBatchId: ${String(i)}`);return{address:r,lastBatchId:i}}function h(e,t){if(typeof e!=`string`||!(0,o.isAddress)(e,{strict:!1}))throw new n.t(`${t} is not an address: ${String(e)}`);return(0,o.getAddress)(e)}const g=[{type:`function`,name:`batchCallbackDeadline`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchCreatedAt`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchDispatchedAt`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchMaxSlippageBps`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint16`,internalType:`uint16`}],stateMutability:`view`},{type:`function`,name:`batchMinBatchAge`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchState`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint8`,internalType:`enum BatcherConfidential.BatchState`}],stateMutability:`view`},{type:`function`,name:`callbackDeadline`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`claim`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`currentBatchId`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`deposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`dispatchBatch`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`dispatchBatchCallback`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`unwrapAmountCleartext`,type:`uint64`,internalType:`uint64`},{name:`decryptionProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`exchangeRate`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`exchangeRateDecimals`,inputs:[],outputs:[{name:``,type:`uint8`,internalType:`uint8`}],stateMutability:`pure`},{type:`function`,name:`fromToken`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC7984ERC20Wrapper`}],stateMutability:`view`},{type:`function`,name:`join`,inputs:[{name:`beneficiary`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`joined`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`maxSlippageBps`,inputs:[],outputs:[{name:``,type:`uint16`,internalType:`uint16`}],stateMutability:`view`},{type:`function`,name:`minBatchAge`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`closed`,inputs:[],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`paused`,inputs:[],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`quit`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`recover`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:`refunded`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`toToken`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC7984ERC20Wrapper`}],stateMutability:`view`},{type:`function`,name:`totalDeposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`unwrapRequestId`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`vault`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC4626`}],stateMutability:`view`},{type:`event`,name:`BatchCanceled`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`BatchDispatched`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`BatchFinalized`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`exchangeRate`,type:`uint64`,indexed:!1,internalType:`uint64`}],anonymous:!1},{type:`event`,name:`Claimed`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Joined`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Quit`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`error`,name:`BatchNonexistent`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`BatchTooYoung`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`elapsed`,type:`uint256`,internalType:`uint256`},{name:`required`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`BatchUnexpectedState`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`current`,type:`uint8`,internalType:`enum BatcherConfidential.BatchState`},{name:`expectedStates`,type:`bytes32`,internalType:`bytes32`}]},{type:`error`,name:`DuplicateUnderlyingTokens`,inputs:[]},{type:`error`,name:`EnforcedPause`,inputs:[]},{type:`error`,name:`ExpectedPause`,inputs:[]},{type:`error`,name:`IntermediateStepToTokenBalanceChanged`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`InvalidBeneficiary`,inputs:[]},{type:`error`,name:`InvalidCallbackDeadline`,inputs:[]},{type:`error`,name:`InvalidExchangeRate`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`totalDeposits`,type:`uint256`,internalType:`uint256`},{name:`exchangeRate`,type:`uint64`,internalType:`uint64`}]},{type:`error`,name:`InvalidKMSSignatures`,inputs:[]},{type:`error`,name:`InvalidMaxSlippageBps`,inputs:[]},{type:`error`,name:`InvalidMinBatchAge`,inputs:[]},{type:`error`,name:`InvalidTokenRate`,inputs:[]},{type:`error`,name:`InvalidWrapperToken`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableInvalidOwner`,inputs:[{name:`owner`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableUnauthorizedAccount`,inputs:[{name:`account`,type:`address`,internalType:`address`}]},{type:`error`,name:`ReentrancyGuardReentrantCall`,inputs:[]},{type:`error`,name:`RouteAssetMismatch`,inputs:[{name:`actualAsset`,type:`address`,internalType:`address`},{name:`expectedAsset`,type:`address`,internalType:`address`}]},{type:`error`,name:`RouteShareMismatch`,inputs:[{name:`actualShare`,type:`address`,internalType:`address`},{name:`expectedShare`,type:`address`,internalType:`address`}]},{type:`error`,name:`SafeCastOverflowedUintDowncast`,inputs:[{name:`bits`,type:`uint8`,internalType:`uint8`},{name:`value`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`SafeERC20FailedOperation`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`SenderNotAllowedToUseHandle`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`sender`,type:`address`,internalType:`address`}]},{type:`error`,name:`SlippageExceeded`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`actual`,type:`uint256`,internalType:`uint256`},{name:`minimum`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`Unauthorized`,inputs:[]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]},{type:`error`,name:`ZeroDeposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}]}];function _(e,t,n){return{address:e,abi:g,functionName:`claim`,args:[t,n]}}function v(e,t){return{address:e,abi:g,functionName:`quit`,args:[t]}}function y(e){return{address:e,abi:g,functionName:`dispatchBatch`,args:[]}}function b(e){return{address:e,abi:g,functionName:`currentBatchId`,args:[]}}function x(e,t){return{address:e,abi:g,functionName:`batchState`,args:[t]}}function S(e,t,n){return{address:e,abi:g,functionName:`deposits`,args:[t,n]}}function C(e){return{address:e,abi:g,functionName:`fromToken`,args:[]}}function w(e,t){return{address:e,abi:g,functionName:`batchMinBatchAge`,args:[t]}}function T(e,t){return{address:e,abi:g,functionName:`batchCallbackDeadline`,args:[t]}}function E(e,t){return{address:e,abi:g,functionName:`batchCreatedAt`,args:[t]}}function ee(e,t){return{address:e,abi:g,functionName:`batchDispatchedAt`,args:[t]}}function te(e,t){return{address:e,abi:g,functionName:`exchangeRate`,args:[t]}}function ne(e){return{address:e,abi:g,functionName:`exchangeRateDecimals`,args:[]}}function D(e){return{address:e,abi:g,functionName:`paused`,args:[]}}function O(e){return{address:e,abi:g,functionName:`closed`,args:[]}}function k(e,t){return{address:e,abi:g,functionName:`unwrapRequestId`,args:[t]}}function re(e,t,n,r){return{address:e,abi:g,functionName:`dispatchBatchCallback`,args:[t,n,r]}}const A=[{type:`function`,name:`join`,inputs:[{name:`legs`,type:`tuple[]`,internalType:`struct IVaultBatcherConfidentialRouter.Allocation[]`,components:[{name:`batcher`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`externalEuint64`}]},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`tokenWrapperRegistry`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract ITokenWrapperRegistry`}],stateMutability:`view`},{type:`error`,name:`InvalidTokenWrapperRegistry`,inputs:[]},{type:`error`,name:`MissingInputProof`,inputs:[]},{type:`error`,name:`ReentrancyGuardReentrantCall`,inputs:[]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]},{type:`error`,name:`UnlistedConfidentialToken`,inputs:[{name:`token`,type:`address`,internalType:`address`}]}];function j(e,t,n){return{address:e,abi:A,functionName:`join`,args:[t,n]}}const M=(0,o.getAbiItem)({abi:A,name:`join`}).inputs;function N(e,t){return(0,o.encodeAbiParameters)(M,[e.map(e=>({...e})),t])}const ie=[`pending`,`dispatched`,`finalized`,`canceled`];function P(e){return[...e].sort((e,t)=>{if(e.dispatchableAt!==t.dispatchableAt)return e.dispatchableAt<t.dispatchableAt?-1:1;let[n,r]=[e.batcher.toLowerCase(),t.batcher.toLowerCase()];return n<r?-1:+(n>r)})[0]}function ae(e,t){let n=e.filter(e=>e.status===`open`);return P(n.filter(e=>!e.blocked&&e.dispatchableAt>=t+60n))??P(n.filter(e=>e.blocked))??P(n)??e.find(e=>e.status===`paused`)}async function F(e,t,n,r){let[a,o]=await Promise.all([e.getBlockTimestamp(t),Promise.all(n.map(async n=>{let i=d(n,r);return{vault:n,entries:i,offers:await Promise.all(i.map(r=>R(e,t,n.id,r)))}}))]);return{now:a,next:o.map(({vault:e,entries:t,offers:n})=>{let o=ae(n,a);if(o===void 0)throw new i.c(`Every ${r} batcher of vault "${e.id}" is closed, so the vault takes no joins`,{batcher:t[0].address,vaultId:e.id});return{vault:e,offer:o}})}}async function I(e,t,r,i){let a=await e.readContract({...x(r,i),chainId:t}),o=ie[a];if(o===void 0)throw new n.t(`Batcher ${r} returned unknown batch state ${a} for batch ${i}; is it a vault batcher?`);return o}async function L(e,t,n,r){return r>1n&&await I(e,t,n,r-1n)===`dispatched`}async function R(e,t,r,a){let o={batcher:a.address,vaultId:r},s=`vault "${r}"`;try{let n=await z(e,t,a)??await z(e,t,a);if(n!==void 0)return n}catch(e){throw e instanceof n.t?e:new i.l(`Could not read batcher ${a.address} of ${s}`,o,{cause:e})}throw new i.l(`Batcher ${a.address} of ${s} has no open batch but is not closed; the RPC returned reads from different blocks`,o,{retryable:!0})}async function z(e,t,{address:n,lastBatchId:r}){let[i,a]=await Promise.all([e.readContract({...D(n),chainId:t}),e.readContract({...b(n),chainId:t})]);if(r!==void 0&&a>r)return{status:`closed`,batcher:n};let[o,s,c]=await Promise.all([e.readContract({...E(n,a),chainId:t}),e.readContract({...w(n,a),chainId:t}),!i&&L(e,t,n,a)]);if(o===0n)return await B(e,t,n)?{status:`closed`,batcher:n}:void 0;let l=o+s;return i?{status:`paused`,batcher:n,batchId:a,dispatchableAt:l}:{status:`open`,batcher:n,batchId:a,dispatchableAt:l,blocked:c}}async function B(e,t,r){try{return await e.readContract({...O(r),chainId:t})}catch(e){if(n.p(e))return!1;throw e}}const V=i.t(`Joined(uint256,address,bytes32)`);function H(e,t,n){for(let[r,a]of e.entries()){let[s,c,l]=a.topics;if(!(s!==V||c===void 0||l===void 0||a.address!==void 0&&(0,o.getAddress)(a.address)!==t||i.n(l)!==n))return e.splice(r,1),BigInt(c)}return null}const U=365n*24n*60n*60n,W={deposit:`vault-deposit`,redeem:`vault-redeem`},G={direct:`vault:join`,router:`vault:routerJoin`};function K(t,n){let r=t[n];return e.z(r,`vault leg ${n}`),r}function q(e){return{to:e.address,data:(0,o.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),value:0n}}function oe(e,t){let r=e.vaults.find(e=>e.id===t);if(r===void 0)throw new n.t(`Vault group "${e.id}" has no vault "${t}"`);return r}function J(t){let[n,...r]=t;return e.z(n,`vault calls`),[n,...r]}function se(e,t,n){let r=e.get(t);return r===void 0&&(r=n().catch(n=>{throw e.delete(t),n}),e.set(t,r)),r}var ce=class{#e;#t=/* @__PURE__ */ new Map;constructor(e){this.#e=e}async prepareDeposit(e,t,n){return(await this.#r(`deposit`,e,t,n)).prepared}async prepareRedeem(e,t,n){return(await this.#r(`redeem`,e,t,n)).prepared}prepareClaim(e,t){return q(_((0,o.getAddress)(e.batcher),e.batchId,(0,o.getAddress)(t)))}prepareQuit(e){return q(v((0,o.getAddress)(e.batcher),e.batchId))}prepareDispatch(e){return q(y((0,o.getAddress)(e.batcher)))}async prepareFinalize(e){return(await this.#n(e)).call}async#n(t){let n=(0,o.getAddress)(t.batcher),[a,s,c]=await Promise.all([I(this.#e.provider,t.chainId,n,t.batchId),this.#g(t.chainId,k(n,t.batchId)),this.#o(t.chainId,n)]);if(a!==`dispatched`)throw new i.s(`Batch ${t.batchId} of batcher ${n} is ${a}, but only a dispatched batch can be finalized`,{batcher:n,batchId:t.batchId,state:a});let l=await this.#g(t.chainId,e.j(c,s));await this.#m(t.chainId,`vault finalize`);let{clearValues:u,decryptionProof:d}=await this.#e.decryption.decryptPublicValues([l],{operation:`vault-finalize`}),f=u[l];if(f===void 0)throw new r.t(`Public decryption returned no value for ${l}`);e.L(f,`finalize: clearValues[handle]`);let p=re(n,t.batchId,f,d);return{config:p,call:{chainId:t.chainId,batcher:n,batchId:t.batchId,unwrapAmountCleartext:f,decryptionProof:d,call:q(p)}}}async deposit(e,t,n){return this.#i(`deposit`,e,t,n)}async redeem(e,t,n){return this.#i(`redeem`,e,t,n)}async claim(e,t){let n=await this.#f(e.chainId,`claim`),r=_((0,o.getAddress)(e.batcher),e.batchId,(0,o.getAddress)(t??n));return this.#p(r,`vault:claim`)}async quit(e){return await this.#f(e.chainId,`quit`),this.#p(v((0,o.getAddress)(e.batcher),e.batchId),`vault:quit`)}async dispatch(e){return await this.#f(e.chainId,`dispatch`),this.#p(y((0,o.getAddress)(e.batcher)),`vault:dispatchBatch`)}async finalize(e){return await this.#f(e.chainId,`finalize`),this.#p((await this.#n(e)).config,`vault:finalize`)}async readBatch(e,n){let{chainId:r,batchId:i}=e,a=(0,o.getAddress)(e.batcher),s=n===void 0?void 0:(0,o.getAddress)(n),[c,l,u,d,f,p,m,h,g,_,v]=await Promise.all([I(this.#e.provider,r,a,i),this.#g(r,E(a,i)),this.#g(r,w(a,i)),this.#g(r,ee(a,i)),this.#g(r,T(a,i)),this.#g(r,D(a)),this.#g(r,te(a,i)),this.#h(`decimals:${r}:${a}`,()=>this.#g(r,ne(a))),s===void 0?null:this.#g(r,S(a,i,s)),this.#e.provider.getBlockTimestamp(r),L(this.#e.provider,r,a,i)]),y=l+u,b=d+f,x=g!==null&&!t.c(g),C=[[`claim`,x&&c===`finalized`],[`quit`,x&&(c===`pending`||c===`canceled`)],[`dispatch`,c===`pending`&&!p&&!v&&y<=_],[`finalize`,c===`dispatched`]].flatMap(([e,t])=>t?[e]:[]),O=c===`pending`?y:c===`dispatched`?b:null,k={chainId:r,batcher:a,batchId:i,createdAt:l,dispatchableAt:y,paused:p,deposit:g,actions:C,observedAt:_,nextChangeAt:O!==null&&O>_?O:null};switch(c){case`pending`:return{...k,state:c};case`finalized`:return{...k,state:c,dispatchedAt:d,cancelsAt:b,exchangeRate:{rate:m,decimals:h}};default:return{...k,state:c,dispatchedAt:d,cancelsAt:b}}}async readOpenBatches(e,t){let{vaults:n,chainId:r}=u(e),{now:i,next:a}=await F(this.#e.provider,r,n,t);return a.map(({vault:e,offer:{status:t,batcher:n,batchId:a,dispatchableAt:o}})=>({vaultId:e.id,chainId:r,batcher:n,batchId:a,dispatchableAt:o,paused:t===`paused`,observedAt:i}))}async#r(t,r,a,s){let{group:c,vaults:l,chainId:d}=u(r),f=c===void 0?l[0]:oe(c,a.vaultId),p=(0,o.getAddress)(a.account),m=c===void 0?`direct`:s?.route??`router`;await this.#m(d,`vault ${t}`);let h=c!==void 0&&m===`router`?this.#a(c):void 0,{next:g}=await F(this.#e.provider,d,l,t),_=g.map(({vault:e,offer:n})=>{if(n.status===`paused`)throw new i.c(c===void 0?`Every ${t} batcher of vault "${e.id}" is paused or closed, so the vault cannot be joined until one resumes`:`Every ${t} batcher of vault "${e.id}" in group "${c.id}" is paused or closed, so no vault of the group can be joined until one resumes`,{batcher:n.batcher,vaultId:e.id});return n.batcher}),v=await Promise.all(_.map(e=>this.#o(d,e))),y=J(l.map((e,t)=>({vaultId:e.id,batcher:K(_,t),token:K(v,t),amount:e===f?a.amount:0n}))),b=K(y,l.indexOf(f)),x=y.find(e=>t===`deposit`&&e.token!==b.token);if(x!==void 0)throw new n.t(`Vault group "${r.id}" mixes deposit assets: vault "${x.vaultId}" takes ${x.token}, vault "${b.vaultId}" takes ${b.token}`);s?.skipBalanceCheck!==!0&&await this.#s(t,y,b,p);let S=W[t],C=(e,t)=>({config:e,call:{...q(e),kind:`join`,leg:t}}),w,T=[];if(h!==void 0){let n=y.map(e=>e.amount),r=e=>y.map((t,n)=>({batcher:t.batcher,token:t.token,amount:K(e,n)}));if(t===`redeem`){let[[e,t],i]=await Promise.all([this.#c(h,p,n,S),this.#u(d,y,p,h)]);T=i,w=[C(j(h,r(e),t),b)]}else{let t=b.token,[[i,o],[[s],c]]=await Promise.all([this.#c(h,p,n,S),this.#c(t,p,[a.amount],S)]),l=N(r(i),o);w=[C(e.x(t,h,s,c,l),b)]}}else{let t=await this.#l(y,p,S);w=y.map((n,r)=>{let{handle:i,inputProof:a}=K(t,r);return C(e.x(n.token,n.batcher,i,a,`0x`),n)})}let E=[...T,...w];return{prepared:{direction:t,chainId:d,groupId:c?.id,vaultId:f.id,account:p,amount:a.amount,route:m,legs:y,calls:J(E.map(({call:e})=>e))},planned:E}}async#i(n,r,a,o){let s=this.#d(n),{chainId:c}=u(r),l=await this.#f(c,n),{prepared:d,planned:f}=await this.#r(n,r,{...a,account:l},{skipBalanceCheck:o?.skipBalanceCheck}),p=[],m;for(let[e,{call:n,config:r}]of f.entries())m=await t.n({operation:n.kind===`operatorApproval`?`setOperator`:G[d.route],signer:s,provider:this.#e.provider,config:r,onSubmitted:e===f.length-1?o?.onJoinSubmitted:void 0,emit:e=>this.#e.emitEvent(e,n.to),logger:this.#e.logger}),p.push(m.txHash);e.z(m,`vault ${n}: last transaction`);let h=[...m.receipt.logs],g=[],_=[];for(let e of d.legs){let t=H(h,e.batcher,l);t===null?_.push(e.vaultId):g.push({vaultId:e.vaultId,chainId:c,batcher:e.batcher,batchId:t})}if(_.length>0)throw new i.u(`Transaction ${m.txHash} was mined, but its receipt has no Joined event for ${l} from the batcher of ${_.map(e=>`vault "${e}"`).join(`, `)}${`vaults`in r?` in group "${r.id}"`:``}`,{txHash:m.txHash,receipt:m.receipt,unconfirmedVaultIds:_});return{batches:g,txHashes:p}}#a(e){let{chainId:t}=u(e),r=this.#e.chains.find(e=>e.id===t)?.vaultRouterAddress;if(r===void 0)throw new n.t(`Vault group "${e.id}" has ${e.vaults.length} vaults, but chain ${t} has no router; set vaultRouterAddress on the chain`);return(0,o.getAddress)(r)}#o(e,t){return this.#h(`fromToken:${e}:${t}`,async()=>(0,o.getAddress)(await this.#g(e,C(t))))}async#s(e,n,r,i){let a=this.#e.signer?.walletAccount.getSnapshot()?.address;if(a===void 0||(0,o.getAddress)(a)!==i)throw new t.l(`Cannot check the balance of ${i} for a vault ${e}: ${a===void 0?`no signer is connected`:`the signer is another account`}. Check it yourself, decrypting every leg's token together, and pass skipBalanceCheck: true`);await t.a({operation:e,tokenAddress:r.token,amount:r.amount,account:i,signer:this.#e.signer,provider:this.#e.provider,readBalance:async e=>{let i=[...new Set(n.map(e=>e.token))].map(e=>new t.t(this.#e,e)),{results:a,errors:o}=await t.t.batchBalancesOf(i,e),s=a.get(r.token);if(s===void 0)throw o.get(r.token)??new t.l(`Balance validation failed (token: ${r.token})`);return s}})}async#c(e,t,n,i){let{encryptedValues:a,inputProof:o}=await this.#e.encrypt({values:n.map(e=>({value:e,type:`euint64`})),contractAddress:e,userAddress:t},{operation:i}),[s,...c]=a;if(s===void 0||a.length!==n.length)throw new r.r(`Encryption returned ${a.length} values for ${n.length} legs`);return[[s,...c],o]}async#l(t,n,r){let i=/* @__PURE__ */ new Map;return await Promise.all([...new Set(t.map(e=>e.token))].map(async e=>{let a=t.filter(t=>t.token===e),[o,s]=await this.#c(e,n,a.map(e=>e.amount),r);a.forEach((e,t)=>i.set(e,{handle:K(o,t),inputProof:s}))})),t.map(t=>{let n=i.get(t);return e.z(n,`vault leg ${t.vaultId}`),n})}async#u(t,n,r,i){let a=await Promise.all(n.map(n=>this.#g(t,e.D(n.token,r,i)))),o=n.filter((e,t)=>!a[t]);if(o.length===0)return[];let s=await this.#e.provider.getBlockTimestamp(t)+U;return o.map(t=>{let n=e.k(t.token,i,Number(s));return{config:n,call:{...q(n),kind:`operatorApproval`,vaultId:t.vaultId,operator:i,until:s}}})}#d(t){if(this.#e.signer===void 0)throw new e.H(t);return this.#e.signer}async#f(t,n){let r=await e.i(`vault ${n}`,this.#d(n),this.#e.provider,t);return(0,o.getAddress)(r.address)}async#p(e,n){return t.n({operation:n,signer:this.#d(n),provider:this.#e.provider,config:e,emit:t=>this.#e.emitEvent(t,e.address),logger:this.#e.logger})}async#m(t,r){let i=await this.#e.provider.getChainId();if(i===t)return;let a=this.#e.signer?.walletAccount.getSnapshot();throw a===void 0?new n.t(`Operation "${r}" encrypts or decrypts on chain ${t}, but the provider is on chain ${i}`):new e.q({operation:r,signerChainId:a.chainId,providerChainId:i,targetChainId:t})}#h(e,t){return se(this.#t,e,t)}#g(e,t){return this.#e.provider.readContract({...t,chainId:e})}};function le(e){return new ce(e)}const Y=15e3,X={all:[`zama.vault`],batch:(e,t)=>[`zama.vault`,{kind:`batch`,chainId:e?.chainId,batcher:e===void 0?void 0:(0,o.getAddress)(e.batcher),batchId:e?.batchId,account:t===void 0?void 0:(0,o.getAddress)(t)}],openBatches:(e,t)=>[`zama.vault`,{kind:`openBatches`,chainId:l(e),scope:`vaults`in e?`group`:`vault`,id:e.id,direction:t}]};function Z(e,t){return Math.min(Number(e-t)*1e3+1e3,36e5)}function ue(e){if(e===void 0||e.state===`finalized`||e.state===`canceled`)return!1;if(e.nextChangeAt===null)return Y;let t=Z(e.nextChangeAt,e.observedAt);return e.state===`dispatched`?Math.min(t,Y):t}function de(t,n={}){let{batch:r,account:i}=n;return{refetchInterval:e=>ue(e.state.data),queryKey:X.batch(r,i),queryFn:async()=>(e.z(r,`batchQueryOptions: batch`),t.readBatch(r,i)),enabled:r!==void 0&&n.query?.enabled!==!1}}function fe(e){return e.vault??e.group}function pe(e){let t=(e??[]).filter(e=>!e.paused).map(e=>{let t=e.dispatchableAt-60n;return t>e.observedAt?Z(t,e.observedAt):Y});return t.length!==0&&Math.min(...t)}function me(e,t){let n=fe(t);return{refetchInterval:e=>pe(e.state.data),queryKey:X.openBatches(n,t.direction),queryFn:async()=>e.readOpenBatches(n,t.direction)}}function Q(e){e.invalidateQueries({queryKey:X.all}),e.invalidateQueries({queryKey:a.t.confidentialBalance.all}),e.invalidateQueries({queryKey:a.t.confidentialBalances.all})}function $(e,t){return{mutationKey:[`zama.vault.${t}`],mutationFn:async({skipBalanceCheck:n,onJoinSubmitted:r,amount:i,...a})=>{let o={skipBalanceCheck:n,onJoinSubmitted:r};return a.vault===void 0?e[t](a.group,{vaultId:a.vaultId,amount:i},o):e[t](a.vault,{amount:i},o)}}}function he(e){return $(e,`deposit`)}function ge(e){return $(e,`redeem`)}function _e(e){return{mutationKey:[`zama.vault.claim`],mutationFn:async({account:t,...n})=>e.claim(n,t)}}function ve(e){return{mutationKey:[`zama.vault.quit`],mutationFn:async t=>e.quit(t)}}function ye(e){return{mutationKey:[`zama.vault.dispatch`],mutationFn:async t=>e.dispatch(t)}}function be(e){return{mutationKey:[`zama.vault.finalize`],mutationFn:async t=>e.finalize(t)}}exports.MAX_GROUP_VAULTS=8,exports.batchQueryOptions=de,exports.claimMutationOptions=_e,exports.createVaultClient=le,exports.defineVault=s,exports.defineVaultGroup=c,exports.depositMutationOptions=he,exports.dispatchMutationOptions=ye,exports.finalizeMutationOptions=be,exports.invalidateAfterVaultAction=Q,exports.openBatchesQueryOptions=me,exports.quitMutationOptions=ve,exports.redeemMutationOptions=ge,exports.vaultQueryKeys=X;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|