@zama-fhe/sdk 2.2.0 → 2.3.0-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/activity.cjs.map +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/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/esm/activity-CcsKpDND.js +2 -0
- package/dist/esm/activity-CcsKpDND.js.map +1 -0
- package/dist/esm/{activity-CcKSL6Oe.d.ts → activity-q99hCR8n.d.ts} +85 -4
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-DuOGGACw.js → cleartext-BU7SYjBM.js} +2 -2
- package/dist/esm/{cleartext-DuOGGACw.js.map → cleartext-BU7SYjBM.js.map} +1 -1
- package/dist/esm/{encryption-CKqGKzHs.js → encryption-UaXE1L_W.js} +2 -2
- package/dist/esm/{encryption-CKqGKzHs.js.map → encryption-UaXE1L_W.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +1 -1
- package/dist/esm/{index-IhsduS7h.d.ts → index-j4Uv5iQi.d.ts} +176 -2
- package/dist/esm/index.d.ts +33 -3
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/query/index.d.ts +2 -2
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/relayer-DfjPWTBf.js +2 -0
- package/dist/esm/relayer-DfjPWTBf.js.map +1 -0
- package/dist/esm/viem/index.d.ts +1 -1
- package/package.json +1 -1
- package/dist/esm/activity-Ctiuld0m.js +0 -2
- package/dist/esm/activity-Ctiuld0m.js.map +0 -1
- package/dist/esm/relayer-DxMV-NQT.js +0 -2
- package/dist/esm/relayer-DxMV-NQT.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-DfjPWTBf.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 h,L as te,M as ne,N as re,O as g,P as ie,Q as _,R as v,S as ae,T as oe,U as y,V as b,W as x,X as se,Y as S,Z as C,_ as ce,a as le,at as ue,b as de,c as fe,d as pe,et as w,f as me,g as he,h as ge,i as _e,it as ve,j as ye,k as be,l as xe,m as Se,n as Ce,nt as we,o as Te,p as Ee,q as T,r as De,rt as Oe,s as ke,t as Ae,tt as je,u as Me,v as Ne,w as E,x as Pe,y as Fe,z as D}from"./activity-CcsKpDND.js";import{n as O,t as k}from"./encryption-UaXE1L_W.js";import{n as Ie,t as Le}from"./fhe-artifact-cache-DNoPom4I.js";import{n as Re,r as A,t as j}from"./memory-storage-DNvc-6oK.js";import{i as M,o as ze}from"./assertions-CASetdUe.js";import{a as Be,i as N,n as Ve,o as P,r as F,t as I}from"./relayer-utils-BeoTNDM4.js";import{C as He,D as Ue,E as We,O as L,S as Ge,T as Ke,_ as qe,a as R,b as Je,c as Ye,d as Xe,f as Ze,g as Qe,h as $e,i as et,k as tt,l as nt,m as rt,n as z,o as B,p as it,r as at,s as V,t as H,u as ot,v as st,w as ct,x as lt,y as ut}from"./wrappers-registry-DqPr_JG2.js";import{n as dt,r as ft,t as pt}from"./transfer-batcher-BXIo7hnu.js";import{n as mt}from"./cleartext-BU7SYjBM.js";import{getAddress as U,hexToBigInt as ht}from"viem";var W=class extends r{constructor(e,n){super(t.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},G=class extends r{constructor(e,n){super(t.TransactionReverted,e,n),this.name=`TransactionRevertedError`}};function gt(e){return e instanceof Error&&`cause`in e&&e.cause!==null&&e.cause!==void 0&&typeof e.cause==`object`&&`data`in e.cause&&e.cause.data!==null&&e.cause.data!==void 0&&typeof e.cause.data==`object`&&`errorName`in e.cause.data&&typeof e.cause.data.errorName==`string`?e.cause.data.errorName:null}const K={AlreadyDelegatedOrRevokedInSameBlock:e=>new T(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new h(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new f(`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 m(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new C(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new _(`Cannot revoke: no active delegation exists.`,{cause:e})};function q(e){let t=e instanceof Error?e:void 0,n=gt(e);if(n&&n in K)return K[n]?.(t)??null;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 _t=new J;function vt(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function yt(e,t,n){vt(e[t],n)}function bt(){let e=globalThis;for(let t of[e.chrome,e.browser])try{M(t,`ns`);let{runtime:e}=t;return M(e,`runtime`),ze(e,`id`,`runtime.id`),yt(e,`getURL`,`runtime.getURL`),e}catch{continue}}var xt=`(function() {
|
|
2
2
|
//#region src/utils/assertions.ts
|
|
3
3
|
function assertObject(value, context) {
|
|
4
4
|
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(\`\${context} must be an object, got \${typeof value}\`);
|
|
@@ -494,5 +494,5 @@ import{a as e,i as t,n,r,t as i}from"./relayer-DxMV-NQT.js";import{A as a,B as o
|
|
|
494
494
|
};
|
|
495
495
|
//#endregion
|
|
496
496
|
})();
|
|
497
|
-
`,at=class extends Oe{constructor(e){super(e,e.logger)}createWorker(){let e=rt();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([it],{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})}},ot=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({},A[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({},A[e],this.#l.transports[e]);this.#a=new ke({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 at(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}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:Me(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 O(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 O(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return O(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 O(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return O(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({},A[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 _{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?G(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(B(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=G(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}),Y(()=>n?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:w(e),durationMs:Date.now()-s}),e instanceof r?e:new S(`Failed to encrypt transfer amount`,{cause:e})}if(a.length===0)throw new S(`Encryption returned no handles`);try{let e=await this.signer.writeContract(Je(this.address,i,a[0],o));return this.emit({type:g.TransferSubmitted,txHash:e}),Y(()=>n?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transfer`,error:w(e)}),e instanceof r?e:new q(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=G(e),o=G(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}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:w(e),durationMs:Date.now()-l}),e instanceof r?e:new S(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new S(`Encryption returned no handles`);try{let e=await this.signer.writeContract(F(this.address,a,o,s[0],c));return this.emit({type:g.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transferFrom`,error:w(e)}),e instanceof r?e:new q(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=G(e);try{let e=await this.signer.writeContract(M(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:w(e)}),e instanceof r?e:new K(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=G(e),r=t?G(t):await this.signer.getAddress();return this.signer.readContract(j(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?G(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(L(this.wrapper,e,t));return this.emit({type:g.ShieldSubmitted,txHash:r}),Y(()=>n?.callbacks?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`shield`,error:w(e)}),e instanceof r?e:new q(`Shield transaction failed`,{cause:e})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(I(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:w(e)}),e instanceof r?e:new q(`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:w(e),durationMs:Date.now()-a}),e instanceof r?e:new S(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new S(`Encryption returned no handles`);try{let e=await this.signer.writeContract(N(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:w(e)}),e instanceof r?e:new q(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new C(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(z(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:w(e)}),e instanceof r?e:new q(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let n=crypto.randomUUID(),r=await this.unwrap(e);return Y(()=>t?.onUnwrapSubmitted?.(r.txHash)),this.#i(r.txHash,t,n)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Y(()=>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=$e(r.abiEncodedClearValues)}catch{throw new C(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`)}}catch(e){throw this.emit({type:g.DecryptError,error:w(e),durationMs:Date.now()-i}),e instanceof r?e:new C(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(He(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:w(e)}),e instanceof r?e:new q(`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(a(t,this.wrapper,0n))}let e=await this.signer.writeContract(a(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:w(e)}),e instanceof r?e:new K(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<=Date.now())throw new i(`Expiration date must be in the future`);let n=await this.getAclAddress(),a=t?BigInt(Math.floor(t.getTime()/1e3)):Ee;try{let t=await this.signer.writeContract(ie(n,G(e),this.address,a));return this.emit({type:g.DelegationSubmitted,txHash:t}),{txHash:t,receipt:await this.signer.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:g.TransactionError,operation:`delegateDecryption`,error:w(e)}),e instanceof r?e:new q(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=await this.getAclAddress();try{let n=await this.signer.writeContract(b(t,G(e),this.address));return this.emit({type:g.RevokeDelegationSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:g.TransactionError,operation:`revokeDelegation`,error:w(e)}),e instanceof r?e:new q(`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,a=await Promise.allSettled(e.map(t));for(let t=0;t<e.length;t++){let o=a[t];if(o.status===`fulfilled`)i.set(e[t].address,o.value);else{let a=o.reason instanceof r?o.reason:new q(n,{cause:o.reason});i.set(e[t].address,a)}}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 q(`Failed to get unshield receipt`,{cause:e})}let a=ve(i.logs);if(!a)throw new q(`No UnwrapRequested event found in unshield receipt`);this.emit({type:g.UnshieldPhase2Started,operationId:n}),Y(()=>t?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:g.UnshieldPhase2Submitted,txHash:o.txHash,operationId:n}),Y(()=>t?.onFinalizeSubmitted?.(o.txHash)),o}async#a(e,t,n){let i=await this.#n(),o=await this.signer.getAddress(),s=await this.signer.readContract(v(i,o,this.wrapper));if(!(s>=e))try{s>0n&&await this.signer.writeContract(a(i,this.wrapper,0n));let r=t?2n**256n-1n:e,o=await this.signer.writeContract(a(i,this.wrapper,r));this.emit({type:g.ApproveUnderlyingSubmitted,txHash:o}),Y(()=>n?.onApprovalSubmitted?.(o))}catch(e){throw e instanceof r?e:new K(`ERC-20 approval failed`,{cause:e})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const ct={[k.chainId]:k.registryAddress,[D.chainId]:D.registryAddress,[Qe.chainId]:Qe.registryAddress},X=300*1e3;var Z=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 G(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(P(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(H(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(h(e.tokenAddress)),this.signer.readContract(u(e.tokenAddress)),this.signer.readContract(m(e.tokenAddress)),this.signer.readContract(te(e.tokenAddress)),this.signer.readContract(h(e.confidentialTokenAddress)),this.signer.readContract(u(e.confidentialTokenAddress)),this.signer.readContract(m(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=G(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(W(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(U(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=G(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(V(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(U(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(R(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(P(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(H(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(Ue(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(W(t,G(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(V(t,G(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(U(t,G(e)))}},lt=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,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??86400;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 x(t),this.delegatedCredentials=new y(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:w(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=G(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 x.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new _({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:G(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:G(e),wrapper:t?G(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 x.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()}};function Q(e){return`zama:pending-unshield:${e}`}async function ut(e,t,n){await e.set(Q(t),n)}async function dt(e,t){return e.get(Q(t))}async function ft(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{K as ApprovalFailedError,$ as ChromeSessionStorage,i as ConfigurationError,x as CredentialsManager,C as DecryptionFailedError,ct as DefaultRegistryAddresses,y as DelegatedCredentialsManager,p as DelegationCooldownError,ee as DelegationExpiredError,re as DelegationNotFoundError,De as DelegationNotPropagatedError,o as DelegationSelfNotAllowedError,Re as ERC7984_INTERFACE_ID,Ve as ERC7984_WRAPPER_INTERFACE_ID,S as EncryptionFailedError,Ne as HardhatConfig,J as IndexedDBStorage,se as InvalidKeypairError,f as KeypairExpiredError,k as MainnetConfig,T as MemoryStorage,oe as NoCiphertextError,_ as ReadonlyToken,n as RelayerRequestFailedError,ot as RelayerWeb,D as SepoliaConfig,ce as SigningFailedError,d as SigningRejectedError,ue as TOKEN_TOPICS,st as Token,be as Topics,q as TransactionRevertedError,Z as WrappersRegistry,le as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,lt as ZamaSDK,g as ZamaSDKEvents,v as allowanceContract,we as applyDecryptedValues,a as approveContract,ge as balanceOfContract,pt as chromeSessionStorage,ft as clearPendingUnshield,Le as confidentialBalanceOfContract,Ze as confidentialBatchTransferContract,Ge as confidentialTotalSupplyContract,Je as confidentialTransferContract,F as confidentialTransferFromContract,m as decimalsContract,Ce as decodeConfidentialTransfer,de as decodeOnChainEvent,_e as decodeOnChainEvents,Te as decodeUnwrapRequested,fe as decodeUnwrappedFinalized,pe as decodeUnwrappedStarted,xe as decodeWrapped,ie as delegateForUserDecryptionContract,qe as deploymentCoordinatorContract,ye as extractEncryptedHandles,He as finalizeUnwrapContract,ve as findUnwrapRequested,me as findWrapped,ae as getBatchTransferFeeContract,W as getConfidentialTokenAddressContract,s as getDelegationExpiryContract,l as getFeeRecipientContract,V as getTokenAddressContract,Ue as getTokenPairContract,R as getTokenPairsContract,P as getTokenPairsLengthContract,H as getTokenPairsSliceContract,c as getUnwrapFeeContract,ne as getWrapFeeContract,Ye as getWrapperContract,et as indexedDBStorage,We as isConfidentialTokenContract,U as isConfidentialTokenValidContract,ze as isConfidentialWrapperContract,Fe as isFinalizeUnwrapOperatorContract,j as isOperatorContract,dt as loadPendingUnshield,e as matchZamaError,Ae as memoryStorage,h as nameContract,Se as parseActivityFeed,Ke as rateContract,b as revokeDelegationContract,ut as savePendingUnshield,Ie as setFinalizeUnwrapOperatorContract,M as setOperatorContract,he as sortByBlockNumber,Be as supportsInterfaceContract,u as symbolContract,Pe as totalSupplyContract,B as underlyingContract,N as unwrapContract,z as unwrapFromBalanceContract,L as wrapContract,I as wrapETHContract,Xe as wrapperExistsContract};
|
|
497
|
+
`,St=class extends Ie{constructor(e){super(e,e.logger)}createWorker(){let e=bt();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([xt],{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})}},Ct=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({},I[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({},I[e],this.#l.transports[e]);this.#a=new Le({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 St(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}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:Be(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 P(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 P(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return P(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 P(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return P(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({},I[e],this.#l.transports[e]);if(!t.aclContractAddress)throw new i(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},wt=class e extends E{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?U(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(rt(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=U(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}),Y(()=>n?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:A(e),durationMs:Date.now()-s}),e instanceof r?e:new O(`Failed to encrypt transfer amount`,{cause:e})}if(a.length===0)throw new O(`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}),Y(()=>n?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transfer`,error:A(e)}),e instanceof r?e:new G(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,t,n,i){let a=U(e),o=U(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}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:g.EncryptError,error:A(e),durationMs:Date.now()-l}),e instanceof r?e:new O(`Failed to encrypt transferFrom amount`,{cause:e})}if(s.length===0)throw new O(`Encryption returned no handles`);try{let e=await this.signer.writeContract(Je(this.address,a,o,s[0],c));return this.emit({type:g.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:g.TransactionError,operation:`transferFrom`,error:A(e)}),e instanceof r?e:new G(`TransferFrom transaction failed`,{cause:e})}}async approve(e,t){let n=U(e);try{let e=await this.signer.writeContract(We(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:A(e)}),e instanceof r?e:new W(`Operator approval failed`,{cause:e})}}async isApproved(e,t){let n=U(e),r=t?U(t):await this.signer.getAddress();return this.signer.readContract(He(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?U(n.to):await this.signer.getAddress(),r=await this.signer.writeContract($e(this.wrapper,e,t));return this.emit({type:g.ShieldSubmitted,txHash:r}),Y(()=>n?.callbacks?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:g.TransactionError,operation:`shield`,error:A(e)}),e instanceof r?e:new G(`Shield transaction failed`,{cause:e})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(Qe(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:A(e)}),e instanceof r?e:new G(`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:A(e),durationMs:Date.now()-a}),e instanceof r?e:new O(`Failed to encrypt unshield amount`,{cause:e})}if(n.length===0)throw new O(`Encryption returned no handles`);try{let e=await this.signer.writeContract(L(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:A(e)}),e instanceof r?e:new G(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new k(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(tt(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:A(e)}),e instanceof r?e:new G(`Unshield-all transaction failed`,{cause:e})}}async unshield(e,t){let n=crypto.randomUUID(),r=await this.unwrap(e);return Y(()=>t?.onUnwrapSubmitted?.(r.txHash)),this.#i(r.txHash,t,n)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Y(()=>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 k(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`)}}catch(e){throw this.emit({type:g.DecryptError,error:A(e),durationMs:Date.now()-i}),e instanceof r?e:new k(`Failed to finalize unshield`,{cause:e})}try{let r=await this.signer.writeContract(it(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:A(e)}),e instanceof r?e:new G(`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(D(t,this.wrapper,0n))}let e=await this.signer.writeContract(D(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:A(e)}),e instanceof r?e:new W(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<Date.now()+36e5)throw new S(`Expiration date must be at least 1 hour in the future`);let n=U(e),i=await this.signer.getAddress();if(n===U(i))throw new w(`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)):be;if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:n})===s)throw new C(`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:A(e)}),e instanceof r?e:q(e)||new G(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let t=U(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(re(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:A(e)}),e instanceof r?e:q(e)||new G(`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,a=await Promise.allSettled(e.map(t));for(let t=0;t<e.length;t++){let o=a[t];if(o.status===`fulfilled`)i.set(e[t].address,o.value);else{let a=o.reason instanceof r?o.reason:new G(n,{cause:o.reason});i.set(e[t].address,a)}}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 G(`Failed to get unshield receipt`,{cause:e})}let a=ae(i.logs);if(!a)throw new G(`No UnwrapRequested event found in unshield receipt`);this.emit({type:g.UnshieldPhase2Started,operationId:n}),Y(()=>t?.onFinalizing?.());let o=await this.finalizeUnwrap(a.encryptedAmount);return this.emit({type:g.UnshieldPhase2Submitted,txHash:o.txHash,operationId:n}),Y(()=>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(D(i,this.wrapper,0n));let r=t?2n**256n-1n:e,a=await this.signer.writeContract(D(i,this.wrapper,r));this.emit({type:g.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof r?e:new W(`ERC-20 approval failed`,{cause:e})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Tt={[F.chainId]:F.registryAddress,[N.chainId]:N.registryAddress,[mt.chainId]:mt.registryAddress},X=300*1e3;var Z=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},Tt,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 U(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(R(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?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(x(e.tokenAddress)),this.signer.readContract(b(e.tokenAddress)),this.signer.readContract(p(e.tokenAddress)),this.signer.readContract(y(e.confidentialTokenAddress)),this.signer.readContract(x(e.confidentialTokenAddress)),this.signer.readContract(b(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=U(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.signer.readContract(H(t,n));if(!a)return this.#i(r,null,X);let s=await this.signer.readContract(V(t,o));return this.#i(r,{confidentialTokenAddress:o,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=U(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,X);let s=await this.signer.readContract(V(t,n));return this.#i(r,{tokenAddress:o,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(et(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(R(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(H(t,U(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(z(t,U(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(V(t,U(e)))}},Et=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 j,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??86400;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: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=U(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 E({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:U(e),onEvent:this.#t})}createToken(e,t){return new wt({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:U(e),wrapper:t?U(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 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()}};function Q(e){return`zama:pending-unshield:${e}`}async function Dt(e,t,n){await e.set(Q(t),n)}async function Ot(e,t){return e.get(Q(t))}async function kt(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 At=new $;export{le as ACL_TOPICS,f as AclPausedError,Te as AclTopics,W as ApprovalFailedError,$ as ChromeSessionStorage,i as ConfigurationError,l as CredentialsManager,k as DecryptionFailedError,Tt as DefaultRegistryAddresses,u as DelegatedCredentialsManager,h as DelegationContractIsSelfError,T as DelegationCooldownError,m as DelegationDelegateEqualsContractError,S as DelegationExpirationTooSoonError,se as DelegationExpiredError,C as DelegationExpiryUnchangedError,_ as DelegationNotFoundError,a as DelegationNotPropagatedError,w as DelegationSelfNotAllowedError,Ye as ERC7984_INTERFACE_ID,nt as ERC7984_WRAPPER_INTERFACE_ID,O as EncryptionFailedError,Ve as HardhatConfig,J as IndexedDBStorage,je as InvalidKeypairError,we as KeypairExpiredError,F as MainnetConfig,j as MemoryStorage,Oe as NoCiphertextError,E as ReadonlyToken,n as RelayerRequestFailedError,Ct as RelayerWeb,N as SepoliaConfig,ve as SigningFailedError,ue as SigningRejectedError,ke as TOKEN_TOPICS,wt as Token,fe as Topics,G as TransactionRevertedError,Z as WrappersRegistry,oe as ZERO_HANDLE,r as ZamaError,t as ZamaErrorCode,Et as ZamaSDK,g as ZamaSDKEvents,v as allowanceContract,Ae as applyDecryptedValues,D as approveContract,s as balanceOfContract,At as chromeSessionStorage,kt as clearPendingUnshield,qe as confidentialBalanceOfContract,pt as confidentialBatchTransferContract,st as confidentialTotalSupplyContract,ut as confidentialTransferContract,Je as confidentialTransferFromContract,b as decimalsContract,xe as decodeAclEvent,Me as decodeAclEvents,pe as decodeConfidentialTransfer,me as decodeDelegatedForUserDecryption,Ee as decodeOnChainEvent,Se as decodeOnChainEvents,ge as decodeRevokedDelegationForUserDecryption,he as decodeUnwrapRequested,ce as decodeUnwrappedFinalized,Ne as decodeUnwrappedStarted,Fe as decodeWrapped,o as delegateForUserDecryptionContract,lt as deploymentCoordinatorContract,Ce as extractEncryptedHandles,it as finalizeUnwrapContract,de as findDelegatedForUserDecryption,Pe as findRevokedDelegationForUserDecryption,ae as findUnwrapRequested,c as findWrapped,ie as getBatchTransferFeeContract,H as getConfidentialTokenAddressContract,ye as getDelegationExpiryContract,d as getFeeRecipientContract,z as getTokenAddressContract,at as getTokenPairContract,et as getTokenPairsContract,R as getTokenPairsLengthContract,B as getTokenPairsSliceContract,ee as getUnwrapFeeContract,te as getWrapFeeContract,dt as getWrapperContract,_t as indexedDBStorage,ot as isConfidentialTokenContract,V as isConfidentialTokenValidContract,Xe as isConfidentialWrapperContract,Ge as isFinalizeUnwrapOperatorContract,ne as isHandleDelegatedContract,He as isOperatorContract,Ot as loadPendingUnshield,q as matchAclRevert,e as matchZamaError,Re as memoryStorage,y as nameContract,De as parseActivityFeed,ct as rateContract,re as revokeDelegationContract,Dt as savePendingUnshield,Ke as setFinalizeUnwrapOperatorContract,We as setOperatorContract,_e as sortByBlockNumber,Ze as supportsInterfaceContract,x as symbolContract,Ue as totalSupplyContract,rt as underlyingContract,L as unwrapContract,tt as unwrapFromBalanceContract,$e as wrapContract,Qe as wrapETHContract,ft as wrapperExistsContract};
|
|
498
498
|
//# sourceMappingURL=index.js.map
|