@zama-fhe/sdk 2.1.0-alpha.2 → 2.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,11 +14,10 @@ yarn add @zama-fhe/sdk
14
14
 
15
15
  ### Peer dependencies
16
16
 
17
- | Package | Version | Required? |
18
- | ----------------------- | ------- | -------------------------------------------------- |
19
- | `viem` | >= 2 | Optional — for the `@zama-fhe/sdk/viem` adapter |
20
- | `ethers` | >= 6 | Optional — for the `@zama-fhe/sdk/ethers` adapter |
21
- | `@zama-fhe/relayer-sdk` | >= 0.4 | Optional — only for `@zama-fhe/sdk/node` (Node.js) |
17
+ | Package | Version | Required? |
18
+ | -------- | ------- | ------------------------------------------------- |
19
+ | `viem` | >= 2 | Optional — for the `@zama-fhe/sdk/viem` adapter |
20
+ | `ethers` | >= 6 | Optional — for the `@zama-fhe/sdk/ethers` adapter |
22
21
 
23
22
  ## Module Systems (ESM & CJS)
24
23
 
@@ -1,2 +1,2 @@
1
- const e=require(`./errors.cjs`),t=require(`./erc165.cjs`);let n=require(`viem`);function r(e){return e instanceof Error?e:Error(String(e))}function i(e){return e.startsWith(`0x`)?e:`0x${e}`}function a(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function o(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function s(e,t){if(!Array.isArray(e))throw TypeError(`${t} must be an array, got ${typeof e}`)}function c(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function l(e,t,n){o(e[t],n)}function u(e,t,n){c(e[t],n)}function d(e,t){if(!e)throw TypeError(t)}function f(){let e=globalThis;for(let t of[e.chrome,e.browser])try{a(t,`ns`);let{runtime:e}=t;return a(e,`runtime`),l(e,`id`,`runtime.id`),u(e,`getURL`,`runtime.getURL`),e}catch{continue}}async function ee(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++;n[t]=await e[t]()}}return await Promise.all(Array.from({length:t},i)),n}function p(e){return{address:e,abi:n.erc20Abi,functionName:`name`,args:[]}}function m(e){return{address:e,abi:n.erc20Abi,functionName:`symbol`,args:[]}}function h(e){return{address:e,abi:n.erc20Abi,functionName:`decimals`,args:[]}}function g(e,t){return{address:e,abi:n.erc20Abi,functionName:`balanceOf`,args:[t]}}function _(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`allowance`,args:[t,r]}}function v(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`approve`,args:[t,r]}}const y=[{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:`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:[],name:`getBatchTransferFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getFeeRecipient`,outputs:[{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`}];function te(e,t,n,r){return{address:e,abi:y,functionName:`getWrapFee`,args:[t,n,r]}}function ne(e,t,n,r){return{address:e,abi:y,functionName:`getUnwrapFee`,args:[t,n,r]}}function re(e){return{address:e,abi:y,functionName:`getBatchTransferFee`,args:[]}}function ie(e){return{address:e,abi:y,functionName:`getFeeRecipient`,args:[]}}const b=[{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 ae(e,t,n,r){return{address:e,abi:b,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function oe(e,t,n){return{address:e,abi:b,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function x(e,t,n,r){return{address:e,abi:b,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}const S=2n**64n-1n,C={CredentialsLoading:`credentials:loading`,CredentialsCached:`credentials:cached`,CredentialsExpired:`credentials:expired`,CredentialsCreating:`credentials:creating`,CredentialsCreated:`credentials:created`,CredentialsRevoked:`credentials:revoked`,CredentialsAllowed:`credentials:allowed`,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 w=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 se=new w;var ce=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),a=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),o=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),s=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a},r,o);return i(new TextDecoder().decode(s))}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 T(e){a(e,`Stored credentials`),o(e.publicKey,`credentials.publicKey`),s(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)d(typeof t==`string`&&(0,n.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);a(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),o(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),o(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`)}function le(e){T(e);let t=e;d(typeof t.delegatorAddress==`string`&&(0,n.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),d(typeof t.delegateAddress==`string`&&(0,n.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),d(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),d(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function E(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function D(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 O(e,t){return E(e)?D(e.contractAddresses,t):!1}function k(e){return[...new Set(e.map(e=>(0,n.getAddress)(e)))].toSorted()}async function ue(...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 de=class{#e;constructor(e){this.#e=e}#t(e){a(e,`Session entry`),o(e.signature,`session.signature`),d(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),d(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}},A=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 de(e.sessionStorage),this.crypto=new ce,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:t,contracts:n,createKey:r,createFn:i}){this.emit({type:C.CredentialsLoading,contractAddresses:n});try{let e=await this.storage.get(t);if(e){this.assertEncrypted(e);let r=await this.sessionSignatures.get(t);if(r)if(this.sessionSignatures.isExpired(r))await this.sessionSignatures.delete(t),this.emit({type:C.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(e,r.signature);if(O(i,n))return this.emit({type:C.CredentialsCached,contractAddresses:n}),this.emit({type:C.CredentialsAllowed,contractAddresses:n}),i;if(E(i))return this.#i({key:t,credentials:i,requiredContracts:n});this.emit({type:C.CredentialsExpired,contractAddresses:n})}if(E(e)){if(D(e.contractAddresses,n)){let r=await this.signForContracts(e,e.contractAddresses);await this.sessionSignatures.set({key:t,signature:r,ttl:this.sessionTTL});let i=await this.decryptCredentials(e,r);return this.emit({type:C.CredentialsCached,contractAddresses:n}),this.emit({type:C.CredentialsAllowed,contractAddresses:n}),i}let r=await this.signForContracts(e,e.contractAddresses),i=await this.decryptCredentials(e,r);return this.#i({key:t,credentials:i,requiredContracts:n})}this.emit({type:C.CredentialsExpired,contractAddresses:n})}}catch(n){if(n instanceof e.m||n instanceof e.p)throw n;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,n),await this.#o(t)}return(!this.#t||this.#n!==r)&&(this.#n=r,this.#t=i().then(e=>(this.emit({type:C.CredentialsAllowed,contractAddresses:n}),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),!O(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:C.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:t,contractAddresses:n,createFn:r,errorContext:i}){this.emit({type:C.CredentialsCreating,contractAddresses:n});try{let e=await r();return await this.persistCredentials(t,e),await this.sessionSignatures.set({key:t,signature:e.signature,ttl:this.sessionTTL}),this.emit({type:C.CredentialsCreated,contractAddresses:n}),e}catch(t){e.y(t,i)}}async#i({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(D(e.contractAddresses,n))return this.emit({type:C.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=k([...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:C.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);return}}async#o(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e)}}};function fe(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 j=class e extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t){return ue((0,n.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,fe(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof w&&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=k(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 isAllowed(){return this.checkAllowed(await this.#r())}async clear(){await this.clearAll(await this.#r())}async create(e){let t=k(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){T(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}},M=class e extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t,r){return ue((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=k(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){le(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 N=`zama:balances`;function P(e,t,r){return`zama:balance:${(0,n.getAddress)(e)}:${(0,n.getAddress)(t)}:${r.toLowerCase()}`}async function F({storage:e,tokenAddress:t,owner:n,handle:r}){try{let i=await e.get(P(t,n,r));return i===null?null:BigInt(i)}catch(e){return console.warn(`[zama-sdk] Balance cache read failed:`,e),null}}async function I(e){let{storage:t,tokenAddress:n,owner:r,handle:i,value:a}=e,o=P(n,r,i);try{await t.set(o,a.toString()),await pe(t,o)}catch{}}const L=new WeakMap;async function pe(e,t){let n=(L.get(e)??Promise.resolve()).then(async()=>{let n=await e.get(N),r=n?JSON.parse(n):[];r.includes(t)||(r.push(t),await e.set(N,JSON.stringify(r)))});return L.set(e,n.catch(()=>{})),n}var me=class i{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 j(t),this.delegatedCredentials=e.delegatedCredentials??new M(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:r,onError:a,maxConcurrency:o}=t??{},s=e[0],c=i.assertSameRelayer(e),l=r??await s.signer.getAddress();return i.#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:r,owner:a,onError:o,maxConcurrency:s}=t,c=a??n,l=e[0];return i.assertSameRelayer(e),i.#t({tokens:e,handles:r,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:i,ownerAddress:a,onError:o,maxConcurrency:s,obtainCreds:c,decrypt:l,errorPrefix:u}=t,d=n[0],f=i??await Promise.all(n.map(e=>e.readConfidentialBalanceOf(a)));if(n.length!==f.length)throw new e.r(`tokens.length (${n.length}) must equal handles.length (${f.length})`);let p=d.storage,m=new Map,h=[],g=await Promise.all(n.map((e,t)=>{let n=f[t];return e.isZeroHandle(n)?0n:F({storage:p,tokenAddress:e.address,owner:a,handle:n})}));for(let e=0;e<n.length;e++){let t=n[e],r=f[e],i=g[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 _=await c(h.map(e=>e.token.address)),v=[],y=[];for(let{token:t,handle:n}of h)y.push(()=>l(_,n,t.address).then(async r=>{let i=r[n];if(i===void 0)throw new e.r(`${u} returned no value for handle ${n} on token ${t.address}`);m.set(t.address,i);try{await I({storage:p,tokenAddress:t.address,owner:a,handle:n,value:i})}catch{}}).catch(e=>{let n=r(e);if(o)try{m.set(t.address,o(n,t.address))}catch(e){v.push({address:t.address,error:r(e)})}else v.push({address:t.address,error:n})}));if(await ee(y,s),v.length>0){let t=v.map(e=>`${e.address}: ${e.error.message}`).join(`; `);throw new e.r(`${u} failed for ${v.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(_(a,o,i))}async name(){return this.signer.readContract(p(this.address))}async symbol(){return this.signer.readContract(m(this.address))}async decimals(){return this.signer.readContract(h(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===S?!0:t>await this.signer.getBlockTimestamp()}async getDelegationExpiry({delegatorAddress:e,delegateAddress:t}){let r=await this.getAclAddress();return this.signer.readContract(x(r,(0,n.getAddress)(e),(0,n.getAddress)(t),this.address))}async#n(t){let n=await this.signer.getAddress(),r=await this.getDelegationExpiry({delegatorAddress:t,delegateAddress:n});if(r===0n)throw new e.o(`No active delegation from ${t} to ${n} for ${this.address}`);if(r!==S&&r<=await this.signer.getBlockTimestamp())throw new e.a(`Delegation from ${t} to ${n} 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:i}){let a=(0,n.getAddress)(t),o=i?(0,n.getAddress)(i):a,s=await this.readConfidentialBalanceOf(o);if(this.isZeroHandle(s))return 0n;let c=await F({storage:this.storage,tokenAddress:this.address,owner:o,handle:s});if(c!==null)return c;await this.#n(a);let l=Date.now();try{this.emit({type:C.DecryptStart});let t=await this.delegatedCredentials.allow(a,this.address),n=await this.relayer.delegatedUserDecrypt({handles:[s],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:C.DecryptEnd,durationMs:Date.now()-l});let r=n[s];if(r===void 0)throw new e.r(`Delegated decryption returned no value for handle ${s}`);try{await I({storage:this.storage,tokenAddress:this.address,owner:o,handle:s,value:r})}catch{}return r}catch(e){throw this.emit({type:C.DecryptError,error:r(e),durationMs:Date.now()-l}),R(e,`Failed to decrypt delegated balance`)}}async decryptBalance(t,n){if(this.isZeroHandle(t))return 0n;let i=n??await this.signer.getAddress(),a=await F({storage:this.storage,tokenAddress:this.address,owner:i,handle:t});if(a!==null)return a;let o=await this.credentials.allow(this.address),s=Date.now();try{this.emit({type:C.DecryptStart});let n=await this.relayer.userDecrypt({handles:[t],contractAddress:this.address,signedContractAddresses:o.contractAddresses,privateKey:o.privateKey,publicKey:o.publicKey,signature:o.signature,signerAddress:i,startTimestamp:o.startTimestamp,durationDays:o.durationDays});this.emit({type:C.DecryptEnd,durationMs:Date.now()-s});let r=n[t];if(r===void 0)throw new e.r(`Decryption returned no value for handle ${t}`);try{await I({storage:this.storage,tokenAddress:this.address,owner:i,handle:t,value:r})}catch{}return r}catch(e){throw this.emit({type:C.DecryptError,error:r(e),durationMs:Date.now()-s}),R(e,`Failed to decrypt balance`)}}async decryptHandles(t,n){let i=new Map,a=[];for(let e of t)this.isZeroHandle(e)?i.set(e,0n):a.push(e);if(a.length===0)return i;let o=await this.credentials.allow(this.address),s=Date.now();try{this.emit({type:C.DecryptStart});let t=await this.relayer.userDecrypt({handles:a,contractAddress:this.address,signedContractAddresses:o.contractAddresses,privateKey:o.privateKey,publicKey:o.publicKey,signature:o.signature,signerAddress:n??await this.signer.getAddress(),startTimestamp:o.startTimestamp,durationDays:o.durationDays});this.emit({type:C.DecryptEnd,durationMs:Date.now()-s});for(let n of a){let r=t[n];if(r===void 0)throw new e.r(`Decryption returned no value for handle ${n}`);i.set(n,r)}}catch(e){throw this.emit({type:C.DecryptError,error:r(e),durationMs:Date.now()-s}),R(e,`Failed to decrypt handles`)}return i}static assertSameRelayer(t){let n=t[0].relayer;for(let r=1;r<t.length;r++)if(t[r].relayer!==n)throw new e.n(`All tokens in a batch operation must share the same relayer instance`);return n}};function R(t,n){if(t instanceof e.r||t instanceof e.d||t instanceof e.f||t instanceof e.m||t instanceof e.p)return t;let r=typeof t==`object`&&t&&`statusCode`in t&&typeof t.statusCode==`number`?t.statusCode:void 0;return r===400?new e.d(t instanceof Error?t.message:`No ciphertext for this account`,{cause:t}):r===void 0?new e.r(n,{cause:t}):new e.f(t instanceof Error?t.message:n,r,{cause:t})}const z={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x1f7907f4d84043abe0fb7c74e8865ee5fe93fe4f691c54a7b8fa9d6fb17c7cba`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0xc64e7c81b18b674fc5b037d8a0041bfe3332d86c780a4688f404ee01fbabb152`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function B(e){return(0,n.getAddress)(i(e.slice(-40)))}function V(e){return BigInt(e)}function H(e){return e}function U(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function he(e,t){return(0,n.getAddress)(i(U(e,t).slice(-40)))}function W(e,t){return BigInt(`0x`+U(e,t))}function G(e,t){return BigInt(`0x`+U(e,t))!==0n}function K(e,t){return i(U(e,t))}function q(e){return e.topics[0]!==z.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:B(e.topics[1]),to:B(e.topics[2]),encryptedAmountHandle:H(e.topics[3])}}function J(e){return e.topics[0]!==z.Wrapped||e.topics.length<3?null:{eventName:`Wrapped`,to:B(e.topics[1]),mintTxId:V(e.topics[2]),mintAmount:W(e.data,0),amountIn:W(e.data,1),feeAmount:W(e.data,2)}}function Y(e){return e.topics[0]!==z.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:B(e.topics[1]),encryptedAmount:K(e.data,0)}}function X(e){return e.topics[0]!==z.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,burntAmountHandle:H(e.topics[1]),nextTxId:V(e.topics[2]),finalizeSuccess:G(e.data,0),feeTransferSuccess:G(e.data,1),burnAmount:W(e.data,2),unwrapAmount:W(e.data,3),feeAmount:W(e.data,4)}}function Z(e){return e.topics[0]!==z.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:V(e.topics[1]),txId:V(e.topics[2]),to:B(e.topics[3]),returnVal:G(e.data,0),refund:he(e.data,1),requestedAmount:K(e.data,2),burnAmount:K(e.data,3)}}function Q(e){return q(e)??J(e)??Y(e)??X(e)??Z(e)}function ge(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function _e(e){for(let t of e){let e=Y(t);if(e)return e}return null}function ve(e){for(let t of e){let e=J(t);if(e)return e}return null}const ye=[z.ConfidentialTransfer,z.Wrapped,z.UnwrapRequested,z.UnwrappedFinalized,z.UnwrappedStarted];function be(e,t){return e.toLowerCase()===t.toLowerCase()}function $(e,t,n){let r=t!==void 0&&be(e,t),i=n!==void 0&&be(e,n);return r&&i?`self`:r?`outgoing`:`incoming`}function xe(e,t,n){switch(e.eventName){case`ConfidentialTransfer`:return Se(e,t,n);case`Wrapped`:return Ce(e,t,n);case`UnwrapRequested`:return we(e,t,n);case`UnwrappedStarted`:return Te(e,t,n);case`UnwrappedFinalized`:return Ee(e,n)}}function Se(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 Ce(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 we(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 Te(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 Ee(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 De(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(xe(e,t,i))}return n}function Oe(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 ke(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 Ae(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 te}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return`0x0000000000000000000000000000000000000000000000000000000000000000`}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return ke}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return f}});
1
+ const e=require(`./errors.cjs`),t=require(`./erc165.cjs`);let n=require(`viem`);function r(e){return e instanceof Error?e:Error(String(e))}function i(e){return e.startsWith(`0x`)?e:`0x${e}`}function a(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function o(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function s(e,t){if(!Array.isArray(e))throw TypeError(`${t} must be an array, got ${typeof e}`)}function c(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function l(e,t,n){o(e[t],n)}function u(e,t,n){c(e[t],n)}function d(e,t){if(!e)throw TypeError(t)}function f(){let e=globalThis;for(let t of[e.chrome,e.browser])try{a(t,`ns`);let{runtime:e}=t;return a(e,`runtime`),l(e,`id`,`runtime.id`),u(e,`getURL`,`runtime.getURL`),e}catch{continue}}async function ee(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++;n[t]=await e[t]()}}return await Promise.all(Array.from({length:t},i)),n}function p(e){return{address:e,abi:n.erc20Abi,functionName:`name`,args:[]}}function m(e){return{address:e,abi:n.erc20Abi,functionName:`symbol`,args:[]}}function h(e){return{address:e,abi:n.erc20Abi,functionName:`decimals`,args:[]}}function g(e,t){return{address:e,abi:n.erc20Abi,functionName:`balanceOf`,args:[t]}}function _(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`allowance`,args:[t,r]}}function v(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`approve`,args:[t,r]}}const y=[{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:`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:[],name:`getBatchTransferFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getFeeRecipient`,outputs:[{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`}];function te(e,t,n,r){return{address:e,abi:y,functionName:`getWrapFee`,args:[t,n,r]}}function ne(e,t,n,r){return{address:e,abi:y,functionName:`getUnwrapFee`,args:[t,n,r]}}function re(e){return{address:e,abi:y,functionName:`getBatchTransferFee`,args:[]}}function ie(e){return{address:e,abi:y,functionName:`getFeeRecipient`,args:[]}}const b=[{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 ae(e,t,n,r){return{address:e,abi:b,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function oe(e,t,n){return{address:e,abi:b,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function x(e,t,n,r){return{address:e,abi:b,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}const S=2n**64n-1n,C={CredentialsLoading:`credentials:loading`,CredentialsCached:`credentials:cached`,CredentialsExpired:`credentials:expired`,CredentialsCreating:`credentials:creating`,CredentialsCreated:`credentials:created`,CredentialsRevoked:`credentials:revoked`,CredentialsAllowed:`credentials:allowed`,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 w=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 se=new w;var ce=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),a=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),o=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),s=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a},r,o);return i(new TextDecoder().decode(s))}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 T(e){a(e,`Stored credentials`),o(e.publicKey,`credentials.publicKey`),s(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)d(typeof t==`string`&&(0,n.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);a(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),o(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),o(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`)}function le(e){T(e);let t=e;d(typeof t.delegatorAddress==`string`&&(0,n.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),d(typeof t.delegateAddress==`string`&&(0,n.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),d(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),d(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function E(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function D(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 O(e,t){return E(e)?D(e.contractAddresses,t):!1}function k(e){return[...new Set(e.map(e=>(0,n.getAddress)(e)))].toSorted()}async function ue(...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 de=class{#e;constructor(e){this.#e=e}#t(e){a(e,`Session entry`),o(e.signature,`session.signature`),d(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),d(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}},A=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 de(e.sessionStorage),this.crypto=new ce,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:t,contracts:n,createKey:r,createFn:i}){this.emit({type:C.CredentialsLoading,contractAddresses:n});try{let e=await this.storage.get(t);if(e){this.assertEncrypted(e);let r=await this.sessionSignatures.get(t);if(r)if(this.sessionSignatures.isExpired(r))await this.sessionSignatures.delete(t),this.emit({type:C.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(e,r.signature);if(O(i,n))return this.emit({type:C.CredentialsCached,contractAddresses:n}),this.emit({type:C.CredentialsAllowed,contractAddresses:n}),i;if(E(i))return this.#i({key:t,credentials:i,requiredContracts:n});this.emit({type:C.CredentialsExpired,contractAddresses:n})}if(E(e)){if(D(e.contractAddresses,n)){let r=await this.signForContracts(e,e.contractAddresses);await this.sessionSignatures.set({key:t,signature:r,ttl:this.sessionTTL});let i=await this.decryptCredentials(e,r);return this.emit({type:C.CredentialsCached,contractAddresses:n}),this.emit({type:C.CredentialsAllowed,contractAddresses:n}),i}let r=await this.signForContracts(e,e.contractAddresses),i=await this.decryptCredentials(e,r);return this.#i({key:t,credentials:i,requiredContracts:n})}this.emit({type:C.CredentialsExpired,contractAddresses:n})}}catch(n){if(n instanceof e.m||n instanceof e.p)throw n;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,n),await this.#o(t)}return(!this.#t||this.#n!==r)&&(this.#n=r,this.#t=i().then(e=>(this.emit({type:C.CredentialsAllowed,contractAddresses:n}),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),!O(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:C.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:t,contractAddresses:n,createFn:r,errorContext:i}){this.emit({type:C.CredentialsCreating,contractAddresses:n});try{let e=await r();return await this.persistCredentials(t,e),await this.sessionSignatures.set({key:t,signature:e.signature,ttl:this.sessionTTL}),this.emit({type:C.CredentialsCreated,contractAddresses:n}),e}catch(t){e.y(t,i)}}async#i({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(D(e.contractAddresses,n))return this.emit({type:C.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=k([...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:C.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);return}}async#o(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e)}}};function fe(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 j=class e extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t){return ue((0,n.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,fe(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof w&&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=k(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=k(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){T(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}},M=class e extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t,r){return ue((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=k(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){le(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 N=`zama:balances`;function P(e,t,r){return`zama:balance:${(0,n.getAddress)(e)}:${(0,n.getAddress)(t)}:${r.toLowerCase()}`}async function F({storage:e,tokenAddress:t,owner:n,handle:r}){try{let i=await e.get(P(t,n,r));return i===null?null:BigInt(i)}catch(e){return console.warn(`[zama-sdk] Balance cache read failed:`,e),null}}async function I(e){let{storage:t,tokenAddress:n,owner:r,handle:i,value:a}=e,o=P(n,r,i);try{await t.set(o,a.toString()),await pe(t,o)}catch{}}const L=new WeakMap;async function pe(e,t){let n=(L.get(e)??Promise.resolve()).then(async()=>{let n=await e.get(N),r=n?JSON.parse(n):[];r.includes(t)||(r.push(t),await e.set(N,JSON.stringify(r)))});return L.set(e,n.catch(()=>{})),n}var me=class i{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 j(t),this.delegatedCredentials=e.delegatedCredentials??new M(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:r,onError:a,maxConcurrency:o}=t??{},s=e[0],c=i.assertSameRelayer(e),l=r??await s.signer.getAddress();return i.#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:r,owner:a,onError:o,maxConcurrency:s}=t,c=a??n,l=e[0];return i.assertSameRelayer(e),i.#t({tokens:e,handles:r,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:i,ownerAddress:a,onError:o,maxConcurrency:s,obtainCreds:c,decrypt:l,errorPrefix:u}=t,d=n[0],f=i??await Promise.all(n.map(e=>e.readConfidentialBalanceOf(a)));if(n.length!==f.length)throw new e.r(`tokens.length (${n.length}) must equal handles.length (${f.length})`);let p=d.storage,m=new Map,h=[],g=await Promise.all(n.map((e,t)=>{let n=f[t];return e.isZeroHandle(n)?0n:F({storage:p,tokenAddress:e.address,owner:a,handle:n})}));for(let e=0;e<n.length;e++){let t=n[e],r=f[e],i=g[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 _=await c(h.map(e=>e.token.address)),v=[],y=[];for(let{token:t,handle:n}of h)y.push(()=>l(_,n,t.address).then(async r=>{let i=r[n];if(i===void 0)throw new e.r(`${u} returned no value for handle ${n} on token ${t.address}`);m.set(t.address,i);try{await I({storage:p,tokenAddress:t.address,owner:a,handle:n,value:i})}catch{}}).catch(e=>{let n=r(e);if(o)try{m.set(t.address,o(n,t.address))}catch(e){v.push({address:t.address,error:r(e)})}else v.push({address:t.address,error:n})}));if(await ee(y,s),v.length>0){let t=v.map(e=>`${e.address}: ${e.error.message}`).join(`; `);throw new e.r(`${u} failed for ${v.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(_(a,o,i))}async name(){return this.signer.readContract(p(this.address))}async symbol(){return this.signer.readContract(m(this.address))}async decimals(){return this.signer.readContract(h(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===S?!0:t>await this.signer.getBlockTimestamp()}async getDelegationExpiry({delegatorAddress:e,delegateAddress:t}){let r=await this.getAclAddress();return this.signer.readContract(x(r,(0,n.getAddress)(e),(0,n.getAddress)(t),this.address))}async#n(t){let n=await this.signer.getAddress(),r=await this.getDelegationExpiry({delegatorAddress:t,delegateAddress:n});if(r===0n)throw new e.o(`No active delegation from ${t} to ${n} for ${this.address}`);if(r!==S&&r<=await this.signer.getBlockTimestamp())throw new e.a(`Delegation from ${t} to ${n} 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:i}){let a=(0,n.getAddress)(t),o=i?(0,n.getAddress)(i):a,s=await this.readConfidentialBalanceOf(o);if(this.isZeroHandle(s))return 0n;let c=await F({storage:this.storage,tokenAddress:this.address,owner:o,handle:s});if(c!==null)return c;await this.#n(a);let l=Date.now();try{this.emit({type:C.DecryptStart});let t=await this.delegatedCredentials.allow(a,this.address),n=await this.relayer.delegatedUserDecrypt({handles:[s],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:C.DecryptEnd,durationMs:Date.now()-l});let r=n[s];if(r===void 0)throw new e.r(`Delegated decryption returned no value for handle ${s}`);try{await I({storage:this.storage,tokenAddress:this.address,owner:o,handle:s,value:r})}catch{}return r}catch(e){throw this.emit({type:C.DecryptError,error:r(e),durationMs:Date.now()-l}),R(e,`Failed to decrypt delegated balance`)}}async decryptBalance(t,n){if(this.isZeroHandle(t))return 0n;let i=n??await this.signer.getAddress(),a=await F({storage:this.storage,tokenAddress:this.address,owner:i,handle:t});if(a!==null)return a;let o=await this.credentials.allow(this.address),s=Date.now();try{this.emit({type:C.DecryptStart});let n=await this.relayer.userDecrypt({handles:[t],contractAddress:this.address,signedContractAddresses:o.contractAddresses,privateKey:o.privateKey,publicKey:o.publicKey,signature:o.signature,signerAddress:i,startTimestamp:o.startTimestamp,durationDays:o.durationDays});this.emit({type:C.DecryptEnd,durationMs:Date.now()-s});let r=n[t];if(r===void 0)throw new e.r(`Decryption returned no value for handle ${t}`);try{await I({storage:this.storage,tokenAddress:this.address,owner:i,handle:t,value:r})}catch{}return r}catch(e){throw this.emit({type:C.DecryptError,error:r(e),durationMs:Date.now()-s}),R(e,`Failed to decrypt balance`)}}async decryptHandles(t,n){let i=new Map,a=[];for(let e of t)this.isZeroHandle(e)?i.set(e,0n):a.push(e);if(a.length===0)return i;let o=await this.credentials.allow(this.address),s=Date.now();try{this.emit({type:C.DecryptStart});let t=await this.relayer.userDecrypt({handles:a,contractAddress:this.address,signedContractAddresses:o.contractAddresses,privateKey:o.privateKey,publicKey:o.publicKey,signature:o.signature,signerAddress:n??await this.signer.getAddress(),startTimestamp:o.startTimestamp,durationDays:o.durationDays});this.emit({type:C.DecryptEnd,durationMs:Date.now()-s});for(let n of a){let r=t[n];if(r===void 0)throw new e.r(`Decryption returned no value for handle ${n}`);i.set(n,r)}}catch(e){throw this.emit({type:C.DecryptError,error:r(e),durationMs:Date.now()-s}),R(e,`Failed to decrypt handles`)}return i}static assertSameRelayer(t){let n=t[0].relayer;for(let r=1;r<t.length;r++)if(t[r].relayer!==n)throw new e.n(`All tokens in a batch operation must share the same relayer instance`);return n}};function R(t,n){if(t instanceof e.r||t instanceof e.d||t instanceof e.f||t instanceof e.m||t instanceof e.p)return t;let r=typeof t==`object`&&t&&`statusCode`in t&&typeof t.statusCode==`number`?t.statusCode:void 0;return r===400?new e.d(t instanceof Error?t.message:`No ciphertext for this account`,{cause:t}):r===void 0?new e.r(n,{cause:t}):new e.f(t instanceof Error?t.message:n,r,{cause:t})}const z={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x1f7907f4d84043abe0fb7c74e8865ee5fe93fe4f691c54a7b8fa9d6fb17c7cba`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0xc64e7c81b18b674fc5b037d8a0041bfe3332d86c780a4688f404ee01fbabb152`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function B(e){return(0,n.getAddress)(i(e.slice(-40)))}function V(e){return BigInt(e)}function H(e){return e}function U(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function he(e,t){return(0,n.getAddress)(i(U(e,t).slice(-40)))}function W(e,t){return BigInt(`0x`+U(e,t))}function G(e,t){return BigInt(`0x`+U(e,t))!==0n}function K(e,t){return i(U(e,t))}function q(e){return e.topics[0]!==z.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:B(e.topics[1]),to:B(e.topics[2]),encryptedAmountHandle:H(e.topics[3])}}function J(e){return e.topics[0]!==z.Wrapped||e.topics.length<3?null:{eventName:`Wrapped`,to:B(e.topics[1]),mintTxId:V(e.topics[2]),mintAmount:W(e.data,0),amountIn:W(e.data,1),feeAmount:W(e.data,2)}}function Y(e){return e.topics[0]!==z.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:B(e.topics[1]),encryptedAmount:K(e.data,0)}}function X(e){return e.topics[0]!==z.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,burntAmountHandle:H(e.topics[1]),nextTxId:V(e.topics[2]),finalizeSuccess:G(e.data,0),feeTransferSuccess:G(e.data,1),burnAmount:W(e.data,2),unwrapAmount:W(e.data,3),feeAmount:W(e.data,4)}}function Z(e){return e.topics[0]!==z.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:V(e.topics[1]),txId:V(e.topics[2]),to:B(e.topics[3]),returnVal:G(e.data,0),refund:he(e.data,1),requestedAmount:K(e.data,2),burnAmount:K(e.data,3)}}function Q(e){return q(e)??J(e)??Y(e)??X(e)??Z(e)}function ge(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function _e(e){for(let t of e){let e=Y(t);if(e)return e}return null}function ve(e){for(let t of e){let e=J(t);if(e)return e}return null}const ye=[z.ConfidentialTransfer,z.Wrapped,z.UnwrapRequested,z.UnwrappedFinalized,z.UnwrappedStarted];function be(e,t){return e.toLowerCase()===t.toLowerCase()}function $(e,t,n){let r=t!==void 0&&be(e,t),i=n!==void 0&&be(e,n);return r&&i?`self`:r?`outgoing`:`incoming`}function xe(e,t,n){switch(e.eventName){case`ConfidentialTransfer`:return Se(e,t,n);case`Wrapped`:return Ce(e,t,n);case`UnwrapRequested`:return we(e,t,n);case`UnwrappedStarted`:return Te(e,t,n);case`UnwrappedFinalized`:return Ee(e,n)}}function Se(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 Ce(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 we(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 Te(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 Ee(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 De(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(xe(e,t,i))}return n}function Oe(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 ke(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 Ae(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 te}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return`0x0000000000000000000000000000000000000000000000000000000000000000`}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return ke}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return f}});
2
2
  //# sourceMappingURL=activity.cjs.map