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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/chains/index.cjs +1 -1
  4. package/dist/cjs/chains.cjs +1 -1
  5. package/dist/cjs/chains.cjs.map +1 -1
  6. package/dist/cjs/index.cjs +1 -1
  7. package/dist/cjs/index.cjs.map +1 -1
  8. package/dist/cjs/node/index.cjs +1 -1
  9. package/dist/cjs/relayer.cjs +1 -1
  10. package/dist/cjs/relayer.cjs.map +1 -1
  11. package/dist/esm/base-signer-CwsN9lXD.js +2 -0
  12. package/dist/esm/{base-signer-D5Cwv7yb.js.map → base-signer-CwsN9lXD.js.map} +1 -1
  13. package/dist/esm/{base-signer-DIYZwDnc.d.ts → base-signer-D902THgk.d.ts} +2 -2
  14. package/dist/esm/chains/index.d.ts +2 -2
  15. package/dist/esm/chains/index.js +1 -1
  16. package/dist/esm/{chains-ByyCdrrd.js → chains-iPpnjXql.js} +2 -2
  17. package/dist/esm/{chains-ByyCdrrd.js.map → chains-iPpnjXql.js.map} +1 -1
  18. package/dist/esm/cleartext/index.d.ts +2 -2
  19. package/dist/esm/cleartext/index.js +1 -1
  20. package/dist/esm/{cleartext-PCpNqRGV.js → cleartext-B58fIRPQ.js} +2 -2
  21. package/dist/esm/{cleartext-PCpNqRGV.js.map → cleartext-B58fIRPQ.js.map} +1 -1
  22. package/dist/esm/{cleartext-3HOk1BAg.d.ts → cleartext-B6vrnBzO.d.ts} +2 -2
  23. package/dist/esm/{encryption-BKoalB4o.js → encryption-6AVd-82z.js} +2 -2
  24. package/dist/esm/{encryption-BKoalB4o.js.map → encryption-6AVd-82z.js.map} +1 -1
  25. package/dist/esm/{erc165-DbMOt-s6.js → erc165-rAtrIcS8.js} +2 -2
  26. package/dist/esm/{erc165-DbMOt-s6.js.map → erc165-rAtrIcS8.js.map} +1 -1
  27. package/dist/esm/ethers/index.d.ts +4 -4
  28. package/dist/esm/ethers/index.js +1 -1
  29. package/dist/esm/{fhevm-relayer-CtrnKjJf.js → fhevm-relayer-Y5XYNOcs.js} +2 -2
  30. package/dist/esm/{fhevm-relayer-CtrnKjJf.js.map → fhevm-relayer-Y5XYNOcs.js.map} +1 -1
  31. package/dist/esm/{index-ijgDL4IC.d.ts → index-Cdbp_93f.d.ts} +24 -4
  32. package/dist/esm/{index-BHrjck_q.d.ts → index-CsuDB4UI.d.ts} +4 -4
  33. package/dist/esm/{index-DJYq1rAB.d.ts → index-DlpdjcMQ.d.ts} +1542 -1091
  34. package/dist/esm/index.d.ts +108 -8
  35. package/dist/esm/index.js +1 -1
  36. package/dist/esm/index.js.map +1 -1
  37. package/dist/esm/node/index.d.ts +5 -5
  38. package/dist/esm/node/index.js +1 -1
  39. package/dist/esm/node/index.js.map +1 -1
  40. package/dist/esm/query/index.d.ts +4 -495
  41. package/dist/esm/query/index.js +1 -1
  42. package/dist/esm/{relayer-CVKO9GmQ.js → relayer-C3jVhqSK.js} +2 -2
  43. package/dist/esm/{relayer-CVKO9GmQ.js.map → relayer-C3jVhqSK.js.map} +1 -1
  44. package/dist/esm/{token-CRJ8eCr7.js → token-CBG_zTyz.js} +2 -2
  45. package/dist/esm/{token-CRJ8eCr7.js.map → token-CBG_zTyz.js.map} +1 -1
  46. package/dist/esm/{types-Bz5-wHPv.d.ts → types-Crf7ymyj.d.ts} +2 -2
  47. package/dist/esm/{types-v0_sfkli.d.ts → types-CuldbZne.d.ts} +3 -3
  48. package/dist/esm/{types-CI6BtpB7.d.ts → types-DnJSNoEC.d.ts} +3 -3
  49. package/dist/esm/{validation-BRu06AM_.js → validation-ClSvPh6P.js} +2 -2
  50. package/dist/esm/{validation-BRu06AM_.js.map → validation-ClSvPh6P.js.map} +1 -1
  51. package/dist/esm/vaults/index.d.ts +2 -3
  52. package/dist/esm/vaults/index.js +1 -1
  53. package/dist/esm/viem/index.d.ts +4 -4
  54. package/dist/esm/viem/index.js +1 -1
  55. package/dist/esm/web/index.d.ts +1 -1
  56. package/dist/esm/web/index.js +1 -1
  57. package/dist/esm/{wrapped-token-BOtzaSAY.js → wrapped-token-BpvG7nqK.js} +2 -2
  58. package/dist/esm/{wrapped-token-BOtzaSAY.js.map → wrapped-token-BpvG7nqK.js.map} +1 -1
  59. package/package.json +1 -1
  60. package/dist/esm/base-signer-D5Cwv7yb.js +0 -2
  61. package/dist/esm/invalidation-CJ-pzOUG.d.ts +0 -46
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../fhevm-relayer.cjs"),t=require("../cleartext.cjs"),n=require("../chains.cjs");let r=require("node:async_hooks");function i(t){return{type:`node`,createRelayer:(n,r)=>new e.t({chain:n,options:t,logger:r})}}var a=class{#e=new r.AsyncLocalStorage;run(e){return this.#e.run(new Map,e)}async get(e){return this.#e.getStore()?.get(e)??null}async set(e,t){this.#e.getStore()?.set(e,t)}async delete(e){this.#e.getStore()?.delete(e)}};const o=new a;exports.AsyncLocalMapStorage=a,exports.anvil=n.t,exports.asyncLocalStorage=o,exports.bscTestnet=n.n,exports.chains=n.r,exports.cleartext=t.t,exports.hardhat=n.i,exports.hoodi=n.a,exports.ingenTestnet=n.o,exports.mainnet=n.s,exports.node=i,exports.polygon=n.c,exports.polygonAmoy=n.l,exports.sepolia=n.u;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../fhevm-relayer.cjs"),t=require("../cleartext.cjs"),n=require("../chains.cjs");let r=require("node:async_hooks");function i(t){return{type:`node`,createRelayer:(n,r)=>new e.t({chain:n,options:t,logger:r})}}var a=class{#e=new r.AsyncLocalStorage;run(e){return this.#e.run(new Map,e)}async get(e){return this.#e.getStore()?.get(e)??null}async set(e,t){this.#e.getStore()?.set(e,t)}async delete(e){this.#e.getStore()?.delete(e)}};const o=new a;exports.AsyncLocalMapStorage=a,exports.anvil=n.t,exports.asyncLocalStorage=o,exports.bscTestnet=n.n,exports.chains=n.r,exports.cleartext=t.t,exports.hardhat=n.i,exports.hoodi=n.a,exports.ingenTestnet=n.o,exports.mainnet=n.s,exports.node=i,exports.polygon=n.c,exports.polygonAmoy=n.l,exports.sepolia=n.u,exports.zenithTrexTestnet=n.d;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -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){if(!(e instanceof Error))return!1;if(e.name===`ContractFunctionExecutionError`||e.name===`ContractFunctionRevertedError`||`code`in e&&e.code===`CALL_EXCEPTION`)return!0;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}const n=[`cause`,`error`,`info`];function r(e,t,i=6){if(i<0||typeof e!=`object`||!e)return;let a=e;if(t(a))return a;for(let e of n){let n=a[e];if(typeof n==`object`&&n){let e=r(n,t,i-1);if(e)return e}}}function i(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 a(e){if(i(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 o(e){return r(e,e=>typeof e.name==`string`&&e.name.startsWith(`Relayer`))!==void 0}function s(e){return r(e,e=>e.name===`RelayerTimeoutError`)!==void 0}function c(e){return!o(e)&&r(e,a)!==void 0}function l(e){return!o(e)&&r(e,i)!==void 0}function u(e){return e.toLowerCase().includes(`is not authorized to decrypt handle`)}function d(e){return e.toLowerCase().includes(`invalid transportkeypair`)}const f=[`data`,`raw`,`signature`];function p(e){for(let t of f){let n=e[t];if(typeof n==`string`&&n.toLowerCase().startsWith(`0x77ddbe81`))return!0}if(typeof e.message==`string`){let t=e.message.toLowerCase();return t.includes(`0x77ddbe81`)||t.includes(`invalidkmscontext`)}return!1}function m(e){return r(e,p)!==void 0}function h(e){return/handle (0x[0-9a-fA-F]{64})/.exec(e)?.[1]}function g(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 _(e){if(typeof e!=`object`||!e)return;let t=e.get;if(typeof t==`function`)return g(t.call(e,`Retry-After`))}function v(e){let t=e.response;if(typeof t==`object`&&t)return _(t.headers)}function y(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function b(e){return y(e.retryAfter)?e.retryAfter:v(e)}function x(e){let t=r(e,e=>b(e)!==void 0);return t?b(t):void 0}function S(e){let t=r(e,e=>typeof e.statusCode==`number`||typeof e.status==`number`);if(t)return typeof t.statusCode==`number`?t.statusCode:t.status}function C(e){let t=r(e,e=>typeof e.code==`number`&&e.code!==-1);return t?t.code:void 0}function w(e){return e instanceof Error&&e.name!==`Error`?e.name:void 0}const T={SigningRejected:`SIGNING_REJECTED`,SigningFailed:`SIGNING_FAILED`,EncryptionFailed:`ENCRYPTION_FAILED`,DecryptionFailed:`DECRYPTION_FAILED`,EncryptOffloadUnavailable:`ENCRYPT_OFFLOAD_UNAVAILABLE`,TransactionReverted:`TRANSACTION_REVERTED`,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`,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`},E={[T.SigningRejected]:!1,[T.SigningFailed]:!1,[T.EncryptionFailed]:!1,[T.DecryptionFailed]:!1,[T.EncryptOffloadUnavailable]:!1,[T.TransactionReverted]:!1,[T.TransportKeyPairExpired]:!1,[T.InvalidTransportKeyPair]:!1,[T.RevokedKmsContext]:!1,[T.NoCiphertext]:!1,[T.RelayerRequestFailed]:!1,[T.NotEntitled]:!1,[T.RpcRateLimited]:!0,[T.Configuration]:!1,[T.DelegationSelfNotAllowed]:!1,[T.DelegationCooldown]:!0,[T.DelegationNotFound]:!1,[T.DelegationExpired]:!1,[T.InsufficientConfidentialBalance]:!1,[T.InsufficientERC20Balance]:!1,[T.InsufficientAllowance]:!1,[T.BalanceCheckUnavailable]:!1,[T.ERC20ReadFailed]:!1,[T.DelegationExpiryUnchanged]:!1,[T.DelegationDelegateEqualsContract]:!1,[T.DelegationContractIsSelf]:!1,[T.AclPaused]:!1,[T.DelegationExpirationTooSoon]:!1,[T.DelegationNotPropagated]:!0,[T.ChainMismatch]:!1,[T.SignerNotConfigured]:!1,[T.WalletNotConnected]:!1,[T.WalletAccountNotReady]:!0,[T.KeyWrappingFailed]:!1,[T.TransportKeyPairChanged]:!1,[T.PreparedPermitChainMismatch]:!1,[T.PreparedPermitExpired]:!1,[T.UnshieldAlreadyFinalized]:!1};var D=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??E[e]}};function O(e){return e instanceof D&&e.retryable}function k(e){if(!O(e)||!(`retryAfter`in e))return;let t=e.retryAfter;return y(t)?t:void 0}var A=class extends D{statusCode;retryAfter;constructor(e,t,n){let r=n?.retryable??t===429;super(T.RelayerRequestFailed,e,{...n,retryable:r}),this.name=`RelayerRequestFailedError`,this.statusCode=t,this.retryAfter=r?n?.retryAfter:void 0}},j=class extends D{constructor(e,t){super(T.Configuration,e,t),this.name=`ConfigurationError`}};Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return y}});
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){if(!(e instanceof Error))return!1;if(e.name===`ContractFunctionExecutionError`||e.name===`ContractFunctionRevertedError`||`code`in e&&e.code===`CALL_EXCEPTION`)return!0;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}const n=[`cause`,`error`,`info`];function r(e,t,i=6){if(i<0||typeof e!=`object`||!e)return;let a=e;if(t(a))return a;for(let e of n){let n=a[e];if(typeof n==`object`&&n){let e=r(n,t,i-1);if(e)return e}}}function i(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 a(e){if(i(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 o(e){return r(e,e=>typeof e.name==`string`&&e.name.startsWith(`Relayer`))!==void 0}function s(e){return r(e,e=>e.name===`RelayerTimeoutError`)!==void 0}function c(e){return!o(e)&&r(e,a)!==void 0}function l(e){return!o(e)&&r(e,i)!==void 0}function u(e){return e.toLowerCase().includes(`is not authorized to decrypt handle`)}function d(e){return e.toLowerCase().includes(`invalid transportkeypair`)}const f=[`data`,`raw`,`signature`];function p(e){for(let t of f){let n=e[t];if(typeof n==`string`&&n.toLowerCase().startsWith(`0x77ddbe81`))return!0}if(typeof e.message==`string`){let t=e.message.toLowerCase();return t.includes(`0x77ddbe81`)||t.includes(`invalidkmscontext`)}return!1}function m(e){return r(e,p)!==void 0}function h(e){return/handle (0x[0-9a-fA-F]{64})/.exec(e)?.[1]}function g(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 _(e){if(typeof e!=`object`||!e)return;let t=e.get;if(typeof t==`function`)return g(t.call(e,`Retry-After`))}function v(e){let t=e.response;if(typeof t==`object`&&t)return _(t.headers)}function y(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function b(e){return y(e.retryAfter)?e.retryAfter:v(e)}function x(e){let t=r(e,e=>b(e)!==void 0);return t?b(t):void 0}function S(e){let t=r(e,e=>typeof e.statusCode==`number`||typeof e.status==`number`);if(t)return typeof t.statusCode==`number`?t.statusCode:t.status}function C(e){let t=r(e,e=>typeof e.code==`number`&&e.code!==-1);return t?t.code:void 0}function w(e){return e instanceof Error&&e.name!==`Error`?e.name:void 0}const T={SigningRejected:`SIGNING_REJECTED`,SigningFailed:`SIGNING_FAILED`,EncryptionFailed:`ENCRYPTION_FAILED`,DecryptionFailed:`DECRYPTION_FAILED`,EncryptOffloadUnavailable:`ENCRYPT_OFFLOAD_UNAVAILABLE`,TransactionReverted:`TRANSACTION_REVERTED`,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`},E={[T.SigningRejected]:!1,[T.SigningFailed]:!1,[T.EncryptionFailed]:!1,[T.DecryptionFailed]:!1,[T.EncryptOffloadUnavailable]:!1,[T.TransactionReverted]:!1,[T.TransportKeyPairExpired]:!1,[T.InvalidTransportKeyPair]:!1,[T.RevokedKmsContext]:!1,[T.NoCiphertext]:!1,[T.RelayerRequestFailed]:!1,[T.NotEntitled]:!1,[T.RpcRateLimited]:!0,[T.Configuration]:!1,[T.DelegationSelfNotAllowed]:!1,[T.DelegationCooldown]:!0,[T.DelegationNotFound]:!1,[T.DelegationExpired]:!1,[T.InsufficientConfidentialBalance]:!1,[T.InsufficientERC20Balance]:!1,[T.InsufficientAllowance]:!1,[T.BalanceCheckUnavailable]:!1,[T.ERC20ReadFailed]:!1,[T.DelegationExpiryUnchanged]:!1,[T.DelegationDelegateEqualsContract]:!1,[T.DelegationDelegateCannotBeWildcard]:!1,[T.DelegationContractIsSelf]:!1,[T.AclPaused]:!1,[T.DelegationExpirationTooSoon]:!1,[T.DelegationNotPropagated]:!0,[T.ChainMismatch]:!1,[T.SignerNotConfigured]:!1,[T.WalletNotConnected]:!1,[T.WalletAccountNotReady]:!0,[T.KeyWrappingFailed]:!1,[T.TransportKeyPairChanged]:!1,[T.PreparedPermitChainMismatch]:!1,[T.PreparedPermitExpired]:!1,[T.UnshieldAlreadyFinalized]:!1};var D=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??E[e]}};function O(e){return e instanceof D&&e.retryable}function k(e){if(!O(e)||!(`retryAfter`in e))return;let t=e.retryAfter;return y(t)?t:void 0}var A=class extends D{statusCode;retryAfter;constructor(e,t,n){let r=n?.retryable??t===429;super(T.RelayerRequestFailed,e,{...n,retryable:r}),this.name=`RelayerRequestFailedError`,this.statusCode=t,this.retryAfter=r?n?.retryAfter:void 0}},j=class extends D{constructor(e,t){super(T.Configuration,e,t),this.name=`ConfigurationError`}};Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return y}});
2
2
  //# sourceMappingURL=relayer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"relayer.cjs","names":[],"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 nodeHasInvalidKmsContextRevert(node: Record<string, unknown>): boolean {\n for (const key of REVERT_DATA_KEYS) {\n const value = node[key];\n if (typeof value === \"string\" && value.toLowerCase().startsWith(INVALID_KMS_CONTEXT_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(INVALID_KMS_CONTEXT_SELECTOR) || msg.includes(\"invalidkmscontext\");\n }\n return false;\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 findInErrorChain(error, nodeHasInvalidKmsContextRevert) !== undefined;\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 /** 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 /** 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} 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.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.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 re-run preparePermit 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 re-run preparePermit for a fresh validity window\n [ZamaErrorCode.UnshieldAlreadyFinalized]: false, // the funds already arrived; the stale pointer is cleared\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,SAAgB,EAAQ,EAAuB,CAO7C,OANI,aAAiB,MACZ,EAEL,OAAO,GAAU,UAAY,GAAkB,YAAa,EACnD,MAAM,OAAO,EAAM,OAAO,CAAC,EAE7B,MAAM,OAAO,CAAK,CAAC,CAChC,CAOA,SAAgB,EAAoB,EAAyB,CAC3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Ac,eAAgB,IAC9B,EAAc,qBAAsB,IACpC,EAAc,oBAAqB,IACnC,EAAc,uBAAwB,IACtC,EAAc,mBAAoB,IAClC,EAAc,yBAA0B,IACxC,EAAc,6BAA8B,IAC5C,EAAc,uBAAwB,IACtC,EAAc,0BAA2B,EAC5C,EAOA,IAAa,EAAb,cAA+B,KAAM,CAEnC,KASA,UAEA,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,CAAO,EACtB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,EAChD,KAAK,KAAO,YACZ,KAAK,KAAO,EACZ,KAAK,UAAY,GAAS,WAAa,EAAkB,EAC3D,CACF,EAwBA,SAAgB,EAAY,EAA0D,CACpF,OAAO,aAAiB,GAAa,EAAM,SAC7C,CAUA,SAAgB,EAAkB,EAAoC,CACpE,GAAI,CAAC,EAAY,CAAK,GAAK,EAAE,eAAgB,GAC3C,OAEF,IAAM,EAAc,EAA+C,WACnE,OAAO,EAAyB,CAAU,EAAI,EAAa,IAAA,EAC7D,CC9NA,IAAa,EAAb,cAA+C,CAAU,CAEvD,WAQA,WAEA,YACE,EACA,EACA,EACA,CAGA,IAAM,EAAY,GAAS,WAAa,IAAe,IACvD,MAAM,EAAc,qBAAsB,EAAS,CAAE,GAAG,EAAS,WAAU,CAAC,EAC5E,KAAK,KAAO,4BACZ,KAAK,WAAa,EAGlB,KAAK,WAAa,EAAY,GAAS,WAAa,IAAA,EACtD,CACF,EAGa,EAAb,cAAwC,CAAU,CAChD,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAc,cAAe,EAAS,CAAO,EACnD,KAAK,KAAO,oBACd,CACF"}
1
+ {"version":3,"file":"relayer.cjs","names":[],"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 nodeHasInvalidKmsContextRevert(node: Record<string, unknown>): boolean {\n for (const key of REVERT_DATA_KEYS) {\n const value = node[key];\n if (typeof value === \"string\" && value.toLowerCase().startsWith(INVALID_KMS_CONTEXT_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(INVALID_KMS_CONTEXT_SELECTOR) || msg.includes(\"invalidkmscontext\");\n }\n return false;\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 findInErrorChain(error, nodeHasInvalidKmsContextRevert) !== undefined;\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 /** 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} 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.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 re-run preparePermit 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 re-run preparePermit for a fresh validity window\n [ZamaErrorCode.UnshieldAlreadyFinalized]: false, // the funds already arrived; the stale pointer is cleared\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,SAAgB,EAAQ,EAAuB,CAO7C,OANI,aAAiB,MACZ,EAEL,OAAO,GAAU,UAAY,GAAkB,YAAa,EACnD,MAAM,OAAO,EAAM,OAAO,CAAC,EAE7B,MAAM,OAAO,CAAK,CAAC,CAChC,CAOA,SAAgB,EAAoB,EAAyB,CAC3D,GAAI,EAAE,aAAiB,OACrB,MAAO,GAUT,GANE,EAAM,OAAS,kCACf,EAAM,OAAS,iCAKb,SAAU,GAAS,EAAM,OAAS,iBACpC,MAAO,GAGT,IAAM,EAAM,EAAM,QAAQ,YAAY,EACtC,OAAO,EAAI,SAAS,oBAAoB,GAAK,EAAI,SAAS,uBAAuB,CACnF,CAGA,MAGM,EAAoB,CAAC,QAAS,QAAS,MAAM,EAQnD,SAAS,EACP,EACA,EACA,EAAQ,EAC6B,CACrC,GAAI,EAAQ,GAA8C,OAAO,GAAU,WAA1D,EACf,OAEF,IAAM,EAAO,EACb,GAAI,EAAU,CAAI,EAChB,OAAO,EAET,IAAK,IAAM,KAAO,EAAmB,CACnC,IAAM,EAAO,EAAK,GAClB,GAA2C,OAAO,GAAS,UAAvD,EAAiE,CACnE,IAAM,EAAQ,EAAiB,EAAM,EAAW,EAAQ,CAAC,EACzD,GAAI,EACF,OAAO,CAEX,CACF,CAEF,CAoBA,SAAS,EAA2B,EAAwC,CAC1E,GAAI,EAAK,OAAS,QAA2B,EAAK,SAAW,KAAO,EAAK,OAAS,IAChF,MAAO,GAGT,GAAI,EAAK,OAAS,gBAAkB,OAAO,EAAK,MAAS,UAAY,EAAK,OAAS,KAAM,CACvF,IAAM,EAAkB,EAAK,KAAiC,eAC9D,GAAI,OAAO,GAAmB,UAAY,YAAY,KAAK,C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AAO,4BACZ,KAAK,WAAa,EAGlB,KAAK,WAAa,EAAY,GAAS,WAAa,IAAA,EACtD,CACF,EAGa,EAAb,cAAwC,CAAU,CAChD,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAc,cAAe,EAAS,CAAO,EACnD,KAAK,KAAO,oBACd,CACF"}
@@ -0,0 +1,2 @@
1
+ import{p as e,r as t,t as n}from"./relayer-C3jVhqSK.js";import{H as r,K as i,L as a,M as o,P as s,W as c,Y as l,d as u,f as d,j as f,m as p,p as m,q as ee}from"./erc165-rAtrIcS8.js";import{r as h}from"./applied-runtime-3fzqBC2V.js";import{a as te,i as ne,n as g,o as _,r as v,s as y,t as b}from"./primitives-Cym-3HKa.js";import{t as x}from"./validation-ClSvPh6P.js";import{a as S,i as re,n as C,o as w,r as ie,s as ae,t as T}from"./wrappers-registry-Cm3JJeqx.js";import{a as E,c as oe,d as se,l as ce,n as le,o as ue,s as de,u as fe}from"./chains-iPpnjXql.js";import{getAddress as D,toBytes as O,toHex as k,zeroAddress as A}from"viem";import{hasFhevmRuntimeConfig as pe,setFhevmRuntimeConfig as me}from"@fhevm/sdk/viem";import{z as j}from"zod/mini";var M=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const he=new M;var N=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const ge=new N;function _e(){return typeof window<`u`?new M(`CredentialStore`):new N}function ve(e=_e(),t=e){return{storage:e,permitStorage:t}}function ye(e,t,r){let i=e.map(e=>e.id),a=[...new Set(i.filter((e,t)=>i.indexOf(e)!==t))];if(a.length>0)throw new n(`Duplicate chain id(s) [${a.join(`, `)}] in the chains array. Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`);let o=Object.keys(t).map(Number).filter(e=>!i.includes(e));o.length>0&&r.warn(`Relayer entries for chain(s) [${o.join(`, `)}] are ignored: those chains are not in the chains array. Add the chain config to use them, or drop the relayer entries.`);let s=new Map;for(let r of e){let e=t[r.id];if(!e)throw new n(`Chain ${r.id} has no relayer configured. Add a relayer entry: relayers: { [${r.id}]: web() }`);s.set(r.id,{chain:r,relayerConfig:e})}return s}var be=class{#e;#t;#n;constructor(e,t,r){if(e.length===0)throw new n(`At least one chain is required.`);this.#e=new Map(e.map(e=>[e.id,e])),this.#n=e[0].id;let i=new Map;for(let[n,{relayerConfig:a,chain:o}]of ye(e,t,r))i.set(n,a.createRelayer(o,r));this.#t=i}get chains(){return[...this.#e.values()]}get chain(){let e=this.#e.get(this.#n);if(e===void 0)throw new n(`Chain ${this.#n} is not configured. Add it to the chains array.`);return e}switchChain(e){this.#n=e}dispose(){for(let e of new Set(this.#t.values()))e.dispose?.()}get relayer(){let e=this.#t.get(this.chain.id);if(e===void 0)throw new n(`No relayer configured for chain ${this.#n}. Add it to the relayers object.`);return e}};const P={version:1,info:`zama-sdk-keypair-wrapping-v1`,ivLengthBytes:12,tagLengthBytes:16};function F(e){return new Uint8Array(e)}function I(e){return F(new TextEncoder().encode(JSON.stringify([e.publicKey,e.createdAt,e.expiresAt,e.tkmsVersion??null])))}function xe(e){return typeof e==`string`?new TextEncoder().encode(e):F(e)}var Se=class{#e;#t;constructor(e){this.#e=e}async baseKey(){return this.#t??=this.#n(this.#e),this.#t}async#n(e){let t=xe(e),n=await crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return t.fill(0),e instanceof Uint8Array&&e.fill(0),this.#e=void 0,n}};async function L(e,t){let n=await e.baseKey();return crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:new TextEncoder().encode(t),info:new TextEncoder().encode(P.info)},n,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function Ce(e,t,n,r){let i=await L(t,n),a=crypto.getRandomValues(new Uint8Array(P.ivLengthBytes)),o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:a,additionalData:I(r)},i,F(O(e)));return{wrappedPrivateKey:k(new Uint8Array(o)),iv:k(a)}}async function we(e,t,n,r){let i=await L(t,n),a=await crypto.subtle.decrypt({name:`AES-GCM`,iv:F(O(e.iv)),additionalData:I(r)},i,F(O(e.wrappedPrivateKey)));return k(new Uint8Array(a))}function Te(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`OperationError`}const R=86400;function z(){return Math.floor(Date.now()/1e3)}function B(e){return[...new Set(e.map(b))].sort()}function Ee(e){let{chainId:t}=e.domain;return typeof t==`bigint`?{...e,domain:{...e.domain,chainId:t.toString()}}:e}const V=`transportKeyPairTTL must be a positive integer number of seconds`,H=`permitTTL must be a positive integer number of days`,U=`transportKeyPairScope must be a non-empty string`,W=`transportKeyPairDerivationSecret must be a Uint8Array of at least 32 bytes or a string of at least 64 characters (256 bits of entropy): source it from a CSPRNG or secrets manager, not a human-memorable passphrase`,De=365*R,Oe=j.int({error:V}).check(j.positive({error:V}),j.maximum(De,`transportKeyPairTTL must not exceed the fhevm ACL maximum of ${De}s (365 days)`)),ke=j.int({error:H}).check(j.positive({error:H}),j.maximum(365,`permitTTL must not exceed the V1 permit maximum of 365 days`)),Ae=j.string({error:U}).check(j.minLength(1,U)),je=j.union([j.string({error:W}).check(j.minLength(64,W)),j.instanceof(Uint8Array,{error:W}).check(j.refine(e=>e.byteLength>=32,{error:W}))],{error:W}),Me=j.object({publicKey:v,privateKey:v,createdAt:y,expiresAt:_,tkmsVersion:j.optional(j.string())}),G=j.object({domain:j.record(j.string(),j.unknown()),primaryType:j.optional(j.string()),types:j.record(j.string(),j.array(j.object({name:j.string(),type:j.string()}))),message:j.record(j.string(),j.unknown())}),K=j.object({version:j.int().check(j.positive()),eip712:G,signature:v,signerAddress:g}),q=j.object({keypairPublicKey:v,contractAddresses:j.array(g).check(j.maxLength(10)),serializedPermit:K,startTimestamp:y,durationDays:te}),Ne=j.array(q),Pe=j.array(j.string()),Fe=j.object({version:j.literal(1),eip712:G,signerAddress:g}),Ie=`iv must be a ${P.ivLengthBytes}-byte hex string`,Le=`wrappedPrivateKey must be a whole number of bytes and at least ${P.tagLengthBytes} bytes (the AES-GCM authentication tag)`;function Re(e){return(e.length-2)/2}const ze=j.object({wrappingVersion:j.literal(P.version,{error:`wrappingVersion must be a wrapping scheme this SDK can read`}),publicKey:v,wrappedPrivateKey:v.check(j.refine(e=>e.length%2==0&&Re(e)>=P.tagLengthBytes,{error:Le})),iv:v.check(j.refine(e=>Re(e)===P.ivLengthBytes,{error:Ie})),createdAt:y,expiresAt:_,tkmsVersion:j.optional(j.string())});function Be(e){let t={publicKey:e.publicKey,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(t.tkmsVersion=e.tkmsVersion),t}const J={version:P.version,schema:ze,async encode(e,t,n){let{wrappedPrivateKey:r,iv:i}=await Ce(e.privateKey,t,n,Be(e)),a={wrappingVersion:P.version,publicKey:e.publicKey,wrappedPrivateKey:r,iv:i,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(a.tkmsVersion=e.tkmsVersion),a},async decode(e,t,n){let r=await we({wrappedPrivateKey:e.wrappedPrivateKey,iv:e.iv},t,n,Be(e)),i={publicKey:e.publicKey,privateKey:r,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(i.tkmsVersion=e.tkmsVersion),i}},Ve=new Map([[J.version,J]]),He=J;function Ue(e){let t=e;return t.wrappingVersion!==void 0||t.wrappedPrivateKey!==void 0&&t.iv!==void 0}function We(e){if(typeof e!=`object`||!e||!Ue(e)){let t=Me.safeParse(e);return t.success?{kind:`plaintext`,keyPair:t.data}:{kind:`unrecognized`}}let t=e.wrappingVersion,n=typeof t==`number`?Ve.get(t):void 0;if(n===void 0)return{kind:`unsupported-version`,version:t};let r=n.schema.safeParse(e);if(!r.success)return{kind:`corrupt-wrapped`};let i=r.data;return{kind:`wrapped`,expiresAt:i.expiresAt,decode:(e,t)=>n.decode(i,e,t)}}function Ge(e,t,n){return He.encode(e,t,n)}function Ke(e){return`keypair:${e}`}function Y(e){return`keypair:scope:${e}`}function X(e){return`permits:${e.signerAddress}:${e.chainId}:${e.delegatorAddress}`}function Z(e){return`permits-index:${e}`}function qe(e){return`scope:${e}`}function Je(e,t){return{"wrapped-without-secret":`Transport key pair for scope "${t}" is wrapped, but this instance has no transportKeyPairDerivationSecret configured. Every instance sharing this scope must use the same transportKeyPairDerivationSecret; once they do, call permits.revokeTransportKeyPair() to rotate the entry.`,"unwrapped-under-secret":`Transport key pair for scope "${t}" is stored unwrapped, but this instance is configured with a transportKeyPairDerivationSecret. A peer instance sharing this scope is running without the secret: configure the same transportKeyPairDerivationSecret everywhere, then call permits.revokeTransportKeyPair() to migrate the scope to a wrapped entry.`,"unwrap-failed":`Transport key pair for scope "${t}" failed to unwrap. This usually means another instance created it with a different transportKeyPairDerivationSecret: every instance sharing this scope must use the same secret. It can also mean the stored entry is corrupted.`,"corrupt-wrapped":`Transport key pair for scope "${t}" is wrapped but structurally invalid: the stored iv or ciphertext is not a shape this wrapping scheme can produce. This usually means the stored entry is corrupted, or instances sharing this scope are running mismatched wrapping-scheme versions.`}[e]}const Ye={"unwrapped-under-secret":`unwrapped transport key pair entry found while a transportKeyPairDerivationSecret is configured`,"unwrap-failed":`transport key pair entry failed to unwrap (wrong transportKeyPairDerivationSecret?)`,"corrupt-wrapped":`structurally invalid wrapped transport key pair entry`};function Xe(e,t){let n=typeof e==`number`?`wrappingVersion ${e}`:`no wrappingVersion this build recognizes`;return`Transport key pair ${t===void 0?`for this signer`:`for scope "${t}"`} was written under a wrapping scheme this SDK build cannot read (${n}). The entry is preserved instead of regenerated, since an instance that understands the scheme may still be using it: ${t===void 0?`run a build that supports it, or call permits.clear() to discard the entry deliberately`:`run a build that supports it everywhere, or call permits.revokeTransportKeyPair() to rotate the scope`}.`}var Ze=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=new Map;constructor(e){this.#e=e.generator,this.#t=e.storage,this.#n=e.ttl,this.#r=e.logger,this.#i=e.scope,this.#a=e.derivationSecret}#c(e){return this.#i===void 0?`signer:${e}`:qe(this.#i)}#l(e){return this.#i===void 0?Ke(e):Y(this.#i)}async readStored(e){return this.#u(this.#l(e),this.#c(e))}async#u(e,t){let n=await this.#t.get(e);if(n==null)return null;let r=We(n);if(r.kind===`unsupported-version`)throw this.#f(e,Xe(r.version,this.#i));if(r.kind===`unrecognized`)return await this.#m(e,`malformed transport key pair entry`),null;let i=this.#a;if(i===void 0)return r.kind===`plaintext`?await this.#p(e,r.keyPair.expiresAt)?null:r.keyPair:this.#d(e,`wrapped-without-secret`);if(r.kind===`plaintext`)return this.#d(e,`unwrapped-under-secret`);if(r.kind===`corrupt-wrapped`)return this.#d(e,`corrupt-wrapped`);if(await this.#p(e,r.expiresAt))return null;try{return await r.decode(i,t)}catch(t){if(!Te(t))throw this.#r.error(`transport key pair unwrap failed unexpectedly`,{key:e,error:t}),new c(`Transport key pair unwrap failed unexpectedly.`,{cause:t});return this.#d(e,`unwrap-failed`,t)}}async#d(e,t,n){if(this.#i!==void 0)throw this.#f(e,Je(t,this.#i),n);if(t===`wrapped-without-secret`)throw this.#f(e,`Transport key pair for this signer is wrapped, but this instance has no transportKeyPairDerivationSecret configured. Configure the same transportKeyPairDerivationSecret the entry was written with. To downgrade to plaintext at rest on purpose, discard the stored entry first by calling permits.clear(), then run without the secret.`,n);let r=Ye[t];return this.#r.warn(r,{key:e}),await this.#m(e,r),null}#f(e,t,n){return this.#r.error(t,{key:e}),new c(t,{cause:n})}async#p(e,t){return z()<t?!1:(await this.#m(e,`expired transport key pair entry`),!0)}async#m(e,t){this.#r.debug(`discarding transport key pair entry`,{key:e,reason:t}),await f(`delete transport key pair entry`,()=>this.#t.delete(e),this.#r)}async getOrCreate(e,t){return this.#h(this.#l(e),this.#c(e),{strict:t?.strict})}async#h(e,t,n){let r=n?.strict??!1,i=`${e}::${r}`,a=this.#o.get(i);if(a)return a;let o=this.#s.get(e)??0,s=(async()=>{let n=await this.#u(e,t);if(n!==null)return n;let i=await this.#e(),a=z(),s=a+this.#n,u={publicKey:i.publicKey,privateKey:i.privateKey,createdAt:a,expiresAt:s};i.tkmsVersion&&(u.tkmsVersion=i.tkmsVersion);let d=u;if(this.#a!==void 0)try{d=await Ge(u,this.#a,t)}catch(t){let n=`Failed to wrap the transport private key for at-rest storage.`;throw this.#r.error(n,{key:e,error:t}),new c(n,{cause:t})}if((this.#s.get(e)??0)===o)r?await this.#t.set(e,d):await f(`persist transport key pair`,()=>this.#t.set(e,d),this.#r);else if(r)throw new l(`The transport key pair was rotated while it was being generated, so the freshly generated key pair could not be persisted. Retry.`);return u})().finally(()=>{this.#o.delete(i)});return this.#o.set(i,s),s}async clear(e){let t=Ke(e);await f(`delete transport key pair entry`,()=>this.#t.delete(t),this.#r)}async evict(e){let t=this.#l(e);await f(`evict transport key pair entry`,()=>this.#t.delete(t),this.#r)}async clearScope(){if(this.#i===void 0)return;let e=Y(this.#i);this.#s.set(e,(this.#s.get(e)??0)+1),await this.#t.delete(e)}async warmScope(){this.#i!==void 0&&await this.#h(Y(this.#i),qe(this.#i),{strict:!0})}};function Qe(e,t){let n=new Set(e.flatMap(e=>e.contractAddresses));return t.filter(e=>!n.has(e))}function $e(e){let t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));return t}function et(e,t,n){return e.filter(e=>e.keypairPublicKey===t&&n<e.startTimestamp+e.durationDays*86400)}function tt(e,t){let n=new Set(t);return e.filter(e=>!e.contractAddresses.some(e=>n.has(e)))}function nt(e,t){return[...new Set([...e,...t])].sort()}function rt(e,t,n){let r=new Set(n),i=e.filter(e=>new Set([...e.contractAddresses,...t]).size<=10);if(i.length===0)return null;function a(e){return e.contractAddresses.reduce((e,t)=>e+ +!!r.has(t),0)}let o=Math.max(...i.map(a));return i.filter(e=>a(e)===o).reduce((e,t)=>t.startTimestamp>e.startTimestamp?t:e)}var it=class{#e;#t;constructor(e){this.#e=e.storage,this.#t=e.logger}async list(e){let t=X(e),n=await this.#e.get(t);if(n==null)return[];let r=Ne.safeParse(n);return r.success?r.data:(await this.clearScope(e),[])}async listUsableAndPrune(e,t){let n=await this.list(e),r=et(n,t,Math.floor(Date.now()/1e3));return r.length!==n.length&&(r.length===0?await this.clearScope(e):await f(`update permit entry`,()=>this.#e.set(X(e),r),this.#t)),r}async append(e,t){if(t.length===0)return;let n=t.map(e=>q.parse(e)),r=await this.list(e);await this.#e.set(X(e),[...r,...n]),await this.#r(e)}async replace(e,t,n){let r=q.parse(n),i=(await this.list(e)).filter(e=>e.serializedPermit.signature!==t);await this.#e.set(X(e),[...i,r]),await this.#r(e)}async deletePermitsTouching(e,t){let n=await this.list(e);if(n.length===0)return;let r=tt(n,t);r.length===0?await this.clearScope(e):await this.#e.set(X(e),r)}async clearScope(e){await this.#a(X(e)),await this.#i(e)}async clearAllForSigner(e){let t=Z(e),n=await this.#n(t);await Promise.all(n.map(e=>this.#a(e))),await f(`delete permit index`,()=>this.#e.delete(t),this.#t)}async#n(e){let t=await this.#e.get(e);if(t==null)return[];let n=Pe.safeParse(t);return n.success?n.data:(await f(`delete permit index`,()=>this.#e.delete(e),this.#t),[])}async#r(e){let t=Z(e.signerAddress),n=X(e),r=await this.#n(t);r.includes(n)||await this.#e.set(t,[...r,n])}async#i(e){let t=Z(e.signerAddress),n=X(e),r=await this.#n(t),i=r.filter(e=>e!==n);i.length!==r.length&&(i.length===0?await f(`delete permit index`,()=>this.#e.delete(t),this.#t):await f(`update permit index`,()=>this.#e.set(t,i),this.#t))}async#a(e){await f(`delete permit entry`,()=>this.#e.delete(e),this.#t)}},at=class{#e;#t;#n;#r;#i;#a;#o;#s;#c=new Map;constructor(e){this.#e=new Ze({generator:async()=>{let t=e.router.relayer,n=await t.generateTransportKeyPair();return t.serializeTransportKeyPair({transportKeyPair:n})},storage:e.storage,ttl:e.transportKeyPairTTL,logger:e.logger,scope:e.scope,derivationSecret:e.derivationSecret}),this.#t=new it({storage:e.permitStorage??e.storage,logger:e.logger}),this.#n=e.router,this.#r=e.signer,this.#i=e.permitTTL,this.#a=e.logger,this.#o=e.emitEvent,this.#s=e.scope}#l(e){if(!this.#r)throw new s(e);return this.#r}#u(e,t){let n=r(t,{operation:e});return this.#o({type:o.PermitError,operation:e,error:n}),n}async grantPermit(e,t){let n=t===void 0?`grantPermit`:`grantDelegationPermit`,r,i,a;try{r=b(this.#l(`grantPermit`).requireWalletAccount(`grantPermit`).address),i=B(e),a=this.#d(r,t)}catch(e){throw this.#u(n,e)}let o=await this.#e.getOrCreate(r);if(i.length===0)return{keypair:o,permissions:[]};let s;try{s=await this.#t.listUsableAndPrune(a,o.publicKey)}catch(e){throw this.#u(n,e)}let c=Qe(s,i);if(c.length>0){let e=rt(s,c,i);if(e!==null){let t=nt(e.contractAddresses,c),n=await this.#f({chunk:t,keypair:o,scope:a});await f(`replace permit`,()=>this.#t.replace(a,e.serializedPermit.signature,n),this.#a),s[s.indexOf(e)]=n}else for(let e of $e(c)){let t=await this.#f({chunk:e,keypair:o,scope:a});s.push(t),await f(`persist permit`,()=>this.#t.append(a,[t]),this.#a)}}let l=new Set(i);return{keypair:o,permissions:s.filter(e=>e.contractAddresses.some(e=>l.has(e)))}}async preparePermit(e){let t=b(e.signer),r=B(e.contracts);if(r.length===0)throw new n(`preparePermit: request.contracts must not be empty.`);if(r.length>10)throw new n(`preparePermit: request.contracts must not exceed 10 addresses per call (got ${r.length}) — grantPermit chunks automatically, preparePermit does not.`);let i=e.delegator?b(e.delegator):void 0;if(i!==void 0&&i===t)throw new n(`preparePermit: request.delegator must differ from request.signer — self-delegation is not allowed.`);let a=e.durationDays===void 0?this.#i:x(ke,e.durationDays),o=this.#n.relayer,s=await this.#e.getOrCreate(t,{strict:!0}),c=await o.parseTransportKeyPair(s),l=z();return{version:1,eip712:Ee(G.parse(await o.createUnsignedLegacyDecryptionPermitEip712({transportKeyPair:c,contractAddresses:r,startTimestamp:l,durationSeconds:a*R,...i&&{delegatorAddress:i}}))),signerAddress:t}}async registerPermit(e,t){let r;try{r=x(Fe,e)}catch(e){throw this.#u(`registerPermit`,e)}let a=this.#n.relayer,o=this.#n.chain.id,{domain:s,message:c}=r.eip712,u=Number(s.chainId);if(u!==o)throw this.#u(`registerPermit`,new i({preparedChainId:u,activeChainId:o}));let d=Number(c.startTimestamp),p=Number(c.durationDays);if(z()>=d+p*86400)throw this.#u(`registerPermit`,new ee(`registerPermit: the prepared permit's validity window (starting ${d}, ${p}d) has already elapsed — call preparePermit again.`));let m=r.signerAddress,h=await this.#e.readStored(m);if(h===null||h.publicKey!==c.publicKey)throw new l(`registerPermit: the transport key pair changed since preparePermit ran — call preparePermit again to rebind the signature request to the current key pair.`);try{let e=await a.parseTransportKeyPair(h),i=await a.parseSignedDecryptionPermit({serializedPermit:{version:r.version,eip712:r.eip712,signature:t,signerAddress:m},transportKeyPair:e});if(i.version!==1)throw new n(`registerPermit: expected a V1 signed permit, got version ${i.version}.`);let s=x(K,await a.serializeSignedDecryptionPermit({signedPermit:i})),c={keypairPublicKey:h.publicKey,contractAddresses:B(i.eip712.message.contractAddresses),serializedPermit:s,startTimestamp:Number(i.eip712.message.startTimestamp),durationDays:Number(i.eip712.message.durationDays)},l={signerAddress:m,chainId:o,delegatorAddress:b(i.encryptedDataOwnerAddress)};await f(`replace permit`,()=>this.#t.replace(l,s.signature,c),this.#a)}catch(e){throw this.#u(`registerPermit`,e)}}async hasPermit(e,t){if(e.length===0)return!0;let n=this.#r?.walletAccount.getSnapshot();if(!n)return!1;let r=b(n.address),i;try{i=await this.#e.readStored(r)}catch(e){if(!(e instanceof c))throw e;return!1}if(i===null)return!1;let a=this.#d(r,t);return Qe(await this.#t.listUsableAndPrune(a,i.publicKey),B(e)).length===0}async revokePermits(e){let t=b(this.#l(`revokePermits`).requireWalletAccount(`revokePermits`).address);if(e===void 0){await this.#t.clearAllForSigner(t);return}let n=B(e);n.length!==0&&await this.#t.deletePermitsTouching(this.#d(t),n)}#d(e,t){return{signerAddress:e,chainId:this.#n.chain.id,delegatorAddress:t?b(t):e}}async clearCredentials(){let e=b(this.#l(`clearCredentials`).requireWalletAccount(`clearCredentials`).address);await this.#e.clear(e),await this.#t.clearAllForSigner(e)}async revokeTransportKeyPair(e){if(this.#s===void 0)throw new n(`revokeTransportKeyPair() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to revoke.`);if(e!==this.#s)throw new n(`revokeTransportKeyPair("${e}") does not match the configured scope ("${this.#s}").`);await this.#e.clearScope()}async warmTransportKeyPair(e){await this.#e.getOrCreate(b(e))}async warmTransportKeyPairScope(e){if(this.#s===void 0)throw new n(`warmTransportKeyPairScope() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to warm.`);if(e!==this.#s)throw new n(`warmTransportKeyPairScope("${e}") does not match the configured scope ("${this.#s}").`);await this.#e.warmScope()}async handleWalletAccountChange(e,t){let n=e?b(e.address):void 0;n!==(t?b(t.address):void 0)&&n&&(await this.#e.clear(n),await this.#t.clearAllForSigner(n))}async#f(n){let{chunk:r,keypair:i,scope:a}=n,o=z(),s=a.delegatorAddress!==a.signerAddress,c=this.#n.relayer;try{let e={transportKeyPair:await c.parseTransportKeyPair(i),contractAddresses:r,startTimestamp:o,durationSeconds:this.#i*R,signerAddress:a.signerAddress,signer:this.#l(`signPermit`)},t=s?await c.signDecryptionPermit({...e,delegatorAddress:a.delegatorAddress}):await c.signDecryptionPermit(e),n=x(K,await c.serializeSignedDecryptionPermit({signedPermit:t}));return{keypairPublicKey:i.publicKey,contractAddresses:r,serializedPermit:n,startTimestamp:o,durationDays:this.#i}}catch(n){let r=s?`grantDelegationPermit`:`grantPermit`;throw!(n instanceof t)&&n instanceof Error&&e(n.message)&&await this.#e.evict(a.signerAddress),this.#u(r,n)}}async evictTransportKeyPair(){let e=this.#r?.walletAccount.getSnapshot();e&&await this.#e.evict(b(e.address))}async recoverPermits(e,t,n){let r=this.#l(`recoverPermits`).requireWalletAccount(`recoverPermits`),i=this.#d(b(r.address),t),a=X(i),o=this.#c.get(a);if(o)return await o,this.grantPermit(e,t);let s=await this.#p(i),c=this.#c.get(a);if(c)return await c,this.grantPermit(e,t);if(s===null)return this.grantPermit(e,t);let l=new Set(n??[]);if(l.size>0&&!s.some(e=>l.has(e.serializedPermit.signature)))return this.grantPermit(e,t);let u=s.filter(e=>!l.has(e.serializedPermit.signature)),d=s.flatMap(e=>e.contractAddresses),f=this.#m(i,d,e,u,t).finally(()=>{this.#c.delete(a)});return this.#c.set(a,f),await f,this.grantPermit(e,t)}async#p(e){try{return await this.#t.list(e)}catch(e){return this.#a.warn(`read permits for recovery failed`,{error:e}),null}}async#m(e,t,n,r,i){await f(`evict revoked permits`,()=>this.#t.clearScope(e),this.#a);try{await this.grantPermit(nt(t,B(n)),i)}catch(t){throw r.length>0&&await f(`restore surviving permits`,async()=>{let t=await this.#t.list(e),n=new Set(t.map(e=>e.serializedPermit.signature)),i=r.filter(e=>!n.has(e.serializedPermit.signature));i.length>0&&await this.#t.append(e,i)},this.#a),t}}},ot=class{#e;#t=`[zama-sdk]`;constructor(e){this.#e=e}error(e,t){this.#e?.error(`${this.#t} ${e}`,t)}warn(e,t){this.#e?.warn(`${this.#t} ${e}`,t)}info(e,t){this.#e?.info(`${this.#t} ${e}`,t)}debug(e,t){this.#e?.debug(`${this.#t} ${e}`,t)}warnAlways(e){console.warn(`${this.#t} ${e}`),this.warn(e)}};const st={[de.id]:de.registryAddress,[oe.id]:oe.registryAddress,[fe.id]:fe.registryAddress,[ce.id]:ce.registryAddress,[E.id]:E.registryAddress,[ue.id]:ue.registryAddress,[se.id]:se.registryAddress,[le.id]:le.registryAddress},ct=j.record(j.string().check(j.regex(/^\d+$/,`expected numeric chain id key`)),g),lt=ne,Q=300*1e3;var ut=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},st,x(j.optional(ct),e.registryAddresses)),this.#t=x(lt,e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let e=await this.provider.getChainId(),t=this.#e[e];if(!t)throw new n(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return D(t)}async listPairs(e={}){let t=e.page??1,r=e.pageSize??100,i=e.metadata??!1;if(t<1)throw new n(`page must be >= 1, got ${t}`);if(r<1)throw new n(`pageSize must be >= 1, got ${r}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.provider.readContract(S(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*r),l=c+BigInt(r)>BigInt(s)?BigInt(s):c+BigInt(r);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:r};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.provider.readContract(w(a,c,l));d=this.#i(u,[...e])}if(!i)return{items:d,total:s,page:t,pageSize:r};let f=`metadata:${a}:${c}:${l}`,p=this.#r(f);if(p===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));p=this.#i(f,n,t?Q:void 0)}return{items:p,total:s,page:t,pageSize:r}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.provider.readContract(m(e.tokenAddress)),this.provider.readContract(p(e.tokenAddress)),this.provider.readContract(u(e.tokenAddress)),this.provider.readContract(d(e.tokenAddress)),this.provider.readContract(m(e.confidentialTokenAddress)),this.provider.readContract(p(e.confidentialTokenAddress)),this.provider.readContract(u(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:s}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=D(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(T(t,n));return o===A?this.#i(r,null,Q):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=D(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(C(t,n));return o===A?this.#i(r,null,Q):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(re(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(S(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(w(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(ie(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(T(t,D(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(C(t,D(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(ae(t,D(e)))}};function dt(e,t,n){let r=new ot(n.logger),i=n.logger,a={wasmAssetLoadMode:`auto`,moduleVersions:`auto`,logger:{error:(e,t)=>i?.error(e,{cause:t}),warn:e=>i?.warn(e),debug:e=>i?.debug(e)},...n.runtime};if(pe()){let e=`runtime configuration is already set and cannot be changed.`;n.runtime===void 0?r.debug(e):r.warn(e)}else me(a),h(a);let{storage:o,permitStorage:s}=ve(n.storage,n.permitStorage),c=new be(n.chains,n.relayers,r);return{chains:n.chains,router:c,provider:t,signer:e,storage:o,permitStorage:s,transportKeyPairTTL:x(Oe,n.transportKeyPairTTL??2592e3),permitTTL:x(ke,n.permitTTL??30),transportKeyPairScope:n.transportKeyPairScope===void 0?void 0:x(Ae,n.transportKeyPairScope),registryTTL:x(lt,n.registryTTL??86400),logger:r,onEvent:n.onEvent}}function ft(e,t){return e?.address===t?.address&&e?.chainId===t?.chainId}var $=class{#e=new Set;#t;#n;constructor(e){this.#t=e,this.#n=e!==void 0}getSnapshot(){return this.#t}isReady(){return this.#n}setSnapshot(e){this.#n=!0;let t=this.#t;ft(t,e)||(this.#t=e,this.#r({previous:t,next:e}))}subscribe(e){this.#e.add(e);let t=this.#t;return t&&e({previous:void 0,next:t}),()=>{this.#e.delete(e)}}#r(e){for(let t of this.#e)t(e)}};function pt(e){return new $(e)}var mt=class{walletAccount;#e=!1;constructor(e){this.walletAccount=new $(e)}requireWalletAccount(e){let t=this.walletAccount.getSnapshot();if(!t)throw new a(e);return t}dispose(){this.#e||(this.#e=!0,this.onDispose())}[Symbol.dispose](){this.dispose()}onDispose(){}};export{st as a,je as c,ge as d,M as f,dt as i,Se as l,$ as n,ut as o,he as p,pt as r,at as s,mt as t,N as u};
2
+ //# sourceMappingURL=base-signer-CwsN9lXD.js.map