@zama-fhe/sdk 2.1.1-alpha.2 → 2.2.0-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 (64) hide show
  1. package/README.md +3 -4
  2. package/dist/cjs/activity.cjs +1 -1
  3. package/dist/cjs/activity.cjs.map +1 -1
  4. package/dist/cjs/cleartext/index.cjs +1 -2
  5. package/dist/cjs/cleartext.cjs +2 -0
  6. package/dist/cjs/{cleartext/index.cjs.map → cleartext.cjs.map} +1 -1
  7. package/dist/cjs/ethers/index.cjs +1 -1
  8. package/dist/cjs/ethers/index.cjs.map +1 -1
  9. package/dist/cjs/index.cjs +2 -2
  10. package/dist/cjs/index.cjs.map +1 -1
  11. package/dist/cjs/query/index.cjs +1 -1
  12. package/dist/cjs/query/index.cjs.map +1 -1
  13. package/dist/cjs/transfer-batcher.cjs +1 -1
  14. package/dist/cjs/transfer-batcher.cjs.map +1 -1
  15. package/dist/cjs/viem/index.cjs +1 -1
  16. package/dist/cjs/viem/index.cjs.map +1 -1
  17. package/dist/cjs/{erc165.cjs → wrappers-registry.cjs} +2 -2
  18. package/dist/cjs/wrappers-registry.cjs.map +1 -0
  19. package/dist/esm/{activity-B4coeVs1.d.ts → activity-BRrEPcPO.d.ts} +256 -27
  20. package/dist/esm/activity-ChJnF5yd.js +2 -0
  21. package/dist/esm/activity-ChJnF5yd.js.map +1 -0
  22. package/dist/esm/cleartext/index.d.ts +5 -2
  23. package/dist/esm/cleartext/index.js +1 -2
  24. package/dist/esm/cleartext-CxGEREks.js +2 -0
  25. package/dist/esm/cleartext-CxGEREks.js.map +1 -0
  26. package/dist/esm/{eip1193-subscribe-Cl_wlVuQ.js → eip1193-subscribe-Cp2QVN0m.js} +1 -1
  27. package/dist/esm/{eip1193-subscribe-Cl_wlVuQ.js.map → eip1193-subscribe-Cp2QVN0m.js.map} +1 -1
  28. package/dist/esm/ethers/index.d.ts +12 -5
  29. package/dist/esm/ethers/index.js +1 -1
  30. package/dist/esm/ethers/index.js.map +1 -1
  31. package/dist/esm/fhe-artifact-cache-vzh7Xn9G.js.map +1 -1
  32. package/dist/esm/{index-BaBH5_l6.d.ts → index-IhsduS7h.d.ts} +1134 -7
  33. package/dist/esm/index.d.ts +6 -6
  34. package/dist/esm/index.js +2 -2
  35. package/dist/esm/index.js.map +1 -1
  36. package/dist/esm/node/index.d.ts +3 -3
  37. package/dist/esm/node/index.js +1 -1
  38. package/dist/esm/query/index.d.ts +124 -8
  39. package/dist/esm/query/index.js +1 -1
  40. package/dist/esm/query/index.js.map +1 -1
  41. package/dist/esm/{relayer-sdk-mcgawhDN.d.ts → relayer-sdk-CcIghrEq.d.ts} +2 -2
  42. package/dist/esm/{relayer-sdk.types--cY3a2ni.d.ts → relayer-sdk.types-D7rylLS4.d.ts} +1 -1
  43. package/dist/esm/{relayer-utils-DgRkaB8f.d.ts → relayer-utils-BcTAyZOr.d.ts} +14 -3
  44. package/dist/esm/relayer-utils-BeoTNDM4.js +2 -0
  45. package/dist/esm/relayer-utils-BeoTNDM4.js.map +1 -0
  46. package/dist/esm/transfer-batcher-BXIo7hnu.js +2 -0
  47. package/dist/esm/transfer-batcher-BXIo7hnu.js.map +1 -0
  48. package/dist/esm/viem/index.d.ts +24 -5
  49. package/dist/esm/viem/index.js +1 -1
  50. package/dist/esm/viem/index.js.map +1 -1
  51. package/dist/esm/{erc165-GmIEu75Z.js → wrappers-registry-DqPr_JG2.js} +2 -2
  52. package/dist/esm/wrappers-registry-DqPr_JG2.js.map +1 -0
  53. package/package.json +1 -1
  54. package/dist/cjs/erc165.cjs.map +0 -1
  55. package/dist/cjs/relayer-utils.cjs +0 -2
  56. package/dist/cjs/relayer-utils.cjs.map +0 -1
  57. package/dist/esm/activity-q5o6CCaY.js +0 -2
  58. package/dist/esm/activity-q5o6CCaY.js.map +0 -1
  59. package/dist/esm/cleartext/index.js.map +0 -1
  60. package/dist/esm/erc165-GmIEu75Z.js.map +0 -1
  61. package/dist/esm/relayer-utils--TV3NTMg.js +0 -2
  62. package/dist/esm/relayer-utils--TV3NTMg.js.map +0 -1
  63. package/dist/esm/transfer-batcher-C8gp7S82.js +0 -2
  64. package/dist/esm/transfer-batcher-C8gp7S82.js.map +0 -1
package/README.md CHANGED
@@ -181,7 +181,7 @@ Full read/write interface for a single confidential ERC-20. Extends `ReadonlyTok
181
181
  | Method | Description |
182
182
  | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
183
183
  | `shield(amount, options?)` | Shield (wrap) public ERC-20 tokens. Handles approval automatically. Options: `{ approvalStrategy: "max" \| "exact" \| "skip" }` (default `"exact"`). `"skip"` bypasses approval (use when already approved). |
184
- | `shieldETH(amount, value?)` | Shield (wrap) native ETH. `value` defaults to `amount`. Use this when the underlying token is the zero address (native ETH). |
184
+ | `shieldETH(amount, value?)` | Shield (wrap) native ETH. `value` defaults to `amount`. Use when the underlying token is the zero address (native ETH). |
185
185
  | `unshield(amount, callbacks?)` | Unwrap a specific amount and finalize in one call. Orchestrates: unwrap → wait receipt → parse event → finalizeUnwrap. Optional `UnshieldCallbacks` for progress tracking. |
186
186
  | `unshieldAll(callbacks?)` | Unwrap the entire balance and finalize in one call. Orchestrates: unwrapAll → wait receipt → parse event → finalizeUnwrap. Optional `UnshieldCallbacks` for progress tracking. |
187
187
  | `unwrap(amount)` | Request unwrap for a specific amount (low-level, requires manual finalization). |
@@ -231,7 +231,6 @@ Read-only subset. No wrapper address needed.
231
231
  | `getDelegationExpiry({ delegatorAddress, delegateAddress })` | Raw expiry timestamp (`0n` = none, `2^64-1` = permanent). |
232
232
  | `isConfidential()` | ERC-165 check for ERC-7984 support. |
233
233
  | `isWrapper()` | ERC-165 check for wrapper interface. |
234
- | `discoverWrapper(coordinatorAddress)` | Look up a wrapper for this token via the deployment coordinator. |
235
234
  | `underlyingToken()` | Read the underlying ERC-20 address from a wrapper. |
236
235
  | `allowance(wrapper, owner?)` | Read ERC-20 allowance of the underlying token. |
237
236
  | `isZeroHandle(handle)` | Returns `true` if the handle is the zero sentinel. |
@@ -335,7 +334,7 @@ const sdk = new ZamaSDK({
335
334
 
336
335
  | Field | Type | Description |
337
336
  | ---------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
338
- | `relayer` | `RelayerSDK` | Relayer backend (`RelayerWeb` or `RelayerNode` instance) |
337
+ | `relayer` | `RelayerSDK` | Relayer backend (`RelayerWeb` or `RelayerNode` instance). |
339
338
  | `signer` | `GenericSigner` | Wallet signer interface. |
340
339
  | `storage` | `GenericStorage` | Credential storage backend. |
341
340
  | `sessionStorage` | `GenericStorage` | Optional. Session storage for wallet signatures. Default: in-memory (lost on reload). Use `chrome.storage.session` for web extensions. |
@@ -610,7 +609,7 @@ const txHash = await writeConfidentialTransferContract(
610
609
  );
611
610
  ```
612
611
 
613
- **Read helpers:** `readConfidentialBalanceOfContract`, `readWrapperForTokenContract`, `readUnderlyingTokenContract`, `readWrapperExistsContract`, `readSupportsInterfaceContract`.
612
+ **Read helpers:** `readConfidentialBalanceOfContract`, `readUnderlyingTokenContract`, `readWrapperExistsContract`, `readSupportsInterfaceContract`, `readWrapperForTokenContract` (legacy — prefer `sdk.registry.getConfidentialToken()`).
614
613
 
615
614
  **Write helpers:** `writeConfidentialTransferContract`, `writeConfidentialBatchTransferContract`, `writeUnwrapContract`, `writeUnwrapFromBalanceContract`, `writeFinalizeUnwrapContract`, `writeSetOperatorContract`, `writeWrapContract`, `writeWrapETHContract`.
616
615
 
