@zama-fhe/sdk 2.3.0-alpha.4 → 2.3.0
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/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,i as t,n,r,t as i}from"./relayer-
|
|
1
|
+
import{a as e,i as t,n,r,t as i}from"./relayer-C6u3eOlN.js";import{$ as a,A as o,B as s,C as c,D as l,E as u,F as d,G as f,H as p,I as ee,J as m,K as te,L as ne,M as re,N as ie,O as h,P as g,Q as _,R as ae,S as v,T as oe,U as se,V as ce,W as y,X as b,Y as x,Z as le,_ as ue,a as de,at as fe,b as pe,c as me,d as he,et as ge,f as _e,g as ve,h as ye,i as be,it as xe,j as Se,k as S,l as Ce,m as we,n as Te,nt as Ee,o as De,ot as Oe,p as ke,q as C,r as Ae,rt as je,s as Me,t as Ne,tt as w,u as Pe,v as Fe,w as T,x as Ie,y as Le,z as E}from"./activity-b2RsqKHW.js";import{n as D,t as O}from"./encryption-CmIPBcfP.js";import{n as Re,t as ze}from"./fhe-artifact-cache-CyXna-Br.js";import{a as k,r as Be,s as Ve}from"./assertions-Dty7Quc0.js";import{i as A,n as He,t as Ue}from"./memory-storage-B4_heQa5.js";import{a as We,i as j,n as Ge,o as M,r as N,t as P}from"./relayer-utils-BeoTNDM4.js";import{C as Ke,D as qe,E as Je,O as Ye,S as Xe,T as Ze,_ as Qe,a as F,b as $e,c as et,d as tt,f as nt,g as rt,h as it,i as at,k as ot,l as st,m as ct,n as I,o as L,p as lt,r as ut,s as R,t as z,u as dt,v as ft,w as pt,x as mt,y as ht}from"./wrappers-registry-DqPr_JG2.js";import{n as gt,r as _t,t as vt}from"./transfer-batcher-BXIo7hnu.js";import{n as yt}from"./cleartext-Bzxet3H7.js";import{getAddress as B,hexToBigInt as bt}from"viem";var V=class extends r{constructor(e,n){super(t.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},H=class extends r{constructor(e,n){super(t.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},U=class extends r{requested;available;token;constructor(e,n,r){super(t.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},W=class extends r{requested;available;token;constructor(e,n,r){super(t.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},G=class extends r{constructor(e,n){super(t.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},xt=class extends r{constructor(e,n){super(t.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function St(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 K={AlreadyDelegatedOrRevokedInSameBlock:e=>new m(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new C(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new te(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new w(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new b(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new _(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new a(`Cannot revoke: no active delegation exists.`,{cause:e})};function q(e){let t=e instanceof Error?e:void 0,n=St(e);if(n&&n in K)return K[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(K))if(r.includes(e))return n(t);return null}var J=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 Ct=new J;function wt(e){try{return k(e,`runtime`),Ve(e,`id`,`runtime.id`),Be(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function Tt(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(k(t,`ns`),wt(t.runtime))return t.runtime}catch{continue}}var Et=class extends Re{constructor(e){super(e,e.logger)}createWorker(){let e=Tt();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 @@ import{a as e,i as t,n,r,t as i}from"./relayer-DfjPWTBf.js";import{$ as a,A as o
|
|
|
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})}},xt=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:n,threads:r}=this.#l;if(r!==void 0&&(!Number.isInteger(r)||r<1))throw Error(`Invalid thread count: ${r}. Must be a positive integer.`);return r!==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({},F[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:r}}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 e=await this.#l.getChainId();if(this.#i!==null&&e!==this.#i&&this.#p(),this.#i=e,this.#o||=this.#l.fheArtifactStorage??new Y(`FheArtifactCache`,1,`artifacts`),!this.#a){let t=Object.assign({},F[e],this.#l.transports[e]);this.#a=new Ie({storage:this.#o,chainId:e,relayerUrl:t.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(e=>{this.#t=null;let t=e instanceof r?e:new i(`Failed to initialize FHE worker`,{cause:e});throw this.#u(`error`,t),t})),this.#t}async#h(){let e=new bt(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,n,r=7){let i=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r}),a={name:i.domain.name,version:i.domain.version,chainId:i.domain.chainId,verifyingContract:i.domain.verifyingContract};return{domain:a,types:{EIP712Domain:He(a),UserDecryptRequestVerification:i.types.UserDecryptRequestVerification},message:{publicKey:i.message.publicKey,contractAddresses:i.message.contractAddresses,startTimestamp:i.message.startTimestamp,durationDays:i.message.durationDays,extraData:i.message.extraData}}}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;return N(async()=>{let e=await this.#f();await this.#g();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return N(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return N(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(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return N(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 e=await this.#l.getChainId(),t=Object.assign({},F[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},St=class e extends D{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?W(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(R(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(e,t,n){let i=W(e),a,o,s=Date.now();try{this.emit({type:g.EncryptStart}),{handles:a,inputProof:o}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-s}),X(()=>n?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:j(e),durationMs:Date.now()-s}),e instanceof r?e:new k(`Failed to encrypt transfer amount`,{cause:e})}if(a.length===0)throw new k(`Encryption returned no handles`);try{let e=await this.signer.writeContract(ut(this.address,i,a[0],o));return this.emit({type:g.TransferSubmitted,txHash:e}),X(()=>n?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transfer`,error:j(e)}),e instanceof r?e:new K(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=W(e),o=W(t),s,c,l=Date.now();try{this.emit({type:g.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-l}),X(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:j(e),durationMs:Date.now()-l}),e instanceof r?e:new k(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new k(`Encryption returned no handles`);try{let e=await this.signer.writeContract(Ze(this.address,a,o,s[0],c));return this.emit({type:g.TransferFromSubmitted,txHash:e}),X(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transferFrom`,error:j(e)}),e instanceof r?e:new K(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=W(e);try{let e=await this.signer.writeContract(Ke(this.address,n,t));return this.emit({type:g.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`approve`,error:j(e)}),e instanceof r?e:new G(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=W(e),r=t?W(t):await this.signer.getAddress();return this.signer.readContract(We(this.address,r,n))}async shield(t,n){if(await this.#n()===e.ZERO_ADDRESS)return this.shieldETH(t,t+(n?.fees??0n));let i=n?.approvalStrategy??`exact`;i!==`skip`&&await this.#a(t,i===`max`,n?.callbacks);try{let e=n?.to?W(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(nt(this.wrapper,e,t));return this.emit({type:g.ShieldSubmitted,txHash:r}),X(()=>n?.callbacks?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`shield`,error:j(e)}),e instanceof r?e:new K(`Shield transaction failed`,{cause:e})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(tt(this.wrapper,n,e,t??e));return this.emit({type:g.ShieldSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`shieldETH`,error:j(e)}),e instanceof r?e:new K(`Shield ETH transaction failed`,{cause:e})}}async unwrap(e){let t=await this.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:g.EncryptStart}),{handles:n,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:g.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:g.EncryptError,error:j(e),durationMs:Date.now()-a}),e instanceof r?e:new k(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new k(`Encryption returned no handles`);try{let e=await this.signer.writeContract(qe(this.address,t,t,n[0],i));return this.emit({type:g.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`unwrap`,error:j(e)}),e instanceof r?e:new K(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new A(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(L(this.address,e,e,t));return this.emit({type:g.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:g.TransactionError,operation:`unwrap`,error:j(e)}),e instanceof r?e:new K(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let n=crypto.randomUUID(),r=await this.unwrap(e);return X(()=>t?.onUnwrapSubmitted?.(r.txHash)),this.#i(r.txHash,t,n)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return X(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#i(n.txHash,e,t)}async resumeUnshield(e,t){return this.#i(e,t,crypto.randomUUID())}async finalizeUnwrap(e){let t,n,i=Date.now();try{this.emit({type:g.DecryptStart});let r=await this.relayer.publicDecrypt([e]);this.emit({type:g.DecryptEnd,durationMs:Date.now()-i}),n=r.decryptionProof;try{t=ht(r.abiEncodedClearValues)}catch{throw new A(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`)}}catch(e){throw this.emit({type:g.DecryptError,error:j(e),durationMs:Date.now()-i}),e instanceof r?e:new A(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(V(this.wrapper,e,t,n));return this.emit({type:g.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`finalizeUnwrap`,error:j(e)}),e instanceof r?e:new K(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){let t=await this.#n(),n=e??2n**256n-1n;try{if(n>0n){let e=await this.signer.getAddress();await this.signer.readContract(v(t,e,this.wrapper))>0n&&await this.signer.writeContract(O(t,this.wrapper,0n))}let e=await this.signer.writeContract(O(t,this.wrapper,n));return this.emit({type:g.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`approveUnderlying`,error:j(e)}),e instanceof r?e:new G(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new C(`Expiration date must be at least 1 hour in the future`);let n=W(e),i=await this.signer.getAddress();if(n===W(i))throw new T(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new m(`Delegate address cannot be the same as the contract address (${this.address}).`);let a=await this.getAclAddress(),s=t?BigInt(Math.floor(t.getTime()/1e3)):ye;if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})===s)throw new w(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(o(a,n,this.address,s));return this.emit({type:g.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`delegateDecryption`,error:j(e)}),e instanceof r?e:J(e)||new K(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=W(e),n=await this.signer.getAddress(),i=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})===0n)throw new _(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await this.signer.writeContract(h(i,t,this.address));return this.emit({type:g.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`revokeDelegation`,error:j(e)}),e instanceof r?e:J(e)||new K(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,t,n){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await t(e[a]))}catch(t){t instanceof r?i.set(e[a].address,t):i.set(e[a].address,new K(n,{cause:t}))}return i}async#i(e,t,n){this.emit({type:g.UnshieldPhase1Submitted,txHash:e,operationId:n});let i;try{i=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new K(`Failed to get unshield receipt`,{cause:e})}let a=y(i.logs);if(!a)throw new K(`No UnwrapRequested event found in unshield receipt`);this.emit({type:g.UnshieldPhase2Started,operationId:n}),X(()=>t?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:g.UnshieldPhase2Submitted,txHash:o.txHash,operationId:n}),X(()=>t?.onFinalizeSubmitted?.(o.txHash)),o}async#a(e,t,n){let i=await this.#n(),a=await this.signer.getAddress(),o=await this.signer.readContract(v(i,a,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(O(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.signer.writeContract(O(i,this.wrapper,r));this.emit({type:g.ApproveUnderlyingSubmitted,txHash:a}),X(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new G(`ERC-20 approval failed`,{cause:e})}}};function X(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Ct={[P.chainId]:P.registryAddress,[M.chainId]:M.registryAddress,[mt.chainId]:mt.registryAddress},Z=300*1e3;var Q=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},Ct,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 e=await this.signer.getChainId(),t=this.#e[e];if(!t)throw new i(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return W(t)}async listPairs(e={}){let t=e.page??1,n=e.pageSize??100,r=e.metadata??!1;if(t<1)throw new i(`page must be >= 1, got ${t}`);if(n<1)throw new i(`pageSize must be >= 1, got ${n}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.signer.readContract(I(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*n),l=c+BigInt(n)>BigInt(s)?BigInt(s):c+BigInt(n);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:n};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.signer.readContract(B(a,c,l));d=this.#i(u,[...e])}if(!r)return{items:d,total:s,page:t,pageSize:n};let f=`metadata:${a}:${c}:${l}`,p=this.#r(f);if(p===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));p=this.#i(f,n,t?Z:void 0)}return{items:p,total:s,page:t,pageSize:n}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.signer.readContract(b(e.tokenAddress)),this.signer.readContract(S(e.tokenAddress)),this.signer.readContract(x(e.tokenAddress)),this.signer.readContract(p(e.tokenAddress)),this.signer.readContract(b(e.confidentialTokenAddress)),this.signer.readContract(S(e.confidentialTokenAddress)),this.signer.readContract(x(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:s}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=W(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(U(t,n));if(!a)return this.#i(r,null,Z);let s=await this.signer.readContract(H(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=W(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(z(t,n));if(!a)return this.#i(r,null,Z);let s=await this.signer.readContract(H(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(rt(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(I(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(B(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(at(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(U(t,W(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(z(t,W(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(H(t,W(e)))}},wt=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 Ve,this.#t=e.onEvent??function(){},this.registry=new Q({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let t={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 l(t),this.delegatedCredentials=new u(t),this.#r=this.#o(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#t?.({type:g.TransactionError,operation:e,error:j(t),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),this.#i=W(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}t?.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 l.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new D({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:W(e),onEvent:this.#t})}createToken(e,t){return new St({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:W(e),wrapper:t?W(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new Q({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(),t=this.#a??await this.signer.getChainId(),n=await l.computeStoreKey(e,t);await this.credentials.revokeByKey(n)}async isAllowed(){return this.credentials.isAllowed()}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${e}`}async function Tt(e,t,n){await e.set($(t),n)}async function Et(e,t){return e.get($(t))}async function Dt(e,t){await e.delete($(t))}var Ot=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 kt=new Ot;export{ce as ACL_TOPICS,f as AclPausedError,we as AclTopics,G as ApprovalFailedError,Ot as ChromeSessionStorage,i as ConfigurationError,l as CredentialsManager,A as DecryptionFailedError,Ct as DefaultRegistryAddresses,u as DelegatedCredentialsManager,te as DelegationContractIsSelfError,E as DelegationCooldownError,m as DelegationDelegateEqualsContractError,C as DelegationExpirationTooSoonError,oe as DelegationExpiredError,w as DelegationExpiryUnchangedError,_ as DelegationNotFoundError,a as DelegationNotPropagatedError,T as DelegationSelfNotAllowedError,Qe as ERC7984_INTERFACE_ID,it as ERC7984_WRAPPER_INTERFACE_ID,k as EncryptionFailedError,Ue as HardhatConfig,Y as IndexedDBStorage,Ae as InvalidKeypairError,Ce as KeypairExpiredError,P as MainnetConfig,Ve as MemoryStorage,De as NoCiphertextError,D as ReadonlyToken,n as RelayerRequestFailedError,xt as RelayerWeb,M as SepoliaConfig,_e as SigningFailedError,le as SigningRejectedError,Oe as TOKEN_TOPICS,St as Token,de as Topics,K as TransactionRevertedError,Q as WrappersRegistry,ae as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,wt as ZamaSDK,g as ZamaSDKEvents,v as allowanceContract,ke as applyDecryptedValues,O as approveContract,s as balanceOfContract,kt as chromeSessionStorage,Dt as clearPendingUnshield,Xe as confidentialBalanceOfContract,pt as confidentialBatchTransferContract,st as confidentialTotalSupplyContract,ut as confidentialTransferContract,Ze as confidentialTransferFromContract,x as decimalsContract,be as decodeAclEvent,je as decodeAclEvents,fe as decodeConfidentialTransfer,pe as decodeDelegatedForUserDecryption,Te as decodeOnChainEvent,xe as decodeOnChainEvents,he as decodeRevokedDelegationForUserDecryption,me as decodeUnwrapRequested,se as decodeUnwrappedFinalized,Me as decodeUnwrappedStarted,Pe as decodeWrapped,o as delegateForUserDecryptionContract,lt as deploymentCoordinatorContract,Se as extractEncryptedHandles,V as finalizeUnwrapContract,ue as findDelegatedForUserDecryption,Ne as findRevokedDelegationForUserDecryption,y as findUnwrapRequested,c as findWrapped,ie as getBatchTransferFeeContract,U as getConfidentialTokenAddressContract,ve as getDelegationExpiryContract,d as getFeeRecipientContract,z as getTokenAddressContract,at as getTokenPairContract,rt as getTokenPairsContract,I as getTokenPairsLengthContract,B as getTokenPairsSliceContract,ee as getUnwrapFeeContract,ne as getWrapFeeContract,dt as getWrapperContract,_t as indexedDBStorage,ot as isConfidentialTokenContract,H as isConfidentialTokenValidContract,$e as isConfidentialWrapperContract,Je as isFinalizeUnwrapOperatorContract,re as isHandleDelegatedContract,We as isOperatorContract,Et as loadPendingUnshield,J as matchAclRevert,e as matchZamaError,Be as memoryStorage,b as nameContract,Ee as parseActivityFeed,ct as rateContract,h as revokeDelegationContract,Tt as savePendingUnshield,Ye as setFinalizeUnwrapOperatorContract,Ke as setOperatorContract,ge as sortByBlockNumber,et as supportsInterfaceContract,S as symbolContract,Ge as totalSupplyContract,R as underlyingContract,qe as unwrapContract,L as unwrapFromBalanceContract,nt as wrapContract,tt as wrapETHContract,ft as wrapperExistsContract};
|
|
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})}},Dt=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:n,threads:r}=this.#l;if(r!==void 0&&(!Number.isInteger(r)||r<1))throw Error(`Invalid thread count: ${r}. Must be a positive integer.`);return r!==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({},P[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:r}}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 e=await this.#l.getChainId();if(this.#i!==null&&e!==this.#i&&this.#p(),this.#i=e,this.#o||=this.#l.fheArtifactStorage??new J(`FheArtifactCache`,1,`artifacts`),!this.#a){let t=Object.assign({},P[e],this.#l.transports[e]);this.#a=new ze({storage:this.#o,chainId:e,relayerUrl:t.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(e=>{this.#t=null;let t=e instanceof r?e:new i(`Failed to initialize FHE worker`,{cause:e});throw this.#u(`error`,t),t})),this.#t}async#h(){let e=new Et(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,n,r=7){let i=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r}),a={name:i.domain.name,version:i.domain.version,chainId:i.domain.chainId,verifyingContract:i.domain.verifyingContract};return{domain:a,types:{EIP712Domain:We(a),UserDecryptRequestVerification:i.types.UserDecryptRequestVerification},message:{publicKey:i.message.publicKey,contractAddresses:i.message.contractAddresses,startTimestamp:i.message.startTimestamp,durationDays:i.message.durationDays,extraData:i.message.extraData}}}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;return M(async()=>{let e=await this.#f();await this.#g();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return M(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return M(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 M(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return M(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 e=await this.#l.getChainId(),t=Object.assign({},P[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},Ot=class e extends T{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?B(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(ct(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(e,t,n){let{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=B(e);i||await this.#i(t);let c,l,u=Date.now();try{this.emit({type:S.EncryptStart}),{handles:c,inputProof:l}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-u}),Y(()=>a?.())}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-u}),e instanceof r?e:new D(`Failed to encrypt transfer amount`,{cause:e})}if(c.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract(ht(this.address,s,c[0],l));return this.emit({type:S.TransferSubmitted,txHash:e}),Y(()=>o?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`transfer`,error:A(e)}),e instanceof r?e:new H(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=B(e),o=B(t),s,c,l=Date.now();try{this.emit({type:S.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:a}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-l}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-l}),e instanceof r?e:new D(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract($e(this.address,a,o,s[0],c));return this.emit({type:S.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`transferFrom`,error:A(e)}),e instanceof r?e:new H(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=B(e);try{let e=await this.signer.writeContract(Je(this.address,n,t));return this.emit({type:S.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`approve`,error:A(e)}),e instanceof r?e:new V(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=B(e),r=t?B(t):await this.signer.getAddress();return this.signer.readContract(Ke(this.address,r,n))}async shield(t,n){let i=await this.#n();if(i===e.ZERO_ADDRESS)return this.shieldETH(t,t+(n?.fees??0n));let a;try{let e=await this.signer.getAddress();a=await this.signer.readContract(ce(i,e))}catch(e){throw e instanceof r?e:new xt(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:A(e)})}if(a<t)throw new W(`Insufficient ERC-20 balance: requested ${t}, available ${a} (token: ${i})`,{requested:t,available:a,token:i});let o=n?.approvalStrategy??`exact`;o!==`skip`&&await this.#o(t,o===`max`,n);try{let e=n?.to?B(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(it(this.wrapper,e,t));return this.emit({type:S.ShieldSubmitted,txHash:r}),Y(()=>n?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`shield`,error:A(e)}),e instanceof r?e:new H(`Shield transaction failed`,{cause:e})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(rt(this.wrapper,n,e,t??e));return this.emit({type:S.ShieldSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`shieldETH`,error:A(e)}),e instanceof r?e:new H(`Shield ETH transaction failed`,{cause:e})}}async unwrap(e){let t=await this.signer.getAddress(),n,i,a=Date.now();try{this.emit({type:S.EncryptStart}),{handles:n,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:S.EncryptEnd,durationMs:Date.now()-a})}catch(e){throw this.emit({type:S.EncryptError,error:A(e),durationMs:Date.now()-a}),e instanceof r?e:new D(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new D(`Encryption returned no handles`);try{let e=await this.signer.writeContract(Ye(this.address,t,t,n[0],i));return this.emit({type:S.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new H(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new O(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(ot(this.address,e,e,t));return this.emit({type:S.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:S.TransactionError,operation:`unwrap`,error:A(e)}),e instanceof r?e:new H(`Unshield-all transaction failed`,{cause:e})}}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 Y(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Y(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(e){let t,n,i=Date.now();try{this.emit({type:S.DecryptStart});let r=await this.relayer.publicDecrypt([e]);this.emit({type:S.DecryptEnd,durationMs:Date.now()-i}),n=r.decryptionProof;try{t=bt(r.abiEncodedClearValues)}catch(e){throw new O(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:e})}}catch(e){throw this.emit({type:S.DecryptError,error:A(e),durationMs:Date.now()-i}),e instanceof r?e:new O(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(lt(this.wrapper,e,t,n));return this.emit({type:S.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:S.TransactionError,operation:`finalizeUnwrap`,error:A(e)}),e instanceof r?e:new H(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){let t=await this.#n(),n=e??2n**256n-1n;try{if(n>0n){let e=await this.signer.getAddress();await this.signer.readContract(E(t,e,this.wrapper))>0n&&await this.signer.writeContract(s(t,this.wrapper,0n))}let e=await this.signer.writeContract(s(t,this.wrapper,n));return this.emit({type:S.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`approveUnderlying`,error:A(e)}),e instanceof r?e:new V(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new b(`Expiration date must be at least 1 hour in the future`);let n=B(e),i=await this.signer.getAddress();if(n===B(i))throw new w(`Cannot delegate to yourself (delegate === msg.sender).`);if(n===this.address)throw new x(`Delegate address cannot be the same as the contract address (${this.address}).`);let a=await this.getAclAddress(),s=t?BigInt(Math.floor(t.getTime()/1e3)):o;if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})===s)throw new _(`The new expiration date (${s}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(Se(a,n,this.address,s));return this.emit({type:S.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`delegateDecryption`,error:A(e)}),e instanceof r?e:q(e)||new H(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=B(e),n=await this.signer.getAddress(),i=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:n,delegateAddress:t})===0n)throw new a(`No active delegation found for delegate ${t} on contract ${this.address}.`);try{let e=await this.signer.writeContract(g(i,t,this.address));return this.emit({type:S.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:S.TransactionError,operation:`revokeDelegation`,error:A(e)}),e instanceof r?e:q(e)||new H(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,t,n){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await t(e[a]))}catch(t){t instanceof r?i.set(e[a].address,t):i.set(e[a].address,new H(n,{cause:t}))}return i}async#i(e){if(e===0n)return;let t,n;try{t=await this.signer.getAddress(),n=await this.readConfidentialBalanceOf(t)}catch(e){throw e instanceof r?e:new G(`Could not read confidential balance handle (token: ${this.address})`,{cause:A(e)})}if(this.isZeroHandle(n))throw new U(`Insufficient confidential balance: requested ${e}, available 0 (token: ${this.address})`,{requested:e,available:0n,token:this.address});let i=await u({storage:this.storage,tokenAddress:this.address,owner:t,handle:n});if(i!==null){if(i<e)throw new U(`Insufficient confidential balance: requested ${e}, available ${i} (token: ${this.address})`,{requested:e,available:i,token:this.address});return}let a;try{a=await this.isAllowed()}catch(e){throw e instanceof r?e:new G(`Could not check credential status for balance validation (token: ${this.address})`,{cause:e})}if(!a)throw new G(`Cannot validate confidential balance: no cached credentials. Call allow() first or use skipBalanceCheck: true for smart wallets (token: ${this.address})`);let o;try{o=await this.decryptBalance(n,t)}catch(e){throw e instanceof r?e:new G(`Balance validation failed: could not decrypt confidential balance (token: ${this.address})`,{cause:e})}if(o<e)throw new U(`Insufficient confidential balance: requested ${e}, available ${o} (token: ${this.address})`,{requested:e,available:o,token:this.address})}async#a(e,t,n){this.emit({type:S.UnshieldPhase1Submitted,txHash:e,operationId:t});let i;try{i=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof r?e:new H(`Failed to get unshield receipt`,{cause:e})}let a=v(i.logs);if(!a)throw new H(`No UnwrapRequested event found in unshield receipt`);this.emit({type:S.UnshieldPhase2Started,operationId:t}),Y(()=>n?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:S.UnshieldPhase2Submitted,txHash:o.txHash,operationId:t}),Y(()=>n?.onFinalizeSubmitted?.(o.txHash)),o}async#o(e,t,n){let i=await this.#n(),a=await this.signer.getAddress(),o=await this.signer.readContract(E(i,a,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(s(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.signer.writeContract(s(i,this.wrapper,r));this.emit({type:S.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new V(`ERC-20 approval failed`,{cause:e})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const kt={[N.chainId]:N.registryAddress,[j.chainId]:j.registryAddress,[yt.chainId]:yt.registryAddress},X=300*1e3;var Z=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},kt,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 e=await this.signer.getChainId(),t=this.#e[e];if(!t)throw new i(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return B(t)}async listPairs(e={}){let t=e.page??1,n=e.pageSize??100,r=e.metadata??!1;if(t<1)throw new i(`page must be >= 1, got ${t}`);if(n<1)throw new i(`pageSize must be >= 1, got ${n}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.signer.readContract(F(a));s=this.#i(o,Number(e))}let c=BigInt((t-1)*n),l=c+BigInt(n)>BigInt(s)?BigInt(s):c+BigInt(n);if(c>=BigInt(s))return{items:[],total:s,page:t,pageSize:n};let u=`slice:${a}:${c}:${l}`,d=this.#r(u);if(d===void 0){let e=await this.signer.readContract(L(a,c,l));d=this.#i(u,[...e])}if(!r)return{items:d,total:s,page:t,pageSize:n};let f=`metadata:${a}:${c}:${l}`,p=this.#r(f);if(p===void 0){let e=await Promise.allSettled(d.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},d[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));p=this.#i(f,n,t?X:void 0)}return{items:p,total:s,page:t,pageSize:n}}async#a(e){let[t,n,r,i,a,o,s]=await Promise.all([this.signer.readContract(y(e.tokenAddress)),this.signer.readContract(f(e.tokenAddress)),this.signer.readContract(p(e.tokenAddress)),this.signer.readContract(se(e.tokenAddress)),this.signer.readContract(y(e.confidentialTokenAddress)),this.signer.readContract(f(e.confidentialTokenAddress)),this.signer.readContract(p(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:n,decimals:r,totalSupply:i},confidential:{name:a,symbol:o,decimals:s}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=B(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(z(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(R(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=B(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(I(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(R(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(at(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(F(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(L(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(ut(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(z(t,B(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(I(t,B(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(R(t,B(e)))}},At=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 Ue,this.#t=e.onEvent??function(){},this.registry=new Z({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let t={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 h(t),this.delegatedCredentials=new l(t),this.#r=this.#o(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#t?.({type:S.TransactionError,operation:e,error:A(t),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#s(),this.#i=B(e);try{this.#a=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#s(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}t?.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 h.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new T({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:B(e),onEvent:this.#t})}createToken(e,t){return new Ot({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:B(e),wrapper:t?B(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new Z({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(),t=this.#a??await this.signer.getChainId(),n=await h.computeStoreKey(e,t);await this.credentials.revokeByKey(n)}async isAllowed(){return this.credentials.isAllowed()}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}async function jt(e,t,n){await e.set(Q(t),n)}async function Mt(e,t){return e.get(Q(t))}async function Nt(e,t){await e.delete(Q(t))}var $=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 Pt=new $;export{de as ACL_TOPICS,te as AclPausedError,De as AclTopics,V as ApprovalFailedError,G as BalanceCheckUnavailableError,$ as ChromeSessionStorage,i as ConfigurationError,h as CredentialsManager,O as DecryptionFailedError,kt as DefaultRegistryAddresses,l as DelegatedCredentialsManager,C as DelegationContractIsSelfError,m as DelegationCooldownError,x as DelegationDelegateEqualsContractError,b as DelegationExpirationTooSoonError,le as DelegationExpiredError,_ as DelegationExpiryUnchangedError,a as DelegationNotFoundError,ge as DelegationNotPropagatedError,w as DelegationSelfNotAllowedError,xt as ERC20ReadFailedError,et as ERC7984_INTERFACE_ID,st as ERC7984_WRAPPER_INTERFACE_ID,D as EncryptionFailedError,Ge as HardhatConfig,J as IndexedDBStorage,U as InsufficientConfidentialBalanceError,W as InsufficientERC20BalanceError,Ee as InvalidKeypairError,je as KeypairExpiredError,N as MainnetConfig,Ue as MemoryStorage,xe as NoCiphertextError,T as ReadonlyToken,n as RelayerRequestFailedError,Dt as RelayerWeb,j as SepoliaConfig,fe as SigningFailedError,Oe as SigningRejectedError,Me as TOKEN_TOPICS,Ot as Token,me as Topics,H as TransactionRevertedError,Z as WrappersRegistry,oe as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,At as ZamaSDK,S as ZamaSDKEvents,E as allowanceContract,Ne as applyDecryptedValues,s as approveContract,ce as balanceOfContract,Pt as chromeSessionStorage,Nt as clearPendingUnshield,Qe as confidentialBalanceOfContract,vt as confidentialBatchTransferContract,ft as confidentialTotalSupplyContract,ht as confidentialTransferContract,$e as confidentialTransferFromContract,p as decimalsContract,Ce as decodeAclEvent,Pe as decodeAclEvents,he as decodeConfidentialTransfer,_e as decodeDelegatedForUserDecryption,ke as decodeOnChainEvent,we as decodeOnChainEvents,ye as decodeRevokedDelegationForUserDecryption,ve as decodeUnwrapRequested,ue as decodeUnwrappedFinalized,Fe as decodeUnwrappedStarted,Le as decodeWrapped,Se as delegateForUserDecryptionContract,mt as deploymentCoordinatorContract,Te as extractEncryptedHandles,lt as finalizeUnwrapContract,pe as findDelegatedForUserDecryption,Ie as findRevokedDelegationForUserDecryption,v as findUnwrapRequested,c as findWrapped,d as getBatchTransferFeeContract,z as getConfidentialTokenAddressContract,re as getDelegationExpiryContract,ee as getFeeRecipientContract,I as getTokenAddressContract,ut as getTokenPairContract,at as getTokenPairsContract,F as getTokenPairsLengthContract,L as getTokenPairsSliceContract,ne as getUnwrapFeeContract,ae as getWrapFeeContract,gt as getWrapperContract,Ct as indexedDBStorage,dt as isConfidentialTokenContract,R as isConfidentialTokenValidContract,tt as isConfidentialWrapperContract,Xe as isFinalizeUnwrapOperatorContract,ie as isHandleDelegatedContract,Ke as isOperatorContract,Mt as loadPendingUnshield,q as matchAclRevert,e as matchZamaError,He as memoryStorage,y as nameContract,Ae as parseActivityFeed,pt as rateContract,g as revokeDelegationContract,jt as savePendingUnshield,Ze as setFinalizeUnwrapOperatorContract,Je as setOperatorContract,be as sortByBlockNumber,nt as supportsInterfaceContract,f as symbolContract,qe as totalSupplyContract,ct as underlyingContract,Ye as unwrapContract,ot as unwrapFromBalanceContract,it as wrapContract,rt as wrapETHContract,_t as wrapperExistsContract};
|
|
515
515
|
//# sourceMappingURL=index.js.map
|