@zama-fhe/sdk 3.3.0 → 3.3.1-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +0 -2
  2. package/dist/cjs/base-signer.cjs +1 -1
  3. package/dist/cjs/base-signer.cjs.map +1 -1
  4. package/dist/cjs/chains.cjs +1 -1
  5. package/dist/cjs/chains.cjs.map +1 -1
  6. package/dist/cjs/cleartext/index.cjs +1 -1
  7. package/dist/cjs/cleartext.cjs +2 -0
  8. package/dist/cjs/cleartext.cjs.map +1 -0
  9. package/dist/cjs/ethers/index.cjs.map +1 -1
  10. package/dist/cjs/fhevm-relayer.cjs +2 -0
  11. package/dist/cjs/fhevm-relayer.cjs.map +1 -0
  12. package/dist/cjs/index.cjs +1 -1
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/node/index.cjs +2 -0
  15. package/dist/cjs/node/index.cjs.map +1 -0
  16. package/dist/cjs/query/index.cjs +1 -1
  17. package/dist/cjs/query/index.cjs.map +1 -1
  18. package/dist/cjs/relayer.cjs +1 -1
  19. package/dist/cjs/relayer.cjs.map +1 -1
  20. package/dist/cjs/token.cjs +1 -1
  21. package/dist/cjs/token.cjs.map +1 -1
  22. package/dist/cjs/viem/index.cjs +1 -1
  23. package/dist/cjs/viem/index.cjs.map +1 -1
  24. package/dist/cjs/web/index.cjs +1 -590
  25. package/dist/cjs/web/index.cjs.map +1 -1
  26. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  27. package/dist/esm/base-signer-CI-FYai2.js +2 -0
  28. package/dist/esm/base-signer-CI-FYai2.js.map +1 -0
  29. package/dist/esm/{base-signer-C3Wc5oi9.d.ts → base-signer-Q2EJECrc.d.ts} +2 -2
  30. package/dist/esm/chains/index.d.ts +2 -3
  31. package/dist/esm/chains/index.js +1 -1
  32. package/dist/esm/chains-CLv9HEJ_.js +2 -0
  33. package/dist/esm/chains-CLv9HEJ_.js.map +1 -0
  34. package/dist/esm/cleartext/index.d.ts +3 -2
  35. package/dist/esm/cleartext/index.js +1 -1
  36. package/dist/esm/cleartext-BfXTVQu-.js +2 -0
  37. package/dist/esm/cleartext-BfXTVQu-.js.map +1 -0
  38. package/dist/esm/cleartext-U6sPs_Kd.d.ts +19 -0
  39. package/dist/esm/ethers/index.d.ts +4 -5
  40. package/dist/esm/ethers/index.js +1 -1
  41. package/dist/esm/ethers/index.js.map +1 -1
  42. package/dist/esm/fhevm-relayer-B-lEKfPQ.js +2 -0
  43. package/dist/esm/fhevm-relayer-B-lEKfPQ.js.map +1 -0
  44. package/dist/esm/index-BnIp_-Ak.d.ts +328 -0
  45. package/dist/esm/{index-CYBH0nyo.d.ts → index-D66eC3G7.d.ts} +60 -13
  46. package/dist/esm/index.d.ts +8 -11
  47. package/dist/esm/index.js +1 -1
  48. package/dist/esm/index.js.map +1 -1
  49. package/dist/esm/node/index.d.ts +5 -194
  50. package/dist/esm/node/index.js +1 -1
  51. package/dist/esm/node/index.js.map +1 -1
  52. package/dist/esm/query/index.d.ts +3 -380
  53. package/dist/esm/query/index.js +1 -1
  54. package/dist/esm/query/index.js.map +1 -1
  55. package/dist/esm/relayer-BYq9bLh8.js +2 -0
  56. package/dist/esm/relayer-BYq9bLh8.js.map +1 -0
  57. package/dist/esm/token-CmHTAAWW.js +2 -0
  58. package/dist/esm/token-CmHTAAWW.js.map +1 -0
  59. package/dist/esm/{types-piBsdTIP.d.ts → types-Bov8XY36.d.ts} +3 -3
  60. package/dist/esm/{types-OHIaPwCy.d.ts → types-BpvL50qX.d.ts} +3 -3
  61. package/dist/esm/types-C-WTLcHZ.d.ts +988 -0
  62. package/dist/esm/viem/index.d.ts +4 -5
  63. package/dist/esm/viem/index.js +1 -1
  64. package/dist/esm/viem/index.js.map +1 -1
  65. package/dist/esm/web/index.d.ts +6 -9
  66. package/dist/esm/web/index.js +1 -590
  67. package/dist/esm/web/index.js.map +1 -1
  68. package/dist/esm/{wrappers-registry-C1oK8Bi6.js → wrappers-registry-xZWzyAi4.js} +2 -2
  69. package/dist/esm/wrappers-registry-xZWzyAi4.js.map +1 -0
  70. package/dist/esm/{index-C1Mtc8Rw.d.ts → zama-sdk-q4_qt64Q.d.ts} +1471 -1102
  71. package/package.json +6 -2
  72. package/dist/cjs/assertions.cjs +0 -2
  73. package/dist/cjs/assertions.cjs.map +0 -1
  74. package/dist/cjs/encryption.cjs +0 -2
  75. package/dist/cjs/encryption.cjs.map +0 -1
  76. package/dist/cjs/relayer-cleartext.cjs +0 -2
  77. package/dist/cjs/relayer-cleartext.cjs.map +0 -1
  78. package/dist/cjs/relayer-sdk.worker.js +0 -589
  79. package/dist/cjs/timeout.cjs +0 -2
  80. package/dist/cjs/timeout.cjs.map +0 -1
  81. package/dist/cjs/validation.cjs +0 -2
  82. package/dist/cjs/validation.cjs.map +0 -1
  83. package/dist/esm/assertions-zYseN5Xz.js +0 -2
  84. package/dist/esm/assertions-zYseN5Xz.js.map +0 -1
  85. package/dist/esm/base-signer-DjytqPkd.js +0 -2
  86. package/dist/esm/base-signer-DjytqPkd.js.map +0 -1
  87. package/dist/esm/chains-CXcO1DBP.js +0 -2
  88. package/dist/esm/chains-CXcO1DBP.js.map +0 -1
  89. package/dist/esm/cleartext-DAkOTlrE.d.ts +0 -19
  90. package/dist/esm/cleartext-rTWFctyd.js +0 -2
  91. package/dist/esm/cleartext-rTWFctyd.js.map +0 -1
  92. package/dist/esm/encryption-x4Z_Icqk.js +0 -2
  93. package/dist/esm/encryption-x4Z_Icqk.js.map +0 -1
  94. package/dist/esm/hex-A72GrTf9.js +0 -2
  95. package/dist/esm/hex-A72GrTf9.js.map +0 -1
  96. package/dist/esm/indexeddb-storage-Mi-fCWN3.js +0 -2
  97. package/dist/esm/indexeddb-storage-Mi-fCWN3.js.map +0 -1
  98. package/dist/esm/memory-storage-fp9RY5BQ.js +0 -2
  99. package/dist/esm/memory-storage-fp9RY5BQ.js.map +0 -1
  100. package/dist/esm/node/relayer-sdk.node-worker.d.ts +0 -1
  101. package/dist/esm/node/relayer-sdk.node-worker.js +0 -2
  102. package/dist/esm/node/relayer-sdk.node-worker.js.map +0 -1
  103. package/dist/esm/relayer-cleartext-Bp6jtxDd.js +0 -2
  104. package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +0 -1
  105. package/dist/esm/relayer-cleartext-CSeMlmGO.d.ts +0 -844
  106. package/dist/esm/relayer-eavK5bfZ.js +0 -2
  107. package/dist/esm/relayer-eavK5bfZ.js.map +0 -1
  108. package/dist/esm/relayer-sdk.worker.js +0 -589
  109. package/dist/esm/timeout-CNVfiaJD.js +0 -2
  110. package/dist/esm/timeout-CNVfiaJD.js.map +0 -1
  111. package/dist/esm/token-Bt33g0zQ.js +0 -2
  112. package/dist/esm/token-Bt33g0zQ.js.map +0 -1
  113. package/dist/esm/types-BgczXqW2.d.ts +0 -49
  114. package/dist/esm/types-Gn5MeDsr.d.ts +0 -669
  115. package/dist/esm/validation-DLszOweh.js +0 -2
  116. package/dist/esm/validation-DLszOweh.js.map +0 -1
  117. package/dist/esm/worker.base-client-BVnT4yJa.js +0 -2
  118. package/dist/esm/worker.base-client-BVnT4yJa.js.map +0 -1
  119. package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +0 -1