@@ -1,2 +1,2 @@
1
- const e=require(`./relayer.cjs`),t=require(`./erc165.cjs`);let n=require(`viem`);var r=class extends e.a{constructor(t,n){super(e.o.SigningRejected,t,n),this.name=`SigningRejectedError`}},i=class extends e.a{constructor(t,n){super(e.o.SigningFailed,t,n),this.name=`SigningFailedError`}};function a(e,t){let n=typeof e==`object`&&!!e&&`code`in e&&e.code===4001,a=e instanceof Error?e.message.toLowerCase():``,o=a.includes(`user rejected`)||a.includes(`user denied`);throw n||o?new r(t,{cause:e}):new i(t,{cause:e})}var o=class extends e.a{constructor(t,n){super(e.o.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},s=class extends e.a{constructor(t,n){super(e.o.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},c=class extends e.a{constructor(t,n){super(e.o.NoCiphertext,t,n),this.name=`NoCiphertextError`}},l=class extends e.a{constructor(t,n){super(e.o.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},u=class extends e.a{constructor(t,n){super(e.o.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},d=class extends e.a{constructor(t,n){super(e.o.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},f=class extends e.a{constructor(t,n){super(e.o.DelegationExpired,t,n),this.name=`DelegationExpiredError`}};function p(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function m(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function h(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function ee(e,t){if(!Array.isArray(e))throw TypeError(`${t} must be an array, got ${typeof e}`)}function g(e,t,n){h(e[t],n)}function _(e,t){if(!e)throw TypeError(t)}function v(e){return e.startsWith(`0x`)?e:`0x${e}`}function te(e){return{address:e,abi:n.erc20Abi,functionName:`name`,args:[]}}function ne(e){return{address:e,abi:n.erc20Abi,functionName:`symbol`,args:[]}}function y(e){return{address:e,abi:n.erc20Abi,functionName:`decimals`,args:[]}}function re(e,t){return{address:e,abi:n.erc20Abi,functionName:`balanceOf`,args:[t]}}function b(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`allowance`,args:[t,r]}}function ie(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`approve`,args:[t,r]}}const x=[{inputs:[{internalType:`uint64`,name:`wrapFeeBasisPoints_`,type:`uint64`},{internalType:`uint64`,name:`unwrapFeeBasisPoints_`,type:`uint64`},{internalType:`uint64`,name:`deployFee_`,type:`uint64`},{internalType:`uint64`,name:`batchTransferFee_`,type:`uint64`},{internalType:`address`,name:`feeRecipient_`,type:`address`}],stateMutability:`nonpayable`,type:`constructor`},{inputs:[],name:`AccessControlBadConfirmation`,type:`error`},{inputs:[{internalType:`address`,name:`account`,type:`address`},{internalType:`bytes32`,name:`neededRole`,type:`bytes32`}],name:`AccessControlUnauthorizedAccount`,type:`error`},{inputs:[],name:`FeeExceedsMaximum`,type:`error`},{inputs:[],name:`ZeroAddressFeeRecipient`,type:`error`},{anonymous:!1,inputs:[{indexed:!1,internalType:`uint64`,name:`oldBatchTransferFee`,type:`uint64`},{indexed:!1,internalType:`uint64`,name:`newBatchTransferFee`,type:`uint64`}],name:`BatchTransferFeeUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!1,internalType:`uint64`,name:`oldDeployFee`,type:`uint64`},{indexed:!1,internalType:`uint64`,name:`newDeployFee`,type:`uint64`}],name:`DeployFeeUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!0,internalType:`address`,name:`oldRecipient`,type:`address`},{indexed:!0,internalType:`address`,name:`newRecipient`,type:`address`}],name:`FeeRecipientUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!0,internalType:`bytes32`,name:`role`,type:`bytes32`},{indexed:!0,internalType:`bytes32`,name:`previousAdminRole`,type:`bytes32`},{indexed:!0,internalType:`bytes32`,name:`newAdminRole`,type:`bytes32`}],name:`RoleAdminChanged`,type:`event`},{anonymous:!1,inputs:[{indexed:!0,internalType:`bytes32`,name:`role`,type:`bytes32`},{indexed:!0,internalType:`address`,name:`account`,type:`address`},{indexed:!0,internalType:`address`,name:`sender`,type:`address`}],name:`RoleGranted`,type:`event`},{anonymous:!1,inputs:[{indexed:!0,internalType:`bytes32`,name:`role`,type:`bytes32`},{indexed:!0,internalType:`address`,name:`account`,type:`address`},{indexed:!0,internalType:`address`,name:`sender`,type:`address`}],name:`RoleRevoked`,type:`event`},{anonymous:!1,inputs:[{indexed:!1,internalType:`bool`,name:`active`,type:`bool`}],name:`SwapperFeeWaiverUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!1,internalType:`uint64`,name:`oldFeeBasisPoints`,type:`uint64`},{indexed:!1,internalType:`uint64`,name:`newFeeBasisPoints`,type:`uint64`}],name:`UnwrapFeeBasisPointsUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!1,internalType:`uint64`,name:`oldFeeBasisPoints`,type:`uint64`},{indexed:!1,internalType:`uint64`,name:`newFeeBasisPoints`,type:`uint64`}],name:`WrapFeeBasisPointsUpdated`,type:`event`},{inputs:[],name:`DEFAULT_ADMIN_ROLE`,outputs:[{internalType:`bytes32`,name:``,type:`bytes32`}],stateMutability:`view`,type:`function`},{inputs:[],name:`FEE_MANAGER_ROLE`,outputs:[{internalType:`bytes32`,name:``,type:`bytes32`}],stateMutability:`view`,type:`function`},{inputs:[],name:`MAX_BASIS_POINTS`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`SWAPPER_ROLE`,outputs:[{internalType:`bytes32`,name:``,type:`bytes32`}],stateMutability:`view`,type:`function`},{inputs:[],name:`batchTransferFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`deployFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`feeRecipient`,outputs:[{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getBatchTransferFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`deployer`,type:`address`}],name:`getDeployFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getFeeRecipient`,outputs:[{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`}],name:`getRoleAdmin`,outputs:[{internalType:`bytes32`,name:``,type:`bytes32`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint64`,name:`amount`,type:`uint64`},{internalType:`address`,name:`unwrapFrom`,type:`address`},{internalType:`address`,name:`unwrapTo`,type:`address`}],name:`getUnwrapFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint256`,name:`amount`,type:`uint256`},{internalType:`address`,name:`wrapFrom`,type:`address`},{internalType:`address`,name:`wrapTo`,type:`address`}],name:`getWrapFee`,outputs:[{internalType:`uint256`,name:``,type:`uint256`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`},{internalType:`address`,name:`account`,type:`address`}],name:`grantRole`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`},{internalType:`address`,name:`account`,type:`address`}],name:`hasRole`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`},{inputs:[],name:`protocolId`,outputs:[{internalType:`uint256`,name:``,type:`uint256`}],stateMutability:`pure`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`},{internalType:`address`,name:`callerConfirmation`,type:`address`}],name:`renounceRole`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`},{internalType:`address`,name:`account`,type:`address`}],name:`revokeRole`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`uint64`,name:`newBatchTransferFee`,type:`uint64`}],name:`setBatchTransferFee`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`uint64`,name:`newDeployFee`,type:`uint64`}],name:`setDeployFee`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`recipient`,type:`address`}],name:`setFeeRecipient`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`bool`,name:`active`,type:`bool`}],name:`setSwapperFeeWaiverActive`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`uint64`,name:`feeBasisPoints`,type:`uint64`}],name:`setUnwrapFeeBasisPoints`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`uint64`,name:`feeBasisPoints`,type:`uint64`}],name:`setWrapFeeBasisPoints`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`bytes4`,name:`interfaceId`,type:`bytes4`}],name:`supportsInterface`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`},{inputs:[],name:`swapperFeeWaiverActive`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`},{inputs:[],name:`unwrapFeeBasisPoints`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`wrapFeeBasisPoints`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`}];function ae(e,t,n,r){return{address:e,abi:x,functionName:`getWrapFee`,args:[t,n,r]}}function oe(e,t,n,r){return{address:e,abi:x,functionName:`getUnwrapFee`,args:[t,n,r]}}function se(e){return{address:e,abi:x,functionName:`getBatchTransferFee`,args:[]}}function ce(e){return{address:e,abi:x,functionName:`getFeeRecipient`,args:[]}}const S=[{inputs:[{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`},{internalType:`uint64`,name:`expirationDate`,type:`uint64`}],name:`delegateForUserDecryption`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`}],name:`revokeDelegationForUserDecryption`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`delegator`,type:`address`},{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`}],name:`getUserDecryptionDelegationExpirationDate`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`}];function le(e,t,n,r){return{address:e,abi:S,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function ue(e,t,n){return{address:e,abi:S,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function C(e,t,n,r){return{address:e,abi:S,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}const w=2n**64n-1n,T={CredentialsLoading:`credentials:loading`,CredentialsCached:`credentials:cached`,CredentialsExpired:`credentials:expired`,CredentialsCreating:`credentials:creating`,CredentialsCreated:`credentials:created`,CredentialsRevoked:`credentials:revoked`,CredentialsAllowed:`credentials:allowed`,CredentialsPersistFailed:`credentials:persist_failed`,CredentialsCorrupted:`credentials:corrupted`,SessionExpired:`session:expired`,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`,ApproveSubmitted:`approve: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`};var E=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 de=new E;var fe=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return v(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function pe(e){m(e,`Stored credentials`),h(e.publicKey,`credentials.publicKey`),ee(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)_(typeof t==`string`&&(0,n.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);m(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),h(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),h(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),_(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),_(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function me(e){pe(e);let t=e;_(typeof t.delegatorAddress==`string`&&(0,n.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),_(typeof t.delegateAddress==`string`&&(0,n.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),_(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),_(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function D(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function O(e,t){let r=new Set(t.map(e=>(0,n.getAddress)(e))),i=new Set(e.map(e=>(0,n.getAddress)(e)));return r.isSubsetOf(i)}function k(e,t){return D(e)?O(e.contractAddresses,t):!1}function A(e){return[...new Set(e.map(e=>(0,n.getAddress)(e)))].toSorted()}async function j(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var he=class{#e;constructor(e){this.#e=e}#t(e){m(e,`Session entry`),h(e.signature,`session.signature`),_(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),_(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},M=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new he(e.sessionStorage),this.crypto=new fe,this.keypairTTL=e.keypairTTL??86400,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`)}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:e,contracts:t,createKey:n,createFn:a}){this.emit({type:T.CredentialsLoading,contractAddresses:t});try{let n=await this.storage.get(e);if(n){this.assertEncrypted(n);let r=await this.sessionSignatures.get(e);if(r)if(this.sessionSignatures.isExpired(r))await this.sessionSignatures.delete(e),this.emit({type:T.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(n,r.signature);if(k(i,t))return this.emit({type:T.CredentialsCached,contractAddresses:t}),this.emit({type:T.CredentialsAllowed,contractAddresses:t}),i;if(D(i))return this.#i({key:e,credentials:i,requiredContracts:t});this.emit({type:T.CredentialsExpired,contractAddresses:t})}if(D(n)){if(O(n.contractAddresses,t)){let r=await this.signForContracts(n,n.contractAddresses);await this.sessionSignatures.set({key:e,signature:r,ttl:this.sessionTTL});let i=await this.decryptCredentials(n,r);return this.emit({type:T.CredentialsCached,contractAddresses:t}),this.emit({type:T.CredentialsAllowed,contractAddresses:t}),i}let r=await this.signForContracts(n,n.contractAddresses),i=await this.decryptCredentials(n,r);return this.#i({key:e,credentials:i,requiredContracts:t})}this.emit({type:T.CredentialsExpired,contractAddresses:t})}}catch(t){if(t instanceof r||t instanceof i)throw t;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,t),this.emit({type:T.CredentialsCorrupted,error:p(t)}),await this.#o(e)}return(!this.#t||this.#n!==n)&&(this.#n=n,this.#t=a().then(e=>(this.emit({type:T.CredentialsAllowed,contractAddresses:t}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!k(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,t){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:T.CredentialsRevoked,...t?{contractAddresses:t}:{}})}async checkAllowed(e){let t=await this.sessionSignatures.get(e);return t===null?!1:!this.sessionSignatures.isExpired(t)}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#o(e)}clearCaches(){this.crypto.clearCache()}async createCredentials({key:e,contractAddresses:t,createFn:n,errorContext:r}){this.emit({type:T.CredentialsCreating,contractAddresses:t});try{let r=await n();return await this.persistCredentials(e,r),await this.sessionSignatures.set({key:e,signature:r.signature,ttl:this.sessionTTL}),this.emit({type:T.CredentialsCreated,contractAddresses:t}),r}catch(e){a(e,r)}}async#i({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(O(e.contractAddresses,n))return this.emit({type:T.CredentialsAllowed,contractAddresses:n}),e;t=e}let r=this.#a({key:e,credentials:t,requiredContracts:n});this.#r=r;try{return await r}finally{this.#r===r&&(this.#r=null)}}async#a({key:e,credentials:t,requiredContracts:n}){let r=A([...t.contractAddresses,...n]),i=await this.signForContracts(t,r),a={...t,contractAddresses:r,signature:i};return await this.persistCredentials(e,a),await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL}),this.emit({type:T.CredentialsAllowed,contractAddresses:n}),a}async persistCredentials(e,t){try{let n=await this.encryptCredentials(t);await this.storage.set(e,n)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:T.CredentialsPersistFailed,error:p(e)})}}async#o(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:T.CredentialsPersistFailed,error:p(e)})}}};function ge(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var N=class e extends M{#e;#t=null;#n=null;static async computeStoreKey(e,t){return j((0,n.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,ge(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof E&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=A(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeByKey(e){await this.revokeSession(e)}async isAllowed(){return this.checkAllowed(await this.#r())}async clear(){await this.clearAll(await this.#r())}async create(e){let t=A(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){pe(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),r=await this.signer.getChainId(),i=`${(0,n.getAddress)(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(t,r);return this.#n=i,this.#t=a,a}},P=class e extends M{#e;#t=null;#n=null;static async computeStoreKey(e,t,r){return j((0,n.getAddress)(e),(0,n.getAddress)(t),r)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let r=(0,n.getAddress)(e),i=A(t),a=await this.#i(r);return this.resolveCredentials({key:a,contracts:i,createKey:`${r}:${i.join(`,`)}`,createFn:()=>this.#r(r,i)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,n.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,n.getAddress)(e)))}async isAllowed(e){return this.checkAllowed(await this.#i((0,n.getAddress)(e)))}async clear(e){await this.clearAll(await this.#i((0,n.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){me(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let r=await this.signer.getAddress(),i=await this.signer.getChainId(),a=`${(0,n.getAddress)(r)}:${(0,n.getAddress)(t)}:${i}`;if(this.#t&&this.#n===a)return this.#t;let o=await e.computeStoreKey(r,t,i);return this.#n=a,this.#t=o,o}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData({domain:{...n.domain,chainId:Number(n.domain.chainId)},types:n.types,message:{...n.message,startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays)}})}};async function _e(e,t=1/0){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 F=`zama:balances`;function I(e,t,r){return`zama:balance:${(0,n.getAddress)(e)}:${(0,n.getAddress)(t)}:${r.toLowerCase()}`}async function L({storage:e,tokenAddress:t,owner:n,handle:r}){try{let i=await e.get(I(t,n,r));return i===null?null:BigInt(i)}catch(e){return console.warn(`[zama-sdk] Balance cache read failed:`,e),null}}async function R(e){let{storage:t,tokenAddress:n,owner:r,handle:i,value:a}=e,o=I(n,r,i);try{await t.set(o,a.toString()),await ve(t,o)}catch{}}const z=new WeakMap;async function ve(e,t){let n=(z.get(e)??Promise.resolve()).then(async()=>{let n=await e.get(F),r=n?JSON.parse(n):[];r.includes(t)||(r.push(t),await e.set(F,JSON.stringify(r)))});return z.set(e,n.catch(()=>{})),n}var ye=class r{credentials;delegatedCredentials;relayer;signer;address;storage;#e;constructor(e){let t={relayer:e.relayer,signer:e.signer,storage:e.storage,sessionStorage:e.sessionStorage,keypairTTL:e.keypairTTL??86400,sessionTTL:e.sessionTTL??2592e3,onEvent:e.onEvent};this.credentials=e.credentials??new N(t),this.delegatedCredentials=e.delegatedCredentials??new P(t),this.relayer=e.relayer,this.signer=e.signer,this.address=(0,n.getAddress)(e.address),this.storage=e.storage,this.#e=e.onEvent}emit(e){this.#e?.({...e,tokenAddress:this.address,timestamp:Date.now()})}async balanceOf(e){let t=e?(0,n.getAddress)(e):await this.signer.getAddress(),r=await this.readConfidentialBalanceOf(t);return this.decryptBalance(r,t)}async confidentialBalanceOf(e){let t=e?(0,n.getAddress)(e):await this.signer.getAddress();return this.readConfidentialBalanceOf(t)}async isConfidential(){return await this.signer.readContract(t.a(this.address,t.t))}async isWrapper(){return await this.signer.readContract(t.a(this.address,t.n))}static async batchDecryptBalances(e,t){if(e.length===0)return new Map;let{handles:n,owner:i,onError:a,maxConcurrency:o}=t??{},s=e[0],c=r.assertSameRelayer(e),l=i??await s.signer.getAddress();return r.#t({tokens:e,handles:n,ownerAddress:l,onError:a,maxConcurrency:o,obtainCreds:e=>s.credentials.allow(...e),decrypt:(e,t,n)=>c.userDecrypt({handles:[t],contractAddress:n,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,signerAddress:l,startTimestamp:e.startTimestamp,durationDays:e.durationDays}),errorPrefix:`Batch decryption`})}static async batchDecryptBalancesAs(e,t){if(e.length===0)return new Map;let{delegatorAddress:n,handles:i,owner:a,onError:o,maxConcurrency:s}=t,c=a??n,l=e[0];return r.assertSameRelayer(e),r.#t({tokens:e,handles:i,ownerAddress:c,onError:o,maxConcurrency:s,preFlightCheck:()=>l.#n(n),obtainCreds:e=>l.delegatedCredentials.allow(n,...e),decrypt:(e,t,n)=>l.relayer.delegatedUserDecrypt({handles:[t],contractAddress:n,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,delegatorAddress:e.delegatorAddress,delegateAddress:e.delegateAddress,startTimestamp:e.startTimestamp,durationDays:e.durationDays}),errorPrefix:`Batch delegated decryption`})}static async#t(t){let{tokens:n,handles:r,ownerAddress:i,onError:a,maxConcurrency:o,obtainCreds:s,decrypt:c,errorPrefix:l}=t,u=n[0],d=r??await Promise.all(n.map(e=>e.readConfidentialBalanceOf(i)));if(n.length!==d.length)throw new e.r(`tokens.length (${n.length}) must equal handles.length (${d.length})`);let f=u.storage,m=new Map,h=[],ee=await Promise.all(n.map((e,t)=>{let n=d[t];return e.isZeroHandle(n)?0n:L({storage:f,tokenAddress:e.address,owner:i,handle:n})}));for(let e=0;e<n.length;e++){let t=n[e],r=d[e],i=ee[e];if(i!=null){m.set(t.address,i);continue}h.push({token:t,handle:r})}if(h.length===0)return m;t.preFlightCheck&&await t.preFlightCheck();let g=await s(h.map(e=>e.token.address)),_=[],v=[];for(let{token:t,handle:n}of h)v.push(()=>c(g,n,t.address).then(async r=>{let a=r[n];if(a===void 0)throw new e.r(`${l} returned no value for handle ${n} on token ${t.address}`);m.set(t.address,a);try{await R({storage:f,tokenAddress:t.address,owner:i,handle:n,value:a})}catch{}}).catch(e=>{let n=p(e);if(a)try{m.set(t.address,a(n,t.address))}catch(e){_.push({address:t.address,error:p(e)})}else _.push({address:t.address,error:n})}));if(await _e(v,o),_.length>0){let t=_.map(e=>`${e.address}: ${e.error.message}`).join(`; `);throw new e.r(`${l} failed for ${_.length} token(s): ${t}`)}return m}async discoverWrapper(e){let r=(0,n.getAddress)(e);return await this.signer.readContract(t.s(r,this.address))?this.signer.readContract(t.o(r,this.address)):null}async underlyingToken(){return this.signer.readContract(t.l(this.address))}async allowance(e,r){let i=(0,n.getAddress)(e),a=await this.signer.readContract(t.l(i)),o=r?(0,n.getAddress)(r):await this.signer.getAddress();return this.signer.readContract(b(a,o,i))}async name(){return this.signer.readContract(te(this.address))}async symbol(){return this.signer.readContract(ne(this.address))}async decimals(){return this.signer.readContract(y(this.address))}async allow(){await this.credentials.allow(this.address)}async isAllowed(){return this.credentials.isAllowed()}async revoke(...e){await this.credentials.revoke(...e)}static async allow(...e){if(e.length===0)return;let t=e.map(e=>e.address);await e[0].credentials.allow(...t)}async getAclAddress(){return this.relayer.getAclAddress()}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===w?!0:t>await this.signer.getBlockTimestamp()}async getDelegationExpiry({delegatorAddress:e,delegateAddress:t}){let r=await this.getAclAddress();return this.signer.readContract(C(r,(0,n.getAddress)(e),(0,n.getAddress)(t),this.address))}async#n(e){let t=await this.signer.getAddress(),n=await this.getDelegationExpiry({delegatorAddress:e,delegateAddress:t});if(n===0n)throw new d(`No active delegation from ${e} to ${t} for ${this.address}`);if(n!==w&&n<=await this.signer.getBlockTimestamp())throw new f(`Delegation from ${e} to ${t} for ${this.address} has expired`)}async readConfidentialBalanceOf(e){return await this.signer.readContract(t.f(this.address,e))}isZeroHandle(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}async decryptBalanceAs({delegatorAddress:t,owner:r}){let i=(0,n.getAddress)(t),a=r?(0,n.getAddress)(r):i,o=await this.readConfidentialBalanceOf(a);if(this.isZeroHandle(o))return 0n;let s=await L({storage:this.storage,tokenAddress:this.address,owner:a,handle:o});if(s!==null)return s;await this.#n(i);let c=Date.now();try{this.emit({type:T.DecryptStart});let t=await this.delegatedCredentials.allow(i,this.address),n=await this.relayer.delegatedUserDecrypt({handles:[o],contractAddress:this.address,signedContractAddresses:t.contractAddresses,privateKey:t.privateKey,publicKey:t.publicKey,signature:t.signature,delegatorAddress:t.delegatorAddress,delegateAddress:t.delegateAddress,startTimestamp:t.startTimestamp,durationDays:t.durationDays});this.emit({type:T.DecryptEnd,durationMs:Date.now()-c});let r=n[o];if(r===void 0)throw new e.r(`Delegated decryption returned no value for handle ${o}`);try{await R({storage:this.storage,tokenAddress:this.address,owner:a,handle:o,value:r})}catch{}return r}catch(e){throw this.emit({type:T.DecryptError,error:p(e),durationMs:Date.now()-c}),B(e,`Failed to decrypt delegated balance`)}}async decryptBalance(t,n){if(this.isZeroHandle(t))return 0n;let r=n??await this.signer.getAddress(),i=await L({storage:this.storage,tokenAddress:this.address,owner:r,handle:t});if(i!==null)return i;let a=await this.credentials.allow(this.address),o=Date.now();try{this.emit({type:T.DecryptStart});let n=await this.relayer.userDecrypt({handles:[t],contractAddress:this.address,signedContractAddresses:a.contractAddresses,privateKey:a.privateKey,publicKey:a.publicKey,signature:a.signature,signerAddress:r,startTimestamp:a.startTimestamp,durationDays:a.durationDays});this.emit({type:T.DecryptEnd,durationMs:Date.now()-o});let i=n[t];if(i===void 0)throw new e.r(`Decryption returned no value for handle ${t}`);try{await R({storage:this.storage,tokenAddress:this.address,owner:r,handle:t,value:i})}catch{}return i}catch(e){throw this.emit({type:T.DecryptError,error:p(e),durationMs:Date.now()-o}),B(e,`Failed to decrypt balance`)}}async decryptHandles(t,n){let r=new Map,i=[];for(let e of t)this.isZeroHandle(e)?r.set(e,0n):i.push(e);if(i.length===0)return r;let a=await this.credentials.allow(this.address),o=Date.now();try{this.emit({type:T.DecryptStart});let t=await this.relayer.userDecrypt({handles:i,contractAddress:this.address,signedContractAddresses:a.contractAddresses,privateKey:a.privateKey,publicKey:a.publicKey,signature:a.signature,signerAddress:n??await this.signer.getAddress(),startTimestamp:a.startTimestamp,durationDays:a.durationDays});this.emit({type:T.DecryptEnd,durationMs:Date.now()-o});for(let n of i){let i=t[n];if(i===void 0)throw new e.r(`Decryption returned no value for handle ${n}`);r.set(n,i)}}catch(e){throw this.emit({type:T.DecryptError,error:p(e),durationMs:Date.now()-o}),B(e,`Failed to decrypt handles`)}return r}static assertSameRelayer(t){let n=t[0].relayer;for(let r=1;r<t.length;r++)if(t[r].relayer!==n)throw new e.t(`All tokens in a batch operation must share the same relayer instance`);return n}};function B(t,n){if(t instanceof e.r||t instanceof c||t instanceof e.n||t instanceof r||t instanceof i)return t;let a=typeof t==`object`&&t&&`statusCode`in t&&typeof t.statusCode==`number`?t.statusCode:void 0;return a===400?new c(t instanceof Error?t.message:`No ciphertext for this account`,{cause:t}):a===void 0?new e.r(n,{cause:t}):new e.n(t instanceof Error?t.message:n,a,{cause:t})}const V={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x1f7907f4d84043abe0fb7c74e8865ee5fe93fe4f691c54a7b8fa9d6fb17c7cba`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0xc64e7c81b18b674fc5b037d8a0041bfe3332d86c780a4688f404ee01fbabb152`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function H(e){return(0,n.getAddress)(v(e.slice(-40)))}function U(e){return BigInt(e)}function W(e){return e}function G(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function be(e,t){return(0,n.getAddress)(v(G(e,t).slice(-40)))}function K(e,t){return BigInt(`0x`+G(e,t))}function q(e,t){return BigInt(`0x`+G(e,t))!==0n}function J(e,t){return v(G(e,t))}function xe(e){return e.topics[0]!==V.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:H(e.topics[1]),to:H(e.topics[2]),encryptedAmountHandle:W(e.topics[3])}}function Y(e){return e.topics[0]!==V.Wrapped||e.topics.length<3?null:{eventName:`Wrapped`,to:H(e.topics[1]),mintTxId:U(e.topics[2]),mintAmount:K(e.data,0),amountIn:K(e.data,1),feeAmount:K(e.data,2)}}function X(e){return e.topics[0]!==V.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:H(e.topics[1]),encryptedAmount:J(e.data,0)}}function Se(e){return e.topics[0]!==V.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,burntAmountHandle:W(e.topics[1]),nextTxId:U(e.topics[2]),finalizeSuccess:q(e.data,0),feeTransferSuccess:q(e.data,1),burnAmount:K(e.data,2),unwrapAmount:K(e.data,3),feeAmount:K(e.data,4)}}function Ce(e){return e.topics[0]!==V.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:U(e.topics[1]),txId:U(e.topics[2]),to:H(e.topics[3]),returnVal:q(e.data,0),refund:be(e.data,1),requestedAmount:J(e.data,2),burnAmount:J(e.data,3)}}function Z(e){return xe(e)??Y(e)??X(e)??Se(e)??Ce(e)}function we(e){let t=[];for(let n of e){let e=Z(n);e&&t.push(e)}return t}function Te(e){for(let t of e){let e=X(t);if(e)return e}return null}function Ee(e){for(let t of e){let e=Y(t);if(e)return e}return null}const De=[V.ConfidentialTransfer,V.Wrapped,V.UnwrapRequested,V.UnwrappedFinalized,V.UnwrappedStarted];function Q(e,t){return e.toLowerCase()===t.toLowerCase()}function $(e,t,n){let r=t!==void 0&&Q(e,t),i=n!==void 0&&Q(e,n);return r&&i?`self`:r?`outgoing`:`incoming`}function Oe(e,t,n){switch(e.eventName){case`ConfidentialTransfer`:return ke(e,t,n);case`Wrapped`:return Ae(e,t,n);case`UnwrapRequested`:return je(e,t,n);case`UnwrappedStarted`:return Me(e,t,n);case`UnwrappedFinalized`:return Ne(e,n)}}function ke(e,t,n){return{type:`transfer`,direction:$(t,e.from,e.to),amount:{type:`encrypted`,handle:e.encryptedAmountHandle},from:e.from,to:e.to,metadata:n,rawEvent:e}}function Ae(e,t,n){return{type:`shield`,direction:$(t,void 0,e.to),amount:{type:`clear`,value:e.amountIn},to:e.to,fee:e.feeAmount,metadata:n,rawEvent:e}}function je(e,t,n){return{type:`unshield_requested`,direction:$(t,void 0,e.receiver),amount:{type:`encrypted`,handle:e.encryptedAmount},to:e.receiver,metadata:n,rawEvent:e}}function Me(e,t,n){return{type:`unshield_started`,direction:$(t,void 0,e.to),amount:{type:`encrypted`,handle:e.requestedAmount},to:e.to,success:e.returnVal,metadata:n,rawEvent:e}}function Ne(e,t){return{type:`unshield_finalized`,direction:`incoming`,amount:{type:`clear`,value:e.unwrapAmount},fee:e.feeAmount,success:e.finalizeSuccess,metadata:t,rawEvent:e}}function Pe(e,t){let n=[];for(let r of e){let e=Z(r);if(!e)continue;let i={transactionHash:r.transactionHash,blockNumber:r.blockNumber,logIndex:r.logIndex};n.push(Oe(e,t,i))}return n}function Fe(e){let t=new Set;for(let n of e)if(n.amount.type===`encrypted`&&n.amount.decryptedValue===void 0){let e=n.amount.handle;e!==`0x`&&e!==`0x0000000000000000000000000000000000000000000000000000000000000000`&&t.add(e)}return[...t]}function Ie(e,t){return e.map(e=>{if(e.amount.type!==`encrypted`)return e;let n=t.get(e.amount.handle);return n===void 0?e:{...e,amount:{type:`encrypted`,handle:e.amount.handle,decryptedValue:n}}})}function Le(e){return[...e].toSorted((e,t)=>{let n=e.metadata.blockNumber,r=t.metadata.blockNumber;if(n===void 0&&r===void 0)return 0;if(n===void 0)return-1;if(r===void 0)return 1;let i=typeof n==`bigint`?n:BigInt(n),a=typeof r==`bigint`?r:BigInt(r);if(a>i)return 1;if(a<i)return-1;let o=e.metadata.logIndex??0;return(t.metadata.logIndex??0)-o})}Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,`G`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`H`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,`J`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`K`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`U`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`V`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`W`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return`0x0000000000000000000000000000000000000000000000000000000000000000`}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return we}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return Fe}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`q`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return p}});
1
+ const e=require(`./relayer.cjs`),t=require(`./wrappers-registry.cjs`);let n=require(`viem`);var r=class extends e.a{constructor(t,n){super(e.o.SigningRejected,t,n),this.name=`SigningRejectedError`}},i=class extends e.a{constructor(t,n){super(e.o.SigningFailed,t,n),this.name=`SigningFailedError`}};function a(e,t){let n=typeof e==`object`&&!!e&&`code`in e&&e.code===4001,a=e instanceof Error?e.message:String(e),o=a.toLowerCase().includes(`user rejected`)||a.toLowerCase().includes(`user denied`),s=`${t}: ${a}`;throw n||o?new r(s,{cause:e}):new i(s,{cause:e})}var o=class extends e.a{constructor(t,n){super(e.o.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},s=class extends e.a{constructor(t,n){super(e.o.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},c=class extends e.a{constructor(t,n){super(e.o.NoCiphertext,t,n),this.name=`NoCiphertextError`}},l=class extends e.a{constructor(t,n){super(e.o.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},u=class extends e.a{constructor(t,n){super(e.o.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},d=class extends e.a{constructor(t,n){super(e.o.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},f=class extends e.a{constructor(t,n){super(e.o.DelegationExpired,t,n),this.name=`DelegationExpiredError`}};function p(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function m(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function h(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function ee(e,t){if(!Array.isArray(e))throw TypeError(`${t} must be an array, got ${typeof e}`)}function g(e,t,n){h(e[t],n)}function _(e,t){if(!e)throw TypeError(t)}function v(e){return e.startsWith(`0x`)?e:`0x${e}`}function te(e){return{address:e,abi:n.erc20Abi,functionName:`name`,args:[]}}function ne(e){return{address:e,abi:n.erc20Abi,functionName:`symbol`,args:[]}}function y(e){return{address:e,abi:n.erc20Abi,functionName:`decimals`,args:[]}}function re(e){return{address:e,abi:n.erc20Abi,functionName:`totalSupply`,args:[]}}function ie(e,t){return{address:e,abi:n.erc20Abi,functionName:`balanceOf`,args:[t]}}function b(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`allowance`,args:[t,r]}}function ae(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`approve`,args:[t,r]}}const x=[{inputs:[{internalType:`uint64`,name:`wrapFeeBasisPoints_`,type:`uint64`},{internalType:`uint64`,name:`unwrapFeeBasisPoints_`,type:`uint64`},{internalType:`uint64`,name:`deployFee_`,type:`uint64`},{internalType:`uint64`,name:`batchTransferFee_`,type:`uint64`},{internalType:`address`,name:`feeRecipient_`,type:`address`}],stateMutability:`nonpayable`,type:`constructor`},{inputs:[],name:`AccessControlBadConfirmation`,type:`error`},{inputs:[{internalType:`address`,name:`account`,type:`address`},{internalType:`bytes32`,name:`neededRole`,type:`bytes32`}],name:`AccessControlUnauthorizedAccount`,type:`error`},{inputs:[],name:`FeeExceedsMaximum`,type:`error`},{inputs:[],name:`ZeroAddressFeeRecipient`,type:`error`},{anonymous:!1,inputs:[{indexed:!1,internalType:`uint64`,name:`oldBatchTransferFee`,type:`uint64`},{indexed:!1,internalType:`uint64`,name:`newBatchTransferFee`,type:`uint64`}],name:`BatchTransferFeeUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!1,internalType:`uint64`,name:`oldDeployFee`,type:`uint64`},{indexed:!1,internalType:`uint64`,name:`newDeployFee`,type:`uint64`}],name:`DeployFeeUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!0,internalType:`address`,name:`oldRecipient`,type:`address`},{indexed:!0,internalType:`address`,name:`newRecipient`,type:`address`}],name:`FeeRecipientUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!0,internalType:`bytes32`,name:`role`,type:`bytes32`},{indexed:!0,internalType:`bytes32`,name:`previousAdminRole`,type:`bytes32`},{indexed:!0,internalType:`bytes32`,name:`newAdminRole`,type:`bytes32`}],name:`RoleAdminChanged`,type:`event`},{anonymous:!1,inputs:[{indexed:!0,internalType:`bytes32`,name:`role`,type:`bytes32`},{indexed:!0,internalType:`address`,name:`account`,type:`address`},{indexed:!0,internalType:`address`,name:`sender`,type:`address`}],name:`RoleGranted`,type:`event`},{anonymous:!1,inputs:[{indexed:!0,internalType:`bytes32`,name:`role`,type:`bytes32`},{indexed:!0,internalType:`address`,name:`account`,type:`address`},{indexed:!0,internalType:`address`,name:`sender`,type:`address`}],name:`RoleRevoked`,type:`event`},{anonymous:!1,inputs:[{indexed:!1,internalType:`bool`,name:`active`,type:`bool`}],name:`SwapperFeeWaiverUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!1,internalType:`uint64`,name:`oldFeeBasisPoints`,type:`uint64`},{indexed:!1,internalType:`uint64`,name:`newFeeBasisPoints`,type:`uint64`}],name:`UnwrapFeeBasisPointsUpdated`,type:`event`},{anonymous:!1,inputs:[{indexed:!1,internalType:`uint64`,name:`oldFeeBasisPoints`,type:`uint64`},{indexed:!1,internalType:`uint64`,name:`newFeeBasisPoints`,type:`uint64`}],name:`WrapFeeBasisPointsUpdated`,type:`event`},{inputs:[],name:`DEFAULT_ADMIN_ROLE`,outputs:[{internalType:`bytes32`,name:``,type:`bytes32`}],stateMutability:`view`,type:`function`},{inputs:[],name:`FEE_MANAGER_ROLE`,outputs:[{internalType:`bytes32`,name:``,type:`bytes32`}],stateMutability:`view`,type:`function`},{inputs:[],name:`MAX_BASIS_POINTS`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`SWAPPER_ROLE`,outputs:[{internalType:`bytes32`,name:``,type:`bytes32`}],stateMutability:`view`,type:`function`},{inputs:[],name:`batchTransferFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`deployFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`feeRecipient`,outputs:[{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getBatchTransferFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`deployer`,type:`address`}],name:`getDeployFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getFeeRecipient`,outputs:[{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`}],name:`getRoleAdmin`,outputs:[{internalType:`bytes32`,name:``,type:`bytes32`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint64`,name:`amount`,type:`uint64`},{internalType:`address`,name:`unwrapFrom`,type:`address`},{internalType:`address`,name:`unwrapTo`,type:`address`}],name:`getUnwrapFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint256`,name:`amount`,type:`uint256`},{internalType:`address`,name:`wrapFrom`,type:`address`},{internalType:`address`,name:`wrapTo`,type:`address`}],name:`getWrapFee`,outputs:[{internalType:`uint256`,name:``,type:`uint256`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`},{internalType:`address`,name:`account`,type:`address`}],name:`grantRole`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`},{internalType:`address`,name:`account`,type:`address`}],name:`hasRole`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`},{inputs:[],name:`protocolId`,outputs:[{internalType:`uint256`,name:``,type:`uint256`}],stateMutability:`pure`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`},{internalType:`address`,name:`callerConfirmation`,type:`address`}],name:`renounceRole`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`bytes32`,name:`role`,type:`bytes32`},{internalType:`address`,name:`account`,type:`address`}],name:`revokeRole`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`uint64`,name:`newBatchTransferFee`,type:`uint64`}],name:`setBatchTransferFee`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`uint64`,name:`newDeployFee`,type:`uint64`}],name:`setDeployFee`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`recipient`,type:`address`}],name:`setFeeRecipient`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`bool`,name:`active`,type:`bool`}],name:`setSwapperFeeWaiverActive`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`uint64`,name:`feeBasisPoints`,type:`uint64`}],name:`setUnwrapFeeBasisPoints`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`uint64`,name:`feeBasisPoints`,type:`uint64`}],name:`setWrapFeeBasisPoints`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`bytes4`,name:`interfaceId`,type:`bytes4`}],name:`supportsInterface`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`},{inputs:[],name:`swapperFeeWaiverActive`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`},{inputs:[],name:`unwrapFeeBasisPoints`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`wrapFeeBasisPoints`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`}];function oe(e,t,n,r){return{address:e,abi:x,functionName:`getWrapFee`,args:[t,n,r]}}function se(e,t,n,r){return{address:e,abi:x,functionName:`getUnwrapFee`,args:[t,n,r]}}function ce(e){return{address:e,abi:x,functionName:`getBatchTransferFee`,args:[]}}function le(e){return{address:e,abi:x,functionName:`getFeeRecipient`,args:[]}}const S=[{inputs:[{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`},{internalType:`uint64`,name:`expirationDate`,type:`uint64`}],name:`delegateForUserDecryption`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`}],name:`revokeDelegationForUserDecryption`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`delegator`,type:`address`},{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`}],name:`getUserDecryptionDelegationExpirationDate`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`}];function ue(e,t,n,r){return{address:e,abi:S,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function de(e,t,n){return{address:e,abi:S,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function C(e,t,n,r){return{address:e,abi:S,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}const w=2n**64n-1n;var T=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 fe=new T,E={CredentialsLoading:`credentials:loading`,CredentialsCached:`credentials:cached`,CredentialsExpired:`credentials:expired`,CredentialsCreating:`credentials:creating`,CredentialsCreated:`credentials:created`,CredentialsRevoked:`credentials:revoked`,CredentialsPersistFailed:`credentials:persist_failed`,CredentialsAllowed:`credentials:allowed`,CredentialsCorrupted:`credentials:corrupted`,SessionExpired:`session:expired`,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`,ApproveSubmitted:`approve: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`};var pe=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return v(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function D(e){m(e,`Stored credentials`),h(e.publicKey,`credentials.publicKey`),ee(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)_(typeof t==`string`&&(0,n.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);m(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),h(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),h(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),_(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),_(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function me(e){D(e);let t=e;_(typeof t.delegatorAddress==`string`&&(0,n.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),_(typeof t.delegateAddress==`string`&&(0,n.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),_(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),_(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function O(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function k(e,t){let r=new Set(t.map(e=>(0,n.getAddress)(e))),i=new Set(e.map(e=>(0,n.getAddress)(e)));return r.isSubsetOf(i)}function A(e,t){return O(e)?k(e.contractAddresses,t):!1}function j(e){return[...new Set(e.map(e=>(0,n.getAddress)(e)))].toSorted()}async function M(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var he=class{#e;constructor(e){this.#e=e}#t(e){m(e,`Session entry`),h(e.signature,`session.signature`),_(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),_(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},N=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new he(e.sessionStorage),this.crypto=new pe,this.keypairTTL=e.keypairTTL??86400,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`)}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:e,contracts:t,createKey:n,createFn:a}){this.emit({type:E.CredentialsLoading,contractAddresses:t});try{let n=await this.storage.get(e);if(n){this.assertEncrypted(n);let r=await this.sessionSignatures.get(e);if(r)if(this.sessionSignatures.isExpired(r))await this.sessionSignatures.delete(e),this.emit({type:E.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(n,r.signature);if(A(i,t))return this.emit({type:E.CredentialsCached,contractAddresses:t}),this.emit({type:E.CredentialsAllowed,contractAddresses:t}),i;if(O(i))return this.#i({key:e,credentials:i,requiredContracts:t});this.emit({type:E.CredentialsExpired,contractAddresses:t})}if(O(n)){if(k(n.contractAddresses,t)){let r=await this.signForContracts(n,n.contractAddresses);await this.sessionSignatures.set({key:e,signature:r,ttl:this.sessionTTL});let i=await this.decryptCredentials(n,r);return this.emit({type:E.CredentialsCached,contractAddresses:t}),this.emit({type:E.CredentialsAllowed,contractAddresses:t}),i}let r=await this.signForContracts(n,n.contractAddresses),i=await this.decryptCredentials(n,r);return this.#i({key:e,credentials:i,requiredContracts:t})}this.emit({type:E.CredentialsExpired,contractAddresses:t})}}catch(t){if(t instanceof r||t instanceof i)throw t;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,t),this.emit({type:E.CredentialsCorrupted,error:p(t)}),await this.#o(e)}return(!this.#t||this.#n!==n)&&(this.#n=n,this.#t=a().then(e=>(this.emit({type:E.CredentialsAllowed,contractAddresses:t}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!A(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,t){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:E.CredentialsRevoked,...t?{contractAddresses:t}:{}})}async checkAllowed(e){let t=await this.sessionSignatures.get(e);return t===null?!1:!this.sessionSignatures.isExpired(t)}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#o(e)}clearCaches(){this.crypto.clearCache()}async createCredentials({key:e,contractAddresses:t,createFn:n,errorContext:r}){this.emit({type:E.CredentialsCreating,contractAddresses:t});try{let r=await n();return await this.persistCredentials(e,r),await this.sessionSignatures.set({key:e,signature:r.signature,ttl:this.sessionTTL}),this.emit({type:E.CredentialsCreated,contractAddresses:t}),r}catch(e){a(e,r)}}async#i({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(k(e.contractAddresses,n))return this.emit({type:E.CredentialsAllowed,contractAddresses:n}),e;t=e}let r=this.#a({key:e,credentials:t,requiredContracts:n});this.#r=r;try{return await r}finally{this.#r===r&&(this.#r=null)}}async#a({key:e,credentials:t,requiredContracts:n}){let r=j([...t.contractAddresses,...n]),i=await this.signForContracts(t,r),a={...t,contractAddresses:r,signature:i};return await this.persistCredentials(e,a),await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL}),this.emit({type:E.CredentialsAllowed,contractAddresses:n}),a}async persistCredentials(e,t){try{let n=await this.encryptCredentials(t);await this.storage.set(e,n)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:E.CredentialsPersistFailed,error:p(e)})}}async#o(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:E.CredentialsPersistFailed,error:p(e)})}}};function ge(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var P=class e extends N{#e;#t=null;#n=null;static async computeStoreKey(e,t){return M((0,n.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,ge(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof T&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=j(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeByKey(e){await this.revokeSession(e)}async isAllowed(){return this.checkAllowed(await this.#r())}async clear(){await this.clearAll(await this.#r())}async create(e){let t=j(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){D(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),r=await this.signer.getChainId(),i=`${(0,n.getAddress)(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(t,r);return this.#n=i,this.#t=a,a}},F=class e extends N{#e;#t=null;#n=null;static async computeStoreKey(e,t,r){return M((0,n.getAddress)(e),(0,n.getAddress)(t),r)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let r=(0,n.getAddress)(e),i=j(t),a=await this.#i(r);return this.resolveCredentials({key:a,contracts:i,createKey:`${r}:${i.join(`,`)}`,createFn:()=>this.#r(r,i)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,n.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,n.getAddress)(e)))}async isAllowed(e){return this.checkAllowed(await this.#i((0,n.getAddress)(e)))}async clear(e){await this.clearAll(await this.#i((0,n.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){me(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let r=await this.signer.getAddress(),i=await this.signer.getChainId(),a=`${(0,n.getAddress)(r)}:${(0,n.getAddress)(t)}:${i}`;if(this.#t&&this.#n===a)return this.#t;let o=await e.computeStoreKey(r,t,i);return this.#n=a,this.#t=o,o}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData({domain:{...n.domain,chainId:Number(n.domain.chainId)},types:n.types,message:{...n.message,startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays)}})}};const I=`zama:balances`;function L(e,t,r){return`zama:balance:${(0,n.getAddress)(e)}:${(0,n.getAddress)(t)}:${r.toLowerCase()}`}async function R({storage:e,tokenAddress:t,owner:n,handle:r}){try{let i=await e.get(L(t,n,r));return i===null?null:BigInt(i)}catch(e){return console.warn(`[zama-sdk] Balance cache read failed:`,e),null}}async function z(e){let{storage:t,tokenAddress:n,owner:r,handle:i,value:a}=e,o=L(n,r,i);try{await t.set(o,a.toString()),await _e(t,o)}catch{}}const B=new WeakMap;async function _e(e,t){let n=(B.get(e)??Promise.resolve()).then(async()=>{let n=await e.get(I),r=n?JSON.parse(n):[];r.includes(t)||(r.push(t),await e.set(I,JSON.stringify(r)))});return B.set(e,n.catch(()=>{})),n}async function ve(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}var ye=class r{credentials;delegatedCredentials;relayer;signer;address;storage;#e;constructor(e){let t={relayer:e.relayer,signer:e.signer,storage:e.storage,sessionStorage:e.sessionStorage,keypairTTL:e.keypairTTL??86400,sessionTTL:e.sessionTTL??2592e3,onEvent:e.onEvent};this.credentials=e.credentials??new P(t),this.delegatedCredentials=e.delegatedCredentials??new F(t),this.relayer=e.relayer,this.signer=e.signer,this.address=(0,n.getAddress)(e.address),this.storage=e.storage,this.#e=e.onEvent}emit(e){this.#e?.({...e,tokenAddress:this.address,timestamp:Date.now()})}async balanceOf(e){let t=e?(0,n.getAddress)(e):await this.signer.getAddress(),r=await this.readConfidentialBalanceOf(t);return this.decryptBalance(r,t)}async confidentialBalanceOf(e){let t=e?(0,n.getAddress)(e):await this.signer.getAddress();return this.readConfidentialBalanceOf(t)}async isConfidential(){return await this.signer.readContract(t.f(this.address,t.c))}async isWrapper(){return await this.signer.readContract(t.f(this.address,t.l))}static async batchDecryptBalances(e,t){if(e.length===0)return new Map;let{handles:n,owner:i,onError:a,maxConcurrency:o}=t??{},s=e[0],c=r.assertSameRelayer(e),l=i??await s.signer.getAddress();return r.#t({tokens:e,handles:n,ownerAddress:l,onError:a,maxConcurrency:o,obtainCreds:e=>s.credentials.allow(...e),decrypt:(e,t,n)=>c.userDecrypt({handles:[t],contractAddress:n,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,signerAddress:l,startTimestamp:e.startTimestamp,durationDays:e.durationDays}),errorPrefix:`Batch decryption`})}static async batchDecryptBalancesAs(e,t){if(e.length===0)return new Map;let{delegatorAddress:n,handles:i,owner:a,onError:o,maxConcurrency:s}=t,c=a??n,l=e[0];return r.assertSameRelayer(e),r.#t({tokens:e,handles:i,ownerAddress:c,onError:o,maxConcurrency:s,preFlightCheck:()=>l.#n(n),obtainCreds:e=>l.delegatedCredentials.allow(n,...e),decrypt:(e,t,n)=>l.relayer.delegatedUserDecrypt({handles:[t],contractAddress:n,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,delegatorAddress:e.delegatorAddress,delegateAddress:e.delegateAddress,startTimestamp:e.startTimestamp,durationDays:e.durationDays}),errorPrefix:`Batch delegated decryption`})}static async#t(t){let{tokens:n,handles:r,ownerAddress:i,onError:a,maxConcurrency:o,obtainCreds:s,decrypt:c,errorPrefix:l}=t,u=n[0],d=r??await Promise.all(n.map(e=>e.readConfidentialBalanceOf(i)));if(n.length!==d.length)throw new e.r(`tokens.length (${n.length}) must equal handles.length (${d.length})`);let f=u.storage,m=new Map,h=[],ee=await Promise.all(n.map((e,t)=>{let n=d[t];return e.isZeroHandle(n)?0n:R({storage:f,tokenAddress:e.address,owner:i,handle:n})}));for(let e=0;e<n.length;e++){let t=n[e],r=d[e],i=ee[e];if(i!=null){m.set(t.address,i);continue}h.push({token:t,handle:r})}if(h.length===0)return m;t.preFlightCheck&&await t.preFlightCheck();let g=await s(h.map(e=>e.token.address)),_=[],v=[];for(let{token:t,handle:n}of h)v.push(()=>c(g,n,t.address).then(async r=>{let a=r[n];if(a===void 0)throw new e.r(`${l} returned no value for handle ${n} on token ${t.address}`);m.set(t.address,a);try{await z({storage:f,tokenAddress:t.address,owner:i,handle:n,value:a})}catch(e){console.warn(`[zama-sdk] Cache write failed (non-blocking):`,e)}}).catch(e=>{let n=p(e);if(a)try{m.set(t.address,a(n,t.address))}catch(e){_.push({address:t.address,error:p(e)})}else _.push({address:t.address,error:n})}));if(await ve(v,o),_.length>0){let t=_.map(e=>`${e.address}: ${e.error.message}`).join(`; `);throw new e.r(`${l} failed for ${_.length} token(s): ${t}`)}return m}async underlyingToken(){return this.signer.readContract(t.m(this.address))}async allowance(e,r){let i=(0,n.getAddress)(e),a=await this.signer.readContract(t.m(i)),o=r?(0,n.getAddress)(r):await this.signer.getAddress();return this.signer.readContract(b(a,o,i))}async name(){return this.signer.readContract(te(this.address))}async symbol(){return this.signer.readContract(ne(this.address))}async decimals(){return this.signer.readContract(y(this.address))}async allow(){await this.credentials.allow(this.address)}async isAllowed(){return this.credentials.isAllowed()}async revoke(...e){await this.credentials.revoke(...e)}static async allow(...e){if(e.length===0)return;let t=e.map(e=>e.address);await e[0].credentials.allow(...t)}async getAclAddress(){return this.relayer.getAclAddress()}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===w?!0:t>await this.signer.getBlockTimestamp()}async getDelegationExpiry({delegatorAddress:e,delegateAddress:t}){let r=await this.getAclAddress();return this.signer.readContract(C(r,(0,n.getAddress)(e),(0,n.getAddress)(t),this.address))}async#n(e){let t=await this.signer.getAddress(),n=await this.getDelegationExpiry({delegatorAddress:e,delegateAddress:t});if(n===0n)throw new d(`No active delegation from ${e} to ${t} for ${this.address}`);if(n!==w&&n<=await this.signer.getBlockTimestamp())throw new f(`Delegation from ${e} to ${t} for ${this.address} has expired`)}async readConfidentialBalanceOf(e){return await this.signer.readContract(t._(this.address,e))}isZeroHandle(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}async decryptBalanceAs({delegatorAddress:t,owner:r}){let i=(0,n.getAddress)(t),a=r?(0,n.getAddress)(r):i,o=await this.readConfidentialBalanceOf(a);if(this.isZeroHandle(o))return 0n;let s=await R({storage:this.storage,tokenAddress:this.address,owner:a,handle:o});if(s!==null)return s;await this.#n(i);let c=Date.now();try{this.emit({type:E.DecryptStart});let t=await this.delegatedCredentials.allow(i,this.address),n=await this.relayer.delegatedUserDecrypt({handles:[o],contractAddress:this.address,signedContractAddresses:t.contractAddresses,privateKey:t.privateKey,publicKey:t.publicKey,signature:t.signature,delegatorAddress:t.delegatorAddress,delegateAddress:t.delegateAddress,startTimestamp:t.startTimestamp,durationDays:t.durationDays});this.emit({type:E.DecryptEnd,durationMs:Date.now()-c});let r=n[o];if(r===void 0)throw new e.r(`Delegated decryption returned no value for handle ${o}`);try{await z({storage:this.storage,tokenAddress:this.address,owner:a,handle:o,value:r})}catch(e){console.warn(`[zama-sdk] Cache write failed (non-blocking):`,e)}return r}catch(e){throw this.emit({type:E.DecryptError,error:p(e),durationMs:Date.now()-c}),V(e,`Failed to decrypt delegated balance`)}}async decryptBalance(t,n){if(this.isZeroHandle(t))return 0n;let r=n??await this.signer.getAddress(),i=await R({storage:this.storage,tokenAddress:this.address,owner:r,handle:t});if(i!==null)return i;let a=await this.credentials.allow(this.address),o=Date.now();try{this.emit({type:E.DecryptStart});let n=await this.relayer.userDecrypt({handles:[t],contractAddress:this.address,signedContractAddresses:a.contractAddresses,privateKey:a.privateKey,publicKey:a.publicKey,signature:a.signature,signerAddress:r,startTimestamp:a.startTimestamp,durationDays:a.durationDays});this.emit({type:E.DecryptEnd,durationMs:Date.now()-o});let i=n[t];if(i===void 0)throw new e.r(`Decryption returned no value for handle ${t}`);try{await z({storage:this.storage,tokenAddress:this.address,owner:r,handle:t,value:i})}catch(e){console.warn(`[zama-sdk] Cache write failed (non-blocking):`,e)}return i}catch(e){throw this.emit({type:E.DecryptError,error:p(e),durationMs:Date.now()-o}),V(e,`Failed to decrypt balance`)}}async decryptHandles(t,n){let r=new Map,i=[];for(let e of t)this.isZeroHandle(e)?r.set(e,0n):i.push(e);if(i.length===0)return r;let a=await this.credentials.allow(this.address),o=Date.now();try{this.emit({type:E.DecryptStart});let t=await this.relayer.userDecrypt({handles:i,contractAddress:this.address,signedContractAddresses:a.contractAddresses,privateKey:a.privateKey,publicKey:a.publicKey,signature:a.signature,signerAddress:n??await this.signer.getAddress(),startTimestamp:a.startTimestamp,durationDays:a.durationDays});this.emit({type:E.DecryptEnd,durationMs:Date.now()-o});for(let n of i){let i=t[n];if(i===void 0)throw new e.r(`Decryption returned no value for handle ${n}`);r.set(n,i)}}catch(e){throw this.emit({type:E.DecryptError,error:p(e),durationMs:Date.now()-o}),V(e,`Failed to decrypt handles`)}return r}static assertSameRelayer(t){let n=t[0].relayer;for(let r=1;r<t.length;r++)if(t[r].relayer!==n)throw new e.t(`All tokens in a batch operation must share the same relayer instance`);return n}};function V(t,n){if(t instanceof e.r||t instanceof c||t instanceof e.n||t instanceof r||t instanceof i)return t;let a=typeof t==`object`&&t&&`statusCode`in t&&typeof t.statusCode==`number`?t.statusCode:void 0;return a===400?new c(t instanceof Error?t.message:`No ciphertext for this account`,{cause:t}):a===void 0?new e.r(n,{cause:t}):new e.n(t instanceof Error?t.message:n,a,{cause:t})}const H={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x1f7907f4d84043abe0fb7c74e8865ee5fe93fe4f691c54a7b8fa9d6fb17c7cba`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0xc64e7c81b18b674fc5b037d8a0041bfe3332d86c780a4688f404ee01fbabb152`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function U(e){return(0,n.getAddress)(v(e.slice(-40)))}function W(e){return BigInt(e)}function G(e){return e}function K(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function be(e,t){return(0,n.getAddress)(v(K(e,t).slice(-40)))}function q(e,t){return BigInt(`0x`+K(e,t))}function J(e,t){return BigInt(`0x`+K(e,t))!==0n}function Y(e,t){return v(K(e,t))}function xe(e){return e.topics[0]!==H.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:U(e.topics[1]),to:U(e.topics[2]),encryptedAmountHandle:G(e.topics[3])}}function X(e){return e.topics[0]!==H.Wrapped||e.topics.length<3?null:{eventName:`Wrapped`,to:U(e.topics[1]),mintTxId:W(e.topics[2]),mintAmount:q(e.data,0),amountIn:q(e.data,1),feeAmount:q(e.data,2)}}function Z(e){return e.topics[0]!==H.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:U(e.topics[1]),encryptedAmount:Y(e.data,0)}}function Se(e){return e.topics[0]!==H.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,burntAmountHandle:G(e.topics[1]),nextTxId:W(e.topics[2]),finalizeSuccess:J(e.data,0),feeTransferSuccess:J(e.data,1),burnAmount:q(e.data,2),unwrapAmount:q(e.data,3),feeAmount:q(e.data,4)}}function Ce(e){return e.topics[0]!==H.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:W(e.topics[1]),txId:W(e.topics[2]),to:U(e.topics[3]),returnVal:J(e.data,0),refund:be(e.data,1),requestedAmount:Y(e.data,2),burnAmount:Y(e.data,3)}}function Q(e){return xe(e)??X(e)??Z(e)??Se(e)??Ce(e)}function we(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function Te(e){for(let t of e){let e=Z(t);if(e)return e}return null}function Ee(e){for(let t of e){let e=X(t);if(e)return e}return null}const De=[H.ConfidentialTransfer,H.Wrapped,H.UnwrapRequested,H.UnwrappedFinalized,H.UnwrappedStarted];function Oe(e,t){return e.toLowerCase()===t.toLowerCase()}function $(e,t,n){let r=t!==void 0&&Oe(e,t),i=n!==void 0&&Oe(e,n);return r&&i?`self`:r?`outgoing`:`incoming`}function ke(e,t,n){switch(e.eventName){case`ConfidentialTransfer`:return Ae(e,t,n);case`Wrapped`:return je(e,t,n);case`UnwrapRequested`:return Me(e,t,n);case`UnwrappedStarted`:return Ne(e,t,n);case`UnwrappedFinalized`:return Pe(e,n)}}function Ae(e,t,n){return{type:`transfer`,direction:$(t,e.from,e.to),amount:{type:`encrypted`,handle:e.encryptedAmountHandle},from:e.from,to:e.to,metadata:n,rawEvent:e}}function je(e,t,n){return{type:`shield`,direction:$(t,void 0,e.to),amount:{type:`clear`,value:e.amountIn},to:e.to,fee:e.feeAmount,metadata:n,rawEvent:e}}function Me(e,t,n){return{type:`unshield_requested`,direction:$(t,void 0,e.receiver),amount:{type:`encrypted`,handle:e.encryptedAmount},to:e.receiver,metadata:n,rawEvent:e}}function Ne(e,t,n){return{type:`unshield_started`,direction:$(t,void 0,e.to),amount:{type:`encrypted`,handle:e.requestedAmount},to:e.to,success:e.returnVal,metadata:n,rawEvent:e}}function Pe(e,t){return{type:`unshield_finalized`,direction:`incoming`,amount:{type:`clear`,value:e.unwrapAmount},fee:e.feeAmount,success:e.finalizeSuccess,metadata:t,rawEvent:e}}function Fe(e,t){let n=[];for(let r of e){let e=Q(r);if(!e)continue;let i={transactionHash:r.transactionHash,blockNumber:r.blockNumber,logIndex:r.logIndex};n.push(ke(e,t,i))}return n}function Ie(e){let t=new Set;for(let n of e)if(n.amount.type===`encrypted`&&n.amount.decryptedValue===void 0){let e=n.amount.handle;e!==`0x`&&e!==`0x0000000000000000000000000000000000000000000000000000000000000000`&&t.add(e)}return[...t]}function Le(e,t){return e.map(e=>{if(e.amount.type!==`encrypted`)return e;let n=t.get(e.amount.handle);return n===void 0?e:{...e,amount:{type:`encrypted`,handle:e.amount.handle,decryptedValue:n}}})}function Re(e){return[...e].toSorted((e,t)=>{let n=e.metadata.blockNumber,r=t.metadata.blockNumber;if(n===void 0&&r===void 0)return 0;if(n===void 0)return-1;if(r===void 0)return 1;let i=typeof n==`bigint`?n:BigInt(n),a=typeof r==`bigint`?r:BigInt(r);if(a>i)return 1;if(a<i)return-1;let o=e.metadata.logIndex??0;return(t.metadata.logIndex??0)-o})}Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,`G`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`H`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,`J`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`K`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`U`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,`V`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`W`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`Y`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return`0x0000000000000000000000000000000000000000000000000000000000000000`}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return Re}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return we}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`q`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return Fe}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return g}});
2
2
  //# sourceMappingURL=activity.cjs.map