@zama-fhe/sdk 3.6.0-beta.2 → 3.6.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.
@@ -1,2 +1,2 @@
1
- const e=require("./relayer.cjs"),t=require("./wrappers-registry.cjs"),n=require("./applied-runtime.cjs"),r=require("./validation.cjs"),i=require("./chains.cjs");let a=require("viem"),o=require("@fhevm/sdk/viem"),s=require("zod/mini");var c=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const l=new c;var u=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const d=new u;function f(){return typeof window<`u`?new c(`CredentialStore`):new u}function p(e=f(),t=e){return{storage:e,permitStorage:t}}function m(t,n){let r=new Map(t.map(e=>[e.id,e]));if(r.size!==t.length){let n=t.map(e=>e.id);throw new e.t(`Duplicate chain id(s) [${[...new Set(n.filter((e,t)=>n.indexOf(e)!==t))].join(`, `)}] in the chains array. Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`)}let i=new Map(Object.entries(n)),a=new Map;for(let t of r.keys()){let n=r.get(t),o=i.get(String(t));if(!o)throw new e.t(`Chain ${t} has no relayer configured. Add a relayer entry: relayers: { [${t}]: web() }`);if(!n)throw new e.t(`Chain ${t} has a relayer configured but no entry in the chains array. Add the chain config to the chains array.`);a.set(t,{chain:n,relayerConfig:o})}let o=new Set(Object.keys(n).map(Number)),s=new Set([...o].filter(e=>!r.has(e)));if(s.size>0)throw new e.t(`Relayer entries for chain(s) [${[...s].join(`, `)}] have no matching entry in the chains array. Remove them or add the corresponding chain config.`);return a}var ee=class{#e;#t;#n;constructor(t,n,r){if(t.length===0)throw new e.t(`At least one chain is required.`);this.#e=new Map(t.map(e=>[e.id,e])),this.#n=t[0].id;let i=new Map;for(let[e,{relayerConfig:a,chain:o}]of m(t,n))i.set(e,a.createRelayer(o,r));this.#t=i}get chains(){return[...this.#e.values()]}get chain(){let t=this.#e.get(this.#n);if(t===void 0)throw new e.t(`Chain ${this.#n} is not configured. Add it to the chains array.`);return t}switchChain(e){this.#n=e}dispose(){for(let e of new Set(this.#t.values()))e.dispose?.()}get relayer(){let t=this.#t.get(this.chain.id);if(t===void 0)throw new e.t(`No relayer configured for chain ${this.#n}. Add it to the relayers object.`);return t}};function h(e){return(0,a.getAddress)(e)}const g=s.z.custom(e=>typeof e==`string`&&(0,a.isHex)(e,{strict:!0}),`expected 0x-prefixed hex string`),te=s.z.custom(e=>typeof e==`string`&&(0,a.isAddress)(e,{strict:!1}),`expected EVM address`),_=s.z.pipe(te,s.z.transform(h)),v=s.z.int().check(s.z.nonnegative()),y=s.z.int().check(s.z.positive()),ne=s.z.int().check(s.z.nonnegative()),re=s.z.int().check(s.z.positive());s.z.int().check(s.z.positive());const b={version:1,info:`zama-sdk-keypair-wrapping-v1`,ivLengthBytes:12,tagLengthBytes:16};function x(e){return new Uint8Array(e)}function S(e){return x(new TextEncoder().encode(JSON.stringify([e.publicKey,e.createdAt,e.expiresAt,e.tkmsVersion??null])))}function ie(e){return typeof e==`string`?new TextEncoder().encode(e):x(e)}var ae=class{#e;#t;constructor(e){this.#e=e}async baseKey(){return this.#t??=this.#n(this.#e),this.#t}async#n(e){let t=ie(e),n=await crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return t.fill(0),e instanceof Uint8Array&&e.fill(0),this.#e=void 0,n}};async function C(e,t){let n=await e.baseKey();return crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:new TextEncoder().encode(t),info:new TextEncoder().encode(b.info)},n,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function oe(e,t,n,r){let i=await C(t,n),o=crypto.getRandomValues(new Uint8Array(b.ivLengthBytes)),s=await crypto.subtle.encrypt({name:`AES-GCM`,iv:o,additionalData:S(r)},i,x((0,a.toBytes)(e)));return{wrappedPrivateKey:(0,a.toHex)(new Uint8Array(s)),iv:(0,a.toHex)(o)}}async function se(e,t,n,r){let i=await C(t,n),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:x((0,a.toBytes)(e.iv)),additionalData:S(r)},i,x((0,a.toBytes)(e.wrappedPrivateKey)));return(0,a.toHex)(new Uint8Array(o))}function ce(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`OperationError`}const w=86400;function T(){return Math.floor(Date.now()/1e3)}function E(e){return[...new Set(e.map(h))].sort()}function le(e){let{chainId:t}=e.domain;return typeof t==`bigint`?{...e,domain:{...e.domain,chainId:t.toString()}}:e}const D=`transportKeyPairTTL must be a positive integer number of seconds`,O=`permitTTL must be a positive integer number of days`,k=`transportKeyPairScope must be a non-empty string`,A=`transportKeyPairDerivationSecret must be a Uint8Array of at least 32 bytes or a string of at least 64 characters (256 bits of entropy): source it from a CSPRNG or secrets manager, not a human-memorable passphrase`,j=365*w,ue=s.z.int({error:D}).check(s.z.positive({error:D}),s.z.maximum(j,`transportKeyPairTTL must not exceed the fhevm ACL maximum of ${j}s (365 days)`)),M=s.z.int({error:O}).check(s.z.positive({error:O}),s.z.maximum(365,`permitTTL must not exceed the V1 permit maximum of 365 days`)),de=s.z.string({error:k}).check(s.z.minLength(1,k)),fe=s.z.union([s.z.string({error:A}).check(s.z.minLength(64,A)),s.z.instanceof(Uint8Array,{error:A}).check(s.z.refine(e=>e.byteLength>=32,{error:A}))],{error:A}),pe=s.z.object({publicKey:g,privateKey:g,createdAt:v,expiresAt:y,tkmsVersion:s.z.optional(s.z.string())}),N=s.z.object({domain:s.z.record(s.z.string(),s.z.unknown()),primaryType:s.z.optional(s.z.string()),types:s.z.record(s.z.string(),s.z.array(s.z.object({name:s.z.string(),type:s.z.string()}))),message:s.z.record(s.z.string(),s.z.unknown())}),P=s.z.object({version:s.z.int().check(s.z.positive()),eip712:N,signature:g,signerAddress:_}),F=s.z.object({keypairPublicKey:g,contractAddresses:s.z.array(_).check(s.z.maxLength(10)),serializedPermit:P,startTimestamp:v,durationDays:re}),me=s.z.array(F),he=s.z.array(s.z.string()),I=s.z.object({version:s.z.literal(1),eip712:N,signerAddress:_}),L=`iv must be a ${b.ivLengthBytes}-byte hex string`,R=`wrappedPrivateKey must be a whole number of bytes and at least ${b.tagLengthBytes} bytes (the AES-GCM authentication tag)`;function z(e){return(e.length-2)/2}const ge=s.z.object({wrappingVersion:s.z.literal(b.version,{error:`wrappingVersion must be a wrapping scheme this SDK can read`}),publicKey:g,wrappedPrivateKey:g.check(s.z.refine(e=>e.length%2==0&&z(e)>=b.tagLengthBytes,{error:R})),iv:g.check(s.z.refine(e=>z(e)===b.ivLengthBytes,{error:L})),createdAt:v,expiresAt:y,tkmsVersion:s.z.optional(s.z.string())});function B(e){let t={publicKey:e.publicKey,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(t.tkmsVersion=e.tkmsVersion),t}const V={version:b.version,schema:ge,async encode(e,t,n){let{wrappedPrivateKey:r,iv:i}=await oe(e.privateKey,t,n,B(e)),a={wrappingVersion:b.version,publicKey:e.publicKey,wrappedPrivateKey:r,iv:i,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(a.tkmsVersion=e.tkmsVersion),a},async decode(e,t,n){let r=await se({wrappedPrivateKey:e.wrappedPrivateKey,iv:e.iv},t,n,B(e)),i={publicKey:e.publicKey,privateKey:r,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(i.tkmsVersion=e.tkmsVersion),i}},_e=new Map([[V.version,V]]),ve=V;function ye(e){let t=e;return t.wrappingVersion!==void 0||t.wrappedPrivateKey!==void 0&&t.iv!==void 0}function be(e){if(typeof e!=`object`||!e||!ye(e)){let t=pe.safeParse(e);return t.success?{kind:`plaintext`,keyPair:t.data}:{kind:`unrecognized`}}let t=e.wrappingVersion,n=typeof t==`number`?_e.get(t):void 0;if(n===void 0)return{kind:`unsupported-version`,version:t};let r=n.schema.safeParse(e);if(!r.success)return{kind:`corrupt-wrapped`};let i=r.data;return{kind:`wrapped`,expiresAt:i.expiresAt,decode:(e,t)=>n.decode(i,e,t)}}function H(e,t,n){return ve.encode(e,t,n)}function U(e){return`keypair:${e}`}function W(e){return`keypair:scope:${e}`}function G(e){return`permits:${e.signerAddress}:${e.chainId}:${e.delegatorAddress}`}function K(e){return`permits-index:${e}`}function q(e){return`scope:${e}`}function xe(e,t){return{"wrapped-without-secret":`Transport key pair for scope "${t}" is wrapped, but this instance has no transportKeyPairDerivationSecret configured. Every instance sharing this scope must use the same transportKeyPairDerivationSecret; once they do, call permits.revokeTransportKeyPair() to rotate the entry.`,"unwrapped-under-secret":`Transport key pair for scope "${t}" is stored unwrapped, but this instance is configured with a transportKeyPairDerivationSecret. A peer instance sharing this scope is running without the secret: configure the same transportKeyPairDerivationSecret everywhere, then call permits.revokeTransportKeyPair() to migrate the scope to a wrapped entry.`,"unwrap-failed":`Transport key pair for scope "${t}" failed to unwrap. This usually means another instance created it with a different transportKeyPairDerivationSecret: every instance sharing this scope must use the same secret. It can also mean the stored entry is corrupted.`,"corrupt-wrapped":`Transport key pair for scope "${t}" is wrapped but structurally invalid: the stored iv or ciphertext is not a shape this wrapping scheme can produce. This usually means the stored entry is corrupted, or instances sharing this scope are running mismatched wrapping-scheme versions.`}[e]}const Se={"unwrapped-under-secret":`unwrapped transport key pair entry found while a transportKeyPairDerivationSecret is configured`,"unwrap-failed":`transport key pair entry failed to unwrap (wrong transportKeyPairDerivationSecret?)`,"corrupt-wrapped":`structurally invalid wrapped transport key pair entry`};function Ce(e,t){let n=typeof e==`number`?`wrappingVersion ${e}`:`no wrappingVersion this build recognizes`;return`Transport key pair ${t===void 0?`for this signer`:`for scope "${t}"`} was written under a wrapping scheme this SDK build cannot read (${n}). The entry is preserved instead of regenerated, since an instance that understands the scheme may still be using it: ${t===void 0?`run a build that supports it, or call permits.clear() to discard the entry deliberately`:`run a build that supports it everywhere, or call permits.revokeTransportKeyPair() to rotate the scope`}.`}var we=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=new Map;constructor(e){this.#e=e.generator,this.#t=e.storage,this.#n=e.ttl,this.#r=e.logger,this.#i=e.scope,this.#a=e.derivationSecret}#c(e){return this.#i===void 0?`signer:${e}`:q(this.#i)}#l(e){return this.#i===void 0?U(e):W(this.#i)}async readStored(e){return this.#u(this.#l(e),this.#c(e))}async#u(e,n){let r=await this.#t.get(e);if(r==null)return null;let i=be(r);if(i.kind===`unsupported-version`)throw this.#f(e,Ce(i.version,this.#i));if(i.kind===`unrecognized`)return await this.#m(e,`malformed transport key pair entry`),null;let a=this.#a;if(a===void 0)return i.kind===`plaintext`?await this.#p(e,i.keyPair.expiresAt)?null:i.keyPair:this.#d(e,`wrapped-without-secret`);if(i.kind===`plaintext`)return this.#d(e,`unwrapped-under-secret`);if(i.kind===`corrupt-wrapped`)return this.#d(e,`corrupt-wrapped`);if(await this.#p(e,i.expiresAt))return null;try{return await i.decode(a,n)}catch(n){if(!ce(n))throw this.#r.error(`transport key pair unwrap failed unexpectedly`,{key:e,error:n}),new t.Z(`Transport key pair unwrap failed unexpectedly.`,{cause:n});return this.#d(e,`unwrap-failed`,n)}}async#d(e,t,n){if(this.#i!==void 0)throw this.#f(e,xe(t,this.#i),n);if(t===`wrapped-without-secret`)throw this.#f(e,`Transport key pair for this signer is wrapped, but this instance has no transportKeyPairDerivationSecret configured. Configure the same transportKeyPairDerivationSecret the entry was written with. To downgrade to plaintext at rest on purpose, discard the stored entry first by calling permits.clear(), then run without the secret.`,n);let r=Se[t];return this.#r.warn(r,{key:e}),await this.#m(e,r),null}#f(e,n,r){return this.#r.error(n,{key:e}),new t.Z(n,{cause:r})}async#p(e,t){return T()<t?!1:(await this.#m(e,`expired transport key pair entry`),!0)}async#m(e,n){this.#r.debug(`discarding transport key pair entry`,{key:e,reason:n}),await t.R(`delete transport key pair entry`,()=>this.#t.delete(e),this.#r)}async getOrCreate(e,t){return this.#h(this.#l(e),this.#c(e),{strict:t?.strict})}async#h(e,n,r){let i=r?.strict??!1,a=`${e}::${i}`,o=this.#o.get(a);if(o)return o;let s=this.#s.get(e)??0,c=(async()=>{let r=await this.#u(e,n);if(r!==null)return r;let a=await this.#e(),o=T(),c=o+this.#n,l={publicKey:a.publicKey,privateKey:a.privateKey,createdAt:o,expiresAt:c};a.tkmsVersion&&(l.tkmsVersion=a.tkmsVersion);let u=l;if(this.#a!==void 0)try{u=await H(l,this.#a,n)}catch(n){let r=`Failed to wrap the transport private key for at-rest storage.`;throw this.#r.error(r,{key:e,error:n}),new t.Z(r,{cause:n})}if((this.#s.get(e)??0)===s)i?await this.#t.set(e,u):await t.R(`persist transport key pair`,()=>this.#t.set(e,u),this.#r);else if(i)throw new t.nt(`The transport key pair was rotated while it was being generated, so the freshly generated key pair could not be persisted. Retry.`);return l})().finally(()=>{this.#o.delete(a)});return this.#o.set(a,c),c}async clear(e){let n=U(e);await t.R(`delete transport key pair entry`,()=>this.#t.delete(n),this.#r)}async evict(e){let n=this.#l(e);await t.R(`evict transport key pair entry`,()=>this.#t.delete(n),this.#r)}async clearScope(){if(this.#i===void 0)return;let e=W(this.#i);this.#s.set(e,(this.#s.get(e)??0)+1),await this.#t.delete(e)}async warmScope(){this.#i!==void 0&&await this.#h(W(this.#i),q(this.#i),{strict:!0})}};function J(e,t){let n=new Set(e.flatMap(e=>e.contractAddresses));return t.filter(e=>!n.has(e))}function Te(e){let t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));return t}function Ee(e,t,n){return e.filter(e=>e.keypairPublicKey===t&&n<e.startTimestamp+e.durationDays*86400)}function De(e,t){let n=new Set(t);return e.filter(e=>!e.contractAddresses.some(e=>n.has(e)))}function Y(e,t){return[...new Set([...e,...t])].sort()}function Oe(e,t,n){let r=new Set(n),i=e.filter(e=>new Set([...e.contractAddresses,...t]).size<=10);if(i.length===0)return null;function a(e){return e.contractAddresses.reduce((e,t)=>e+ +!!r.has(t),0)}let o=Math.max(...i.map(a));return i.filter(e=>a(e)===o).reduce((e,t)=>t.startTimestamp>e.startTimestamp?t:e)}var ke=class{#e;#t;constructor(e){this.#e=e.storage,this.#t=e.logger}async list(e){let t=G(e),n=await this.#e.get(t);if(n==null)return[];let r=me.safeParse(n);return r.success?r.data:(await this.clearScope(e),[])}async listUsableAndPrune(e,n){let r=await this.list(e),i=Ee(r,n,Math.floor(Date.now()/1e3));return i.length!==r.length&&(i.length===0?await this.clearScope(e):await t.R(`update permit entry`,()=>this.#e.set(G(e),i),this.#t)),i}async append(e,t){if(t.length===0)return;let n=t.map(e=>F.parse(e)),r=await this.list(e);await this.#e.set(G(e),[...r,...n]),await this.#r(e)}async replace(e,t,n){let r=F.parse(n),i=(await this.list(e)).filter(e=>e.serializedPermit.signature!==t);await this.#e.set(G(e),[...i,r]),await this.#r(e)}async deletePermitsTouching(e,t){let n=await this.list(e);if(n.length===0)return;let r=De(n,t);r.length===0?await this.clearScope(e):await this.#e.set(G(e),r)}async clearScope(e){await this.#a(G(e)),await this.#i(e)}async clearAllForSigner(e){let n=K(e),r=await this.#n(n);await Promise.all(r.map(e=>this.#a(e))),await t.R(`delete permit index`,()=>this.#e.delete(n),this.#t)}async#n(e){let n=await this.#e.get(e);if(n==null)return[];let r=he.safeParse(n);return r.success?r.data:(await t.R(`delete permit index`,()=>this.#e.delete(e),this.#t),[])}async#r(e){let t=K(e.signerAddress),n=G(e),r=await this.#n(t);r.includes(n)||await this.#e.set(t,[...r,n])}async#i(e){let n=K(e.signerAddress),r=G(e),i=await this.#n(n),a=i.filter(e=>e!==r);a.length!==i.length&&(a.length===0?await t.R(`delete permit index`,()=>this.#e.delete(n),this.#t):await t.R(`update permit index`,()=>this.#e.set(n,a),this.#t))}async#a(e){await t.R(`delete permit entry`,()=>this.#e.delete(e),this.#t)}},Ae=class{#e;#t;#n;#r;#i;#a;#o;#s;#c=new Map;constructor(e){this.#e=new we({generator:async()=>{let t=e.router.relayer,n=await t.generateTransportKeyPair();return t.serializeTransportKeyPair({transportKeyPair:n})},storage:e.storage,ttl:e.transportKeyPairTTL,logger:e.logger,scope:e.scope,derivationSecret:e.derivationSecret}),this.#t=new ke({storage:e.permitStorage??e.storage,logger:e.logger}),this.#n=e.router,this.#r=e.signer,this.#i=e.permitTTL,this.#a=e.logger,this.#o=e.emitEvent,this.#s=e.scope}#l(e){if(!this.#r)throw new t.V(e);return this.#r}#u(e,n){let r=t.Y(n,{operation:e});return this.#o({type:t.z.PermitError,operation:e,error:r}),r}async grantPermit(e,n){let r=n===void 0?`grantPermit`:`grantDelegationPermit`,i,a,o;try{i=h(this.#l(`grantPermit`).requireWalletAccount(`grantPermit`).address),a=E(e),o=this.#d(i,n)}catch(e){throw this.#u(r,e)}let s=await this.#e.getOrCreate(i);if(a.length===0)return{keypair:s,permissions:[]};let c;try{c=await this.#t.listUsableAndPrune(o,s.publicKey)}catch(e){throw this.#u(r,e)}let l=J(c,a);if(l.length>0){let e=Oe(c,l,a);if(e!==null){let n=Y(e.contractAddresses,l),r=await this.#f({chunk:n,keypair:s,scope:o});await t.R(`replace permit`,()=>this.#t.replace(o,e.serializedPermit.signature,r),this.#a),c[c.indexOf(e)]=r}else for(let e of Te(l)){let n=await this.#f({chunk:e,keypair:s,scope:o});c.push(n),await t.R(`persist permit`,()=>this.#t.append(o,[n]),this.#a)}}let u=new Set(a);return{keypair:s,permissions:c.filter(e=>e.contractAddresses.some(e=>u.has(e)))}}async preparePermit(t){let n=h(t.signer),i=E(t.contracts);if(i.length===0)throw new e.t(`preparePermit: request.contracts must not be empty.`);if(i.length>10)throw new e.t(`preparePermit: request.contracts must not exceed 10 addresses per call (got ${i.length}) — grantPermit chunks automatically, preparePermit does not.`);let a=t.delegator?h(t.delegator):void 0;if(a!==void 0&&a===n)throw new e.t(`preparePermit: request.delegator must differ from request.signer — self-delegation is not allowed.`);let o=t.durationDays===void 0?this.#i:r.t(M,t.durationDays),s=this.#n.relayer,c=await this.#e.getOrCreate(n,{strict:!0}),l=await s.parseTransportKeyPair(c),u=T();return{version:1,eip712:le(N.parse(await s.createUnsignedLegacyDecryptionPermitEip712({transportKeyPair:l,contractAddresses:i,startTimestamp:u,durationSeconds:o*w,...a&&{delegatorAddress:a}}))),signerAddress:n}}async registerPermit(n,i){let a;try{a=r.t(I,n)}catch(e){throw this.#u(`registerPermit`,e)}let o=this.#n.relayer,s=this.#n.chain.id,{domain:c,message:l}=a.eip712,u=Number(c.chainId);if(u!==s)throw this.#u(`registerPermit`,new t.$({preparedChainId:u,activeChainId:s}));let d=Number(l.startTimestamp),f=Number(l.durationDays);if(T()>=d+f*86400)throw this.#u(`registerPermit`,new t.et(`registerPermit: the prepared permit's validity window (starting ${d}, ${f}d) has already elapsed — call preparePermit again.`));let p=a.signerAddress,m=await this.#e.readStored(p);if(m===null||m.publicKey!==l.publicKey)throw new t.nt(`registerPermit: the transport key pair changed since preparePermit ran — call preparePermit again to rebind the signature request to the current key pair.`);try{let n=await o.parseTransportKeyPair(m),c=await o.parseSignedDecryptionPermit({serializedPermit:{version:a.version,eip712:a.eip712,signature:i,signerAddress:p},transportKeyPair:n});if(c.version!==1)throw new e.t(`registerPermit: expected a V1 signed permit, got version ${c.version}.`);let l=r.t(P,await o.serializeSignedDecryptionPermit({signedPermit:c})),u={keypairPublicKey:m.publicKey,contractAddresses:E(c.eip712.message.contractAddresses),serializedPermit:l,startTimestamp:Number(c.eip712.message.startTimestamp),durationDays:Number(c.eip712.message.durationDays)},d={signerAddress:p,chainId:s,delegatorAddress:h(c.encryptedDataOwnerAddress)};await t.R(`replace permit`,()=>this.#t.replace(d,l.signature,u),this.#a)}catch(e){throw this.#u(`registerPermit`,e)}}async hasPermit(e,n){if(e.length===0)return!0;let r=this.#r?.walletAccount.getSnapshot();if(!r)return!1;let i=h(r.address),a;try{a=await this.#e.readStored(i)}catch(e){if(!(e instanceof t.Z))throw e;return!1}if(a===null)return!1;let o=this.#d(i,n);return J(await this.#t.listUsableAndPrune(o,a.publicKey),E(e)).length===0}async revokePermits(e){let t=h(this.#l(`revokePermits`).requireWalletAccount(`revokePermits`).address);if(e===void 0){await this.#t.clearAllForSigner(t);return}let n=E(e);n.length!==0&&await this.#t.deletePermitsTouching(this.#d(t),n)}#d(e,t){return{signerAddress:e,chainId:this.#n.chain.id,delegatorAddress:t?h(t):e}}async clearCredentials(){let e=h(this.#l(`clearCredentials`).requireWalletAccount(`clearCredentials`).address);await this.#e.clear(e),await this.#t.clearAllForSigner(e)}async revokeTransportKeyPair(t){if(this.#s===void 0)throw new e.t(`revokeTransportKeyPair() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to revoke.`);if(t!==this.#s)throw new e.t(`revokeTransportKeyPair("${t}") does not match the configured scope ("${this.#s}").`);await this.#e.clearScope()}async warmTransportKeyPair(e){await this.#e.getOrCreate(h(e))}async warmTransportKeyPairScope(t){if(this.#s===void 0)throw new e.t(`warmTransportKeyPairScope() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to warm.`);if(t!==this.#s)throw new e.t(`warmTransportKeyPairScope("${t}") does not match the configured scope ("${this.#s}").`);await this.#e.warmScope()}async handleWalletAccountChange(e,t){let n=e?h(e.address):void 0;n!==(t?h(t.address):void 0)&&n&&(await this.#e.clear(n),await this.#t.clearAllForSigner(n))}async#f(t){let{chunk:n,keypair:i,scope:a}=t,o=T(),s=a.delegatorAddress!==a.signerAddress,c=this.#n.relayer;try{let e={transportKeyPair:await c.parseTransportKeyPair(i),contractAddresses:n,startTimestamp:o,durationSeconds:this.#i*w,signerAddress:a.signerAddress,signer:this.#l(`signPermit`)},t=s?await c.signDecryptionPermit({...e,delegatorAddress:a.delegatorAddress}):await c.signDecryptionPermit(e),l=r.t(P,await c.serializeSignedDecryptionPermit({signedPermit:t}));return{keypairPublicKey:i.publicKey,contractAddresses:n,serializedPermit:l,startTimestamp:o,durationDays:this.#i}}catch(t){let n=s?`grantDelegationPermit`:`grantPermit`;throw!(t instanceof e.r)&&t instanceof Error&&e.p(t.message)&&await this.#e.evict(a.signerAddress),this.#u(n,t)}}async evictTransportKeyPair(){let e=this.#r?.walletAccount.getSnapshot();e&&await this.#e.evict(h(e.address))}async recoverPermits(e,t,n){let r=this.#l(`recoverPermits`).requireWalletAccount(`recoverPermits`),i=this.#d(h(r.address),t),a=G(i),o=this.#c.get(a);if(o)return await o,this.grantPermit(e,t);let s=await this.#p(i),c=this.#c.get(a);if(c)return await c,this.grantPermit(e,t);if(s===null)return this.grantPermit(e,t);let l=new Set(n??[]);if(l.size>0&&!s.some(e=>l.has(e.serializedPermit.signature)))return this.grantPermit(e,t);let u=s.filter(e=>!l.has(e.serializedPermit.signature)),d=s.flatMap(e=>e.contractAddresses),f=this.#m(i,d,e,u,t).finally(()=>{this.#c.delete(a)});return this.#c.set(a,f),await f,this.grantPermit(e,t)}async#p(e){try{return await this.#t.list(e)}catch(e){return this.#a.warn(`read permits for recovery failed`,{error:e}),null}}async#m(e,n,r,i,a){await t.R(`evict revoked permits`,()=>this.#t.clearScope(e),this.#a);try{await this.grantPermit(Y(n,E(r)),a)}catch(n){throw i.length>0&&await t.R(`restore surviving permits`,async()=>{let t=await this.#t.list(e),n=new Set(t.map(e=>e.serializedPermit.signature)),r=i.filter(e=>!n.has(e.serializedPermit.signature));r.length>0&&await this.#t.append(e,r)},this.#a),n}}},je=class{#e;#t=`[zama-sdk]`;constructor(e){this.#e=e}error(e,t){this.#e?.error(`${this.#t} ${e}`,t)}warn(e,t){this.#e?.warn(`${this.#t} ${e}`,t)}info(e,t){this.#e?.info(`${this.#t} ${e}`,t)}debug(e,t){this.#e?.debug(`${this.#t} ${e}`,t)}warnAlways(e){console.warn(`${this.#t} ${e}`),this.warn(e)}};const X={[i.s.id]:i.s.registryAddress,[i.c.id]:i.c.registryAddress,[i.u.id]:i.u.registryAddress,[i.l.id]:i.l.registryAddress,[i.a.id]:i.a.registryAddress,[i.o.id]:i.o.registryAddress,[i.n.id]:i.n.registryAddress},Me=s.z.record(s.z.string().check(s.z.regex(/^\d+$/,`expected numeric chain id key`)),_),Z=ne,Q=300*1e3;var Ne=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},X,r.t(s.z.optional(Me),e.registryAddresses)),this.#t=r.t(Z,e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.provider.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,a.getAddress)(n)}async listPairs(n={}){let r=n.page??1,i=n.pageSize??100,a=n.metadata??!1;if(r<1)throw new e.t(`page must be >= 1, got ${r}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.provider.readContract(t.a(o));c=this.#i(s,Number(e))}let l=BigInt((r-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:r,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(t.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:r,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Q:void 0)}return{items:m,total:c,page:r,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.b(e.tokenAddress)),this.provider.readContract(t.x(e.tokenAddress)),this.provider.readContract(t.v(e.tokenAddress)),this.provider.readContract(t.y(e.tokenAddress)),this.provider.readContract(t.b(e.confidentialTokenAddress)),this.provider.readContract(t.x(e.confidentialTokenAddress)),this.provider.readContract(t.v(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let n=await this.getRegistryAddress(),r=(0,a.getAddress)(e),i=`ct:${n}:${r}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.provider.readContract(t.t(n,r));return c===a.zeroAddress?this.#i(i,null,Q):this.#i(i,{confidentialTokenAddress:c,isValid:s})}async getUnderlyingToken(e){let n=await this.getRegistryAddress(),r=(0,a.getAddress)(e),i=`ut:${n}:${r}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.provider.readContract(t.n(n,r));return c===a.zeroAddress?this.#i(i,null,Q):this.#i(i,{tokenAddress:c,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(t.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(t.a(e))}async getTokenPairsSlice(e,n){let r=await this.getRegistryAddress();return this.provider.readContract(t.o(r,e,n))}async getTokenPair(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.r(n,e))}async getConfidentialTokenAddress(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.t(n,(0,a.getAddress)(e)))}async getTokenAddress(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.n(n,(0,a.getAddress)(e)))}async isConfidentialTokenValid(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.s(n,(0,a.getAddress)(e)))}};function Pe(e,t,i){let a=new je(i.logger),s=i.logger,c={wasmAssetLoadMode:`auto`,moduleVersions:`auto`,logger:{error:(e,t)=>s?.error(e,{cause:t}),warn:e=>s?.warn(e),debug:e=>s?.debug(e)},...i.runtime};if((0,o.hasFhevmRuntimeConfig)()){let e=`runtime configuration is already set and cannot be changed.`;i.runtime===void 0?a.debug(e):a.warn(e)}else(0,o.setFhevmRuntimeConfig)(c),n.r(c);let{storage:l,permitStorage:u}=p(i.storage,i.permitStorage),d=new ee(i.chains,i.relayers,a);return{chains:i.chains,router:d,provider:t,signer:e,storage:l,permitStorage:u,transportKeyPairTTL:r.t(ue,i.transportKeyPairTTL??2592e3),permitTTL:r.t(M,i.permitTTL??30),transportKeyPairScope:i.transportKeyPairScope===void 0?void 0:r.t(de,i.transportKeyPairScope),registryTTL:r.t(Z,i.registryTTL??86400),logger:a,onEvent:i.onEvent}}function Fe(e,t){return e?.address===t?.address&&e?.chainId===t?.chainId}var $=class{#e=new Set;#t;#n;constructor(e){this.#t=e,this.#n=e!==void 0}getSnapshot(){return this.#t}isReady(){return this.#n}setSnapshot(e){this.#n=!0;let t=this.#t;Fe(t,e)||(this.#t=e,this.#r({previous:t,next:e}))}subscribe(e){this.#e.add(e);let t=this.#t;return t&&e({previous:void 0,next:t}),()=>{this.#e.delete(e)}}#r(e){for(let t of this.#e)t(e)}};function Ie(e){return new $(e)}var Le=class{walletAccount;#e=!1;constructor(e){this.walletAccount=new $(e)}requireWalletAccount(e){let n=this.walletAccount.getSnapshot();if(!n)throw new t.W(e);return n}dispose(){this.#e||(this.#e=!0,this.onDispose())}[Symbol.dispose](){this.dispose()}onDispose(){}};Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return Ne}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return h}});
1
+ const e=require("./relayer.cjs"),t=require("./wrappers-registry.cjs"),n=require("./applied-runtime.cjs"),r=require("./validation.cjs"),i=require("./chains.cjs");let a=require("viem"),o=require("@fhevm/sdk/viem"),s=require("zod/mini");var c=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const l=new c;var u=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const d=new u;function f(){return typeof window<`u`?new c(`CredentialStore`):new u}function p(e=f(),t=e){return{storage:e,permitStorage:t}}function m(t,n,r){let i=t.map(e=>e.id),a=[...new Set(i.filter((e,t)=>i.indexOf(e)!==t))];if(a.length>0)throw new e.t(`Duplicate chain id(s) [${a.join(`, `)}] in the chains array. Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`);let o=Object.keys(n).map(Number).filter(e=>!i.includes(e));o.length>0&&r.warn(`Relayer entries for chain(s) [${o.join(`, `)}] are ignored: those chains are not in the chains array. Add the chain config to use them, or drop the relayer entries.`);let s=new Map;for(let r of t){let t=n[r.id];if(!t)throw new e.t(`Chain ${r.id} has no relayer configured. Add a relayer entry: relayers: { [${r.id}]: web() }`);s.set(r.id,{chain:r,relayerConfig:t})}return s}var ee=class{#e;#t;#n;constructor(t,n,r){if(t.length===0)throw new e.t(`At least one chain is required.`);this.#e=new Map(t.map(e=>[e.id,e])),this.#n=t[0].id;let i=new Map;for(let[e,{relayerConfig:a,chain:o}]of m(t,n,r))i.set(e,a.createRelayer(o,r));this.#t=i}get chains(){return[...this.#e.values()]}get chain(){let t=this.#e.get(this.#n);if(t===void 0)throw new e.t(`Chain ${this.#n} is not configured. Add it to the chains array.`);return t}switchChain(e){this.#n=e}dispose(){for(let e of new Set(this.#t.values()))e.dispose?.()}get relayer(){let t=this.#t.get(this.chain.id);if(t===void 0)throw new e.t(`No relayer configured for chain ${this.#n}. Add it to the relayers object.`);return t}};function h(e){return(0,a.getAddress)(e)}const g=s.z.custom(e=>typeof e==`string`&&(0,a.isHex)(e,{strict:!0}),`expected 0x-prefixed hex string`),te=s.z.custom(e=>typeof e==`string`&&(0,a.isAddress)(e,{strict:!1}),`expected EVM address`),_=s.z.pipe(te,s.z.transform(h)),v=s.z.int().check(s.z.nonnegative()),y=s.z.int().check(s.z.positive()),ne=s.z.int().check(s.z.nonnegative()),re=s.z.int().check(s.z.positive());s.z.int().check(s.z.positive());const b={version:1,info:`zama-sdk-keypair-wrapping-v1`,ivLengthBytes:12,tagLengthBytes:16};function x(e){return new Uint8Array(e)}function S(e){return x(new TextEncoder().encode(JSON.stringify([e.publicKey,e.createdAt,e.expiresAt,e.tkmsVersion??null])))}function ie(e){return typeof e==`string`?new TextEncoder().encode(e):x(e)}var ae=class{#e;#t;constructor(e){this.#e=e}async baseKey(){return this.#t??=this.#n(this.#e),this.#t}async#n(e){let t=ie(e),n=await crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return t.fill(0),e instanceof Uint8Array&&e.fill(0),this.#e=void 0,n}};async function C(e,t){let n=await e.baseKey();return crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:new TextEncoder().encode(t),info:new TextEncoder().encode(b.info)},n,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function oe(e,t,n,r){let i=await C(t,n),o=crypto.getRandomValues(new Uint8Array(b.ivLengthBytes)),s=await crypto.subtle.encrypt({name:`AES-GCM`,iv:o,additionalData:S(r)},i,x((0,a.toBytes)(e)));return{wrappedPrivateKey:(0,a.toHex)(new Uint8Array(s)),iv:(0,a.toHex)(o)}}async function se(e,t,n,r){let i=await C(t,n),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:x((0,a.toBytes)(e.iv)),additionalData:S(r)},i,x((0,a.toBytes)(e.wrappedPrivateKey)));return(0,a.toHex)(new Uint8Array(o))}function ce(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`OperationError`}const w=86400;function T(){return Math.floor(Date.now()/1e3)}function E(e){return[...new Set(e.map(h))].sort()}function le(e){let{chainId:t}=e.domain;return typeof t==`bigint`?{...e,domain:{...e.domain,chainId:t.toString()}}:e}const D=`transportKeyPairTTL must be a positive integer number of seconds`,O=`permitTTL must be a positive integer number of days`,k=`transportKeyPairScope must be a non-empty string`,A=`transportKeyPairDerivationSecret must be a Uint8Array of at least 32 bytes or a string of at least 64 characters (256 bits of entropy): source it from a CSPRNG or secrets manager, not a human-memorable passphrase`,j=365*w,ue=s.z.int({error:D}).check(s.z.positive({error:D}),s.z.maximum(j,`transportKeyPairTTL must not exceed the fhevm ACL maximum of ${j}s (365 days)`)),M=s.z.int({error:O}).check(s.z.positive({error:O}),s.z.maximum(365,`permitTTL must not exceed the V1 permit maximum of 365 days`)),de=s.z.string({error:k}).check(s.z.minLength(1,k)),fe=s.z.union([s.z.string({error:A}).check(s.z.minLength(64,A)),s.z.instanceof(Uint8Array,{error:A}).check(s.z.refine(e=>e.byteLength>=32,{error:A}))],{error:A}),pe=s.z.object({publicKey:g,privateKey:g,createdAt:v,expiresAt:y,tkmsVersion:s.z.optional(s.z.string())}),N=s.z.object({domain:s.z.record(s.z.string(),s.z.unknown()),primaryType:s.z.optional(s.z.string()),types:s.z.record(s.z.string(),s.z.array(s.z.object({name:s.z.string(),type:s.z.string()}))),message:s.z.record(s.z.string(),s.z.unknown())}),P=s.z.object({version:s.z.int().check(s.z.positive()),eip712:N,signature:g,signerAddress:_}),F=s.z.object({keypairPublicKey:g,contractAddresses:s.z.array(_).check(s.z.maxLength(10)),serializedPermit:P,startTimestamp:v,durationDays:re}),me=s.z.array(F),he=s.z.array(s.z.string()),I=s.z.object({version:s.z.literal(1),eip712:N,signerAddress:_}),L=`iv must be a ${b.ivLengthBytes}-byte hex string`,R=`wrappedPrivateKey must be a whole number of bytes and at least ${b.tagLengthBytes} bytes (the AES-GCM authentication tag)`;function z(e){return(e.length-2)/2}const ge=s.z.object({wrappingVersion:s.z.literal(b.version,{error:`wrappingVersion must be a wrapping scheme this SDK can read`}),publicKey:g,wrappedPrivateKey:g.check(s.z.refine(e=>e.length%2==0&&z(e)>=b.tagLengthBytes,{error:R})),iv:g.check(s.z.refine(e=>z(e)===b.ivLengthBytes,{error:L})),createdAt:v,expiresAt:y,tkmsVersion:s.z.optional(s.z.string())});function B(e){let t={publicKey:e.publicKey,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(t.tkmsVersion=e.tkmsVersion),t}const V={version:b.version,schema:ge,async encode(e,t,n){let{wrappedPrivateKey:r,iv:i}=await oe(e.privateKey,t,n,B(e)),a={wrappingVersion:b.version,publicKey:e.publicKey,wrappedPrivateKey:r,iv:i,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(a.tkmsVersion=e.tkmsVersion),a},async decode(e,t,n){let r=await se({wrappedPrivateKey:e.wrappedPrivateKey,iv:e.iv},t,n,B(e)),i={publicKey:e.publicKey,privateKey:r,createdAt:e.createdAt,expiresAt:e.expiresAt};return e.tkmsVersion&&(i.tkmsVersion=e.tkmsVersion),i}},_e=new Map([[V.version,V]]),ve=V;function ye(e){let t=e;return t.wrappingVersion!==void 0||t.wrappedPrivateKey!==void 0&&t.iv!==void 0}function be(e){if(typeof e!=`object`||!e||!ye(e)){let t=pe.safeParse(e);return t.success?{kind:`plaintext`,keyPair:t.data}:{kind:`unrecognized`}}let t=e.wrappingVersion,n=typeof t==`number`?_e.get(t):void 0;if(n===void 0)return{kind:`unsupported-version`,version:t};let r=n.schema.safeParse(e);if(!r.success)return{kind:`corrupt-wrapped`};let i=r.data;return{kind:`wrapped`,expiresAt:i.expiresAt,decode:(e,t)=>n.decode(i,e,t)}}function H(e,t,n){return ve.encode(e,t,n)}function U(e){return`keypair:${e}`}function W(e){return`keypair:scope:${e}`}function G(e){return`permits:${e.signerAddress}:${e.chainId}:${e.delegatorAddress}`}function K(e){return`permits-index:${e}`}function q(e){return`scope:${e}`}function xe(e,t){return{"wrapped-without-secret":`Transport key pair for scope "${t}" is wrapped, but this instance has no transportKeyPairDerivationSecret configured. Every instance sharing this scope must use the same transportKeyPairDerivationSecret; once they do, call permits.revokeTransportKeyPair() to rotate the entry.`,"unwrapped-under-secret":`Transport key pair for scope "${t}" is stored unwrapped, but this instance is configured with a transportKeyPairDerivationSecret. A peer instance sharing this scope is running without the secret: configure the same transportKeyPairDerivationSecret everywhere, then call permits.revokeTransportKeyPair() to migrate the scope to a wrapped entry.`,"unwrap-failed":`Transport key pair for scope "${t}" failed to unwrap. This usually means another instance created it with a different transportKeyPairDerivationSecret: every instance sharing this scope must use the same secret. It can also mean the stored entry is corrupted.`,"corrupt-wrapped":`Transport key pair for scope "${t}" is wrapped but structurally invalid: the stored iv or ciphertext is not a shape this wrapping scheme can produce. This usually means the stored entry is corrupted, or instances sharing this scope are running mismatched wrapping-scheme versions.`}[e]}const Se={"unwrapped-under-secret":`unwrapped transport key pair entry found while a transportKeyPairDerivationSecret is configured`,"unwrap-failed":`transport key pair entry failed to unwrap (wrong transportKeyPairDerivationSecret?)`,"corrupt-wrapped":`structurally invalid wrapped transport key pair entry`};function Ce(e,t){let n=typeof e==`number`?`wrappingVersion ${e}`:`no wrappingVersion this build recognizes`;return`Transport key pair ${t===void 0?`for this signer`:`for scope "${t}"`} was written under a wrapping scheme this SDK build cannot read (${n}). The entry is preserved instead of regenerated, since an instance that understands the scheme may still be using it: ${t===void 0?`run a build that supports it, or call permits.clear() to discard the entry deliberately`:`run a build that supports it everywhere, or call permits.revokeTransportKeyPair() to rotate the scope`}.`}var we=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=new Map;constructor(e){this.#e=e.generator,this.#t=e.storage,this.#n=e.ttl,this.#r=e.logger,this.#i=e.scope,this.#a=e.derivationSecret}#c(e){return this.#i===void 0?`signer:${e}`:q(this.#i)}#l(e){return this.#i===void 0?U(e):W(this.#i)}async readStored(e){return this.#u(this.#l(e),this.#c(e))}async#u(e,n){let r=await this.#t.get(e);if(r==null)return null;let i=be(r);if(i.kind===`unsupported-version`)throw this.#f(e,Ce(i.version,this.#i));if(i.kind===`unrecognized`)return await this.#m(e,`malformed transport key pair entry`),null;let a=this.#a;if(a===void 0)return i.kind===`plaintext`?await this.#p(e,i.keyPair.expiresAt)?null:i.keyPair:this.#d(e,`wrapped-without-secret`);if(i.kind===`plaintext`)return this.#d(e,`unwrapped-under-secret`);if(i.kind===`corrupt-wrapped`)return this.#d(e,`corrupt-wrapped`);if(await this.#p(e,i.expiresAt))return null;try{return await i.decode(a,n)}catch(n){if(!ce(n))throw this.#r.error(`transport key pair unwrap failed unexpectedly`,{key:e,error:n}),new t.Z(`Transport key pair unwrap failed unexpectedly.`,{cause:n});return this.#d(e,`unwrap-failed`,n)}}async#d(e,t,n){if(this.#i!==void 0)throw this.#f(e,xe(t,this.#i),n);if(t===`wrapped-without-secret`)throw this.#f(e,`Transport key pair for this signer is wrapped, but this instance has no transportKeyPairDerivationSecret configured. Configure the same transportKeyPairDerivationSecret the entry was written with. To downgrade to plaintext at rest on purpose, discard the stored entry first by calling permits.clear(), then run without the secret.`,n);let r=Se[t];return this.#r.warn(r,{key:e}),await this.#m(e,r),null}#f(e,n,r){return this.#r.error(n,{key:e}),new t.Z(n,{cause:r})}async#p(e,t){return T()<t?!1:(await this.#m(e,`expired transport key pair entry`),!0)}async#m(e,n){this.#r.debug(`discarding transport key pair entry`,{key:e,reason:n}),await t.R(`delete transport key pair entry`,()=>this.#t.delete(e),this.#r)}async getOrCreate(e,t){return this.#h(this.#l(e),this.#c(e),{strict:t?.strict})}async#h(e,n,r){let i=r?.strict??!1,a=`${e}::${i}`,o=this.#o.get(a);if(o)return o;let s=this.#s.get(e)??0,c=(async()=>{let r=await this.#u(e,n);if(r!==null)return r;let a=await this.#e(),o=T(),c=o+this.#n,l={publicKey:a.publicKey,privateKey:a.privateKey,createdAt:o,expiresAt:c};a.tkmsVersion&&(l.tkmsVersion=a.tkmsVersion);let u=l;if(this.#a!==void 0)try{u=await H(l,this.#a,n)}catch(n){let r=`Failed to wrap the transport private key for at-rest storage.`;throw this.#r.error(r,{key:e,error:n}),new t.Z(r,{cause:n})}if((this.#s.get(e)??0)===s)i?await this.#t.set(e,u):await t.R(`persist transport key pair`,()=>this.#t.set(e,u),this.#r);else if(i)throw new t.nt(`The transport key pair was rotated while it was being generated, so the freshly generated key pair could not be persisted. Retry.`);return l})().finally(()=>{this.#o.delete(a)});return this.#o.set(a,c),c}async clear(e){let n=U(e);await t.R(`delete transport key pair entry`,()=>this.#t.delete(n),this.#r)}async evict(e){let n=this.#l(e);await t.R(`evict transport key pair entry`,()=>this.#t.delete(n),this.#r)}async clearScope(){if(this.#i===void 0)return;let e=W(this.#i);this.#s.set(e,(this.#s.get(e)??0)+1),await this.#t.delete(e)}async warmScope(){this.#i!==void 0&&await this.#h(W(this.#i),q(this.#i),{strict:!0})}};function J(e,t){let n=new Set(e.flatMap(e=>e.contractAddresses));return t.filter(e=>!n.has(e))}function Te(e){let t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));return t}function Ee(e,t,n){return e.filter(e=>e.keypairPublicKey===t&&n<e.startTimestamp+e.durationDays*86400)}function De(e,t){let n=new Set(t);return e.filter(e=>!e.contractAddresses.some(e=>n.has(e)))}function Y(e,t){return[...new Set([...e,...t])].sort()}function Oe(e,t,n){let r=new Set(n),i=e.filter(e=>new Set([...e.contractAddresses,...t]).size<=10);if(i.length===0)return null;function a(e){return e.contractAddresses.reduce((e,t)=>e+ +!!r.has(t),0)}let o=Math.max(...i.map(a));return i.filter(e=>a(e)===o).reduce((e,t)=>t.startTimestamp>e.startTimestamp?t:e)}var ke=class{#e;#t;constructor(e){this.#e=e.storage,this.#t=e.logger}async list(e){let t=G(e),n=await this.#e.get(t);if(n==null)return[];let r=me.safeParse(n);return r.success?r.data:(await this.clearScope(e),[])}async listUsableAndPrune(e,n){let r=await this.list(e),i=Ee(r,n,Math.floor(Date.now()/1e3));return i.length!==r.length&&(i.length===0?await this.clearScope(e):await t.R(`update permit entry`,()=>this.#e.set(G(e),i),this.#t)),i}async append(e,t){if(t.length===0)return;let n=t.map(e=>F.parse(e)),r=await this.list(e);await this.#e.set(G(e),[...r,...n]),await this.#r(e)}async replace(e,t,n){let r=F.parse(n),i=(await this.list(e)).filter(e=>e.serializedPermit.signature!==t);await this.#e.set(G(e),[...i,r]),await this.#r(e)}async deletePermitsTouching(e,t){let n=await this.list(e);if(n.length===0)return;let r=De(n,t);r.length===0?await this.clearScope(e):await this.#e.set(G(e),r)}async clearScope(e){await this.#a(G(e)),await this.#i(e)}async clearAllForSigner(e){let n=K(e),r=await this.#n(n);await Promise.all(r.map(e=>this.#a(e))),await t.R(`delete permit index`,()=>this.#e.delete(n),this.#t)}async#n(e){let n=await this.#e.get(e);if(n==null)return[];let r=he.safeParse(n);return r.success?r.data:(await t.R(`delete permit index`,()=>this.#e.delete(e),this.#t),[])}async#r(e){let t=K(e.signerAddress),n=G(e),r=await this.#n(t);r.includes(n)||await this.#e.set(t,[...r,n])}async#i(e){let n=K(e.signerAddress),r=G(e),i=await this.#n(n),a=i.filter(e=>e!==r);a.length!==i.length&&(a.length===0?await t.R(`delete permit index`,()=>this.#e.delete(n),this.#t):await t.R(`update permit index`,()=>this.#e.set(n,a),this.#t))}async#a(e){await t.R(`delete permit entry`,()=>this.#e.delete(e),this.#t)}},Ae=class{#e;#t;#n;#r;#i;#a;#o;#s;#c=new Map;constructor(e){this.#e=new we({generator:async()=>{let t=e.router.relayer,n=await t.generateTransportKeyPair();return t.serializeTransportKeyPair({transportKeyPair:n})},storage:e.storage,ttl:e.transportKeyPairTTL,logger:e.logger,scope:e.scope,derivationSecret:e.derivationSecret}),this.#t=new ke({storage:e.permitStorage??e.storage,logger:e.logger}),this.#n=e.router,this.#r=e.signer,this.#i=e.permitTTL,this.#a=e.logger,this.#o=e.emitEvent,this.#s=e.scope}#l(e){if(!this.#r)throw new t.V(e);return this.#r}#u(e,n){let r=t.Y(n,{operation:e});return this.#o({type:t.z.PermitError,operation:e,error:r}),r}async grantPermit(e,n){let r=n===void 0?`grantPermit`:`grantDelegationPermit`,i,a,o;try{i=h(this.#l(`grantPermit`).requireWalletAccount(`grantPermit`).address),a=E(e),o=this.#d(i,n)}catch(e){throw this.#u(r,e)}let s=await this.#e.getOrCreate(i);if(a.length===0)return{keypair:s,permissions:[]};let c;try{c=await this.#t.listUsableAndPrune(o,s.publicKey)}catch(e){throw this.#u(r,e)}let l=J(c,a);if(l.length>0){let e=Oe(c,l,a);if(e!==null){let n=Y(e.contractAddresses,l),r=await this.#f({chunk:n,keypair:s,scope:o});await t.R(`replace permit`,()=>this.#t.replace(o,e.serializedPermit.signature,r),this.#a),c[c.indexOf(e)]=r}else for(let e of Te(l)){let n=await this.#f({chunk:e,keypair:s,scope:o});c.push(n),await t.R(`persist permit`,()=>this.#t.append(o,[n]),this.#a)}}let u=new Set(a);return{keypair:s,permissions:c.filter(e=>e.contractAddresses.some(e=>u.has(e)))}}async preparePermit(t){let n=h(t.signer),i=E(t.contracts);if(i.length===0)throw new e.t(`preparePermit: request.contracts must not be empty.`);if(i.length>10)throw new e.t(`preparePermit: request.contracts must not exceed 10 addresses per call (got ${i.length}) — grantPermit chunks automatically, preparePermit does not.`);let a=t.delegator?h(t.delegator):void 0;if(a!==void 0&&a===n)throw new e.t(`preparePermit: request.delegator must differ from request.signer — self-delegation is not allowed.`);let o=t.durationDays===void 0?this.#i:r.t(M,t.durationDays),s=this.#n.relayer,c=await this.#e.getOrCreate(n,{strict:!0}),l=await s.parseTransportKeyPair(c),u=T();return{version:1,eip712:le(N.parse(await s.createUnsignedLegacyDecryptionPermitEip712({transportKeyPair:l,contractAddresses:i,startTimestamp:u,durationSeconds:o*w,...a&&{delegatorAddress:a}}))),signerAddress:n}}async registerPermit(n,i){let a;try{a=r.t(I,n)}catch(e){throw this.#u(`registerPermit`,e)}let o=this.#n.relayer,s=this.#n.chain.id,{domain:c,message:l}=a.eip712,u=Number(c.chainId);if(u!==s)throw this.#u(`registerPermit`,new t.$({preparedChainId:u,activeChainId:s}));let d=Number(l.startTimestamp),f=Number(l.durationDays);if(T()>=d+f*86400)throw this.#u(`registerPermit`,new t.et(`registerPermit: the prepared permit's validity window (starting ${d}, ${f}d) has already elapsed — call preparePermit again.`));let p=a.signerAddress,m=await this.#e.readStored(p);if(m===null||m.publicKey!==l.publicKey)throw new t.nt(`registerPermit: the transport key pair changed since preparePermit ran — call preparePermit again to rebind the signature request to the current key pair.`);try{let n=await o.parseTransportKeyPair(m),c=await o.parseSignedDecryptionPermit({serializedPermit:{version:a.version,eip712:a.eip712,signature:i,signerAddress:p},transportKeyPair:n});if(c.version!==1)throw new e.t(`registerPermit: expected a V1 signed permit, got version ${c.version}.`);let l=r.t(P,await o.serializeSignedDecryptionPermit({signedPermit:c})),u={keypairPublicKey:m.publicKey,contractAddresses:E(c.eip712.message.contractAddresses),serializedPermit:l,startTimestamp:Number(c.eip712.message.startTimestamp),durationDays:Number(c.eip712.message.durationDays)},d={signerAddress:p,chainId:s,delegatorAddress:h(c.encryptedDataOwnerAddress)};await t.R(`replace permit`,()=>this.#t.replace(d,l.signature,u),this.#a)}catch(e){throw this.#u(`registerPermit`,e)}}async hasPermit(e,n){if(e.length===0)return!0;let r=this.#r?.walletAccount.getSnapshot();if(!r)return!1;let i=h(r.address),a;try{a=await this.#e.readStored(i)}catch(e){if(!(e instanceof t.Z))throw e;return!1}if(a===null)return!1;let o=this.#d(i,n);return J(await this.#t.listUsableAndPrune(o,a.publicKey),E(e)).length===0}async revokePermits(e){let t=h(this.#l(`revokePermits`).requireWalletAccount(`revokePermits`).address);if(e===void 0){await this.#t.clearAllForSigner(t);return}let n=E(e);n.length!==0&&await this.#t.deletePermitsTouching(this.#d(t),n)}#d(e,t){return{signerAddress:e,chainId:this.#n.chain.id,delegatorAddress:t?h(t):e}}async clearCredentials(){let e=h(this.#l(`clearCredentials`).requireWalletAccount(`clearCredentials`).address);await this.#e.clear(e),await this.#t.clearAllForSigner(e)}async revokeTransportKeyPair(t){if(this.#s===void 0)throw new e.t(`revokeTransportKeyPair() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to revoke.`);if(t!==this.#s)throw new e.t(`revokeTransportKeyPair("${t}") does not match the configured scope ("${this.#s}").`);await this.#e.clearScope()}async warmTransportKeyPair(e){await this.#e.getOrCreate(h(e))}async warmTransportKeyPairScope(t){if(this.#s===void 0)throw new e.t(`warmTransportKeyPairScope() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to warm.`);if(t!==this.#s)throw new e.t(`warmTransportKeyPairScope("${t}") does not match the configured scope ("${this.#s}").`);await this.#e.warmScope()}async handleWalletAccountChange(e,t){let n=e?h(e.address):void 0;n!==(t?h(t.address):void 0)&&n&&(await this.#e.clear(n),await this.#t.clearAllForSigner(n))}async#f(t){let{chunk:n,keypair:i,scope:a}=t,o=T(),s=a.delegatorAddress!==a.signerAddress,c=this.#n.relayer;try{let e={transportKeyPair:await c.parseTransportKeyPair(i),contractAddresses:n,startTimestamp:o,durationSeconds:this.#i*w,signerAddress:a.signerAddress,signer:this.#l(`signPermit`)},t=s?await c.signDecryptionPermit({...e,delegatorAddress:a.delegatorAddress}):await c.signDecryptionPermit(e),l=r.t(P,await c.serializeSignedDecryptionPermit({signedPermit:t}));return{keypairPublicKey:i.publicKey,contractAddresses:n,serializedPermit:l,startTimestamp:o,durationDays:this.#i}}catch(t){let n=s?`grantDelegationPermit`:`grantPermit`;throw!(t instanceof e.r)&&t instanceof Error&&e.p(t.message)&&await this.#e.evict(a.signerAddress),this.#u(n,t)}}async evictTransportKeyPair(){let e=this.#r?.walletAccount.getSnapshot();e&&await this.#e.evict(h(e.address))}async recoverPermits(e,t,n){let r=this.#l(`recoverPermits`).requireWalletAccount(`recoverPermits`),i=this.#d(h(r.address),t),a=G(i),o=this.#c.get(a);if(o)return await o,this.grantPermit(e,t);let s=await this.#p(i),c=this.#c.get(a);if(c)return await c,this.grantPermit(e,t);if(s===null)return this.grantPermit(e,t);let l=new Set(n??[]);if(l.size>0&&!s.some(e=>l.has(e.serializedPermit.signature)))return this.grantPermit(e,t);let u=s.filter(e=>!l.has(e.serializedPermit.signature)),d=s.flatMap(e=>e.contractAddresses),f=this.#m(i,d,e,u,t).finally(()=>{this.#c.delete(a)});return this.#c.set(a,f),await f,this.grantPermit(e,t)}async#p(e){try{return await this.#t.list(e)}catch(e){return this.#a.warn(`read permits for recovery failed`,{error:e}),null}}async#m(e,n,r,i,a){await t.R(`evict revoked permits`,()=>this.#t.clearScope(e),this.#a);try{await this.grantPermit(Y(n,E(r)),a)}catch(n){throw i.length>0&&await t.R(`restore surviving permits`,async()=>{let t=await this.#t.list(e),n=new Set(t.map(e=>e.serializedPermit.signature)),r=i.filter(e=>!n.has(e.serializedPermit.signature));r.length>0&&await this.#t.append(e,r)},this.#a),n}}},je=class{#e;#t=`[zama-sdk]`;constructor(e){this.#e=e}error(e,t){this.#e?.error(`${this.#t} ${e}`,t)}warn(e,t){this.#e?.warn(`${this.#t} ${e}`,t)}info(e,t){this.#e?.info(`${this.#t} ${e}`,t)}debug(e,t){this.#e?.debug(`${this.#t} ${e}`,t)}warnAlways(e){console.warn(`${this.#t} ${e}`),this.warn(e)}};const X={[i.s.id]:i.s.registryAddress,[i.c.id]:i.c.registryAddress,[i.u.id]:i.u.registryAddress,[i.l.id]:i.l.registryAddress,[i.a.id]:i.a.registryAddress,[i.o.id]:i.o.registryAddress,[i.n.id]:i.n.registryAddress},Me=s.z.record(s.z.string().check(s.z.regex(/^\d+$/,`expected numeric chain id key`)),_),Z=ne,Q=300*1e3;var Ne=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},X,r.t(s.z.optional(Me),e.registryAddresses)),this.#t=r.t(Z,e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.provider.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,a.getAddress)(n)}async listPairs(n={}){let r=n.page??1,i=n.pageSize??100,a=n.metadata??!1;if(r<1)throw new e.t(`page must be >= 1, got ${r}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.provider.readContract(t.a(o));c=this.#i(s,Number(e))}let l=BigInt((r-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:r,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(t.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:r,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Q:void 0)}return{items:m,total:c,page:r,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.b(e.tokenAddress)),this.provider.readContract(t.x(e.tokenAddress)),this.provider.readContract(t.v(e.tokenAddress)),this.provider.readContract(t.y(e.tokenAddress)),this.provider.readContract(t.b(e.confidentialTokenAddress)),this.provider.readContract(t.x(e.confidentialTokenAddress)),this.provider.readContract(t.v(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let n=await this.getRegistryAddress(),r=(0,a.getAddress)(e),i=`ct:${n}:${r}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.provider.readContract(t.t(n,r));return c===a.zeroAddress?this.#i(i,null,Q):this.#i(i,{confidentialTokenAddress:c,isValid:s})}async getUnderlyingToken(e){let n=await this.getRegistryAddress(),r=(0,a.getAddress)(e),i=`ut:${n}:${r}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.provider.readContract(t.n(n,r));return c===a.zeroAddress?this.#i(i,null,Q):this.#i(i,{tokenAddress:c,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(t.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(t.a(e))}async getTokenPairsSlice(e,n){let r=await this.getRegistryAddress();return this.provider.readContract(t.o(r,e,n))}async getTokenPair(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.r(n,e))}async getConfidentialTokenAddress(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.t(n,(0,a.getAddress)(e)))}async getTokenAddress(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.n(n,(0,a.getAddress)(e)))}async isConfidentialTokenValid(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.s(n,(0,a.getAddress)(e)))}};function Pe(e,t,i){let a=new je(i.logger),s=i.logger,c={wasmAssetLoadMode:`auto`,moduleVersions:`auto`,logger:{error:(e,t)=>s?.error(e,{cause:t}),warn:e=>s?.warn(e),debug:e=>s?.debug(e)},...i.runtime};if((0,o.hasFhevmRuntimeConfig)()){let e=`runtime configuration is already set and cannot be changed.`;i.runtime===void 0?a.debug(e):a.warn(e)}else(0,o.setFhevmRuntimeConfig)(c),n.r(c);let{storage:l,permitStorage:u}=p(i.storage,i.permitStorage),d=new ee(i.chains,i.relayers,a);return{chains:i.chains,router:d,provider:t,signer:e,storage:l,permitStorage:u,transportKeyPairTTL:r.t(ue,i.transportKeyPairTTL??2592e3),permitTTL:r.t(M,i.permitTTL??30),transportKeyPairScope:i.transportKeyPairScope===void 0?void 0:r.t(de,i.transportKeyPairScope),registryTTL:r.t(Z,i.registryTTL??86400),logger:a,onEvent:i.onEvent}}function Fe(e,t){return e?.address===t?.address&&e?.chainId===t?.chainId}var $=class{#e=new Set;#t;#n;constructor(e){this.#t=e,this.#n=e!==void 0}getSnapshot(){return this.#t}isReady(){return this.#n}setSnapshot(e){this.#n=!0;let t=this.#t;Fe(t,e)||(this.#t=e,this.#r({previous:t,next:e}))}subscribe(e){this.#e.add(e);let t=this.#t;return t&&e({previous:void 0,next:t}),()=>{this.#e.delete(e)}}#r(e){for(let t of this.#e)t(e)}};function Ie(e){return new $(e)}var Le=class{walletAccount;#e=!1;constructor(e){this.walletAccount=new $(e)}requireWalletAccount(e){let n=this.walletAccount.getSnapshot();if(!n)throw new t.W(e);return n}dispose(){this.#e||(this.#e=!0,this.onDispose())}[Symbol.dispose](){this.dispose()}onDispose(){}};Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return Ne}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return h}});
2
2
  //# sourceMappingURL=base-signer.cjs.map