@@ -1,2 +0,0 @@
1
- const e={SigningRejected:`SIGNING_REJECTED`,SigningFailed:`SIGNING_FAILED`,EncryptionFailed:`ENCRYPTION_FAILED`,DecryptionFailed:`DECRYPTION_FAILED`,TransactionReverted:`TRANSACTION_REVERTED`,TransportKeyPairExpired:`KEYPAIR_EXPIRED`,InvalidTransportKeyPair:`INVALID_KEYPAIR`,NoCiphertext:`NO_CIPHERTEXT`,RelayerRequestFailed:`RELAYER_REQUEST_FAILED`,NotEntitled:`NOT_ENTITLED`,RpcRateLimited:`RPC_RATE_LIMITED`,OperationTimeout:`OPERATION_TIMEOUT`,WorkerRecycled:`WORKER_RECYCLED`,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`,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`};var t=class extends Error{code;constructor(e,t,n){super(t,n),Object.setPrototypeOf(this,new.target.prototype),this.name=`ZamaError`,this.code=e}},n=class extends t{statusCode;retryAfter;retryable;constructor(t,n,r){super(e.RelayerRequestFailed,t,r),this.name=`RelayerRequestFailedError`,this.statusCode=n,this.retryable=n===429,this.retryAfter=this.retryable?r?.retryAfter:void 0}},r=class extends t{constructor(t,n){super(e.Configuration,t,n),this.name=`ConfigurationError`}};export{e as i,n,t as r,r as t};
2
- //# sourceMappingURL=relayer-eavK5bfZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"relayer-eavK5bfZ.js","names":[],"sources":["../../src/errors/base.ts","../../src/errors/relayer.ts"],"sourcesContent":["/**\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 /** 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 /** 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 /** A worker operation exceeded its configured timeout; the worker is recycled by default. Retryable. */\n OperationTimeout: \"OPERATION_TIMEOUT\",\n /** An in-flight worker operation was aborted as collateral of another operation's timeout recycle. Retryable. */\n WorkerRecycled: \"WORKER_RECYCLED\",\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 /** 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} as const;\n\n/** Union of all {@link ZamaErrorCode} string values. */\nexport type ZamaErrorCode = (typeof ZamaErrorCode)[keyof typeof ZamaErrorCode];\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 constructor(code: ZamaErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"ZamaError\";\n this.code = code;\n }\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 retryable}.\n */\n readonly retryAfter: number | undefined;\n\n /**\n * Whether the request may be safely retried. `true` for relayer back-pressure\n * (HTTP 429); pair with {@link retryAfter} for the server's suggested delay.\n */\n readonly retryable: boolean;\n\n constructor(\n message: string,\n statusCode?: number,\n options?: ErrorOptions & { retryAfter?: number },\n ) {\n super(ZamaErrorCode.RelayerRequestFailed, message, options);\n this.name = \"RelayerRequestFailedError\";\n this.statusCode = statusCode;\n this.retryable = statusCode === 429;\n // Keep the two fields consistent: a delay only makes sense when retryable.\n this.retryAfter = this.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":"AAeA,MAAa,EAAgB,CAE3B,gBAAiB,mBAEjB,cAAe,iBAEf,iBAAkB,oBAElB,iBAAkB,oBAElB,oBAAqB,uBAErB,wBAAyB,kBAEzB,wBAAyB,kBAEzB,aAAc,gBAEd,qBAAsB,yBAEtB,YAAa,eAEb,eAAgB,mBAEhB,iBAAkB,oBAElB,eAAgB,kBAEhB,cAAe,gBAEf,yBAA0B,8BAE1B,mBAAoB,sBAEpB,mBAAoB,uBAEpB,kBAAmB,qBAEnB,gCAAiC,oCAEjC,yBAA0B,6BAE1B,wBAAyB,4BAEzB,gBAAiB,oBAEjB,0BAA2B,8BAE3B,iCAAkC,sCAElC,yBAA0B,8BAE1B,UAAW,aAEX,4BAA6B,iCAE7B,wBAAyB,4BAEzB,cAAe,iBAEf,oBAAqB,wBAErB,mBAAoB,uBAEpB,sBAAuB,0BACzB,EAUA,IAAa,EAAb,cAA+B,KAAM,CAEnC,KAEA,YAAY,EAAqB,EAAiB,EAAwB,CACxE,MAAM,EAAS,CAAO,EACtB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,EAChD,KAAK,KAAO,YACZ,KAAK,KAAO,CACd,CACF,ECjGa,EAAb,cAA+C,CAAU,CAEvD,WAQA,WAMA,UAEA,YACE,EACA,EACA,EACA,CACA,MAAM,EAAc,qBAAsB,EAAS,CAAO,EAC1D,KAAK,KAAO,4BACZ,KAAK,WAAa,EAClB,KAAK,UAAY,IAAe,IAEhC,KAAK,WAAa,KAAK,UAAY,GAAS,WAAa,IAAA,EAC3D,CACF,EAGa,EAAb,cAAwC,CAAU,CAChD,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAc,cAAe,EAAS,CAAO,EACnD,KAAK,KAAO,oBACd,CACF"}
@@ -1,589 +0,0 @@
1
- (function() {
2
- //#region src/utils/error.ts
3
- /** Coerce an unknown caught value to an Error instance. */
4
- function toError(error) {
5
- if (error instanceof Error) return error;
6
- if (typeof error === "object" && error !== null && "message" in error) return new Error(String(error.message));
7
- return new Error(String(error));
8
- }
9
- /** Properties that may nest a lower-level cause across viem / ethers / fetch. */
10
- const NESTED_ERROR_KEYS = [
11
- "cause",
12
- "error",
13
- "info"
14
- ];
15
- /**
16
- * ethers reports its HTTP status only as a string on `info.responseStatus`
17
- * (e.g. `"429 Too Many Requests"`). Read it directly off the node — not via the
18
- * cause-chain flattening, which descends a single branch — so it survives even
19
- * when the error also carries an `error` link that would be walked first.
20
- */
21
- function responseStatusFromNode(node) {
22
- const info = node.info;
23
- if (info !== null && typeof info === "object") {
24
- const responseStatus = info.responseStatus;
25
- if (typeof responseStatus === "string") return responseStatus;
26
- }
27
- }
28
- /**
29
- * Copy the scalar signal fields the classifier keys on from a raw error node
30
- * onto the envelope, only where not already set — so a shallower node keeps
31
- * priority. Also lifts ethers' string `info.responseStatus` and the relayer's
32
- * `Retry-After` header (both destroyed by structured clone: the header lives on
33
- * a non-cloneable `Headers`, the status on a nested `info` the flattening skips).
34
- */
35
- function captureNodeSignals(node, into) {
36
- if (into.code === void 0 && (typeof node.code === "string" || typeof node.code === "number")) into.code = node.code;
37
- if (into.status === void 0 && typeof node.status === "number") into.status = node.status;
38
- if (into.statusCode === void 0 && typeof node.statusCode === "number") into.statusCode = node.statusCode;
39
- if (into.responseStatus === void 0) {
40
- const responseStatus = responseStatusFromNode(node);
41
- if (responseStatus !== void 0) into.responseStatus = responseStatus;
42
- }
43
- if (into.retryAfter === void 0) if (typeof node.retryAfter === "number") into.retryAfter = node.retryAfter;
44
- else {
45
- const fromHeader = retryAfterFromHeader(node);
46
- if (fromHeader !== void 0) into.retryAfter = fromHeader;
47
- }
48
- }
49
- /** Lift any still-missing scalar signal from an already-serialized child up. */
50
- function hoistMissingSignals(from, into) {
51
- if (into.code === void 0 && from.code !== void 0) into.code = from.code;
52
- if (into.status === void 0 && from.status !== void 0) into.status = from.status;
53
- if (into.statusCode === void 0 && from.statusCode !== void 0) into.statusCode = from.statusCode;
54
- if (into.responseStatus === void 0 && from.responseStatus !== void 0) into.responseStatus = from.responseStatus;
55
- if (into.retryAfter === void 0 && from.retryAfter !== void 0) into.retryAfter = from.retryAfter;
56
- }
57
- /**
58
- * Flatten an error (and its `cause` / `error` / `info` chain) into a
59
- * structured-clone-safe {@link SerializedError}. Depth-bounded to mirror
60
- * {@link findInErrorChain} and guard against cyclic structures.
61
- */
62
- function serializeError(error, depth = 6) {
63
- const coerced = toError(error);
64
- const node = typeof error === "object" && error !== null ? error : coerced;
65
- const serialized = {
66
- name: coerced.name,
67
- message: coerced.message
68
- };
69
- captureNodeSignals(node, serialized);
70
- if (depth > 0) for (const key of NESTED_ERROR_KEYS) {
71
- const next = node[key];
72
- if (next !== void 0 && next !== null && typeof next === "object") {
73
- const child = serializeError(next, depth - 1);
74
- if (serialized.cause === void 0) serialized.cause = child;
75
- hoistMissingSignals(child, serialized);
76
- }
77
- }
78
- return serialized;
79
- }
80
- /**
81
- * Parse an HTTP `Retry-After` header value into **seconds** (the SDK's duration
82
- * unit and the header's own unit), or `undefined` when absent/unparseable. Per
83
- * RFC 9110 the value is either a non-negative number of seconds (`"120"`) or an
84
- * HTTP-date; a past date floors to `0`.
85
- */
86
- function parseRetryAfterHeader(value) {
87
- if (value === null || value === void 0) return;
88
- const trimmed = value.trim();
89
- if (trimmed === "") return;
90
- if (/^\d+$/.test(trimmed)) return Number(trimmed);
91
- if (/[a-zA-Z]/.test(trimmed)) {
92
- const dateMs = Date.parse(trimmed);
93
- if (!Number.isNaN(dateMs)) return Math.max(0, Math.round((dateMs - Date.now()) / 1e3));
94
- }
95
- }
96
- /** Read a `Retry-After` header (→ seconds) off a `Headers`-like object, if present. */
97
- function readRetryAfterHeader(headers) {
98
- if (headers === null || typeof headers !== "object") return;
99
- const get = headers.get;
100
- if (typeof get !== "function") return;
101
- return parseRetryAfterHeader(get.call(headers, "Retry-After"));
102
- }
103
- /**
104
- * A node's **relayer** `Retry-After` header (seconds), read from a wrapped fetch
105
- * `Response` (the relayer SDK's `cause.response.headers`). The SDK owns the
106
- * relayer fetch, so parsing the header there is legitimate.
107
- *
108
- * The viem/chain side (`HttpRequestError.headers`) is deliberately **not** read:
109
- * for consumer RPC the integrator's viem/ethers transport already honors
110
- * `Retry-After` in its own retry loop (and retries) before the error ever
111
- * surfaces, so re-reading it here would re-implement a transport concern.
112
- * Chain-RPC backoff is configured on the consumer's transport (`chain.network`).
113
- */
114
- function retryAfterFromHeader(node) {
115
- const response = node.response;
116
- if (response !== null && typeof response === "object") return readRetryAfterHeader(response.headers);
117
- }
118
- //#endregion
119
- //#region src/utils/assertions.ts
120
- function assertObject(value, context) {
121
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${context} must be an object, got ${typeof value}`);
122
- }
123
- function assertString(value, context) {
124
- if (typeof value !== "string") throw new TypeError(`${context} must be a string, got ${typeof value}`);
125
- }
126
- function assertFunction(value, context) {
127
- if (typeof value !== "function") throw new TypeError(`${context} must be a function, got ${typeof value}`);
128
- }
129
- /** Assert that `obj[key]` is a string. Narrows `obj` to include `{ [key]: string }`. */
130
- function assertStringProp(obj, key, context) {
131
- assertString(obj[key], context);
132
- }
133
- /** Assert that `obj[key]` is a function. Narrows `obj` to include `{ [key]: F }`. */
134
- function assertFunctionProp(obj, key, context) {
135
- assertFunction(obj[key], context);
136
- }
137
- function assertCondition(condition, message) {
138
- if (!condition) throw new TypeError(message);
139
- }
140
- //#endregion
141
- //#region src/utils/hex.ts
142
- /** Normalize a un-prefixed hex payload to a 0x-prefixed `Hex` value. */
143
- function prefixHex(value) {
144
- return value.startsWith("0x") ? value : `0x${value}`;
145
- }
146
- /** Convert a public `Hex` value back an unprefixed format. */
147
- function unprefixHex(value) {
148
- assertCondition(value.startsWith("0x"), `Expected 0x-prefixed hex, got: ${value}`);
149
- return value.slice(2);
150
- }
151
- //#endregion
152
- //#region src/worker/browser-extension.ts
153
- function isValidRuntime(runtime) {
154
- try {
155
- assertObject(runtime, "runtime");
156
- assertStringProp(runtime, "id", "runtime.id");
157
- assertFunctionProp(runtime, "getURL", "runtime.getURL");
158
- return true;
159
- } catch {
160
- return false;
161
- }
162
- }
163
- /**
164
- * Return the browser extension runtime object, or `undefined` outside extensions.
165
- * Works across Chrome/Edge (`chrome.runtime`) and Firefox/Safari (`browser.runtime`).
166
- * Extensions have restricted CSP that blocks `blob:` URLs, so callers use
167
- * this to detect the environment and resolve file URLs via `runtime.getURL`.
168
- */
169
- function getBrowserExtensionRuntime() {
170
- const g = globalThis;
171
- for (const ns of [g.chrome, g.browser]) try {
172
- assertObject(ns, "ns");
173
- if (isValidRuntime(ns.runtime)) return ns.runtime;
174
- } catch {
175
- continue;
176
- }
177
- }
178
- //#endregion
179
- //#region src/worker/relayer-sdk.worker.ts
180
- const instances = /* @__PURE__ */ new Map();
181
- const pending = /* @__PURE__ */ new Map();
182
- const configs = /* @__PURE__ */ new Map();
183
- /** Convert an FheChain to the FhevmInstanceConfig shape expected by createInstance. */
184
- function toInstanceConfig(chain) {
185
- return {
186
- ...chain,
187
- chainId: chain.id
188
- };
189
- }
190
- let sdkGlobal = null;
191
- /**
192
- * Get or lazily create an FhevmInstance for the given chain.
193
- */
194
- async function getInstance(chainId) {
195
- const existing = instances.get(chainId);
196
- if (existing) return existing;
197
- const inflight = pending.get(chainId);
198
- if (inflight) return inflight;
199
- const config = configs.get(chainId);
200
- if (!config) throw new Error(`No config for chain ${chainId}. Available: [${[...configs.keys()].join(", ")}]`);
201
- if (!sdkGlobal) throw new Error("Relayer SDK is not initialized. Call INIT first.");
202
- const promise = sdkGlobal.createInstance({
203
- ...toInstanceConfig(config),
204
- batchRpcCalls: false
205
- }).then((instance) => {
206
- instances.set(chainId, instance);
207
- pending.delete(chainId);
208
- return instance;
209
- }).catch((err) => {
210
- pending.delete(chainId);
211
- throw err;
212
- });
213
- pending.set(chainId, promise);
214
- return promise;
215
- }
216
- function unreachableFheType(_) {
217
- throw new Error("Unsupported FHE type");
218
- }
219
- const relayerUrls = /* @__PURE__ */ new Set();
220
- let csrfTokenBase = "";
221
- const CSRF_HEADER_NAME = "x-csrf-token";
222
- const MUTATING_METHODS = /* @__PURE__ */ new Set([
223
- "POST",
224
- "PUT",
225
- "DELETE",
226
- "PATCH"
227
- ]);
228
- /**
229
- * Register relayer URLs from chain configs for fetch interception.
230
- */
231
- function registerRelayerUrls(chainConfigs) {
232
- for (const c of chainConfigs) if (c.relayerUrl) relayerUrls.add(c.relayerUrl);
233
- }
234
- /**
235
- * Send a success response back to the main thread.
236
- * Optionally transfers ArrayBuffers for zero-copy performance.
237
- */
238
- function sendSuccess(id, type, data, transfer) {
239
- const response = {
240
- id,
241
- type,
242
- success: true,
243
- data
244
- };
245
- return transfer ? self.postMessage(response, transfer) : self.postMessage(response);
246
- }
247
- /**
248
- * Send an error response back to the main thread.
249
- */
250
- function sendError(id, type, error) {
251
- self.postMessage({
252
- id,
253
- type,
254
- success: false,
255
- error: error instanceof Error ? error.message : String(error),
256
- serialized: serializeError(error)
257
- });
258
- }
259
- const originalFetch = fetch;
260
- /** Allowed CDN hostnames for loading the relayer SDK script. */
261
- const ALLOWED_CDN_HOSTS = /* @__PURE__ */ new Set(["cdn.zama.org"]);
262
- /**
263
- * Validate the CDN URL supplied by the caller.
264
- * Ensures only HTTPS URLs from approved hosts are used when loading
265
- * SDK code into the worker.
266
- */
267
- function validateCdnUrl(rawUrl) {
268
- let url;
269
- try {
270
- url = new URL(rawUrl);
271
- } catch {
272
- throw new Error("Invalid CDN URL");
273
- }
274
- if (url.protocol !== "https:") throw new Error("CDN URL must use https");
275
- if (!ALLOWED_CDN_HOSTS.has(url.hostname)) throw new Error(`CDN URL host is not allowed: ${url.hostname}`);
276
- return url.toString();
277
- }
278
- /**
279
- * Set up fetch interceptor to add credentials and CSRF token for relayer requests.
280
- * Workers don't automatically include cookies, so we intercept fetch calls
281
- * targeting our relayer proxy to inject credentials and CSRF headers.
282
- */
283
- function setupFetchInterceptor() {
284
- globalThis.fetch = async (input, init) => {
285
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
286
- const method = init?.method?.toUpperCase() ?? "GET";
287
- if (relayerUrls.size > 0 && [...relayerUrls].some((base) => url.startsWith(base))) {
288
- const headers = new Headers(init?.headers);
289
- if (MUTATING_METHODS.has(method) && csrfTokenBase) headers.set(CSRF_HEADER_NAME, csrfTokenBase);
290
- return originalFetch(input, {
291
- ...init,
292
- headers,
293
- credentials: "include"
294
- });
295
- }
296
- return originalFetch(input, init);
297
- };
298
- }
299
- /**
300
- * Verify a fetched script's SHA-384 hash matches the expected integrity value.
301
- */
302
- async function verifyIntegrity(content, expectedHash) {
303
- const encoder = new TextEncoder();
304
- const hashBuffer = await crypto.subtle.digest("SHA-384", encoder.encode(content));
305
- const hashHex = [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
306
- if (hashHex !== expectedHash) throw new Error(`CDN integrity check failed: expected SHA-384 ${expectedHash}, got ${hashHex}`);
307
- }
308
- /**
309
- * Load SDK script from CDN.
310
- * Uses two strategies depending on the environment:
311
- * - **Web apps (default):** fetch + blob URL + importScripts. Avoids MIME-type
312
- * rejections (some CDNs serve .cjs as `application/node`) and CSP
313
- * `unsafe-eval` violations.
314
- * - **Browser extensions (Chrome/Firefox/Safari):** importScripts directly.
315
- * Blob URLs are blocked by extension CSP, but the CDN must be allowed
316
- * in the extension's manifest CSP.
317
- *
318
- * Integrity is always verified when a hash is provided, regardless of strategy.
319
- */
320
- async function fetchScript(cdnUrl) {
321
- const response = await originalFetch(cdnUrl);
322
- if (!response.ok) throw new Error(`Failed to fetch SDK: ${response.status} ${response.statusText}`);
323
- return response.text();
324
- }
325
- async function loadSdkScript(cdnUrl, integrity) {
326
- const validatedUrl = validateCdnUrl(cdnUrl);
327
- if (getBrowserExtensionRuntime()) {
328
- if (integrity) await verifyIntegrity(await fetchScript(validatedUrl), integrity);
329
- return self.importScripts(validatedUrl);
330
- }
331
- const scriptContent = await fetchScript(validatedUrl);
332
- if (integrity) await verifyIntegrity(scriptContent, integrity);
333
- const blob = new Blob([scriptContent], { type: "application/javascript" });
334
- const blobUrl = URL.createObjectURL(blob);
335
- try {
336
- self.importScripts(blobUrl);
337
- } finally {
338
- URL.revokeObjectURL(blobUrl);
339
- }
340
- }
341
- /**
342
- * Handle INIT request - load SDK WASM and register chain configs (instances are lazy).
343
- */
344
- async function handleInit(request) {
345
- const { id, type, payload } = request;
346
- try {
347
- if (payload.env !== "web") throw new Error(`Web worker received unexpected env: ${payload.env}`);
348
- const { cdnUrl, csrfToken, integrity, thread } = payload;
349
- csrfTokenBase = csrfToken;
350
- setupFetchInterceptor();
351
- await loadSdkScript(cdnUrl, integrity);
352
- if (!self.relayerSDK) throw new Error("Failed to load relayerSDK from CDN");
353
- sdkGlobal = self.relayerSDK;
354
- await sdkGlobal.initSDK(thread !== null && thread !== void 0 ? { thread } : void 0);
355
- registerRelayerUrls(payload.chains);
356
- for (const chain of payload.chains) configs.set(chain.id, chain);
357
- sendSuccess(id, type, { initialized: true });
358
- } catch (error) {
359
- sendError(id, type, error);
360
- }
361
- }
362
- /** Coerce a boolean to bigint for numeric FHE types. */
363
- function toBigInt(value) {
364
- return typeof value === "boolean" ? value ? 1n : 0n : value;
365
- }
366
- /**
367
- * Add a single typed value to the encrypted input builder.
368
- */
369
- function addTypedValue(input, entry) {
370
- const { value, type: fheType } = entry;
371
- switch (fheType) {
372
- case "ebool":
373
- input.addBool(typeof value === "boolean" ? value : value !== 0n);
374
- break;
375
- case "euint8":
376
- input.add8(toBigInt(value));
377
- break;
378
- case "euint16":
379
- input.add16(toBigInt(value));
380
- break;
381
- case "euint32":
382
- input.add32(toBigInt(value));
383
- break;
384
- case "euint64":
385
- input.add64(toBigInt(value));
386
- break;
387
- case "euint128":
388
- input.add128(toBigInt(value));
389
- break;
390
- case "euint256":
391
- input.add256(toBigInt(value));
392
- break;
393
- case "eaddress":
394
- input.addAddress(value);
395
- break;
396
- default: unreachableFheType(fheType);
397
- }
398
- }
399
- /**
400
- * Handle ENCRYPT request.
401
- */
402
- async function handleEncrypt(request) {
403
- const { id, type, payload } = request;
404
- const { values, contractAddress, userAddress } = payload;
405
- try {
406
- const input = (await getInstance(payload.chainId)).createEncryptedInput(contractAddress, userAddress);
407
- for (const entry of values) addTypedValue(input, entry);
408
- const encrypted = await input.encrypt();
409
- sendSuccess(id, type, {
410
- handles: encrypted.handles,
411
- inputProof: encrypted.inputProof
412
- }, [encrypted.inputProof.buffer, ...encrypted.handles.map((h) => h.buffer)]);
413
- } catch (error) {
414
- sendError(id, type, error);
415
- }
416
- }
417
- /**
418
- * Handle USER_DECRYPT request.
419
- */
420
- async function handleUserDecrypt(request) {
421
- const { id, type, payload } = request;
422
- try {
423
- const instance = await getInstance(payload.chainId);
424
- const handleContractPairs = payload.encryptedValues.map((encryptedValue) => ({
425
- handle: encryptedValue,
426
- contractAddress: payload.contractAddress
427
- }));
428
- sendSuccess(id, type, { clearValues: await instance.userDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.signerAddress, payload.startTimestamp, payload.durationDays) });
429
- } catch (error) {
430
- sendError(id, type, error);
431
- }
432
- }
433
- /**
434
- * Handle PUBLIC_DECRYPT request.
435
- */
436
- async function handlePublicDecrypt(request) {
437
- const { id, type, payload } = request;
438
- try {
439
- sendSuccess(id, type, { ...await (await getInstance(payload.chainId)).publicDecrypt(payload.encryptedValues) });
440
- } catch (error) {
441
- sendError(id, type, error);
442
- }
443
- }
444
- /**
445
- * Handle GENERATE_KEYPAIR request.
446
- */
447
- async function handleGenerateKeypair(request) {
448
- const { id, type, payload } = request;
449
- try {
450
- const keypair = (await getInstance(payload.chainId)).generateKeypair();
451
- sendSuccess(id, type, {
452
- publicKey: prefixHex(keypair.publicKey),
453
- privateKey: prefixHex(keypair.privateKey)
454
- });
455
- } catch (error) {
456
- sendError(id, type, error);
457
- }
458
- }
459
- /**
460
- * Handle CREATE_EIP712 request.
461
- */
462
- async function handleCreateEIP712(request) {
463
- const { id, type, payload } = request;
464
- try {
465
- sendSuccess(id, type, (await getInstance(payload.chainId)).createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays));
466
- } catch (error) {
467
- sendError(id, type, error);
468
- }
469
- }
470
- /**
471
- * Handle CREATE_DELEGATED_EIP712 request.
472
- */
473
- async function handleCreateDelegatedEIP712(request) {
474
- const { id, type, payload } = request;
475
- try {
476
- sendSuccess(id, type, (await getInstance(payload.chainId)).createDelegatedUserDecryptEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.delegatorAddress, payload.startTimestamp, payload.durationDays));
477
- } catch (error) {
478
- sendError(id, type, error);
479
- }
480
- }
481
- /**
482
- * Handle DELEGATED_USER_DECRYPT request.
483
- */
484
- async function handleDelegatedUserDecrypt(request) {
485
- const { id, type, payload } = request;
486
- try {
487
- const instance = await getInstance(payload.chainId);
488
- const handleContractPairs = payload.encryptedValues.map((encryptedValue) => ({
489
- handle: encryptedValue,
490
- contractAddress: payload.contractAddress
491
- }));
492
- sendSuccess(id, type, { clearValues: await instance.delegatedUserDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.delegatorAddress, payload.delegateAddress, payload.startTimestamp, payload.durationDays) });
493
- } catch (error) {
494
- sendError(id, type, error);
495
- }
496
- }
497
- /**
498
- * Handle REQUEST_ZK_PROOF_VERIFICATION request.
499
- */
500
- async function handleRequestZKProofVerification(request) {
501
- const { id, type, payload } = request;
502
- try {
503
- const result = await (await getInstance(payload.chainId)).requestZKProofVerification(payload.zkProof);
504
- sendSuccess(id, type, result, [result.inputProof.buffer, ...result.handles.map((h) => h.buffer)]);
505
- } catch (error) {
506
- sendError(id, type, error);
507
- }
508
- }
509
- /**
510
- * Handle GET_PUBLIC_KEY request.
511
- */
512
- async function handleGetPublicKey(request) {
513
- const { id, type, payload } = request;
514
- try {
515
- sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicKey() });
516
- } catch (error) {
517
- sendError(id, type, error);
518
- }
519
- }
520
- /**
521
- * Handle GET_PUBLIC_PARAMS request.
522
- */
523
- async function handleGetPublicParams(request) {
524
- const { id, type, payload } = request;
525
- try {
526
- sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicParams(payload.bits) });
527
- } catch (error) {
528
- sendError(id, type, error);
529
- }
530
- }
531
- /**
532
- * Handle UPDATE_CSRF request - update the stored CSRF token.
533
- */
534
- function handleUpdateCsrf(request) {
535
- const { id, type, payload } = request;
536
- csrfTokenBase = payload.csrfToken;
537
- sendSuccess(id, type, { updated: true });
538
- }
539
- /**
540
- * Main message handler.
541
- */
542
- self.onmessage = async (event) => {
543
- const request = event.data;
544
- try {
545
- switch (request.type) {
546
- case "INIT":
547
- await handleInit(request);
548
- break;
549
- case "UPDATE_CSRF":
550
- handleUpdateCsrf(request);
551
- break;
552
- case "ENCRYPT":
553
- await handleEncrypt(request);
554
- break;
555
- case "USER_DECRYPT":
556
- await handleUserDecrypt(request);
557
- break;
558
- case "PUBLIC_DECRYPT":
559
- await handlePublicDecrypt(request);
560
- break;
561
- case "GENERATE_KEYPAIR":
562
- await handleGenerateKeypair(request);
563
- break;
564
- case "CREATE_EIP712":
565
- await handleCreateEIP712(request);
566
- break;
567
- case "CREATE_DELEGATED_EIP712":
568
- await handleCreateDelegatedEIP712(request);
569
- break;
570
- case "DELEGATED_USER_DECRYPT":
571
- await handleDelegatedUserDecrypt(request);
572
- break;
573
- case "REQUEST_ZK_PROOF_VERIFICATION":
574
- await handleRequestZKProofVerification(request);
575
- break;
576
- case "GET_PUBLIC_KEY":
577
- await handleGetPublicKey(request);
578
- break;
579
- case "GET_PUBLIC_PARAMS":
580
- await handleGetPublicParams(request);
581
- break;
582
- default: throw new Error(`Unknown request type: ${request.type}`);
583
- }
584
- } catch (error) {
585
- sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", error);
586
- }
587
- };
588
- //#endregion
589
- })();
@@ -1,2 +0,0 @@
1
- import{i as e,r as t}from"./relayer-eavK5bfZ.js";var n=class extends t{operation;timeout;elapsed;worker;constructor(t,n){super(e.OperationTimeout,`Worker operation ${t.operation} timed out after ${t.timeout}s`+(t.worker?` (worker ${t.worker})`:``),n),this.name=`WorkerTimeoutError`,this.operation=t.operation,this.timeout=t.timeout,this.elapsed=t.elapsed,this.worker=t.worker}},r=class extends t{operation;worker;constructor(t,n){super(e.WorkerRecycled,`Worker operation ${t.operation} was aborted because its worker was recycled after a timeout`+(t.worker?` (worker ${t.worker})`:``),n),this.name=`WorkerRecycledError`,this.operation=t.operation,this.worker=t.worker}};export{n,r as t};
2
- //# sourceMappingURL=timeout-CNVfiaJD.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"timeout-CNVfiaJD.js","names":[],"sources":["../../src/errors/timeout.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * A worker operation (encrypt / decrypt / EIP-712 / key fetch) did not complete\n * within its configured timeout — typically a stuck relayer or WASM call. On the\n * Node pool the SDK **recycles the affected worker** (terminating the hung\n * thread) so it self-heals; the operation itself is **retryable**.\n *\n * Configure the bound (seconds) via `node({ operationTimeout })`. Distinct from a\n * decryption/entitlement failure — a timeout is an infrastructure/latency\n * condition, so it no longer collapses into {@link DecryptionFailedError}.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof WorkerTimeoutError) {\n * // retry (the worker was recycled); consider raising operationTimeout\n * }\n * }\n * ```\n */\nexport class WorkerTimeoutError extends ZamaError {\n /**\n * The worker operation that timed out. This is the internal worker op code\n * (e.g. `USER_DECRYPT`, `ENCRYPT`), not the public SDK method name.\n */\n readonly operation: string;\n /** The configured timeout that was exceeded, in **seconds** (the SDK's duration unit). */\n readonly timeout: number;\n /** Wall-clock time the operation ran before being abandoned, in **seconds** (may be fractional). */\n readonly elapsed: number;\n /** Label of the worker that stalled, when known (e.g. `node-worker-2`). */\n readonly worker: string | undefined;\n\n constructor(\n args: { operation: string; timeout: number; elapsed: number; worker?: string },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.OperationTimeout,\n `Worker operation ${args.operation} timed out after ${args.timeout}s` +\n (args.worker ? ` (worker ${args.worker})` : \"\"),\n options,\n );\n this.name = \"WorkerTimeoutError\";\n this.operation = args.operation;\n this.timeout = args.timeout;\n this.elapsed = args.elapsed;\n this.worker = args.worker;\n }\n}\n\n/**\n * An in-flight worker operation was aborted as **collateral** when its worker was\n * recycled — the worker was torn down to recover from *another* operation's\n * timeout (Node pool self-healing), not because this operation itself timed out.\n *\n * The operation never reached a verdict, so it is **retryable**: the next call\n * lazily re-inits a fresh worker. It is intentionally distinct from\n * {@link WorkerTimeoutError} (this op did not exceed its own bound) and from\n * {@link DecryptionFailedError} (nothing actually failed to decrypt) — so a\n * consumer can retry it instead of surfacing a terminal failure.\n *\n * @example\n * ```ts\n * matchZamaError(error, {\n * WORKER_RECYCLED: () => retry(), // transient: the worker was replaced\n * });\n * ```\n */\nexport class WorkerRecycledError extends ZamaError {\n /**\n * The worker operation that was aborted. This is the internal worker op code\n * (e.g. `USER_DECRYPT`, `ENCRYPT`), not the public SDK method name.\n */\n readonly operation: string;\n /** Label of the recycled worker, when known (e.g. `node-worker-2`). */\n readonly worker: string | undefined;\n\n constructor(args: { operation: string; worker?: string }, options?: ErrorOptions) {\n super(\n ZamaErrorCode.WorkerRecycled,\n `Worker operation ${args.operation} was aborted because its worker was recycled after a timeout` +\n (args.worker ? ` (worker ${args.worker})` : \"\"),\n options,\n );\n this.name = \"WorkerRecycledError\";\n this.operation = args.operation;\n this.worker = args.worker;\n }\n}\n"],"mappings":"iDAuBA,IAAa,EAAb,cAAwC,CAAU,CAKhD,UAEA,QAEA,QAEA,OAEA,YACE,EACA,EACA,CACA,MACE,EAAc,iBACd,oBAAoB,EAAK,UAAU,mBAAmB,EAAK,QAAQ,IAChE,EAAK,OAAS,YAAY,EAAK,OAAO,GAAK,IAC9C,CACF,EACA,KAAK,KAAO,qBACZ,KAAK,UAAY,EAAK,UACtB,KAAK,QAAU,EAAK,QACpB,KAAK,QAAU,EAAK,QACpB,KAAK,OAAS,EAAK,MACrB,CACF,EAoBa,EAAb,cAAyC,CAAU,CAKjD,UAEA,OAEA,YAAY,EAA8C,EAAwB,CAChF,MACE,EAAc,eACd,oBAAoB,EAAK,UAAU,+DAChC,EAAK,OAAS,YAAY,EAAK,OAAO,GAAK,IAC9C,CACF,EACA,KAAK,KAAO,sBACZ,KAAK,UAAY,EAAK,UACtB,KAAK,OAAS,EAAK,MACrB,CACF"}
@@ -1,2 +0,0 @@
1
- import{i as e,r as t,t as n}from"./relayer-eavK5bfZ.js";import{A as r,B as i,D as a,E as o,H as s,L as c,M as l,R as u,S as d,T as f,U as p,W as m,b as h,l as g,m as _,u as v,v as y,w as b,x}from"./wrappers-registry-C1oK8Bi6.js";import{n as S,t as C}from"./encryption-x4Z_Icqk.js";import{_ as w,t as T}from"./assertions-zYseN5Xz.js";import{getAddress as E}from"viem";var D=class extends t{constructor(t,n){super(e.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},O=class extends t{retryAfter;constructor(t,n){let{retryAfter:r,...i}=n??{};super(e.RpcRateLimited,t,i),this.name=`RpcRateLimitError`,this.retryAfter=r}},k=class extends t{operation;signerChainId;providerChainId;constructor({operation:t,signerChainId:n,providerChainId:r},i){super(e.ChainMismatch,`Operation "${t}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=t,this.signerChainId=n,this.providerChainId=r}},A=class extends t{requested;available;token;constructor(t,n,r){super(e.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},j=class extends t{requested;available;token;constructor(t,n,r){super(e.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},M=class extends t{constructor(t,n){super(e.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},N=class extends t{constructor(t,n){super(e.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function P(e){return e instanceof m||e instanceof p||e instanceof n||e instanceof O}const F=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function I(e,t,n,r){return{address:e,abi:F,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function L(e,t,n){return{address:e,abi:F,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function R(e,t,n,r){return{address:e,abi:F,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function z(e,t,n,r,i){return{address:e,abi:F,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const B=2n**64n-1n;async function V(e,t,n){if(!t)throw new u(e);let r;try{r=t.requireWalletAccount(e)}catch(n){if(!(n instanceof i)||!t.refreshWalletAccount)throw n;await t.refreshWalletAccount(),r=t.requireWalletAccount(e)}let a=await n.getChainId();if(r.chainId!==a)throw new k({operation:e,signerChainId:r.chainId,providerChainId:a});return r}async function H(e,t,n){return(await V(e,t,n)).chainId}const U={EncryptStart:`encrypt:start`,EncryptEnd:`encrypt:end`,EncryptError:`encrypt:error`,DecryptStart:`decrypt:start`,DecryptEnd:`decrypt:end`,DecryptError:`decrypt:error`,TransactionError:`transaction:error`,ShieldSubmitted:`shield:submitted`,TransferSubmitted:`transfer:submitted`,TransferFromSubmitted:`transferFrom:submitted`,SetOperatorSubmitted:`setOperator:submitted`,ApproveUnderlyingSubmitted:`approveUnderlying:submitted`,UnwrapSubmitted:`unwrap:submitted`,FinalizeUnwrapSubmitted:`finalizeUnwrap:submitted`,DelegationSubmitted:`delegation:submitted`,RevokeDelegationSubmitted:`revokeDelegation:submitted`,UnshieldPhase1Submitted:`unshield:phase1_submitted`,UnshieldPhase2Started:`unshield:phase2_started`,UnshieldPhase2Submitted:`unshield:phase2_submitted`},W={approveUnderlying:{submittedEvent:e=>({type:U.ApproveUnderlyingSubmitted,txHash:e,step:`approve`})},"approveUnderlying:reset":{submittedEvent:e=>({type:U.ApproveUnderlyingSubmitted,txHash:e,step:`reset`})},delegateDecryption:{submittedEvent:e=>({type:U.DelegationSubmitted,txHash:e})},finalizeUnwrap:{submittedEvent:e=>({type:U.FinalizeUnwrapSubmitted,txHash:e})},revokeDelegation:{submittedEvent:e=>({type:U.RevokeDelegationSubmitted,txHash:e})},setOperator:{submittedEvent:e=>({type:U.SetOperatorSubmitted,txHash:e})},"shield:transferAndCall":{submittedEvent:e=>({type:U.ShieldSubmitted,txHash:e,shieldPath:`transferAndCall`})},"shield:approveAndWrap":{submittedEvent:e=>({type:U.ShieldSubmitted,txHash:e,shieldPath:`approveAndWrap`})},transfer:{submittedEvent:e=>({type:U.TransferSubmitted,txHash:e})},transferAndCall:{submittedEvent:e=>({type:U.TransferSubmitted,txHash:e})},transferFrom:{submittedEvent:e=>({type:U.TransferFromSubmitted,txHash:e})},transferFromAndCall:{submittedEvent:e=>({type:U.TransferFromSubmitted,txHash:e})},unwrap:{submittedEvent:e=>({type:U.UnwrapSubmitted,txHash:e})},unwrapAll:{submittedEvent:e=>({type:U.UnwrapSubmitted,txHash:e})}};async function G(e,t=1/0){if(Number.isFinite(t)&&t<=0)throw Error(`maxConcurrency must be a positive number`);if(!Number.isFinite(t)||t>=e.length)return Promise.all(e.map(e=>e()));let n=Array.from({length:e.length}),r=0;async function i(){for(;r<e.length;){let t=r++;e[t]&&(n[t]=await e[t]())}}return await Promise.all(Array.from({length:t},i)),n}const K=`0x0000000000000000000000000000000000000000000000000000000000000000`;function q(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}async function J(e){let{operation:n,signer:r,provider:i,config:a,emit:o,onSubmitted:s,logger:l}=e,u=W[n];try{let e=await r.writeContract(a);return o(u.submittedEvent(e)),c(`${n}: onSubmitted`,()=>s?.(e),l),{txHash:e,receipt:await i.waitForTransactionReceipt(e)}}catch(e){let r=e instanceof t?e:new D(`Transaction failed during ${n}`,{cause:e});throw o({type:U.TransactionError,operation:n,error:r}),r}}var Y=class e{sdk;address;constructor(e,t){this.sdk=e,this.address=E(t)}#e(e){return s(this.sdk.signer,e)}async name(){return this.sdk.provider.readContract(h(this.address))}async symbol(){return this.sdk.provider.readContract(x(this.address))}async decimals(){return this.sdk.provider.readContract(y(this.address))}async isConfidential(){return this.sdk.provider.readContract(_(this.address,g))}async isWrapper(){return this.sdk.provider.readContract(_(this.address,v))}async balanceOf(e){let t=E(e),n=await this.readConfidentialBalanceOf(t),r=(await this.sdk.decryption.decryptValues([{encryptedValue:n,contractAddress:this.address}]))[n];if(r===void 0)throw new C(`Decryption returned no value for ${n}`);return T(r,`balanceOf: result[encryptedValue]`),r}async confidentialBalanceOf(e){return this.readConfidentialBalanceOf(E(e))}async decryptBalanceAs({delegatorAddress:e,accountAddress:t}){await H(`decryptBalanceAs`,this.sdk.signer,this.sdk.provider);let n=E(e),r=t?E(t):n,i=await this.readConfidentialBalanceOf(r);if(q(i))return 0n;let a=(await this.sdk.decryption.delegatedDecryptValues([{encryptedValue:i,contractAddress:this.address}],n,r))[i];if(a===void 0)throw new C(`Delegated decryption returned no value for ${i}`);return T(a,`decryptBalanceAs: result[encryptedValue]`),a}static async batchBalancesOf(n,r){let i=new Map,a=new Map;if(n.length===0)return{results:i,errors:a};let o=e.assertSameSdk(n);await H(`batchBalancesOf`,o.signer,o.provider),await o.permits.grantPermit(n.map(e=>e.address));let s=await G(n.map(e=>async()=>{try{return{status:`fulfilled`,value:await e.balanceOf(r)}}catch(e){return{status:`rejected`,reason:e}}}),5);for(let e=0;e<n.length;e++){let r=n[e].address,o=s[e];if(o.status===`fulfilled`)i.set(r,o.value);else{let e=o.reason;if(P(e))throw e;let n=e instanceof t?e:new C(w(e).message,{cause:e});a.set(r,n)}}if(a.size===n.length)throw a.values().next().value??new C(`All token balance decryptions failed`);return{results:i,errors:a}}static async batchDecryptBalancesAs(t,n){if(t.length===0)return new Map;let r=e.assertSameSdk(t),i=new Map,a=new Map,o=n.accountAddress?E(n.accountAddress):E(n.delegatorAddress),s=n.maxConcurrency??10;if(n.encryptedValues&&t.length!==n.encryptedValues.length)throw new C(`tokens.length (${t.length}) must equal encryptedValues.length (${n.encryptedValues.length})`);let c=n.encryptedValues??await e.readBalanceHandlesBatch(t,o,a,s),l=[];for(let[e,n]of t.entries()){let t=c[e];!t||a.has(n.address)||(q(t)?i.set(n.address,0n):l.push({token:n,encryptedValue:t}))}if(l.length>0){let e=await r.decryption.delegatedBatchDecryptValues({encryptedInputs:l.map(({token:e,encryptedValue:t})=>({encryptedValue:t,contractAddress:e.address})),delegatorAddress:n.delegatorAddress,accountAddress:n.accountAddress,maxConcurrency:s});for(let[t,n]of e.items.entries()){let e=l[t];if(!e)continue;if(n.error){a.set(e.token.address,n.error);continue}let r=n.value;if(r===void 0){a.set(e.token.address,new C(`Batch delegated decryption returned no value for ${n.encryptedValue} on token ${e.token.address}`));continue}T(r,`batchDecryptBalancesAs: result[encryptedValue]`),i.set(e.token.address,r)}}if(a.size===0)return i;if(n.onError){let e=[];for(let[t,r]of a)try{i.set(t,n.onError(r,t))}catch(n){e.push({address:t,error:w(n)})}if(e.length>0){let t=e.map(({address:e,error:t})=>`${e}: ${t.message}`).join(`; `);throw new C(`Batch delegated decryption onError callback failed for ${e.length} token(s): ${t}`,{cause:e[0]?.error})}return i}let u=Array.from(a.entries()),d=u.map(([e,t])=>`${e}: ${t.message}`).join(`; `);throw new C(`Batch delegated decryption failed for ${a.size} token(s): ${d}`,{cause:u[0]?.[1]})}static async readBalanceHandlesBatch(e,n,r,i){let a=await G(e.map(e=>async()=>{try{return{status:`fulfilled`,value:await e.readConfidentialBalanceOf(n)}}catch(e){return{status:`rejected`,reason:e}}}),i),o=[];for(let[n,i]of e.entries()){let e=a[n];if(e){if(e.status===`fulfilled`){o[n]=e.value;continue}if(P(e.reason))throw e.reason;r.set(i.address,e.reason instanceof t?e.reason:new C(w(e.reason).message,{cause:e.reason}))}}return o}async confidentialTransfer(e,t,n){this.#e(`confidentialTransfer`);let r=await V(`confidentialTransfer`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=E(e);i||await this.assertConfidentialBalance(t);let{encryptedValues:l,inputProof:u}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:E(r.address)});if(c(`transfer: onEncryptComplete`,()=>a?.(),this.sdk.logger),l.length===0)throw new S(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transfer`,config:f(this.address,s,l[0],u),onSubmitted:o})}async confidentialTransferFrom(e,t,n,r){this.#e(`confidentialTransferFrom`),await V(`confidentialTransferFrom`,this.sdk.signer,this.sdk.provider);let i=E(e),o=E(t),{encryptedValues:s,inputProof:l}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:i});if(c(`transferFrom: onEncryptComplete`,()=>r?.onEncryptComplete?.(),this.sdk.logger),s.length===0)throw new S(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFrom`,config:a(this.address,i,o,s[0],l),onSubmitted:r?.onTransferSubmitted})}async confidentialTransferAndCall(e,t,n,r){this.#e(`confidentialTransferAndCall`);let i=await V(`confidentialTransferAndCall`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:a=!1,onEncryptComplete:o,onTransferSubmitted:s}=r??{},l=E(e);a||await this.assertConfidentialBalance(t);let{encryptedValues:u,inputProof:d}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:E(i.address)});if(c(`transferAndCall: onEncryptComplete`,()=>o?.(),this.sdk.logger),u.length===0)throw new S(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferAndCall`,config:b(this.address,l,u[0],d,n),onSubmitted:s})}async confidentialTransferFromAndCall(e,t,n,r,i){this.#e(`confidentialTransferFromAndCall`),await V(`confidentialTransferFromAndCall`,this.sdk.signer,this.sdk.provider);let a=E(e),s=E(t),{encryptedValues:l,inputProof:u}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a});if(c(`transferFromAndCall: onEncryptComplete`,()=>i?.onEncryptComplete?.(),this.sdk.logger),l.length===0)throw new S(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFromAndCall`,config:o(this.address,a,s,l[0],u,r),onSubmitted:i?.onTransferSubmitted})}async setOperator(e,t){this.#e(`setOperator`),await H(`setOperator`,this.sdk.signer,this.sdk.provider);let n=E(e);return this.submitTransaction({operation:`setOperator`,config:l(this.address,n,t)})}async isOperator(e,t){return this.sdk.provider.readContract(r(this.address,E(e),E(t)))}async readConfidentialBalanceOf(e){return await this.sdk.provider.readContract(d(this.address,e))}async assertConfidentialBalance(e){if(e===0n)return;let n;try{let e=await V(`assertConfidentialBalance`,this.sdk.signer,this.sdk.provider);n=await this.balanceOf(E(e.address))}catch(e){throw e instanceof t?e:new M(`Balance validation failed (token: ${this.address})`,{cause:e})}if(n<e)throw new A(`Insufficient confidential balance: requested ${e}, available ${n} (token: ${this.address})`,{requested:e,available:n,token:this.address})}emit(e){this.sdk.emitEvent(e,this.address)}async submitTransaction(e){let{operation:t,config:n,onSubmitted:r}=e;return J({operation:t,signer:this.#e(t),provider:this.sdk.provider,config:n,emit:e=>this.emit(e),onSubmitted:r,logger:this.sdk.logger})}static assertSameSdk(e){let t=e[0].sdk;for(let r=1;r<e.length;r++)if(e[r].sdk!==t)throw new n(`All tokens in a batch operation must share the same ZamaSDK instance`);return t}};export{A as _,G as a,O as b,H as c,R as d,z as f,N as g,M as h,q as i,B as l,P as m,J as n,U as o,L as p,K as r,V as s,Y as t,I as u,j as v,D as x,k as y};
2
- //# sourceMappingURL=token-Bt33g0zQ.js.map