@zama-fhe/sdk 3.9.0-beta.1 → 3.9.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{t as e}from"./cleartext-BPIXzovl.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as ee,t as te,u as ne,v as re}from"./base-signer-LWfNMbWV.js";import{a as ie,c as ae,i as oe,l as se,n as ce,o as le,r as ue,s as de,t as fe,u as pe}from"./chains-BQXSxIwU.js";import{A as me,B as h,C as he,D as ge,E as _e,F as g,G as ve,H as ye,I as _,J as be,K as v,L as xe,M as Se,N as Ce,O as we,P as Te,S as Ee,T as De,U as Oe,W as ke,X as y,Y as Ae,_ as je,a as Me,b as Ne,c as Pe,d as Fe,f as b,h as Ie,j as Le,k as Re,l as ze,m as Be,n as Ve,o as He,p as x,q as Ue,s as We,t as S,u as Ge,v as Ke,w as qe,x as Je,y as Ye,z as Xe}from"./alignment-o-YIndFR.js";import{C,_ as Ze,a as Qe,c as w,f as $e,g as et,h as tt,i as T,m as nt,n as E,o as rt,r as D,s as it,t as O,v as at,x as ot,y as st}from"./relayer-nWfQAlo7.js";import{c as ct,d as lt,f as ut,i as dt,l as ft,n as pt,o as mt,p as ht,r as gt,s as _t,t as vt,u as k}from"./token-AXsOIUDB.js";import{n as yt,r as A,t as j}from"./encryption-BT886Jlj.js";import{a as bt,c as xt,d as St,i as Ct,l as M,n as wt,o as Tt,s as Et,t as Dt,u as Ot}from"./signing-CVEOw21I.js";import{n as kt,r as N}from"./fatal-batch-BYeHrf0V.js";import{a as P,c as At,i as jt,l as Mt,n as F,o as Nt,r as Pt,s as Ft,t as I}from"./log-decoding-ZthqwHOv.js";import{r as L}from"./telemetry-BCZsKGmH.js";import{t as R}from"./validation-CZfDLOUh.js";import{a as It,i as Lt,n as Rt,o as zt,r as Bt,s as Vt,t as Ht}from"./wrappers-registry-Cm3JJeqx.js";import{getAddress as z,keccak256 as Ut,size as Wt,toBytes as Gt,zeroAddress as Kt}from"viem";import{z as B}from"zod/mini";function qt(e,t){if(e instanceof D){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var Jt=class extends D{encryptedValue;contractAddress;account;constructor(e,t){super(T.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},V=class extends D{constructor(e,t){super(T.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},Yt=class extends D{constructor(e,t){super(T.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},H=class extends D{constructor(e,t){super(T.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},Xt=class extends D{constructor(e,t){super(T.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},Zt=class extends D{constructor(e,t){super(T.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},U=class extends D{constructor(e,t){super(T.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},Qt=class extends D{constructor(e,t){super(T.DelegationDelegateCannotBeWildcard,e,t),this.name=`DelegationDelegateCannotBeWildcardError`}},$t=class extends D{constructor(e,t){super(T.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},en=class extends D{constructor(e,t){super(T.AclPaused,e,t),this.name=`AclPausedError`}},W=class extends D{constructor(e,t){super(T.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},G=class extends D{constructor(e,t){super(T.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};function tn(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}var nn=class extends D{unwrapTxHash;unwrapRequestId;constructor(e,t,n){super(T.UnshieldAlreadyFinalized,e,n),this.name=`UnshieldAlreadyFinalizedError`,this.unwrapTxHash=t.unwrapTxHash,this.unwrapRequestId=t.unwrapRequestId}};const rn=`InvalidUnwrapRequest`,an=Ut(Gt(`${rn}(bytes32)`)).slice(0,10);function on(e){for(let t=e;t instanceof Error;t=t.cause)if(tn(t)===rn||t.message.includes(rn)||t.message.includes(an))return!0;return!1}const sn=[j,Tt,E,G,wt,Dt,Jt,N,Ct,M];function K(e,t,n={}){if(sn.some(t=>e instanceof t))return e;let r=e instanceof Error?e.message:t;if(e instanceof Error&&nt(e.message))return new Ct(e.message,{cause:e});if(at(e))return new M(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:e});if(e instanceof Error&&tt(e.message))return n.isDelegated?new G(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new Jt({encryptedValue:ot(e.message)??``,contractAddress:n.contractAddress??``,account:n.account??``},{cause:e});if($e(e))return new N(r,{cause:e,retryAfter:w(e)});let i=it(e);return i===void 0&&st(e)?new N(r,{cause:e,retryAfter:w(e)}):i===400?new Tt(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):n.isDelegated&&i===500?new G(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):et(e)||i!==void 0?new E(r,i,{cause:e,retryAfter:w(e),retryable:Ze(e)||void 0}):new j(t,{cause:e})}function cn(e,t){if(e instanceof D)return e;let n=it(e),r=Ze(e);return n!==void 0||et(e)?new E(e instanceof Error?e.message:t,n,{cause:e,retryAfter:w(e),retryable:r||void 0}):new A(t,{cause:e})}const ln=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function un(e,t,n,r=`0x`){return{address:e,abi:ln,functionName:`transferAndCall`,args:[t,n,r]}}const q=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function dn(e,t,n,r){return{address:e,abi:q,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function fn(e,t,n){return{address:e,abi:q,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function pn(e,t,n,r){return{address:e,abi:q,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function mn(e,t,n,r,i){return{address:e,abi:q,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const J=2n**64n-1n,Y=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function hn(e){return c(e.signer,e.provider,e)}const X={ConfidentialTransfer:I(`ConfidentialTransfer(address,address,bytes32)`),Wrap:I(`Wrap(address,uint256,bytes32)`),UnwrapRequested:I(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:I(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function gn(e){return e.topics[0]!==X.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmount:Pt(e.topics[3])}}function Z(e){return e.topics[0]!==X.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:F(e.topics[1]),roundedAmount:P(e.data,0),encryptedWrappedAmount:Nt(e.data,1)}}function _n(e){return e.topics[0]!==X.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:Pt(e.topics[2]),encryptedAmount:Nt(e.data,0)}}function vn(e){return e.topics[0]!==X.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:Pt(e.topics[2]),encryptedAmount:Nt(e.data,0),cleartextAmount:P(e.data,1)}}function yn(e){return gn(e)??Z(e)??_n(e)??vn(e)}function bn(e){let t=[];for(let n of e){let e=yn(n);e&&t.push(e)}return t}function xn(e){for(let t of e){let e=_n(t);if(e)return e}return null}function Sn(e){for(let t of e){let e=Z(t);if(e)return e}return null}const Cn=[X.ConfidentialTransfer,X.Wrap,X.UnwrapRequested,X.UnwrapFinalized],Q={DelegatedForUserDecryption:I(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:I(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function wn(e){return e.topics[0]!==Q.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:jt(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2),newExpirationDate:P(e.data,3)}}function Tn(e){return e.topics[0]!==Q.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:jt(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2)}}function En(e){return wn(e)??Tn(e)}function Dn(e){let t=[];for(let n of e){let e=En(n);e&&t.push(e)}return t}function On(e){for(let t of e){let e=wn(t);if(e)return e}return null}function kn(e){for(let t of e){let e=Tn(t);if(e)return e}return null}const An=[Q.DelegatedForUserDecryption,Q.RevokedDelegationForUserDecryption];var jn=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return v(this.#r,e)}#s(e,t){throw this.#a({type:h.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await Ve(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await Ve(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}registerPermit(e,t){return this.batchRegisterPermits([{prepared:e,signature:t}])}async batchRegisterPermits(e){let t;try{t=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await t.batchRegisterPermits(e),await Promise.all([...new Set(e.map(e=>e.prepared.signerAddress))].map(e=>this.#c(e)))}async revokePermits(e){let t=this.#o(`revokePermits`),n=await S(`revokePermits`,this.#e,this.#t),r=z(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await S(`clear`,this.#e,this.#t),n=z(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},Mn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return v(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await S(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await S(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},Nn=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return v(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await S(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,L(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await S(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,L(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=L(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{Xe(t.clearValues[n],`result.clearValues[${n}]`),r[e]=t.clearValues[n].value}),{clearValues:r,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw K(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i,operation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await S(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i,operation:a??`delegated-batch-decrypt-values`})}},Pn=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}batchPreparePermits(e){return this.#t.batchPreparePermits(e)}},Fn=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 In=new Fn;function $(e){return`zama:pending-unshield:${i(e)}`}const Ln=B.union([B.pipe(p,B.transform(e=>({unwrapTxHash:e}))),B.pipe(B.object({version:B.literal(1),unwrapTxHash:p,unwrapRequestId:B.optional(p)}),B.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function Rn(e,t,n,r){r===void 0?await e.set($(t),n):await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function zn(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=Ln.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Bn(e,t){await e.delete($(t))}var Vn=class extends vt{#e;#t=null;#n=null;#r(e){try{return Xe(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new ye(e,{cause:t})}}async underlying(){return this.#f()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#f();this.#n=await this.sdk.provider.readContract(Ge(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#f();return this.sdk.provider.readContract(b(t,z(e),this.address))}async shield(e,t){let n=await S(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#f(),a=z(n.address),o;try{o=await this.sdk.provider.readContract(Be(i,a))}catch(e){throw e instanceof D?e:new k(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:C(e)})}if(o<e)throw new ht(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${i})`,{requested:e,available:o,token:i});return r?this.#i(e,i,a,t):this.#a(e,a,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?z(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:un(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await S(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#f(),i=z(n.address),a;try{a=await this.sdk.provider.readContract(Be(r,i))}catch(e){throw e instanceof D?e:new k(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:C(e)})}if(a<e)throw new ht(`Insufficient ERC-20 balance: requested ${e}, available ${a} (token: ${r})`,{requested:e,available:a,token:r});let o;try{o=await this.sdk.provider.readContract(b(r,i,this.address))}catch(e){throw e instanceof D?e:new k(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:C(e)})}if(o<e)throw new lt(`Insufficient allowance for wrap: requested ${e}, approved ${o}. Call approveUnderlying() first (token: ${r}).`,{requested:e,available:o,token:r});let s=t?.to?z(t.to):i;return this.submitTransaction({operation:`wrap`,config:g(this.address,s,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#m(e,r===`max`,n);let i=n?.to?z(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:g(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await S(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#f(),r=z(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(b(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:x(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:x(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.#o(e,`unshield`);return _(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#p(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return _(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#p(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof D?e:new y(`Failed to get unwrap receipt`,{cause:e})}if(n.status===`reverted`)throw new y(`Unwrap transaction ${e} reverted, so there is nothing to resume`);let r=this.#c(n.logs);if(await this.#l(r))throw await this.#d(`resumeUnshield`),new nn(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:r});return this.#p(r,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=await zn(this.sdk.storage,this.address);return e?await this.#u(e)?(await this.#d(`getPendingUnshield`),null):e.unwrapTxHash:null}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t){this.#r(`unwrap`);let n=await S(`unwrap`,this.sdk.signer,this.sdk.provider),r=z(n.address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r},{operation:t}),[o]=i;if(!o)throw new A(`Encryption returned no encrypted values`);let s=await this.submitTransaction({operation:`unwrap`,config:Se(this.address,r,r,o,a)});return{...s,unwrapRequestId:this.#c(s.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=await S(`unwrapAll`,this.sdk.signer,this.sdk.provider),t=z(e.address),n=await this.readConfidentialBalanceOf(t);if(ct(n))throw new j(`Cannot unshield: balance is zero`);let r=await this.submitTransaction({operation:`unwrapAll`,config:Ce(this.address,t,t,n)});return{...r,unwrapRequestId:this.#c(r.receipt.logs)}}async finalizeUnwrap(e){return this.#s(e,`finalize-unwrap`)}async#s(e,t){this.#r(`finalizeUnwrap`),await Ve(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e],{operation:t}),r=n.clearValues[e];return xe(r,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:De(this.address,e,r,n.decryptionProof)})}#c(e){let t=xn(e.filter(e=>e.address===void 0||z(e.address)===this.address));if(!t)throw new y(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t.unwrapRequestId}async#l(e){try{return await this.sdk.provider.readContract(Te(this.address,e))===Kt}catch{return!1}}async#u(e){let t=e.unwrapRequestId;if(t===void 0)try{let n=await this.sdk.provider.waitForTransactionReceipt(e.unwrapTxHash);t=this.#c(n.logs)}catch{return!1}return this.#l(t)}async#d(e){await _(`${e}: clearPendingUnshield`,()=>Bn(this.sdk.storage,this.address),this.sdk.logger)}async#f(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(me(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#p(e,t,n,r,i){this.emit({type:h.UnshieldPhase1Submitted,txHash:t,operationId:n}),await _(`unshield: savePendingUnshield`,()=>Rn(this.sdk.storage,this.address,t,e),this.sdk.logger),this.emit({type:h.UnshieldPhase2Started,operationId:n}),_(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#s(e,i)}catch(n){throw on(n)||n instanceof y&&await this.#l(e)?(await this.#d(`unshield`),new nn(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:h.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),_(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#d(`unshield`),a}async#m(e,t,n){this.#r(`approveUnderlying`);let r=await this.#f(),i=await S(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=z(i.address),o=await this.sdk.provider.readContract(b(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:x(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:x(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const Hn=B.union([B.bigint(),B.boolean(),a]),Un=B.array(B.string());var Wn=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=Hn.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=z(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${z(e)}:${z(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Un.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function Gn(e,t){let n=Kn(e,t);if(!n)throw new j(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function Kn(e,t){let n=i(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const qn=e=>new Promise(t=>setTimeout(t,e));var Jn=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=z(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=z(t),o=z(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:z(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof G))throw t;await qn(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0,operation:o}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:z(e.contractAddress)}));if(s.length===0)return{items:s};let c=z(r);try{let e=await this.delegatedDecryptValues(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:a,operation:o});for(let t of s)this.#d(t,e);return{items:s}}catch(e){if(kt(e))throw e;if(s.length===1){let[n=this.#p()]=s;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:z(t)}),{items:s}}}let l=!1,u;if(await dt(s.map(e=>async()=>{if(!l)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,c,{waitForPropagation:!1,operation:o});this.#d(e,r)}catch(n){if(kt(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:z(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=Gn(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&nt(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,r={spent:!1}){if(e.length===0)return{};let i=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:z(e.contractAddress)})),a={},o=[];for(let e of i)ct(e.encryptedValue)?a[e.encryptedValue]=0n:o.push(e);if(o.length===0)return a;let s=Array.from(new Set(i.map(e=>e.contractAddress))),c=Array.from(new Set(o.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(c)}catch(e){throw st(e)?this.#u(e,`the delegation pre-check`):e}let l=[];for(let e of o){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?l.push(e):a[e.encryptedValue]=n}if(l.length===0)return a;let u=await this.#t.grantPermit(s,t.delegator),d=/* @__PURE__ */ new Map;for(let e of l){let t=d.get(e.contractAddress);t?t.push(e.encryptedValue):d.set(e.contractAddress,[e.encryptedValue])}let f=[];for(let[e,t]of d)for(let n of _t(t))f.push({contractAddress:e,encryptedValues:n});let p=Date.now(),m=l.map(e=>e.encryptedValue);try{this.#i({type:h.DecryptStart,encryptedValues:m});try{await this.#c(t,u,f,a,n)}catch(e){if(!(e instanceof M)||r.spent)throw e;let i=u.permissions.map(e=>e.serializedPermit.signature);r.spent=!0;try{u=await this.#t.recoverPermits(s,t.delegator,i)}catch(e){throw e instanceof Dt?new M(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(t,u,f.filter(({encryptedValues:e})=>e.some(e=>a[e]===void 0)),a,n)}let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:h.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),a}catch(e){let n=e instanceof D&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:C(n),durationMs:Date.now()-p,encryptedValues:m}),K(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await dt(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(a.length>0)throw a.find(e=>e instanceof M)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw K(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new j(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new j(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new N(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:w(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new j(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`):e.value=n}#f(e,t,n){return e instanceof D?e:K(e,t,n)}#p(){throw new j(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};const Yn={AlreadyDelegatedOrRevokedInSameBlock:e=>new Yt(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new $t(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new en(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new V(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new U(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new Qt(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new W(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new Zt(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new H(`Cannot revoke: no active delegation exists.`,{cause:e})};function Xn(e){return Object.hasOwn(Yn,e)}function Zn(e,t){let n=tn(e);if(n&&Xn(n))return Yn[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Yn))if(r.includes(e))return n(t);return null}var Qn=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new W(`Expiration date must be at least 1 hour in the future`);let a=z(t),o=z(n),s=z(r);if(o===s)throw new V(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===z(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new Qt(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new U(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):J,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new Zt(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==z(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:dn(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=z(t),a=z(n),o=z(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new H(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:fn(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=z(e.contractAddress)===Y,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:Y})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:Y});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==J}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===J?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(pn(r,z(t),z(n),z(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await pt({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof y))return;let t=Zn(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof H||t instanceof Xt){let n=z(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=z(e),i=z(t),a=z(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new H(`No active delegation from ${i} to ${a} for ${r}`):new Xt(`Delegation from ${i} to ${a} for ${r} has expired`)}},$n=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=z(e.contractAddress);try{this.#t({type:h.EncryptStart},r);let i=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:h.EncryptEnd,durationMs:Date.now()-n},r),i}catch(e){throw this.#t({type:h.EncryptError,error:C(e),durationMs:Date.now()-n},r),cn(e,`Encryption failed`)}}},er=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.clearCredentialsOnWalletChange,this.#a=e.logger,this.#e&&(this.#s=this.#e.walletAccount.subscribe(e=>{this.#c(e).catch(e=>{this.#a.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#o.add(e),()=>{this.#o.delete(e)}}dispose(){this.#s?.(),this.#s=void 0,this.#o.clear()}async#c(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await _(`switch relayer chain`,()=>this.#t.switchChain(r),this.#a),this.#i&&await this.#l(t,n),await Promise.all(Array.from(this.#o,t=>_(`wallet account listener`,()=>t(e),this.#a)))}async#l(e,t){let n=this.#r;n&&await _(`credential wallet account change`,()=>n.handleWalletAccountChange(e,t),this.#a),e&&await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e.address),this.#a)}};const tr=B.object({kind:B.literal(`ConfidentialTransfer`),from:a,token:a,to:a,amount:B.bigint()}),nr=B.object({kind:B.literal(`ConfidentialTransferFrom`),from:a,token:a,owner:a,to:a,amount:B.bigint()}),rr=B.object({kind:B.literal(`SetOperator`),from:a,token:a,operator:a,until:u}),ir=B.object({kind:B.literal(`Unwrap`),from:a,token:a,to:a,amount:B.bigint()}),ar=B.object({kind:B.literal(`UnwrapAll`),from:a,token:a,to:a}),or=B.object({kind:B.literal(`FinalizeUnwrap`),from:a,wrapper:a,unwrapRequestIdOrAmount:p}),sr=B.object({kind:B.literal(`ApproveUnderlying`),from:a,underlying:a,spender:a,amount:B.bigint()}),cr=B.object({kind:B.literal(`Wrap`),from:a,wrapper:a,to:a,amount:B.bigint()}),lr=p.check(B.refine(e=>e===`0x`||Wt(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),ur=B.object({kind:B.literal(`TransferAndCall`),from:a,underlying:a,wrapper:a,amount:B.bigint(),recipientData:B.optional(lr)}),dr=B.object({kind:B.literal(`DelegateDecryption`),from:a,contractAddress:a,delegateAddress:a,expirationDate:B.optional(B.date())}),fr=B.object({kind:B.literal(`RevokeDelegation`),from:a,contractAddress:a,delegateAddress:a});B.discriminatedUnion(`kind`,[tr,nr,rr,ir,ar,or,sr,cr,ur,dr,fr]);const pr=B.strictObject({maxFeePerGas:B.bigint(),maxPriorityFeePerGas:B.bigint()}),mr=B.object({nonce:B.optional(B.int().check(B.nonnegative())),gasLimit:B.optional(B.bigint()),fees:B.optional(pr)}),hr=B.object({address:a,abi:B.array(B.unknown()),functionName:B.string(),args:B.array(B.unknown()),value:B.optional(B.bigint()),gas:B.optional(B.bigint())}),gr=B.extend(mr,{from:a,calldata:hr});var _r=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=R(mr,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new O(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},a=R(gr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw gt(t,`prepare ${e.kind}`)??t});return{kind:e.kind,unsignedTx:o,from:a.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new O(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=R(tr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer`}),r=t[0];if(!r)throw new A(`Encryption returned no handles for ConfidentialTransfer`);return Ee(e.token,e.to,r,n)}async#a(e){e=R(nr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer-from`}),r=t[0];if(!r)throw new A(`Encryption returned no handles for ConfidentialTransferFrom`);return qe(e.token,e.owner,e.to,r,n)}#o(e){return e=R(rr,e),Re(e.token,e.operator,e.until)}async#s(e){e=R(ir,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-unwrap`}),r=t[0];if(!r)throw new A(`Encryption returned no handles for Unwrap`);return Se(e.token,e.from,e.to,r,n)}async#c(e){e=R(ar,e);let t=await this.#e.readContract(Ye(e.token,e.from));return Ce(e.token,e.from,e.to,t)}async#l(e){e=R(or,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount],options:{operation:`offline-finalize-unwrap`}}).catch(e=>{throw K(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return xe(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),De(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=R(sr,e),x(e.underlying,e.spender,e.amount)}#d(e){return e=R(cr,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=R(ur,e),un(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=R(dr,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new W(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new V(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new U(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):J;return dn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=R(fr,e),fn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function vr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new O(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function yr(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new O(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function br(e){if(e===void 0)return;let t=R(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var xr=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){vr(t),yr(t.transportKeyPairDerivationSecret);let n=br(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new Wn(e.storage,this.#i),this.#u=new Qn({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new f({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new ee({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new Jn({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new $n({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new er({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new _r({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new jn({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new Mn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new Nn({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new Pn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new f({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,L(t,`encrypt`))}createToken(e){return new vt(this,e)}createWrappedToken(e){return new Vn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{An as ACL_TOPICS,en as AclPausedError,Q as AclTopics,ft as BalanceCheckUnavailableError,te as BaseSigner,Ue as ChainMismatchError,Fn as ChromeSessionStorage,O as ConfigurationError,Nn as Decryption,j as DecryptionFailedError,n as DefaultRegistryAddresses,$t as DelegationContractIsSelfError,Yt as DelegationCooldownError,Qt as DelegationDelegateCannotBeWildcardError,U as DelegationDelegateEqualsContractError,W as DelegationExpirationTooSoonError,Xt as DelegationExpiredError,Zt as DelegationExpiryUnchangedError,H as DelegationNotFoundError,G as DelegationNotPropagatedError,V as DelegationSelfNotAllowedError,Mn as Delegations,Me as ERC1363_INTERFACE_ID,k as ERC20ReadFailedError,He as ERC7984_INTERFACE_ID,We as ERC7984_WRAPPER_INTERFACE_ID,yt as EncryptOffloadUnavailableError,A as EncryptionFailedError,be as HcuBlockLimitExceededError,Ae as HcuTransactionLimitExceededError,t as IndexedDBStorage,lt as InsufficientAllowanceError,ut as InsufficientConfidentialBalanceError,ht as InsufficientERC20BalanceError,Ct as InvalidTransportKeyPairError,bt as KeyWrappingError,J as MAX_UINT64,s as MemoryStorage,d as MutableWalletAccountStore,Tt as NoCiphertextError,Jt as NotEntitledError,Pn as Offline,jn as Permits,Et as PreparedPermitChainMismatchError,xt as PreparedPermitExpiredError,E as RelayerRequestFailedError,M as RevokedKmsContextError,N as RpcRateLimitError,ye as SignerNotConfiguredError,Oe as SignerRequiredError,Dt as SigningFailedError,wt as SigningRejectedError,Cn as TOKEN_TOPICS,vt as Token,X as Topics,y as TransactionRevertedError,Ot as TransportKeyPairChangedError,St as TransportKeyPairExpiredError,nn as UnshieldAlreadyFinalizedError,Ft as VaultBatchNotDispatchedError,At as VaultBatcherPausedError,Mt as VaultJoinUnconfirmedError,Y as WILDCARD_CONTRACT,ke as WalletAccountNotReadyError,ve as WalletNotConnectedError,Vn as WrappedToken,f as WrappersRegistry,mt as ZERO_ENCRYPTED_VALUE,D as ZamaError,T as ZamaErrorCode,xr as ZamaSDK,h as ZamaSDKEvents,b as allowanceContract,fe as anvil,x as approveContract,Be as balanceOfContract,ce as bscTestnet,ue as chains,In as chromeSessionStorage,e as cleartext,Ye as confidentialBalanceOfContract,Ne as confidentialTotalSupplyContract,Je as confidentialTransferAndCallContract,Ee as confidentialTransferContract,he as confidentialTransferFromAndCallContract,qe as confidentialTransferFromContract,hn as createConfig,m as createWalletAccountStore,Ie as decimalsContract,En as decodeAclEvent,Dn as decodeAclEvents,gn as decodeConfidentialTransfer,wn as decodeDelegatedForUserDecryption,yn as decodeOnChainEvent,bn as decodeOnChainEvents,Tn as decodeRevokedDelegationForUserDecryption,vn as decodeUnwrapFinalized,_n as decodeUnwrapRequested,Z as decodeWrap,dn as delegateForUserDecryptionContract,De as finalizeUnwrapContract,On as findDelegatedForUserDecryption,kn as findRevokedDelegationForUserDecryption,xn as findUnwrapRequested,Sn as findWrap,Ht as getConfidentialTokenAddressContract,pn as getDelegationExpiryContract,Rt as getTokenAddressContract,Bt as getTokenPairContract,Lt as getTokenPairsContract,It as getTokenPairsLengthContract,zt as getTokenPairsSliceContract,oe as hardhat,ie as hoodi,re as indexedDBStorage,_e as inferredTotalSupplyContract,Pe as isConfidentialTokenContract,Vt as isConfidentialTokenValidContract,ze as isConfidentialWrapperContract,ct as isEncryptedValueZero,mn as isHandleDelegatedContract,ge as isOperatorContract,Qe as isRetryable,le as mainnet,qt as matchZamaError,o as memoryStorage,je as nameContract,r as parsePreparedPermit,de as polygon,ae as polygonAmoy,we as rateContract,rt as retryAfterSeconds,fn as revokeDelegationContract,se as sepolia,Re as setOperatorContract,Fe as supportsInterfaceContract,Ke as symbolContract,un as transferAndCallContract,me as underlyingContract,Le as unwrapAmountContract,Se as unwrapContract,Ce as unwrapFromBalanceContract,Te as unwrapRequesterContract,g as wrapContract,pe as zenithTrexTestnet};
1
+ import{t as e}from"./cleartext-DcCwbO5i.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as ee,t as te,u as ne,v as re}from"./base-signer-Bst8sJcc.js";import{a as ie,c as ae,i as oe,l as se,n as ce,o as le,r as ue,s as de,t as fe,u as pe}from"./chains-BQXSxIwU.js";import{A as me,B as h,C as he,D as ge,E as _e,F as g,G as ve,H as ye,I as _,J as be,K as v,L as xe,M as Se,N as Ce,O as we,P as Te,S as Ee,T as De,U as Oe,W as ke,X as y,Y as Ae,_ as je,a as Me,b as Ne,c as Pe,d as Fe,f as b,h as Ie,j as Le,k as Re,l as ze,m as Be,n as Ve,o as He,p as x,q as Ue,s as We,t as S,u as Ge,v as Ke,w as qe,x as Je,y as Ye,z as Xe}from"./alignment-o-YIndFR.js";import{C,_ as Ze,a as Qe,c as w,f as $e,g as et,h as tt,i as T,m as nt,n as E,o as rt,r as D,s as it,t as O,v as at,x as ot,y as st}from"./relayer-nWfQAlo7.js";import{c as ct,d as lt,f as ut,i as dt,l as ft,n as pt,o as mt,p as ht,r as gt,s as _t,t as vt,u as k}from"./token-AXsOIUDB.js";import{n as yt,r as A,t as j}from"./encryption-BT886Jlj.js";import{a as bt,c as xt,d as St,i as Ct,l as M,n as wt,o as Tt,s as Et,t as Dt,u as Ot}from"./signing-CVEOw21I.js";import{n as kt,r as N}from"./fatal-batch-BYeHrf0V.js";import{a as P,c as At,i as jt,l as Mt,n as F,o as Nt,r as Pt,s as Ft,t as I}from"./log-decoding-ZthqwHOv.js";import{r as L}from"./telemetry-DZs0eTBf.js";import{t as R}from"./validation-CZfDLOUh.js";import{a as It,i as Lt,n as Rt,o as zt,r as Bt,s as Vt,t as Ht}from"./wrappers-registry-Cm3JJeqx.js";import{getAddress as z,keccak256 as Ut,size as Wt,toBytes as Gt,zeroAddress as Kt}from"viem";import{z as B}from"zod/mini";function qt(e,t){if(e instanceof D){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var Jt=class extends D{encryptedValue;contractAddress;account;constructor(e,t){super(T.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},V=class extends D{constructor(e,t){super(T.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},Yt=class extends D{constructor(e,t){super(T.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},H=class extends D{constructor(e,t){super(T.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},Xt=class extends D{constructor(e,t){super(T.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},Zt=class extends D{constructor(e,t){super(T.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},U=class extends D{constructor(e,t){super(T.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},Qt=class extends D{constructor(e,t){super(T.DelegationDelegateCannotBeWildcard,e,t),this.name=`DelegationDelegateCannotBeWildcardError`}},$t=class extends D{constructor(e,t){super(T.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},en=class extends D{constructor(e,t){super(T.AclPaused,e,t),this.name=`AclPausedError`}},W=class extends D{constructor(e,t){super(T.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},G=class extends D{constructor(e,t){super(T.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};function tn(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}var nn=class extends D{unwrapTxHash;unwrapRequestId;constructor(e,t,n){super(T.UnshieldAlreadyFinalized,e,n),this.name=`UnshieldAlreadyFinalizedError`,this.unwrapTxHash=t.unwrapTxHash,this.unwrapRequestId=t.unwrapRequestId}};const rn=`InvalidUnwrapRequest`,an=Ut(Gt(`${rn}(bytes32)`)).slice(0,10);function on(e){for(let t=e;t instanceof Error;t=t.cause)if(tn(t)===rn||t.message.includes(rn)||t.message.includes(an))return!0;return!1}const sn=[j,Tt,E,G,wt,Dt,Jt,N,Ct,M];function K(e,t,n={}){if(sn.some(t=>e instanceof t))return e;let r=e instanceof Error?e.message:t;if(e instanceof Error&&nt(e.message))return new Ct(e.message,{cause:e});if(at(e))return new M(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:e});if(e instanceof Error&&tt(e.message))return n.isDelegated?new G(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new Jt({encryptedValue:ot(e.message)??``,contractAddress:n.contractAddress??``,account:n.account??``},{cause:e});if($e(e))return new N(r,{cause:e,retryAfter:w(e)});let i=it(e);return i===void 0&&st(e)?new N(r,{cause:e,retryAfter:w(e)}):i===400?new Tt(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):n.isDelegated&&i===500?new G(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):et(e)||i!==void 0?new E(r,i,{cause:e,retryAfter:w(e),retryable:Ze(e)||void 0}):new j(t,{cause:e})}function cn(e,t){if(e instanceof D)return e;let n=it(e),r=Ze(e);return n!==void 0||et(e)?new E(e instanceof Error?e.message:t,n,{cause:e,retryAfter:w(e),retryable:r||void 0}):new A(t,{cause:e})}const ln=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function un(e,t,n,r=`0x`){return{address:e,abi:ln,functionName:`transferAndCall`,args:[t,n,r]}}const q=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function dn(e,t,n,r){return{address:e,abi:q,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function fn(e,t,n){return{address:e,abi:q,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function pn(e,t,n,r){return{address:e,abi:q,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function mn(e,t,n,r,i){return{address:e,abi:q,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const J=2n**64n-1n,Y=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function hn(e){return c(e.signer,e.provider,e)}const X={ConfidentialTransfer:I(`ConfidentialTransfer(address,address,bytes32)`),Wrap:I(`Wrap(address,uint256,bytes32)`),UnwrapRequested:I(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:I(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function gn(e){return e.topics[0]!==X.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmount:Pt(e.topics[3])}}function Z(e){return e.topics[0]!==X.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:F(e.topics[1]),roundedAmount:P(e.data,0),encryptedWrappedAmount:Nt(e.data,1)}}function _n(e){return e.topics[0]!==X.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:Pt(e.topics[2]),encryptedAmount:Nt(e.data,0)}}function vn(e){return e.topics[0]!==X.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:Pt(e.topics[2]),encryptedAmount:Nt(e.data,0),cleartextAmount:P(e.data,1)}}function yn(e){return gn(e)??Z(e)??_n(e)??vn(e)}function bn(e){let t=[];for(let n of e){let e=yn(n);e&&t.push(e)}return t}function xn(e){for(let t of e){let e=_n(t);if(e)return e}return null}function Sn(e){for(let t of e){let e=Z(t);if(e)return e}return null}const Cn=[X.ConfidentialTransfer,X.Wrap,X.UnwrapRequested,X.UnwrapFinalized],Q={DelegatedForUserDecryption:I(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:I(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function wn(e){return e.topics[0]!==Q.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:jt(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2),newExpirationDate:P(e.data,3)}}function Tn(e){return e.topics[0]!==Q.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:jt(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2)}}function En(e){return wn(e)??Tn(e)}function Dn(e){let t=[];for(let n of e){let e=En(n);e&&t.push(e)}return t}function On(e){for(let t of e){let e=wn(t);if(e)return e}return null}function kn(e){for(let t of e){let e=Tn(t);if(e)return e}return null}const An=[Q.DelegatedForUserDecryption,Q.RevokedDelegationForUserDecryption];var jn=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return v(this.#r,e)}#s(e,t){throw this.#a({type:h.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await Ve(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await Ve(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}registerPermit(e,t){return this.batchRegisterPermits([{prepared:e,signature:t}])}async batchRegisterPermits(e){let t;try{t=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await t.batchRegisterPermits(e),await Promise.all([...new Set(e.map(e=>e.prepared.signerAddress))].map(e=>this.#c(e)))}async revokePermits(e){let t=this.#o(`revokePermits`),n=await S(`revokePermits`,this.#e,this.#t),r=z(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await S(`clear`,this.#e,this.#t),n=z(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},Mn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return v(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await S(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await S(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},Nn=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return v(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await S(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,L(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await S(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,L(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=L(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{Xe(t.clearValues[n],`result.clearValues[${n}]`),r[e]=t.clearValues[n].value}),{clearValues:r,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw K(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i,operation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await S(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i,operation:a??`delegated-batch-decrypt-values`})}},Pn=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}batchPreparePermits(e){return this.#t.batchPreparePermits(e)}},Fn=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 In=new Fn;function $(e){return`zama:pending-unshield:${i(e)}`}const Ln=B.union([B.pipe(p,B.transform(e=>({unwrapTxHash:e}))),B.pipe(B.object({version:B.literal(1),unwrapTxHash:p,unwrapRequestId:B.optional(p)}),B.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function Rn(e,t,n,r){r===void 0?await e.set($(t),n):await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function zn(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=Ln.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Bn(e,t){await e.delete($(t))}var Vn=class extends vt{#e;#t=null;#n=null;#r(e){try{return Xe(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new ye(e,{cause:t})}}async underlying(){return this.#f()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#f();this.#n=await this.sdk.provider.readContract(Ge(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#f();return this.sdk.provider.readContract(b(t,z(e),this.address))}async shield(e,t){let n=await S(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#f(),a=z(n.address),o;try{o=await this.sdk.provider.readContract(Be(i,a))}catch(e){throw e instanceof D?e:new k(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:C(e)})}if(o<e)throw new ht(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${i})`,{requested:e,available:o,token:i});return r?this.#i(e,i,a,t):this.#a(e,a,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?z(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:un(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await S(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#f(),i=z(n.address),a;try{a=await this.sdk.provider.readContract(Be(r,i))}catch(e){throw e instanceof D?e:new k(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:C(e)})}if(a<e)throw new ht(`Insufficient ERC-20 balance: requested ${e}, available ${a} (token: ${r})`,{requested:e,available:a,token:r});let o;try{o=await this.sdk.provider.readContract(b(r,i,this.address))}catch(e){throw e instanceof D?e:new k(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:C(e)})}if(o<e)throw new lt(`Insufficient allowance for wrap: requested ${e}, approved ${o}. Call approveUnderlying() first (token: ${r}).`,{requested:e,available:o,token:r});let s=t?.to?z(t.to):i;return this.submitTransaction({operation:`wrap`,config:g(this.address,s,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#m(e,r===`max`,n);let i=n?.to?z(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:g(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await S(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#f(),r=z(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(b(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:x(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:x(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.#o(e,`unshield`);return _(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#p(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return _(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#p(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof D?e:new y(`Failed to get unwrap receipt`,{cause:e})}if(n.status===`reverted`)throw new y(`Unwrap transaction ${e} reverted, so there is nothing to resume`);let r=this.#c(n.logs);if(await this.#l(r))throw await this.#d(`resumeUnshield`),new nn(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:r});return this.#p(r,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=await zn(this.sdk.storage,this.address);return e?await this.#u(e)?(await this.#d(`getPendingUnshield`),null):e.unwrapTxHash:null}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t){this.#r(`unwrap`);let n=await S(`unwrap`,this.sdk.signer,this.sdk.provider),r=z(n.address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r},{operation:t}),[o]=i;if(!o)throw new A(`Encryption returned no encrypted values`);let s=await this.submitTransaction({operation:`unwrap`,config:Se(this.address,r,r,o,a)});return{...s,unwrapRequestId:this.#c(s.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=await S(`unwrapAll`,this.sdk.signer,this.sdk.provider),t=z(e.address),n=await this.readConfidentialBalanceOf(t);if(ct(n))throw new j(`Cannot unshield: balance is zero`);let r=await this.submitTransaction({operation:`unwrapAll`,config:Ce(this.address,t,t,n)});return{...r,unwrapRequestId:this.#c(r.receipt.logs)}}async finalizeUnwrap(e){return this.#s(e,`finalize-unwrap`)}async#s(e,t){this.#r(`finalizeUnwrap`),await Ve(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e],{operation:t}),r=n.clearValues[e];return xe(r,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:De(this.address,e,r,n.decryptionProof)})}#c(e){let t=xn(e.filter(e=>e.address===void 0||z(e.address)===this.address));if(!t)throw new y(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t.unwrapRequestId}async#l(e){try{return await this.sdk.provider.readContract(Te(this.address,e))===Kt}catch{return!1}}async#u(e){let t=e.unwrapRequestId;if(t===void 0)try{let n=await this.sdk.provider.waitForTransactionReceipt(e.unwrapTxHash);t=this.#c(n.logs)}catch{return!1}return this.#l(t)}async#d(e){await _(`${e}: clearPendingUnshield`,()=>Bn(this.sdk.storage,this.address),this.sdk.logger)}async#f(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(me(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#p(e,t,n,r,i){this.emit({type:h.UnshieldPhase1Submitted,txHash:t,operationId:n}),await _(`unshield: savePendingUnshield`,()=>Rn(this.sdk.storage,this.address,t,e),this.sdk.logger),this.emit({type:h.UnshieldPhase2Started,operationId:n}),_(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#s(e,i)}catch(n){throw on(n)||n instanceof y&&await this.#l(e)?(await this.#d(`unshield`),new nn(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:h.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),_(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#d(`unshield`),a}async#m(e,t,n){this.#r(`approveUnderlying`);let r=await this.#f(),i=await S(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=z(i.address),o=await this.sdk.provider.readContract(b(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:x(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:x(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const Hn=B.union([B.bigint(),B.boolean(),a]),Un=B.array(B.string());var Wn=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=Hn.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=z(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${z(e)}:${z(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Un.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function Gn(e,t){let n=Kn(e,t);if(!n)throw new j(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function Kn(e,t){let n=i(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const qn=e=>new Promise(t=>setTimeout(t,e));var Jn=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=z(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=z(t),o=z(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:z(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof G))throw t;await qn(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0,operation:o}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:z(e.contractAddress)}));if(s.length===0)return{items:s};let c=z(r);try{let e=await this.delegatedDecryptValues(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:a,operation:o});for(let t of s)this.#d(t,e);return{items:s}}catch(e){if(kt(e))throw e;if(s.length===1){let[n=this.#p()]=s;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:z(t)}),{items:s}}}let l=!1,u;if(await dt(s.map(e=>async()=>{if(!l)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,c,{waitForPropagation:!1,operation:o});this.#d(e,r)}catch(n){if(kt(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:z(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=Gn(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&nt(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,r={spent:!1}){if(e.length===0)return{};let i=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:z(e.contractAddress)})),a={},o=[];for(let e of i)ct(e.encryptedValue)?a[e.encryptedValue]=0n:o.push(e);if(o.length===0)return a;let s=Array.from(new Set(i.map(e=>e.contractAddress))),c=Array.from(new Set(o.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(c)}catch(e){throw st(e)?this.#u(e,`the delegation pre-check`):e}let l=[];for(let e of o){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?l.push(e):a[e.encryptedValue]=n}if(l.length===0)return a;let u=await this.#t.grantPermit(s,t.delegator),d=/* @__PURE__ */ new Map;for(let e of l){let t=d.get(e.contractAddress);t?t.push(e.encryptedValue):d.set(e.contractAddress,[e.encryptedValue])}let f=[];for(let[e,t]of d)for(let n of _t(t))f.push({contractAddress:e,encryptedValues:n});let p=Date.now(),m=l.map(e=>e.encryptedValue);try{this.#i({type:h.DecryptStart,encryptedValues:m});try{await this.#c(t,u,f,a,n)}catch(e){if(!(e instanceof M)||r.spent)throw e;let i=u.permissions.map(e=>e.serializedPermit.signature);r.spent=!0;try{u=await this.#t.recoverPermits(s,t.delegator,i)}catch(e){throw e instanceof Dt?new M(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(t,u,f.filter(({encryptedValues:e})=>e.some(e=>a[e]===void 0)),a,n)}let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:h.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),a}catch(e){let n=e instanceof D&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:C(n),durationMs:Date.now()-p,encryptedValues:m}),K(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await dt(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(a.length>0)throw a.find(e=>e instanceof M)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw K(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new j(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new j(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new N(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:w(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new j(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`):e.value=n}#f(e,t,n){return e instanceof D?e:K(e,t,n)}#p(){throw new j(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};const Yn={AlreadyDelegatedOrRevokedInSameBlock:e=>new Yt(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new $t(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new en(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new V(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new U(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new Qt(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new W(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new Zt(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new H(`Cannot revoke: no active delegation exists.`,{cause:e})};function Xn(e){return Object.hasOwn(Yn,e)}function Zn(e,t){let n=tn(e);if(n&&Xn(n))return Yn[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Yn))if(r.includes(e))return n(t);return null}var Qn=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new W(`Expiration date must be at least 1 hour in the future`);let a=z(t),o=z(n),s=z(r);if(o===s)throw new V(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===z(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new Qt(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new U(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):J,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new Zt(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==z(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:dn(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=z(t),a=z(n),o=z(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new H(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:fn(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=z(e.contractAddress)===Y,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:Y})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:Y});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==J}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===J?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(pn(r,z(t),z(n),z(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await pt({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof y))return;let t=Zn(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof H||t instanceof Xt){let n=z(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=z(e),i=z(t),a=z(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new H(`No active delegation from ${i} to ${a} for ${r}`):new Xt(`Delegation from ${i} to ${a} for ${r} has expired`)}},$n=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=z(e.contractAddress);try{this.#t({type:h.EncryptStart},r);let i=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:h.EncryptEnd,durationMs:Date.now()-n},r),i}catch(e){throw this.#t({type:h.EncryptError,error:C(e),durationMs:Date.now()-n},r),cn(e,`Encryption failed`)}}},er=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.clearCredentialsOnWalletChange,this.#a=e.logger,this.#e&&(this.#s=this.#e.walletAccount.subscribe(e=>{this.#c(e).catch(e=>{this.#a.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#o.add(e),()=>{this.#o.delete(e)}}dispose(){this.#s?.(),this.#s=void 0,this.#o.clear()}async#c(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await _(`switch relayer chain`,()=>this.#t.switchChain(r),this.#a),this.#i&&await this.#l(t,n),await Promise.all(Array.from(this.#o,t=>_(`wallet account listener`,()=>t(e),this.#a)))}async#l(e,t){let n=this.#r;n&&await _(`credential wallet account change`,()=>n.handleWalletAccountChange(e,t),this.#a),e&&await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e.address),this.#a)}};const tr=B.object({kind:B.literal(`ConfidentialTransfer`),from:a,token:a,to:a,amount:B.bigint()}),nr=B.object({kind:B.literal(`ConfidentialTransferFrom`),from:a,token:a,owner:a,to:a,amount:B.bigint()}),rr=B.object({kind:B.literal(`SetOperator`),from:a,token:a,operator:a,until:u}),ir=B.object({kind:B.literal(`Unwrap`),from:a,token:a,to:a,amount:B.bigint()}),ar=B.object({kind:B.literal(`UnwrapAll`),from:a,token:a,to:a}),or=B.object({kind:B.literal(`FinalizeUnwrap`),from:a,wrapper:a,unwrapRequestIdOrAmount:p}),sr=B.object({kind:B.literal(`ApproveUnderlying`),from:a,underlying:a,spender:a,amount:B.bigint()}),cr=B.object({kind:B.literal(`Wrap`),from:a,wrapper:a,to:a,amount:B.bigint()}),lr=p.check(B.refine(e=>e===`0x`||Wt(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),ur=B.object({kind:B.literal(`TransferAndCall`),from:a,underlying:a,wrapper:a,amount:B.bigint(),recipientData:B.optional(lr)}),dr=B.object({kind:B.literal(`DelegateDecryption`),from:a,contractAddress:a,delegateAddress:a,expirationDate:B.optional(B.date())}),fr=B.object({kind:B.literal(`RevokeDelegation`),from:a,contractAddress:a,delegateAddress:a});B.discriminatedUnion(`kind`,[tr,nr,rr,ir,ar,or,sr,cr,ur,dr,fr]);const pr=B.strictObject({maxFeePerGas:B.bigint(),maxPriorityFeePerGas:B.bigint()}),mr=B.object({nonce:B.optional(B.int().check(B.nonnegative())),gasLimit:B.optional(B.bigint()),fees:B.optional(pr)}),hr=B.object({address:a,abi:B.array(B.unknown()),functionName:B.string(),args:B.array(B.unknown()),value:B.optional(B.bigint()),gas:B.optional(B.bigint())}),gr=B.extend(mr,{from:a,calldata:hr});var _r=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=R(mr,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new O(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},a=R(gr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw gt(t,`prepare ${e.kind}`)??t});return{kind:e.kind,unsignedTx:o,from:a.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new O(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=R(tr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer`}),r=t[0];if(!r)throw new A(`Encryption returned no handles for ConfidentialTransfer`);return Ee(e.token,e.to,r,n)}async#a(e){e=R(nr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer-from`}),r=t[0];if(!r)throw new A(`Encryption returned no handles for ConfidentialTransferFrom`);return qe(e.token,e.owner,e.to,r,n)}#o(e){return e=R(rr,e),Re(e.token,e.operator,e.until)}async#s(e){e=R(ir,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-unwrap`}),r=t[0];if(!r)throw new A(`Encryption returned no handles for Unwrap`);return Se(e.token,e.from,e.to,r,n)}async#c(e){e=R(ar,e);let t=await this.#e.readContract(Ye(e.token,e.from));return Ce(e.token,e.from,e.to,t)}async#l(e){e=R(or,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount],options:{operation:`offline-finalize-unwrap`}}).catch(e=>{throw K(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return xe(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),De(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=R(sr,e),x(e.underlying,e.spender,e.amount)}#d(e){return e=R(cr,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=R(ur,e),un(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=R(dr,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new W(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new V(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new U(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):J;return dn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=R(fr,e),fn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function vr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new O(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function yr(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new O(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function br(e){if(e===void 0)return;let t=R(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var xr=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){vr(t),yr(t.transportKeyPairDerivationSecret);let n=br(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new Wn(e.storage,this.#i),this.#u=new Qn({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new f({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new ee({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new Jn({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new $n({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new er({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new _r({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new jn({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new Mn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new Nn({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new Pn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new f({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,L(t,`encrypt`))}createToken(e){return new vt(this,e)}createWrappedToken(e){return new Vn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{An as ACL_TOPICS,en as AclPausedError,Q as AclTopics,ft as BalanceCheckUnavailableError,te as BaseSigner,Ue as ChainMismatchError,Fn as ChromeSessionStorage,O as ConfigurationError,Nn as Decryption,j as DecryptionFailedError,n as DefaultRegistryAddresses,$t as DelegationContractIsSelfError,Yt as DelegationCooldownError,Qt as DelegationDelegateCannotBeWildcardError,U as DelegationDelegateEqualsContractError,W as DelegationExpirationTooSoonError,Xt as DelegationExpiredError,Zt as DelegationExpiryUnchangedError,H as DelegationNotFoundError,G as DelegationNotPropagatedError,V as DelegationSelfNotAllowedError,Mn as Delegations,Me as ERC1363_INTERFACE_ID,k as ERC20ReadFailedError,He as ERC7984_INTERFACE_ID,We as ERC7984_WRAPPER_INTERFACE_ID,yt as EncryptOffloadUnavailableError,A as EncryptionFailedError,be as HcuBlockLimitExceededError,Ae as HcuTransactionLimitExceededError,t as IndexedDBStorage,lt as InsufficientAllowanceError,ut as InsufficientConfidentialBalanceError,ht as InsufficientERC20BalanceError,Ct as InvalidTransportKeyPairError,bt as KeyWrappingError,J as MAX_UINT64,s as MemoryStorage,d as MutableWalletAccountStore,Tt as NoCiphertextError,Jt as NotEntitledError,Pn as Offline,jn as Permits,Et as PreparedPermitChainMismatchError,xt as PreparedPermitExpiredError,E as RelayerRequestFailedError,M as RevokedKmsContextError,N as RpcRateLimitError,ye as SignerNotConfiguredError,Oe as SignerRequiredError,Dt as SigningFailedError,wt as SigningRejectedError,Cn as TOKEN_TOPICS,vt as Token,X as Topics,y as TransactionRevertedError,Ot as TransportKeyPairChangedError,St as TransportKeyPairExpiredError,nn as UnshieldAlreadyFinalizedError,Ft as VaultBatchNotDispatchedError,At as VaultBatcherPausedError,Mt as VaultJoinUnconfirmedError,Y as WILDCARD_CONTRACT,ke as WalletAccountNotReadyError,ve as WalletNotConnectedError,Vn as WrappedToken,f as WrappersRegistry,mt as ZERO_ENCRYPTED_VALUE,D as ZamaError,T as ZamaErrorCode,xr as ZamaSDK,h as ZamaSDKEvents,b as allowanceContract,fe as anvil,x as approveContract,Be as balanceOfContract,ce as bscTestnet,ue as chains,In as chromeSessionStorage,e as cleartext,Ye as confidentialBalanceOfContract,Ne as confidentialTotalSupplyContract,Je as confidentialTransferAndCallContract,Ee as confidentialTransferContract,he as confidentialTransferFromAndCallContract,qe as confidentialTransferFromContract,hn as createConfig,m as createWalletAccountStore,Ie as decimalsContract,En as decodeAclEvent,Dn as decodeAclEvents,gn as decodeConfidentialTransfer,wn as decodeDelegatedForUserDecryption,yn as decodeOnChainEvent,bn as decodeOnChainEvents,Tn as decodeRevokedDelegationForUserDecryption,vn as decodeUnwrapFinalized,_n as decodeUnwrapRequested,Z as decodeWrap,dn as delegateForUserDecryptionContract,De as finalizeUnwrapContract,On as findDelegatedForUserDecryption,kn as findRevokedDelegationForUserDecryption,xn as findUnwrapRequested,Sn as findWrap,Ht as getConfidentialTokenAddressContract,pn as getDelegationExpiryContract,Rt as getTokenAddressContract,Bt as getTokenPairContract,Lt as getTokenPairsContract,It as getTokenPairsLengthContract,zt as getTokenPairsSliceContract,oe as hardhat,ie as hoodi,re as indexedDBStorage,_e as inferredTotalSupplyContract,Pe as isConfidentialTokenContract,Vt as isConfidentialTokenValidContract,ze as isConfidentialWrapperContract,ct as isEncryptedValueZero,mn as isHandleDelegatedContract,ge as isOperatorContract,Qe as isRetryable,le as mainnet,qt as matchZamaError,o as memoryStorage,je as nameContract,r as parsePreparedPermit,de as polygon,ae as polygonAmoy,we as rateContract,rt as retryAfterSeconds,fn as revokeDelegationContract,se as sepolia,Re as setOperatorContract,Fe as supportsInterfaceContract,Ke as symbolContract,un as transferAndCallContract,me as underlyingContract,Le as unwrapAmountContract,Se as unwrapContract,Ce as unwrapFromBalanceContract,Te as unwrapRequesterContract,g as wrapContract,pe as zenithTrexTestnet};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{b as e,i as t,r as n}from"../relayer-nWfQAlo7.js";import{t as r}from"../fatal-batch-BYeHrf0V.js";import{n as i}from"../fhevm-relayer-CFQaXXPp.js";import{t as a}from"../typed-data-eAgGr9V-.js";const o=r;function s(r,i,a){let s=o[r],c=s?new s(i):new n(r,i,r===t.RelayerRequestFailed?{retryable:a.retryable}:void 0);return c.retryable&&e(a.retryAfter)?Object.assign(c,{retryAfter:a.retryAfter}):c}function c(e,t){return e.onWalletAccountChange(t)}export{s as reviveZamaError,c as subscribeWalletAccountChanges,i as toFhevmAuth,a as toViemTypedData};
1
+ import{b as e,i as t,r as n}from"../relayer-nWfQAlo7.js";import{t as r}from"../fatal-batch-BYeHrf0V.js";import{n as i}from"../fhevm-relayer-Da6yGHJQ.js";import{t as a}from"../typed-data-eAgGr9V-.js";const o=r;function s(r,i,a){let s=o[r],c=s?new s(i):new n(r,i,r===t.RelayerRequestFailed?{retryable:a.retryable}:void 0);return c.retryable&&e(a.retryAfter)?Object.assign(c,{retryAfter:a.retryAfter}):c}function c(e,t){return e.onWalletAccountChange(t)}export{s as reviveZamaError,c as subscribeWalletAccountChanges,i as toFhevmAuth,a as toViemTypedData};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{t as e}from"../fhevm-relayer-CFQaXXPp.js";import{t}from"../telemetry-BCZsKGmH.js";import{t as n}from"../cleartext-BPIXzovl.js";import{a as r,c as i,i as a,l as o,n as s,o as c,r as l,s as u,t as d,u as f}from"../chains-BQXSxIwU.js";import{AsyncLocalStorage as p}from"node:async_hooks";function m(n){return{type:`node`,createRelayer:(r,i,a)=>{let o=t(globalThis.process?.env?.ZAMA_SDK_TELEMETRY)??a?.mode;return new e({chain:r,options:n,logger:i,telemetry:a&&o!==void 0&&o!==`off`?{state:a,runtime:`node`,mode:o}:void 0})}}}var h=class{#e=new p;run(e){return this.#e.run(/* @__PURE__ */ 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 g=new h;export{h as AsyncLocalMapStorage,d as anvil,g as asyncLocalStorage,s as bscTestnet,l as chains,n as cleartext,a as hardhat,r as hoodi,c as mainnet,m as node,u as polygon,i as polygonAmoy,o as sepolia,f as zenithTrexTestnet};
1
+ import{t as e}from"../fhevm-relayer-Da6yGHJQ.js";import{t}from"../telemetry-DZs0eTBf.js";import{t as n}from"../cleartext-DcCwbO5i.js";import{a as r,c as i,i as a,l as o,n as s,o as c,r as l,s as u,t as d,u as f}from"../chains-BQXSxIwU.js";import{AsyncLocalStorage as p}from"node:async_hooks";function m(n){return{type:`node`,createRelayer:(r,i,a)=>{let o=t(globalThis.process?.env?.ZAMA_SDK_TELEMETRY)??a?.mode;return new e({chain:r,options:n,logger:i,telemetry:a&&o!==void 0&&o!==`off`?{state:a,runtime:`node`,mode:o}:void 0})}}}var h=class{#e=new p;run(e){return this.#e.run(/* @__PURE__ */ 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 g=new h;export{h as AsyncLocalMapStorage,d as anvil,g as asyncLocalStorage,s as bscTestnet,l as chains,n as cleartext,a as hardhat,r as hoodi,c as mainnet,m as node,u as polygon,i as polygonAmoy,o as sepolia,f as zenithTrexTestnet};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- let e,t=!1;function n(n){e=Object.freeze({wasmAssetLoadMode:n.wasmAssetLoadMode,moduleVersions:n.moduleVersions,singleThread:n.singleThread,numberOfThreads:n.numberOfThreads,auth:n.auth}),t=n.locateFile!==void 0}function r(){return e}function i(){return t}function a(e,t){let{layer:n,daemonClient:r}=e.state,i=Object.entries({version:`3.9.0-beta.1`,layer:n,...r===void 0?{runtime:e.runtime}:{runtime:`daemon`,client:r},...t!==void 0&&{operation:t}}),a=e=>Object.fromEntries(i.map(([t,n])=>[`${e}${t}`,n]));return e.mode===`query`?{query:a(`zama_sdk_`)}:{headers:a(`x-zama-sdk-`)}}function o(e,t){return Object.assign({},e,{operation:e?.operation??t})}function s(e){if(typeof e==`boolean`)return e?`header`:`off`;let t=typeof e==`string`?e.trim().toLowerCase():void 0;return t===`0`||t===`false`?`off`:t===`header`||t===`query`||t===`off`?t:void 0}export{i as a,r as i,a as n,n as o,o as r,s as t};
2
- //# sourceMappingURL=telemetry-BCZsKGmH.js.map
1
+ let e,t=!1;function n(n){e=Object.freeze({wasmAssetLoadMode:n.wasmAssetLoadMode,moduleVersions:n.moduleVersions,singleThread:n.singleThread,numberOfThreads:n.numberOfThreads,auth:n.auth}),t=n.locateFile!==void 0}function r(){return e}function i(){return t}function a(e,t){let{layer:n,daemonClient:r}=e.state,i=Object.entries({version:`3.9.0-beta.3`,layer:n,...r===void 0?{runtime:e.runtime}:{runtime:`daemon`,client:r},...t!==void 0&&{operation:t}}),a=e=>Object.fromEntries(i.map(([t,n])=>[`${e}${t}`,n]));return e.mode===`query`?{query:a(`zama_sdk_`)}:{headers:a(`x-zama-sdk-`)}}function o(e,t){return Object.assign({},e,{operation:e?.operation??t})}function s(e){if(typeof e==`boolean`)return e?`header`:`off`;let t=typeof e==`string`?e.trim().toLowerCase():void 0;return t===`0`||t===`false`?`off`:t===`header`||t===`query`||t===`off`?t:void 0}export{i as a,r as i,a as n,n as o,o as r,s as t};
2
+ //# sourceMappingURL=telemetry-DZs0eTBf.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-BCZsKGmH.js","names":["packageJson.version","appliedWireRuntime","appliedLocateFile","recordAppliedRuntimeConfig","runtime","getAppliedWireRuntime","hasAppliedLocateFile","telemetryRequestOptions","telemetry","fields","daemonClient","operation","prefixed","name","value","prefix","withOperation","options","parseTelemetryMode","mode"],"sources":["../../src/relayer/applied-runtime.ts","../../package.json","../../src/version.ts","../../src/telemetry.ts"],"sourcesContent":["import type { FhevmRuntimeConfig, WireRuntimeConfig } from \"./types\";\n\n/**\n * Mirror of the runtime config this package applied via the upstream\n * `setFhevmRuntimeConfig`, which is itself a process-wide one-shot. An encrypt\n * worker realm replicates it, since the upstream lock offers no getter.\n */\nlet appliedWireRuntime: WireRuntimeConfig | undefined;\n\n/** `locateFile` is a function, so it stays off the wire and is only flagged here. */\nlet appliedLocateFile = false;\n\n/** Projects the applied runtime onto the fields a worker realm replicates. */\nexport function recordAppliedRuntimeConfig(runtime: FhevmRuntimeConfig): void {\n appliedWireRuntime = Object.freeze({\n wasmAssetLoadMode: runtime.wasmAssetLoadMode,\n moduleVersions: runtime.moduleVersions,\n singleThread: runtime.singleThread,\n numberOfThreads: runtime.numberOfThreads,\n auth: runtime.auth,\n });\n appliedLocateFile = runtime.locateFile !== undefined;\n}\n\n/** `undefined` when the upstream lock was set outside this package. */\nexport function getAppliedWireRuntime(): WireRuntimeConfig | undefined {\n return appliedWireRuntime;\n}\n\nexport function hasAppliedLocateFile(): boolean {\n return appliedLocateFile;\n}\n\n/** @internal */\nexport function resetAppliedRuntimeConfig(): void {\n appliedWireRuntime = undefined;\n appliedLocateFile = false;\n}\n","","import packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const SDK_VERSION: string = packageJson.version;\n","import { SDK_VERSION } from \"./version\";\n\n// No telemetry field may carry a wallet address, encrypted value, amount or identifier.\n\nexport type TelemetryLayer = \"core\" | \"react\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryRuntime = \"web\" | \"node\" | \"daemon\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryClient = \"go\" | \"rust\" | \"unknown\";\n\nexport type TelemetryMode = \"header\" | \"query\" | \"off\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive method renames. */\nexport type TelemetryOperation =\n | \"balance-of\"\n | \"decrypt-balance-as\"\n | \"batch-balances-of\"\n | \"batch-decrypt-balances-as\"\n | \"confidential-transfer\"\n | \"confidential-transfer-from\"\n | \"confidential-transfer-and-call\"\n | \"confidential-transfer-from-and-call\"\n | \"unshield\"\n | \"unshield-all\"\n | \"resume-unshield\"\n | \"unwrap\"\n | \"finalize-unwrap\"\n | \"vault-deposit\"\n | \"vault-redeem\"\n | \"vault-join\"\n | \"vault-deposit-of\"\n | \"vault-finalize\"\n | \"encrypt\"\n | \"decrypt-values\"\n | \"delegated-decrypt-values\"\n | \"delegated-batch-decrypt-values\"\n | \"decrypt-public-values\"\n | \"offline-confidential-transfer\"\n | \"offline-confidential-transfer-from\"\n | \"offline-unwrap\"\n | \"offline-finalize-unwrap\";\n\n/**\n * Shared by every relayer of a config; `layer` and `daemonClient` are set on it\n * after the relayers exist.\n *\n * @internal\n */\nexport interface TelemetryState {\n layer: TelemetryLayer;\n /** Set only by the daemon; overrides the reported runtime with `daemon`. */\n daemonClient?: TelemetryClient;\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport interface RelayerTelemetry {\n readonly state: TelemetryState;\n readonly runtime: Exclude<TelemetryRuntime, \"daemon\">;\n /** The config's `mode`, unless `ZAMA_SDK_TELEMETRY` overrode it on Node. */\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport function telemetryRequestOptions(\n telemetry: RelayerTelemetry,\n operation: TelemetryOperation | undefined,\n): { headers?: Record<string, string>; query?: Record<string, string> } {\n const { layer, daemonClient } = telemetry.state;\n const fields = Object.entries({\n version: SDK_VERSION,\n layer,\n ...(daemonClient === undefined\n ? { runtime: telemetry.runtime }\n : { runtime: \"daemon\" satisfies TelemetryRuntime, client: daemonClient }),\n ...(operation !== undefined && { operation }),\n });\n const prefixed = (prefix: string) =>\n Object.fromEntries(fields.map(([name, value]) => [`${prefix}${name}`, value]));\n return telemetry.mode === \"query\"\n ? { query: prefixed(\"zama_sdk_\") }\n : { headers: prefixed(\"x-zama-sdk-\") };\n}\n\n/** `options` labelled with `operation`, unless the caller already labelled it. */\nexport function withOperation<T extends { readonly operation?: TelemetryOperation }>(\n options: T | undefined,\n operation: TelemetryOperation,\n): Partial<T> & { readonly operation: TelemetryOperation } {\n return Object.assign({}, options, { operation: options?.operation ?? operation });\n}\n\nexport function parseTelemetryMode(value: string | boolean | undefined): TelemetryMode | undefined {\n if (typeof value === \"boolean\") {\n return value ? \"header\" : \"off\";\n }\n // JavaScript callers can pass anything; only a string can name a mode.\n const mode = typeof value === \"string\" ? value.trim().toLowerCase() : undefined;\n // `0` and `false` predate the named modes and still mean off.\n if (mode === \"0\" || mode === \"false\") {\n return \"off\";\n }\n return mode === \"header\" || mode === \"query\" || mode === \"off\" ? mode : undefined;\n}\n"],"mappings":"AAOA,IAAIC,EAGAC,EAAoB,GAGxB,SAAgBC,EAA2B,EAAmC,CAC5E,EAAqB,OAAO,OAAO,CACjC,kBAAmBC,EAAQ,kBAC3B,eAAgBA,EAAQ,eACxB,aAAcA,EAAQ,aACtB,gBAAiBA,EAAQ,gBACzB,KAAMA,EAAQ,IAChB,CAAC,EACD,EAAoBA,EAAQ,aAAe,IAAA,EAC7C,CAGA,SAAgBC,GAAuD,CACrE,OAAOJ,CACT,CAEA,SAAgBK,GAAgC,CAC9C,OAAOJ,CACT,CGiCA,SAAgBK,EACd,EACA,EACsE,CACtE,GAAM,CAAE,QAAO,gBAAiBC,EAAU,MACpCC,EAAS,OAAO,QAAQ,CAC5B,QAAS,eACT,QACA,GAAIC,IAAiB,IAAA,GACjB,CAAE,QAASF,EAAU,OAAQ,EAC7B,CAAE,QAAS,SAAqC,OAAQE,CAAa,EACzE,GAAIC,IAAc,IAAA,IAAa,CAAE,WAAU,CAC7C,CAAC,EACKC,EAAY,GAChB,OAAO,YAAYH,EAAO,KAAK,CAACI,EAAMC,KAAW,CAAC,GAAGC,IAASF,IAAQC,CAAK,CAAC,CAAC,EAC/E,OAAON,EAAU,OAAS,QACtB,CAAE,MAAOI,EAAS,WAAW,CAAE,EAC/B,CAAE,QAASA,EAAS,aAAa,CAAE,CACzC,CAGA,SAAgBI,EACd,EACA,EACyD,CACzD,OAAO,OAAO,OAAO,CAAC,EAAGC,EAAS,CAAE,UAAWA,GAAS,WAAaN,CAAU,CAAC,CAClF,CAEA,SAAgBO,EAAmB,EAAgE,CACjG,GAAI,OAAOJ,GAAU,UACnB,OAAOA,EAAQ,SAAW,MAG5B,IAAMK,EAAO,OAAOL,GAAU,SAAWA,EAAM,KAAK,CAAC,CAAC,YAAY,EAAI,IAAA,GAKtE,OAHIK,IAAS,KAAOA,IAAS,QACpB,MAEFA,IAAS,UAAYA,IAAS,SAAWA,IAAS,MAAQA,EAAO,IAAA,EAC1E,C"}
1
+ {"version":3,"file":"telemetry-DZs0eTBf.js","names":["packageJson.version","appliedWireRuntime","appliedLocateFile","recordAppliedRuntimeConfig","runtime","getAppliedWireRuntime","hasAppliedLocateFile","telemetryRequestOptions","telemetry","fields","daemonClient","operation","prefixed","name","value","prefix","withOperation","options","parseTelemetryMode","mode"],"sources":["../../src/relayer/applied-runtime.ts","../../package.json","../../src/version.ts","../../src/telemetry.ts"],"sourcesContent":["import type { FhevmRuntimeConfig, WireRuntimeConfig } from \"./types\";\n\n/**\n * Mirror of the runtime config this package applied via the upstream\n * `setFhevmRuntimeConfig`, which is itself a process-wide one-shot. An encrypt\n * worker realm replicates it, since the upstream lock offers no getter.\n */\nlet appliedWireRuntime: WireRuntimeConfig | undefined;\n\n/** `locateFile` is a function, so it stays off the wire and is only flagged here. */\nlet appliedLocateFile = false;\n\n/** Projects the applied runtime onto the fields a worker realm replicates. */\nexport function recordAppliedRuntimeConfig(runtime: FhevmRuntimeConfig): void {\n appliedWireRuntime = Object.freeze({\n wasmAssetLoadMode: runtime.wasmAssetLoadMode,\n moduleVersions: runtime.moduleVersions,\n singleThread: runtime.singleThread,\n numberOfThreads: runtime.numberOfThreads,\n auth: runtime.auth,\n });\n appliedLocateFile = runtime.locateFile !== undefined;\n}\n\n/** `undefined` when the upstream lock was set outside this package. */\nexport function getAppliedWireRuntime(): WireRuntimeConfig | undefined {\n return appliedWireRuntime;\n}\n\nexport function hasAppliedLocateFile(): boolean {\n return appliedLocateFile;\n}\n\n/** @internal */\nexport function resetAppliedRuntimeConfig(): void {\n appliedWireRuntime = undefined;\n appliedLocateFile = false;\n}\n","","import packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const SDK_VERSION: string = packageJson.version;\n","import { SDK_VERSION } from \"./version\";\n\n// No telemetry field may carry a wallet address, encrypted value, amount or identifier.\n\nexport type TelemetryLayer = \"core\" | \"react\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryRuntime = \"web\" | \"node\" | \"daemon\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryClient = \"go\" | \"rust\" | \"unknown\";\n\nexport type TelemetryMode = \"header\" | \"query\" | \"off\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive method renames. */\nexport type TelemetryOperation =\n | \"balance-of\"\n | \"decrypt-balance-as\"\n | \"batch-balances-of\"\n | \"batch-decrypt-balances-as\"\n | \"confidential-transfer\"\n | \"confidential-transfer-from\"\n | \"confidential-transfer-and-call\"\n | \"confidential-transfer-from-and-call\"\n | \"unshield\"\n | \"unshield-all\"\n | \"resume-unshield\"\n | \"unwrap\"\n | \"finalize-unwrap\"\n | \"vault-deposit\"\n | \"vault-redeem\"\n | \"vault-join\"\n | \"vault-deposit-of\"\n | \"vault-finalize\"\n | \"encrypt\"\n | \"decrypt-values\"\n | \"delegated-decrypt-values\"\n | \"delegated-batch-decrypt-values\"\n | \"decrypt-public-values\"\n | \"offline-confidential-transfer\"\n | \"offline-confidential-transfer-from\"\n | \"offline-unwrap\"\n | \"offline-finalize-unwrap\";\n\n/**\n * Shared by every relayer of a config; `layer` and `daemonClient` are set on it\n * after the relayers exist.\n *\n * @internal\n */\nexport interface TelemetryState {\n layer: TelemetryLayer;\n /** Set only by the daemon; overrides the reported runtime with `daemon`. */\n daemonClient?: TelemetryClient;\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport interface RelayerTelemetry {\n readonly state: TelemetryState;\n readonly runtime: Exclude<TelemetryRuntime, \"daemon\">;\n /** The config's `mode`, unless `ZAMA_SDK_TELEMETRY` overrode it on Node. */\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport function telemetryRequestOptions(\n telemetry: RelayerTelemetry,\n operation: TelemetryOperation | undefined,\n): { headers?: Record<string, string>; query?: Record<string, string> } {\n const { layer, daemonClient } = telemetry.state;\n const fields = Object.entries({\n version: SDK_VERSION,\n layer,\n ...(daemonClient === undefined\n ? { runtime: telemetry.runtime }\n : { runtime: \"daemon\" satisfies TelemetryRuntime, client: daemonClient }),\n ...(operation !== undefined && { operation }),\n });\n const prefixed = (prefix: string) =>\n Object.fromEntries(fields.map(([name, value]) => [`${prefix}${name}`, value]));\n return telemetry.mode === \"query\"\n ? { query: prefixed(\"zama_sdk_\") }\n : { headers: prefixed(\"x-zama-sdk-\") };\n}\n\n/** `options` labelled with `operation`, unless the caller already labelled it. */\nexport function withOperation<T extends { readonly operation?: TelemetryOperation }>(\n options: T | undefined,\n operation: TelemetryOperation,\n): Partial<T> & { readonly operation: TelemetryOperation } {\n return Object.assign({}, options, { operation: options?.operation ?? operation });\n}\n\nexport function parseTelemetryMode(value: string | boolean | undefined): TelemetryMode | undefined {\n if (typeof value === \"boolean\") {\n return value ? \"header\" : \"off\";\n }\n // JavaScript callers can pass anything; only a string can name a mode.\n const mode = typeof value === \"string\" ? value.trim().toLowerCase() : undefined;\n // `0` and `false` predate the named modes and still mean off.\n if (mode === \"0\" || mode === \"false\") {\n return \"off\";\n }\n return mode === \"header\" || mode === \"query\" || mode === \"off\" ? mode : undefined;\n}\n"],"mappings":"AAOA,IAAIC,EAGAC,EAAoB,GAGxB,SAAgBC,EAA2B,EAAmC,CAC5E,EAAqB,OAAO,OAAO,CACjC,kBAAmBC,EAAQ,kBAC3B,eAAgBA,EAAQ,eACxB,aAAcA,EAAQ,aACtB,gBAAiBA,EAAQ,gBACzB,KAAMA,EAAQ,IAChB,CAAC,EACD,EAAoBA,EAAQ,aAAe,IAAA,EAC7C,CAGA,SAAgBC,GAAuD,CACrE,OAAOJ,CACT,CAEA,SAAgBK,GAAgC,CAC9C,OAAOJ,CACT,CGiCA,SAAgBK,EACd,EACA,EACsE,CACtE,GAAM,CAAE,QAAO,gBAAiBC,EAAU,MACpCC,EAAS,OAAO,QAAQ,CAC5B,QAAS,eACT,QACA,GAAIC,IAAiB,IAAA,GACjB,CAAE,QAASF,EAAU,OAAQ,EAC7B,CAAE,QAAS,SAAqC,OAAQE,CAAa,EACzE,GAAIC,IAAc,IAAA,IAAa,CAAE,WAAU,CAC7C,CAAC,EACKC,EAAY,GAChB,OAAO,YAAYH,EAAO,KAAK,CAACI,EAAMC,KAAW,CAAC,GAAGC,IAASF,IAAQC,CAAK,CAAC,CAAC,EAC/E,OAAON,EAAU,OAAS,QACtB,CAAE,MAAOI,EAAS,WAAW,CAAE,EAC/B,CAAE,QAASA,EAAS,aAAa,CAAE,CACzC,CAGA,SAAgBI,EACd,EACA,EACyD,CACzD,OAAO,OAAO,OAAO,CAAC,EAAGC,EAAS,CAAE,UAAWA,GAAS,WAAaN,CAAU,CAAC,CAClF,CAEA,SAAgBO,EAAmB,EAAgE,CACjG,GAAI,OAAOJ,GAAU,UACnB,OAAOA,EAAQ,SAAW,MAG5B,IAAMK,EAAO,OAAOL,GAAU,SAAWA,EAAM,KAAK,CAAC,CAAC,YAAY,EAAI,IAAA,GAKtE,OAHIK,IAAS,KAAOA,IAAS,QACpB,MAEFA,IAAS,UAAYA,IAAS,SAAWA,IAAS,MAAQA,EAAO,IAAA,EAC1E,C"}
@@ -1,2 +1,2 @@
1
- import{A as e,B as t,F as n,G as r,M as i,N as a,S as o,T as s,X as c,d as l,k as u,r as d,y as f}from"../alignment-o-YIndFR.js";import{i as p,t as m}from"../base-signer-LWfNMbWV.js";import{t as h}from"../eip1193-subscribe-DxAQh8dY.js";import{t as g}from"../typed-data-eAgGr9V-.js";import{a as _,i as v,n as y,o as b,r as x,s as S,t as C}from"../wrappers-registry-Cm3JJeqx.js";import{encodeFunctionData as w,getAddress as T,serializeTransaction as E}from"viem";var D=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){let{chainId:t,...n}=e;return await d(`ViemProvider`,t,()=>this.getChainId()),this.#e.readContract(n)}async multicall(e){return await d(`ViemProvider`,e.chainId,()=>this.getChainId()),await this.#e.multicall({contracts:e.calls.map(({chainId:e,...t})=>t),allowFailure:!1,deployless:this.#e.chain?.contracts?.multicall3===void 0})}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getBlockTimestamp(e){return await d(`ViemProvider`,e,()=>this.getChainId()),(await this.#e.getBlock()).timestamp}async prepareTransaction(e){let{from:t,calldata:n}=e,r=w({abi:n.abi,functionName:n.functionName,args:n.args}),i=this.#e.getChainId(),a=e.nonce===void 0?this.#e.getTransactionCount({address:t,blockTag:`pending`}):Promise.resolve(e.nonce),o=e.gasLimit===void 0?n.gas??this.#e.estimateGas({account:t,to:n.address,data:r,value:n.value??0n}).catch(e=>{throw new c(`ViemProvider.prepareTransaction: gas estimation reverted for ${n.functionName} on ${n.address}`,{cause:e})}):Promise.resolve(e.gasLimit),s=e.fees??this.#e.estimateFeesPerGas(),[l,u,d,f]=await Promise.all([i,a,o,s]);return E({type:`eip1559`,chainId:l,nonce:u,to:n.address,data:r,value:n.value??0n,gas:d,maxFeePerGas:f.maxFeePerGas,maxPriorityFeePerGas:f.maxPriorityFeePerGas})}};function O(e){if(e.account&&e.chain)return{address:T(e.account.address),chainId:e.chain.id}}var k=class extends m{#e;#t;#n;constructor(e){super(O(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(e){if(!this.#e.account)throw new r(e);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`);return t.signTypedData({account:n,...g(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?h({provider:this.#t,getInitialWalletAccount:()=>O(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function A(e){let t=new k({walletClient:e.walletClient,ethereum:e.ethereum}),n=new D({publicClient:e.publicClient});return p(t,n,e)}function j(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function M(e,t,n){return e.readContract(f(t,n))}function N(t,n){return t.readContract(e(n))}function P(e,t,n){return e.readContract(l(t,n))}function F(e,t,n,r,i){return e.writeContract({chain:e.chain,account:j(e),...o(t,n,r,i)})}function I(e,t,n,r,a,o){return e.writeContract({chain:e.chain,account:j(e),...i(t,n,r,a,o)})}function L(e,t,n,r,i){return e.writeContract({chain:e.chain,account:j(e),...a(t,n,r,i)})}function R(e,t,n,r,i){return e.writeContract({chain:e.chain,account:j(e),...s(t,n,r,i)})}function z(e,t,n,r){return e.writeContract({chain:e.chain,account:j(e),...u(t,n,r)})}function B(e,t,r,i){return e.writeContract({chain:e.chain,account:j(e),...n(t,r,i)})}function V(e,t){return e.readContract(v(t))}function H(e,t){return e.readContract(_(t))}function U(e,t,n,r){return e.readContract(b(t,n,r))}function W(e,t,n){return e.readContract(x(t,n))}function G(e,t,n){return e.readContract(C(t,n))}function K(e,t,n){return e.readContract(y(t,n))}function q(e,t,n){return e.readContract(S(t,n))}export{m as BaseSigner,D as ViemProvider,k as ViemSigner,t as ZamaSDKEvents,A as createConfig,M as readConfidentialBalanceOfContract,G as readConfidentialTokenAddressContract,q as readIsConfidentialTokenValidContract,P as readSupportsInterfaceContract,K as readTokenAddressContract,W as readTokenPairContract,V as readTokenPairsContract,H as readTokenPairsLengthContract,U as readTokenPairsSliceContract,N as readUnderlyingTokenContract,F as writeConfidentialTransferContract,R as writeFinalizeUnwrapContract,z as writeSetOperatorContract,I as writeUnwrapContract,L as writeUnwrapFromBalanceContract,B as writeWrapContract};
1
+ import{A as e,B as t,F as n,G as r,M as i,N as a,S as o,T as s,X as c,d as l,k as u,r as d,y as f}from"../alignment-o-YIndFR.js";import{i as p,t as m}from"../base-signer-Bst8sJcc.js";import{t as h}from"../eip1193-subscribe-DxAQh8dY.js";import{t as g}from"../typed-data-eAgGr9V-.js";import{a as _,i as v,n as y,o as b,r as x,s as S,t as C}from"../wrappers-registry-Cm3JJeqx.js";import{encodeFunctionData as w,getAddress as T,serializeTransaction as E}from"viem";var D=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){let{chainId:t,...n}=e;return await d(`ViemProvider`,t,()=>this.getChainId()),this.#e.readContract(n)}async multicall(e){return await d(`ViemProvider`,e.chainId,()=>this.getChainId()),await this.#e.multicall({contracts:e.calls.map(({chainId:e,...t})=>t),allowFailure:!1,deployless:this.#e.chain?.contracts?.multicall3===void 0})}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getBlockTimestamp(e){return await d(`ViemProvider`,e,()=>this.getChainId()),(await this.#e.getBlock()).timestamp}async prepareTransaction(e){let{from:t,calldata:n}=e,r=w({abi:n.abi,functionName:n.functionName,args:n.args}),i=this.#e.getChainId(),a=e.nonce===void 0?this.#e.getTransactionCount({address:t,blockTag:`pending`}):Promise.resolve(e.nonce),o=e.gasLimit===void 0?n.gas??this.#e.estimateGas({account:t,to:n.address,data:r,value:n.value??0n}).catch(e=>{throw new c(`ViemProvider.prepareTransaction: gas estimation reverted for ${n.functionName} on ${n.address}`,{cause:e})}):Promise.resolve(e.gasLimit),s=e.fees??this.#e.estimateFeesPerGas(),[l,u,d,f]=await Promise.all([i,a,o,s]);return E({type:`eip1559`,chainId:l,nonce:u,to:n.address,data:r,value:n.value??0n,gas:d,maxFeePerGas:f.maxFeePerGas,maxPriorityFeePerGas:f.maxPriorityFeePerGas})}};function O(e){if(e.account&&e.chain)return{address:T(e.account.address),chainId:e.chain.id}}var k=class extends m{#e;#t;#n;constructor(e){super(O(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(e){if(!this.#e.account)throw new r(e);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`);return t.signTypedData({account:n,...g(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?h({provider:this.#t,getInitialWalletAccount:()=>O(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function A(e){let t=new k({walletClient:e.walletClient,ethereum:e.ethereum}),n=new D({publicClient:e.publicClient});return p(t,n,e)}function j(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function M(e,t,n){return e.readContract(f(t,n))}function N(t,n){return t.readContract(e(n))}function P(e,t,n){return e.readContract(l(t,n))}function F(e,t,n,r,i){return e.writeContract({chain:e.chain,account:j(e),...o(t,n,r,i)})}function I(e,t,n,r,a,o){return e.writeContract({chain:e.chain,account:j(e),...i(t,n,r,a,o)})}function L(e,t,n,r,i){return e.writeContract({chain:e.chain,account:j(e),...a(t,n,r,i)})}function R(e,t,n,r,i){return e.writeContract({chain:e.chain,account:j(e),...s(t,n,r,i)})}function z(e,t,n,r){return e.writeContract({chain:e.chain,account:j(e),...u(t,n,r)})}function B(e,t,r,i){return e.writeContract({chain:e.chain,account:j(e),...n(t,r,i)})}function V(e,t){return e.readContract(v(t))}function H(e,t){return e.readContract(_(t))}function U(e,t,n,r){return e.readContract(b(t,n,r))}function W(e,t,n){return e.readContract(x(t,n))}function G(e,t,n){return e.readContract(C(t,n))}function K(e,t,n){return e.readContract(y(t,n))}function q(e,t,n){return e.readContract(S(t,n))}export{m as BaseSigner,D as ViemProvider,k as ViemSigner,t as ZamaSDKEvents,A as createConfig,M as readConfidentialBalanceOfContract,G as readConfidentialTokenAddressContract,q as readIsConfidentialTokenValidContract,P as readSupportsInterfaceContract,K as readTokenAddressContract,W as readTokenPairContract,V as readTokenPairsContract,H as readTokenPairsLengthContract,U as readTokenPairsSliceContract,N as readUnderlyingTokenContract,F as writeConfidentialTransferContract,R as writeFinalizeUnwrapContract,z as writeSetOperatorContract,I as writeUnwrapContract,L as writeUnwrapFromBalanceContract,B as writeWrapContract};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{r as e,t}from"../fhevm-relayer-CFQaXXPp.js";import{t as n}from"../validation-CZfDLOUh.js";import{z as r}from"zod/mini";const i=e=>r._default(r.number().check(r.positive()),e),a=r.custom(e=>typeof e==`function`),o=r.object({offloadEncrypt:r._default(r.union([r.literal(`auto`),r.boolean()]),`auto`),offloadTimeouts:r.optional(r.object({spawn:i(e.spawn),init:i(e.init)})),offloadWorker:r.optional(r.union([r.string().check(r.minLength(1)),r.instanceof(URL),a]))});function s(e){let{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a,...s}=e??{},c=n(o,{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a});return{type:`web`,createRelayer:(e,n,r)=>new t({chain:e,options:s,telemetry:r&&{state:r,runtime:`web`,mode:r.mode},offloadEncrypt:c.offloadEncrypt,offloadTimeouts:c.offloadTimeouts,offloadWorker:c.offloadWorker,logger:n})}}export{s as web};
1
+ import{r as e,t}from"../fhevm-relayer-Da6yGHJQ.js";import{t as n}from"../validation-CZfDLOUh.js";import{z as r}from"zod/mini";const i=e=>r._default(r.number().check(r.positive()),e),a=r.custom(e=>typeof e==`function`),o=r.object({offloadEncrypt:r._default(r.union([r.literal(`auto`),r.boolean()]),`auto`),offloadTimeouts:r.optional(r.object({spawn:i(e.spawn),init:i(e.init)})),offloadWorker:r.optional(r.union([r.string().check(r.minLength(1)),r.instanceof(URL),a]))});function s(e){let{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a,...s}=e??{},c=n(o,{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a});return{type:`web`,createRelayer:(e,n,r)=>new t({chain:e,options:s,telemetry:r&&{state:r,runtime:`web`,mode:r.mode},offloadEncrypt:c.offloadEncrypt,offloadTimeouts:c.offloadTimeouts,offloadWorker:c.offloadWorker,logger:n})}}export{s as web};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zama-fhe/sdk",
3
- "version": "3.9.0-beta.1",
3
+ "version": "3.9.0-beta.3",
4
4
  "description": "TypeScript SDK for Zama fhEVM confidential smart contracts",
5
5
  "keywords": [
6
6
  "blockchain",