@zama-fhe/sdk 1.2.0-alpha.3 → 1.2.0-alpha.4
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/{activity-jvpqohOy.d.ts → activity-CV1NDmFr.d.ts} +4 -4
- package/dist/activity-DEoxFQLE.js +2 -0
- package/dist/cleartext/index.d.ts +2 -2
- package/dist/cleartext/index.js +1 -1
- package/dist/ethers/index.d.ts +3 -3
- package/dist/ethers/index.js +1 -1
- package/dist/{index-CKQy-JYP.d.ts → index-BFPpJ8wt.d.ts} +2 -2
- package/dist/index.d.ts +5 -5
- package/dist/index.js +23 -16
- package/dist/node/index.d.ts +3 -3
- package/dist/node/index.js +1 -1
- package/dist/query/index.d.ts +4 -4
- package/dist/query/index.js +1 -1
- package/dist/{relayer-sdk-DFUB0ULp.d.ts → relayer-sdk-CVVR30IW.d.ts} +2 -2
- package/dist/relayer-sdk.node-worker.js +1 -1
- package/dist/{relayer-sdk.types-7bIeWnws.d.ts → relayer-sdk.types-DI4WWkTB.d.ts} +7 -9
- package/dist/relayer-sdk.worker.js +21 -14
- package/dist/{token.types-CKH_X0ki.d.ts → token.types-DDdIZEax.d.ts} +2 -2
- package/dist/{utils-CYS8x8P_.js → utils-eIBZNA_w.js} +2 -2
- package/dist/viem/index.d.ts +3 -3
- package/package.json +3 -3
- package/dist/activity-BlZy4dNC.js +0 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { o as Handle } from "./relayer-sdk.types-
|
|
2
|
-
import { b as OnChainEvent, d as StoredCredentials, h as UnshieldCallbacks, i as GenericStorage, l as ShieldCallbacks, m as TransferCallbacks, n as DelegatedStoredCredentials, p as TransactionResult, r as GenericSigner, u as SignerLifecycleCallbacks, x as RawLog } from "./token.types-
|
|
3
|
-
import { t as RelayerSDK } from "./relayer-sdk-
|
|
1
|
+
import { o as Handle } from "./relayer-sdk.types-DI4WWkTB.js";
|
|
2
|
+
import { b as OnChainEvent, d as StoredCredentials, h as UnshieldCallbacks, i as GenericStorage, l as ShieldCallbacks, m as TransferCallbacks, n as DelegatedStoredCredentials, p as TransactionResult, r as GenericSigner, u as SignerLifecycleCallbacks, x as RawLog } from "./token.types-DDdIZEax.js";
|
|
3
|
+
import { t as RelayerSDK } from "./relayer-sdk-CVVR30IW.js";
|
|
4
4
|
import { Address, Hex } from "viem";
|
|
5
5
|
|
|
6
6
|
//#region src/events/sdk-events.d.ts
|
|
@@ -1461,4 +1461,4 @@ declare function applyDecryptedValues(items: readonly ActivityItem[], decryptedM
|
|
|
1461
1461
|
declare function sortByBlockNumber(items: readonly ActivityItem[]): ActivityItem[];
|
|
1462
1462
|
//#endregion
|
|
1463
1463
|
export { DecryptStartEvent as $, ZamaErrorCode as A, CredentialsManagerConfig as B, KeypairExpiredError as C, SigningRejectedError as D, SigningFailedError as E, ReadonlyTokenConfig as F, CredentialsCachedEvent as G, ApproveUnderlyingSubmittedEvent as H, ZERO_HANDLE as I, CredentialsExpiredEvent as J, CredentialsCreatedEvent as K, DelegatedCredentialsManager as L, BatchDecryptAsOptions as M, BatchDecryptOptions as N, TransactionRevertedError as O, ReadonlyToken as P, DecryptErrorEvent as Q, DelegatedCredentialsManagerConfig as R, InvalidKeypairError as S, RelayerRequestFailedError as T, BaseEvent as U, ApproveSubmittedEvent as V, CredentialsAllowedEvent as W, CredentialsRevokedEvent as X, CredentialsLoadingEvent as Y, DecryptEndEvent as Z, DelegationCooldownError as _, ZamaSDKEvents as _t, ActivityType as a, ShieldSubmittedEvent as at, DelegationSelfNotAllowedError as b, parseActivityFeed as c, TransferSubmittedEvent as ct, ZamaSDKConfig as d, UnshieldPhase2SubmittedEvent as dt, EncryptEndEvent as et, Token as f, UnwrapSubmittedEvent as ft, DecryptionFailedError as g, ZamaSDKEventType as gt, ConfigurationError as h, ZamaSDKEventListener as ht, ActivityLogMetadata as i, SessionExpiredEvent as it, matchZamaError as j, ZamaError as k, sortByBlockNumber as l, UnshieldPhase1SubmittedEvent as lt, ApprovalFailedError as m, ZamaSDKEventInput as mt, ActivityDirection as n, EncryptStartEvent as nt, applyDecryptedValues as o, TransactionErrorEvent as ot, TokenConfig as p, ZamaSDKEvent as pt, CredentialsCreatingEvent as q, ActivityItem as r, FinalizeUnwrapSubmittedEvent as rt, extractEncryptedHandles as s, TransferFromSubmittedEvent as st, ActivityAmount as t, EncryptErrorEvent as tt, ZamaSDK as u, UnshieldPhase2StartedEvent as ut, DelegationExpiredError as v, NoCiphertextError as w, EncryptionFailedError as x, DelegationNotFoundError as y, CredentialsManager as z };
|
|
1464
|
-
//# sourceMappingURL=activity-
|
|
1464
|
+
//# sourceMappingURL=activity-CV1NDmFr.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as e,d as t,f as n,m as r,n as i,o as a,p as o,r as s,y as c}from"./errors-Cw9kKQJc.js";import{c as l,i as u,n as d,o as ee,r as f,s as p,t as m}from"./utils-eIBZNA_w.js";import{a as h,f as te,l as g,n as _,o as v,s as ne,t as re}from"./erc165-BZgfzGxL.js";import{erc20Abi as y,getAddress as b,isAddress as x}from"viem";function ie(e){return{address:e,abi:y,functionName:`name`,args:[]}}function S(e){return{address:e,abi:y,functionName:`symbol`,args:[]}}function C(e){return{address:e,abi:y,functionName:`decimals`,args:[]}}function ae(e,t){return{address:e,abi:y,functionName:`balanceOf`,args:[t]}}function w(e,t,n){return{address:e,abi:y,functionName:`allowance`,args:[t,n]}}function oe(e,t,n){return{address:e,abi:y,functionName:`approve`,args:[t,n]}}const T=[{inputs:[{internalType:`uint256`,name:`amount`,type:`uint256`},{internalType:`address`,name:`wrapFrom`,type:`address`},{internalType:`address`,name:`wrapTo`,type:`address`}],name:`getWrapFee`,outputs:[{internalType:`uint256`,name:``,type:`uint256`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint64`,name:`amount`,type:`uint64`},{internalType:`address`,name:`unwrapFrom`,type:`address`},{internalType:`address`,name:`unwrapTo`,type:`address`}],name:`getUnwrapFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getBatchTransferFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getFeeRecipient`,outputs:[{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`}];function se(e,t,n,r){return{address:e,abi:T,functionName:`getWrapFee`,args:[t,n,r]}}function ce(e,t,n,r){return{address:e,abi:T,functionName:`getUnwrapFee`,args:[t,n,r]}}function le(e){return{address:e,abi:T,functionName:`getBatchTransferFee`,args:[]}}function ue(e){return{address:e,abi:T,functionName:`getFeeRecipient`,args:[]}}const E=[{inputs:[{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`},{internalType:`uint64`,name:`expirationDate`,type:`uint64`}],name:`delegateForUserDecryption`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`}],name:`revokeDelegationForUserDecryption`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`delegator`,type:`address`},{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`}],name:`getUserDecryptionDelegationExpirationDate`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`}];function de(e,t,n,r){return{address:e,abi:E,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function fe(e,t,n){return{address:e,abi:E,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function pe(e,t,n,r){return{address:e,abi:E,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}const D=2n**64n-1n,O={CredentialsLoading:`credentials:loading`,CredentialsCached:`credentials:cached`,CredentialsExpired:`credentials:expired`,CredentialsCreating:`credentials:creating`,CredentialsCreated:`credentials:created`,CredentialsRevoked:`credentials:revoked`,CredentialsAllowed:`credentials:allowed`,SessionExpired:`session:expired`,EncryptStart:`encrypt:start`,EncryptEnd:`encrypt:end`,EncryptError:`encrypt:error`,DecryptStart:`decrypt:start`,DecryptEnd:`decrypt:end`,DecryptError:`decrypt:error`,TransactionError:`transaction:error`,ShieldSubmitted:`shield:submitted`,TransferSubmitted:`transfer:submitted`,TransferFromSubmitted:`transferFrom:submitted`,ApproveSubmitted:`approve:submitted`,ApproveUnderlyingSubmitted:`approveUnderlying:submitted`,UnwrapSubmitted:`unwrap:submitted`,FinalizeUnwrapSubmitted:`finalizeUnwrap:submitted`,DelegationSubmitted:`delegation:submitted`,RevokeDelegationSubmitted:`revokeDelegation:submitted`,UnshieldPhase1Submitted:`unshield:phase1_submitted`,UnshieldPhase2Started:`unshield:phase2_started`,UnshieldPhase2Submitted:`unshield:phase2_submitted`};var k=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const me=new k;var he=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return p(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function A(e){f(e,`Stored credentials`),u(e.publicKey,`credentials.publicKey`),m(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)d(typeof t==`string`&&x(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);f(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),u(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),u(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`)}function ge(e){A(e);let t=e;d(typeof t.delegatorAddress==`string`&&x(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),d(typeof t.delegateAddress==`string`&&x(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),d(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),d(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function j(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function M(e,t){let n=new Set(t.map(e=>b(e))),r=new Set(e.map(e=>b(e)));return n.isSubsetOf(r)}function N(e,t){return j(e)?M(e.contractAddresses,t):!1}function P(e){return[...new Set(e.map(e=>b(e)))].toSorted()}async function F(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var _e=class{#e;constructor(e){this.#e=e}#t(e){f(e,`Session entry`),u(e.signature,`session.signature`),d(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),d(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},I=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new _e(e.sessionStorage),this.crypto=new he,this.keypairTTL=e.keypairTTL??86400,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`)}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:e,contracts:t,createKey:n,createFn:i}){this.emit({type:O.CredentialsLoading,contractAddresses:t});try{let n=await this.storage.get(e);if(n){this.assertEncrypted(n);let r=await this.sessionSignatures.get(e);if(r)if(this.sessionSignatures.isExpired(r))await this.sessionSignatures.delete(e),this.emit({type:O.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(n,r.signature);if(N(i,t))return this.emit({type:O.CredentialsCached,contractAddresses:t}),this.emit({type:O.CredentialsAllowed,contractAddresses:t}),i;if(j(i))return this.#i({key:e,credentials:i,requiredContracts:t});this.emit({type:O.CredentialsExpired,contractAddresses:t})}if(j(n)){if(M(n.contractAddresses,t)){let r=await this.signForContracts(n,n.contractAddresses);await this.sessionSignatures.set({key:e,signature:r,ttl:this.sessionTTL});let i=await this.decryptCredentials(n,r);return this.emit({type:O.CredentialsCached,contractAddresses:t}),this.emit({type:O.CredentialsAllowed,contractAddresses:t}),i}let r=await this.signForContracts(n,n.contractAddresses),i=await this.decryptCredentials(n,r);return this.#i({key:e,credentials:i,requiredContracts:t})}this.emit({type:O.CredentialsExpired,contractAddresses:t})}}catch(t){if(t instanceof r||t instanceof o)throw t;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,t),await this.#o(e)}return(!this.#t||this.#n!==n)&&(this.#n=n,this.#t=i().then(e=>(this.emit({type:O.CredentialsAllowed,contractAddresses:t}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!N(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,t){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:O.CredentialsRevoked,...t?{contractAddresses:t}:{}})}async checkAllowed(e){let t=await this.sessionSignatures.get(e);return t===null?!1:!this.sessionSignatures.isExpired(t)}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#o(e)}clearCaches(){this.crypto.clearCache()}async createCredentials({key:e,contractAddresses:t,createFn:n,errorContext:r}){this.emit({type:O.CredentialsCreating,contractAddresses:t});try{let r=await n();return await this.persistCredentials(e,r),await this.sessionSignatures.set({key:e,signature:r.signature,ttl:this.sessionTTL}),this.emit({type:O.CredentialsCreated,contractAddresses:t}),r}catch(e){c(e,r)}}async#i({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(M(e.contractAddresses,n))return this.emit({type:O.CredentialsAllowed,contractAddresses:n}),e;t=e}let r=this.#a({key:e,credentials:t,requiredContracts:n});this.#r=r;try{return await r}finally{this.#r===r&&(this.#r=null)}}async#a({key:e,credentials:t,requiredContracts:n}){let r=P([...t.contractAddresses,...n]),i=await this.signForContracts(t,r),a={...t,contractAddresses:r,signature:i};return await this.persistCredentials(e,a),await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL}),this.emit({type:O.CredentialsAllowed,contractAddresses:n}),a}async persistCredentials(e,t){try{let n=await this.encryptCredentials(t);await this.storage.set(e,n)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e);return}}async#o(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e)}}};function ve(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var L=class e extends I{#e;#t=null;#n=null;static async computeStoreKey(e,t){return F(b(e),t)}constructor(e){super(e),this.#e=e.relayer,ve(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof k&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=P(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async isAllowed(){return this.checkAllowed(await this.#r())}async clear(){await this.clearAll(await this.#r())}async create(e){let t=P(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){A(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${b(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await e.computeStoreKey(t,n);return this.#n=r,this.#t=i,i}},R=class e extends I{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return F(b(e),b(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=b(e),r=P(t),i=await this.#i(n);return this.resolveCredentials({key:i,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i(b(e)),t)}async revoke(e){await this.revokeSession(await this.#i(b(e)))}async isAllowed(e){return this.checkAllowed(await this.#i(b(e)))}async clear(e){await this.clearAll(await this.#i(b(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){ge(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),i=`${b(n)}:${b(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(n,t,r);return this.#n=i,this.#t=a,a}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData({domain:{...n.domain,chainId:Number(n.domain.chainId)},types:n.types,message:{...n.message,startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays)}})}};const z=`zama:balances`;function ye(e,t,n){return`zama:balance:${b(e)}:${b(t)}:${n.toLowerCase()}`}async function B({storage:e,tokenAddress:t,owner:n,handle:r}){try{let i=await e.get(ye(t,n,r));return i===null?null:BigInt(i)}catch(e){return console.warn(`[zama-sdk] Balance cache read failed:`,e),null}}async function V(e){let{storage:t,tokenAddress:n,owner:r,handle:i,value:a}=e,o=ye(n,r,i);try{await t.set(o,a.toString()),await xe(t,o)}catch{}}const be=new WeakMap;async function xe(e,t){let n=(be.get(e)??Promise.resolve()).then(async()=>{let n=await e.get(z),r=n?JSON.parse(n):[];r.includes(t)||(r.push(t),await e.set(z,JSON.stringify(r)))});return be.set(e,n.catch(()=>{})),n}const Se=`0x0000000000000000000000000000000000000000000000000000000000000000`;var Ce=class t{credentials;delegatedCredentials;relayer;signer;address;storage;#e;constructor(e){let t={relayer:e.relayer,signer:e.signer,storage:e.storage,sessionStorage:e.sessionStorage,keypairTTL:e.keypairTTL??86400,sessionTTL:e.sessionTTL??2592e3,onEvent:e.onEvent};this.credentials=e.credentials??new L(t),this.delegatedCredentials=e.delegatedCredentials??new R(t),this.relayer=e.relayer,this.signer=e.signer,this.address=b(e.address),this.storage=e.storage,this.#e=e.onEvent}emit(e){this.#e?.({...e,tokenAddress:this.address,timestamp:Date.now()})}async balanceOf(e){let t=e?b(e):await this.signer.getAddress(),n=await this.readConfidentialBalanceOf(t);return this.decryptBalance(n,t)}async confidentialBalanceOf(e){let t=e?b(e):await this.signer.getAddress();return this.readConfidentialBalanceOf(t)}async isConfidential(){return await this.signer.readContract(h(this.address,re))}async isWrapper(){return await this.signer.readContract(h(this.address,_))}static async batchDecryptBalances(e,n){if(e.length===0)return new Map;let{handles:r,owner:i,onError:a,maxConcurrency:o}=n??{},s=e[0],c=t.assertSameRelayer(e),l=i??await s.signer.getAddress();return t.#t({tokens:e,handles:r,ownerAddress:l,onError:a,maxConcurrency:o,obtainCreds:e=>s.credentials.allow(...e),decrypt:(e,t,n)=>c.userDecrypt({handles:[t],contractAddress:n,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,signerAddress:l,startTimestamp:e.startTimestamp,durationDays:e.durationDays}),errorPrefix:`Batch decryption`})}static async batchDecryptBalancesAs(e,n){if(e.length===0)return new Map;let{delegatorAddress:r,handles:i,owner:a,onError:o,maxConcurrency:s}=n,c=a??r,l=e[0];return t.assertSameRelayer(e),t.#t({tokens:e,handles:i,ownerAddress:c,onError:o,maxConcurrency:s,preFlightCheck:()=>l.#n(r),obtainCreds:e=>l.delegatedCredentials.allow(r,...e),decrypt:(e,t,n)=>l.relayer.delegatedUserDecrypt({handles:[t],contractAddress:n,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,delegatorAddress:e.delegatorAddress,delegateAddress:e.delegateAddress,startTimestamp:e.startTimestamp,durationDays:e.durationDays}),errorPrefix:`Batch delegated decryption`})}static async#t(e){let{tokens:t,handles:n,ownerAddress:r,onError:i,maxConcurrency:a,obtainCreds:o,decrypt:c,errorPrefix:u}=e,d=t[0],f=n??await Promise.all(t.map(e=>e.readConfidentialBalanceOf(r)));if(t.length!==f.length)throw new s(`tokens.length (${t.length}) must equal handles.length (${f.length})`);let p=d.storage,m=new Map,h=[],te=await Promise.all(t.map((e,t)=>{let n=f[t];return e.isZeroHandle(n)?0n:B({storage:p,tokenAddress:e.address,owner:r,handle:n})}));for(let e=0;e<t.length;e++){let n=t[e],r=f[e],i=te[e];if(i!=null){m.set(n.address,i);continue}h.push({token:n,handle:r})}if(h.length===0)return m;e.preFlightCheck&&await e.preFlightCheck();let g=await o(h.map(e=>e.token.address)),_=[],v=[];for(let{token:e,handle:t}of h)v.push(()=>c(g,t,e.address).then(async n=>{let i=n[t];if(i===void 0)throw new s(`${u} returned no value for handle ${t} on token ${e.address}`);m.set(e.address,i);try{await V({storage:p,tokenAddress:e.address,owner:r,handle:t,value:i})}catch{}}).catch(t=>{let n=l(t);if(i)try{m.set(e.address,i(n,e.address))}catch(t){_.push({address:e.address,error:l(t)})}else _.push({address:e.address,error:n})}));if(await ee(v,a),_.length>0){let e=_.map(e=>`${e.address}: ${e.error.message}`).join(`; `);throw new s(`${u} failed for ${_.length} token(s): ${e}`)}return m}async discoverWrapper(e){let t=b(e);return await this.signer.readContract(ne(t,this.address))?this.signer.readContract(v(t,this.address)):null}async underlyingToken(){return this.signer.readContract(g(this.address))}async allowance(e,t){let n=b(e),r=await this.signer.readContract(g(n)),i=t?b(t):await this.signer.getAddress();return this.signer.readContract(w(r,i,n))}async name(){return this.signer.readContract(ie(this.address))}async symbol(){return this.signer.readContract(S(this.address))}async decimals(){return this.signer.readContract(C(this.address))}async allow(){await this.credentials.allow(this.address)}async isAllowed(){return this.credentials.isAllowed()}async revoke(...e){await this.credentials.revoke(...e)}static async allow(...e){if(e.length===0)return;let t=e.map(e=>e.address);await e[0].credentials.allow(...t)}async getAclAddress(){return this.relayer.getAclAddress()}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===D?!0:t>await this.signer.getBlockTimestamp()}async getDelegationExpiry({delegatorAddress:e,delegateAddress:t}){let n=await this.getAclAddress();return this.signer.readContract(pe(n,b(e),b(t),this.address))}async#n(t){let n=await this.signer.getAddress(),r=await this.getDelegationExpiry({delegatorAddress:t,delegateAddress:n});if(r===0n)throw new a(`No active delegation from ${t} to ${n} for ${this.address}`);if(r!==D&&r<=await this.signer.getBlockTimestamp())throw new e(`Delegation from ${t} to ${n} for ${this.address} has expired`)}async readConfidentialBalanceOf(e){return await this.signer.readContract(te(this.address,e))}isZeroHandle(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}async decryptBalanceAs({delegatorAddress:e,owner:t}){let n=b(e),r=t?b(t):n,i=await this.readConfidentialBalanceOf(r);if(this.isZeroHandle(i))return 0n;let a=await B({storage:this.storage,tokenAddress:this.address,owner:r,handle:i});if(a!==null)return a;await this.#n(n);let o=Date.now();try{this.emit({type:O.DecryptStart});let e=await this.delegatedCredentials.allow(n,this.address),t=await this.relayer.delegatedUserDecrypt({handles:[i],contractAddress:this.address,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,delegatorAddress:e.delegatorAddress,delegateAddress:e.delegateAddress,startTimestamp:e.startTimestamp,durationDays:e.durationDays});this.emit({type:O.DecryptEnd,durationMs:Date.now()-o});let a=t[i];if(a===void 0)throw new s(`Delegated decryption returned no value for handle ${i}`);try{await V({storage:this.storage,tokenAddress:this.address,owner:r,handle:i,value:a})}catch{}return a}catch(e){throw this.emit({type:O.DecryptError,error:l(e),durationMs:Date.now()-o}),H(e,`Failed to decrypt delegated balance`)}}async decryptBalance(e,t){if(this.isZeroHandle(e))return 0n;let n=t??await this.signer.getAddress(),r=await B({storage:this.storage,tokenAddress:this.address,owner:n,handle:e});if(r!==null)return r;let i=await this.credentials.allow(this.address),a=Date.now();try{this.emit({type:O.DecryptStart});let t=await this.relayer.userDecrypt({handles:[e],contractAddress:this.address,signedContractAddresses:i.contractAddresses,privateKey:i.privateKey,publicKey:i.publicKey,signature:i.signature,signerAddress:n,startTimestamp:i.startTimestamp,durationDays:i.durationDays});this.emit({type:O.DecryptEnd,durationMs:Date.now()-a});let r=t[e];if(r===void 0)throw new s(`Decryption returned no value for handle ${e}`);try{await V({storage:this.storage,tokenAddress:this.address,owner:n,handle:e,value:r})}catch{}return r}catch(e){throw this.emit({type:O.DecryptError,error:l(e),durationMs:Date.now()-a}),H(e,`Failed to decrypt balance`)}}async decryptHandles(e,t){let n=new Map,r=[];for(let t of e)this.isZeroHandle(t)?n.set(t,0n):r.push(t);if(r.length===0)return n;let i=await this.credentials.allow(this.address),a=Date.now();try{this.emit({type:O.DecryptStart});let e=await this.relayer.userDecrypt({handles:r,contractAddress:this.address,signedContractAddresses:i.contractAddresses,privateKey:i.privateKey,publicKey:i.publicKey,signature:i.signature,signerAddress:t??await this.signer.getAddress(),startTimestamp:i.startTimestamp,durationDays:i.durationDays});this.emit({type:O.DecryptEnd,durationMs:Date.now()-a});for(let t of r){let r=e[t];if(r===void 0)throw new s(`Decryption returned no value for handle ${t}`);n.set(t,r)}}catch(e){throw this.emit({type:O.DecryptError,error:l(e),durationMs:Date.now()-a}),H(e,`Failed to decrypt handles`)}return n}static assertSameRelayer(e){let t=e[0].relayer;for(let n=1;n<e.length;n++)if(e[n].relayer!==t)throw new i(`All tokens in a batch operation must share the same relayer instance`);return t}};function H(e,i){if(e instanceof s||e instanceof t||e instanceof n||e instanceof r||e instanceof o)return e;let a=typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`?e.statusCode:void 0;return a===400?new t(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):a===void 0?new s(i,{cause:e}):new n(e instanceof Error?e.message:i,a,{cause:e})}const U={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x1f7907f4d84043abe0fb7c74e8865ee5fe93fe4f691c54a7b8fa9d6fb17c7cba`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0xc64e7c81b18b674fc5b037d8a0041bfe3332d86c780a4688f404ee01fbabb152`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function W(e){return b(p(e.slice(-40)))}function G(e){return BigInt(e)}function we(e){return e}function K(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function Te(e,t){return b(p(K(e,t).slice(-40)))}function q(e,t){return BigInt(`0x`+K(e,t))}function J(e,t){return BigInt(`0x`+K(e,t))!==0n}function Y(e,t){return p(K(e,t))}function Ee(e){return e.topics[0]!==U.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:W(e.topics[1]),to:W(e.topics[2]),encryptedAmountHandle:we(e.topics[3])}}function X(e){return e.topics[0]!==U.Wrapped||e.topics.length<3?null:{eventName:`Wrapped`,to:W(e.topics[1]),mintTxId:G(e.topics[2]),mintAmount:q(e.data,0),amountIn:q(e.data,1),feeAmount:q(e.data,2)}}function Z(e){return e.topics[0]!==U.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:W(e.topics[1]),encryptedAmount:Y(e.data,0)}}function De(e){return e.topics[0]!==U.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,burntAmountHandle:we(e.topics[1]),nextTxId:G(e.topics[2]),finalizeSuccess:J(e.data,0),feeTransferSuccess:J(e.data,1),burnAmount:q(e.data,2),unwrapAmount:q(e.data,3),feeAmount:q(e.data,4)}}function Oe(e){return e.topics[0]!==U.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:G(e.topics[1]),txId:G(e.topics[2]),to:W(e.topics[3]),returnVal:J(e.data,0),refund:Te(e.data,1),requestedAmount:Y(e.data,2),burnAmount:Y(e.data,3)}}function Q(e){return Ee(e)??X(e)??Z(e)??De(e)??Oe(e)}function ke(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function Ae(e){for(let t of e){let e=Z(t);if(e)return e}return null}function je(e){for(let t of e){let e=X(t);if(e)return e}return null}const Me=[U.ConfidentialTransfer,U.Wrapped,U.UnwrapRequested,U.UnwrappedFinalized,U.UnwrappedStarted];function Ne(e,t){return e.toLowerCase()===t.toLowerCase()}function $(e,t,n){let r=t!==void 0&&Ne(e,t),i=n!==void 0&&Ne(e,n);return r&&i?`self`:r?`outgoing`:`incoming`}function Pe(e,t,n){switch(e.eventName){case`ConfidentialTransfer`:return Fe(e,t,n);case`Wrapped`:return Ie(e,t,n);case`UnwrapRequested`:return Le(e,t,n);case`UnwrappedStarted`:return Re(e,t,n);case`UnwrappedFinalized`:return ze(e,n)}}function Fe(e,t,n){return{type:`transfer`,direction:$(t,e.from,e.to),amount:{type:`encrypted`,handle:e.encryptedAmountHandle},from:e.from,to:e.to,metadata:n,rawEvent:e}}function Ie(e,t,n){return{type:`shield`,direction:$(t,void 0,e.to),amount:{type:`clear`,value:e.amountIn},to:e.to,fee:e.feeAmount,metadata:n,rawEvent:e}}function Le(e,t,n){return{type:`unshield_requested`,direction:$(t,void 0,e.receiver),amount:{type:`encrypted`,handle:e.encryptedAmount},to:e.receiver,metadata:n,rawEvent:e}}function Re(e,t,n){return{type:`unshield_started`,direction:$(t,void 0,e.to),amount:{type:`encrypted`,handle:e.requestedAmount},to:e.to,success:e.returnVal,metadata:n,rawEvent:e}}function ze(e,t){return{type:`unshield_finalized`,direction:`incoming`,amount:{type:`clear`,value:e.unwrapAmount},fee:e.feeAmount,success:e.finalizeSuccess,metadata:t,rawEvent:e}}function Be(e,t){let n=[];for(let r of e){let e=Q(r);if(!e)continue;let i={transactionHash:r.transactionHash,blockNumber:r.blockNumber,logIndex:r.logIndex};n.push(Pe(e,t,i))}return n}function Ve(e){let t=new Set;for(let n of e)if(n.amount.type===`encrypted`&&n.amount.decryptedValue===void 0){let e=n.amount.handle;e!==`0x`&&e!==`0x0000000000000000000000000000000000000000000000000000000000000000`&&t.add(e)}return[...t]}function He(e,t){return e.map(e=>{if(e.amount.type!==`encrypted`)return e;let n=t.get(e.amount.handle);return n===void 0?e:{...e,amount:{type:`encrypted`,handle:e.amount.handle,decryptedValue:n}}})}function Ue(e){return[...e].toSorted((e,t)=>{let n=e.metadata.blockNumber,r=t.metadata.blockNumber;if(n===void 0&&r===void 0)return 0;if(n===void 0)return-1;if(r===void 0)return 1;let i=typeof n==`bigint`?n:BigInt(n),a=typeof r==`bigint`?r:BigInt(r);if(a>i)return 1;if(a<i)return-1;let o=e.metadata.logIndex??0;return(t.metadata.logIndex??0)-o})}export{se as A,D as C,le as D,fe as E,ie as F,S as I,oe as M,ae as N,ue as O,C as P,O as S,pe as T,Se as _,Me as a,k as b,Q as c,De as d,Oe as f,Ce as g,je as h,Ue as i,w as j,ce as k,ke as l,Ae as m,Ve as n,U as o,X as p,Be as r,Ee as s,He as t,Z as u,R as v,de as w,me as x,L as y};
|
|
2
|
+
//# sourceMappingURL=activity-DEoxFQLE.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as EncryptResult, c as PublicDecryptResult, f as UserDecryptParams, i as EncryptParams, n as EIP712TypedData, o as Handle, t as DelegatedUserDecryptParams } from "../relayer-sdk.types-
|
|
2
|
-
import { t as RelayerSDK } from "../relayer-sdk-
|
|
1
|
+
import { a as EncryptResult, c as PublicDecryptResult, f as UserDecryptParams, i as EncryptParams, n as EIP712TypedData, o as Handle, t as DelegatedUserDecryptParams } from "../relayer-sdk.types-DI4WWkTB.js";
|
|
2
|
+
import { t as RelayerSDK } from "../relayer-sdk-CVVR30IW.js";
|
|
3
3
|
import { Address, EIP1193Provider, Hex } from "viem";
|
|
4
4
|
import { PrivateKeyAccount } from "viem/accounts";
|
|
5
5
|
import { ClearValueType, InputProofBytesType, KeypairType, KmsDelegatedUserDecryptEIP712Type, ZKProofLike } from "@zama-fhe/relayer-sdk/bundle";
|
package/dist/cleartext/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as e,n as t,r as n}from"../errors-Cw9kKQJc.js";import{n as r}from"../relayer-utils-CpHWf9Jl.js";import{concat as i,createPublicClient as a,custom as o,encodePacked as s,getAddress as c,http as l,keccak256 as u,pad as d,parseAbi as f,toBytes as p,toHex as m}from"viem";import{privateKeyToAccount as h}from"viem/accounts";import{mainnet as g,sepolia as _}from"viem/chains";const v=(e,t)=>({name:`InputVerification`,version:`1`,chainId:Number(e),verifyingContract:t}),y=(e,t)=>({name:`Decryption`,version:`1`,chainId:Number(e),verifyingContract:t}),b={domain:v,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},x={domain:y,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},S={domain:y,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},C={domain:y,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},w={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},T={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},E={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(w),Object.freeze(T),Object.freeze(E),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function D(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function O(e){return typeof e==`string`?e in w:!1}function k(e){if(!O(e))throw Error(`Invalid FheType name '${e}'`);return w[e]}function A(e){if(!D(e))throw Error(`Invalid FheType id '${e}'`);let t=E[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const j=p(`ZK-w_rct`),M=p(`ZK-w_hdl`);function N(e,t){let n=Math.ceil(A(t)/8);return p(d(m(e),{size:n}))}function P(t,n,r){if(r.length!==32)throw new e(`random32 must be exactly 32 bytes`);let a=N(n,t),o=u(i([m(new Uint8Array([t])),m(a),m(r)]));return u(i([m(j),o]))}function F(t,n,r,a,o){if(!Number.isInteger(n)||n<0||n>255)throw new e(`index must be an integer between 0 and 255`);let c=u(i([m(j),t])),l=u(s([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[m(M),c,n,a,o])),d=o&18446744073709551615n;return m(BigInt(l)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(n)<<80n|d<<16n|BigInt(r)<<8n|BigInt(0),{size:32})}const I=f([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),L=f([`function plaintexts(bytes32 handle) view returns (uint256)`]),R=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],z={EIP712Domain:R,UserDecryptRequestVerification:S.types.UserDecryptRequestVerification},B={EIP712Domain:R,DelegatedUserDecryptRequestVerification:C.types.DelegatedUserDecryptRequestVerification},V={EIP712Domain:R,PublicDecryptVerification:x.types.PublicDecryptVerification},H=new Set([g.id,_.id]);function U(e,t){let n=Number(BigInt(e)>>8n&255n);return n===0?t!==0n:n===7?m(t,{size:20}):t}function W(t){if(!O(t.type))throw new e(`Unsupported FHE type
|
|
1
|
+
import{c as e,n as t,r as n}from"../errors-Cw9kKQJc.js";import{n as r}from"../relayer-utils-CpHWf9Jl.js";import{concat as i,createPublicClient as a,custom as o,encodePacked as s,getAddress as c,http as l,keccak256 as u,pad as d,parseAbi as f,toBytes as p,toHex as m}from"viem";import{privateKeyToAccount as h}from"viem/accounts";import{mainnet as g,sepolia as _}from"viem/chains";const v=(e,t)=>({name:`InputVerification`,version:`1`,chainId:Number(e),verifyingContract:t}),y=(e,t)=>({name:`Decryption`,version:`1`,chainId:Number(e),verifyingContract:t}),b={domain:v,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},x={domain:y,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},S={domain:y,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},C={domain:y,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},w={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},T={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},E={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(w),Object.freeze(T),Object.freeze(E),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function D(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function O(e){return typeof e==`string`?e in w:!1}function k(e){if(!O(e))throw Error(`Invalid FheType name '${e}'`);return w[e]}function A(e){if(!D(e))throw Error(`Invalid FheType id '${e}'`);let t=E[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const j=p(`ZK-w_rct`),M=p(`ZK-w_hdl`);function N(e,t){let n=Math.ceil(A(t)/8);return p(d(m(e),{size:n}))}function P(t,n,r){if(r.length!==32)throw new e(`random32 must be exactly 32 bytes`);let a=N(n,t),o=u(i([m(new Uint8Array([t])),m(a),m(r)]));return u(i([m(j),o]))}function F(t,n,r,a,o){if(!Number.isInteger(n)||n<0||n>255)throw new e(`index must be an integer between 0 and 255`);let c=u(i([m(j),t])),l=u(s([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[m(M),c,n,a,o])),d=o&18446744073709551615n;return m(BigInt(l)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(n)<<80n|d<<16n|BigInt(r)<<8n|BigInt(0),{size:32})}const I=f([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),L=f([`function plaintexts(bytes32 handle) view returns (uint256)`]),R=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],z={EIP712Domain:R,UserDecryptRequestVerification:S.types.UserDecryptRequestVerification},B={EIP712Domain:R,DelegatedUserDecryptRequestVerification:C.types.DelegatedUserDecryptRequestVerification},V={EIP712Domain:R,PublicDecryptVerification:x.types.PublicDecryptVerification},H=new Set([g.id,_.id]);function U(e,t){let n=Number(BigInt(e)>>8n&255n);return n===0?t!==0n:n===7?m(t,{size:20}):t}function W(t){if(!O(t.type))throw new e(`Unsupported FHE type`);let n=k(t.type),r;if(t.type===`ebool`){if(typeof t.value==`boolean`)r=t.value?1n:0n;else if(r=t.value,r!==0n&&r!==1n)throw new e(`Bool value must be 0, 1, true, or false`)}else r=t.type===`eaddress`?BigInt(c(t.value)):t.value;if(r<0n)throw new e(`Only non-negative cleartext values are supported`);let i=A(n),a=(1n<<BigInt(i))-1n;if(r>a)throw new e(`Value ${r} exceeds max ${a} for FheType ${n}`);return{fheType:n,value:r}}var G=class{#e;#t;kmsSigner;inputSigner;constructor(e){if(H.has(e.chainId))throw new t(`Cleartext mode is not allowed on chain ${e.chainId}. It is intended for local development and testing only.`);this.#e=a({transport:typeof e.network==`string`?l(e.network):o(e.network)}),this.#t=e,this.kmsSigner=h(e.kmsSignerPrivateKey??`0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91`),this.inputSigner=h(e.inputSignerPrivateKey??`0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901`)}async generateKeypair(){let e=m(crypto.getRandomValues(new Uint8Array(32))),t=m(crypto.getRandomValues(new Uint8Array(32)));for(;t===e;)t=m(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:e,privateKey:t}}async createEIP712(e,t,n,r=7){return{domain:S.domain(this.#t.chainId,this.#t.verifyingContractAddressDecryption),types:z,primaryType:`UserDecryptRequestVerification`,message:{publicKey:e,contractAddresses:t,startTimestamp:BigInt(n),durationDays:BigInt(r),extraData:`0x00`}}}async encrypt(e){let t=e.values.map(W),n=c(e.contractAddress),r=c(e.userAddress),a=t.map(({fheType:e,value:t})=>P(e,t,crypto.getRandomValues(new Uint8Array(32)))),o=u(a.length>0?i(a):`0x`),s=t.map(({fheType:e},t)=>F(o,t,e,this.#t.aclContractAddress,BigInt(this.#t.chainId))),l=t.map(({value:e})=>d(m(e),{size:32})),f=l.length>0?i(l):`0x`,h=await this.inputSigner.signTypedData({domain:b.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressInputVerification),types:{CiphertextVerification:b.types.CiphertextVerification},primaryType:`CiphertextVerification`,message:{ctHandles:s,userAddress:r,contractAddress:n,contractChainId:BigInt(this.#t.chainId),extraData:f}}),g=p(i([m(new Uint8Array([s.length])),m(new Uint8Array([1])),...s,h,f]));return{handles:s.map(e=>p(e)),inputProof:g}}async userDecrypt(e){return await this.#r(e.handles,c(e.signerAddress),c(e.contractAddress),`User`,`user decrypt`),this.#n(e.handles)}async publicDecrypt(e){let t=e,r=(await Promise.all(t.map(e=>this.#o(e)))).findIndex(e=>!e);if(r!==-1)throw new n(`Handle ${t[r]} is not allowed for public decryption`);let a=await Promise.all(t.map(e=>this.#s(e))),o=Object.fromEntries(t.map((e,t)=>[e,U(e,a[t])])),s=i(a.map(e=>d(m(e),{size:32}))),c=await this.kmsSigner.signTypedData({domain:x.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressDecryption),types:V,primaryType:`PublicDecryptVerification`,message:{ctHandles:t,decryptedResult:s,extraData:`0x`}});return{clearValues:o,abiEncodedClearValues:s,decryptionProof:i([m(new Uint8Array([1])),c])}}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){let a={publicKey:e,contractAddresses:t,delegatorAddress:c(n),startTimestamp:String(r),durationDays:String(i),extraData:`0x00`};return{domain:C.domain(BigInt(this.#t.chainId),this.#t.verifyingContractAddressDecryption),types:B,primaryType:`DelegatedUserDecryptRequestVerification`,message:a}}async delegatedUserDecrypt(e){return await this.#i(e.handles,c(e.delegatorAddress),c(e.delegateAddress),c(e.contractAddress)),this.#n(e.handles)}async requestZKProofVerification(e){throw new t(`Not implemented in cleartext mode`)}async getPublicKey(){return{publicKeyId:`mock-public-key-id`,publicKey:new Uint8Array([32])}}async getPublicParams(e){return{publicParams:new Uint8Array([32]),publicParamsId:`mock-public-params-id`}}async getAclAddress(){return this.#t.aclContractAddress}terminate(){}async#n(e){let t=await Promise.all(e.map(e=>this.#s(e)));return Object.fromEntries(e.map((e,n)=>[e,U(e,t[n])]))}async#r(e,t,r,i,a){if(t===r)throw new n(`${i} address ${t} must not equal contract address for ${a}`);let o=await Promise.all(e.flatMap(e=>[this.#a(e,t),this.#a(e,r)]));for(let s=0;s<e.length;s++){let c=o[s*2],l=o[s*2+1];if(!c)throw new n(`${i} ${t} is not authorized for ${a} of handle ${e[s]}`);if(!l)throw new n(`Contract ${r} is not authorized for ${a} of handle ${e[s]}`)}}async#i(e,t,r,i){let a=await Promise.all(e.map(e=>this.#e.readContract({address:this.#t.aclContractAddress,abi:I,functionName:`isHandleDelegatedForUserDecryption`,args:[t,r,i,e]})));for(let t=0;t<e.length;t++)if(!a[t])throw new n(`Handle ${e[t]} is not delegated for user decryption`)}async#a(e,t){return this.#e.readContract({address:this.#t.aclContractAddress,abi:I,functionName:`persistAllowed`,args:[e,t]})}async#o(e){return this.#e.readContract({address:this.#t.aclContractAddress,abi:I,functionName:`isAllowedForDecryption`,args:[e]})}async#s(e){return this.#e.readContract({address:this.#t.executorAddress,abi:L,functionName:`plaintexts`,args:[e]})}};const K={...r,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`},q={chainId:560048,network:`https://rpc.hoodi.ethpandaops.io`,gatewayChainId:r.gatewayChainId,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`,verifyingContractAddressDecryption:r.verifyingContractAddressDecryption,verifyingContractAddressInputVerification:r.verifyingContractAddressInputVerification};export{G as RelayerCleartext,K as hardhatCleartextConfig,q as hoodiCleartextConfig};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/ethers/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as EIP712TypedData, o as Handle } from "../relayer-sdk.types-
|
|
2
|
-
import { _ as WriteContractConfig, f as TransactionReceipt, o as ReadContractConfig, r as GenericSigner, u as SignerLifecycleCallbacks } from "../token.types-
|
|
3
|
-
import { i as BatchTransferData } from "../index-
|
|
1
|
+
import { n as EIP712TypedData, o as Handle } from "../relayer-sdk.types-DI4WWkTB.js";
|
|
2
|
+
import { _ as WriteContractConfig, f as TransactionReceipt, o as ReadContractConfig, r as GenericSigner, u as SignerLifecycleCallbacks } from "../token.types-DDdIZEax.js";
|
|
3
|
+
import { i as BatchTransferData } from "../index-BFPpJ8wt.js";
|
|
4
4
|
import { Abi, Address, ContractFunctionArgs, ContractFunctionName, ContractFunctionReturnType, EIP1193EventMap, EIP1193Events, EIP1193Provider, EIP1193Provider as EIP1193Provider$1, Hex, ProviderConnectInfo, ProviderMessage, ProviderRpcError } from "viem";
|
|
5
5
|
import { Signer, ethers } from "ethers";
|
|
6
6
|
|
package/dist/ethers/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{C as e,a as t,c as n,d as r,f as i,l as a,m as o,o as s,s as c,u as l,w as u,x as d}from"../erc165-BZgfzGxL.js";import{t as f}from"../transfer-batcher-uEcB2HJO.js";import{t as p}from"../eip1193-subscribe-3FLcs1me.js";import{ProviderRpcError as m,decodeFunctionResult as h,encodeFunctionData as g,getAddress as _,isHex as v}from"viem";import{BrowserProvider as y,ethers as b}from"ethers";var x=class{#e;#t;#n;constructor(e){if(`ethereum`in e){let t=new y(e.ethereum);this.#e=t.getSigner(),this.#t=t,this.#n=e.ethereum}else `signer`in e?(this.#e=Promise.resolve(e.signer),this.#t=e.signer.provider??void 0):this.#t=e.provider}async#r(){if(!this.#e)throw TypeError(`No signer configured — read-only mode`);return this.#e}#i(){if(!this.#t)throw TypeError(`Signer has no provider`);return this.#t}async getChainId(){let e=await this.#i().getNetwork();return Number(e.chainId)}async getAddress(){return _(await(await this.#r()).getAddress())}async signTypedData(e){let t=await this.#r(),{domain:n,types:r,message:i}=e,{EIP712Domain:a,...o}=r,s=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,[...t]])),c=await t.signTypedData(n,s,i);if(!v(c))throw TypeError(`Expected hex string, got: ${c}`);return c}async writeContract(e){let t=await this.#r(),n=new b.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let i=await n[e.functionName](...e.args,r);if(!v(i.hash))throw TypeError(`Expected hex string, got: ${i.hash}`);return i.hash}async readContract(e){let t=this.#i();return new b.Contract(e.address,e.abi,t)[e.functionName](...e.args)}async getBlockTimestamp(){let e=await this.#i().getBlock(`latest`);if(!e)throw Error(`Failed to fetch latest block`);if(e.timestamp
|
|
1
|
+
import{C as e,a as t,c as n,d as r,f as i,l as a,m as o,o as s,s as c,u as l,w as u,x as d}from"../erc165-BZgfzGxL.js";import{t as f}from"../transfer-batcher-uEcB2HJO.js";import{t as p}from"../eip1193-subscribe-3FLcs1me.js";import{ProviderRpcError as m,decodeFunctionResult as h,encodeFunctionData as g,getAddress as _,isHex as v}from"viem";import{BrowserProvider as y,ethers as b}from"ethers";var x=class{#e;#t;#n;constructor(e){if(`ethereum`in e){let t=new y(e.ethereum);this.#e=t.getSigner(),this.#t=t,this.#n=e.ethereum}else `signer`in e?(this.#e=Promise.resolve(e.signer),this.#t=e.signer.provider??void 0):this.#t=e.provider}async#r(){if(!this.#e)throw TypeError(`No signer configured — read-only mode`);return this.#e}#i(){if(!this.#t)throw TypeError(`Signer has no provider`);return this.#t}async getChainId(){let e=await this.#i().getNetwork();return Number(e.chainId)}async getAddress(){return _(await(await this.#r()).getAddress())}async signTypedData(e){let t=await this.#r(),{domain:n,types:r,message:i}=e,{EIP712Domain:a,...o}=r,s=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,[...t]])),c=await t.signTypedData(n,s,i);if(!v(c))throw TypeError(`Expected hex string, got: ${c}`);return c}async writeContract(e){let t=await this.#r(),n=new b.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let i=await n[e.functionName](...e.args,r);if(!v(i.hash))throw TypeError(`Expected hex string, got: ${i.hash}`);return i.hash}async readContract(e){let t=this.#i();return new b.Contract(e.address,e.abi,t)[e.functionName](...e.args)}async getBlockTimestamp(){let e=await this.#i().getBlock(`latest`);if(!e)throw Error(`Failed to fetch latest block`);if(e.timestamp===null)throw Error(`Latest block has no timestamp`);return BigInt(e.timestamp)}async waitForTransactionReceipt(e){let t=await this.#i().waitForTransaction(e);if(!t)throw Error(`Transaction receipt not found`);return{logs:t.logs.map(e=>({topics:e.topics.filter(e=>e!==null),data:e.data}))}}subscribe(e){return p(this.#n,()=>this.getAddress(),e)}};function S(e){return{to:e.address,data:g({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function C(e,t){let n=await e.call(S(t));if(!v(n))throw TypeError(`Expected hex string, got: ${n}`);return h({abi:t.abi,functionName:t.functionName,data:n})}async function w(e,t){let n=await e.sendTransaction(S(t));if(!v(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function T(e,t,n){return C(e,i(t,n))}function E(e,t,n){return C(e,s(t,n))}function D(e,t){return C(e,a(t))}function O(e,t,n){return C(e,c(t,n))}function k(e,n,r){return C(e,t(n,r))}function A(e,t,n,r,i){return w(e,o(t,n,r,i))}function j(e,t,n,r,i,a){return w(e,f(t,n,r,i,a))}function M(t,n,r,i,a,o){return w(t,e(n,r,i,a,o))}function N(e,t,n,r,i){return w(e,u(t,n,r,i))}function P(e,t,r,i,a){return w(e,n(t,r,i,a))}function F(e,t,n,r){return w(e,d(t,n,r))}function I(e,t,n,r){return w(e,l(t,n,r))}function L(e,t,n,i,a){return w(e,r(t,n,i,a))}export{x as EthersSigner,m as ProviderRpcError,T as readConfidentialBalanceOfContract,k as readSupportsInterfaceContract,D as readUnderlyingTokenContract,O as readWrapperExistsContract,E as readWrapperForTokenContract,j as writeConfidentialBatchTransferContract,A as writeConfidentialTransferContract,P as writeFinalizeUnwrapContract,F as writeSetOperatorContract,M as writeUnwrapContract,N as writeUnwrapFromBalanceContract,I as writeWrapContract,L as writeWrapETHContract};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as Handle } from "./relayer-sdk.types-
|
|
1
|
+
import { o as Handle } from "./relayer-sdk.types-DI4WWkTB.js";
|
|
2
2
|
import { Address, Hex } from "viem";
|
|
3
3
|
|
|
4
4
|
//#region src/contracts/encrypted.d.ts
|
|
@@ -5379,4 +5379,4 @@ declare function getDelegationExpiryContract(aclAddress: Address, delegatorAddre
|
|
|
5379
5379
|
};
|
|
5380
5380
|
//#endregion
|
|
5381
5381
|
export { confidentialTransferFromContract as A, finalizeUnwrapContract as C, confidentialBalanceOfContract as D, wrapETHContract as E, setFinalizeUnwrapOperatorContract as F, setOperatorContract as I, totalSupplyContract as L, isFinalizeUnwrapOperatorContract as M, isOperatorContract as N, confidentialTotalSupplyContract as O, rateContract as P, unwrapContract as R, symbolContract as S, wrapContract as T, allowanceContract as _, confidentialBatchTransferContract as a, decimalsContract as b, getUnwrapFeeContract as c, ERC7984_WRAPPER_INTERFACE_ID as d, isConfidentialTokenContract as f, wrapperExistsContract as g, getWrapperContract as h, BatchTransferData as i, deploymentCoordinatorContract as j, confidentialTransferContract as k, getWrapFeeContract as l, supportsInterfaceContract as m, getDelegationExpiryContract as n, getBatchTransferFeeContract as o, isConfidentialWrapperContract as p, revokeDelegationContract as r, getFeeRecipientContract as s, delegateForUserDecryptionContract as t, ERC7984_INTERFACE_ID as u, approveContract as v, underlyingContract as w, nameContract as x, balanceOfContract as y, unwrapFromBalanceContract as z };
|
|
5382
|
-
//# sourceMappingURL=index-
|
|
5382
|
+
//# sourceMappingURL=index-BFPpJ8wt.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { a as EncryptResult, c as PublicDecryptResult, d as RelayerWebSecurityConfig, f as UserDecryptParams, i as EncryptParams, k as GenericLogger, l as RelayerSDKStatus, n as EIP712TypedData, o as Handle, r as EncryptInput, s as NetworkType, t as DelegatedUserDecryptParams, u as RelayerWebConfig } from "./relayer-sdk.types-
|
|
2
|
-
import { A as decodeOnChainEvents, C as Topics, D as WrappedEvent, E as UnwrappedStartedEvent, F as findUnwrapRequested, I as findWrapped, M as decodeUnwrappedFinalized, N as decodeUnwrappedStarted, O as decodeConfidentialTransfer, P as decodeWrapped, S as TOKEN_TOPICS, T as UnwrappedFinalizedEvent, _ as WriteContractConfig, a as ReadContractArgs, b as OnChainEvent, c as ReadFunctionName, d as StoredCredentials, f as TransactionReceipt, g as WriteContractArgs, h as UnshieldCallbacks, i as GenericStorage, j as decodeUnwrapRequested, k as decodeOnChainEvent, l as ShieldCallbacks, m as TransferCallbacks, n as DelegatedStoredCredentials, o as ReadContractConfig, p as TransactionResult, r as GenericSigner, s as ReadContractReturnType, t as ContractAbi, u as SignerLifecycleCallbacks, v as WriteFunctionName, w as UnwrapRequestedEvent, x as RawLog, y as ConfidentialTransferEvent } from "./token.types-
|
|
3
|
-
import { A as confidentialTransferFromContract, C as finalizeUnwrapContract, D as confidentialBalanceOfContract, E as wrapETHContract, F as setFinalizeUnwrapOperatorContract, I as setOperatorContract, L as totalSupplyContract, M as isFinalizeUnwrapOperatorContract, N as isOperatorContract, O as confidentialTotalSupplyContract, P as rateContract, R as unwrapContract, S as symbolContract, T as wrapContract, _ as allowanceContract, a as confidentialBatchTransferContract, b as decimalsContract, c as getUnwrapFeeContract, d as ERC7984_WRAPPER_INTERFACE_ID, f as isConfidentialTokenContract, g as wrapperExistsContract, h as getWrapperContract, i as BatchTransferData, j as deploymentCoordinatorContract, k as confidentialTransferContract, l as getWrapFeeContract, m as supportsInterfaceContract, n as getDelegationExpiryContract, o as getBatchTransferFeeContract, p as isConfidentialWrapperContract, r as revokeDelegationContract, s as getFeeRecipientContract, t as delegateForUserDecryptionContract, u as ERC7984_INTERFACE_ID, v as approveContract, w as underlyingContract, x as nameContract, y as balanceOfContract, z as unwrapFromBalanceContract } from "./index-
|
|
4
|
-
import { t as RelayerSDK } from "./relayer-sdk-
|
|
1
|
+
import { a as EncryptResult, c as PublicDecryptResult, d as RelayerWebSecurityConfig, f as UserDecryptParams, i as EncryptParams, k as GenericLogger, l as RelayerSDKStatus, n as EIP712TypedData, o as Handle, r as EncryptInput, s as NetworkType, t as DelegatedUserDecryptParams, u as RelayerWebConfig } from "./relayer-sdk.types-DI4WWkTB.js";
|
|
2
|
+
import { A as decodeOnChainEvents, C as Topics, D as WrappedEvent, E as UnwrappedStartedEvent, F as findUnwrapRequested, I as findWrapped, M as decodeUnwrappedFinalized, N as decodeUnwrappedStarted, O as decodeConfidentialTransfer, P as decodeWrapped, S as TOKEN_TOPICS, T as UnwrappedFinalizedEvent, _ as WriteContractConfig, a as ReadContractArgs, b as OnChainEvent, c as ReadFunctionName, d as StoredCredentials, f as TransactionReceipt, g as WriteContractArgs, h as UnshieldCallbacks, i as GenericStorage, j as decodeUnwrapRequested, k as decodeOnChainEvent, l as ShieldCallbacks, m as TransferCallbacks, n as DelegatedStoredCredentials, o as ReadContractConfig, p as TransactionResult, r as GenericSigner, s as ReadContractReturnType, t as ContractAbi, u as SignerLifecycleCallbacks, v as WriteFunctionName, w as UnwrapRequestedEvent, x as RawLog, y as ConfidentialTransferEvent } from "./token.types-DDdIZEax.js";
|
|
3
|
+
import { A as confidentialTransferFromContract, C as finalizeUnwrapContract, D as confidentialBalanceOfContract, E as wrapETHContract, F as setFinalizeUnwrapOperatorContract, I as setOperatorContract, L as totalSupplyContract, M as isFinalizeUnwrapOperatorContract, N as isOperatorContract, O as confidentialTotalSupplyContract, P as rateContract, R as unwrapContract, S as symbolContract, T as wrapContract, _ as allowanceContract, a as confidentialBatchTransferContract, b as decimalsContract, c as getUnwrapFeeContract, d as ERC7984_WRAPPER_INTERFACE_ID, f as isConfidentialTokenContract, g as wrapperExistsContract, h as getWrapperContract, i as BatchTransferData, j as deploymentCoordinatorContract, k as confidentialTransferContract, l as getWrapFeeContract, m as supportsInterfaceContract, n as getDelegationExpiryContract, o as getBatchTransferFeeContract, p as isConfidentialWrapperContract, r as revokeDelegationContract, s as getFeeRecipientContract, t as delegateForUserDecryptionContract, u as ERC7984_INTERFACE_ID, v as approveContract, w as underlyingContract, x as nameContract, y as balanceOfContract, z as unwrapFromBalanceContract } from "./index-BFPpJ8wt.js";
|
|
4
|
+
import { t as RelayerSDK } from "./relayer-sdk-CVVR30IW.js";
|
|
5
5
|
import { n as MainnetConfig, r as SepoliaConfig, t as HardhatConfig } from "./relayer-utils-DsivYLt_.js";
|
|
6
|
-
import { $ as DecryptStartEvent, A as ZamaErrorCode, B as CredentialsManagerConfig, C as KeypairExpiredError, D as SigningRejectedError, E as SigningFailedError, F as ReadonlyTokenConfig, G as CredentialsCachedEvent, H as ApproveUnderlyingSubmittedEvent, I as ZERO_HANDLE, J as CredentialsExpiredEvent, K as CredentialsCreatedEvent, L as DelegatedCredentialsManager, M as BatchDecryptAsOptions, N as BatchDecryptOptions, O as TransactionRevertedError, P as ReadonlyToken, Q as DecryptErrorEvent, R as DelegatedCredentialsManagerConfig, S as InvalidKeypairError, T as RelayerRequestFailedError, U as BaseEvent, V as ApproveSubmittedEvent, W as CredentialsAllowedEvent, X as CredentialsRevokedEvent, Y as CredentialsLoadingEvent, Z as DecryptEndEvent, _ as DelegationCooldownError, _t as ZamaSDKEvents, a as ActivityType, at as ShieldSubmittedEvent, b as DelegationSelfNotAllowedError, c as parseActivityFeed, ct as TransferSubmittedEvent, d as ZamaSDKConfig, dt as UnshieldPhase2SubmittedEvent, et as EncryptEndEvent, f as Token, ft as UnwrapSubmittedEvent, g as DecryptionFailedError, gt as ZamaSDKEventType, h as ConfigurationError, ht as ZamaSDKEventListener, i as ActivityLogMetadata, it as SessionExpiredEvent, j as matchZamaError, k as ZamaError, l as sortByBlockNumber, lt as UnshieldPhase1SubmittedEvent, m as ApprovalFailedError, mt as ZamaSDKEventInput, n as ActivityDirection, nt as EncryptStartEvent, o as applyDecryptedValues, ot as TransactionErrorEvent, p as TokenConfig, pt as ZamaSDKEvent, q as CredentialsCreatingEvent, r as ActivityItem, rt as FinalizeUnwrapSubmittedEvent, s as extractEncryptedHandles, st as TransferFromSubmittedEvent, t as ActivityAmount, tt as EncryptErrorEvent, u as ZamaSDK, ut as UnshieldPhase2StartedEvent, v as DelegationExpiredError, w as NoCiphertextError, x as EncryptionFailedError, y as DelegationNotFoundError, z as CredentialsManager } from "./activity-
|
|
6
|
+
import { $ as DecryptStartEvent, A as ZamaErrorCode, B as CredentialsManagerConfig, C as KeypairExpiredError, D as SigningRejectedError, E as SigningFailedError, F as ReadonlyTokenConfig, G as CredentialsCachedEvent, H as ApproveUnderlyingSubmittedEvent, I as ZERO_HANDLE, J as CredentialsExpiredEvent, K as CredentialsCreatedEvent, L as DelegatedCredentialsManager, M as BatchDecryptAsOptions, N as BatchDecryptOptions, O as TransactionRevertedError, P as ReadonlyToken, Q as DecryptErrorEvent, R as DelegatedCredentialsManagerConfig, S as InvalidKeypairError, T as RelayerRequestFailedError, U as BaseEvent, V as ApproveSubmittedEvent, W as CredentialsAllowedEvent, X as CredentialsRevokedEvent, Y as CredentialsLoadingEvent, Z as DecryptEndEvent, _ as DelegationCooldownError, _t as ZamaSDKEvents, a as ActivityType, at as ShieldSubmittedEvent, b as DelegationSelfNotAllowedError, c as parseActivityFeed, ct as TransferSubmittedEvent, d as ZamaSDKConfig, dt as UnshieldPhase2SubmittedEvent, et as EncryptEndEvent, f as Token, ft as UnwrapSubmittedEvent, g as DecryptionFailedError, gt as ZamaSDKEventType, h as ConfigurationError, ht as ZamaSDKEventListener, i as ActivityLogMetadata, it as SessionExpiredEvent, j as matchZamaError, k as ZamaError, l as sortByBlockNumber, lt as UnshieldPhase1SubmittedEvent, m as ApprovalFailedError, mt as ZamaSDKEventInput, n as ActivityDirection, nt as EncryptStartEvent, o as applyDecryptedValues, ot as TransactionErrorEvent, p as TokenConfig, pt as ZamaSDKEvent, q as CredentialsCreatingEvent, r as ActivityItem, rt as FinalizeUnwrapSubmittedEvent, s as extractEncryptedHandles, st as TransferFromSubmittedEvent, t as ActivityAmount, tt as EncryptErrorEvent, u as ZamaSDK, ut as UnshieldPhase2StartedEvent, v as DelegationExpiredError, w as NoCiphertextError, x as EncryptionFailedError, y as DelegationNotFoundError, z as CredentialsManager } from "./activity-CV1NDmFr.js";
|
|
7
7
|
import { Address, Address as Address$1, Hex, Hex as Hex$1 } from "viem";
|
|
8
8
|
import { ClearValueType, ClearValueType as ClearValueType$1, FheTypeName, FhevmInstanceConfig, InputProofBytesType, InputProofBytesType as InputProofBytesType$1, KeypairType, KeypairType as KeypairType$1, KmsDelegatedUserDecryptEIP712Type, KmsDelegatedUserDecryptEIP712Type as KmsDelegatedUserDecryptEIP712Type$1, ZKProofLike, ZKProofLike as ZKProofLike$1 } from "@zama-fhe/relayer-sdk/bundle";
|
|
9
9
|
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as ee,t as m,u as h,v as g}from"./errors-Cw9kKQJc.js";import{t as te}from"./worker.base-client-DGGSkczN.js";import{a as ne,c as _}from"./utils-
|
|
1
|
+
import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as ee,t as m,u as h,v as g}from"./errors-Cw9kKQJc.js";import{t as te}from"./worker.base-client-DGGSkczN.js";import{a as ne,c as _}from"./utils-eIBZNA_w.js";import{a as re,i as ie,n as v,o as y,r as b,t as x}from"./relayer-utils-CpHWf9Jl.js";import{C as S,S as ae,_ as oe,a as se,b as ce,c as C,d as w,f as le,g as ue,h as T,i as de,l as E,m as D,n as fe,o as pe,p as me,r as he,s as ge,t as O,u as k,v as A,w as j,x as M,y as N}from"./erc165-BZgfzGxL.js";import{A as P,C as F,D as I,E as L,F as _e,I as ve,M as R,N as ye,O as be,P as xe,S as z,T as Se,_ as Ce,a as we,b as B,c as Te,d as Ee,f as De,g as V,h as Oe,i as ke,j as H,k as Ae,l as je,m as U,n as Me,o as Ne,p as Pe,r as Fe,s as Ie,t as Le,u as Re,v as W,w as G,x as ze,y as K}from"./activity-DEoxFQLE.js";import{t as Be}from"./transfer-batcher-uEcB2HJO.js";import{getAddress as q,hexToBigInt as Ve}from"viem";var He=`(function() {
|
|
2
2
|
//#region src/utils.ts
|
|
3
3
|
/** Normalize a un-prefixed hex payload to a 0x-prefixed \`Hex\` value. */
|
|
4
4
|
function prefixHex(value) {
|
|
@@ -52,6 +52,9 @@ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n a
|
|
|
52
52
|
//#region src/worker/relayer-sdk.worker.ts
|
|
53
53
|
let sdkInstance = null;
|
|
54
54
|
let sdkGlobal = null;
|
|
55
|
+
function unreachableFheType(_) {
|
|
56
|
+
throw new Error("Unsupported FHE type");
|
|
57
|
+
}
|
|
55
58
|
let relayerUrlBase = "";
|
|
56
59
|
let csrfTokenBase = "";
|
|
57
60
|
const CSRF_HEADER_NAME = "x-csrf-token";
|
|
@@ -133,7 +136,7 @@ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n a
|
|
|
133
136
|
async function verifyIntegrity(content, expectedHash) {
|
|
134
137
|
const encoder = new TextEncoder();
|
|
135
138
|
const hashBuffer = await crypto.subtle.digest("SHA-384", encoder.encode(content));
|
|
136
|
-
const hashHex =
|
|
139
|
+
const hashHex = [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
137
140
|
if (hashHex !== expectedHash) throw new Error(\`CDN integrity check failed: expected SHA-384 \${expectedHash}, got \${hashHex}\`);
|
|
138
141
|
}
|
|
139
142
|
/**
|
|
@@ -182,7 +185,7 @@ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n a
|
|
|
182
185
|
await loadSdkScript(cdnUrl, integrity);
|
|
183
186
|
if (!self.relayerSDK) throw new Error("Failed to load relayerSDK from CDN");
|
|
184
187
|
sdkGlobal = self.relayerSDK;
|
|
185
|
-
await sdkGlobal.initSDK(thread
|
|
188
|
+
await sdkGlobal.initSDK(thread !== null && thread !== void 0 ? { thread } : void 0);
|
|
186
189
|
const config = {
|
|
187
190
|
...fhevmConfig,
|
|
188
191
|
batchRpcCalls: false
|
|
@@ -195,6 +198,10 @@ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n a
|
|
|
195
198
|
sendError(id, type, message);
|
|
196
199
|
}
|
|
197
200
|
}
|
|
201
|
+
/** Coerce a boolean to bigint for numeric FHE types. */
|
|
202
|
+
function toBigInt(value) {
|
|
203
|
+
return typeof value === "boolean" ? value ? 1n : 0n : value;
|
|
204
|
+
}
|
|
198
205
|
/**
|
|
199
206
|
* Add a single typed value to the encrypted input builder.
|
|
200
207
|
*/
|
|
@@ -205,27 +212,27 @@ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n a
|
|
|
205
212
|
input.addBool(typeof value === "boolean" ? value : value !== 0n);
|
|
206
213
|
break;
|
|
207
214
|
case "euint8":
|
|
208
|
-
input.add8(
|
|
215
|
+
input.add8(toBigInt(value));
|
|
209
216
|
break;
|
|
210
217
|
case "euint16":
|
|
211
|
-
input.add16(
|
|
218
|
+
input.add16(toBigInt(value));
|
|
212
219
|
break;
|
|
213
220
|
case "euint32":
|
|
214
|
-
input.add32(
|
|
221
|
+
input.add32(toBigInt(value));
|
|
215
222
|
break;
|
|
216
223
|
case "euint64":
|
|
217
|
-
input.add64(
|
|
224
|
+
input.add64(toBigInt(value));
|
|
218
225
|
break;
|
|
219
226
|
case "euint128":
|
|
220
|
-
input.add128(
|
|
227
|
+
input.add128(toBigInt(value));
|
|
221
228
|
break;
|
|
222
229
|
case "euint256":
|
|
223
|
-
input.add256(
|
|
230
|
+
input.add256(toBigInt(value));
|
|
224
231
|
break;
|
|
225
232
|
case "eaddress":
|
|
226
|
-
input.addAddress(
|
|
233
|
+
input.addAddress(String(value));
|
|
227
234
|
break;
|
|
228
|
-
default:
|
|
235
|
+
default: unreachableFheType(fheType);
|
|
229
236
|
}
|
|
230
237
|
}
|
|
231
238
|
/**
|
|
@@ -273,11 +280,11 @@ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n a
|
|
|
273
280
|
* Relayer SDK errors may carry a \`status\` or \`statusCode\` property.
|
|
274
281
|
*/
|
|
275
282
|
function extractHttpStatus(error) {
|
|
276
|
-
if (error
|
|
283
|
+
if (error === null || error === void 0 || typeof error !== "object") return;
|
|
277
284
|
const e = error;
|
|
278
285
|
if (typeof e.statusCode === "number") return e.statusCode;
|
|
279
286
|
if (typeof e.status === "number") return e.status;
|
|
280
|
-
if (e.cause
|
|
287
|
+
if (e.cause !== null && e.cause !== void 0 && typeof e.cause === "object") {
|
|
281
288
|
const cause = e.cause;
|
|
282
289
|
if (typeof cause.statusCode === "number") return cause.statusCode;
|
|
283
290
|
if (typeof cause.status === "number") return cause.status;
|
|
@@ -477,12 +484,12 @@ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n a
|
|
|
477
484
|
break;
|
|
478
485
|
default: console.error("[Worker] Unknown request type:", request.type);
|
|
479
486
|
}
|
|
480
|
-
} catch (
|
|
481
|
-
const message =
|
|
487
|
+
} catch (error) {
|
|
488
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
482
489
|
sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", message);
|
|
483
490
|
}
|
|
484
491
|
};
|
|
485
492
|
//#endregion
|
|
486
493
|
})();
|
|
487
|
-
`,Ue=class extends te{constructor(e){super(e,e.logger)}createWorker(){let e=ne();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([He],{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(){return{type:`INIT`,payload:this.config}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}},We=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=`idle`;#o;#s;constructor(e){this.#s=e}get status(){return this.#a}get initError(){return this.#o}#c(e,t){this.#a=e,this.#o=t,this.#s.onStatusChange?.(e,t)}async#l(){let e=await this.#s.getChainId(),{transports:t,security:n,threads:r}=this.#s;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.#s.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.1/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},x[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`2bd5401738b74509549bed2029bbbabedd481b10ac260f66e64a4ff3723d6d704180c51e882757c56ca1840491e90e33`,logger:this.#s.logger,thread:r}}async#u(){if(this.#n)return this.#n;this.#n=this.#d();try{return await this.#n}finally{this.#n=null}}async#d(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let e=await this.#s.getChainId();return this.#i!==null&&e!==this.#i&&(this.#e?.terminate(),this.#e=null,this.#t=null),this.#i=e,this.#t||=(this.#c(`initializing`),this.#f().then(e=>(this.#c(`ready`),e)).catch(e=>{this.#t=null;let t=e instanceof a?e:new n(`Failed to initialize FHE worker`,{cause:e instanceof Error?e:void 0});throw this.#c(`error`,t),t})),this.#t}async#f(){let e=new Ue(await this.#l());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#p(){if(this.#e){let e=this.#s.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#u()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){let i=await(await this.#u()).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:re(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 y(async()=>{let e=await this.#u();await this.#p();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return y(async()=>{let t=await this.#u();return await this.#p(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return y(async()=>{let t=await this.#u();await this.#p();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.#u()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return y(async()=>{let t=await this.#u();return await this.#p(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return y(async()=>{let t=await this.#u();return await this.#p(),t.requestZKProofVerification(e)})}async getPublicKey(){return(await(await this.#u()).getPublicKey()).result}async getPublicParams(e){return(await(await this.#u()).getPublicParams(e)).result}async getAclAddress(){let e=await this.#s.getChainId(),t=Object.assign({},x[e],this.#s.transports[e]);if(!t.aclContractAddress)throw new u(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},J=class e extends V{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?q(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(E(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,r){let i=q(e),s,c,l=Date.now();try{this.emit({type:z.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:z.EncryptEnd,durationMs:Date.now()-l}),Y(()=>r?.onEncryptComplete?.())}catch(e){throw this.emit({type:z.EncryptError,error:_(e),durationMs:Date.now()-l}),e instanceof a?e:new n(`Failed to encrypt transfer amount`,{cause:e instanceof Error?e:void 0})}if(s.length===0)throw new n(`Encryption returned no handles`);try{let e=await this.signer.writeContract(D(this.address,i,s[0],c));return this.emit({type:z.TransferSubmitted,txHash:e}),Y(()=>r?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`transfer`,error:_(e)}),e instanceof a?e:new o(`Transfer transaction failed`,{cause:e instanceof Error?e:void 0})}}async confidentialTransferFrom(e,t,r,i){let s=q(e),c=q(t),l,u,d=Date.now();try{this.emit({type:z.EncryptStart}),{handles:l,inputProof:u}=await this.relayer.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.address,userAddress:s}),this.emit({type:z.EncryptEnd,durationMs:Date.now()-d}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:z.EncryptError,error:_(e),durationMs:Date.now()-d}),e instanceof a?e:new n(`Failed to encrypt transferFrom amount`,{cause:e instanceof Error?e:void 0})}if(l.length===0)throw new n(`Encryption returned no handles`);try{let e=await this.signer.writeContract(T(this.address,s,c,l[0],u));return this.emit({type:z.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`transferFrom`,error:_(e)}),e instanceof a?e:new o(`TransferFrom transaction failed`,{cause:e instanceof Error?e:void 0})}}async approve(e,t){let n=q(e);try{let e=await this.signer.writeContract(M(this.address,n,t));return this.emit({type:z.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`approve`,error:_(e)}),e instanceof a?e:new m(`Operator approval failed`,{cause:e instanceof Error?e:void 0})}}async isApproved(e,t){let n=q(e),r=t?q(t):await this.signer.getAddress();return this.signer.readContract(A(this.address,r,n))}async shield(t,n){if(await this.#n()===e.ZERO_ADDRESS)return this.shieldETH(t,t+(n?.fees??0n));let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#a(t,r===`max`,n?.callbacks);try{let e=n?.to?q(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(k(this.wrapper,e,t));return this.emit({type:z.ShieldSubmitted,txHash:r}),Y(()=>n?.callbacks?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:z.TransactionError,operation:`shield`,error:_(e)}),e instanceof a?e:new o(`Shield transaction failed`,{cause:e instanceof Error?e:void 0})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(w(this.wrapper,n,e,t??e));return this.emit({type:z.ShieldSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:z.TransactionError,operation:`shieldETH`,error:_(e)}),e instanceof a?e:new o(`Shield ETH transaction failed`,{cause:e instanceof Error?e:void 0})}}async unwrap(e){let t=await this.signer.getAddress(),r,i,s=Date.now();try{this.emit({type:z.EncryptStart}),{handles:r,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:z.EncryptEnd,durationMs:Date.now()-s})}catch(e){throw this.emit({type:z.EncryptError,error:_(e),durationMs:Date.now()-s}),e instanceof a?e:new n(`Failed to encrypt unshield amount`,{cause:e instanceof Error?e:void 0})}if(r.length===0)throw new n(`Encryption returned no handles`);try{let e=await this.signer.writeContract(S(this.address,t,t,r[0],i));return this.emit({type:z.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`unwrap`,error:_(e)}),e instanceof a?e:new o(`Unshield transaction failed`,{cause:e instanceof Error?e:void 0})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new p(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(j(this.address,e,e,t));return this.emit({type:z.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:z.TransactionError,operation:`unwrap`,error:_(e)}),e instanceof a?e:new o(`Unshield-all transaction failed`,{cause:e instanceof Error?e:void 0})}}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,r=Date.now();try{this.emit({type:z.DecryptStart});let i=await this.relayer.publicDecrypt([e]);this.emit({type:z.DecryptEnd,durationMs:Date.now()-r}),n=i.decryptionProof;try{t=Ve(i.abiEncodedClearValues)}catch{throw new p(`Cannot parse decrypted value: ${i.abiEncodedClearValues}`)}}catch(e){throw this.emit({type:z.DecryptError,error:_(e),durationMs:Date.now()-r}),e instanceof a?e:new p(`Failed to finalize unshield`,{cause:e instanceof Error?e:void 0})}try{let r=await this.signer.writeContract(C(this.wrapper,e,t,n));return this.emit({type:z.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:z.TransactionError,operation:`finalizeUnwrap`,error:_(e)}),e instanceof a?e:new o(`Failed to finalize unshield`,{cause:e instanceof Error?e:void 0})}}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(H(t,e,this.wrapper))>0n&&await this.signer.writeContract(R(t,this.wrapper,0n))}let e=await this.signer.writeContract(R(t,this.wrapper,n));return this.emit({type:z.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`approveUnderlying`,error:_(e)}),e instanceof a?e:new m(`ERC-20 approval failed`,{cause:e instanceof Error?e:void 0})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<=Date.now())throw new u(`Expiration date must be in the future`);let n=await this.getAclAddress(),r=t?BigInt(Math.floor(t.getTime()/1e3)):F;try{let t=await this.signer.writeContract(G(n,q(e),this.address,r));return this.emit({type:z.DelegationSubmitted,txHash:t}),{txHash:t,receipt:await this.signer.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:z.TransactionError,operation:`delegateDecryption`,error:_(e)}),e instanceof a?e:new o(`Delegation transaction failed`,{cause:e instanceof Error?e:void 0})}}async revokeDelegation({delegateAddress:e}){let t=await this.getAclAddress();try{let n=await this.signer.writeContract(L(t,q(e),this.address));return this.emit({type:z.RevokeDelegationSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:z.TransactionError,operation:`revokeDelegation`,error:_(e)}),e instanceof a?e:new o(`Revoke delegation transaction failed`,{cause:e instanceof Error?e:void 0})}}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 r=new Map,i=await Promise.allSettled(e.map(t));for(let t=0;t<e.length;t++){let s=i[t];if(s.status===`fulfilled`)r.set(e[t].address,s.value);else{let i=s.reason instanceof a?s.reason:new o(n,{cause:s.reason});r.set(e[t].address,i)}}return r}async#i(e,t,n){this.emit({type:z.UnshieldPhase1Submitted,txHash:e,operationId:n});let r;try{r=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof a?e:new o(`Failed to get unshield receipt`,{cause:e})}let i=U(r.logs);if(!i)throw new o(`No UnwrapRequested event found in unshield receipt`);this.emit({type:z.UnshieldPhase2Started,operationId:n}),Y(()=>t?.onFinalizing?.());let s=await this.finalizeUnwrap(i.encryptedAmount);return this.emit({type:z.UnshieldPhase2Submitted,txHash:s.txHash,operationId:n}),Y(()=>t?.onFinalizeSubmitted?.(s.txHash)),s}async#a(e,t,n){let r=await this.#n(),i=await this.signer.getAddress(),o=await this.signer.readContract(H(r,i,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(R(r,this.wrapper,0n));let i=t?2n**256n-1n:e,a=await this.signer.writeContract(R(r,this.wrapper,i));this.emit({type:z.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof a?e:new m(`ERC-20 approval failed`,{cause:e instanceof Error?e:void 0})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}var X=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;#e;#t;#n;#r=null;#i=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new B,this.#e=e.onEvent??function(){};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.#e};if(this.credentials=new K(t),this.delegatedCredentials=new W(t),this.#n=this.#a(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#e?.({type:z.TransactionError,operation:e,error:_(t),timestamp:Date.now()})})};this.#t=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#o(),this.#r=null,this.#i=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#o(),this.#r=q(e);try{this.#i=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#o(),this.#i=e;try{this.#r=await this.signer.getAddress()}catch{}t?.onChainChange?.(e)})}})}}async#a(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#r=e,this.#i=t}catch{}}async#o(){if(await this.#n,this.#r==null||this.#i==null)return;let e=await K.computeStoreKey(this.#r,this.#i);await this.sessionStorage.delete(e),this.#e?.({type:z.CredentialsRevoked,timestamp:Date.now()})}createReadonlyToken(e){return new V({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:q(e),onEvent:this.#e})}createToken(e,t){return new J({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,address:q(e),wrapper:t?q(t):void 0,onEvent:this.#e})}async allow(...e){await this.credentials.allow(...e)}async revoke(...e){await this.credentials.revoke(...e)}async revokeSession(){await this.#n;let e=this.#r??await this.signer.getAddress(),t=this.#i??await this.signer.getChainId(),n=await K.computeStoreKey(e,t);await this.sessionStorage.delete(n),this.#e?.({type:z.CredentialsRevoked,timestamp:Date.now()})}async isAllowed(){return this.credentials.isAllowed()}dispose(){this.#t?.(),this.#t=void 0}terminate(){this.dispose(),this.relayer.terminate()}},Z=class{#e=null;#t=null;#n;#r;#i=`credentials`;constructor(e=`CredentialStore`,t=1){this.#n=e,this.#r=t}#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=()=>{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 Ge=new Z;var Q=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 Ke=new Q;function $(e){return`zama:pending-unshield:${e}`}async function qe(e,t,n){await e.set($(t),n)}async function Je(e,t){return e.get($(t))}async function Ye(e,t){await e.delete($(t))}export{m as ApprovalFailedError,Q as ChromeSessionStorage,u as ConfigurationError,K as CredentialsManager,p as DecryptionFailedError,W as DelegatedCredentialsManager,s as DelegationCooldownError,t as DelegationExpiredError,d as DelegationNotFoundError,ee as DelegationSelfNotAllowedError,O as ERC7984_INTERFACE_ID,fe as ERC7984_WRAPPER_INTERFACE_ID,n as EncryptionFailedError,v as HardhatConfig,Z as IndexedDBStorage,c as InvalidKeypairError,h as KeypairExpiredError,b as MainnetConfig,B as MemoryStorage,r as NoCiphertextError,V as ReadonlyToken,i as RelayerRequestFailedError,We as RelayerWeb,ie as SepoliaConfig,f as SigningFailedError,l as SigningRejectedError,we as TOKEN_TOPICS,J as Token,Ne as Topics,o as TransactionRevertedError,Ce as ZERO_HANDLE,a as ZamaError,e as ZamaErrorCode,X as ZamaSDK,z as ZamaSDKEvents,H as allowanceContract,Le as applyDecryptedValues,R as approveContract,ye as balanceOfContract,Ke as chromeSessionStorage,Ye as clearPendingUnshield,le as confidentialBalanceOfContract,Be as confidentialBatchTransferContract,me as confidentialTotalSupplyContract,D as confidentialTransferContract,T as confidentialTransferFromContract,xe as decimalsContract,Ie as decodeConfidentialTransfer,Te as decodeOnChainEvent,je as decodeOnChainEvents,Re as decodeUnwrapRequested,Ee as decodeUnwrappedFinalized,De as decodeUnwrappedStarted,Pe as decodeWrapped,G as delegateForUserDecryptionContract,ue as deploymentCoordinatorContract,Me as extractEncryptedHandles,C as finalizeUnwrapContract,U as findUnwrapRequested,Oe as findWrapped,I as getBatchTransferFeeContract,Se as getDelegationExpiryContract,be as getFeeRecipientContract,Ae as getUnwrapFeeContract,P as getWrapFeeContract,pe as getWrapperContract,Ge as indexedDBStorage,he as isConfidentialTokenContract,de as isConfidentialWrapperContract,oe as isFinalizeUnwrapOperatorContract,A as isOperatorContract,Je as loadPendingUnshield,g as matchZamaError,ze as memoryStorage,_e as nameContract,Fe as parseActivityFeed,N as rateContract,L as revokeDelegationContract,qe as savePendingUnshield,ce as setFinalizeUnwrapOperatorContract,M as setOperatorContract,ke as sortByBlockNumber,se as supportsInterfaceContract,ve as symbolContract,ae as totalSupplyContract,E as underlyingContract,S as unwrapContract,j as unwrapFromBalanceContract,k as wrapContract,w as wrapETHContract,ge as wrapperExistsContract};
|
|
494
|
+
`,Ue=class extends te{constructor(e){super(e,e.logger)}createWorker(){let e=ne();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([He],{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(){return{type:`INIT`,payload:this.config}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}},We=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=`idle`;#o;#s;constructor(e){this.#s=e}get status(){return this.#a}get initError(){return this.#o}#c(e,t){this.#a=e,this.#o=t,this.#s.onStatusChange?.(e,t)}async#l(){let e=await this.#s.getChainId(),{transports:t,security:n,threads:r}=this.#s;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.#s.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.1/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},x[e],t[e]),csrfToken:n?.getCsrfToken?.()??``,integrity:n?.integrityCheck===!1?void 0:`2bd5401738b74509549bed2029bbbabedd481b10ac260f66e64a4ff3723d6d704180c51e882757c56ca1840491e90e33`,logger:this.#s.logger,thread:r}}async#u(){if(this.#n)return this.#n;this.#n=this.#d();try{return await this.#n}finally{this.#n=null}}async#d(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let e=await this.#s.getChainId();return this.#i!==null&&e!==this.#i&&(this.#e?.terminate(),this.#e=null,this.#t=null),this.#i=e,this.#t||=(this.#c(`initializing`),this.#f().then(e=>(this.#c(`ready`),e)).catch(e=>{this.#t=null;let t=e instanceof a?e:new n(`Failed to initialize FHE worker`,{cause:e instanceof Error?e:void 0});throw this.#c(`error`,t),t})),this.#t}async#f(){let e=new Ue(await this.#l());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#p(){if(this.#e){let e=this.#s.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#u()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){let i=await(await this.#u()).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:re(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 y(async()=>{let e=await this.#u();await this.#p();let i=await e.encrypt({values:t,contractAddress:n,userAddress:r});return{handles:i.handles,inputProof:i.inputProof}})}async userDecrypt(e){return y(async()=>{let t=await this.#u();return await this.#p(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return y(async()=>{let t=await this.#u();await this.#p();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.#u()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return y(async()=>{let t=await this.#u();return await this.#p(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return y(async()=>{let t=await this.#u();return await this.#p(),t.requestZKProofVerification(e)})}async getPublicKey(){return(await(await this.#u()).getPublicKey()).result}async getPublicParams(e){return(await(await this.#u()).getPublicParams(e)).result}async getAclAddress(){let e=await this.#s.getChainId(),t=Object.assign({},x[e],this.#s.transports[e]);if(!t.aclContractAddress)throw new u(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},J=class e extends V{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?q(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(E(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,r){let i=q(e),s,c,l=Date.now();try{this.emit({type:z.EncryptStart}),{handles:s,inputProof:c}=await this.relayer.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:z.EncryptEnd,durationMs:Date.now()-l}),Y(()=>r?.onEncryptComplete?.())}catch(e){throw this.emit({type:z.EncryptError,error:_(e),durationMs:Date.now()-l}),e instanceof a?e:new n(`Failed to encrypt transfer amount`,{cause:e instanceof Error?e:void 0})}if(s.length===0)throw new n(`Encryption returned no handles`);try{let e=await this.signer.writeContract(D(this.address,i,s[0],c));return this.emit({type:z.TransferSubmitted,txHash:e}),Y(()=>r?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`transfer`,error:_(e)}),e instanceof a?e:new o(`Transfer transaction failed`,{cause:e instanceof Error?e:void 0})}}async confidentialTransferFrom(e,t,r,i){let s=q(e),c=q(t),l,u,d=Date.now();try{this.emit({type:z.EncryptStart}),{handles:l,inputProof:u}=await this.relayer.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.address,userAddress:s}),this.emit({type:z.EncryptEnd,durationMs:Date.now()-d}),Y(()=>i?.onEncryptComplete?.())}catch(e){throw this.emit({type:z.EncryptError,error:_(e),durationMs:Date.now()-d}),e instanceof a?e:new n(`Failed to encrypt transferFrom amount`,{cause:e instanceof Error?e:void 0})}if(l.length===0)throw new n(`Encryption returned no handles`);try{let e=await this.signer.writeContract(T(this.address,s,c,l[0],u));return this.emit({type:z.TransferFromSubmitted,txHash:e}),Y(()=>i?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`transferFrom`,error:_(e)}),e instanceof a?e:new o(`TransferFrom transaction failed`,{cause:e instanceof Error?e:void 0})}}async approve(e,t){let n=q(e);try{let e=await this.signer.writeContract(M(this.address,n,t));return this.emit({type:z.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`approve`,error:_(e)}),e instanceof a?e:new m(`Operator approval failed`,{cause:e instanceof Error?e:void 0})}}async isApproved(e,t){let n=q(e),r=t?q(t):await this.signer.getAddress();return this.signer.readContract(A(this.address,r,n))}async shield(t,n){if(await this.#n()===e.ZERO_ADDRESS)return this.shieldETH(t,t+(n?.fees??0n));let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#a(t,r===`max`,n?.callbacks);try{let e=n?.to?q(n.to):await this.signer.getAddress(),r=await this.signer.writeContract(k(this.wrapper,e,t));return this.emit({type:z.ShieldSubmitted,txHash:r}),Y(()=>n?.callbacks?.onShieldSubmitted?.(r)),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:z.TransactionError,operation:`shield`,error:_(e)}),e instanceof a?e:new o(`Shield transaction failed`,{cause:e instanceof Error?e:void 0})}}async shieldETH(e,t){try{let n=await this.signer.getAddress(),r=await this.signer.writeContract(w(this.wrapper,n,e,t??e));return this.emit({type:z.ShieldSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:z.TransactionError,operation:`shieldETH`,error:_(e)}),e instanceof a?e:new o(`Shield ETH transaction failed`,{cause:e instanceof Error?e:void 0})}}async unwrap(e){let t=await this.signer.getAddress(),r,i,s=Date.now();try{this.emit({type:z.EncryptStart}),{handles:r,inputProof:i}=await this.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:t}),this.emit({type:z.EncryptEnd,durationMs:Date.now()-s})}catch(e){throw this.emit({type:z.EncryptError,error:_(e),durationMs:Date.now()-s}),e instanceof a?e:new n(`Failed to encrypt unshield amount`,{cause:e instanceof Error?e:void 0})}if(r.length===0)throw new n(`Encryption returned no handles`);try{let e=await this.signer.writeContract(S(this.address,t,t,r[0],i));return this.emit({type:z.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`unwrap`,error:_(e)}),e instanceof a?e:new o(`Unshield transaction failed`,{cause:e instanceof Error?e:void 0})}}async unwrapAll(){let e=await this.signer.getAddress(),t=await this.readConfidentialBalanceOf(e);if(this.isZeroHandle(t))throw new p(`Cannot unshield: balance is zero`);try{let n=await this.signer.writeContract(j(this.address,e,e,t));return this.emit({type:z.UnwrapSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:z.TransactionError,operation:`unwrap`,error:_(e)}),e instanceof a?e:new o(`Unshield-all transaction failed`,{cause:e instanceof Error?e:void 0})}}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,r=Date.now();try{this.emit({type:z.DecryptStart});let i=await this.relayer.publicDecrypt([e]);this.emit({type:z.DecryptEnd,durationMs:Date.now()-r}),n=i.decryptionProof;try{t=Ve(i.abiEncodedClearValues)}catch{throw new p(`Cannot parse decrypted value: ${i.abiEncodedClearValues}`)}}catch(e){throw this.emit({type:z.DecryptError,error:_(e),durationMs:Date.now()-r}),e instanceof a?e:new p(`Failed to finalize unshield`,{cause:e instanceof Error?e:void 0})}try{let r=await this.signer.writeContract(C(this.wrapper,e,t,n));return this.emit({type:z.FinalizeUnwrapSubmitted,txHash:r}),{txHash:r,receipt:await this.signer.waitForTransactionReceipt(r)}}catch(e){throw this.emit({type:z.TransactionError,operation:`finalizeUnwrap`,error:_(e)}),e instanceof a?e:new o(`Failed to finalize unshield`,{cause:e instanceof Error?e:void 0})}}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(H(t,e,this.wrapper))>0n&&await this.signer.writeContract(R(t,this.wrapper,0n))}let e=await this.signer.writeContract(R(t,this.wrapper,n));return this.emit({type:z.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:z.TransactionError,operation:`approveUnderlying`,error:_(e)}),e instanceof a?e:new m(`ERC-20 approval failed`,{cause:e instanceof Error?e:void 0})}}async delegateDecryption({delegateAddress:e,expirationDate:t}){if(t&&t.getTime()<=Date.now())throw new u(`Expiration date must be in the future`);let n=await this.getAclAddress(),r=t?BigInt(Math.floor(t.getTime()/1e3)):F;try{let t=await this.signer.writeContract(G(n,q(e),this.address,r));return this.emit({type:z.DelegationSubmitted,txHash:t}),{txHash:t,receipt:await this.signer.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:z.TransactionError,operation:`delegateDecryption`,error:_(e)}),e instanceof a?e:new o(`Delegation transaction failed`,{cause:e instanceof Error?e:void 0})}}async revokeDelegation({delegateAddress:e}){let t=await this.getAclAddress();try{let n=await this.signer.writeContract(L(t,q(e),this.address));return this.emit({type:z.RevokeDelegationSubmitted,txHash:n}),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(e){throw this.emit({type:z.TransactionError,operation:`revokeDelegation`,error:_(e)}),e instanceof a?e:new o(`Revoke delegation transaction failed`,{cause:e instanceof Error?e:void 0})}}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 r=new Map,i=await Promise.allSettled(e.map(t));for(let t=0;t<e.length;t++){let s=i[t];if(s.status===`fulfilled`)r.set(e[t].address,s.value);else{let i=s.reason instanceof a?s.reason:new o(n,{cause:s.reason});r.set(e[t].address,i)}}return r}async#i(e,t,n){this.emit({type:z.UnshieldPhase1Submitted,txHash:e,operationId:n});let r;try{r=await this.signer.waitForTransactionReceipt(e)}catch(e){throw e instanceof a?e:new o(`Failed to get unshield receipt`,{cause:e})}let i=U(r.logs);if(!i)throw new o(`No UnwrapRequested event found in unshield receipt`);this.emit({type:z.UnshieldPhase2Started,operationId:n}),Y(()=>t?.onFinalizing?.());let s=await this.finalizeUnwrap(i.encryptedAmount);return this.emit({type:z.UnshieldPhase2Submitted,txHash:s.txHash,operationId:n}),Y(()=>t?.onFinalizeSubmitted?.(s.txHash)),s}async#a(e,t,n){let r=await this.#n(),i=await this.signer.getAddress(),o=await this.signer.readContract(H(r,i,this.wrapper));if(!(o>=e))try{o>0n&&await this.signer.writeContract(R(r,this.wrapper,0n));let i=t?2n**256n-1n:e,a=await this.signer.writeContract(R(r,this.wrapper,i));this.emit({type:z.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>n?.onApprovalSubmitted?.(a))}catch(e){throw e instanceof a?e:new m(`ERC-20 approval failed`,{cause:e instanceof Error?e:void 0})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}var X=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;#e;#t;#n;#r=null;#i=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new B,this.#e=e.onEvent??function(){};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.#e};if(this.credentials=new K(t),this.delegatedCredentials=new W(t),this.#n=this.#a(),this.signer.subscribe){let t=e.signerLifecycleCallbacks,n=(e,t)=>{t().catch(t=>{this.#e?.({type:z.TransactionError,operation:e,error:_(t),timestamp:Date.now()})})};this.#t=this.signer.subscribe({onDisconnect:()=>{n(`signerDisconnect`,async()=>{await this.#o(),this.#r=null,this.#i=null,t?.onDisconnect?.()})},onAccountChange:e=>{n(`signerAccountChange`,async()=>{await this.#o(),this.#r=q(e);try{this.#i=await this.signer.getChainId()}catch{}t?.onAccountChange?.(e)})},onChainChange:e=>{n(`signerChainChange`,async()=>{await this.#o(),this.#i=e;try{this.#r=await this.signer.getAddress()}catch{}t?.onChainChange?.(e)})}})}}async#a(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#r=e,this.#i=t}catch{}}async#o(){if(await this.#n,this.#r===null||this.#r===void 0||this.#i===null||this.#i===void 0)return;let e=await K.computeStoreKey(this.#r,this.#i);await this.sessionStorage.delete(e),this.#e?.({type:z.CredentialsRevoked,timestamp:Date.now()})}createReadonlyToken(e){return new V({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:q(e),onEvent:this.#e})}createToken(e,t){return new J({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,address:q(e),wrapper:t?q(t):void 0,onEvent:this.#e})}async allow(...e){await this.credentials.allow(...e)}async revoke(...e){await this.credentials.revoke(...e)}async revokeSession(){await this.#n;let e=this.#r??await this.signer.getAddress(),t=this.#i??await this.signer.getChainId(),n=await K.computeStoreKey(e,t);await this.sessionStorage.delete(n),this.#e?.({type:z.CredentialsRevoked,timestamp:Date.now()})}async isAllowed(){return this.credentials.isAllowed()}dispose(){this.#t?.(),this.#t=void 0}terminate(){this.dispose(),this.relayer.terminate()}},Z=class{#e=null;#t=null;#n;#r;#i=`credentials`;constructor(e=`CredentialStore`,t=1){this.#n=e,this.#r=t}#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=()=>{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 Ge=new Z;var Q=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 Ke=new Q;function $(e){return`zama:pending-unshield:${e}`}async function qe(e,t,n){await e.set($(t),n)}async function Je(e,t){return e.get($(t))}async function Ye(e,t){await e.delete($(t))}export{m as ApprovalFailedError,Q as ChromeSessionStorage,u as ConfigurationError,K as CredentialsManager,p as DecryptionFailedError,W as DelegatedCredentialsManager,s as DelegationCooldownError,t as DelegationExpiredError,d as DelegationNotFoundError,ee as DelegationSelfNotAllowedError,O as ERC7984_INTERFACE_ID,fe as ERC7984_WRAPPER_INTERFACE_ID,n as EncryptionFailedError,v as HardhatConfig,Z as IndexedDBStorage,c as InvalidKeypairError,h as KeypairExpiredError,b as MainnetConfig,B as MemoryStorage,r as NoCiphertextError,V as ReadonlyToken,i as RelayerRequestFailedError,We as RelayerWeb,ie as SepoliaConfig,f as SigningFailedError,l as SigningRejectedError,we as TOKEN_TOPICS,J as Token,Ne as Topics,o as TransactionRevertedError,Ce as ZERO_HANDLE,a as ZamaError,e as ZamaErrorCode,X as ZamaSDK,z as ZamaSDKEvents,H as allowanceContract,Le as applyDecryptedValues,R as approveContract,ye as balanceOfContract,Ke as chromeSessionStorage,Ye as clearPendingUnshield,le as confidentialBalanceOfContract,Be as confidentialBatchTransferContract,me as confidentialTotalSupplyContract,D as confidentialTransferContract,T as confidentialTransferFromContract,xe as decimalsContract,Ie as decodeConfidentialTransfer,Te as decodeOnChainEvent,je as decodeOnChainEvents,Re as decodeUnwrapRequested,Ee as decodeUnwrappedFinalized,De as decodeUnwrappedStarted,Pe as decodeWrapped,G as delegateForUserDecryptionContract,ue as deploymentCoordinatorContract,Me as extractEncryptedHandles,C as finalizeUnwrapContract,U as findUnwrapRequested,Oe as findWrapped,I as getBatchTransferFeeContract,Se as getDelegationExpiryContract,be as getFeeRecipientContract,Ae as getUnwrapFeeContract,P as getWrapFeeContract,pe as getWrapperContract,Ge as indexedDBStorage,he as isConfidentialTokenContract,de as isConfidentialWrapperContract,oe as isFinalizeUnwrapOperatorContract,A as isOperatorContract,Je as loadPendingUnshield,g as matchZamaError,ze as memoryStorage,_e as nameContract,Fe as parseActivityFeed,N as rateContract,L as revokeDelegationContract,qe as savePendingUnshield,ce as setFinalizeUnwrapOperatorContract,M as setOperatorContract,ke as sortByBlockNumber,se as supportsInterfaceContract,ve as symbolContract,ae as totalSupplyContract,E as underlyingContract,S as unwrapContract,j as unwrapFromBalanceContract,k as wrapContract,w as wrapETHContract,ge as wrapperExistsContract};
|
|
488
495
|
//# sourceMappingURL=index.js.map
|
package/dist/node/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { A as GetPublicKeyRequest, B as SuccessResponse, C as EncryptPayload, D as GenerateKeypairRequest, E as ErrorResponse, F as NodeInitRequest, G as WorkerRequest, H as UserDecryptPayload, I as PublicDecryptRequest, K as WorkerRequestType, L as PublicDecryptResponseData, M as GetPublicParamsRequest, N as GetPublicParamsResponseData, O as GenerateKeypairResponseData, P as InitRequest, R as RequestZKProofVerificationRequest, S as DelegatedUserDecryptResponseData, T as EncryptResponseData, U as UserDecryptRequest, V as UpdateCsrfRequest, W as UserDecryptResponseData, _ as CreateEIP712Payload, a as EncryptResult, b as DelegatedUserDecryptPayload, c as PublicDecryptResult, f as UserDecryptParams, g as CreateDelegatedEIP712ResponseData, h as CreateDelegatedEIP712Request, i as EncryptParams, j as GetPublicKeyResponseData, k as GenericLogger, m as CreateDelegatedEIP712Payload, n as EIP712TypedData, o as Handle, p as BaseRequest, q as WorkerResponse, t as DelegatedUserDecryptParams, v as CreateEIP712Request, w as EncryptRequest, x as DelegatedUserDecryptRequest, y as CreateEIP712ResponseData, z as RequestZKProofVerificationResponseData } from "../relayer-sdk.types-
|
|
2
|
-
import { i as GenericStorage } from "../token.types-
|
|
3
|
-
import { t as RelayerSDK } from "../relayer-sdk-
|
|
1
|
+
import { A as GetPublicKeyRequest, B as SuccessResponse, C as EncryptPayload, D as GenerateKeypairRequest, E as ErrorResponse, F as NodeInitRequest, G as WorkerRequest, H as UserDecryptPayload, I as PublicDecryptRequest, K as WorkerRequestType, L as PublicDecryptResponseData, M as GetPublicParamsRequest, N as GetPublicParamsResponseData, O as GenerateKeypairResponseData, P as InitRequest, R as RequestZKProofVerificationRequest, S as DelegatedUserDecryptResponseData, T as EncryptResponseData, U as UserDecryptRequest, V as UpdateCsrfRequest, W as UserDecryptResponseData, _ as CreateEIP712Payload, a as EncryptResult, b as DelegatedUserDecryptPayload, c as PublicDecryptResult, f as UserDecryptParams, g as CreateDelegatedEIP712ResponseData, h as CreateDelegatedEIP712Request, i as EncryptParams, j as GetPublicKeyResponseData, k as GenericLogger, m as CreateDelegatedEIP712Payload, n as EIP712TypedData, o as Handle, p as BaseRequest, q as WorkerResponse, t as DelegatedUserDecryptParams, v as CreateEIP712Request, w as EncryptRequest, x as DelegatedUserDecryptRequest, y as CreateEIP712ResponseData, z as RequestZKProofVerificationResponseData } from "../relayer-sdk.types-DI4WWkTB.js";
|
|
2
|
+
import { i as GenericStorage } from "../token.types-DDdIZEax.js";
|
|
3
|
+
import { t as RelayerSDK } from "../relayer-sdk-CVVR30IW.js";
|
|
4
4
|
import { n as MainnetConfig, r as SepoliaConfig, t as HardhatConfig } from "../relayer-utils-DsivYLt_.js";
|
|
5
5
|
import { Address, Hex } from "viem";
|
|
6
6
|
import { Worker } from "node:worker_threads";
|
package/dist/node/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as e,g as t,n}from"../errors-Cw9kKQJc.js";import{t as r}from"../worker.base-client-DGGSkczN.js";import{a as i,i as a,n as o,o as s,r as c,t as l}from"../relayer-utils-CpHWf9Jl.js";import{availableParallelism as u}from"node:os";import{Worker as d}from"node:worker_threads";import{randomUUID as f}from"node:crypto";import{AsyncLocalStorage as p}from"node:async_hooks";var m=class extends r{constructor(e){super(e,e.logger)}createWorker(){return new d(new URL(
|
|
1
|
+
import{c as e,g as t,n}from"../errors-Cw9kKQJc.js";import{t as r}from"../worker.base-client-DGGSkczN.js";import{a as i,i as a,n as o,o as s,r as c,t as l}from"../relayer-utils-CpHWf9Jl.js";import{availableParallelism as u}from"node:os";import{Worker as d}from"node:worker_threads";import{randomUUID as f}from"node:crypto";import{AsyncLocalStorage as p}from"node:async_hooks";var m=class extends r{constructor(e){super(e,e.logger)}createWorker(){return new d(new URL(`relayer-sdk.node-worker.js`,import.meta.url))}wireEvents(e){e.on(`message`,e=>this.handleResponse(e)),e.on(`error`,e=>this.handleWorkerError(e.message)),e.on(`messageerror`,()=>this.handleWorkerMessageError())}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return f()}getInitPayload(){return{type:`NODE_INIT`,payload:{fhevmConfig:this.config.fhevmConfig}}}onWorkerReady(e){e.unref()}},h=class{#e=[];#t=[];#n;#r;#i=null;constructor(e){this.#n=e,this.#r=e.poolSize??Math.min(u(),4)}get poolSize(){return this.#r}async initPool(){if(!(this.#e.length>0))return this.#i||=this.#a().finally(()=>{this.#i=null}),this.#i}async#a(){for(let e=0;e<this.#r;e++)this.#e.push(new m(this.#n)),this.#t.push(0);try{await Promise.all(this.#e.map(e=>e.initWorker()))}catch(e){for(let e of this.#e)e.terminate();throw this.#e.length=0,this.#t.length=0,e}}terminate(){for(let e of this.#e)e.terminate();this.#e.length=0,this.#t.length=0}#o(){let e=0,t=this.#t[0];for(let n=1;n<this.#t.length;n++)this.#t[n]<t&&(t=this.#t[n],e=n);return e}async#s(e){if(this.#e.length===0)throw Error(`NodeWorkerPool not initialized. Call initPool() first.`);let t=this.#o();this.#t[t]++;try{return await e(this.#e[t])}finally{this.#t[t]--}}async generateKeypair(){return this.#s(e=>e.generateKeypair())}async createEIP712(e){return this.#s(t=>t.createEIP712(e))}async encrypt(e){return this.#s(t=>t.encrypt(e))}async userDecrypt(e){return this.#s(t=>t.userDecrypt(e))}async publicDecrypt(e){return this.#s(t=>t.publicDecrypt(e))}async createDelegatedUserDecryptEIP712(e){return this.#s(t=>t.createDelegatedUserDecryptEIP712(e))}async delegatedUserDecrypt(e){return this.#s(t=>t.delegatedUserDecrypt(e))}async requestZKProofVerification(e){return this.#s(t=>t.requestZKProofVerification(e))}async getPublicKey(){return this.#s(e=>e.getPublicKey())}async getPublicParams(e){return this.#s(t=>t.getPublicParams(e))}},g=class{#e;#t=null;#n=null;#r=null;#i=!1;#a=null;constructor(e){this.#e=e}async#o(){let e=await this.#e.getChainId(),{transports:t,poolSize:n}=this.#e;return{fhevmConfig:Object.assign({},l[e],t[e]),poolSize:n,logger:this.#e.logger}}async#s(){if(this.#r)return this.#r;this.#r=this.#c();try{return await this.#r}finally{this.#r=null}}async#c(){if(this.#i)throw new e(`RelayerNode has been terminated`);let n=await this.#e.getChainId();return this.#a!==null&&n!==this.#a&&(this.#t?.terminate(),this.#t=null,this.#n=null),this.#a=n,this.#n||=this.#l().catch(n=>{throw this.#n=null,n instanceof t?n:new e(`Failed to initialize FHE worker pool`,{cause:n instanceof Error?n:void 0})}),this.#n}async#l(){let e=new h(await this.#o());if(await e.initPool(),this.#i)throw e.terminate(),Error(`RelayerNode was terminated during initialization`);return this.#t=e,e}terminate(){this.#i=!0,this.#t&&=(this.#t.terminate(),null),this.#n=null,this.#r=null}async generateKeypair(){let e=await(await this.#s()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,n,r=7){let a=await(await this.#s()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:i(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){return s(async()=>{let t=await(await this.#s()).encrypt(e);return{handles:t.handles,inputProof:t.inputProof}})}async userDecrypt(e){return s(async()=>(await(await this.#s()).userDecrypt(e)).clearValues)}async publicDecrypt(e){return s(async()=>{let t=await(await this.#s()).publicDecrypt(e);return{clearValues:t.clearValues,abiEncodedClearValues:t.abiEncodedClearValues,decryptionProof:t.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#s()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return s(async()=>(await(await this.#s()).delegatedUserDecrypt(e)).clearValues)}async requestZKProofVerification(e){return s(async()=>(await this.#s()).requestZKProofVerification(e))}async getPublicKey(){return(await(await this.#s()).getPublicKey()).result}async getPublicParams(e){return(await(await this.#s()).getPublicParams(e)).result}async getAclAddress(){let e=await this.#e.getChainId(),t=Object.assign({},l[e],this.#e.transports[e]);if(!t.aclContractAddress)throw new n(`No ACL address configured for chain ${e}`);return t.aclContractAddress}},_=class{#e=new p;run(e){return this.#e.run(new Map,e)}async get(e){return this.#e.getStore()?.get(e)??null}async set(e,t){this.#e.getStore()?.set(e,t)}async delete(e){this.#e.getStore()?.delete(e)}};const v=new _;export{_ as AsyncLocalMapStorage,r as BaseWorkerClient,o as HardhatConfig,c as MainnetConfig,m as NodeWorkerClient,h as NodeWorkerPool,g as RelayerNode,a as SepoliaConfig,v as asyncLocalStorage};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as EncryptResult, c as PublicDecryptResult, f as UserDecryptParams, i as EncryptParams, n as EIP712TypedData, o as Handle, r as EncryptInput, t as DelegatedUserDecryptParams } from "../relayer-sdk.types-
|
|
2
|
-
import { D as WrappedEvent, E as UnwrappedStartedEvent, T as UnwrappedFinalizedEvent, b as OnChainEvent, d as StoredCredentials, f as TransactionReceipt, h as UnshieldCallbacks, i as GenericStorage, l as ShieldCallbacks, m as TransferCallbacks, p as TransactionResult, r as GenericSigner, u as SignerLifecycleCallbacks, w as UnwrapRequestedEvent, x as RawLog, y as ConfidentialTransferEvent } from "../token.types-
|
|
3
|
-
import { t as RelayerSDK } from "../relayer-sdk-
|
|
4
|
-
import { $ as DecryptStartEvent, B as CredentialsManagerConfig, F as ReadonlyTokenConfig, G as CredentialsCachedEvent, H as ApproveUnderlyingSubmittedEvent, J as CredentialsExpiredEvent, K as CredentialsCreatedEvent, M as BatchDecryptAsOptions, N as BatchDecryptOptions, P as ReadonlyToken, Q as DecryptErrorEvent, U as BaseEvent, V as ApproveSubmittedEvent, W as CredentialsAllowedEvent, X as CredentialsRevokedEvent, Y as CredentialsLoadingEvent, Z as DecryptEndEvent, _t as ZamaSDKEvents, a as ActivityType, at as ShieldSubmittedEvent, ct as TransferSubmittedEvent, d as ZamaSDKConfig, dt as UnshieldPhase2SubmittedEvent, et as EncryptEndEvent, f as Token, ft as UnwrapSubmittedEvent, ht as ZamaSDKEventListener, i as ActivityLogMetadata, lt as UnshieldPhase1SubmittedEvent, mt as ZamaSDKEventInput, n as ActivityDirection, nt as EncryptStartEvent, ot as TransactionErrorEvent, p as TokenConfig, pt as ZamaSDKEvent, q as CredentialsCreatingEvent, r as ActivityItem, rt as FinalizeUnwrapSubmittedEvent, st as TransferFromSubmittedEvent, t as ActivityAmount, tt as EncryptErrorEvent, u as ZamaSDK, ut as UnshieldPhase2StartedEvent, z as CredentialsManager } from "../activity-
|
|
1
|
+
import { a as EncryptResult, c as PublicDecryptResult, f as UserDecryptParams, i as EncryptParams, n as EIP712TypedData, o as Handle, r as EncryptInput, t as DelegatedUserDecryptParams } from "../relayer-sdk.types-DI4WWkTB.js";
|
|
2
|
+
import { D as WrappedEvent, E as UnwrappedStartedEvent, T as UnwrappedFinalizedEvent, b as OnChainEvent, d as StoredCredentials, f as TransactionReceipt, h as UnshieldCallbacks, i as GenericStorage, l as ShieldCallbacks, m as TransferCallbacks, p as TransactionResult, r as GenericSigner, u as SignerLifecycleCallbacks, w as UnwrapRequestedEvent, x as RawLog, y as ConfidentialTransferEvent } from "../token.types-DDdIZEax.js";
|
|
3
|
+
import { t as RelayerSDK } from "../relayer-sdk-CVVR30IW.js";
|
|
4
|
+
import { $ as DecryptStartEvent, B as CredentialsManagerConfig, F as ReadonlyTokenConfig, G as CredentialsCachedEvent, H as ApproveUnderlyingSubmittedEvent, J as CredentialsExpiredEvent, K as CredentialsCreatedEvent, M as BatchDecryptAsOptions, N as BatchDecryptOptions, P as ReadonlyToken, Q as DecryptErrorEvent, U as BaseEvent, V as ApproveSubmittedEvent, W as CredentialsAllowedEvent, X as CredentialsRevokedEvent, Y as CredentialsLoadingEvent, Z as DecryptEndEvent, _t as ZamaSDKEvents, a as ActivityType, at as ShieldSubmittedEvent, ct as TransferSubmittedEvent, d as ZamaSDKConfig, dt as UnshieldPhase2SubmittedEvent, et as EncryptEndEvent, f as Token, ft as UnwrapSubmittedEvent, ht as ZamaSDKEventListener, i as ActivityLogMetadata, lt as UnshieldPhase1SubmittedEvent, mt as ZamaSDKEventInput, n as ActivityDirection, nt as EncryptStartEvent, ot as TransactionErrorEvent, p as TokenConfig, pt as ZamaSDKEvent, q as CredentialsCreatingEvent, r as ActivityItem, rt as FinalizeUnwrapSubmittedEvent, st as TransferFromSubmittedEvent, t as ActivityAmount, tt as EncryptErrorEvent, u as ZamaSDK, ut as UnshieldPhase2StartedEvent, z as CredentialsManager } from "../activity-CV1NDmFr.js";
|
|
5
5
|
import { Address, Hex } from "viem";
|
|
6
6
|
import { QueryKey, QueryObserverOptions, skipToken } from "@tanstack/query-core";
|
|
7
7
|
|
package/dist/query/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"../errors-Cw9kKQJc.js";import{S as t,f as n,i as r,l as i,o as a,r as o,s,v as c}from"../erc165-BZgfzGxL.js";import{A as l,C as u,D as d,F as f,I as p,O as ee,P as te,S as m,g as h,i as g,j as _,k as v,n as y,r as b,t as x}from"../activity-BlZy4dNC.js";import{getAddress as S}from"viem";function ne(e){if(!C(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!C(n)||!n.hasOwnProperty(`isPrototypeOf`))}function C(e){return Object.prototype.toString.call(e)===`[object Object]`}const re=`0x0000000000000000000000000000000000000000000000000000000000000000`;function w(e){let{gcTime:t,staleTime:n,enabled:r,select:i,refetchInterval:a,refetchOnMount:o,refetchOnWindowFocus:s,refetchOnReconnect:c,retry:l,retryDelay:u,retryOnMount:d,queryFn:f,queryKey:p,queryKeyHashFn:ee,initialData:te,initialDataUpdatedAt:m,placeholderData:h,structuralSharing:g,throwOnError:_,meta:v,query:y,pollingInterval:b,...x}=e;return x}function T(e){return JSON.stringify(e,(e,t)=>ne(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):typeof t==`bigint`?t.toString():t)}const E=e=>e.map(e=>S(e)),D={signerAddress:{all:[`zama.signerAddress`],scope:e=>[`zama.signerAddress`,{scope:e}],token:e=>[`zama.signerAddress`,{tokenAddress:S(e)}]},confidentialHandle:{all:[`zama.confidentialHandle`],token:e=>[`zama.confidentialHandle`,{tokenAddress:S(e)}],owner:(e,t)=>[`zama.confidentialHandle`,{tokenAddress:S(e),...t?{owner:S(t)}:{}}]},confidentialBalance:{all:[`zama.confidentialBalance`],token:e=>[`zama.confidentialBalance`,{tokenAddress:S(e)}],owner:(e,t,n)=>[`zama.confidentialBalance`,{tokenAddress:S(e),...t?{owner:S(t)}:{},...n===void 0?{}:{handle:n}}]},confidentialHandles:{all:[`zama.confidentialHandles`],tokens:(e,t)=>[`zama.confidentialHandles`,{tokenAddresses:E(e),...t?{owner:S(t)}:{}}]},confidentialBalances:{all:[`zama.confidentialBalances`],tokens:(e,t,n)=>[`zama.confidentialBalances`,{tokenAddresses:E(e),...t?{owner:S(t)}:{},...n===void 0?{}:{handles:n}}]},tokenMetadata:{all:[`zama.tokenMetadata`],token:e=>[`zama.tokenMetadata`,{tokenAddress:S(e)}]},isConfidential:{all:[`zama.isConfidential`],token:e=>[`zama.isConfidential`,{tokenAddress:S(e)}]},isWrapper:{all:[`zama.isWrapper`],token:e=>[`zama.isWrapper`,{tokenAddress:S(e)}]},wrapperDiscovery:{all:[`zama.wrapperDiscovery`],token:(e,t)=>[`zama.wrapperDiscovery`,{tokenAddress:S(e),coordinatorAddress:S(t)}]},underlyingAllowance:{all:[`zama.underlyingAllowance`],token:e=>[`zama.underlyingAllowance`,{tokenAddress:S(e)}],scope:(e,t,n)=>[`zama.underlyingAllowance`,{tokenAddress:S(e),...t?{owner:S(t)}:{},...n?{wrapperAddress:S(n)}:{}}]},confidentialIsApproved:{all:[`zama.confidentialIsApproved`],token:e=>[`zama.confidentialIsApproved`,{tokenAddress:S(e)}],scope:(e,t,n)=>[`zama.confidentialIsApproved`,{tokenAddress:S(e),...t?{holder:S(t)}:{},...n?{spender:S(n)}:{}}]},totalSupply:{all:[`zama.totalSupply`],token:e=>[`zama.totalSupply`,{tokenAddress:S(e)}]},activityFeed:{all:[`zama.activityFeed`],token:e=>[`zama.activityFeed`,{tokenAddress:S(e)}],scope:(e,t,n,r)=>[`zama.activityFeed`,{tokenAddress:S(e),...t?{userAddress:S(t)}:{},...n?{logsKey:n}:{},...r===void 0?{}:{decrypt:r}}]},fees:{all:[`zama.fees`],shieldFee:(e,t,n,r)=>[`zama.fees`,{type:`shield`,...e?{feeManagerAddress:S(e)}:{},...t===void 0?{}:{amount:t},...n?{from:S(n)}:{},...r?{to:S(r)}:{}}],unshieldFee:(e,t,n,r)=>[`zama.fees`,{type:`unshield`,...e?{feeManagerAddress:S(e)}:{},...t===void 0?{}:{amount:t},...n?{from:S(n)}:{},...r?{to:S(r)}:{}}],batchTransferFee:e=>[`zama.fees`,{type:`batchTransfer`,...e?{feeManagerAddress:S(e)}:{}}],feeRecipient:e=>[`zama.fees`,{type:`feeRecipient`,...e?{feeManagerAddress:S(e)}:{}}]},isAllowed:{all:[`zama.isAllowed`],scope:e=>[`zama.isAllowed`,{account:S(e)}]},publicKey:{all:[`zama.publicKey`]},publicParams:{all:[`zama.publicParams`],bits:e=>[`zama.publicParams`,{bits:e}]},delegationStatus:{all:[`zama.delegationStatus`],token:e=>[`zama.delegationStatus`,{tokenAddress:S(e)}],scope:(e,t,n)=>[`zama.delegationStatus`,{tokenAddress:S(e),delegatorAddress:S(t),delegateAddress:S(n)}]},decryption:{all:[`zama.decryption`],handle:(e,t)=>[`zama.decryption`,{handle:e,...t===void 0?{}:{contractAddress:S(t)}}]}};function O(e,t){e.invalidateQueries({queryKey:D.underlyingAllowance.token(t)})}function k(e,t){A(e,t),O(e,t),R(e),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function A(e,t){e.invalidateQueries({queryKey:D.confidentialHandle.token(t)}),e.invalidateQueries({queryKey:D.confidentialHandles.all}),e.invalidateQueries({queryKey:D.confidentialBalance.token(t)}),e.invalidateQueries({queryKey:D.confidentialBalances.all})}function j(e,t){A(e,t),O(e,t),R(e),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function M(e,t){A(e,t),O(e,t),R(e),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function N(e,t){A(e,t),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function P(e,t){O(e,t)}function F(e,t){e.invalidateQueries({queryKey:D.confidentialIsApproved.token(t)}),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function I(e){return Array.isArray(e.queryKey)&&typeof e.queryKey[0]==`string`?e.queryKey[0].startsWith(`zama.`):!1}function L(e){return Array.isArray(e.queryKey)&&e.queryKey.some(e=>typeof e!=`object`||!e||!(`functionName`in e)?!1:e.functionName===`balanceOf`)}function R(e){e.invalidateQueries({predicate:L})}function z(e){e.removeQueries({queryKey:D.signerAddress.all}),e.removeQueries({queryKey:D.decryption.all}),e.invalidateQueries({predicate:I}),R(e)}const B=new WeakMap;let V=1;function H(e){let t=B.get(e);if(t!==void 0)return t;let n=V++;return B.set(e,n),n}function U(e,t){return{...w(t?.query??{}),queryKey:D.signerAddress.scope(H(e)),queryFn:async()=>e.getAddress(),staleTime:3e4,enabled:t?.query?.enabled!==!1}}function W(e,t,n){let r=D.tokenMetadata.token(t);return{...w(n?.query??{}),queryKey:r,queryFn:async t=>{let[,{tokenAddress:n}]=t.queryKey,[r,i,a]=await Promise.all([e.readContract(f(n)),e.readContract(p(n)),e.readContract(te(n))]);return{name:r,symbol:i,decimals:a}},staleTime:1/0,enabled:n?.query?.enabled!==!1}}function G(e,t,n){let r=D.isConfidential.token(t);return{...w(n?.query??{}),queryKey:r,queryFn:async t=>{let[,{tokenAddress:n}]=t.queryKey;return e.readContract(o(n))},staleTime:1/0,enabled:n?.query?.enabled!==!1}}function K(e,t,n){let i=D.isWrapper.token(t);return{...w(n?.query??{}),queryKey:i,queryFn:async t=>{let[,{tokenAddress:n}]=t.queryKey;return e.readContract(r(n))},staleTime:1/0,enabled:n?.query?.enabled!==!1}}function q(e,n,r){let i=D.totalSupply.token(n);return{...w(r?.query??{}),queryKey:i,queryFn:async n=>{let[,{tokenAddress:r}]=n.queryKey;return e.readContract(t(r))},staleTime:3e4,enabled:r?.query?.enabled!==!1}}function J(e,t,n){let r=D.wrapperDiscovery.token(t,n.coordinatorAddress);return{...w(n.query??{}),queryKey:r,queryFn:async t=>{let[,{tokenAddress:n,coordinatorAddress:r}]=t.queryKey;return await e.readContract(s(r,n))?e.readContract(a(r,n)):null},staleTime:1/0,enabled:!!t&&n.query?.enabled!==!1}}function Y(e,t,n){let r=n.owner,a=n.wrapperAddress,o=n.query?.enabled!==!1,s=D.underlyingAllowance.scope(t,r,a);return{...w(n.query??{}),queryKey:s,queryFn:async t=>{let[,{owner:n,wrapperAddress:r}]=t.queryKey;if(!n)throw Error(`owner is required`);if(!r)throw Error(`wrapperAddress is required`);let a=await e.readContract(i(r));return e.readContract(_(a,n,r))},staleTime:3e4,enabled:!!(r&&a)&&o}}function X(e,t,n){let r=n.holder,i=n.spender,a=n.query?.enabled!==!1,o=D.confidentialIsApproved.scope(t,r,i);return{...w(n.query??{}),queryKey:o,queryFn:async t=>{let[,{tokenAddress:n,holder:r,spender:i}]=t.queryKey;if(!r)throw Error(`holder is required`);if(!i)throw Error(`spender is required`);return e.readContract(c(n,r,i))},staleTime:3e4,enabled:!!(r&&i)&&a}}function Z(e){return e===void 0?void 0:BigInt(e)}function ie(e,t){let n=t.amount?.toString(),r=t.feeManagerAddress,i=t.from,a=t.to,o=t.query?.enabled!==!1,s=D.fees.shieldFee(r,n,i,a);return{...w(t.query??{}),queryKey:s,queryFn:async t=>{let[,n]=t.queryKey,r=Z(n.amount);if(!n.feeManagerAddress)throw Error(`feeManagerAddress is required`);if(r===void 0)throw Error(`amount is required`);if(!n.from)throw Error(`from is required`);if(!n.to)throw Error(`to is required`);return e.readContract(l(n.feeManagerAddress,r,n.from,n.to))},staleTime:3e4,enabled:!!(r&&n!==void 0&&i&&a)&&o}}function ae(e,t){let n=t.amount?.toString(),r=t.feeManagerAddress,i=t.from,a=t.to,o=t.query?.enabled!==!1,s=D.fees.unshieldFee(r,n,i,a);return{...w(t.query??{}),queryKey:s,queryFn:async t=>{let[,n]=t.queryKey,r=Z(n.amount);if(!n.feeManagerAddress)throw Error(`feeManagerAddress is required`);if(r===void 0)throw Error(`amount is required`);if(!n.from)throw Error(`from is required`);if(!n.to)throw Error(`to is required`);return e.readContract(v(n.feeManagerAddress,r,n.from,n.to))},staleTime:3e4,enabled:!!(r&&n!==void 0&&i&&a)&&o}}function oe(e,t,n){let r=n?.query?.enabled!==!1,i=D.fees.batchTransferFee(t);return{...w(n?.query??{}),queryKey:i,queryFn:async t=>{let[,{feeManagerAddress:n}]=t.queryKey;if(!n)throw Error(`feeManagerAddress is required`);return e.readContract(d(n))},staleTime:3e4,enabled:!!t&&r}}function se(e,t,n){let r=n?.query?.enabled!==!1,i=D.fees.feeRecipient(t);return{...w(n?.query??{}),queryKey:i,queryFn:async t=>{let[,{feeManagerAddress:n}]=t.queryKey;if(!n)throw Error(`feeManagerAddress is required`);return e.readContract(ee(n))},staleTime:3e4,enabled:!!t&&r}}function ce(e,t){let n=D.publicKey.all;return{...w(t?.query??{}),queryKey:n,queryFn:async()=>e.relayer.getPublicKey(),staleTime:1/0,enabled:t?.query?.enabled!==!1}}function le(e,t,n){let r=D.publicParams.bits(t);return{...w(n?.query??{}),queryKey:r,queryFn:async t=>{let[,{bits:n}]=t.queryKey;return e.relayer.getPublicParams(n)},staleTime:1/0,enabled:n?.query?.enabled!==!1}}function ue(e,t,r){let i=r?.owner,a=r?.query?.enabled!==!1,o=D.confidentialHandle.owner(t,i);return{...w(r?.query??{}),queryKey:o,queryFn:async t=>{let[,{tokenAddress:r,owner:i}]=t.queryKey;if(!i)throw Error(`owner is required`);return await e.readContract(n(r,i))},enabled:!!i&&a,refetchInterval:r?.pollingInterval??1e4}}function de(e,t){let n=t?.owner,r=t?.handle,i=t?.query?.enabled!==!1,a=D.confidentialBalance.owner(e.address,n,r);return{...w(t?.query??{}),queryKey:a,queryFn:async t=>{let[,{owner:n,handle:r}]=t.queryKey;if(!n)throw Error(`owner is required`);if(!r)throw Error(`handle is required`);return e.decryptBalance(r,n)},enabled:!!(n&&r)&&i,staleTime:1/0}}function fe(e,t,r){let i=r?.owner,a=r?.query?.enabled!==!1,o=D.confidentialHandles.tokens(t,i);return{...w(r?.query??{}),queryKey:o,queryFn:async t=>{let[,{tokenAddresses:r,owner:i}]=t.queryKey;if(!i)throw Error(`owner is required`);return Promise.all(r.map(async t=>await e.readContract(n(t,i))))},enabled:!!(i&&t.length>0)&&a,refetchInterval:r?.pollingInterval??1e4}}function pe(t,n){let r=t.map(e=>e.address),i=n?.resultAddresses??r,a=n?.owner,o=n?.handles,s=n?.query?.enabled!==!1,c=Array.isArray(o)&&o.length===t.length&&o.every(e=>!!e),l=D.confidentialBalances.tokens(r,a,o);return{...w(n?.query??{}),queryKey:l,queryFn:async r=>{let[,{owner:a,handles:o}]=r.queryKey;if(!a)throw Error(`owner is required`);if(!o)throw Error(`handles are required`);let s=new Map,c=await h.batchDecryptBalances(t,{owner:a,handles:o,maxConcurrency:n?.maxConcurrency,onError:(e,t)=>(s.set(t,e),0n)}),l=new Map,u=new Map;for(let e=0;e<t.length;e++){let n=t[e].address,r=i[e],a=s.get(n);if(a)u.set(r,a);else{let e=c.get(n);e!==void 0&&l.set(r,e)}}if(u.size===t.length&&t.length>0)throw u.values().next().value??new e(`All token balance decryptions failed`);return{balances:l,errors:u,isPartialError:u.size>0}},enabled:i.length===t.length&&!!a&&t.length>0&&c&&s,staleTime:1/0}}function Q(e){if(e)return T([`zama.activityFeed.logs`,e.map(e=>({topics:[...e.topics],data:e.data,transactionHash:e.transactionHash,blockNumber:e.blockNumber,logIndex:e.logIndex}))])}function me(e,t,n){let r=t.userAddress,i=t.decrypt??!0,a=t.logs,o=t.logsKey??Q(a),s=n?.query?.enabled!==!1,c=D.activityFeed.scope(e.address,r,o,i);return{...w(n?.query??{}),queryKey:c,queryFn:async t=>{let[,{userAddress:n,decrypt:r}]=t.queryKey;if(!n)throw Error(`userAddress is required`);if(!a)throw Error(`logs are required`);let i=b(a,n);if(!r)return g(i);let o=y(i);return o.length===0?g(i):g(x(i,await e.decryptHandles(o,n)))},staleTime:1/0,enabled:!!(r&&a)&&s}}function he(e){return{mutationKey:[`zama.shield`,e.address],mutationFn:async({amount:t,fees:n,approvalStrategy:r,to:i,callbacks:a})=>e.shield(t,{fees:n,approvalStrategy:r,to:i,callbacks:a})}}function ge(e){return{mutationKey:[`zama.shieldETH`,e.address],mutationFn:async({amount:t,value:n})=>e.shieldETH(t,n)}}function _e(e){return{mutationKey:[`zama.confidentialTransfer`,e.address],mutationFn:async({to:t,amount:n,callbacks:r})=>e.confidentialTransfer(t,n,r)}}function ve(e){return{mutationKey:[`zama.confidentialTransferFrom`,e.address],mutationFn:async({from:t,to:n,amount:r,callbacks:i})=>e.confidentialTransferFrom(t,n,r,i)}}function ye(e){return{mutationKey:[`zama.confidentialApprove`,e.address],mutationFn:async({spender:t,until:n})=>e.approve(t,n)}}function be(e){return{mutationKey:[`zama.approveUnderlying`,e.address],mutationFn:async({amount:t})=>e.approveUnderlying(t)}}function xe(e){return{mutationKey:[`zama.unshield`,e.address],mutationFn:async({amount:t,callbacks:n})=>e.unshield(t,n)}}function Se(e){return{mutationKey:[`zama.unshieldAll`,e.address],mutationFn:async t=>e.unshieldAll(t?.callbacks)}}function Ce(e){return{mutationKey:[`zama.resumeUnshield`,e.address],mutationFn:async({unwrapTxHash:t,callbacks:n})=>e.resumeUnshield(t,n)}}function we(e){return{mutationKey:[`zama.unwrap`,e.address],mutationFn:async({amount:t})=>e.unwrap(t)}}function Te(e){return{mutationKey:[`zama.unwrapAll`,e.address],mutationFn:async()=>e.unwrapAll()}}function Ee(e){return{mutationKey:[`zama.finalizeUnwrap`,e.address],mutationFn:async({burnAmountHandle:t})=>e.finalizeUnwrap(t)}}function De(e){return{mutationKey:[`zama.encrypt`],mutationFn:async t=>e.relayer.encrypt(t)}}function $(e){return{mutationKey:[`zama.allow`],mutationFn:t=>e.allow(...t)}}function Oe(e,t){return{...w(t.query??{}),queryKey:D.isAllowed.scope(t.account),queryFn:()=>e.isAllowed(),staleTime:1/0,enabled:t.query?.enabled!==!1}}function ke(e){return{mutationKey:[`zama.revoke`],mutationFn:t=>e.revoke(...t)}}function Ae(e){return{mutationKey:[`zama.revokeSession`],mutationFn:()=>e.revokeSession()}}function je(e){return{mutationKey:[`zama.delegateDecryption`,e.address],mutationFn:async({delegateAddress:t,expirationDate:n})=>e.delegateDecryption({delegateAddress:t,expirationDate:n})}}function Me(e){return{mutationKey:[`zama.decryptBalanceAs`,e.address],mutationFn:async({delegatorAddress:t,owner:n})=>e.decryptBalanceAs({delegatorAddress:t,owner:n})}}function Ne(e){return{mutationKey:[`zama.batchDecryptBalancesAs`,...e.map(e=>e.address)],mutationFn:async t=>h.batchDecryptBalancesAs(e,t)}}function Pe(e){return{mutationKey:[`zama.revokeDelegation`,e.address],mutationFn:async({delegateAddress:t})=>e.revokeDelegation({delegateAddress:t})}}function Fe(e,t){return{...w(t.query??{}),queryKey:D.delegationStatus.scope(e.address,t.delegatorAddress,t.delegateAddress),queryFn:async t=>{let[,{delegatorAddress:n,delegateAddress:r}]=t.queryKey,i=await e.getDelegationExpiry({delegatorAddress:n,delegateAddress:r}),a;return a=i===0n?!1:i===u?!0:i>await e.signer.getBlockTimestamp(),{isDelegated:a,expiryTimestamp:i}},enabled:t.query?.enabled!==!1}}export{re as ZERO_HANDLE,m as ZamaSDKEvents,me as activityFeedQueryOptions,$ as allowMutationOptions,be as approveUnderlyingMutationOptions,Ne as batchDecryptBalancesAsMutationOptions,oe as batchTransferFeeQueryOptions,ye as confidentialApproveMutationOptions,de as confidentialBalanceQueryOptions,pe as confidentialBalancesQueryOptions,ue as confidentialHandleQueryOptions,fe as confidentialHandlesQueryOptions,X as confidentialIsApprovedQueryOptions,ve as confidentialTransferFromMutationOptions,_e as confidentialTransferMutationOptions,Me as decryptBalanceAsMutationOptions,je as delegateDecryptionMutationOptions,Fe as delegationStatusQueryOptions,Q as deriveActivityFeedLogsKey,De as encryptMutationOptions,se as feeRecipientQueryOptions,w as filterQueryOptions,Ee as finalizeUnwrapMutationOptions,T as hashFn,F as invalidateAfterApprove,P as invalidateAfterApproveUnderlying,j as invalidateAfterShield,N as invalidateAfterTransfer,M as invalidateAfterUnshield,k as invalidateAfterUnwrap,A as invalidateBalanceQueries,R as invalidateWagmiBalanceQueries,z as invalidateWalletLifecycleQueries,Oe as isAllowedQueryOptions,G as isConfidentialQueryOptions,K as isWrapperQueryOptions,ce as publicKeyQueryOptions,le as publicParamsQueryOptions,Ce as resumeUnshieldMutationOptions,Pe as revokeDelegationMutationOptions,ke as revokeMutationOptions,Ae as revokeSessionMutationOptions,ge as shieldETHMutationOptions,ie as shieldFeeQueryOptions,he as shieldMutationOptions,U as signerAddressQueryOptions,W as tokenMetadataQueryOptions,q as totalSupplyQueryOptions,Y as underlyingAllowanceQueryOptions,Se as unshieldAllMutationOptions,ae as unshieldFeeQueryOptions,xe as unshieldMutationOptions,Te as unwrapAllMutationOptions,we as unwrapMutationOptions,J as wrapperDiscoveryQueryOptions,D as zamaQueryKeys};
|
|
1
|
+
import{r as e}from"../errors-Cw9kKQJc.js";import{S as t,f as n,i as r,l as i,o as a,r as o,s,v as c}from"../erc165-BZgfzGxL.js";import{A as l,C as u,D as d,F as f,I as p,O as ee,P as te,S as m,g as h,i as g,j as _,k as v,n as y,r as b,t as x}from"../activity-DEoxFQLE.js";import{getAddress as S}from"viem";function ne(e){if(!C(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!C(n)||!n.hasOwnProperty(`isPrototypeOf`))}function C(e){return Object.prototype.toString.call(e)===`[object Object]`}const re=`0x0000000000000000000000000000000000000000000000000000000000000000`;function w(e){let{gcTime:t,staleTime:n,enabled:r,select:i,refetchInterval:a,refetchOnMount:o,refetchOnWindowFocus:s,refetchOnReconnect:c,retry:l,retryDelay:u,retryOnMount:d,queryFn:f,queryKey:p,queryKeyHashFn:ee,initialData:te,initialDataUpdatedAt:m,placeholderData:h,structuralSharing:g,throwOnError:_,meta:v,query:y,pollingInterval:b,...x}=e;return x}function T(e){return JSON.stringify(e,(e,t)=>ne(t)?Object.keys(t).toSorted().reduce((e,n)=>(e[n]=t[n],e),{}):typeof t==`bigint`?t.toString():t)}const E=e=>e.map(e=>S(e)),D={signerAddress:{all:[`zama.signerAddress`],scope:e=>[`zama.signerAddress`,{scope:e}],token:e=>[`zama.signerAddress`,{tokenAddress:S(e)}]},confidentialHandle:{all:[`zama.confidentialHandle`],token:e=>[`zama.confidentialHandle`,{tokenAddress:S(e)}],owner:(e,t)=>[`zama.confidentialHandle`,{tokenAddress:S(e),...t?{owner:S(t)}:{}}]},confidentialBalance:{all:[`zama.confidentialBalance`],token:e=>[`zama.confidentialBalance`,{tokenAddress:S(e)}],owner:(e,t,n)=>[`zama.confidentialBalance`,{tokenAddress:S(e),...t?{owner:S(t)}:{},...n===void 0?{}:{handle:n}}]},confidentialHandles:{all:[`zama.confidentialHandles`],tokens:(e,t)=>[`zama.confidentialHandles`,{tokenAddresses:E(e),...t?{owner:S(t)}:{}}]},confidentialBalances:{all:[`zama.confidentialBalances`],tokens:(e,t,n)=>[`zama.confidentialBalances`,{tokenAddresses:E(e),...t?{owner:S(t)}:{},...n===void 0?{}:{handles:n}}]},tokenMetadata:{all:[`zama.tokenMetadata`],token:e=>[`zama.tokenMetadata`,{tokenAddress:S(e)}]},isConfidential:{all:[`zama.isConfidential`],token:e=>[`zama.isConfidential`,{tokenAddress:S(e)}]},isWrapper:{all:[`zama.isWrapper`],token:e=>[`zama.isWrapper`,{tokenAddress:S(e)}]},wrapperDiscovery:{all:[`zama.wrapperDiscovery`],token:(e,t)=>[`zama.wrapperDiscovery`,{tokenAddress:S(e),coordinatorAddress:S(t)}]},underlyingAllowance:{all:[`zama.underlyingAllowance`],token:e=>[`zama.underlyingAllowance`,{tokenAddress:S(e)}],scope:(e,t,n)=>[`zama.underlyingAllowance`,{tokenAddress:S(e),...t?{owner:S(t)}:{},...n?{wrapperAddress:S(n)}:{}}]},confidentialIsApproved:{all:[`zama.confidentialIsApproved`],token:e=>[`zama.confidentialIsApproved`,{tokenAddress:S(e)}],scope:(e,t,n)=>[`zama.confidentialIsApproved`,{tokenAddress:S(e),...t?{holder:S(t)}:{},...n?{spender:S(n)}:{}}]},totalSupply:{all:[`zama.totalSupply`],token:e=>[`zama.totalSupply`,{tokenAddress:S(e)}]},activityFeed:{all:[`zama.activityFeed`],token:e=>[`zama.activityFeed`,{tokenAddress:S(e)}],scope:(e,t,n,r)=>[`zama.activityFeed`,{tokenAddress:S(e),...t?{userAddress:S(t)}:{},...n?{logsKey:n}:{},...r===void 0?{}:{decrypt:r}}]},fees:{all:[`zama.fees`],shieldFee:(e,t,n,r)=>[`zama.fees`,{type:`shield`,...e?{feeManagerAddress:S(e)}:{},...t===void 0?{}:{amount:t},...n?{from:S(n)}:{},...r?{to:S(r)}:{}}],unshieldFee:(e,t,n,r)=>[`zama.fees`,{type:`unshield`,...e?{feeManagerAddress:S(e)}:{},...t===void 0?{}:{amount:t},...n?{from:S(n)}:{},...r?{to:S(r)}:{}}],batchTransferFee:e=>[`zama.fees`,{type:`batchTransfer`,...e?{feeManagerAddress:S(e)}:{}}],feeRecipient:e=>[`zama.fees`,{type:`feeRecipient`,...e?{feeManagerAddress:S(e)}:{}}]},isAllowed:{all:[`zama.isAllowed`],scope:e=>[`zama.isAllowed`,{account:S(e)}]},publicKey:{all:[`zama.publicKey`]},publicParams:{all:[`zama.publicParams`],bits:e=>[`zama.publicParams`,{bits:e}]},delegationStatus:{all:[`zama.delegationStatus`],token:e=>[`zama.delegationStatus`,{tokenAddress:S(e)}],scope:(e,t,n)=>[`zama.delegationStatus`,{tokenAddress:S(e),delegatorAddress:S(t),delegateAddress:S(n)}]},decryption:{all:[`zama.decryption`],handle:(e,t)=>[`zama.decryption`,{handle:e,...t===void 0?{}:{contractAddress:S(t)}}]}};function O(e,t){e.invalidateQueries({queryKey:D.underlyingAllowance.token(t)})}function k(e,t){A(e,t),O(e,t),R(e),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function A(e,t){e.invalidateQueries({queryKey:D.confidentialHandle.token(t)}),e.invalidateQueries({queryKey:D.confidentialHandles.all}),e.invalidateQueries({queryKey:D.confidentialBalance.token(t)}),e.invalidateQueries({queryKey:D.confidentialBalances.all})}function j(e,t){A(e,t),O(e,t),R(e),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function M(e,t){A(e,t),O(e,t),R(e),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function N(e,t){A(e,t),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function P(e,t){O(e,t)}function F(e,t){e.invalidateQueries({queryKey:D.confidentialIsApproved.token(t)}),e.invalidateQueries({queryKey:D.activityFeed.token(t)})}function I(e){return Array.isArray(e.queryKey)&&typeof e.queryKey[0]==`string`?e.queryKey[0].startsWith(`zama.`):!1}function L(e){return Array.isArray(e.queryKey)&&e.queryKey.some(e=>typeof e!=`object`||!e||!(`functionName`in e)?!1:e.functionName===`balanceOf`)}function R(e){e.invalidateQueries({predicate:L})}function z(e){e.removeQueries({queryKey:D.signerAddress.all}),e.removeQueries({queryKey:D.decryption.all}),e.invalidateQueries({predicate:I}),R(e)}const B=new WeakMap;let V=1;function H(e){let t=B.get(e);if(t!==void 0)return t;let n=V++;return B.set(e,n),n}function U(e,t){return{...w(t?.query??{}),queryKey:D.signerAddress.scope(H(e)),queryFn:async()=>e.getAddress(),staleTime:3e4,enabled:t?.query?.enabled!==!1}}function W(e,t,n){let r=D.tokenMetadata.token(t);return{...w(n?.query??{}),queryKey:r,queryFn:async t=>{let[,{tokenAddress:n}]=t.queryKey,[r,i,a]=await Promise.all([e.readContract(f(n)),e.readContract(p(n)),e.readContract(te(n))]);return{name:r,symbol:i,decimals:a}},staleTime:1/0,enabled:n?.query?.enabled!==!1}}function G(e,t,n){let r=D.isConfidential.token(t);return{...w(n?.query??{}),queryKey:r,queryFn:async t=>{let[,{tokenAddress:n}]=t.queryKey;return e.readContract(o(n))},staleTime:1/0,enabled:n?.query?.enabled!==!1}}function K(e,t,n){let i=D.isWrapper.token(t);return{...w(n?.query??{}),queryKey:i,queryFn:async t=>{let[,{tokenAddress:n}]=t.queryKey;return e.readContract(r(n))},staleTime:1/0,enabled:n?.query?.enabled!==!1}}function q(e,n,r){let i=D.totalSupply.token(n);return{...w(r?.query??{}),queryKey:i,queryFn:async n=>{let[,{tokenAddress:r}]=n.queryKey;return e.readContract(t(r))},staleTime:3e4,enabled:r?.query?.enabled!==!1}}function J(e,t,n){let r=D.wrapperDiscovery.token(t,n.coordinatorAddress);return{...w(n.query??{}),queryKey:r,queryFn:async t=>{let[,{tokenAddress:n,coordinatorAddress:r}]=t.queryKey;return await e.readContract(s(r,n))?e.readContract(a(r,n)):null},staleTime:1/0,enabled:!!t&&n.query?.enabled!==!1}}function Y(e,t,n){let r=n.owner,a=n.wrapperAddress,o=n.query?.enabled!==!1,s=D.underlyingAllowance.scope(t,r,a);return{...w(n.query??{}),queryKey:s,queryFn:async t=>{let[,{owner:n,wrapperAddress:r}]=t.queryKey;if(!n)throw Error(`owner is required`);if(!r)throw Error(`wrapperAddress is required`);let a=await e.readContract(i(r));return e.readContract(_(a,n,r))},staleTime:3e4,enabled:!!(r&&a)&&o}}function X(e,t,n){let r=n.holder,i=n.spender,a=n.query?.enabled!==!1,o=D.confidentialIsApproved.scope(t,r,i);return{...w(n.query??{}),queryKey:o,queryFn:async t=>{let[,{tokenAddress:n,holder:r,spender:i}]=t.queryKey;if(!r)throw Error(`holder is required`);if(!i)throw Error(`spender is required`);return e.readContract(c(n,r,i))},staleTime:3e4,enabled:!!(r&&i)&&a}}function Z(e){return e===void 0?void 0:BigInt(e)}function ie(e,t){let n=t.amount?.toString(),r=t.feeManagerAddress,i=t.from,a=t.to,o=t.query?.enabled!==!1,s=D.fees.shieldFee(r,n,i,a);return{...w(t.query??{}),queryKey:s,queryFn:async t=>{let[,n]=t.queryKey,r=Z(n.amount);if(!n.feeManagerAddress)throw Error(`feeManagerAddress is required`);if(r===void 0)throw Error(`amount is required`);if(!n.from)throw Error(`from is required`);if(!n.to)throw Error(`to is required`);return e.readContract(l(n.feeManagerAddress,r,n.from,n.to))},staleTime:3e4,enabled:!!(r&&n!==void 0&&i&&a)&&o}}function ae(e,t){let n=t.amount?.toString(),r=t.feeManagerAddress,i=t.from,a=t.to,o=t.query?.enabled!==!1,s=D.fees.unshieldFee(r,n,i,a);return{...w(t.query??{}),queryKey:s,queryFn:async t=>{let[,n]=t.queryKey,r=Z(n.amount);if(!n.feeManagerAddress)throw Error(`feeManagerAddress is required`);if(r===void 0)throw Error(`amount is required`);if(!n.from)throw Error(`from is required`);if(!n.to)throw Error(`to is required`);return e.readContract(v(n.feeManagerAddress,r,n.from,n.to))},staleTime:3e4,enabled:!!(r&&n!==void 0&&i&&a)&&o}}function oe(e,t,n){let r=n?.query?.enabled!==!1,i=D.fees.batchTransferFee(t);return{...w(n?.query??{}),queryKey:i,queryFn:async t=>{let[,{feeManagerAddress:n}]=t.queryKey;if(!n)throw Error(`feeManagerAddress is required`);return e.readContract(d(n))},staleTime:3e4,enabled:!!t&&r}}function se(e,t,n){let r=n?.query?.enabled!==!1,i=D.fees.feeRecipient(t);return{...w(n?.query??{}),queryKey:i,queryFn:async t=>{let[,{feeManagerAddress:n}]=t.queryKey;if(!n)throw Error(`feeManagerAddress is required`);return e.readContract(ee(n))},staleTime:3e4,enabled:!!t&&r}}function ce(e,t){let n=D.publicKey.all;return{...w(t?.query??{}),queryKey:n,queryFn:async()=>e.relayer.getPublicKey(),staleTime:1/0,enabled:t?.query?.enabled!==!1}}function le(e,t,n){let r=D.publicParams.bits(t);return{...w(n?.query??{}),queryKey:r,queryFn:async t=>{let[,{bits:n}]=t.queryKey;return e.relayer.getPublicParams(n)},staleTime:1/0,enabled:n?.query?.enabled!==!1}}function ue(e,t,r){let i=r?.owner,a=r?.query?.enabled!==!1,o=D.confidentialHandle.owner(t,i);return{...w(r?.query??{}),queryKey:o,queryFn:async t=>{let[,{tokenAddress:r,owner:i}]=t.queryKey;if(!i)throw Error(`owner is required`);return await e.readContract(n(r,i))},enabled:!!i&&a,refetchInterval:r?.pollingInterval??1e4}}function de(e,t){let n=t?.owner,r=t?.handle,i=t?.query?.enabled!==!1,a=D.confidentialBalance.owner(e.address,n,r);return{...w(t?.query??{}),queryKey:a,queryFn:async t=>{let[,{owner:n,handle:r}]=t.queryKey;if(!n)throw Error(`owner is required`);if(!r)throw Error(`handle is required`);return e.decryptBalance(r,n)},enabled:!!(n&&r)&&i,staleTime:1/0}}function fe(e,t,r){let i=r?.owner,a=r?.query?.enabled!==!1,o=D.confidentialHandles.tokens(t,i);return{...w(r?.query??{}),queryKey:o,queryFn:async t=>{let[,{tokenAddresses:r,owner:i}]=t.queryKey;if(!i)throw Error(`owner is required`);return Promise.all(r.map(async t=>await e.readContract(n(t,i))))},enabled:!!(i&&t.length>0)&&a,refetchInterval:r?.pollingInterval??1e4}}function pe(t,n){let r=t.map(e=>e.address),i=n?.resultAddresses??r,a=n?.owner,o=n?.handles,s=n?.query?.enabled!==!1,c=Array.isArray(o)&&o.length===t.length&&o.every(e=>!!e),l=D.confidentialBalances.tokens(r,a,o);return{...w(n?.query??{}),queryKey:l,queryFn:async r=>{let[,{owner:a,handles:o}]=r.queryKey;if(!a)throw Error(`owner is required`);if(!o)throw Error(`handles are required`);let s=new Map,c=await h.batchDecryptBalances(t,{owner:a,handles:o,maxConcurrency:n?.maxConcurrency,onError:(e,t)=>(s.set(t,e),0n)}),l=new Map,u=new Map;for(let e=0;e<t.length;e++){let n=t[e].address,r=i[e],a=s.get(n);if(a)u.set(r,a);else{let e=c.get(n);e!==void 0&&l.set(r,e)}}if(u.size===t.length&&t.length>0)throw u.values().next().value??new e(`All token balance decryptions failed`);return{balances:l,errors:u,isPartialError:u.size>0}},enabled:i.length===t.length&&!!a&&t.length>0&&c&&s,staleTime:1/0}}function Q(e){if(e)return T([`zama.activityFeed.logs`,e.map(e=>({topics:[...e.topics],data:e.data,transactionHash:e.transactionHash,blockNumber:e.blockNumber,logIndex:e.logIndex}))])}function me(e,t,n){let r=t.userAddress,i=t.decrypt??!0,a=t.logs,o=t.logsKey??Q(a),s=n?.query?.enabled!==!1,c=D.activityFeed.scope(e.address,r,o,i);return{...w(n?.query??{}),queryKey:c,queryFn:async t=>{let[,{userAddress:n,decrypt:r}]=t.queryKey;if(!n)throw Error(`userAddress is required`);if(!a)throw Error(`logs are required`);let i=b(a,n);if(!r)return g(i);let o=y(i);return o.length===0?g(i):g(x(i,await e.decryptHandles(o,n)))},staleTime:1/0,enabled:!!(r&&a)&&s}}function he(e){return{mutationKey:[`zama.shield`,e.address],mutationFn:async({amount:t,fees:n,approvalStrategy:r,to:i,callbacks:a})=>e.shield(t,{fees:n,approvalStrategy:r,to:i,callbacks:a})}}function ge(e){return{mutationKey:[`zama.shieldETH`,e.address],mutationFn:async({amount:t,value:n})=>e.shieldETH(t,n)}}function _e(e){return{mutationKey:[`zama.confidentialTransfer`,e.address],mutationFn:async({to:t,amount:n,callbacks:r})=>e.confidentialTransfer(t,n,r)}}function ve(e){return{mutationKey:[`zama.confidentialTransferFrom`,e.address],mutationFn:async({from:t,to:n,amount:r,callbacks:i})=>e.confidentialTransferFrom(t,n,r,i)}}function ye(e){return{mutationKey:[`zama.confidentialApprove`,e.address],mutationFn:async({spender:t,until:n})=>e.approve(t,n)}}function be(e){return{mutationKey:[`zama.approveUnderlying`,e.address],mutationFn:async({amount:t})=>e.approveUnderlying(t)}}function xe(e){return{mutationKey:[`zama.unshield`,e.address],mutationFn:async({amount:t,callbacks:n})=>e.unshield(t,n)}}function Se(e){return{mutationKey:[`zama.unshieldAll`,e.address],mutationFn:async t=>e.unshieldAll(t?.callbacks)}}function Ce(e){return{mutationKey:[`zama.resumeUnshield`,e.address],mutationFn:async({unwrapTxHash:t,callbacks:n})=>e.resumeUnshield(t,n)}}function we(e){return{mutationKey:[`zama.unwrap`,e.address],mutationFn:async({amount:t})=>e.unwrap(t)}}function Te(e){return{mutationKey:[`zama.unwrapAll`,e.address],mutationFn:async()=>e.unwrapAll()}}function Ee(e){return{mutationKey:[`zama.finalizeUnwrap`,e.address],mutationFn:async({burnAmountHandle:t})=>e.finalizeUnwrap(t)}}function De(e){return{mutationKey:[`zama.encrypt`],mutationFn:async t=>e.relayer.encrypt(t)}}function $(e){return{mutationKey:[`zama.allow`],mutationFn:t=>e.allow(...t)}}function Oe(e,t){return{...w(t.query??{}),queryKey:D.isAllowed.scope(t.account),queryFn:()=>e.isAllowed(),staleTime:1/0,enabled:t.query?.enabled!==!1}}function ke(e){return{mutationKey:[`zama.revoke`],mutationFn:t=>e.revoke(...t)}}function Ae(e){return{mutationKey:[`zama.revokeSession`],mutationFn:()=>e.revokeSession()}}function je(e){return{mutationKey:[`zama.delegateDecryption`,e.address],mutationFn:async({delegateAddress:t,expirationDate:n})=>e.delegateDecryption({delegateAddress:t,expirationDate:n})}}function Me(e){return{mutationKey:[`zama.decryptBalanceAs`,e.address],mutationFn:async({delegatorAddress:t,owner:n})=>e.decryptBalanceAs({delegatorAddress:t,owner:n})}}function Ne(e){return{mutationKey:[`zama.batchDecryptBalancesAs`,...e.map(e=>e.address)],mutationFn:async t=>h.batchDecryptBalancesAs(e,t)}}function Pe(e){return{mutationKey:[`zama.revokeDelegation`,e.address],mutationFn:async({delegateAddress:t})=>e.revokeDelegation({delegateAddress:t})}}function Fe(e,t){return{...w(t.query??{}),queryKey:D.delegationStatus.scope(e.address,t.delegatorAddress,t.delegateAddress),queryFn:async t=>{let[,{delegatorAddress:n,delegateAddress:r}]=t.queryKey,i=await e.getDelegationExpiry({delegatorAddress:n,delegateAddress:r}),a;return a=i===0n?!1:i===u?!0:i>await e.signer.getBlockTimestamp(),{isDelegated:a,expiryTimestamp:i}},enabled:t.query?.enabled!==!1}}export{re as ZERO_HANDLE,m as ZamaSDKEvents,me as activityFeedQueryOptions,$ as allowMutationOptions,be as approveUnderlyingMutationOptions,Ne as batchDecryptBalancesAsMutationOptions,oe as batchTransferFeeQueryOptions,ye as confidentialApproveMutationOptions,de as confidentialBalanceQueryOptions,pe as confidentialBalancesQueryOptions,ue as confidentialHandleQueryOptions,fe as confidentialHandlesQueryOptions,X as confidentialIsApprovedQueryOptions,ve as confidentialTransferFromMutationOptions,_e as confidentialTransferMutationOptions,Me as decryptBalanceAsMutationOptions,je as delegateDecryptionMutationOptions,Fe as delegationStatusQueryOptions,Q as deriveActivityFeedLogsKey,De as encryptMutationOptions,se as feeRecipientQueryOptions,w as filterQueryOptions,Ee as finalizeUnwrapMutationOptions,T as hashFn,F as invalidateAfterApprove,P as invalidateAfterApproveUnderlying,j as invalidateAfterShield,N as invalidateAfterTransfer,M as invalidateAfterUnshield,k as invalidateAfterUnwrap,A as invalidateBalanceQueries,R as invalidateWagmiBalanceQueries,z as invalidateWalletLifecycleQueries,Oe as isAllowedQueryOptions,G as isConfidentialQueryOptions,K as isWrapperQueryOptions,ce as publicKeyQueryOptions,le as publicParamsQueryOptions,Ce as resumeUnshieldMutationOptions,Pe as revokeDelegationMutationOptions,ke as revokeMutationOptions,Ae as revokeSessionMutationOptions,ge as shieldETHMutationOptions,ie as shieldFeeQueryOptions,he as shieldMutationOptions,U as signerAddressQueryOptions,W as tokenMetadataQueryOptions,q as totalSupplyQueryOptions,Y as underlyingAllowanceQueryOptions,Se as unshieldAllMutationOptions,ae as unshieldFeeQueryOptions,xe as unshieldMutationOptions,Te as unwrapAllMutationOptions,we as unwrapMutationOptions,J as wrapperDiscoveryQueryOptions,D as zamaQueryKeys};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as EncryptResult, c as PublicDecryptResult, f as UserDecryptParams, i as EncryptParams, n as EIP712TypedData, o as Handle, t as DelegatedUserDecryptParams } from "./relayer-sdk.types-
|
|
1
|
+
import { a as EncryptResult, c as PublicDecryptResult, f as UserDecryptParams, i as EncryptParams, n as EIP712TypedData, o as Handle, t as DelegatedUserDecryptParams } from "./relayer-sdk.types-DI4WWkTB.js";
|
|
2
2
|
import { Address, Hex } from "viem";
|
|
3
3
|
import { ClearValueType, InputProofBytesType, KeypairType, KmsDelegatedUserDecryptEIP712Type, ZKProofLike } from "@zama-fhe/relayer-sdk/bundle";
|
|
4
4
|
|
|
@@ -41,4 +41,4 @@ interface RelayerSDK {
|
|
|
41
41
|
}
|
|
42
42
|
//#endregion
|
|
43
43
|
export { RelayerSDK as t };
|
|
44
|
-
//# sourceMappingURL=relayer-sdk-
|
|
44
|
+
//# sourceMappingURL=relayer-sdk-CVVR30IW.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{l as e,s as t}from"./utils-
|
|
1
|
+
import{l as e,s as t}from"./utils-eIBZNA_w.js";import{parentPort as n}from"node:worker_threads";if(!n)throw Error(`This script must be run as a worker thread`);const r=n;let i=null;function a(e,t,n,i){let a={id:e,type:t,success:!0,data:n};r.postMessage(a,i)}function o(e,t,n){let i={id:e,type:t,success:!1,error:n};r.postMessage(i)}async function s(e){let{id:t,type:n,payload:r}=e,{fhevmConfig:s}=r;try{let e=await import(`@zama-fhe/relayer-sdk/node`),r={...s,batchRpcCalls:!1};i=await e.createInstance(r),a(t,n,{initialized:!0})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] Init error:`,r),o(t,n,r)}}function c(e){return typeof e==`boolean`?e?1n:0n:e}function l(e){throw Error(`Unsupported FHE type`)}async function u(e){let{id:t,type:n,payload:r}=e,{values:s,contractAddress:u,userAddress:d}=r;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);let e=i.createEncryptedInput(u,d);for(let t of s){let{value:n,type:r}=t;switch(r){case`ebool`:e.addBool(typeof n==`boolean`?n:n!==0n);break;case`euint8`:e.add8(c(n));break;case`euint16`:e.add16(c(n));break;case`euint32`:e.add32(c(n));break;case`euint64`:e.add64(c(n));break;case`euint128`:e.add128(c(n));break;case`euint256`:e.add256(c(n));break;case`eaddress`:e.addAddress(String(n));break;default:l(r)}}let r=await e.encrypt();a(t,n,{handles:r.handles,inputProof:r.inputProof},[r.inputProof.buffer,...r.handles.map(e=>e.buffer)])}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] Encrypt error:`,r),o(t,n,r)}}async function d(t){let{id:n,type:r,payload:s}=t;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);let t=s.handles.map(e=>({handle:e,contractAddress:s.contractAddress}));a(n,r,{clearValues:await i.userDecrypt(t,e(s.privateKey),e(s.publicKey),s.signature,s.signedContractAddresses,s.signerAddress,s.startTimestamp,s.durationDays)})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] UserDecrypt error:`,t),o(n,r,t)}}async function f(e){let{id:t,type:n,payload:r}=e;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);a(t,n,{...await i.publicDecrypt(r.handles)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] PublicDecrypt error:`,r),o(t,n,r)}}function p(e){let{id:n,type:r}=e;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);let e=i.generateKeypair();a(n,r,{publicKey:t(e.publicKey),privateKey:t(e.privateKey)})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] GenerateKeypair error:`,t),o(n,r,t)}}function m(n){let{id:r,type:s,payload:c}=n;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);let n=i.createEIP712(e(c.publicKey),c.contractAddresses,c.startTimestamp,c.durationDays);a(r,s,{domain:{name:n.domain.name,version:n.domain.version,chainId:Number(n.domain.chainId),verifyingContract:n.domain.verifyingContract},types:{UserDecryptRequestVerification:n.types.UserDecryptRequestVerification.map(e=>({name:e.name,type:e.type}))},message:{publicKey:t(n.message.publicKey),contractAddresses:[...n.message.contractAddresses],startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays),extraData:t(n.message.extraData)}})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] CreateEIP712 error:`,t),o(r,s,t)}}function h(t){let{id:n,type:r,payload:s}=t;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);a(n,r,i.createDelegatedUserDecryptEIP712(e(s.publicKey),s.contractAddresses,s.delegatorAddress,s.startTimestamp,s.durationDays))}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] CreateDelegatedEIP712 error:`,t),o(n,r,t)}}async function g(t){let{id:n,type:r,payload:s}=t;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);let t=s.handles.map(e=>({handle:e,contractAddress:s.contractAddress}));a(n,r,{clearValues:await i.delegatedUserDecrypt(t,e(s.privateKey),e(s.publicKey),s.signature,s.signedContractAddresses,s.delegatorAddress,s.delegateAddress,s.startTimestamp,s.durationDays)})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] DelegatedUserDecrypt error:`,t),o(n,r,t)}}async function _(e){let{id:t,type:n,payload:r}=e;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);let e=await i.requestZKProofVerification(r.zkProof);a(t,n,e,[e.inputProof.buffer,...e.handles.map(e=>e.buffer)])}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] RequestZKProofVerification error:`,r),o(t,n,r)}}function v(e){let{id:t,type:n}=e;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);a(t,n,{result:i.getPublicKey()})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] GetPublicKey error:`,r),o(t,n,r)}}function y(e){let{id:t,type:n,payload:r}=e;try{if(!i)throw Error(`SDK not initialized. Call NODE_INIT first.`);a(t,n,{result:i.getPublicParams(r.bits)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[NodeWorker] GetPublicParams error:`,r),o(t,n,r)}}async function b(e){try{switch(e.type){case`NODE_INIT`:await s(e);break;case`ENCRYPT`:await u(e);break;case`USER_DECRYPT`:await d(e);break;case`PUBLIC_DECRYPT`:await f(e);break;case`GENERATE_KEYPAIR`:p(e);break;case`CREATE_EIP712`:m(e);break;case`CREATE_DELEGATED_EIP712`:h(e);break;case`DELEGATED_USER_DECRYPT`:await g(e);break;case`REQUEST_ZK_PROOF_VERIFICATION`:await _(e);break;case`GET_PUBLIC_KEY`:v(e);break;case`GET_PUBLIC_PARAMS`:y(e);break;default:console.error(`[NodeWorker] Unknown request type:`,e.type)}}catch(t){let n=t instanceof Error?t.message:String(t);o(e.id,e.type,n)}}r.on(`message`,e=>{b(e)});
|
|
2
2
|
//# sourceMappingURL=relayer-sdk.node-worker.js.map
|
|
@@ -168,10 +168,10 @@ interface CreateEIP712ResponseData {
|
|
|
168
168
|
verifyingContract: Address;
|
|
169
169
|
};
|
|
170
170
|
types: {
|
|
171
|
-
UserDecryptRequestVerification:
|
|
171
|
+
UserDecryptRequestVerification: {
|
|
172
172
|
name: string;
|
|
173
173
|
type: string;
|
|
174
|
-
}
|
|
174
|
+
}[];
|
|
175
175
|
};
|
|
176
176
|
message: {
|
|
177
177
|
publicKey: Hex;
|
|
@@ -284,12 +284,10 @@ interface EIP712TypedData {
|
|
|
284
284
|
chainId: number;
|
|
285
285
|
verifyingContract: Address;
|
|
286
286
|
};
|
|
287
|
-
types: {
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
}>;
|
|
292
|
-
};
|
|
287
|
+
types: Record<string, readonly {
|
|
288
|
+
readonly name: string;
|
|
289
|
+
readonly type: string;
|
|
290
|
+
}[]>;
|
|
293
291
|
primaryType?: string;
|
|
294
292
|
message: {
|
|
295
293
|
publicKey: Hex;
|
|
@@ -316,4 +314,4 @@ interface DelegatedUserDecryptParams {
|
|
|
316
314
|
type RelayerSDKStatus = "idle" | "initializing" | "ready" | "error";
|
|
317
315
|
//#endregion
|
|
318
316
|
export { GetPublicKeyRequest as A, SuccessResponse as B, EncryptPayload as C, GenerateKeypairRequest as D, ErrorResponse as E, NodeInitRequest as F, WorkerRequest as G, UserDecryptPayload as H, PublicDecryptRequest as I, WorkerRequestType as K, PublicDecryptResponseData as L, GetPublicParamsRequest as M, GetPublicParamsResponseData as N, GenerateKeypairResponseData as O, InitRequest as P, RequestZKProofVerificationRequest as R, DelegatedUserDecryptResponseData as S, EncryptResponseData as T, UserDecryptRequest as U, UpdateCsrfRequest as V, UserDecryptResponseData as W, CreateEIP712Payload as _, EncryptResult as a, DelegatedUserDecryptPayload as b, PublicDecryptResult as c, RelayerWebSecurityConfig as d, UserDecryptParams as f, CreateDelegatedEIP712ResponseData as g, CreateDelegatedEIP712Request as h, EncryptParams as i, GetPublicKeyResponseData as j, GenericLogger as k, RelayerSDKStatus as l, CreateDelegatedEIP712Payload as m, EIP712TypedData as n, Handle as o, BaseRequest as p, WorkerResponse as q, EncryptInput as r, NetworkType as s, DelegatedUserDecryptParams as t, RelayerWebConfig as u, CreateEIP712Request as v, EncryptRequest as w, DelegatedUserDecryptRequest as x, CreateEIP712ResponseData as y, RequestZKProofVerificationResponseData as z };
|
|
319
|
-
//# sourceMappingURL=relayer-sdk.types-
|
|
317
|
+
//# sourceMappingURL=relayer-sdk.types-DI4WWkTB.d.ts.map
|
|
@@ -52,6 +52,9 @@
|
|
|
52
52
|
//#region src/worker/relayer-sdk.worker.ts
|
|
53
53
|
let sdkInstance = null;
|
|
54
54
|
let sdkGlobal = null;
|
|
55
|
+
function unreachableFheType(_) {
|
|
56
|
+
throw new Error("Unsupported FHE type");
|
|
57
|
+
}
|
|
55
58
|
let relayerUrlBase = "";
|
|
56
59
|
let csrfTokenBase = "";
|
|
57
60
|
const CSRF_HEADER_NAME = "x-csrf-token";
|
|
@@ -133,7 +136,7 @@
|
|
|
133
136
|
async function verifyIntegrity(content, expectedHash) {
|
|
134
137
|
const encoder = new TextEncoder();
|
|
135
138
|
const hashBuffer = await crypto.subtle.digest("SHA-384", encoder.encode(content));
|
|
136
|
-
const hashHex =
|
|
139
|
+
const hashHex = [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
137
140
|
if (hashHex !== expectedHash) throw new Error(`CDN integrity check failed: expected SHA-384 ${expectedHash}, got ${hashHex}`);
|
|
138
141
|
}
|
|
139
142
|
/**
|
|
@@ -182,7 +185,7 @@
|
|
|
182
185
|
await loadSdkScript(cdnUrl, integrity);
|
|
183
186
|
if (!self.relayerSDK) throw new Error("Failed to load relayerSDK from CDN");
|
|
184
187
|
sdkGlobal = self.relayerSDK;
|
|
185
|
-
await sdkGlobal.initSDK(thread
|
|
188
|
+
await sdkGlobal.initSDK(thread !== null && thread !== void 0 ? { thread } : void 0);
|
|
186
189
|
const config = {
|
|
187
190
|
...fhevmConfig,
|
|
188
191
|
batchRpcCalls: false
|
|
@@ -195,6 +198,10 @@
|
|
|
195
198
|
sendError(id, type, message);
|
|
196
199
|
}
|
|
197
200
|
}
|
|
201
|
+
/** Coerce a boolean to bigint for numeric FHE types. */
|
|
202
|
+
function toBigInt(value) {
|
|
203
|
+
return typeof value === "boolean" ? value ? 1n : 0n : value;
|
|
204
|
+
}
|
|
198
205
|
/**
|
|
199
206
|
* Add a single typed value to the encrypted input builder.
|
|
200
207
|
*/
|
|
@@ -205,27 +212,27 @@
|
|
|
205
212
|
input.addBool(typeof value === "boolean" ? value : value !== 0n);
|
|
206
213
|
break;
|
|
207
214
|
case "euint8":
|
|
208
|
-
input.add8(
|
|
215
|
+
input.add8(toBigInt(value));
|
|
209
216
|
break;
|
|
210
217
|
case "euint16":
|
|
211
|
-
input.add16(
|
|
218
|
+
input.add16(toBigInt(value));
|
|
212
219
|
break;
|
|
213
220
|
case "euint32":
|
|
214
|
-
input.add32(
|
|
221
|
+
input.add32(toBigInt(value));
|
|
215
222
|
break;
|
|
216
223
|
case "euint64":
|
|
217
|
-
input.add64(
|
|
224
|
+
input.add64(toBigInt(value));
|
|
218
225
|
break;
|
|
219
226
|
case "euint128":
|
|
220
|
-
input.add128(
|
|
227
|
+
input.add128(toBigInt(value));
|
|
221
228
|
break;
|
|
222
229
|
case "euint256":
|
|
223
|
-
input.add256(
|
|
230
|
+
input.add256(toBigInt(value));
|
|
224
231
|
break;
|
|
225
232
|
case "eaddress":
|
|
226
|
-
input.addAddress(
|
|
233
|
+
input.addAddress(String(value));
|
|
227
234
|
break;
|
|
228
|
-
default:
|
|
235
|
+
default: unreachableFheType(fheType);
|
|
229
236
|
}
|
|
230
237
|
}
|
|
231
238
|
/**
|
|
@@ -273,11 +280,11 @@
|
|
|
273
280
|
* Relayer SDK errors may carry a `status` or `statusCode` property.
|
|
274
281
|
*/
|
|
275
282
|
function extractHttpStatus(error) {
|
|
276
|
-
if (error
|
|
283
|
+
if (error === null || error === void 0 || typeof error !== "object") return;
|
|
277
284
|
const e = error;
|
|
278
285
|
if (typeof e.statusCode === "number") return e.statusCode;
|
|
279
286
|
if (typeof e.status === "number") return e.status;
|
|
280
|
-
if (e.cause
|
|
287
|
+
if (e.cause !== null && e.cause !== void 0 && typeof e.cause === "object") {
|
|
281
288
|
const cause = e.cause;
|
|
282
289
|
if (typeof cause.statusCode === "number") return cause.statusCode;
|
|
283
290
|
if (typeof cause.status === "number") return cause.status;
|
|
@@ -477,8 +484,8 @@
|
|
|
477
484
|
break;
|
|
478
485
|
default: console.error("[Worker] Unknown request type:", request.type);
|
|
479
486
|
}
|
|
480
|
-
} catch (
|
|
481
|
-
const message =
|
|
487
|
+
} catch (error) {
|
|
488
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
482
489
|
sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", message);
|
|
483
490
|
}
|
|
484
491
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as EIP712TypedData, o as Handle } from "./relayer-sdk.types-
|
|
1
|
+
import { n as EIP712TypedData, o as Handle } from "./relayer-sdk.types-DI4WWkTB.js";
|
|
2
2
|
import { Abi, Address, ContractFunctionArgs, ContractFunctionName, ContractFunctionReturnType, Hex } from "viem";
|
|
3
3
|
|
|
4
4
|
//#region src/events/onchain-events.d.ts
|
|
@@ -324,4 +324,4 @@ interface TransferCallbacks {
|
|
|
324
324
|
}
|
|
325
325
|
//#endregion
|
|
326
326
|
export { decodeOnChainEvents as A, Topics as C, WrappedEvent as D, UnwrappedStartedEvent as E, findUnwrapRequested as F, findWrapped as I, decodeUnwrappedFinalized as M, decodeUnwrappedStarted as N, decodeConfidentialTransfer as O, decodeWrapped as P, TOKEN_TOPICS as S, UnwrappedFinalizedEvent as T, WriteContractConfig as _, ReadContractArgs as a, OnChainEvent as b, ReadFunctionName as c, StoredCredentials as d, TransactionReceipt as f, WriteContractArgs as g, UnshieldCallbacks as h, GenericStorage as i, decodeUnwrapRequested as j, decodeOnChainEvent as k, ShieldCallbacks as l, TransferCallbacks as m, DelegatedStoredCredentials as n, ReadContractConfig as o, TransactionResult as p, GenericSigner as r, ReadContractReturnType as s, ContractAbi as t, SignerLifecycleCallbacks as u, WriteFunctionName as v, UnwrapRequestedEvent as w, RawLog as x, ConfidentialTransferEvent as y };
|
|
327
|
-
//# sourceMappingURL=token.types-
|
|
327
|
+
//# sourceMappingURL=token.types-DDdIZEax.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){return e instanceof Error?e:Error(String(e))}function t(e){return e.startsWith(`0x`)?e:`0x${e}`}function n(e){return l(e.startsWith(`0x`),`Expected 0x-prefixed hex, got: ${e}`),e.slice(2)}function r(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function i(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function a(e,t){if(!Array.isArray(e))throw TypeError(`${t} must be an array, got ${typeof e}`)}function o(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function s(e,t,n){i(e[t],n)}function c(e,t,n){o(e[t],n)}function l(e,t){if(!e)throw TypeError(t)}function u(){let e=globalThis;for(let t of[e.chrome,e.browser])try{r(t,`ns`);let{runtime:e}=t;return r(e,`runtime`),s(e,`id`,`runtime.id`),c(e,`getURL`,`runtime.getURL`),e}catch{continue}}async function d(e,t=1/0){if(!isFinite(t)||t>=e.length)return Promise.all(e.map(e=>e()));let n=Array(e.length),r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}return await Promise.all(Array.from({length:t},i)),n}export{u as a,e as c,i,n as l,l as n,d as o,r,t as s,a as t};
|
|
2
|
-
//# sourceMappingURL=utils-
|
|
1
|
+
function e(e){return e instanceof Error?e:Error(String(e))}function t(e){return e.startsWith(`0x`)?e:`0x${e}`}function n(e){return l(e.startsWith(`0x`),`Expected 0x-prefixed hex, got: ${e}`),e.slice(2)}function r(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function i(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function a(e,t){if(!Array.isArray(e))throw TypeError(`${t} must be an array, got ${typeof e}`)}function o(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function s(e,t,n){i(e[t],n)}function c(e,t,n){o(e[t],n)}function l(e,t){if(!e)throw TypeError(t)}function u(){let e=globalThis;for(let t of[e.chrome,e.browser])try{r(t,`ns`);let{runtime:e}=t;return r(e,`runtime`),s(e,`id`,`runtime.id`),c(e,`getURL`,`runtime.getURL`),e}catch{continue}}async function d(e,t=1/0){if(!Number.isFinite(t)||t>=e.length)return Promise.all(e.map(e=>e()));let n=Array.from({length:e.length}),r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}return await Promise.all(Array.from({length:t},i)),n}export{u as a,e as c,i,n as l,l as n,d as o,r,t as s,a as t};
|
|
2
|
+
//# sourceMappingURL=utils-eIBZNA_w.js.map
|
package/dist/viem/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as EIP712TypedData, o as Handle } from "../relayer-sdk.types-
|
|
2
|
-
import { _ as WriteContractConfig, f as TransactionReceipt, o as ReadContractConfig, r as GenericSigner, u as SignerLifecycleCallbacks } from "../token.types-
|
|
3
|
-
import { i as BatchTransferData } from "../index-
|
|
1
|
+
import { n as EIP712TypedData, o as Handle } from "../relayer-sdk.types-DI4WWkTB.js";
|
|
2
|
+
import { _ as WriteContractConfig, f as TransactionReceipt, o as ReadContractConfig, r as GenericSigner, u as SignerLifecycleCallbacks } from "../token.types-DDdIZEax.js";
|
|
3
|
+
import { i as BatchTransferData } from "../index-BFPpJ8wt.js";
|
|
4
4
|
import { Abi, Address, ContractFunctionArgs, ContractFunctionName, ContractFunctionReturnType, EIP1193Provider, Hex, PublicClient, WalletClient } from "viem";
|
|
5
5
|
|
|
6
6
|
//#region src/viem/viem-signer.d.ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zama-fhe/sdk",
|
|
3
|
-
"version": "1.2.0-alpha.
|
|
3
|
+
"version": "1.2.0-alpha.4",
|
|
4
4
|
"description": "TypeScript SDK for Zama confidential ERC-20 tokens (fhEVM)",
|
|
5
5
|
"license": "BSD-3-Clause-Clear",
|
|
6
6
|
"author": "Zama",
|
|
@@ -69,13 +69,13 @@
|
|
|
69
69
|
"typecheck": "tsc --noEmit"
|
|
70
70
|
},
|
|
71
71
|
"dependencies": {
|
|
72
|
-
"viem": "^2.47.
|
|
72
|
+
"viem": "^2.47.4"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@tanstack/query-core": "^5.90.20",
|
|
76
76
|
"@zama-fhe/relayer-sdk": "0.4.2",
|
|
77
77
|
"rolldown": "1.0.0-rc.7",
|
|
78
|
-
"rolldown-plugin-dts": "^0.22.
|
|
78
|
+
"rolldown-plugin-dts": "^0.22.5"
|
|
79
79
|
},
|
|
80
80
|
"peerDependencies": {
|
|
81
81
|
"@tanstack/query-core": ">=5",
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as e,d as t,f as n,m as r,n as i,o as a,p as o,r as s,y as c}from"./errors-Cw9kKQJc.js";import{c as l,i as u,n as d,o as ee,r as f,s as p,t as m}from"./utils-CYS8x8P_.js";import{a as h,f as te,l as g,n as _,o as v,s as ne,t as re}from"./erc165-BZgfzGxL.js";import{erc20Abi as y,getAddress as b,isAddress as x}from"viem";function ie(e){return{address:e,abi:y,functionName:`name`,args:[]}}function S(e){return{address:e,abi:y,functionName:`symbol`,args:[]}}function C(e){return{address:e,abi:y,functionName:`decimals`,args:[]}}function ae(e,t){return{address:e,abi:y,functionName:`balanceOf`,args:[t]}}function w(e,t,n){return{address:e,abi:y,functionName:`allowance`,args:[t,n]}}function oe(e,t,n){return{address:e,abi:y,functionName:`approve`,args:[t,n]}}const T=[{inputs:[{internalType:`uint256`,name:`amount`,type:`uint256`},{internalType:`address`,name:`wrapFrom`,type:`address`},{internalType:`address`,name:`wrapTo`,type:`address`}],name:`getWrapFee`,outputs:[{internalType:`uint256`,name:``,type:`uint256`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint64`,name:`amount`,type:`uint64`},{internalType:`address`,name:`unwrapFrom`,type:`address`},{internalType:`address`,name:`unwrapTo`,type:`address`}],name:`getUnwrapFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getBatchTransferFee`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getFeeRecipient`,outputs:[{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`}];function se(e,t,n,r){return{address:e,abi:T,functionName:`getWrapFee`,args:[t,n,r]}}function ce(e,t,n,r){return{address:e,abi:T,functionName:`getUnwrapFee`,args:[t,n,r]}}function le(e){return{address:e,abi:T,functionName:`getBatchTransferFee`,args:[]}}function ue(e){return{address:e,abi:T,functionName:`getFeeRecipient`,args:[]}}const E=[{inputs:[{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`},{internalType:`uint64`,name:`expirationDate`,type:`uint64`}],name:`delegateForUserDecryption`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`}],name:`revokeDelegationForUserDecryption`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`delegator`,type:`address`},{internalType:`address`,name:`delegate`,type:`address`},{internalType:`address`,name:`contractAddress`,type:`address`}],name:`getUserDecryptionDelegationExpirationDate`,outputs:[{internalType:`uint64`,name:``,type:`uint64`}],stateMutability:`view`,type:`function`}];function de(e,t,n,r){return{address:e,abi:E,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function fe(e,t,n){return{address:e,abi:E,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function pe(e,t,n,r){return{address:e,abi:E,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}const D=2n**64n-1n,O={CredentialsLoading:`credentials:loading`,CredentialsCached:`credentials:cached`,CredentialsExpired:`credentials:expired`,CredentialsCreating:`credentials:creating`,CredentialsCreated:`credentials:created`,CredentialsRevoked:`credentials:revoked`,CredentialsAllowed:`credentials:allowed`,SessionExpired:`session:expired`,EncryptStart:`encrypt:start`,EncryptEnd:`encrypt:end`,EncryptError:`encrypt:error`,DecryptStart:`decrypt:start`,DecryptEnd:`decrypt:end`,DecryptError:`decrypt:error`,TransactionError:`transaction:error`,ShieldSubmitted:`shield:submitted`,TransferSubmitted:`transfer:submitted`,TransferFromSubmitted:`transferFrom:submitted`,ApproveSubmitted:`approve:submitted`,ApproveUnderlyingSubmitted:`approveUnderlying:submitted`,UnwrapSubmitted:`unwrap:submitted`,FinalizeUnwrapSubmitted:`finalizeUnwrap:submitted`,DelegationSubmitted:`delegation:submitted`,RevokeDelegationSubmitted:`revokeDelegation:submitted`,UnshieldPhase1Submitted:`unshield:phase1_submitted`,UnshieldPhase2Started:`unshield:phase2_started`,UnshieldPhase2Submitted:`unshield:phase2_submitted`};var k=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const me=new k;var he=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return p(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function A(e){f(e,`Stored credentials`),u(e.publicKey,`credentials.publicKey`),m(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)d(typeof t==`string`&&x(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);f(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),u(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),u(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`)}function ge(e){A(e);let t=e;d(typeof t.delegatorAddress==`string`&&x(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),d(typeof t.delegateAddress==`string`&&x(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),d(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),d(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function j(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function M(e,t){let n=new Set(t.map(e=>b(e))),r=new Set(e.map(e=>b(e)));return n.isSubsetOf(r)}function N(e,t){return j(e)?M(e.contractAddresses,t):!1}function P(e){return[...new Set(e.map(e=>b(e)))].sort()}async function F(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var _e=class{#e;constructor(e){this.#e=e}#t(e){f(e,`Session entry`),u(e.signature,`session.signature`),d(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),d(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},I=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new _e(e.sessionStorage),this.crypto=new he,this.keypairTTL=e.keypairTTL??86400,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`)}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:e,contracts:t,createKey:n,createFn:i}){this.emit({type:O.CredentialsLoading,contractAddresses:t});try{let n=await this.storage.get(e);if(n){this.assertEncrypted(n);let r=await this.sessionSignatures.get(e);if(r)if(this.sessionSignatures.isExpired(r))await this.sessionSignatures.delete(e),this.emit({type:O.SessionExpired,reason:`ttl`});else{let i=await this.decryptCredentials(n,r.signature);if(N(i,t))return this.emit({type:O.CredentialsCached,contractAddresses:t}),this.emit({type:O.CredentialsAllowed,contractAddresses:t}),i;if(j(i))return this.#i({key:e,credentials:i,requiredContracts:t});this.emit({type:O.CredentialsExpired,contractAddresses:t})}if(j(n)){if(M(n.contractAddresses,t)){let r=await this.signForContracts(n,n.contractAddresses);await this.sessionSignatures.set({key:e,signature:r,ttl:this.sessionTTL});let i=await this.decryptCredentials(n,r);return this.emit({type:O.CredentialsCached,contractAddresses:t}),this.emit({type:O.CredentialsAllowed,contractAddresses:t}),i}let r=await this.signForContracts(n,n.contractAddresses),i=await this.decryptCredentials(n,r);return this.#i({key:e,credentials:i,requiredContracts:t})}this.emit({type:O.CredentialsExpired,contractAddresses:t})}}catch(t){if(t instanceof r||t instanceof o)throw t;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,t),await this.#o(e)}return(!this.#t||this.#n!==n)&&(this.#n=n,this.#t=i().then(e=>(this.emit({type:O.CredentialsAllowed,contractAddresses:t}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!N(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,t){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:O.CredentialsRevoked,...t?{contractAddresses:t}:{}})}async checkAllowed(e){let t=await this.sessionSignatures.get(e);return t===null?!1:!this.sessionSignatures.isExpired(t)}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#o(e)}clearCaches(){this.crypto.clearCache()}async createCredentials({key:e,contractAddresses:t,createFn:n,errorContext:r}){this.emit({type:O.CredentialsCreating,contractAddresses:t});try{let r=await n();return await this.persistCredentials(e,r),await this.sessionSignatures.set({key:e,signature:r.signature,ttl:this.sessionTTL}),this.emit({type:O.CredentialsCreated,contractAddresses:t}),r}catch(e){c(e,r)}}async#i({key:e,credentials:t,requiredContracts:n}){if(this.#r){let e=await this.#r;if(M(e.contractAddresses,n))return this.emit({type:O.CredentialsAllowed,contractAddresses:n}),e;t=e}let r=this.#a({key:e,credentials:t,requiredContracts:n});this.#r=r;try{return await r}finally{this.#r===r&&(this.#r=null)}}async#a({key:e,credentials:t,requiredContracts:n}){let r=P([...t.contractAddresses,...n]),i=await this.signForContracts(t,r),a={...t,contractAddresses:r,signature:i};return await this.persistCredentials(e,a),await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL}),this.emit({type:O.CredentialsAllowed,contractAddresses:n}),a}async persistCredentials(e,t){try{let n=await this.encryptCredentials(t);await this.storage.set(e,n)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e);return}}async#o(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e)}}};function ve(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var L=class e extends I{#e;#t=null;#n=null;static async computeStoreKey(e,t){return F(b(e),t)}constructor(e){super(e),this.#e=e.relayer,ve(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof k&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=P(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async isAllowed(){return this.checkAllowed(await this.#r())}async clear(){await this.clearAll(await this.#r())}async create(e){let t=P(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){A(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${b(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await e.computeStoreKey(t,n);return this.#n=r,this.#t=i,i}},R=class e extends I{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return F(b(e),b(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=b(e),r=P(t),i=await this.#i(n);return this.resolveCredentials({key:i,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i(b(e)),t)}async revoke(e){await this.revokeSession(await this.#i(b(e)))}async isAllowed(e){return this.checkAllowed(await this.#i(b(e)))}async clear(e){await this.clearAll(await this.#i(b(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){ge(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),i=`${b(n)}:${b(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(n,t,r);return this.#n=i,this.#t=a,a}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData({domain:{...n.domain,chainId:Number(n.domain.chainId)},types:n.types,message:{...n.message,startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays)}})}};const z=`zama:balances`;function ye(e,t,n){return`zama:balance:${b(e)}:${b(t)}:${n.toLowerCase()}`}async function B({storage:e,tokenAddress:t,owner:n,handle:r}){try{let i=await e.get(ye(t,n,r));return i===null?null:BigInt(i)}catch(e){return console.warn(`[zama-sdk] Balance cache read failed:`,e),null}}async function V(e){let{storage:t,tokenAddress:n,owner:r,handle:i,value:a}=e,o=ye(n,r,i);try{await t.set(o,a.toString()),await xe(t,o)}catch{}}const be=new WeakMap;async function xe(e,t){let n=(be.get(e)??Promise.resolve()).then(async()=>{let n=await e.get(z),r=n?JSON.parse(n):[];r.includes(t)||(r.push(t),await e.set(z,JSON.stringify(r)))});return be.set(e,n.catch(()=>{})),n}const Se=`0x0000000000000000000000000000000000000000000000000000000000000000`;var Ce=class t{credentials;delegatedCredentials;relayer;signer;address;storage;#e;constructor(e){let t={relayer:e.relayer,signer:e.signer,storage:e.storage,sessionStorage:e.sessionStorage,keypairTTL:e.keypairTTL??86400,sessionTTL:e.sessionTTL??2592e3,onEvent:e.onEvent};this.credentials=e.credentials??new L(t),this.delegatedCredentials=e.delegatedCredentials??new R(t),this.relayer=e.relayer,this.signer=e.signer,this.address=b(e.address),this.storage=e.storage,this.#e=e.onEvent}emit(e){this.#e?.({...e,tokenAddress:this.address,timestamp:Date.now()})}async balanceOf(e){let t=e?b(e):await this.signer.getAddress(),n=await this.readConfidentialBalanceOf(t);return this.decryptBalance(n,t)}async confidentialBalanceOf(e){let t=e?b(e):await this.signer.getAddress();return this.readConfidentialBalanceOf(t)}async isConfidential(){return await this.signer.readContract(h(this.address,re))===!0}async isWrapper(){return await this.signer.readContract(h(this.address,_))===!0}static async batchDecryptBalances(e,n){if(e.length===0)return new Map;let{handles:r,owner:i,onError:a,maxConcurrency:o}=n??{},s=e[0],c=t.assertSameRelayer(e),l=i??await s.signer.getAddress();return t.#t({tokens:e,handles:r,ownerAddress:l,onError:a,maxConcurrency:o,obtainCreds:e=>s.credentials.allow(...e),decrypt:(e,t,n)=>c.userDecrypt({handles:[t],contractAddress:n,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,signerAddress:l,startTimestamp:e.startTimestamp,durationDays:e.durationDays}),errorPrefix:`Batch decryption`})}static async batchDecryptBalancesAs(e,n){if(e.length===0)return new Map;let{delegatorAddress:r,handles:i,owner:a,onError:o,maxConcurrency:s}=n,c=a??r,l=e[0];return t.assertSameRelayer(e),t.#t({tokens:e,handles:i,ownerAddress:c,onError:o,maxConcurrency:s,preFlightCheck:()=>l.#n(r),obtainCreds:e=>l.delegatedCredentials.allow(r,...e),decrypt:(e,t,n)=>l.relayer.delegatedUserDecrypt({handles:[t],contractAddress:n,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,delegatorAddress:e.delegatorAddress,delegateAddress:e.delegateAddress,startTimestamp:e.startTimestamp,durationDays:e.durationDays}),errorPrefix:`Batch delegated decryption`})}static async#t(e){let{tokens:t,handles:n,ownerAddress:r,onError:i,maxConcurrency:a,obtainCreds:o,decrypt:c,errorPrefix:u}=e,d=t[0],f=n??await Promise.all(t.map(e=>e.readConfidentialBalanceOf(r)));if(t.length!==f.length)throw new s(`tokens.length (${t.length}) must equal handles.length (${f.length})`);let p=d.storage,m=new Map,h=[],te=await Promise.all(t.map((e,t)=>{let n=f[t];return e.isZeroHandle(n)?Promise.resolve(BigInt(0)):B({storage:p,tokenAddress:e.address,owner:r,handle:n})}));for(let e=0;e<t.length;e++){let n=t[e],r=f[e],i=te[e];if(i!=null){m.set(n.address,i);continue}h.push({token:n,handle:r})}if(h.length===0)return m;e.preFlightCheck&&await e.preFlightCheck();let g=await o(h.map(e=>e.token.address)),_=[],v=[];for(let{token:e,handle:t}of h)v.push(()=>c(g,t,e.address).then(async n=>{let i=n[t];if(i===void 0)throw new s(`${u} returned no value for handle ${t} on token ${e.address}`);m.set(e.address,i);try{await V({storage:p,tokenAddress:e.address,owner:r,handle:t,value:i})}catch{}}).catch(t=>{let n=l(t);if(i)try{m.set(e.address,i(n,e.address))}catch(t){_.push({address:e.address,error:l(t)})}else _.push({address:e.address,error:n})}));if(await ee(v,a),_.length>0){let e=_.map(e=>`${e.address}: ${e.error.message}`).join(`; `);throw new s(`${u} failed for ${_.length} token(s): ${e}`)}return m}async discoverWrapper(e){let t=b(e);return await this.signer.readContract(ne(t,this.address))?this.signer.readContract(v(t,this.address)):null}async underlyingToken(){return this.signer.readContract(g(this.address))}async allowance(e,t){let n=b(e),r=await this.signer.readContract(g(n)),i=t?b(t):await this.signer.getAddress();return this.signer.readContract(w(r,i,n))}async name(){return this.signer.readContract(ie(this.address))}async symbol(){return this.signer.readContract(S(this.address))}async decimals(){return this.signer.readContract(C(this.address))}async allow(){await this.credentials.allow(this.address)}async isAllowed(){return this.credentials.isAllowed()}async revoke(...e){await this.credentials.revoke(...e)}static async allow(...e){if(e.length===0)return;let t=e.map(e=>e.address);await e[0].credentials.allow(...t)}async getAclAddress(){return this.relayer.getAclAddress()}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===D?!0:t>await this.signer.getBlockTimestamp()}async getDelegationExpiry({delegatorAddress:e,delegateAddress:t}){let n=await this.getAclAddress();return this.signer.readContract(pe(n,b(e),b(t),this.address))}async#n(t){let n=await this.signer.getAddress(),r=await this.getDelegationExpiry({delegatorAddress:t,delegateAddress:n});if(r===0n)throw new a(`No active delegation from ${t} to ${n} for ${this.address}`);if(r!==D&&r<=await this.signer.getBlockTimestamp())throw new e(`Delegation from ${t} to ${n} for ${this.address} has expired`)}async readConfidentialBalanceOf(e){return await this.signer.readContract(te(this.address,e))}isZeroHandle(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}async decryptBalanceAs({delegatorAddress:e,owner:t}){let n=b(e),r=t?b(t):n,i=await this.readConfidentialBalanceOf(r);if(this.isZeroHandle(i))return 0n;let a=await B({storage:this.storage,tokenAddress:this.address,owner:r,handle:i});if(a!==null)return a;await this.#n(n);let o=Date.now();try{this.emit({type:O.DecryptStart});let e=await this.delegatedCredentials.allow(n,this.address),t=await this.relayer.delegatedUserDecrypt({handles:[i],contractAddress:this.address,signedContractAddresses:e.contractAddresses,privateKey:e.privateKey,publicKey:e.publicKey,signature:e.signature,delegatorAddress:e.delegatorAddress,delegateAddress:e.delegateAddress,startTimestamp:e.startTimestamp,durationDays:e.durationDays});this.emit({type:O.DecryptEnd,durationMs:Date.now()-o});let a=t[i];if(a===void 0)throw new s(`Delegated decryption returned no value for handle ${i}`);try{await V({storage:this.storage,tokenAddress:this.address,owner:r,handle:i,value:a})}catch{}return a}catch(e){throw this.emit({type:O.DecryptError,error:l(e),durationMs:Date.now()-o}),H(e,`Failed to decrypt delegated balance`)}}async decryptBalance(e,t){if(this.isZeroHandle(e))return BigInt(0);let n=t??await this.signer.getAddress(),r=await B({storage:this.storage,tokenAddress:this.address,owner:n,handle:e});if(r!==null)return r;let i=await this.credentials.allow(this.address),a=Date.now();try{this.emit({type:O.DecryptStart});let t=await this.relayer.userDecrypt({handles:[e],contractAddress:this.address,signedContractAddresses:i.contractAddresses,privateKey:i.privateKey,publicKey:i.publicKey,signature:i.signature,signerAddress:n,startTimestamp:i.startTimestamp,durationDays:i.durationDays});this.emit({type:O.DecryptEnd,durationMs:Date.now()-a});let r=t[e];if(r===void 0)throw new s(`Decryption returned no value for handle ${e}`);try{await V({storage:this.storage,tokenAddress:this.address,owner:n,handle:e,value:r})}catch{}return r}catch(e){throw this.emit({type:O.DecryptError,error:l(e),durationMs:Date.now()-a}),H(e,`Failed to decrypt balance`)}}async decryptHandles(e,t){let n=new Map,r=[];for(let t of e)this.isZeroHandle(t)?n.set(t,BigInt(0)):r.push(t);if(r.length===0)return n;let i=await this.credentials.allow(this.address),a=Date.now();try{this.emit({type:O.DecryptStart});let e=await this.relayer.userDecrypt({handles:r,contractAddress:this.address,signedContractAddresses:i.contractAddresses,privateKey:i.privateKey,publicKey:i.publicKey,signature:i.signature,signerAddress:t??await this.signer.getAddress(),startTimestamp:i.startTimestamp,durationDays:i.durationDays});this.emit({type:O.DecryptEnd,durationMs:Date.now()-a});for(let t of r){let r=e[t];if(r===void 0)throw new s(`Decryption returned no value for handle ${t}`);n.set(t,r)}}catch(e){throw this.emit({type:O.DecryptError,error:l(e),durationMs:Date.now()-a}),H(e,`Failed to decrypt handles`)}return n}static assertSameRelayer(e){let t=e[0].relayer;for(let n=1;n<e.length;n++)if(e[n].relayer!==t)throw new i(`All tokens in a batch operation must share the same relayer instance`);return t}};function H(e,i){if(e instanceof s||e instanceof t||e instanceof n||e instanceof r||e instanceof o)return e;let a=typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`?e.statusCode:void 0;return a===400?new t(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):a===void 0?new s(i,{cause:e}):new n(e instanceof Error?e.message:i,a,{cause:e})}const U={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x1f7907f4d84043abe0fb7c74e8865ee5fe93fe4f691c54a7b8fa9d6fb17c7cba`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0xc64e7c81b18b674fc5b037d8a0041bfe3332d86c780a4688f404ee01fbabb152`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function W(e){return b(p(e.slice(-40)))}function G(e){return BigInt(e)}function we(e){return e}function K(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function Te(e,t){return b(p(K(e,t).slice(-40)))}function q(e,t){return BigInt(`0x`+K(e,t))}function J(e,t){return BigInt(`0x`+K(e,t))!==0n}function Y(e,t){return p(K(e,t))}function Ee(e){return e.topics[0]!==U.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:W(e.topics[1]),to:W(e.topics[2]),encryptedAmountHandle:we(e.topics[3])}}function X(e){return e.topics[0]!==U.Wrapped||e.topics.length<3?null:{eventName:`Wrapped`,to:W(e.topics[1]),mintTxId:G(e.topics[2]),mintAmount:q(e.data,0),amountIn:q(e.data,1),feeAmount:q(e.data,2)}}function Z(e){return e.topics[0]!==U.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:W(e.topics[1]),encryptedAmount:Y(e.data,0)}}function De(e){return e.topics[0]!==U.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,burntAmountHandle:we(e.topics[1]),nextTxId:G(e.topics[2]),finalizeSuccess:J(e.data,0),feeTransferSuccess:J(e.data,1),burnAmount:q(e.data,2),unwrapAmount:q(e.data,3),feeAmount:q(e.data,4)}}function Oe(e){return e.topics[0]!==U.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:G(e.topics[1]),txId:G(e.topics[2]),to:W(e.topics[3]),returnVal:J(e.data,0),refund:Te(e.data,1),requestedAmount:Y(e.data,2),burnAmount:Y(e.data,3)}}function Q(e){return Ee(e)??X(e)??Z(e)??De(e)??Oe(e)}function ke(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function Ae(e){for(let t of e){let e=Z(t);if(e)return e}return null}function je(e){for(let t of e){let e=X(t);if(e)return e}return null}const Me=[U.ConfidentialTransfer,U.Wrapped,U.UnwrapRequested,U.UnwrappedFinalized,U.UnwrappedStarted];function Ne(e,t){return e.toLowerCase()===t.toLowerCase()}function $(e,t,n){let r=t!==void 0&&Ne(e,t),i=n!==void 0&&Ne(e,n);return r&&i?`self`:r?`outgoing`:`incoming`}function Pe(e,t,n){switch(e.eventName){case`ConfidentialTransfer`:return Fe(e,t,n);case`Wrapped`:return Ie(e,t,n);case`UnwrapRequested`:return Le(e,t,n);case`UnwrappedStarted`:return Re(e,t,n);case`UnwrappedFinalized`:return ze(e,n)}}function Fe(e,t,n){return{type:`transfer`,direction:$(t,e.from,e.to),amount:{type:`encrypted`,handle:e.encryptedAmountHandle},from:e.from,to:e.to,metadata:n,rawEvent:e}}function Ie(e,t,n){return{type:`shield`,direction:$(t,void 0,e.to),amount:{type:`clear`,value:e.amountIn},to:e.to,fee:e.feeAmount,metadata:n,rawEvent:e}}function Le(e,t,n){return{type:`unshield_requested`,direction:$(t,void 0,e.receiver),amount:{type:`encrypted`,handle:e.encryptedAmount},to:e.receiver,metadata:n,rawEvent:e}}function Re(e,t,n){return{type:`unshield_started`,direction:$(t,void 0,e.to),amount:{type:`encrypted`,handle:e.requestedAmount},to:e.to,success:e.returnVal,metadata:n,rawEvent:e}}function ze(e,t){return{type:`unshield_finalized`,direction:`incoming`,amount:{type:`clear`,value:e.unwrapAmount},fee:e.feeAmount,success:e.finalizeSuccess,metadata:t,rawEvent:e}}function Be(e,t){let n=[];for(let r of e){let e=Q(r);if(!e)continue;let i={transactionHash:r.transactionHash,blockNumber:r.blockNumber,logIndex:r.logIndex};n.push(Pe(e,t,i))}return n}function Ve(e){let t=new Set;for(let n of e)if(n.amount.type===`encrypted`&&n.amount.decryptedValue===void 0){let e=n.amount.handle;e!==`0x`&&e!==`0x0000000000000000000000000000000000000000000000000000000000000000`&&t.add(e)}return[...t]}function He(e,t){return e.map(e=>{if(e.amount.type!==`encrypted`)return e;let n=t.get(e.amount.handle);return n===void 0?e:{...e,amount:{type:`encrypted`,handle:e.amount.handle,decryptedValue:n}}})}function Ue(e){return[...e].sort((e,t)=>{let n=e.metadata.blockNumber,r=t.metadata.blockNumber;if(n===void 0&&r===void 0)return 0;if(n===void 0)return-1;if(r===void 0)return 1;let i=typeof n==`bigint`?n:BigInt(n),a=typeof r==`bigint`?r:BigInt(r);if(a>i)return 1;if(a<i)return-1;let o=e.metadata.logIndex??0;return(t.metadata.logIndex??0)-o})}export{se as A,D as C,le as D,fe as E,ie as F,S as I,oe as M,ae as N,ue as O,C as P,O as S,pe as T,Se as _,Me as a,k as b,Q as c,De as d,Oe as f,Ce as g,je as h,Ue as i,w as j,ce as k,ke as l,Ae as m,Ve as n,U as o,X as p,Be as r,Ee as s,He as t,Z as u,R as v,de as w,me as x,L as y};
|
|
2
|
-
//# sourceMappingURL=activity-BlZy4dNC.js.map
|