@zama-fhe/sdk 2.3.0-alpha.4 → 2.3.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/activity.cjs +1 -1
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/esm/{activity-CitpHeLO.d.ts → activity-DTBvolDB.d.ts} +195 -15
- package/dist/esm/{activity-CNU7ZLpc.js → activity-b2RsqKHW.js} +2 -2
- package/dist/esm/{activity-CNU7ZLpc.js.map → activity-b2RsqKHW.js.map} +1 -1
- package/dist/esm/cleartext/index.d.ts +2 -2
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-BO5OIem2.js → cleartext-Bzxet3H7.js} +2 -2
- package/dist/esm/{cleartext-BO5OIem2.js.map → cleartext-Bzxet3H7.js.map} +1 -1
- package/dist/esm/{encryption-UaXE1L_W.js → encryption-CmIPBcfP.js} +2 -2
- package/dist/esm/{encryption-UaXE1L_W.js.map → encryption-CmIPBcfP.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +2 -2
- package/dist/esm/{index-C3ELlhM8.d.ts → index-BXdXzzx4.d.ts} +2 -2
- package/dist/esm/index.d.ts +5 -128
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.d.ts +2 -2
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/query/index.d.ts +10 -18
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/relayer-C6u3eOlN.js +2 -0
- package/dist/esm/relayer-C6u3eOlN.js.map +1 -0
- package/dist/esm/{relayer-sdk-Cqx3HnZh.d.ts → relayer-sdk-C_4bkxxH.d.ts} +2 -2
- package/dist/esm/{relayer-sdk.types-BhV3n5qO.d.ts → relayer-sdk.types-C9GAgQ7q.d.ts} +23 -2
- package/dist/esm/viem/index.d.ts +2 -2
- package/package.json +1 -1
- package/dist/esm/relayer-DfjPWTBf.js +0 -2
- package/dist/esm/relayer-DfjPWTBf.js.map +0 -1
package/dist/cjs/activity.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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(),s=o.includes(`user rejected`)||o.includes(`user denied`),c=`${t}: ${a}`;throw n||s?new r(c,{cause:e}):new i(c,{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`}},ee=class extends e.a{constructor(t,n){super(e.o.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},u=class extends e.a{constructor(t,n){super(e.o.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},d=class extends e.a{constructor(t,n){super(e.o.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},f=class extends e.a{constructor(t,n){super(e.o.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},p=class extends e.a{constructor(t,n){super(e.o.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},m=class extends e.a{constructor(t,n){super(e.o.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},h=class extends e.a{constructor(t,n){super(e.o.AclPaused,t,n),this.name=`AclPausedError`}},g=class extends e.a{constructor(t,n){super(e.o.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},_=class extends e.a{constructor(t,n){super(e.o.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function te(e,t){if(e==null)throw TypeError(`${t} must not be null or undefined`)}function v(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function y(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function ne(e,t){if(!Array.isArray(e))throw TypeError(`${t} must be an array, got ${typeof e}`)}function re(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function ie(e,t,n){y(e[t],n)}function ae(e,t,n){re(e[t],n)}function b(e,t){if(!e)throw TypeError(t)}function x(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function oe(e){if(!(e instanceof Error))return!1;if(e.name===`ContractFunctionExecutionError`||e.name===`ContractFunctionRevertedError`||`code`in e&&e.code===`CALL_EXCEPTION`)return!0;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}function S(e){return e.startsWith(`0x`)?e:`0x${e}`}function se(e){return{address:e,abi:n.erc20Abi,functionName:`name`,args:[]}}function ce(e){return{address:e,abi:n.erc20Abi,functionName:`symbol`,args:[]}}function le(e){return{address:e,abi:n.erc20Abi,functionName:`decimals`,args:[]}}function ue(e){return{address:e,abi:n.erc20Abi,functionName:`totalSupply`,args:[]}}function de(e,t){return{address:e,abi:n.erc20Abi,functionName:`balanceOf`,args:[t]}}function fe(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`allowance`,args:[t,r]}}function pe(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`approve`,args:[t,r]}}const C=[{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 me(e,t,n,r){return{address:e,abi:C,functionName:`getWrapFee`,args:[t,n,r]}}function he(e,t,n,r){return{address:e,abi:C,functionName:`getUnwrapFee`,args:[t,n,r]}}function ge(e){return{address:e,abi:C,functionName:`getBatchTransferFee`,args:[]}}function _e(e){return{address:e,abi:C,functionName:`getFeeRecipient`,args:[]}}const w=[{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`},{inputs:[{internalType:`address`,name:`delegator`,type:`address`},{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`},{internalType:`bytes32`,name:`handle`,type:`bytes32`}],name:`isHandleDelegatedForUserDecryption`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`}];function ve(e,t,n,r){return{address:e,abi:w,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function ye(e,t,n){return{address:e,abi:w,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function be(e,t,n,r){return{address:e,abi:w,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function xe(e,t,n,r,i){return{address:e,abi:w,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const T=2n**64n-1n;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 Se=new E,D={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 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),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 S(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 O(e){v(e,`Stored credentials`),y(e.publicKey,`credentials.publicKey`),ne(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)b(typeof t==`string`&&(0,n.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);v(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),y(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),y(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),b(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),b(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function we(e){O(e);let t=e;b(typeof t.delegatorAddress==`string`&&(0,n.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),b(typeof t.delegateAddress==`string`&&(0,n.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),b(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),b(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function k(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function A(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 j(e,t){return k(e)?A(e.contractAddresses,t):!1}function M(e){return[...new Set(e.map(e=>(0,n.getAddress)(e)))].toSorted()}async function N(...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 Te=class{#e;constructor(e){this.#e=e}#t(e){v(e,`Session entry`),y(e.signature,`session.signature`),b(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),b(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}},P=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 Te(e.sessionStorage),this.crypto=new Ce,this.keypairTTL=e.keypairTTL??2592e3,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`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:t,contracts:n,createKey:r,createFn:i}){this.emit({type:D.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:D.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(e,r.signature);if(j(i,n))return this.emit({type:D.CredentialsCached,contractAddresses:n}),this.emit({type:D.CredentialsAllowed,contractAddresses:n}),i;if(k(i))return this.#i({key:t,credentials:i,requiredContracts:n});this.emit({type:D.CredentialsExpired,contractAddresses:n})}if(k(e)){if(A(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:D.CredentialsCached,contractAddresses:n}),this.emit({type:D.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:D.CredentialsExpired,contractAddresses:n})}}catch(n){if(n instanceof e.a)throw n;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,n),this.emit({type:D.CredentialsCorrupted,error:x(n)}),await this.#o(t)}return(!this.#t||this.#n!==r)&&(this.#n=r,this.#t=i().then(e=>(this.emit({type:D.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),!j(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:D.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:D.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:D.CredentialsCreated,contractAddresses:n}),e}catch(t){if(t instanceof e.a)throw t;a(t,i)}}async#i({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(A(e.contractAddresses,n))return this.emit({type:D.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=M([...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:D.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:D.CredentialsPersistFailed,error:x(e)})}}async#o(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:D.CredentialsPersistFailed,error:x(e)})}}};function Ee(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 De=class e extends P{#e;#t=null;#n=null;static async computeStoreKey(e,t){return N((0,n.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,Ee(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=M(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=M(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){O(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}},Oe=class e extends P{#e;#t=null;#n=null;static async computeStoreKey(e,t,r){return N((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=M(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){we(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 ke=`zama:balances`;function Ae(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(Ae(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=Ae(n,r,i);try{await t.set(o,a.toString()),await Me(t,o)}catch{}}const je=new WeakMap;async function Me(e,t){let n=(je.get(e)??Promise.resolve()).then(async()=>{let n=await e.get(ke),r=n?JSON.parse(n):[];r.includes(t)||(r.push(t),await e.set(ke,JSON.stringify(r)))});return je.set(e,n.catch(()=>{})),n}async function Ne(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 Pe=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??2592e3,sessionTTL:e.sessionTTL??2592e3,onEvent:e.onEvent};this.credentials=e.credentials??new De(t),this.delegatedCredentials=e.delegatedCredentials??new Oe(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,ee=n[0],u=r??await Promise.all(n.map(e=>e.readConfidentialBalanceOf(i)));if(n.length!==u.length)throw new e.r(`tokens.length (${n.length}) must equal handles.length (${u.length})`);let d=ee.storage,f=new Map,p=[],m=await Promise.all(n.map((e,t)=>{let n=u[t];return e.isZeroHandle(n)?0n:F({storage:d,tokenAddress:e.address,owner:i,handle:n})}));for(let e=0;e<n.length;e++){let t=n[e],r=u[e],i=m[e];if(i!=null){f.set(t.address,i);continue}p.push({token:t,handle:r})}if(p.length===0)return f;t.preFlightCheck&&await t.preFlightCheck();let h=await s(p.map(e=>e.token.address)),g=[],_=[];for(let{token:t,handle:n}of p)_.push(()=>c(h,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}`);f.set(t.address,a);try{await I({storage:d,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=x(e);if(a)try{f.set(t.address,a(n,t.address))}catch(e){g.push({address:t.address,error:x(e)})}else g.push({address:t.address,error:n})}));if(await Ne(_,o),g.length>0){let t=g.map(e=>`${e.address}: ${e.error.message}`).join(`; `);throw new e.r(`${l} failed for ${g.length} token(s): ${t}`)}return f}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(fe(a,o,i))}async name(){return this.signer.readContract(se(this.address))}async symbol(){return this.signer.readContract(ce(this.address))}async decimals(){return this.signer.readContract(le(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===T?!0:t>await this.signer.getBlockTimestamp()}async getDelegationExpiry({delegatorAddress:e,delegateAddress:t}){let r=await this.getAclAddress();return this.signer.readContract(be(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 u(`No active delegation from ${e} to ${t} for ${this.address}`);if(n!==T&&n<=await this.signer.getBlockTimestamp())throw new d(`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 F({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:D.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:D.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 I({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:D.DecryptError,error:x(e),durationMs:Date.now()-c}),L(e,`Failed to decrypt delegated balance`,!0)}}async decryptBalance(t,n){if(this.isZeroHandle(t))return 0n;let r=n??await this.signer.getAddress(),i=await F({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:D.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:D.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 I({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:D.DecryptError,error:x(e),durationMs:Date.now()-o}),L(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:D.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:D.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:D.DecryptError,error:x(e),durationMs:Date.now()-o}),L(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 L(t,n,a=!1){if(t instanceof e.r||t instanceof c||t instanceof e.n||t instanceof _||t instanceof r||t instanceof i)return t;let o=typeof t==`object`&&t&&`statusCode`in t&&typeof t.statusCode==`number`?t.statusCode:void 0;return o===400?new c(t instanceof Error?t.message:`No ciphertext for this account`,{cause:t}):a&&o===500?new _(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet — after granting delegation, allow 1–2 minutes for cross-chain synchronization before retrying. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:t}):o===void 0?new e.r(n,{cause:t}):new e.n(t instanceof Error?t.message:n,o,{cause:t})}const R={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x1f7907f4d84043abe0fb7c74e8865ee5fe93fe4f691c54a7b8fa9d6fb17c7cba`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0xc64e7c81b18b674fc5b037d8a0041bfe3332d86c780a4688f404ee01fbabb152`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function z(e){return(0,n.getAddress)(S(e.slice(-40)))}function B(e){return BigInt(e)}function Fe(e){return e}function V(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function H(e,t){return(0,n.getAddress)(S(V(e,t).slice(-40)))}function U(e,t){return BigInt(`0x`+V(e,t))}function W(e,t){return BigInt(`0x`+V(e,t))!==0n}function G(e,t){return S(V(e,t))}function Ie(e){return e.topics[0]!==R.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:z(e.topics[1]),to:z(e.topics[2]),encryptedAmountHandle:Fe(e.topics[3])}}function K(e){return e.topics[0]!==R.Wrapped||e.topics.length<3?null:{eventName:`Wrapped`,to:z(e.topics[1]),mintTxId:B(e.topics[2]),mintAmount:U(e.data,0),amountIn:U(e.data,1),feeAmount:U(e.data,2)}}function q(e){return e.topics[0]!==R.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:z(e.topics[1]),encryptedAmount:G(e.data,0)}}function Le(e){return e.topics[0]!==R.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,burntAmountHandle:Fe(e.topics[1]),nextTxId:B(e.topics[2]),finalizeSuccess:W(e.data,0),feeTransferSuccess:W(e.data,1),burnAmount:U(e.data,2),unwrapAmount:U(e.data,3),feeAmount:U(e.data,4)}}function Re(e){return e.topics[0]!==R.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:B(e.topics[1]),txId:B(e.topics[2]),to:z(e.topics[3]),returnVal:W(e.data,0),refund:H(e.data,1),requestedAmount:G(e.data,2),burnAmount:G(e.data,3)}}function J(e){return Ie(e)??K(e)??q(e)??Le(e)??Re(e)}function ze(e){let t=[];for(let n of e){let e=J(n);e&&t.push(e)}return t}function Be(e){for(let t of e){let e=q(t);if(e)return e}return null}function Ve(e){for(let t of e){let e=K(t);if(e)return e}return null}const He=[R.ConfidentialTransfer,R.Wrapped,R.UnwrapRequested,R.UnwrappedFinalized,R.UnwrappedStarted],Y={DelegatedForUserDecryption:`0x527b025d7ff06689c1ab9d32dfd7881c964cce72ce8ac5b2fe1d3be8cfda5bfc`,RevokedDelegationForUserDecryption:`0x7aca80b6b7928b9038f186e3d9922a0fc5d52c398fbf144725c142c52a5277e4`};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:z(e.topics[1]),delegate:z(e.topics[2]),contractAddress:H(e.data,0),delegationCounter:U(e.data,1),oldExpirationDate:U(e.data,2),newExpirationDate:U(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:z(e.topics[1]),delegate:z(e.topics[2]),contractAddress:H(e.data,0),delegationCounter:U(e.data,1),oldExpirationDate:U(e.data,2)}}function Ue(e){return X(e)??Z(e)}function We(e){let t=[];for(let n of e){let e=Ue(n);e&&t.push(e)}return t}function Ge(e){for(let t of e){let e=X(t);if(e)return e}return null}function Ke(e){for(let t of e){let e=Z(t);if(e)return e}return null}const qe=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];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 Je(e,t,n){switch(e.eventName){case`ConfidentialTransfer`:return Ye(e,t,n);case`Wrapped`:return Xe(e,t,n);case`UnwrapRequested`:return Ze(e,t,n);case`UnwrappedStarted`:return Qe(e,t,n);case`UnwrappedFinalized`:return $e(e,n)}}function Ye(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 Xe(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 Ze(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 Qe(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 $e(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 et(e,t){let n=[];for(let r of e){let e=J(r);if(!e)continue;let i={transactionHash:r.transactionHash,blockNumber:r.blockNumber,logIndex:r.logIndex};n.push(Je(e,t,i))}return n}function tt(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 nt(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 rt(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,`$`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,`G`,{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,`H`,{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,`J`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`K`,{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,`Q`,{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return he}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return`0x0000000000000000000000000000000000000000000000000000000000000000`}}),Object.defineProperty(exports,`U`,{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,`V`,{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,`W`,{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,`X`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,`Y`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`Z`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return qe}}),Object.defineProperty(exports,`at`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return Ge}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`ct`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,`dt`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`et`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`ft`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return rt}}),Object.defineProperty(exports,`it`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(exports,`lt`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return tt}}),Object.defineProperty(exports,`nt`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`ot`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`pt`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`q`,{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return et}}),Object.defineProperty(exports,`rt`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return He}}),Object.defineProperty(exports,`st`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return nt}}),Object.defineProperty(exports,`tt`,{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return We}}),Object.defineProperty(exports,`ut`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return Re}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return me}});
|
|
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(),s=o.includes(`user rejected`)||o.includes(`user denied`),c=`${t}: ${a}`;throw n||s?new r(c,{cause:e}):new i(c,{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`}},ee=class extends e.a{constructor(t,n){super(e.o.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},u=class extends e.a{constructor(t,n){super(e.o.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},d=class extends e.a{constructor(t,n){super(e.o.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},f=class extends e.a{constructor(t,n){super(e.o.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},p=class extends e.a{constructor(t,n){super(e.o.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},m=class extends e.a{constructor(t,n){super(e.o.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},h=class extends e.a{constructor(t,n){super(e.o.AclPaused,t,n),this.name=`AclPausedError`}},g=class extends e.a{constructor(t,n){super(e.o.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},_=class extends e.a{constructor(t,n){super(e.o.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function te(e,t){if(e==null)throw TypeError(`${t} must not be null or undefined`)}function v(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function y(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function ne(e,t){if(!Array.isArray(e))throw TypeError(`${t} must be an array, got ${typeof e}`)}function re(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function ie(e,t,n){y(e[t],n)}function ae(e,t,n){re(e[t],n)}function b(e,t){if(!e)throw TypeError(t)}function x(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function oe(e){if(!(e instanceof Error))return!1;if(e.name===`ContractFunctionExecutionError`||e.name===`ContractFunctionRevertedError`||`code`in e&&e.code===`CALL_EXCEPTION`)return!0;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}function S(e){return e.startsWith(`0x`)?e:`0x${e}`}function se(e){return{address:e,abi:n.erc20Abi,functionName:`name`,args:[]}}function ce(e){return{address:e,abi:n.erc20Abi,functionName:`symbol`,args:[]}}function le(e){return{address:e,abi:n.erc20Abi,functionName:`decimals`,args:[]}}function ue(e){return{address:e,abi:n.erc20Abi,functionName:`totalSupply`,args:[]}}function de(e,t){return{address:e,abi:n.erc20Abi,functionName:`balanceOf`,args:[t]}}function fe(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`allowance`,args:[t,r]}}function pe(e,t,r){return{address:e,abi:n.erc20Abi,functionName:`approve`,args:[t,r]}}const C=[{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 me(e,t,n,r){return{address:e,abi:C,functionName:`getWrapFee`,args:[t,n,r]}}function he(e,t,n,r){return{address:e,abi:C,functionName:`getUnwrapFee`,args:[t,n,r]}}function ge(e){return{address:e,abi:C,functionName:`getBatchTransferFee`,args:[]}}function _e(e){return{address:e,abi:C,functionName:`getFeeRecipient`,args:[]}}const w=[{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`},{inputs:[{internalType:`address`,name:`delegator`,type:`address`},{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`},{internalType:`bytes32`,name:`handle`,type:`bytes32`}],name:`isHandleDelegatedForUserDecryption`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`}];function ve(e,t,n,r){return{address:e,abi:w,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function ye(e,t,n){return{address:e,abi:w,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function be(e,t,n,r){return{address:e,abi:w,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function xe(e,t,n,r,i){return{address:e,abi:w,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const T=2n**64n-1n;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 Se=new E,D={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 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),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 S(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 O(e){v(e,`Stored credentials`),y(e.publicKey,`credentials.publicKey`),ne(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)b(typeof t==`string`&&(0,n.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);v(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),y(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),y(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),b(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),b(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function we(e){O(e);let t=e;b(typeof t.delegatorAddress==`string`&&(0,n.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),b(typeof t.delegateAddress==`string`&&(0,n.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),b(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),b(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function k(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function A(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 j(e,t){return k(e)?A(e.contractAddresses,t):!1}function M(e){return[...new Set(e.map(e=>(0,n.getAddress)(e)))].toSorted()}async function N(...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 Te=class{#e;constructor(e){this.#e=e}#t(e){v(e,`Session entry`),y(e.signature,`session.signature`),b(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),b(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}},P=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 Te(e.sessionStorage),this.crypto=new Ce,this.keypairTTL=e.keypairTTL??2592e3,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`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:t,contracts:n,createKey:r,createFn:i}){this.emit({type:D.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:D.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(e,r.signature);if(j(i,n))return this.emit({type:D.CredentialsCached,contractAddresses:n}),this.emit({type:D.CredentialsAllowed,contractAddresses:n}),i;if(k(i))return this.#i({key:t,credentials:i,requiredContracts:n});this.emit({type:D.CredentialsExpired,contractAddresses:n})}if(k(e)){if(A(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:D.CredentialsCached,contractAddresses:n}),this.emit({type:D.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:D.CredentialsExpired,contractAddresses:n})}}catch(n){if(n instanceof e.a)throw n;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,n),this.emit({type:D.CredentialsCorrupted,error:x(n)}),await this.#o(t)}return(!this.#t||this.#n!==r)&&(this.#n=r,this.#t=i().then(e=>(this.emit({type:D.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),!j(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:D.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:D.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:D.CredentialsCreated,contractAddresses:n}),e}catch(t){if(t instanceof e.a)throw t;a(t,i)}}async#i({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(A(e.contractAddresses,n))return this.emit({type:D.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=M([...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:D.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:D.CredentialsPersistFailed,error:x(e)})}}async#o(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:D.CredentialsPersistFailed,error:x(e)})}}};function Ee(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 De=class e extends P{#e;#t=null;#n=null;static async computeStoreKey(e,t){return N((0,n.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,Ee(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=M(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=M(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){O(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}},Oe=class e extends P{#e;#t=null;#n=null;static async computeStoreKey(e,t,r){return N((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=M(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){we(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 ke=`zama:balances`;function Ae(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(Ae(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=Ae(n,r,i);try{await t.set(o,a.toString()),await Me(t,o)}catch{}}const je=new WeakMap;async function Me(e,t){let n=(je.get(e)??Promise.resolve()).then(async()=>{let n=await e.get(ke),r=n?JSON.parse(n):[];r.includes(t)||(r.push(t),await e.set(ke,JSON.stringify(r)))});return je.set(e,n.catch(()=>{})),n}async function Ne(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 Pe=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??2592e3,sessionTTL:e.sessionTTL??2592e3,onEvent:e.onEvent};this.credentials=e.credentials??new De(t),this.delegatedCredentials=e.delegatedCredentials??new Oe(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,ee=n[0],u=r??await Promise.all(n.map(e=>e.readConfidentialBalanceOf(i)));if(n.length!==u.length)throw new e.r(`tokens.length (${n.length}) must equal handles.length (${u.length})`);let d=ee.storage,f=new Map,p=[],m=await Promise.all(n.map((e,t)=>{let n=u[t];return e.isZeroHandle(n)?0n:F({storage:d,tokenAddress:e.address,owner:i,handle:n})}));for(let e=0;e<n.length;e++){let t=n[e],r=u[e],i=m[e];if(i!=null){f.set(t.address,i);continue}p.push({token:t,handle:r})}if(p.length===0)return f;t.preFlightCheck&&await t.preFlightCheck();let h=await s(p.map(e=>e.token.address)),g=[],_=[];for(let{token:t,handle:n}of p)_.push(()=>c(h,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}`);f.set(t.address,a);try{await I({storage:d,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=x(e);if(a)try{f.set(t.address,a(n,t.address))}catch(e){g.push({address:t.address,error:x(e)})}else g.push({address:t.address,error:n})}));if(await Ne(_,o),g.length>0){let t=g.map(e=>`${e.address}: ${e.error.message}`).join(`; `);throw new e.r(`${l} failed for ${g.length} token(s): ${t}`)}return f}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(fe(a,o,i))}async name(){return this.signer.readContract(se(this.address))}async symbol(){return this.signer.readContract(ce(this.address))}async decimals(){return this.signer.readContract(le(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===T?!0:t>await this.signer.getBlockTimestamp()}async getDelegationExpiry({delegatorAddress:e,delegateAddress:t}){let r=await this.getAclAddress();return this.signer.readContract(be(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 u(`No active delegation from ${e} to ${t} for ${this.address}`);if(n!==T&&n<=await this.signer.getBlockTimestamp())throw new d(`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 F({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:D.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:D.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 I({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:D.DecryptError,error:x(e),durationMs:Date.now()-c}),L(e,`Failed to decrypt delegated balance`,!0)}}async decryptBalance(t,n){if(this.isZeroHandle(t))return 0n;let r=n??await this.signer.getAddress(),i=await F({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:D.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:D.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 I({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:D.DecryptError,error:x(e),durationMs:Date.now()-o}),L(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:D.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:D.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:D.DecryptError,error:x(e),durationMs:Date.now()-o}),L(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 L(t,n,a=!1){if(t instanceof e.r||t instanceof c||t instanceof e.n||t instanceof _||t instanceof r||t instanceof i)return t;let o=typeof t==`object`&&t&&`statusCode`in t&&typeof t.statusCode==`number`?t.statusCode:void 0;return o===400?new c(t instanceof Error?t.message:`No ciphertext for this account`,{cause:t}):a&&o===500?new _(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet — after granting delegation, allow 1–2 minutes for cross-chain synchronization before retrying. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:t}):o===void 0?new e.r(n,{cause:t}):new e.n(t instanceof Error?t.message:n,o,{cause:t})}const R={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x1f7907f4d84043abe0fb7c74e8865ee5fe93fe4f691c54a7b8fa9d6fb17c7cba`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0xc64e7c81b18b674fc5b037d8a0041bfe3332d86c780a4688f404ee01fbabb152`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function z(e){return(0,n.getAddress)(S(e.slice(-40)))}function B(e){return BigInt(e)}function Fe(e){return e}function V(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function H(e,t){return(0,n.getAddress)(S(V(e,t).slice(-40)))}function U(e,t){return BigInt(`0x`+V(e,t))}function W(e,t){return BigInt(`0x`+V(e,t))!==0n}function G(e,t){return S(V(e,t))}function Ie(e){return e.topics[0]!==R.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:z(e.topics[1]),to:z(e.topics[2]),encryptedAmountHandle:Fe(e.topics[3])}}function K(e){return e.topics[0]!==R.Wrapped||e.topics.length<3?null:{eventName:`Wrapped`,to:z(e.topics[1]),mintTxId:B(e.topics[2]),mintAmount:U(e.data,0),amountIn:U(e.data,1),feeAmount:U(e.data,2)}}function q(e){return e.topics[0]!==R.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:z(e.topics[1]),encryptedAmount:G(e.data,0)}}function Le(e){return e.topics[0]!==R.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,burntAmountHandle:Fe(e.topics[1]),nextTxId:B(e.topics[2]),finalizeSuccess:W(e.data,0),feeTransferSuccess:W(e.data,1),burnAmount:U(e.data,2),unwrapAmount:U(e.data,3),feeAmount:U(e.data,4)}}function Re(e){return e.topics[0]!==R.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:B(e.topics[1]),txId:B(e.topics[2]),to:z(e.topics[3]),returnVal:W(e.data,0),refund:H(e.data,1),requestedAmount:G(e.data,2),burnAmount:G(e.data,3)}}function J(e){return Ie(e)??K(e)??q(e)??Le(e)??Re(e)}function ze(e){let t=[];for(let n of e){let e=J(n);e&&t.push(e)}return t}function Be(e){for(let t of e){let e=q(t);if(e)return e}return null}function Ve(e){for(let t of e){let e=K(t);if(e)return e}return null}const He=[R.ConfidentialTransfer,R.Wrapped,R.UnwrapRequested,R.UnwrappedFinalized,R.UnwrappedStarted],Y={DelegatedForUserDecryption:`0x527b025d7ff06689c1ab9d32dfd7881c964cce72ce8ac5b2fe1d3be8cfda5bfc`,RevokedDelegationForUserDecryption:`0x7aca80b6b7928b9038f186e3d9922a0fc5d52c398fbf144725c142c52a5277e4`};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:z(e.topics[1]),delegate:z(e.topics[2]),contractAddress:H(e.data,0),delegationCounter:U(e.data,1),oldExpirationDate:U(e.data,2),newExpirationDate:U(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:z(e.topics[1]),delegate:z(e.topics[2]),contractAddress:H(e.data,0),delegationCounter:U(e.data,1),oldExpirationDate:U(e.data,2)}}function Ue(e){return X(e)??Z(e)}function We(e){let t=[];for(let n of e){let e=Ue(n);e&&t.push(e)}return t}function Ge(e){for(let t of e){let e=X(t);if(e)return e}return null}function Ke(e){for(let t of e){let e=Z(t);if(e)return e}return null}const qe=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];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 Je(e,t,n){switch(e.eventName){case`ConfidentialTransfer`:return Ye(e,t,n);case`Wrapped`:return Xe(e,t,n);case`UnwrapRequested`:return Ze(e,t,n);case`UnwrappedStarted`:return Qe(e,t,n);case`UnwrappedFinalized`:return $e(e,n)}}function Ye(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 Xe(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 Ze(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 Qe(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 $e(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 et(e,t){let n=[];for(let r of e){let e=J(r);if(!e)continue;let i={transactionHash:r.transactionHash,blockNumber:r.blockNumber,logIndex:r.logIndex};n.push(Je(e,t,i))}return n}function tt(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 nt(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 rt(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,`$`,{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,`G`,{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,`H`,{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,`J`,{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,`K`,{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,`Q`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return`0x0000000000000000000000000000000000000000000000000000000000000000`}}),Object.defineProperty(exports,`U`,{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,`V`,{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,`W`,{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,`X`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`Y`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`Z`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return qe}}),Object.defineProperty(exports,`at`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return Ge}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`ct`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,`dt`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`et`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`ft`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return rt}}),Object.defineProperty(exports,`it`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(exports,`lt`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`mt`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return tt}}),Object.defineProperty(exports,`nt`,{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`ot`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`pt`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`q`,{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return et}}),Object.defineProperty(exports,`rt`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return He}}),Object.defineProperty(exports,`st`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return nt}}),Object.defineProperty(exports,`tt`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return We}}),Object.defineProperty(exports,`ut`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return Re}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return he}});
|
|
2
2
|
//# sourceMappingURL=activity.cjs.map
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./activity.cjs`),n=require(`./cleartext.cjs`),r=require(`./wrappers-registry.cjs`),i=require(`./transfer-batcher.cjs`);let a=require(`viem`);var o=class extends e.a{constructor(t,n){super(e.o.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},s=class extends e.a{constructor(t,n){super(e.o.TransactionReverted,t,n),this.name=`TransactionRevertedError`}};function
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./activity.cjs`),n=require(`./cleartext.cjs`),r=require(`./wrappers-registry.cjs`),i=require(`./transfer-batcher.cjs`);let a=require(`viem`);var o=class extends e.a{constructor(t,n){super(e.o.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},s=class extends e.a{constructor(t,n){super(e.o.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},c=class extends e.a{requested;available;token;constructor(t,n,r){super(e.o.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},l=class extends e.a{requested;available;token;constructor(t,n,r){super(e.o.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},u=class extends e.a{constructor(t,n){super(e.o.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},d=class extends e.a{constructor(t,n){super(e.o.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function f(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const p={AlreadyDelegatedOrRevokedInSameBlock:e=>new t.nt(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.tt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.et(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.lt(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.rt(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.it(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.ot(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.st(`Cannot revoke: no active delegation exists.`,{cause:e})};function m(e){let t=e instanceof Error?e:void 0,n=f(e);if(n&&n in p)return p[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(p))if(r.includes(e))return n(t);return null}var h=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{console.warn(`IndexedDB "${this.#n}" closing due to version change from another tab`),this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const g=new h,_=3e4;var v=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,6e4),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let t=this.#t.get(e.id);if(!t){this.logger?.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let n=Math.round(performance.now()-t.startTime);if(clearTimeout(t.timeoutId),this.#t.delete(e.id),e.success)this.logger?.debug(`[WorkerClient] ← ${t.type} OK`,{id:e.id,elapsed:n}),t.resolve(e.data);else{this.logger?.error(`[WorkerClient] ← ${t.type} FAILED`,{id:e.id,elapsed:n,error:e.error});let r=Error(e.error);`statusCode`in e&&typeof e.statusCode==`number`&&(r.statusCode=e.statusCode),t.reject(r)}}handleWorkerError(e){this.logger?.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#i(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger?.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#i(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(e,t,n,r=_){return new Promise((i,a)=>{let o=this.generateRequestId(),s=performance.now();this.logger?.debug(`[WorkerClient] → ${t}`,{id:o});let c=setTimeout(()=>{this.#t.delete(o);let e=Math.round(performance.now()-s);this.logger?.error(`[WorkerClient] ${t} timed out after ${r}ms`,{id:o,elapsed:e}),a(Error(`Request ${t} timed out after ${r}ms`))},r);this.#t.set(o,{resolve:i,reject:a,timeoutId:c,startTime:s,type:t});let l={id:o,type:t,payload:n};this.postMessage(e,l)})}async sendRequest(e,t,n=_){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n)}async generateKeypair(){return this.sendRequest(`GENERATE_KEYPAIR`,{})}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,{handles:e})}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,{zkProof:e})}async getPublicKey(){return this.sendRequest(`GET_PUBLIC_KEY`,{})}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,{bits:e})}#i(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function y(e){try{return t.Q(e,`runtime`),t.$(e,`id`,`runtime.id`),t.X(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function b(){let e=globalThis;for(let n of[e.chrome,e.browser])try{if(t.Q(n,`ns`),y(n.runtime))return n.runtime}catch{continue}}var x=class extends v{constructor(e){super(e,e.logger)}createWorker(){let e=b();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
|
|
2
2
|
//#region src/utils/assertions.ts
|
|
3
3
|
function assertNonNullable(value, context) {
|
|
4
4
|
if (value === null || value === void 0) throw new TypeError(\`\${context} must not be null or undefined\`);
|
|
@@ -511,5 +511,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
511
511
|
};
|
|
512
512
|
//#endregion
|
|
513
513
|
})();
|
|
514
|
-
`],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};const v=8192,y=300*1e3;function b(e){let t=[];for(let n=0;n<e.length;n+=v)t.push(String.fromCharCode(...e.subarray(n,n+v)));return btoa(t.join(``))}function x(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function S(e){return`fhe:pubkey:${e}`}function C(e,t){return`fhe:params:${e}:${t}`}function w(e){return`fhe:params-index:${e}`}function T(e){t.Z(e,`CachedPublicKey`),t.Q(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.Q(e,`publicKey`,`CachedPublicKey.publicKey`)}function E(e){t.Z(e,`CachedPublicParams`),t.Q(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.Q(e,`publicParams`,`CachedPublicParams.publicParams`)}var D=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let n=S(this.#t);try{let e=await this.#e.get(n);if(e){T(e);let t={publicKeyId:e.publicKeyId,publicKey:x(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.J(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:b(r.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:t.J(e).message})}return r}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,n){let r=C(this.#t,e);try{let t=await this.#e.get(r);if(t){E(t);let n={publicParamsId:t.publicParamsId,publicParams:x(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.J(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:b(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=w(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.J(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.J(n).message})}return i}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let n=S(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{T(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.J(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+y;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+y;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.J(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+y;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:t.J(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=w(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.J(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=C(this.#t,e),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:t.J(n).message}),null}if(!r)return null;try{return E(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.J(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.J(n).message})})}async#_(e,n){let r=w(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:t.J(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,n,r){let i=[this.#e.set(e,n).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:t.J(e).message})}),...r.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:t.J(e).message})}))];await Promise.all(i)}},O=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new d(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new D({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new _(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,r,i=7){let a=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:r,durationDays:i}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:n.c(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.l(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.l(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},k=class n extends t.w{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?(0,a.getAddress)(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(r.m(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,i,o){let c=(0,a.getAddress)(n),l,u,d=Date.now();try{this.emit({type:t.O.EncryptStart}),{handles:l,inputProof:u}=await this.relayer.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:t.O.EncryptEnd,durationMs:Date.now()-d}),A(()=>o?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.O.EncryptError,error:t.J(n),durationMs:Date.now()-d}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(l.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.y(this.address,c,l[0],u));return this.emit({type:t.O.TransferSubmitted,txHash:e}),A(()=>o?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`transfer`,error:t.J(n)}),n instanceof e.a?n:new s(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,i,o,c){let l=(0,a.getAddress)(n),u=(0,a.getAddress)(i),d,f,p=Date.now();try{this.emit({type:t.O.EncryptStart}),{handles:d,inputProof:f}=await this.relayer.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.O.EncryptEnd,durationMs:Date.now()-p}),A(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.O.EncryptError,error:t.J(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.b(this.address,l,u,d[0],f));return this.emit({type:t.O.TransferFromSubmitted,txHash:e}),A(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`transferFrom`,error:t.J(n)}),n instanceof e.a?n:new s(`TransferFrom transaction failed`,{cause:n})}}async approve(n,i){let s=(0,a.getAddress)(n);try{let e=await this.signer.writeContract(r.E(this.address,s,i));return this.emit({type:t.O.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`approve`,error:t.J(n)}),n instanceof e.a?n:new o(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,a.getAddress)(e),i=t?(0,a.getAddress)(t):await this.signer.getAddress();return this.signer.readContract(r.C(this.address,i,n))}async shield(i,o){if(await this.#n()===n.ZERO_ADDRESS)return this.shieldETH(i,i+(o?.fees??0n));let c=o?.approvalStrategy??`exact`;c!==`skip`&&await this.#a(i,c===`max`,o?.callbacks);try{let e=o?.to?(0,a.getAddress)(o.to):await this.signer.getAddress(),n=await this.signer.writeContract(r.h(this.wrapper,e,i));return this.emit({type:t.O.ShieldSubmitted,txHash:n}),A(()=>o?.callbacks?.onShieldSubmitted?.(n)),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`shield`,error:t.J(n)}),n instanceof e.a?n:new s(`Shield transaction failed`,{cause:n})}}async shieldETH(n,i){try{let e=await this.signer.getAddress(),a=await this.signer.writeContract(r.g(this.wrapper,e,n,i??n));return this.emit({type:t.O.ShieldSubmitted,txHash:a}),{txHash:a,receipt:await this.signer.waitForTransactionReceipt(a)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`shieldETH`,error:t.J(n)}),n instanceof e.a?n:new s(`Shield ETH transaction failed`,{cause:n})}}async unwrap(n){let i=await this.signer.getAddress(),a,o,c=Date.now();try{this.emit({type:t.O.EncryptStart}),{handles:a,inputProof:o}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.O.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.O.EncryptError,error:t.J(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.O(this.address,i,i,a[0],o));return this.emit({type:t.O.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`unwrap`,error:t.J(n)}),n instanceof e.a?n:new s(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(this.isZeroHandle(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.signer.writeContract(r.k(this.address,n,n,i));return this.emit({type:t.O.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`unwrap`,error:t.J(n)}),n instanceof e.a?n:new s(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let n=crypto.randomUUID(),r=await this.unwrap(e);return A(()=>t?.onUnwrapSubmitted?.(r.txHash)),this.#i(r.txHash,t,n)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return A(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#i(n.txHash,e,t)}async resumeUnshield(e,t){return this.#i(e,t,crypto.randomUUID())}async finalizeUnwrap(n){let i,o,c=Date.now();try{this.emit({type:t.O.DecryptStart});let r=await this.relayer.publicDecrypt([n]);this.emit({type:t.O.DecryptEnd,durationMs:Date.now()-c}),o=r.decryptionProof;try{i=(0,a.hexToBigInt)(r.abiEncodedClearValues)}catch{throw new e.r(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`)}}catch(n){throw this.emit({type:t.O.DecryptError,error:t.J(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.r(`Failed to finalize unshield`,{cause:n})}try{let e=await this.signer.writeContract(r.p(this.wrapper,n,i,o));return this.emit({type:t.O.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`finalizeUnwrap`,error:t.J(n)}),n instanceof e.a?n:new s(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.signer.getAddress();await this.signer.readContract(t.B(r,e,this.wrapper))>0n&&await this.signer.writeContract(t.V(r,this.wrapper,0n))}let e=await this.signer.writeContract(t.V(r,this.wrapper,i));return this.emit({type:t.O.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`approveUnderlying`,error:t.J(n)}),n instanceof e.a?n:new o(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.rt(`Expiration date must be at least 1 hour in the future`);let i=(0,a.getAddress)(n),o=await this.signer.getAddress();if(i===(0,a.getAddress)(o))throw new t.ct(`Cannot delegate to yourself (delegate === msg.sender).`);if(i===this.address)throw new t.nt(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.j;if(await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:i})===l)throw new t.at(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(t.M(c,i,this.address,l));return this.emit({type:t.O.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`delegateDecryption`,error:t.J(n)}),n instanceof e.a?n:u(n)||new s(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,a.getAddress)(n),i=await this.signer.getAddress(),o=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:r})===0n)throw new t.ot(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.signer.writeContract(t.F(o,r,this.address));return this.emit({type:t.O.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.O.TransactionError,operation:`revokeDelegation`,error:t.J(n)}),n instanceof e.a?n:u(n)||new s(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new s(r,{cause:n}))}return i}async#i(n,r,i){this.emit({type:t.O.UnshieldPhase1Submitted,txHash:n,operationId:i});let a;try{a=await this.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new s(`Failed to get unshield receipt`,{cause:t})}let o=t.S(a.logs);if(!o)throw new s(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.O.UnshieldPhase2Started,operationId:i}),A(()=>r?.onFinalizing?.());let c=await this.finalizeUnwrap(o.encryptedAmount);return this.emit({type:t.O.UnshieldPhase2Submitted,txHash:c.txHash,operationId:i}),A(()=>r?.onFinalizeSubmitted?.(c.txHash)),c}async#a(n,r,i){let a=await this.#n(),s=await this.signer.getAddress(),c=await this.signer.readContract(t.B(a,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.signer.writeContract(t.V(a,this.wrapper,0n));let e=r?2n**256n-1n:n,o=await this.signer.writeContract(t.V(a,this.wrapper,e));this.emit({type:t.O.ApproveUnderlyingSubmitted,txHash:o}),A(()=>i?.onApprovalSubmitted?.(o))}catch(t){throw t instanceof e.a?t:new o(`ERC-20 approval failed`,{cause:t})}}};function A(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const j={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},M=300*1e3;var N=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},j,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,a.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?M:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.G(e.tokenAddress)),this.signer.readContract(t.K(e.tokenAddress)),this.signer.readContract(t.U(e.tokenAddress)),this.signer.readContract(t.W(e.tokenAddress)),this.signer.readContract(t.G(e.confidentialTokenAddress)),this.signer.readContract(t.K(e.confidentialTokenAddress)),this.signer.readContract(t.U(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,a.getAddress)(e),i=`ct:${t}:${n}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));if(!s)return this.#i(i,null,M);let l=await this.signer.readContract(r.s(t,c));return this.#i(i,{confidentialTokenAddress:c,isValid:l})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,a.getAddress)(e),i=`ut:${t}:${n}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));if(!s)return this.#i(i,null,M);let l=await this.signer.readContract(r.s(t,n));return this.#i(i,{tokenAddress:c,isValid:l})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,a.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,a.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,a.getAddress)(e)))}},P=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new t.k,this.#t=e.onEvent??function(){},this.registry=new N({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0)throw Error(`keypairTTL must be a positive number (seconds)`);return t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new t.D(n),this.delegatedCredentials=new t.E(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.#t?.({type:t.O.TransactionError,operation:e,error:t.J(n),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),this.#i=(0,a.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await t.D.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.w({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:(0,a.getAddress)(e),onEvent:this.#t})}createToken(e,t){return new k({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:(0,a.getAddress)(e),wrapper:t?(0,a.getAddress)(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new N({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(...e){await this.credentials.allow(...e)}async revoke(...e){await this.credentials.revoke(...e)}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),n=this.#a??await this.signer.getChainId(),r=await t.D.computeStoreKey(e,n);await this.credentials.revokeByKey(r)}async isAllowed(){return this.credentials.isAllowed()}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function F(e){return`zama:pending-unshield:${e}`}async function I(e,t,n){await e.set(F(t),n)}async function L(e,t){return e.get(F(t))}async function R(e,t){await e.delete(F(t))}var z=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const B=new z;exports.ACL_TOPICS=t.a,exports.AclPausedError=t.$,exports.AclTopics=t.o,exports.ApprovalFailedError=o,exports.ChromeSessionStorage=z,exports.ConfigurationError=e.t,exports.CredentialsManager=t.D,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=j,exports.DelegatedCredentialsManager=t.E,exports.DelegationContractIsSelfError=t.et,exports.DelegationCooldownError=t.tt,exports.DelegationDelegateEqualsContractError=t.nt,exports.DelegationExpirationTooSoonError=t.rt,exports.DelegationExpiredError=t.it,exports.DelegationExpiryUnchangedError=t.at,exports.DelegationNotFoundError=t.ot,exports.DelegationNotPropagatedError=t.st,exports.DelegationSelfNotAllowedError=t.ct,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=d,exports.InvalidKeypairError=t.lt,exports.KeypairExpiredError=t.ut,exports.MainnetConfig=n.o,exports.MemoryStorage=t.k,exports.NoCiphertextError=t.dt,exports.ReadonlyToken=t.w,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=O,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.ft,exports.SigningRejectedError=t.pt,exports.TOKEN_TOPICS=t.s,exports.Token=k,exports.Topics=t.c,exports.TransactionRevertedError=s,exports.WrappersRegistry=N,exports.ZERO_HANDLE=t.T,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=P,exports.ZamaSDKEvents=t.O,exports.allowanceContract=t.B,exports.applyDecryptedValues=t.t,exports.approveContract=t.V,exports.balanceOfContract=t.H,exports.chromeSessionStorage=B,exports.clearPendingUnshield=R,exports.confidentialBalanceOfContract=r._,exports.confidentialBatchTransferContract=i.t,exports.confidentialTotalSupplyContract=r.v,exports.confidentialTransferContract=r.y,exports.confidentialTransferFromContract=r.b,exports.decimalsContract=t.U,exports.decodeAclEvent=t.l,exports.decodeAclEvents=t.u,exports.decodeConfidentialTransfer=t.d,exports.decodeDelegatedForUserDecryption=t.f,exports.decodeOnChainEvent=t.p,exports.decodeOnChainEvents=t.m,exports.decodeRevokedDelegationForUserDecryption=t.h,exports.decodeUnwrapRequested=t.g,exports.decodeUnwrappedFinalized=t._,exports.decodeUnwrappedStarted=t.v,exports.decodeWrapped=t.y,exports.delegateForUserDecryptionContract=t.M,exports.deploymentCoordinatorContract=r.x,exports.extractEncryptedHandles=t.n,exports.finalizeUnwrapContract=r.p,exports.findDelegatedForUserDecryption=t.b,exports.findRevokedDelegationForUserDecryption=t.x,exports.findUnwrapRequested=t.S,exports.findWrapped=t.C,exports.getBatchTransferFeeContract=t.I,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.N,exports.getFeeRecipientContract=t.L,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.getUnwrapFeeContract=t.R,exports.getWrapFeeContract=t.z,exports.getWrapperContract=i.n,exports.indexedDBStorage=f,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isFinalizeUnwrapOperatorContract=r.S,exports.isHandleDelegatedContract=t.P,exports.isOperatorContract=r.C,exports.loadPendingUnshield=L,exports.matchAclRevert=u,exports.matchZamaError=e.s,exports.memoryStorage=t.A,exports.nameContract=t.G,exports.parseActivityFeed=t.r,exports.rateContract=r.w,exports.revokeDelegationContract=t.F,exports.savePendingUnshield=I,exports.setFinalizeUnwrapOperatorContract=r.T,exports.setOperatorContract=r.E,exports.sortByBlockNumber=t.i,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.K,exports.totalSupplyContract=r.D,exports.underlyingContract=r.m,exports.unwrapContract=r.O,exports.unwrapFromBalanceContract=r.k,exports.wrapContract=r.h,exports.wrapETHContract=r.g,exports.wrapperExistsContract=i.r;
|
|
514
|
+
`],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};const S=8192,C=300*1e3;function w(e){let t=[];for(let n=0;n<e.length;n+=S)t.push(String.fromCharCode(...e.subarray(n,n+S)));return btoa(t.join(``))}function T(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function E(e){return`fhe:pubkey:${e}`}function D(e,t){return`fhe:params:${e}:${t}`}function O(e){return`fhe:params-index:${e}`}function k(e){t.Q(e,`CachedPublicKey`),t.$(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.$(e,`publicKey`,`CachedPublicKey.publicKey`)}function A(e){t.Q(e,`CachedPublicParams`),t.$(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.$(e,`publicParams`,`CachedPublicParams.publicParams`)}var j=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let n=E(this.#t);try{let e=await this.#e.get(n);if(e){k(e);let t={publicKeyId:e.publicKeyId,publicKey:T(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.Y(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:w(r.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:t.Y(e).message})}return r}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,n){let r=D(this.#t,e);try{let t=await this.#e.get(r);if(t){A(t);let n={publicParamsId:t.publicParamsId,publicParams:T(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.Y(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:w(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=O(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.Y(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.Y(n).message})}return i}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let n=E(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{k(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.Y(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+C;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+C;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.Y(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+C;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:t.Y(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=O(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.Y(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=D(this.#t,e),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:t.Y(n).message}),null}if(!r)return null;try{return A(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.Y(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.Y(n).message})})}async#_(e,n){let r=O(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:t.Y(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,n,r){let i=[this.#e.set(e,n).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:t.Y(e).message})}),...r.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:t.Y(e).message})}))];await Promise.all(i)}},M=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new h(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new j({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new x(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,r,i=7){let a=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:r,durationDays:i}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:n.c(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.l(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.l(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},N=class n extends t.w{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?(0,a.getAddress)(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(r.m(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,i,o){let{skipBalanceCheck:c=!1,onEncryptComplete:l,onTransferSubmitted:u}=o??{},d=(0,a.getAddress)(n);c||await this.#i(i);let f,p,m=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:f,inputProof:p}=await this.relayer.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-m}),P(()=>l?.())}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-m}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(f.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.y(this.address,d,f[0],p));return this.emit({type:t.k.TransferSubmitted,txHash:e}),P(()=>u?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`transfer`,error:t.Y(n)}),n instanceof e.a?n:new s(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,i,o,c){let l=(0,a.getAddress)(n),u=(0,a.getAddress)(i),d,f,p=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:d,inputProof:f}=await this.relayer.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-p}),P(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.b(this.address,l,u,d[0],f));return this.emit({type:t.k.TransferFromSubmitted,txHash:e}),P(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`transferFrom`,error:t.Y(n)}),n instanceof e.a?n:new s(`TransferFrom transaction failed`,{cause:n})}}async approve(n,i){let s=(0,a.getAddress)(n);try{let e=await this.signer.writeContract(r.E(this.address,s,i));return this.emit({type:t.k.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`approve`,error:t.Y(n)}),n instanceof e.a?n:new o(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,a.getAddress)(e),i=t?(0,a.getAddress)(t):await this.signer.getAddress();return this.signer.readContract(r.C(this.address,i,n))}async shield(i,o){let c=await this.#n();if(c===n.ZERO_ADDRESS)return this.shieldETH(i,i+(o?.fees??0n));let u;try{let e=await this.signer.getAddress();u=await this.signer.readContract(t.U(c,e))}catch(n){throw n instanceof e.a?n:new d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:t.Y(n)})}if(u<i)throw new l(`Insufficient ERC-20 balance: requested ${i}, available ${u} (token: ${c})`,{requested:i,available:u,token:c});let f=o?.approvalStrategy??`exact`;f!==`skip`&&await this.#o(i,f===`max`,o);try{let e=o?.to?(0,a.getAddress)(o.to):await this.signer.getAddress(),n=await this.signer.writeContract(r.h(this.wrapper,e,i));return this.emit({type:t.k.ShieldSubmitted,txHash:n}),P(()=>o?.onShieldSubmitted?.(n)),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`shield`,error:t.Y(n)}),n instanceof e.a?n:new s(`Shield transaction failed`,{cause:n})}}async shieldETH(n,i){try{let e=await this.signer.getAddress(),a=await this.signer.writeContract(r.g(this.wrapper,e,n,i??n));return this.emit({type:t.k.ShieldSubmitted,txHash:a}),{txHash:a,receipt:await this.signer.waitForTransactionReceipt(a)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`shieldETH`,error:t.Y(n)}),n instanceof e.a?n:new s(`Shield ETH transaction failed`,{cause:n})}}async unwrap(n){let i=await this.signer.getAddress(),a,o,c=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:a,inputProof:o}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.O(this.address,i,i,a[0],o));return this.emit({type:t.k.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`unwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(this.isZeroHandle(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.signer.writeContract(r.k(this.address,n,n,i));return this.emit({type:t.k.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`unwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return P(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return P(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let i,o,c=Date.now();try{this.emit({type:t.k.DecryptStart});let r=await this.relayer.publicDecrypt([n]);this.emit({type:t.k.DecryptEnd,durationMs:Date.now()-c}),o=r.decryptionProof;try{i=(0,a.hexToBigInt)(r.abiEncodedClearValues)}catch(t){throw new e.r(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:t})}}catch(n){throw this.emit({type:t.k.DecryptError,error:t.Y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.r(`Failed to finalize unshield`,{cause:n})}try{let e=await this.signer.writeContract(r.p(this.wrapper,n,i,o));return this.emit({type:t.k.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`finalizeUnwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.signer.getAddress();await this.signer.readContract(t.V(r,e,this.wrapper))>0n&&await this.signer.writeContract(t.H(r,this.wrapper,0n))}let e=await this.signer.writeContract(t.H(r,this.wrapper,i));return this.emit({type:t.k.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`approveUnderlying`,error:t.Y(n)}),n instanceof e.a?n:new o(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.it(`Expiration date must be at least 1 hour in the future`);let i=(0,a.getAddress)(n),o=await this.signer.getAddress();if(i===(0,a.getAddress)(o))throw new t.lt(`Cannot delegate to yourself (delegate === msg.sender).`);if(i===this.address)throw new t.rt(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.M;if(await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:i})===l)throw new t.ot(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(t.N(c,i,this.address,l));return this.emit({type:t.k.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`delegateDecryption`,error:t.Y(n)}),n instanceof e.a?n:m(n)||new s(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,a.getAddress)(n),i=await this.signer.getAddress(),o=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:r})===0n)throw new t.st(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.signer.writeContract(t.I(o,r,this.address));return this.emit({type:t.k.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`revokeDelegation`,error:t.Y(n)}),n instanceof e.a?n:m(n)||new s(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new s(r,{cause:n}))}return i}async#i(n){if(n===0n)return;let r,i;try{r=await this.signer.getAddress(),i=await this.readConfidentialBalanceOf(r)}catch(n){throw n instanceof e.a?n:new u(`Could not read confidential balance handle (token: ${this.address})`,{cause:t.Y(n)})}if(this.isZeroHandle(i))throw new c(`Insufficient confidential balance: requested ${n}, available 0 (token: ${this.address})`,{requested:n,available:0n,token:this.address});let a=await t.E({storage:this.storage,tokenAddress:this.address,owner:r,handle:i});if(a!==null){if(a<n)throw new c(`Insufficient confidential balance: requested ${n}, available ${a} (token: ${this.address})`,{requested:n,available:a,token:this.address});return}let o;try{o=await this.isAllowed()}catch(t){throw t instanceof e.a?t:new u(`Could not check credential status for balance validation (token: ${this.address})`,{cause:t})}if(!o)throw new u(`Cannot validate confidential balance: no cached credentials. Call allow() first or use skipBalanceCheck: true for smart wallets (token: ${this.address})`);let s;try{s=await this.decryptBalance(i,r)}catch(t){throw t instanceof e.a?t:new u(`Balance validation failed: could not decrypt confidential balance (token: ${this.address})`,{cause:t})}if(s<n)throw new c(`Insufficient confidential balance: requested ${n}, available ${s} (token: ${this.address})`,{requested:n,available:s,token:this.address})}async#a(n,r,i){this.emit({type:t.k.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new s(`Failed to get unshield receipt`,{cause:t})}let o=t.S(a.logs);if(!o)throw new s(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.k.UnshieldPhase2Started,operationId:r}),P(()=>i?.onFinalizing?.());let c=await this.finalizeUnwrap(o.encryptedAmount);return this.emit({type:t.k.UnshieldPhase2Submitted,txHash:c.txHash,operationId:r}),P(()=>i?.onFinalizeSubmitted?.(c.txHash)),c}async#o(n,r,i){let a=await this.#n(),s=await this.signer.getAddress(),c=await this.signer.readContract(t.V(a,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.signer.writeContract(t.H(a,this.wrapper,0n));let e=r?2n**256n-1n:n,o=await this.signer.writeContract(t.H(a,this.wrapper,e));this.emit({type:t.k.ApproveUnderlyingSubmitted,txHash:o}),P(()=>i?.onApprovalSubmitted?.(o))}catch(t){throw t instanceof e.a?t:new o(`ERC-20 approval failed`,{cause:t})}}};function P(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const F={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},I=300*1e3;var L=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},F,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,a.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?I:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.K(e.tokenAddress)),this.signer.readContract(t.q(e.tokenAddress)),this.signer.readContract(t.W(e.tokenAddress)),this.signer.readContract(t.G(e.tokenAddress)),this.signer.readContract(t.K(e.confidentialTokenAddress)),this.signer.readContract(t.q(e.confidentialTokenAddress)),this.signer.readContract(t.W(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,a.getAddress)(e),i=`ct:${t}:${n}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));if(!s)return this.#i(i,null,I);let l=await this.signer.readContract(r.s(t,c));return this.#i(i,{confidentialTokenAddress:c,isValid:l})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,a.getAddress)(e),i=`ut:${t}:${n}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));if(!s)return this.#i(i,null,I);let l=await this.signer.readContract(r.s(t,n));return this.#i(i,{tokenAddress:c,isValid:l})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,a.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,a.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,a.getAddress)(e)))}},R=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new t.A,this.#t=e.onEvent??function(){},this.registry=new L({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0)throw Error(`keypairTTL must be a positive number (seconds)`);return t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new t.O(n),this.delegatedCredentials=new t.D(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.#t?.({type:t.k.TransactionError,operation:e,error:t.Y(n),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),this.#i=(0,a.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await t.O.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.w({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:(0,a.getAddress)(e),onEvent:this.#t})}createToken(e,t){return new N({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:(0,a.getAddress)(e),wrapper:t?(0,a.getAddress)(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new L({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(...e){await this.credentials.allow(...e)}async revoke(...e){await this.credentials.revoke(...e)}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),n=this.#a??await this.signer.getChainId(),r=await t.O.computeStoreKey(e,n);await this.credentials.revokeByKey(r)}async isAllowed(){return this.credentials.isAllowed()}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function z(e){return`zama:pending-unshield:${e}`}async function B(e,t,n){await e.set(z(t),n)}async function V(e,t){return e.get(z(t))}async function H(e,t){await e.delete(z(t))}var U=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const W=new U;exports.ACL_TOPICS=t.a,exports.AclPausedError=t.et,exports.AclTopics=t.o,exports.ApprovalFailedError=o,exports.BalanceCheckUnavailableError=u,exports.ChromeSessionStorage=U,exports.ConfigurationError=e.t,exports.CredentialsManager=t.O,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=F,exports.DelegatedCredentialsManager=t.D,exports.DelegationContractIsSelfError=t.tt,exports.DelegationCooldownError=t.nt,exports.DelegationDelegateEqualsContractError=t.rt,exports.DelegationExpirationTooSoonError=t.it,exports.DelegationExpiredError=t.at,exports.DelegationExpiryUnchangedError=t.ot,exports.DelegationNotFoundError=t.st,exports.DelegationNotPropagatedError=t.ct,exports.DelegationSelfNotAllowedError=t.lt,exports.ERC20ReadFailedError=d,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=h,exports.InsufficientConfidentialBalanceError=c,exports.InsufficientERC20BalanceError=l,exports.InvalidKeypairError=t.ut,exports.KeypairExpiredError=t.dt,exports.MainnetConfig=n.o,exports.MemoryStorage=t.A,exports.NoCiphertextError=t.ft,exports.ReadonlyToken=t.w,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=M,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.pt,exports.SigningRejectedError=t.mt,exports.TOKEN_TOPICS=t.s,exports.Token=N,exports.Topics=t.c,exports.TransactionRevertedError=s,exports.WrappersRegistry=L,exports.ZERO_HANDLE=t.T,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=R,exports.ZamaSDKEvents=t.k,exports.allowanceContract=t.V,exports.applyDecryptedValues=t.t,exports.approveContract=t.H,exports.balanceOfContract=t.U,exports.chromeSessionStorage=W,exports.clearPendingUnshield=H,exports.confidentialBalanceOfContract=r._,exports.confidentialBatchTransferContract=i.t,exports.confidentialTotalSupplyContract=r.v,exports.confidentialTransferContract=r.y,exports.confidentialTransferFromContract=r.b,exports.decimalsContract=t.W,exports.decodeAclEvent=t.l,exports.decodeAclEvents=t.u,exports.decodeConfidentialTransfer=t.d,exports.decodeDelegatedForUserDecryption=t.f,exports.decodeOnChainEvent=t.p,exports.decodeOnChainEvents=t.m,exports.decodeRevokedDelegationForUserDecryption=t.h,exports.decodeUnwrapRequested=t.g,exports.decodeUnwrappedFinalized=t._,exports.decodeUnwrappedStarted=t.v,exports.decodeWrapped=t.y,exports.delegateForUserDecryptionContract=t.N,exports.deploymentCoordinatorContract=r.x,exports.extractEncryptedHandles=t.n,exports.finalizeUnwrapContract=r.p,exports.findDelegatedForUserDecryption=t.b,exports.findRevokedDelegationForUserDecryption=t.x,exports.findUnwrapRequested=t.S,exports.findWrapped=t.C,exports.getBatchTransferFeeContract=t.L,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.P,exports.getFeeRecipientContract=t.R,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.getUnwrapFeeContract=t.z,exports.getWrapFeeContract=t.B,exports.getWrapperContract=i.n,exports.indexedDBStorage=g,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isFinalizeUnwrapOperatorContract=r.S,exports.isHandleDelegatedContract=t.F,exports.isOperatorContract=r.C,exports.loadPendingUnshield=V,exports.matchAclRevert=m,exports.matchZamaError=e.s,exports.memoryStorage=t.j,exports.nameContract=t.K,exports.parseActivityFeed=t.r,exports.rateContract=r.w,exports.revokeDelegationContract=t.I,exports.savePendingUnshield=B,exports.setFinalizeUnwrapOperatorContract=r.T,exports.setOperatorContract=r.E,exports.sortByBlockNumber=t.i,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.q,exports.totalSupplyContract=r.D,exports.underlyingContract=r.m,exports.unwrapContract=r.O,exports.unwrapFromBalanceContract=r.k,exports.wrapContract=r.h,exports.wrapETHContract=r.g,exports.wrapperExistsContract=i.r;
|
|
515
515
|
//# sourceMappingURL=index.cjs.map
|