@naculus/connect-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ var Bi=Object.defineProperty;var Ui=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var st=(n,e)=>()=>(n&&(e=n(n=0)),e);var Gt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),kn=(n,e)=>{for(var t in e)Bi(n,t,{get:e[t],enumerable:!0})};var ys=Gt(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.toBig=P.shrSL=P.shrSH=P.rotrSL=P.rotrSH=P.rotrBL=P.rotrBH=P.rotr32L=P.rotr32H=P.rotlSL=P.rotlSH=P.rotlBL=P.rotlBH=P.add5L=P.add5H=P.add4L=P.add4H=P.add3L=P.add3H=void 0;P.add=ds;P.fromBig=Bn;P.split=Xr;var Wt=BigInt(2**32-1),Rn=BigInt(32);function Bn(n,e=!1){return e?{h:Number(n&Wt),l:Number(n>>Rn&Wt)}:{h:Number(n>>Rn&Wt)|0,l:Number(n&Wt)|0}}function Xr(n,e=!1){let t=n.length,r=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Bn(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var Zr=(n,e)=>BigInt(n>>>0)<<Rn|BigInt(e>>>0);P.toBig=Zr;var Qr=(n,e,t)=>n>>>t;P.shrSH=Qr;var Jr=(n,e,t)=>n<<32-t|e>>>t;P.shrSL=Jr;var es=(n,e,t)=>n>>>t|e<<32-t;P.rotrSH=es;var ts=(n,e,t)=>n<<32-t|e>>>t;P.rotrSL=ts;var ns=(n,e,t)=>n<<64-t|e>>>t-32;P.rotrBH=ns;var rs=(n,e,t)=>n>>>t-32|e<<64-t;P.rotrBL=rs;var ss=(n,e)=>e;P.rotr32H=ss;var os=(n,e)=>n;P.rotr32L=os;var is=(n,e,t)=>n<<t|e>>>32-t;P.rotlSH=is;var as=(n,e,t)=>e<<t|n>>>32-t;P.rotlSL=as;var cs=(n,e,t)=>e<<t-32|n>>>64-t;P.rotlBH=cs;var ls=(n,e,t)=>n<<t-32|e>>>64-t;P.rotlBL=ls;function ds(n,e,t,r){let s=(e>>>0)+(r>>>0);return{h:n+t+(s/2**32|0)|0,l:s|0}}var us=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0);P.add3L=us;var fs=(n,e,t,r)=>e+t+r+(n/2**32|0)|0;P.add3H=fs;var ps=(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0);P.add4L=ps;var hs=(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0;P.add4H=hs;var gs=(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0);P.add5L=gs;var ms=(n,e,t,r,s,o)=>e+t+r+s+o+(n/2**32|0)|0;P.add5H=ms;var Ni={fromBig:Bn,split:Xr,toBig:Zr,shrSH:Qr,shrSL:Jr,rotrSH:es,rotrSL:ts,rotrBH:ns,rotrBL:rs,rotr32H:ss,rotr32L:os,rotlSH:is,rotlSL:as,rotlBH:cs,rotlBL:ls,add:ds,add3L:us,add3H:fs,add4L:ps,add4H:hs,add5H:ms,add5L:gs};P.default=Ni});var xs=Gt(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.crypto=void 0;var Oe=Ui("crypto");jt.crypto=Oe&&typeof Oe=="object"&&"webcrypto"in Oe?Oe.webcrypto:Oe&&typeof Oe=="object"&&"randomBytes"in Oe?Oe:void 0});var Nn=Gt(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.wrapXOFConstructorWithOpts=C.wrapConstructorWithOpts=C.wrapConstructor=C.Hash=C.nextTick=C.swap32IfBE=C.byteSwapIfBE=C.swap8IfBE=C.isLE=void 0;C.isBytes=ws;C.anumber=Un;C.abytes=at;C.ahash=Fi;C.aexists=Hi;C.aoutput=Mi;C.u8=$i;C.u32=Gi;C.clean=Ki;C.createView=Vi;C.rotr=Wi;C.rotl=ji;C.byteSwap=Ln;C.byteSwap32=vs;C.bytesToHex=zi;C.hexToBytes=Yi;C.asyncLoop=Zi;C.utf8ToBytes=On;C.bytesToUtf8=Qi;C.toBytes=qt;C.kdfInputToBytes=Ji;C.concatBytes=ea;C.checkOpts=ta;C.createHasher=Ss;C.createOptHasher=Cs;C.createXOFer=Es;C.randomBytes=na;var it=xs();function ws(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function Un(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function at(n,...e){if(!ws(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function Fi(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Un(n.outputLen),Un(n.blockLen)}function Hi(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function Mi(n,e){at(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function $i(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function Gi(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function Ki(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function Vi(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Wi(n,e){return n<<32-e|n>>>e}function ji(n,e){return n<<e|n>>>32-e>>>0}C.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ln(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}C.swap8IfBE=C.isLE?n=>n:n=>Ln(n);C.byteSwapIfBE=C.swap8IfBE;function vs(n){for(let e=0;e<n.length;e++)n[e]=Ln(n[e]);return n}C.swap32IfBE=C.isLE?n=>n:vs;var As=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",qi=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function zi(n){if(at(n),As)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=qi[n[t]];return e}var Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function bs(n){if(n>=Ee._0&&n<=Ee._9)return n-Ee._0;if(n>=Ee.A&&n<=Ee.F)return n-(Ee.A-10);if(n>=Ee.a&&n<=Ee.f)return n-(Ee.a-10)}function Yi(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(As)return Uint8Array.fromHex(n);let e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=bs(n.charCodeAt(o)),a=bs(n.charCodeAt(o+1));if(i===void 0||a===void 0){let c=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=i*16+a}return r}var Xi=async()=>{};C.nextTick=Xi;async function Zi(n,e,t){let r=Date.now();for(let s=0;s<n;s++){t(s);let o=Date.now()-r;o>=0&&o<e||(await(0,C.nextTick)(),r+=o)}}function On(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function Qi(n){return new TextDecoder().decode(n)}function qt(n){return typeof n=="string"&&(n=On(n)),at(n),n}function Ji(n){return typeof n=="string"&&(n=On(n)),at(n),n}function ea(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];at(s),e+=s.length}let t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){let o=n[r];t.set(o,s),s+=o.length}return t}function ta(n,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(n,e)}var Dn=class{};C.Hash=Dn;function Ss(n){let e=r=>n().update(qt(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function Cs(n){let e=(r,s)=>n(s).update(qt(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}function Es(n){let e=(r,s)=>n(s).update(qt(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}C.wrapConstructor=Ss;C.wrapConstructorWithOpts=Cs;C.wrapXOFConstructorWithOpts=Es;function na(n=32){if(it.crypto&&typeof it.crypto.getRandomValues=="function")return it.crypto.getRandomValues(new Uint8Array(n));if(it.crypto&&typeof it.crypto.randomBytes=="function")return Uint8Array.from(it.crypto.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}});var Ds=Gt(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.shake256=H.shake128=H.keccak_512=H.keccak_384=H.keccak_256=H.keccak_224=H.sha3_512=H.sha3_384=H.sha3_256=H.sha3_224=H.Keccak=void 0;H.keccakP=Bs;var wt=ys(),X=Nn(),ra=BigInt(0),bt=BigInt(1),sa=BigInt(2),oa=BigInt(7),ia=BigInt(256),aa=BigInt(113),Ps=[],Is=[],ks=[];for(let n=0,e=bt,t=1,r=0;n<24;n++){[t,r]=[r,(2*t+3*r)%5],Ps.push(2*(5*r+t)),Is.push((n+1)*(n+2)/2%64);let s=ra;for(let o=0;o<7;o++)e=(e<<bt^(e>>oa)*aa)%ia,e&sa&&(s^=bt<<(bt<<BigInt(o))-bt);ks.push(s)}var Rs=(0,wt.split)(ks,!0),ca=Rs[0],la=Rs[1],_s=(n,e,t)=>t>32?(0,wt.rotlBH)(n,e,t):(0,wt.rotlSH)(n,e,t),Ts=(n,e,t)=>t>32?(0,wt.rotlBL)(n,e,t):(0,wt.rotlSL)(n,e,t);function Bs(n,e=24){let t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)t[i]=n[i]^n[i+10]^n[i+20]^n[i+30]^n[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,l=t[c],u=t[c+1],p=_s(l,u,1)^t[a],d=Ts(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)n[i+f]^=p,n[i+f+1]^=d}let s=n[2],o=n[3];for(let i=0;i<24;i++){let a=Is[i],c=_s(s,o,a),l=Ts(s,o,a),u=Ps[i];s=n[u],o=n[u+1],n[u]=c,n[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)t[a]=n[i+a];for(let a=0;a<10;a++)n[i+a]^=~t[(a+2)%10]&t[(a+4)%10]}n[0]^=ca[r],n[1]^=la[r]}(0,X.clean)(t)}var vt=class n extends X.Hash{constructor(e,t,r,s=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=o,(0,X.anumber)(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=(0,X.u32)(this.state)}clone(){return this._cloneInto()}keccak(){(0,X.swap32IfBE)(this.state32),Bs(this.state32,this.rounds),(0,X.swap32IfBE)(this.state32),this.posOut=0,this.pos=0}update(e){(0,X.aexists)(this),e=(0,X.toBytes)(e),(0,X.abytes)(e);let{blockLen:t,state:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(t-this.pos,s-o);for(let a=0;a<i;a++)r[this.pos++]^=e[o++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:s}=this;e[r]^=t,(t&128)!==0&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,X.aexists)(this,!1),(0,X.abytes)(e),this.finish();let t=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(t.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,X.anumber)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,X.aoutput)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,(0,X.clean)(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new n(t,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};H.Keccak=vt;var Ne=(n,e,t)=>(0,X.createHasher)(()=>new vt(e,n,t));H.sha3_224=Ne(6,144,224/8);H.sha3_256=Ne(6,136,256/8);H.sha3_384=Ne(6,104,384/8);H.sha3_512=Ne(6,72,512/8);H.keccak_224=Ne(1,144,224/8);H.keccak_256=Ne(1,136,256/8);H.keccak_384=Ne(1,104,384/8);H.keccak_512=Ne(1,72,512/8);var Us=(n,e,t)=>(0,X.createXOFer)((r={})=>new vt(e,n,r.dkLen===void 0?t:r.dkLen,!0));H.shake128=Us(31,168,128/8);H.shake256=Us(31,136,256/8)});function da(n,e=!1){return e?{h:Number(n&zt),l:Number(n>>Ls&zt)}:{h:Number(n>>Ls&zt)|0,l:Number(n&zt)|0}}function Os(n,e=!1){let t=n.length,r=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=da(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var zt,Ls,Ns,Fs,Hs,Ms,$s=st(()=>{"use strict";zt=BigInt(4294967295),Ls=BigInt(32);Ns=(n,e,t)=>n<<t|e>>>32-t,Fs=(n,e,t)=>e<<t|n>>>32-t,Hs=(n,e,t)=>e<<t-32|n>>>64-t,Ms=(n,e,t)=>n<<t-32|e>>>64-t});import*as _e from"crypto";var ze,Gs=st(()=>{"use strict";ze=_e&&typeof _e=="object"&&"webcrypto"in _e?_e.webcrypto:_e&&typeof _e=="object"&&"randomBytes"in _e?_e:void 0});var Gn={};kn(Gn,{Hash:()=>Pe,abytes:()=>Z,aexists:()=>me,ahash:()=>Ye,anumber:()=>oe,aoutput:()=>At,asyncLoop:()=>zs,byteSwap:()=>Mn,byteSwap32:()=>Ws,byteSwapIfBE:()=>pa,bytesToHex:()=>D,bytesToUtf8:()=>Ys,checkOpts:()=>$n,clean:()=>ie,concatBytes:()=>z,createHasher:()=>ct,createOptHasher:()=>Xs,createView:()=>Xe,createXOFer:()=>Qt,hexToBytes:()=>$,isBytes:()=>Fe,isLE:()=>Hn,kdfInputToBytes:()=>Zt,nextTick:()=>qs,randomBytes:()=>xe,rotl:()=>fa,rotr:()=>de,swap32IfBE:()=>Yt,swap8IfBE:()=>Vs,toBytes:()=>ye,u32:()=>Fn,u8:()=>ua,utf8ToBytes:()=>Xt,wrapConstructor:()=>ga,wrapConstructorWithOpts:()=>ma,wrapXOFConstructorWithOpts:()=>ya});function Fe(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function oe(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Z(n,...e){if(!Fe(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function Ye(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");oe(n.outputLen),oe(n.blockLen)}function me(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function At(n,e){Z(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function ua(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function Fn(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function ie(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function Xe(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function de(n,e){return n<<32-e|n>>>e}function fa(n,e){return n<<e|n>>>32-e>>>0}function Mn(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function Ws(n){for(let e=0;e<n.length;e++)n[e]=Mn(n[e]);return n}function D(n){if(Z(n),js)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=ha[n[t]];return e}function Ks(n){if(n>=Te._0&&n<=Te._9)return n-Te._0;if(n>=Te.A&&n<=Te.F)return n-(Te.A-10);if(n>=Te.a&&n<=Te.f)return n-(Te.a-10)}function $(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(js)return Uint8Array.fromHex(n);let e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=Ks(n.charCodeAt(o)),a=Ks(n.charCodeAt(o+1));if(i===void 0||a===void 0){let c=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=i*16+a}return r}async function zs(n,e,t){let r=Date.now();for(let s=0;s<n;s++){t(s);let o=Date.now()-r;o>=0&&o<e||(await qs(),r+=o)}}function Xt(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function Ys(n){return new TextDecoder().decode(n)}function ye(n){return typeof n=="string"&&(n=Xt(n)),Z(n),n}function Zt(n){return typeof n=="string"&&(n=Xt(n)),Z(n),n}function z(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];Z(s),e+=s.length}let t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){let o=n[r];t.set(o,s),s+=o.length}return t}function $n(n,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(n,e)}function ct(n){let e=r=>n().update(ye(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function Xs(n){let e=(r,s)=>n(s).update(ye(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}function Qt(n){let e=(r,s)=>n(s).update(ye(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}function xe(n=32){if(ze&&typeof ze.getRandomValues=="function")return ze.getRandomValues(new Uint8Array(n));if(ze&&typeof ze.randomBytes=="function")return Uint8Array.from(ze.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}var Hn,Vs,pa,Yt,js,ha,Te,qs,Pe,ga,ma,ya,te=st(()=>{"use strict";Gs();Hn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Vs=Hn?n=>n:n=>Mn(n),pa=Vs;Yt=Hn?n=>n:Ws,js=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ha=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));Te={_0:48,_9:57,A:65,F:70,a:97,f:102};qs=async()=>{};Pe=class{};ga=ct,ma=Xs,ya=Qt});var Kn={};kn(Kn,{Keccak:()=>Ct,keccakP:()=>ro,keccak_224:()=>Ia,keccak_256:()=>Et,keccak_384:()=>ka,keccak_512:()=>Ra,sha3_224:()=>Ea,sha3_256:()=>_a,sha3_384:()=>Ta,sha3_512:()=>Pa,shake128:()=>Ba,shake256:()=>Ua});function ro(n,e=24){let t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)t[i]=n[i]^n[i+10]^n[i+20]^n[i+30]^n[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,l=t[c],u=t[c+1],p=Zs(l,u,1)^t[a],d=Qs(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)n[i+f]^=p,n[i+f+1]^=d}let s=n[2],o=n[3];for(let i=0;i<24;i++){let a=eo[i],c=Zs(s,o,a),l=Qs(s,o,a),u=Js[i];s=n[u],o=n[u+1],n[u]=c,n[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)t[a]=n[i+a];for(let a=0;a<10;a++)n[i+a]^=~t[(a+2)%10]&t[(a+4)%10]}n[0]^=Sa[r],n[1]^=Ca[r]}ie(t)}var xa,St,ba,wa,va,Aa,Js,eo,to,no,Sa,Ca,Zs,Qs,Ct,He,Ea,_a,Ta,Pa,Ia,Et,ka,Ra,so,Ba,Ua,Jt=st(()=>{"use strict";$s();te();xa=BigInt(0),St=BigInt(1),ba=BigInt(2),wa=BigInt(7),va=BigInt(256),Aa=BigInt(113),Js=[],eo=[],to=[];for(let n=0,e=St,t=1,r=0;n<24;n++){[t,r]=[r,(2*t+3*r)%5],Js.push(2*(5*r+t)),eo.push((n+1)*(n+2)/2%64);let s=xa;for(let o=0;o<7;o++)e=(e<<St^(e>>wa)*Aa)%va,e&ba&&(s^=St<<(St<<BigInt(o))-St);to.push(s)}no=Os(to,!0),Sa=no[0],Ca=no[1],Zs=(n,e,t)=>t>32?Hs(n,e,t):Ns(n,e,t),Qs=(n,e,t)=>t>32?Ms(n,e,t):Fs(n,e,t);Ct=class n extends Pe{constructor(e,t,r,s=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=o,oe(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Fn(this.state)}clone(){return this._cloneInto()}keccak(){Yt(this.state32),ro(this.state32,this.rounds),Yt(this.state32),this.posOut=0,this.pos=0}update(e){me(this),e=ye(e),Z(e);let{blockLen:t,state:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(t-this.pos,s-o);for(let a=0;a<i;a++)r[this.pos++]^=e[o++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:s}=this;e[r]^=t,(t&128)!==0&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){me(this,!1),Z(e),this.finish();let t=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(t.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return oe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(At(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,ie(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new n(t,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}},He=(n,e,t)=>ct(()=>new Ct(e,n,t)),Ea=He(6,144,224/8),_a=He(6,136,256/8),Ta=He(6,104,384/8),Pa=He(6,72,512/8),Ia=He(1,144,224/8),Et=He(1,136,256/8),ka=He(1,104,384/8),Ra=He(1,72,512/8),so=(n,e,t)=>Qt((r={})=>new Ct(e,n,r.dkLen===void 0?t:r.dkLen,!0)),Ba=so(31,168,128/8),Ua=so(31,136,256/8)});function cc(n){return n instanceof G}var ac,G,sn=st(()=>{"use strict";ac={token_not_deployed:"Token contract is not deployed on this chain.",invalid_address:"Address is not a valid EVM address.",invalid_amount:"Amount is invalid.",insufficient_allowance:"Insufficient allowance. Please approve the spender first.",insufficient_balance:"Insufficient token balance.",decimals_fetch_failed:"Failed to fetch token decimals from chain.",token_info_fetch_failed:"Failed to fetch token metadata from chain.",rpc_error:"RPC error occurred.",encoding_error:"Failed to encode ABI data.",unknown_error:"An unknown error occurred."},G=class extends Error{constructor(t,r,s){super(r??ac[t]);this.code=t;this.cause=s;this.name="ERC20TokenError"}code;cause;hasCode(t){return this.code===t}}});var mo={};kn(mo,{formatUnits:()=>Qe,parseUnits:()=>Ze});function Ze(n,e){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new G("invalid_amount",`Invalid decimals value: ${e}. Must be a non-negative integer.`);if(typeof n=="bigint")return n;let t;if(typeof n=="number"){if(!Number.isFinite(n))throw new G("invalid_amount",`Amount is not a finite number: ${n}`);if(n<0)throw new G("invalid_amount",`Amount must be non-negative, got: ${n}`);t=n.toString()}else t=n.trim();if(t===""||t===".")throw new G("invalid_amount",`Amount string is empty or invalid: "${n}"`);if(!/^[0-9]*\.?[0-9]*$/.test(t))throw new G("invalid_amount",`Amount contains invalid characters: "${n}"`);if(t.startsWith("-"))throw new G("invalid_amount",`Amount must be non-negative, got: "${n}"`);let r=t.indexOf("."),s,o;if(r===-1?(s=t,o=""):(s=t.slice(0,r),o=t.slice(r+1)),o.length>e)throw new G("invalid_amount",`Amount "${n}" has ${o.length} decimal places, but max is ${e}.`);o=o.padEnd(e,"0"),s=s.replace(/^0+/,"")||"0";let i=s+o;try{return BigInt(i)}catch{throw new G("invalid_amount",`Failed to parse amount as bigint: "${n}"`)}}function Qe(n,e){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new G("invalid_amount",`Invalid decimals value: ${e}. Must be a non-negative integer.`);let t=n<0n,o=(t?-n:n).toString().padStart(e+1,"0"),i=o.length-e,a=o.slice(0,i),c=o.slice(i);return c=c.replace(/0+$/,""),a=a.replace(/^0+/,"")||"0",c.length===0?t?`-${a}`:a:t?`-${a}.${c}`:`${a}.${c}`}var Tt=st(()=>{"use strict";sn()});var Yr={aa_unsupported_chain:"Chain does not support ERC-4337 account abstraction.",aa_no_bundler:"Bundler URL not configured. Provide a bundler URL or bundlerClient.",aa_no_paymaster:"Paymaster not configured.",aa_no_entry_point:"EntryPoint contract address not found for this chain.",aa_no_factory:"Account factory contract address not found for this chain.",aa_account_not_deployed:"Smart account is not deployed on-chain.",aa_account_already_deployed:"Smart account is already deployed.",aa_invalid_owner:"Invalid owner address.",aa_user_op_failed:"UserOperation failed during execution.",aa_user_op_rejected:"UserOperation was rejected by the bundler.",aa_estimation_failed:"Failed to estimate gas for UserOperation.",aa_signature_failed:"Failed to sign UserOperation.",aa_rpc_error:"RPC call failed.",aa_invalid_input:"Invalid input parameters.",aa_unknown_account_type:"Unsupported account type.",aa_no_calls:"At least one call is required for the UserOperation.",aa_encode_error:"ABI encode/decode error.",aa_paymaster_rejected:"Paymaster declined to sponsor this UserOperation.",aa_receipt_timeout:"UserOperation receipt not found after maximum retries.",aa_unknown_error:"An unknown error occurred."},R=class extends Error{constructor(t,r,s){super(r??Yr[t]);this.code=t;this.cause=s;this.name="AccountAbstractionError"}code;cause;hasCode(t){return this.code===t}};function Di(n){return n instanceof R}var ot=class{config;_sponsorInfo=null;constructor(e){this.config=e}async getPaymasterData(e){switch(this.config.type){case"verifying":return this.getVerifyingPaymasterData(e);case"sponsor":return this.getSponsorPaymasterData(e);case"token":return this.getTokenPaymasterData(e);case"custom":return this.getCustomPaymasterData(e);default:throw new R("aa_paymaster_rejected",`Unknown paymaster type: ${this.config.type}`)}}async isSponsored(e){try{let t=await this.getPaymasterData(e);return t.paymasterAndData!=="0x"&&t.paymasterAndData.length>2}catch{return!1}}get sponsorInfo(){return this._sponsorInfo}async getVerifyingPaymasterData(e){let t=this.serializeForPaymaster(e),r={"Content-Type":"application/json"};this.config.apiKey&&(r.Authorization=`Bearer ${this.config.apiKey}`);let s=new AbortController,o=setTimeout(()=>s.abort(),1e4);try{let i=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"pm_sponsorUserOperation",params:[t]}),signal:s.signal});if(!i.ok)throw new R("aa_paymaster_rejected",`Paymaster returned status ${i.status}`);let a=await i.json();if(a.error)throw new R("aa_paymaster_rejected",`Paymaster error: ${a.error.message}`,{code:a.error.code});let c=a.result;if(!c?.paymasterAndData||c.paymasterAndData==="0x")throw new R("aa_paymaster_rejected","Paymaster did not return paymasterAndData");return this._sponsorInfo=c.sponsor?.name??"Sponsored by Paymaster",{paymasterAndData:c.paymasterAndData,sponsorInfo:this._sponsorInfo}}catch(i){throw i instanceof R?i:new R("aa_paymaster_rejected","Failed to get paymaster data",i)}finally{clearTimeout(o)}}async getSponsorPaymasterData(e){let t=this.serializeForPaymaster(e),r=new AbortController,s=setTimeout(()=>r.abort(),1e4);try{let o=await fetch(this.config.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"pm_getPaymasterStakeData",params:[t]}),signal:r.signal});if(!o.ok)throw new R("aa_paymaster_rejected",`Sponsor paymaster returned status ${o.status}`);let i=await o.json();return i.error||!i.result?this.getVerifyingPaymasterData(e):(this._sponsorInfo="Gas sponsored by dApp",{paymasterAndData:i.result.paymasterAndData,sponsorInfo:this._sponsorInfo})}catch(o){throw new R("aa_paymaster_rejected","Sponsor paymaster failed",o)}finally{clearTimeout(s)}}async getTokenPaymasterData(e){let t=this.serializeForPaymaster(e),r={"Content-Type":"application/json"};this.config.apiKey&&(r.Authorization=`Bearer ${this.config.apiKey}`);let s={};this.config.policy?.token&&(s.token=this.config.policy.token);let o=new AbortController,i=setTimeout(()=>o.abort(),1e4);try{let a=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"pm_sponsorUserOperation",params:[t,this.config.policy?.token]}),signal:o.signal});if(!a.ok)throw new R("aa_paymaster_rejected",`Token paymaster returned status ${a.status}`);let c=await a.json();if(c.error)throw new R("aa_paymaster_rejected",`Token paymaster error: ${c.error.message}`);return this._sponsorInfo=this.config.policy?.token?"Gas paid with ERC-20 token":"Gas sponsored",{paymasterAndData:c.result?.paymasterAndData??"0x",sponsorInfo:this._sponsorInfo}}finally{clearTimeout(i)}}async getCustomPaymasterData(e){return this.getVerifyingPaymasterData(e)}serializeForPaymaster(e){return{sender:e.sender??"0x0000000000000000000000000000000000000000",nonce:`0x${(e.nonce??0n).toString(16)}`,initCode:e.initCode??"0x",callData:e.callData??"0x",accountGasLimits:e.accountGasLimits??"0x0000000000000000000000000000000000000000000000000000000000000000",preVerificationGas:`0x${(e.preVerificationGas??0n).toString(16)}`,maxFeePerGas:`0x${(e.maxFeePerGas??0n).toString(16)}`,maxPriorityFeePerGas:`0x${(e.maxPriorityFeePerGas??0n).toString(16)}`,paymasterAndData:e.paymasterAndData??"0x",signature:e.signature??"0x"}}};function Li(n){return new ot({url:n.url,type:n.type,policy:n.policy})}var Kt="0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",xt="0x0000000071727De22E5E9d8BAf0edAc6f37da032",Oi=xt,Ce="0x9406Cc6185a346906296840746125a0E44976454",fe=100000n,pe=100000n,le=50000n,Vt={"eip155:1":{entryPoint:xt,factory:Ce},"eip155:137":{entryPoint:Kt,factory:Ce},"eip155:10":{entryPoint:Kt,factory:Ce},"eip155:42161":{entryPoint:Kt,factory:Ce},"eip155:8453":{entryPoint:xt,factory:Ce},"eip155:11155111":{entryPoint:xt,factory:Ce}};function Vn(n){return{sender:n.sender??"0x",nonce:n.nonce??0n,initCode:n.initCode??"0x",callData:n.callData??"0x",accountGasLimits:n.accountGasLimits??$a(pe,fe),preVerificationGas:n.preVerificationGas??le,maxFeePerGas:n.maxFeePerGas??0n,maxPriorityFeePerGas:n.maxPriorityFeePerGas??0n,paymasterAndData:n.paymasterAndData??"0x",signature:n.signature??"0x"}}function Da(n){if(!n.length)throw new R("aa_no_calls");return n.length===1?La(n[0].to,n[0].value,n[0].data):Oa(n)}function La(n,e,t){let r="0xb61d27f6",s=n.toLowerCase().replace("0x","").padStart(64,"0"),o=e.toString(16).padStart(64,"0"),i=t.replace("0x",""),a=i.length/2,c="60".padStart(64,"0"),l=a.toString(16).padStart(64,"0"),u=Math.ceil(i.length/64)*64,p=i.padEnd(u,"0");return`${r}${s}${o}${c}${l}${p}`}function Oa(n){let e="0x47e1da2a",t=n.length,r=t.toString(16).padStart(64,"0"),s=r+n.map(g=>g.to.toLowerCase().replace("0x","").padStart(64,"0")).join(""),o=r+n.map(g=>g.value.toString(16).padStart(64,"0")).join(""),i=n.map(g=>{let w=g.data.replace("0x","");return(w.length/2).toString(16).padStart(64,"0")+w}).join(""),a=r+i,c=32+t*32,l=32+t*32,u=32+i.length/2,p=96,d=p,f=p+c,h=p+c+l;return`${e}`+d.toString(16).padStart(64,"0")+f.toString(16).padStart(64,"0")+h.toString(16).padStart(64,"0")+s+o+a}function Na(n,e){let{concatBytes:t}={concatBytes:(...g)=>{let w=g.reduce((k,N)=>k+N.length,0),S=new Uint8Array(w),M=0;for(let k of g)S.set(k,M),M+=k.length;return S}},r=g=>{let w=g.startsWith("0x")?g.slice(2):g,S=new Uint8Array(w.length/2);for(let M=0;M<w.length;M+=2)S[M/2]=parseInt(w.slice(M,M+2),16);return S},s=g=>new TextEncoder().encode(g),o=g=>{if(g.length>=32)return g.slice(0,32);let w=new Uint8Array(32);return w.set(g),w},i=Ie(s("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")),a=Ie(s("Account")),c=Ie(s("1")),l=new Uint8Array(32),p=BigInt(e).toString(16).padStart(64,"0"),d=r(`0x${p}`),f=r(n),h=new Uint8Array(32);return h.set(f,12),Ie(t(i,a,c,d,h))}function oo(n,e,t){let{sender:r,nonce:s,initCode:o,callData:i,accountGasLimits:a,preVerificationGas:c,maxFeePerGas:l,maxPriorityFeePerGas:u,paymasterAndData:p}=n,d=Fa({sender:r,nonce:s,initCode:o,callData:i,accountGasLimits:a,preVerificationGas:c,maxFeePerGas:l,maxPriorityFeePerGas:u,paymasterAndData:p}),f=Ie(d),h=Na(e,t),{concatBytes:g}={concatBytes:(...k)=>{let N=k.reduce((Se,Le)=>Se+Le.length,0),re=new Uint8Array(N),Ae=0;for(let Se of k)re.set(Se,Ae),Ae+=Se.length;return re}},w=new Uint8Array([25,1]),S=Ie(g(w,h,f)),{bytesToHex:M}=Ma();return`0x${M(S)}`}function Fa(n){let{concatBytes:e,bytesToHex:t}=(()=>{let o=new TextEncoder;return{concatBytes:(...i)=>{let a=i.reduce((u,p)=>u+p.length,0),c=new Uint8Array(a),l=0;for(let u of i)c.set(u,l),l+=u.length;return c},bytesToHex:i=>Array.from(i).map(a=>a.toString(16).padStart(2,"0")).join("")}})(),r=o=>{let i=o.startsWith("0x")?o.slice(2):o,a=new Uint8Array(i.length/2);for(let c=0;c<i.length;c+=2)a[c/2]=parseInt(i.slice(c,c+2),16);return a},s=o=>{let i=o.toString(16).padStart(64,"0");return r(`0x${i}`)};return e(r(n.sender),s(n.nonce),Ie(r(n.initCode)),Ie(r(n.callData)),r(n.accountGasLimits),s(n.preVerificationGas),s(n.maxFeePerGas),s(n.maxPriorityFeePerGas),Ie(r(n.paymasterAndData)))}function Ie(n){let{keccak_256:e}=Ha();return e(n)}var en=null;function Ha(){if(en)return{keccak_256:en};try{en=Ds().keccak_256}catch{throw new R("aa_encode_error","keccak256 not available. @noble/hashes is required.")}return{keccak_256:en}}var _t=null;function Ma(){if(_t)return{bytesToHex:_t};try{_t=Nn().bytesToHex}catch{_t=n=>Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}return{bytesToHex:_t}}function $a(n,e){let t=n.toString(16).padStart(32,"0"),r=e.toString(16).padStart(32,"0");return`0x${t}${r}`}async function Ga(n,e,t,r){try{let s=oo(n,t,r),o=await Ka(s),i=await e(o);return{...n,signature:i}}catch(s){throw new R("aa_signature_failed","Failed to sign UserOperation",s)}}async function Ka(n){let e=n.startsWith("0x")?n.slice(2):n,t=`Ethereum Signed Message:
2
+ ${e.length/2}`,s=new TextEncoder().encode(t),o=new Uint8Array(e.length/2);for(let l=0;l<e.length;l+=2)o[l/2]=parseInt(e.slice(l,l+2),16);let i=new Uint8Array(s.length+o.length);i.set(s),i.set(o,s.length);let{keccak_256:a}=await Promise.resolve().then(()=>(Jt(),Kn)),{bytesToHex:c}=await Promise.resolve().then(()=>(te(),Gn));return`0x${c(a(i))}`}async function Va(n,e,t){if(!e)throw new R("aa_no_bundler");let r={sender:n.sender,nonce:`0x${n.nonce.toString(16)}`,initCode:n.initCode,callData:n.callData,accountGasLimits:n.accountGasLimits,preVerificationGas:`0x${n.preVerificationGas.toString(16)}`,maxFeePerGas:`0x${n.maxFeePerGas.toString(16)}`,maxPriorityFeePerGas:`0x${n.maxPriorityFeePerGas.toString(16)}`,paymasterAndData:n.paymasterAndData,signature:n.signature},s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{let i;try{i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendUserOperation",params:[r,t]}),signal:s.signal})}catch{throw new R("aa_user_op_rejected","Failed to connect to bundler")}if(!i.ok)throw new R("aa_user_op_rejected",`Bundler returned status ${i.status}`);let a=await i.json();if(a.error)throw new R("aa_user_op_rejected",a.error.message,{code:a.error.code});return{userOpHash:a.result,sender:n.sender,nonce:n.nonce}}finally{clearTimeout(o)}}async function Wa(n,e,t){if(!t)throw new R("aa_no_bundler");let r={sender:n.sender??"0x0000000000000000000000000000000000000000",nonce:`0x${(n.nonce??0n).toString(16)}`,initCode:n.initCode??"0x",callData:n.callData??"0x",accountGasLimits:n.accountGasLimits??`0x${pe.toString(16).padStart(32,"0")}${fe.toString(16).padStart(32,"0")}`,preVerificationGas:`0x${(n.preVerificationGas??le).toString(16)}`,maxFeePerGas:`0x${(n.maxFeePerGas??0n).toString(16)}`,maxPriorityFeePerGas:`0x${(n.maxPriorityFeePerGas??0n).toString(16)}`,paymasterAndData:n.paymasterAndData??"0x",signature:n.signature??"0x"},s=new AbortController,o=setTimeout(()=>s.abort(),15e3);try{let i;try{i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_estimateUserOperationGas",params:[r,e]}),signal:s.signal})}catch{return{callGasLimit:fe,verificationGasLimit:pe,preVerificationGas:le}}if(!i.ok)return{callGasLimit:fe,verificationGasLimit:pe,preVerificationGas:le};let a=await i.json().catch(()=>({}));if(a.error||!a.result)return{callGasLimit:fe,verificationGasLimit:pe,preVerificationGas:le};let c=a.result;if(c.accountGasLimits){let l=c.accountGasLimits.replace("0x","");return{callGasLimit:BigInt(`0x${l.slice(32,64)}`),verificationGasLimit:BigInt(`0x${l.slice(0,32)}`),preVerificationGas:c.preVerificationGas?BigInt(c.preVerificationGas):le,accountGasLimits:c.accountGasLimits}}return{callGasLimit:c.callGasLimit?BigInt(c.callGasLimit):fe,verificationGasLimit:c.verificationGasLimit?BigInt(c.verificationGasLimit):pe,preVerificationGas:c.preVerificationGas?BigInt(c.preVerificationGas):le}}finally{clearTimeout(o)}}function ja(n,e){return Ce}function qa(n){let e=Vt[n];return e?e.entryPoint:null}function io(n,e){let t="0xcf7aba77",r=n.toLowerCase().replace("0x","").padStart(64,"0"),s=e.toString(16).padStart(64,"0");return`${t}${r}${s}`}function za(n,e,t){let r="0xb61d27f6",s=n.toLowerCase().replace("0x","").padStart(64,"0"),o=e.toString(16).padStart(64,"0"),i=s.length/2+o.length/2+64,a=t.startsWith("0x")?(t.length-2)/2:t.length/2,c=`00000000000000000000000000000000000000000000000000000000000000${i.toString(16).padStart(2,"0")}`,l=a.toString(16).padStart(64,"0"),u=t.replace("0x","");return`${r}${s}${o}${c}${l}${u}`}function Ya(n){let e="0x47e1da2a",t=n.length,o=32+32*t+32+32*t+32,i=t.toString(16).padStart(64,"0")+n.map(N=>N.to.toLowerCase().replace("0x","").padStart(64,"0")).join(""),a=t.toString(16).padStart(64,"0")+n.map(N=>N.value.toString(16).padStart(64,"0")).join(""),c=n.map(N=>N.data.replace("0x","").length/2),l=n.map((N,re)=>c[re].toString(16).padStart(64,"0")+N.data.replace("0x","")).join(""),u=32+l.length/2,d=t.toString(16).padStart(64,"0")+l,f=32+t*32,h=32+t*32,g=32+l.length/2,w=96,S=96,M=32,k=S+f;return`${e}${Xa(n)}`}function Xa(n){let e=n.length,t=e.toString(16).padStart(64,"0"),r=t+n.map(f=>f.to.toLowerCase().replace("0x","").padStart(64,"0")).join(""),s=t+n.map(f=>f.value.toString(16).padStart(64,"0")).join(""),o=n.map(f=>{let h=f.data.replace("0x","");return(h.length/2).toString(16).padStart(64,"0")+h}).join(""),i=t+o,a=32+e*32,c=32+e*32,l=32+o.length/2,u="60".padStart(64,"0"),p=(96+a).toString(16).padStart(64,"0"),d=(96+a+c).toString(16).padStart(64,"0");return u+p+d+r+s+i}async function Wn(n,e){return await Me(n,"eth_getCode",[e,"latest"])!=="0x"}async function Me(n,e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),1e4);try{let o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:e,params:t}),signal:r.signal});if(!o.ok)throw new R("aa_rpc_error",`RPC returned status ${o.status}`);let i=await o.json();if(i.error)throw new R("aa_rpc_error",i.error.message,{code:i.error.code});return i.result}finally{clearTimeout(s)}}var jn=class{config;constructor(e){this.config=e}isAASupported(e){return(e??this.config.chainId)in Vt}async getAccountAddress(e){let t=e.chainId??this.config.chainId,r=e.entryPoint??this.getEntryPoint(t),s=this.getFactory(t,e.accountType),o=e.salt??0n,i=io(e.owner,o),a=await Me(this.config.rpcUrl,"eth_call",[{to:s,data:i},"latest"]),c=a.startsWith("0x")?a.slice(2):a;return`0x${c.slice(c.length-40)}`}async createAccount(e){if(!e.owner||!e.owner.startsWith("0x")||e.owner.length!==42)throw new R("aa_invalid_owner");let t=e.chainId??this.config.chainId,r=await this.getAccountAddress(e),s=await Wn(this.config.rpcUrl,r);return{address:r,isDeployed:s,accountType:e.accountType,owner:e.owner}}async deployAccount(e){let t=e.chainId??this.config.chainId,r=await this.getAccountAddress(e);if(await Wn(this.config.rpcUrl,r))return r;throw new R("aa_account_not_deployed",`Account ${r} is not deployed. Use getDeployCallData() to obtain the deploy transaction payload, sign it, and send it to the factory.`)}async getDeployCallData(e){let t=e.chainId??this.config.chainId,r=this.getFactory(t,e.accountType),s=e.salt??0n;return{to:r,data:io(e.owner,s),value:0n}}async sendUserOperation(e,t,r){if(!t.length)throw new R("aa_no_calls");let s=e.chainId??this.config.chainId,o=await this.getAccountAddress(e),i="0x";if(!r?.skipDeploy&&!await Wn(this.config.rpcUrl,o)){let N=await this.getDeployCallData(e);i=`${this.getFactory(s,e.accountType)}${N.data.replace("0x","")}`}let a=e.entryPoint??this.getEntryPoint(s),c=await this.getNonce(a,o),l=t.length===1?za(t[0].to,t[0].value,t[0].data):Ya(t),u;try{u=await this.estimateUserOperationGas(a,{sender:o,nonce:c,initCode:i,callData:l,paymasterAndData:"0x",signature:"0x"})}catch{u={callGasLimit:fe,verificationGasLimit:pe,preVerificationGas:le}}let p=r?.gasOverrides?.callGasLimit??u.callGasLimit,d=r?.gasOverrides?.verificationGasLimit??u.verificationGasLimit,f=r?.gasOverrides?.preVerificationGas??u.preVerificationGas,h,g;if(r?.gasOverrides?.maxFeePerGas)h=r.gasOverrides.maxFeePerGas,g=r.gasOverrides.maxPriorityFeePerGas??await this.getPriorityFee();else{let k=await this.getBaseFee(),N=await this.getPriorityFee();h=k*2n+N,g=N}let w=ao(d,p),S=Vn({sender:o,nonce:c,initCode:i,callData:l,accountGasLimits:w,preVerificationGas:f,maxFeePerGas:h,maxPriorityFeePerGas:g,paymasterAndData:"0x",signature:"0x"}),M=r?.paymaster??this.config.defaultPaymasterConfig;if(M){let N=await(this.config.paymaster??new ot({url:M.url,type:M.type,policy:M.policy})).getPaymasterData(S);S={...S,paymasterAndData:N.paymasterAndData}}return{userOpHash:"0x",sender:o,nonce:c}}async getNonce(e,t){let r="0x"+"0".repeat(64),s=`0x35567e1a${t.replace("0x","").padStart(64,"0")}${r.replace("0x","")}`,o="0x35567e1a",i=t.toLowerCase().replace("0x","").padStart(64,"0"),a=r.replace("0x","").padStart(48,"0"),c=`${o}${i}${a}`,l=r.replace("0x","").padStart(64,"0"),u=await Me(this.config.rpcUrl,"eth_call",[{to:e,data:`${o}${i}${l}`},"latest"]);return BigInt(u)}async estimateUserOperationGas(e,t){let r=this.config.bundlerClient.url,s={...t,sender:t.sender??"0x",nonce:t.nonce??0n,initCode:t.initCode??"0x",callData:t.callData??"0x",accountGasLimits:t.accountGasLimits??"0x",preVerificationGas:t.preVerificationGas??0n,maxFeePerGas:t.maxFeePerGas??0n,maxPriorityFeePerGas:t.maxPriorityFeePerGas??0n,paymasterAndData:t.paymasterAndData??"0x",signature:t.signature??"0x"},o=await Me(r,"eth_estimateUserOperationGas",[s,e]);return{callGasLimit:o.callGasLimit?BigInt(o.callGasLimit):fe,verificationGasLimit:o.verificationGasLimit?BigInt(o.verificationGasLimit):pe,preVerificationGas:o.preVerificationGas?BigInt(o.preVerificationGas):le,accountGasLimits:o.accountGasLimits}}async sendUserOpToBundler(e){let t=this.config.bundlerClient.url;if(!t)throw new R("aa_no_bundler");let r=i=>{let a=i.toString(16);return a.length%2===0?`0x${a}`:`0x0${a}`},s={sender:e.sender,nonce:r(e.nonce),initCode:e.initCode,callData:e.callData,accountGasLimits:e.accountGasLimits,preVerificationGas:r(e.preVerificationGas),maxFeePerGas:r(e.maxFeePerGas),maxPriorityFeePerGas:r(e.maxPriorityFeePerGas),paymasterAndData:e.paymasterAndData,signature:e.signature};return await Me(t,"eth_sendUserOperation",[s,e.sender])}async getUserOperationReceipt(e,t=10,r=2e3){let s=this.config.bundlerClient.url;for(let o=0;o<t;o++){try{let i=await Me(s,"eth_getUserOperationReceipt",[e]);if(i)return{userOpHash:i.userOpHash,entryPoint:i.entryPoint,sender:i.sender,nonce:BigInt(i.nonce),paymaster:i.paymaster,actualGasUsed:BigInt(i.actualGasUsed),actualGasCost:BigInt(i.actualGasCost),success:i.success,transactionHash:i.transactionHash,logs:i.logs}}catch{}o<t-1&&await new Promise(i=>setTimeout(i,r))}throw new R("aa_receipt_timeout","UserOperation receipt not found after maximum retries")}async sendBatch(e,t,r){return this.sendUserOperation(e,t,r)}async getBaseFee(){try{let e=await Me(this.config.rpcUrl,"eth_getBlockByNumber",["latest",!1]);if(e?.baseFeePerGas)return BigInt(e.baseFeePerGas)}catch{}return 10000000000n}async getPriorityFee(){try{let e=await Me(this.config.rpcUrl,"eth_maxPriorityFeePerGas",[]);return BigInt(e)}catch{return 1000000000n}}getEntryPoint(e){let t=qa(e);if(!t)throw new R("aa_no_entry_point");return t}getFactory(e,t){let r=ja(e,t);if(!r)throw new R("aa_no_factory");return r}};function ao(n,e){let t=n.toString(16).padStart(32,"0"),r=e.toString(16).padStart(32,"0");return`0x${t}${r}`}function Za(n){let e=n.startsWith("0x")?n.slice(2):n,t=BigInt(`0x${e.slice(0,32)}`),r=BigInt(`0x${e.slice(32,64)}`);return{verificationGasLimit:t,callGasLimit:r}}var Qa=["dead","deaf","deed","deec","deed"],Ja="0x0000000000000000000000000000000000000000",ec=/^0x[a-fA-F0-9]{40}$/;function Vd(n){return n.toLowerCase()===Ja}function Wd(n){let e=n.toLowerCase().replace(/^0x/,"");return Qa.some(t=>e.startsWith(t))||e==="0000000000000000000000000000000000000000"}function jd(n,e){return!n||typeof n!="string"?!1:e==="eip155"||!e?ec.test(n):e==="solana"?/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(n):e==="xrpl"?/^r[1-9A-HJ-NP-Za-km-z]{24,34}$/.test(n):!0}var qn=class{config;state={lastSession:null,retryCount:0,isReconnecting:!1};retryTimeout=null;constructor(e={}){this.config={enabled:e.enabled??!0,maxRetries:e.maxRetries??3,retryDelay:e.retryDelay??2e3,onReconnecting:e.onReconnecting,onReconnected:e.onReconnected,onFailed:e.onFailed}}setLastSession(e){this.state.lastSession=e,this.state.retryCount=0}getState(){return{lastSession:this.state.lastSession,retryCount:this.state.retryCount,isReconnecting:this.state.isReconnecting}}needsReconnect(){return this.config.enabled&&this.state.lastSession!==null}async reconnect(e){if(!this.config.enabled||!this.state.lastSession||this.state.isReconnecting)return!1;this.state.isReconnecting=!0,this.config.onReconnecting?.();try{return await e(this.state.lastSession),this.state.isReconnecting=!1,this.state.retryCount=0,this.config.onReconnected?.(),!0}catch(t){return this.state.isReconnecting=!1,this.handleReconnectError(t,e)}}async handleReconnectError(e,t){if(this.state.retryCount>=this.config.maxRetries)return this.config.onFailed?.(e),this.clearSession(),!1;this.state.retryCount++;let r=Math.min(this.config.retryDelay*this.state.retryCount,2147483647);return new Promise(s=>{this.retryTimeout=setTimeout(async()=>{try{let o=await this.reconnect(t);s(o)}catch{s(!1)}},r)})}cancel(){this.retryTimeout&&(clearTimeout(this.retryTimeout),this.retryTimeout=null),this.state.isReconnecting=!1}clearSession(){this.state.lastSession=null,this.state.retryCount=0,this.state.isReconnecting=!1,this.cancel()}updateConfig(e){this.config={...this.config,...e}}reset(){this.clearSession(),this.config.onFailed=void 0,this.config.onReconnected=void 0,this.config.onReconnecting=void 0}};function zd(n){return new qn(n)}var co={debug:0,info:1,warn:2,error:3,silent:999},Yn="warn",zn=null;function tc(n){Yn=n}function nc(n){zn=n}function rc(n){return co[n]>=co[Yn]}function $e(n,e,...t){if(!rc(n))return;if(zn){zn(n,e,...t);return}let r=`[${e}]`;switch(n){case"debug":console.debug(r,...t);break;case"info":console.info(r,...t);break;case"warn":console.warn(r,...t);break;case"error":console.error(r,...t);break}}function sc(n){return{debug:(...e)=>$e("debug",n,...e),info:(...e)=>$e("info",n,...e),warn:(...e)=>$e("warn",n,...e),error:(...e)=>$e("error",n,...e)}}var O={debug:(n,...e)=>$e("debug",n,...e),info:(n,...e)=>$e("info",n,...e),warn:(n,...e)=>$e("warn",n,...e),error:(n,...e)=>$e("error",n,...e),for:sc,setLogLevel:tc,setLogSink:nc,getLogLevel:()=>Yn};var Zn={"eip155:1":"ethereum","eip155:137":"polygon","eip155:10":"optimism","eip155:42161":"arbitrum","eip155:8453":"base","eip155:43114":"avalanche","eip155:56":"binance","eip155:250":"fantom","eip155:100":"gnosis","eip155:1101":"polygon-zkevm"},Qd=Object.fromEntries(Object.entries(Zn).map(([n,e])=>[e,n]));function Xn(n){return Zn[n]??(n.startsWith("eip155:")?n.slice(7):n)}var lo=new Set(Object.keys(Zn)),fo={"eip155:1":{USDC:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",USDT:"0xdAC17F958D2ee523a2206206994597C13D831ec7",DAI:"0x6B175474E89094C44Da98b954EedeAC495271d0F",WETH:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",aUSDC:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},"eip155:137":{USDC:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",USDT:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",aUSDC:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"},"eip155:10":{USDC:"0x7F5c764cBc14f9669B88837ca1490cCa17c31607",aUSDC:"0x7F5c764cBc14f9669B88837ca1490cCa17c31607"}};function uo(n,e){let t=fo[n];return!t||e.startsWith("0x")&&e.length===42?e:t[e.toUpperCase()]??e}var tn=class{id="axelar";name="Axelar";config;constructor(e){this.config={apiUrl:e?.apiUrl??"https://api.axelarscan.io",backendUrl:e?.backendUrl}}async getRoutes(e,t,r,s,o){if(!this.supportsChainPair(e,t))return[];let i=uo(e,r),a=uo(t,s);if(this.config.backendUrl)try{let c=await this.getRoutesViaBackend(e,t,i,a,o);if(c.length>0)return c}catch(c){O.warn("axelar-provider","Backend proxy unavailable",c)}try{return await this.getRoutesViaDirectAPI(e,t,i,a,o)}catch(c){return O.warn("axelar-provider","Direct API call failed",c),[]}}async getRoutesViaBackend(e,t,r,s,o){if(!this.config.backendUrl)return[];let i=await fetch(`${this.config.backendUrl}/api/routes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fromChain:e,toChain:t,fromToken:r,toToken:s,amount:o,provider:"axelar"})});if(!i.ok)throw new Error(`Backend returned ${i.status}`);return(await i.json()).routes??[]}async getRoutesViaDirectAPI(e,t,r,s,o){let i=Xn(e),a=Xn(t);if(!i||!a)return[];try{let c=await fetch(`${this.config.apiUrl}/GMP/gmpFee`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceChain:i,destinationChain:a,amount:o,sourceContractAddress:r})});if(!c.ok)return O.warn("axelar-provider",`GMP fee API returned ${c.status}`),[];let l=await c.json(),u=l.baseFee??"0",p=l.destinationGasFee??"0";return[{id:`axelar_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,provider:"axelar",fromChain:e,toChain:t,fromToken:r,toToken:s,fromAmount:o,toAmount:o,toAmountMin:(BigInt(o)-BigInt(u)-BigInt(p)).toString(),gasCosts:{fromChain:{maxFeePerGas:"0",maxPriorityFeePerGas:"0",gasLimit:"250000",totalCostWei:"0",totalCostUsd:"0"},toChain:{maxFeePerGas:"0",maxPriorityFeePerGas:"0",gasLimit:p,totalCostWei:p,totalCostUsd:"0"},totalUsd:"0"},estimatedTime:120,steps:[{type:"approve",chain:e,token:r,contractAddress:this.getAxelarGateway(e),estimatedGas:"150000"},{type:"cross-chain",chain:e,token:r,contractAddress:this.getAxelarGateway(e),estimatedGas:"250000"}],fee:{protocolFee:u,integrationFee:p},summary:`Deposit via Axelar GMP: ${e} \u2192 ${t}`}]}catch(c){return O.warn("axelar-provider","Failed to estimate GMP fee",c),[]}}async getTransactionParams(e,t,r){return[{type:"approve",chainId:e.fromChain,to:e.fromToken,data:"0x",value:"0"},{type:"cross-chain",chainId:e.fromChain,to:this.getAxelarGateway(e.fromChain),data:this.buildGMPData(e,r),value:e.fromAmount}]}async getRouteStatus(e){try{let t=await fetch(`${this.config.apiUrl}/GMP/search?txHash=${e}`);if(!t.ok)return{status:"pending"};let r=await t.json(),s=r.status??"pending";return{status:this.mapAxelarStatus(s),toTxHash:r.toTxHash,currentStep:s}}catch{return{status:"pending"}}}supportsChainPair(e,t){return lo.has(e)&&lo.has(t)}supportsToken(e,t){let r=fo[e];return r?t.startsWith("0x")&&t.length===42?Object.values(r).includes(t.toLowerCase()):Object.keys(r).includes(t.toUpperCase()):!1}getAxelarGateway(e){return{"eip155:1":"0x4F449524383f30E6fEeE5e11e6E65C89CDc3df8D","eip155:137":"0x6f015F16De3fC12C9b5F8E1072e80E8Af7C5B0c4","eip155:10":"0x7f0a0C7149a46Bf943cCd412da687144b49C8274","eip155:42161":"0xe432150cce91c13a887f7D836923b4F32401c4DC","eip155:8453":"0x5a913e3e5dAb48c1B0A5Bf1a31290f2d7eA3C0d4"}[e]??"0x0000000000000000000000000000000000000000"}buildGMPData(e,t){let r=Xn(e.toChain)??e.toChain,s=t.padStart(66,"0x").slice(0,66);return`0x${Buffer.from(r).toString("hex")}${s.slice(2)}`}mapAxelarStatus(e){switch(e){case"executed":case"confirmed":return"completed";case"failed":return"failed";case"approved":case"gateway_call":return"bridging";default:return"pending"}}};var oc={1:"eip155:1",137:"eip155:137",10:"eip155:10",42161:"eip155:42161",8453:"eip155:8453",43114:"eip155:43114",56:"eip155:56",250:"eip155:250",324:"eip155:324",59144:"eip155:59144",534352:"eip155:534352",100:"eip155:100",1101:"eip155:1101"},ic=Object.fromEntries(Object.entries(oc).map(([n,e])=>[e,n]));function nn(n){let e=ic[n];return e||(n.startsWith("eip155:")?n.slice(7):n)}var po=new Set(["eip155:1","eip155:137","eip155:10","eip155:42161","eip155:8453","eip155:43114","eip155:56","eip155:250","eip155:324","eip155:59144","eip155:534352","eip155:100","eip155:1101"]),go={"eip155:1":{USDC:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",USDT:"0xdAC17F958D2ee523a2206206994597C13D831ec7",DAI:"0x6B175474E89094C44Da98b954EedeAC495271d0F",WETH:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",ETH:"0x0000000000000000000000000000000000000000"},"eip155:137":{USDC:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",USDT:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",DAI:"0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",WMATIC:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",MATIC:"0x0000000000000000000000000000000000000000"},"eip155:10":{USDC:"0x7F5c764cBc14f9669B88837ca1490cCa17c31607",USDT:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",DAI:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",WETH:"0x4200000000000000000000000000000000000006",ETH:"0x0000000000000000000000000000000000000000"},"eip155:42161":{USDC:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",USDT:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",DAI:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",WETH:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",ETH:"0x0000000000000000000000000000000000000000"},"eip155:8453":{USDC:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",WETH:"0x4200000000000000000000000000000000000006",ETH:"0x0000000000000000000000000000000000000000"}};function ho(n,e){let t=go[n];return!t||e.startsWith("0x")&&e.length===42?e:t[e.toUpperCase()]??e}var rn=class{id="lifi";name="LI.FI";config;constructor(e){this.config={apiUrl:e?.apiUrl??"https://li.quest/v1",apiKey:e?.apiKey,backendUrl:e?.backendUrl}}async getRoutes(e,t,r,s,o){if(!this.supportsChainPair(e,t))return[];let i=nn(e),a=nn(t),c=ho(e,r),l=ho(t,s);if(this.config.backendUrl)try{let u=await this.getRoutesViaBackend(e,t,c,l,o);if(u.length>0)return u}catch(u){O.warn("lifi-provider","Backend proxy unavailable, falling back to direct API",u)}try{return await this.getRoutesViaDirectAPI(i,a,c,l,o)}catch(u){return O.warn("lifi-provider","Direct LI.FI API call failed",u),[]}}async getRoutesViaBackend(e,t,r,s,o){if(!this.config.backendUrl)return[];let i=await fetch(`${this.config.backendUrl}/api/routes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fromChain:e,toChain:t,fromToken:r,toToken:s,amount:o,provider:"lifi"})});if(!i.ok)throw new Error(`Backend returned ${i.status}`);return(await i.json()).routes??[]}async getRoutesViaDirectAPI(e,t,r,s,o){let i={"Content-Type":"application/json"};this.config.apiKey&&(i["x-lifi-api-key"]=this.config.apiKey);let a=new URLSearchParams({fromChain:e.toString(),toChain:t.toString(),fromToken:r,toToken:s,fromAmount:o,slippage:"0.5"}),c=await fetch(`${this.config.apiUrl}/advanced/stepTransaction?${a}`,{headers:i});if(!c.ok)return O.warn("lifi-provider",`LI.FI API returned ${c.status}`),[];let l=await c.json();return!l.transactionRequest||!l.estimate?[]:[{id:l.id??`lifi_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,provider:"lifi",fromChain:e,toChain:t,fromToken:r,toToken:s,fromAmount:o,toAmount:l.estimate.toAmount,toAmountMin:l.estimate.toAmountMin,gasCosts:{fromChain:{maxFeePerGas:"0",maxPriorityFeePerGas:"0",gasLimit:l.transactionRequest.gasLimit??"0",totalCostWei:"0",totalCostUsd:"0"},toChain:{maxFeePerGas:"0",maxPriorityFeePerGas:"0",gasLimit:"0",totalCostWei:"0",totalCostUsd:"0"},totalUsd:"0"},estimatedTime:30,steps:[{type:"approve",chain:e,token:r,contractAddress:l.transactionRequest.to,estimatedGas:l.transactionRequest.gasLimit??"0"},{type:"cross-chain",chain:e,token:r,contractAddress:l.transactionRequest.to,data:l.transactionRequest.data,estimatedGas:l.transactionRequest.gasLimit??"0"}],fee:{protocolFee:"0"},summary:`Bridge via LI.FI: ${e} \u2192 ${t}`}]}async getTransactionParams(e,t,r){let s=[],o=e.steps.find(a=>a.type==="cross-chain"),i=e.steps.find(a=>a.type==="approve");if(i&&s.push({type:"approve",chainId:e.fromChain,to:e.fromToken,data:i.data??"0x",value:"0"}),o?.data&&s.push({type:"cross-chain",chainId:e.fromChain,to:o.contractAddress,data:o.data,value:e.fromAmount}),s.length===0)try{let a=new URLSearchParams({fromChain:nn(e.fromChain),toChain:nn(e.toChain),fromToken:e.fromToken,toToken:e.toToken,fromAmount:e.fromAmount,fromAddress:t,toAddress:r,slippage:"0.5"}),c=await fetch(`${this.config.apiUrl}/advanced/stepTransaction?${a}`,{headers:this.config.apiKey?{"x-lifi-api-key":this.config.apiKey}:{}});if(c.ok){let l=await c.json();l.transactionRequest&&s.push({type:"cross-chain",chainId:e.fromChain,to:l.transactionRequest.to,data:l.transactionRequest.data,value:l.transactionRequest.value})}}catch(a){throw O.warn("lifi-provider","Failed to fetch transaction params from API",a),new Error("Unable to build transaction parameters for LI.FI route")}return s}async getRouteStatus(e){try{let t={};this.config.apiKey&&(t["x-lifi-api-key"]=this.config.apiKey);let r=await fetch(`${this.config.apiUrl}/status?txHash=${e}`,{headers:t});if(!r.ok)return{status:"pending"};let s=await r.json(),o=s.status??"pending";return{status:this.mapLiFiStatus(o),toTxHash:s.receiving?.txHash,currentStep:o}}catch{return{status:"pending"}}}supportsChainPair(e,t){return po.has(e)&&po.has(t)}supportsToken(e,t){let r=go[e];if(!r)return!1;if(t.startsWith("0x")&&t.length===42){let s=t.toLowerCase();return Object.values(r).some(o=>o.toLowerCase()===s)}return Object.keys(r).some(s=>s.toUpperCase()===t.toUpperCase())}mapLiFiStatus(e){switch(e){case"DONE":case"COMPLETED":return"completed";case"FAILED":return"failed";case"BRIDGE":case"RECEIVED":return"bridging";default:return"pending"}}};Tt();var Q=class extends Error{code;details;constructor(e,t,r){super(t??e),this.name="ChainAbstractionError",this.code=e,this.details=r}};function lc(n,e){if(!n||typeof n!="object")return!1;let t=n;return t.name!=="ChainAbstractionError"||typeof t.code!="string"?!1:e?t.code===e:!0}var dc=3e4,uc=2e3,fc=.5,yo={"eip155:1":"ETH","eip155:10":"ETH","eip155:42161":"ETH","eip155:8453":"ETH","eip155:137":"MATIC","eip155:43114":"AVAX","eip155:56":"BNB","eip155:250":"FTM","eip155:324":"ETH","eip155:59144":"ETH","eip155:534352":"ETH","eip155:100":"xDai","eip155:1101":"ETH"},xo={"eip155:1":18,"eip155:10":18,"eip155:42161":18,"eip155:8453":18,"eip155:137":18,"eip155:43114":18,"eip155:56":18,"eip155:250":18,"eip155:324":18,"eip155:59144":18,"eip155:534352":18,"eip155:100":18,"eip155:1101":18},on=class{providers=new Map;config;quoteCache=new Map;routeStore=new Map;constructor(e){this.config={quoteCacheTtl:e?.quoteCacheTtl??dc,statusPollInterval:e?.statusPollInterval??uc,defaultSlippage:e?.defaultSlippage??fc,backendUrl:e?.backendUrl,lifiApiKey:e?.lifiApiKey,axelarConfig:e?.axelarConfig}}registerProvider(e){this.providers.has(e.id)&&O.warn("route-engine",`Overwriting existing provider: ${e.id}`),this.providers.set(e.id,e),O.debug("route-engine",`Registered provider: ${e.id}`)}unregisterProvider(e){this.providers.delete(e)}getProvider(e){return this.providers.get(e)}listProviders(){return Array.from(this.providers.values())}async getQuote(e,t,r,s,o){if(BigInt(s)<=0n)throw new Q("invalid_config","Amount must be positive");let i=this.buildCacheKey(e,t,r,s),a=this.quoteCache.get(i);if(a&&Date.now()-a.cachedAt<this.config.quoteCacheTtl)return O.debug("route-engine","Returning cached quotes"),this.formatAndSortQuotes(a.routes,o);let c=[],l=[],u=this.getActiveProviders(e,t,r,o);if(u.length===0)throw new Q("no_routes_available",`No providers available for chain pair ${e} \u2192 ${t} with token ${r}`);let p=await Promise.allSettled(u.map(d=>d.getRoutes(e,t,r,r,s).catch(f=>(l.push({provider:d.id,error:f.message}),[]))));for(let d of p)d.status==="fulfilled"&&c.push(...d.value);if(c.length===0)throw l.length>0?new Q("no_routes_available",`No routes found from ${e} to ${t}. Provider errors: ${l.map(d=>`${d.provider}: ${d.error}`).join("; ")}`,{errors:l}):new Q("no_routes_available",`No routes available from ${e} to ${t} for token ${r}`);for(let d of c)this.routeStore.set(d.id,d);return this.quoteCache.set(i,{routes:c,cachedAt:Date.now(),fromChain:e,toChain:t,fromToken:r,toToken:r,amount:s}),this.cleanCache(),this.formatAndSortQuotes(c,o)}async executeRoute(e,t,r){if(Date.now()>e.expiresAt)throw new Q("route_expired","This quote has expired. Please fetch a new quote.");let s=this.routeStore.get(e.routeId);if(!s)throw new Q("no_routes_available",`Route ${e.routeId} not found. It may have expired.`);let o=this.providers.get(e.provider);if(!o)throw new Q("provider_unavailable",`Provider ${e.provider} is not registered`);let i=r?.recipient??t;try{let a=await o.getTransactionParams(s,"sender",i),c=a.find(u=>u.type==="approve");if(!a.find(u=>u.type==="cross-chain"))throw new Q("execution_failed","No cross-chain transaction parameters returned by provider");if(c&&r?.autoApprove!==!1)throw new Q("approve_needed",`Token approval required for ${e.fromTokenSymbol} on ${e.fromChain}`,{approveParams:c});return{fromTxHash:"pending",fromChain:e.fromChain,toChain:e.toChain,status:"pending",bridgeReference:e.routeId,estimatedCompletionAt:Date.now()+e.estimatedArrivalSeconds*1e3}}catch(a){throw a instanceof Q?a:new Q("execution_failed",`Failed to execute route: ${a.message}`)}}async compareCosts(e,t,r){if(t.length===0)return[];let s=[],o=[],i=await Promise.allSettled(t.map(async a=>this.evaluateChainCost(a,e,r)));for(let a=0;a<i.length;a++){let c=i[a],l=t[a];c.status==="fulfilled"?s.push(c.value):o.push({chain:l,error:c.reason?.message??"Unknown error"})}if(s.length===0&&o.length>0)throw new Q("backend_unavailable",`Failed to evaluate costs for any chain: ${o.map(a=>`${a.chain}: ${a.error}`).join("; ")}`);return s.sort((a,c)=>parseFloat(a.totalCost)-parseFloat(c.totalCost))}async getRouteStatus(e){for(let[,t]of this.providers)try{return await t.getRouteStatus(e)}catch{}return{status:"pending"}}getActiveProviders(e,t,r,s){let o=Array.from(this.providers.values());if(o=o.filter(i=>i.supportsChainPair(e,t)),s?.preferredBridges&&s.preferredBridges.length>0){let i=new Set(s.preferredBridges);o=o.filter(a=>i.has(a.id))}if(s?.excludeBridges&&s.excludeBridges.length>0){let i=new Set(s.excludeBridges);o=o.filter(a=>!i.has(a.id))}return o}formatAndSortQuotes(e,t){let r=xo[e[0]?.fromChain??"eip155:1"]??18,s=xo[e[0]?.toChain??"eip155:1"]??18,o=e.map(a=>{let c=BigInt(a.toAmount),l=BigInt(a.toAmountMin),u=BigInt(a.fromAmount),p=this.config.quoteCacheTtl,d="0";if(u>0n){let S=c*10000n/u,M=S/10000n,k=S%10000n;d=`${M}.${k.toString().padStart(4,"0")}`}let f="0",h=Qe(u,r),g=Qe(c,s),w=Qe(l,s);return{routeId:a.id,provider:a.provider,fromChain:a.fromChain,toChain:a.toChain,fromTokenSymbol:this.resolveTokenSymbol(a.fromChain,a.fromToken),toTokenSymbol:this.resolveTokenSymbol(a.toChain,a.toToken),fromAmountFormatted:h,toAmountFormatted:g,toAmountMinFormatted:w,exchangeRate:d,priceImpact:f,totalGasCostUsd:a.gasCosts.totalUsd,totalFeeUsd:this.formatFeeUsd(a),netReceiveFormatted:g,estimatedArrival:this.formatEstimatedTime(a.estimatedTime),estimatedArrivalSeconds:a.estimatedTime,summary:a.summary,needsApprove:a.steps.some(S=>S.type==="approve"),expiresAt:Date.now()+p}}),i=t?.sortBy??"netReceive";return this.sortQuotes(o,i)}sortQuotes(e,t){let r=[...e];switch(t){case"fastest":r.sort((s,o)=>s.estimatedArrivalSeconds-o.estimatedArrivalSeconds);break;case"cheapest":r.sort((s,o)=>{let i=parseFloat(s.totalGasCostUsd)-parseFloat(o.totalGasCostUsd);return i!==0?i:parseFloat(s.totalFeeUsd)-parseFloat(o.totalFeeUsd)});break;default:r.sort((s,o)=>{let i=parseFloat(s.netReceiveFormatted);return parseFloat(o.netReceiveFormatted)-i});break}return r}resolveTokenSymbol(e,t){if(t==="0x0000000000000000000000000000000000000000")return yo[e]??"UNKNOWN";for(let[r,s]of Object.entries(pc))if(r===e){for(let[o,i]of Object.entries(s))if(i.toLowerCase()===t.toLowerCase())return o}return t.startsWith("0x")?t.slice(0,10):t}formatFeeUsd(e){let t=BigInt(e.fee.protocolFee),r=e.fee.integrationFee?BigInt(e.fee.integrationFee):0n,s=t+r;return s===0n?"0":Qe(s,18)}formatEstimatedTime(e){return e<60?`~${e} seconds`:e<3600?`~${Math.floor(e/60)} minutes`:`~${(e/3600).toFixed(1)} hours`}buildCacheKey(e,t,r,s){return`${e}:${t}:${r}:${s}`}cleanCache(){let e=Date.now();for(let[t,r]of this.quoteCache.entries())e-r.cachedAt>this.config.quoteCacheTtl*2&&this.quoteCache.delete(t)}async evaluateChainCost(e,t,r){let s=this.getChainName(e),o=yo[e]??"ETH",i=this.getEstimatedGasUnits(t),u=Number(i*50000000000n/1000000000000000000n).toFixed(6),p=this.getNativeTokenPriceUsd(e),d=(parseFloat(u)*p).toFixed(2),f="0";t==="cross_chain_transfer"&&r?.includeCrossChain&&(f=(.5*p).toFixed(2));let h=(parseFloat(d)+parseFloat(f)).toFixed(2);return{chain:e,chainName:s,gasCost:d,fee:f,totalCost:h,time:this.getEstimatedTime(e,t),congestionLevel:this.getCongestionLevel(e)}}getEstimatedGasUnits(e){switch(e){case"send_native":return 21000n;case"send_erc20":return 65000n;case"swap":return 150000n;case"cross_chain_transfer":return 300000n}}getEstimatedTime(e,t){let r={"eip155:1":12,"eip155:10":2,"eip155:42161":.25,"eip155:8453":2,"eip155:137":2},s=2,o=r[e]??12;return Math.round(o*s)}getChainName(e){return{"eip155:1":"Ethereum","eip155:137":"Polygon","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:8453":"Base","eip155:43114":"Avalanche","eip155:56":"BNB Chain","eip155:250":"Fantom","eip155:324":"zkSync Era","eip155:59144":"Linea","eip155:534352":"Scroll","eip155:100":"Gnosis","eip155:1101":"Polygon zkEVM"}[e]??e}getNativeTokenPriceUsd(e){return{"eip155:1":3500,"eip155:10":3500,"eip155:42161":3500,"eip155:8453":3500,"eip155:137":.7,"eip155:43114":35,"eip155:56":580,"eip155:250":.5,"eip155:324":3500,"eip155:59144":3500,"eip155:534352":3500,"eip155:100":1,"eip155:1101":3500}[e]??100}getCongestionLevel(e){return{"eip155:1":"high","eip155:10":"medium","eip155:42161":"medium","eip155:8453":"low","eip155:137":"medium"}[e]??"low"}},pc={"eip155:1":{USDC:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",USDT:"0xdAC17F958D2ee523a2206206994597C13D831ec7",DAI:"0x6B175474E89094C44Da98b954EedeAC495271d0F",WETH:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"},"eip155:137":{USDC:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",USDT:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",DAI:"0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",WMATIC:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270"},"eip155:10":{USDC:"0x7F5c764cBc14f9669B88837ca1490cCa17c31607",USDT:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",DAI:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",WETH:"0x4200000000000000000000000000000000000006"},"eip155:42161":{USDC:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",USDT:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",DAI:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",WETH:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},"eip155:8453":{USDC:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",WETH:"0x4200000000000000000000000000000000000006"}};function hc(n){return new on(n)}var Qn={1:{name:"Ethereum",caip2Id:"eip155:1",nativeCurrency:{symbol:"ETH",decimals:18},axelarName:"ethereum",usdcAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",usdtAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",entryPoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032",factoryAddress:"0x9406Cc6185a346906296840746125a0E44976454",explorerUrl:"https://etherscan.io",chainlinkEthUsdFeed:"0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"},10:{name:"Optimism",caip2Id:"eip155:10",nativeCurrency:{symbol:"ETH",decimals:18},usdcAddress:"0x7F5c764cBc14f9669B88837ca1490cCa17c31607",usdtAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",entryPoint:"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",factoryAddress:"0x9406Cc6185a346906296840746125a0E44976454",explorerUrl:"https://optimistic.etherscan.io",chainlinkEthUsdFeed:"0x13e3Ee699D1909E989722E753853AE30b17e08c5"},56:{name:"BNB Chain",caip2Id:"eip155:56",nativeCurrency:{symbol:"BNB",decimals:18},axelarName:"binance",usdcAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",usdtAddress:"0x55d398326f99059fF775485246999027B3197955",usdcDecimals:18,usdtDecimals:18,explorerUrl:"https://bscscan.com"},100:{name:"Gnosis",caip2Id:"eip155:100",nativeCurrency:{symbol:"xDAI",decimals:18},axelarName:"gnosis",usdcAddress:"0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83",usdtAddress:"0x4ECaBa5870353805a9F068101A40E0f32ed605C6",explorerUrl:"https://gnosisscan.io"},137:{name:"Polygon",caip2Id:"eip155:137",nativeCurrency:{symbol:"MATIC",decimals:18},axelarName:"polygon",usdcAddress:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",usdtAddress:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",entryPoint:"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",factoryAddress:"0x9406Cc6185a346906296840746125a0E44976454",explorerUrl:"https://polygonscan.com",chainlinkEthUsdFeed:"0xAB594600376Ec9fD91F8e885dADF0CE036862dE0"},250:{name:"Fantom",caip2Id:"eip155:250",nativeCurrency:{symbol:"FTM",decimals:18},axelarName:"fantom",usdcAddress:"0x04068DA6C83AFCFA0e13ba15A6696662335D5B75",explorerUrl:"https://ftmscan.com"},324:{name:"zkSync Era",caip2Id:"eip155:324",nativeCurrency:{symbol:"ETH",decimals:18}},1101:{name:"Polygon zkEVM",caip2Id:"eip155:1101",nativeCurrency:{symbol:"ETH",decimals:18},axelarName:"polygon-zkevm",usdcAddress:"0xA8CE8aee21bC2A48a5EF670afCc9274C7bbbC035",explorerUrl:"https://zkevm.polygonscan.com"},8453:{name:"Base",caip2Id:"eip155:8453",nativeCurrency:{symbol:"ETH",decimals:18},axelarName:"base",usdcAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",entryPoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032",factoryAddress:"0x9406Cc6185a346906296840746125a0E44976454",explorerUrl:"https://basescan.org"},42161:{name:"Arbitrum",caip2Id:"eip155:42161",nativeCurrency:{symbol:"ETH",decimals:18},axelarName:"arbitrum",usdcAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",usdtAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",entryPoint:"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",factoryAddress:"0x9406Cc6185a346906296840746125a0E44976454",explorerUrl:"https://arbiscan.io"},43114:{name:"Avalanche",caip2Id:"eip155:43114",nativeCurrency:{symbol:"AVAX",decimals:18},axelarName:"avalanche",usdcAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",explorerUrl:"https://snowtrace.io"},59144:{name:"Linea",caip2Id:"eip155:59144",nativeCurrency:{symbol:"ETH",decimals:18},usdcAddress:"0x176211869cA2b568f2A7D4EE941E073a542EEd12",explorerUrl:"https://lineascan.build"},534352:{name:"Scroll",caip2Id:"eip155:534352",nativeCurrency:{symbol:"ETH",decimals:18},usdcAddress:"0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",explorerUrl:"https://scrollscan.com"},11155111:{name:"Sepolia",caip2Id:"eip155:11155111",nativeCurrency:{symbol:"ETH",decimals:18},entryPoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032",factoryAddress:"0x9406Cc6185a346906296840746125a0E44976454",explorerUrl:"https://sepolia.etherscan.io"}};function yu(n){return Object.values(n).flatMap(e=>e.accounts)}function xu(n){let e=new Set;return Object.values(n).forEach(t=>{t.chains.forEach(r=>e.add(r))}),Array.from(e)}function bu(n){let e=new Set;return Object.values(n).forEach(t=>{t.methods.forEach(r=>e.add(r))}),Array.from(e)}function wu(n){let e=new Set;return Object.values(n).forEach(t=>{t.events.forEach(r=>e.add(r))}),Array.from(e)}var Au={SESSION_EXPIRED:"Session expired. Please reconnect your wallet.",NO_ACCOUNT_SIGNING:"No account found for signing. Please reconnect your wallet.",NO_ACCOUNT_TX:"No account found for transaction. Please reconnect your wallet.",NO_ACCOUNTS:"No accounts available. Please reconnect your wallet.",INVALID_INPUT:"Invalid input.",MISSING_TX:"Missing transaction.",MISSING_MESSAGE:"Missing message parameter.",USER_REJECTED:"Operation rejected by user.",TX_FAILED:"Transaction failed.",CHAIN_UNSUPPORTED:"Chain not supported.",METHOD_NOT_ALLOWED:"Method not allowed.",WALLET_UNAVAILABLE:"Wallet not available."},ke=class extends Error{code;details;constructor(e,t,r){super(t??e),this.name="WalletError",this.code=e,this.details=r}};function Su(n,e){if(!n||typeof n!="object")return!1;let t=n;return t.name!=="WalletError"||typeof t.code!="string"?!1:e?t.code===e:!0}function Eu(){if(typeof navigator>"u")return"desktop-web";let n=navigator.userAgent.toLowerCase();return/(iphone|ipad|ipod|android|mobile)/i.test(n)?"mobile-web":"desktop-web"}function bo(){if(typeof navigator>"u")return!1;let n=navigator.userAgent.toLowerCase();return/(iphone|ipad|ipod|android|mobile)/i.test(n)}var Jn=class{connectors=new Map;entries=new Map;activeConnectorId=null;activeSession=null;config;_connecting=!1;constructor(e={}){this.config={autoSelect:e.autoSelect??!0,preferOrder:e.preferOrder??[]}}register(e,t,r=0){this.connectors.set(e,t),this.entries.set(e,{id:e,connector:t,priority:r})}unregister(e){this.connectors.delete(e),this.entries.delete(e),this.activeConnectorId===e&&(this.activeConnectorId=null)}get(e){return this.connectors.get(e)}getActive(){if(this.activeConnectorId)return this.connectors.get(this.activeConnectorId)}getActiveSession(){return this.activeSession}list(){return Array.from(this.entries.values()).sort((e,t)=>t.priority-e.priority)}listBySupport(e){return this.list().map(t=>t.connector).filter(t=>t.supports[e])}async connect(e,t){if(this._connecting)throw new Error("Connection already in progress");this._connecting=!0;try{let r;if(e){if(r=this.connectors.get(e),!r)throw new Error(`Connector "${e}" not found`)}else if(this.config.autoSelect){if(r=this.selectBestConnector(),!r)throw new Error("No connectors available")}else throw new Error("No connector specified and autoSelect is disabled");let s=await r.connect(t);return this.activeConnectorId=r.id,this.activeSession=s,s}finally{this._connecting=!1}}async reconnect(e){if(this._connecting)throw new Error("Connection already in progress");this._connecting=!0;try{if(!e.topic)throw new Error("Reconnection not supported for this session type");let t=this.activeConnectorId??this.connectors.keys().next().value,r=t?this.get(t):null;if(r?.reconnect){let s=await r.reconnect(e);return this.activeConnectorId=t,this.activeSession=s,s}throw new Error(`Reconnection not supported by connector "${t??"unknown"}"`)}finally{this._connecting=!1}}async disconnect(){if(!this.activeConnectorId||!this.activeSession)return;let e=this.connectors.get(this.activeConnectorId);e&&await e.disconnect(this.activeSession),this.activeConnectorId=null,this.activeSession=null}async getAccounts(){if(!this.activeConnectorId||!this.activeSession)return[];let e=this.connectors.get(this.activeConnectorId);return e?e.getAccounts(this.activeSession):[]}async signMessage(e){if(!this.activeConnectorId||!this.activeSession)throw new Error("No active session");let t=this.connectors.get(this.activeConnectorId);if(!t?.signMessage)throw new Error("signMessage not supported by this connector");return t.signMessage(this.activeSession,e)}async sendTransaction(e){if(!this.activeConnectorId||!this.activeSession)throw new Error("No active session");let t=this.connectors.get(this.activeConnectorId);if(!t?.sendTransaction)throw new Error("sendTransaction not supported by this connector");return t.sendTransaction(this.activeSession,e)}async switchChain(e){if(!this.activeConnectorId||!this.activeSession)throw new Error("No active session");let t=this.connectors.get(this.activeConnectorId);if(!t?.switchChain)throw new Error("switchChain not supported by this connector");await t.switchChain(this.activeSession,e)}async request(e){let t=this.getActive();if(!t?.request)throw new ke("method_not_allowed","RPC requests not supported by active connector");return t.request(e)}async getBalance(e){let t=this.getActive();if(!t?.getBalance)throw new ke("method_not_allowed","Balance queries not supported by active connector");return t.getBalance(e)}async sendCalls(e,t,r){if(!this.activeConnectorId||!this.activeSession)throw new Error("No active session");let s=this.connectors.get(this.activeConnectorId);if(!s?.sendCalls)throw new Error("sendCalls not supported by this connector");return s.sendCalls(e,t,r)}async getCapabilities(e){if(!this.activeConnectorId||!this.activeSession)throw new Error("No active session");let t=this.connectors.get(this.activeConnectorId);if(!t?.getCapabilities)throw new Error("getCapabilities not supported by this connector");return t.getCapabilities(e)}clear(){this.connectors.clear(),this.entries.clear(),this.activeConnectorId=null,this.activeSession=null}selectBestConnector(){let e=this.list();if(this.config.preferOrder&&this.config.preferOrder.length>0)for(let r of this.config.preferOrder){let s=this.entries.get(r);if(s)return s.connector}let t=bo();for(let r of e){let s=r.connector.supports;if(t&&s.mobile||!t&&s.desktop)return r.connector}return e[0]?.connector}};function Iu(n){return new Jn(n)}var gc="eip155",mc="solana",yc="xrpl",Ru=[gc,mc,yc],xc="eip155:1",Bu="eip155:5",Uu="eip155:11155111",Du="eip155:137",Lu="eip155:80001",Ou="eip155:42161",Nu="eip155:421613",Fu="eip155:10",Hu="eip155:420",Mu="eip155:8453",bc="solana:0",$u="solana:1",Gu="solana:2",wc="xrpl:0",Ku="xrpl:1",Vu="xrpl:2",Wu=xc,ju=bc,qu=wc,zu=6e3,Yu=6001,Xu=6002,Zu={SESSION:"naculus_web3_session",POCKET:"naculus_pocket",PASSKEYS_CREDENTIAL:"naculus_passkeys_credential"},Qu=16,Ju=300*1e3,e0=30*1e3;function vc(n){return n.toString()}function Ac(n){return BigInt(n)}function Sc(n,e=9,t="gwei"){if(n===0n)return`0 ${t}`;let r=10n**BigInt(e),s=n/r,o=n%r;if(o===0n)return`${s.toString()} ${t}`;let a=o.toString().padStart(e,"0").replace(/0+$/,"");return`${s.toString()}.${a} ${t}`}var Ge=class extends Error{code;details;constructor(e,t,r){super(t??e),this.name="FeeEstimationError",this.code=e,this.details=r}};function Cc(n,e){if(!n||typeof n!="object")return!1;let t=n;return t.name!=="FeeEstimationError"||typeof t.code!="string"?!1:e?t.code===e:!0}var er={ESTIMATION_FAILED:"Fee estimation failed after all strategies exhausted.",CHAIN_NOT_SUPPORTED:"Chain not supported for fee estimation.",RPC_ERROR:"RPC call failed during fee estimation."};var ln=new Map;function Ec(n){ln.set(n.chainId,n)}function _c(n){ln.delete(n)}function Tc(){ln.clear()}async function dn(n,e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),1e4);try{let o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:e,params:t}),signal:r.signal});if(!o.ok)throw new Ge("fee_rpc_error",`RPC returned status ${o.status}`);let i=await o.json();if(i.error)throw new Ge("fee_rpc_error",i.error.message,{code:i.error.code});return i.result}finally{clearTimeout(s)}}async function an(n){let e=await dn(n,"eth_maxPriorityFeePerGas",[]);return BigInt(e)}async function cn(n){let e=await dn(n,"eth_getBlockByNumber",["latest",!1]);return e&&typeof e.baseFeePerGas=="string"?BigInt(e.baseFeePerGas):null}async function vo(n){let e=await dn(n,"eth_gasPrice",[]);return BigInt(e)}async function Pc(n){let e=await dn(n,"eth_chainId",[]);return BigInt(e)}async function Ic(n){let e=await cn(n);if(e!==null)try{let t=await an(n);return{eip1559:!0,latestBaseFee:e,recommendedPriorityFee:t}}catch{return{eip1559:!0,latestBaseFee:e}}return{eip1559:!1}}function kc(n){if(n)return ln.get(n)}function Rc(n){return n.type==="eip1559"||n.type==="legacy"?n.type:"auto"}function wo(n,e,t){let r=t.baseFeeMultiplier??2n,s=t.maxPriorityFeePerGas??e;return{type:"eip1559",maxFeePerGas:n*r+s,maxPriorityFeePerGas:s}}async function tr(n){let{rpcUrl:e,chainId:t}=n,r=kc(t);if(r)try{return await r.estimateFees(e,n)}catch(o){O.warn("fee-estimation",`Chain estimator failed for ${t}, falling back`,o)}if(Rc(n)==="eip1559"){let o=n.maxPriorityFeePerGas??await an(e),i=await cn(e);if(i===null)throw new Ge("fee_estimation_failed","EIP-1559 forced but chain does not support base fee");return wo(i,o,n)}try{let o=await an(e),i=await cn(e);if(i!==null)return wo(i,o,n);O.warn("fee-estimation","No base fee found despite priority fee support, falling back to legacy")}catch{O.debug("fee-estimation","eth_maxPriorityFeePerGas not available, using legacy")}try{return{type:"legacy",gasPrice:await vo(e)}}catch(o){throw new Ge("fee_estimation_failed",er.ESTIMATION_FAILED,{error:o})}}var nr="naculus_notif_",rr=class{id="inapp";name="In-App Toast";history=[];maxHistory;storage;onNotification;constructor(e){this.maxHistory=e?.maxHistory??200,this.storage=e?.storage,this.onNotification=e?.onNotification}getCapabilities(){return{supportsRichText:!0,supportsActionButtons:!1,supportsMedia:!1,maxLength:1/0,isBackground:!1}}isAvailable(){return!0}async healthCheck(){return!0}async send(e){let t={id:e.id,title:e.title,body:e.body,status:e.status,txHash:e.txHash,chainName:e.chainName,valueFormatted:e.valueFormatted,explorerUrl:e.explorerUrl,timestamp:e.timestamp,read:!1};this.history.push(t),this.history.length>this.maxHistory&&(this.history=this.history.slice(-this.maxHistory)),this.storage&&await this.persist(),this.onNotification?.(t)}getHistory(){return[...this.history]}markAsRead(e){let t=this.history.find(r=>r.id===e);t&&(t.read=!0)}markAllAsRead(){for(let e of this.history)e.read=!0}clear(){this.history=[],this.storage&&this.storage.removeItem(nr+"history")}get unreadCount(){return this.history.filter(e=>!e.read).length}async persist(){if(this.storage)try{await this.storage.setItem(nr+"history",this.history)}catch{}}async restore(){if(this.storage)try{let e=await this.storage.getItem(nr+"history");e&&Array.isArray(e)&&(this.history=e.slice(-this.maxHistory))}catch{}}},sr=class{id="telegram";name="Telegram";botToken;chatId;transport;constructor(e){this.botToken=e.botToken,this.chatId=e.chatId,this.transport=e.transport}getCapabilities(){return{supportsRichText:!0,supportsActionButtons:!0,supportsMedia:!1,maxLength:4096,isBackground:!0}}isAvailable(){return this.botToken.length>0}async healthCheck(){return this.isAvailable()}async send(e){let t=this.formatMessage(e);this.transport?await this.transport(e,t):console.log(`[TelegramChannel] Would send to ${this.chatId}:
3
+ ${t}`)}formatMessage(e){return[`${this.statusEmoji(e.status)} *Transaction ${e.status}*`,"",`\`${this.shortenHash(e.txHash)}\``,`Chain: ${e.chainName}`,e.valueFormatted?`Value: ${e.valueFormatted}`:"",e.confirmations?`Confirm: ${e.confirmations}`:"","",e.explorerUrl?`\u{1F517} [View on Explorer](${e.explorerUrl})`:""].filter(Boolean).join(`
4
+ `)}shortenHash(e){return e.length<=12?e:`${e.slice(0,8)}...${e.slice(-4)}`}statusEmoji(e){switch(e){case"confirmed":return"\u2705";case"failed":return"\u274C";case"pending":return"\u23F3";case"reorg":return"\u26A0\uFE0F";case"speedup":return"\u23E9";case"cancel":return"\u{1F6AB}";default:return"\u2139\uFE0F"}}},or=class{id="noop";name="No-op";getCapabilities(){return{supportsRichText:!1,supportsActionButtons:!1,supportsMedia:!1,maxLength:0,isBackground:!1}}isAvailable(){return!0}async healthCheck(){return!0}async send(e){}};var Ao=0;function So(){return Ao++,`notif_${Date.now()}_${Ao}_${Math.random().toString(36).slice(2,8)}`}var Co="naculus_notif_prefs",Eo="naculus_notif_watches",_o="naculus_notif_mute_rules",Bc={channels:["inapp"],frequency:"final-only",confirmInterval:6,pendingTimeout:300},ir=class{channels=new Map;watches=new Map;preferences=new Map;muteRules=new Map;statusCallbacks=new Map;defaultPreferences;storage;constructor(e){this.defaultPreferences={...Bc,...e?.defaultPreferences},this.storage=e?.storage}registerChannel(e){this.channels.set(e.id,e)}unregisterChannel(e){this.channels.delete(e)}getChannel(e){return this.channels.get(e)}getActiveChannels(){return Array.from(this.channels.values()).filter(e=>e.isAvailable()).map(e=>e.id)}watchTx(e,t,r){let s=r?.userId??"default",o=this.getPreferences(s),i={txHash:e,userId:s,channels:r?.channels??o.channels,frequency:r?.frequency??o.frequency,confirmInterval:o.confirmInterval,txMetadata:{chainId:t,value:r?.txMetadata?.value,to:r?.txMetadata?.to,txType:r?.txMetadata?.txType??"custom"},createdAt:Date.now()};this.watches.set(e,i),this.persistWatches()}unregisterTxWatch(e){let t=this.watches.get(e);t&&(t.resolvedAt=Date.now()),this.watches.delete(e),this.statusCallbacks.delete(e),this.persistWatches()}getWatch(e){return this.watches.get(e)}getAllWatches(){return Array.from(this.watches.values())}onTxStatus(e,t){return this.statusCallbacks.has(e)||this.statusCallbacks.set(e,new Set),this.statusCallbacks.get(e).add(t),()=>{this.statusCallbacks.get(e)?.delete(t)}}async handleTxStatus(e,t,r){let s=this.watches.get(e);if(!s)return;let o=this.getMuteRules(s.userId);if(this.isMuted(s.txMetadata,o))return;if(this.shouldNotify(s.frequency,t,r?.confirmations)){let c=this.buildPayload(s,t,r);await this.dispatchToChannels(c,s.channels)}let a=this.statusCallbacks.get(e);if(a){let c=r?{confirmations:r.confirmations,value:r.value,gasUsed:r.gasUsed}:void 0;for(let l of a)try{l(t,c)}catch{}}(t==="confirmed"||t==="failed")&&this.unregisterTxWatch(e)}async notify(e,t){let r={...e,id:So(),timestamp:Date.now()},s=t??this.getActiveChannels();await this.dispatchToChannels(r,s)}setPreferences(e,t){let r=this.preferences.get(e)??{...this.defaultPreferences};this.preferences.set(e,{...r,...t}),this.persistPreferences()}getPreferences(e){return{...this.preferences.get(e)??this.defaultPreferences}}getDefaultPreferences(){return{...this.defaultPreferences}}addMuteRule(e,t){let r=this.muteRules.get(e)??[];r.push(t),this.muteRules.set(e,r),this.persistMuteRules()}removeMuteRule(e,t){let r=this.muteRules.get(e);r&&(this.muteRules.set(e,r.filter(s=>s.id!==t)),this.persistMuteRules())}getMuteRules(e){return[...this.muteRules.get(e)??[]]}isMuted(e,t){let r=Date.now();for(let s of t)if(!(s.until&&s.until<=r)&&!(s.chainId&&s.chainId!==e.chainId)&&!(s.txType&&s.txType!==e.txType)){if(s.minValueUsd!==void 0&&e.value!==void 0&&e.value===BigInt(0))return!0;if(s.contractAddress&&e.to){if(s.contractAddress.toLowerCase()===e.to.toLowerCase())return!0;continue}return!0}return!1}async restore(){if(!this.storage)return;let e=await this.storage.getItem(Co);if(e)for(let[s,o]of Object.entries(e))this.preferences.set(s,o);let t=await this.storage.getItem(Eo);if(t)for(let s of t)s.resolvedAt||this.watches.set(s.txHash,s);let r=await this.storage.getItem(_o);if(r)for(let[s,o]of Object.entries(r))this.muteRules.set(s,o)}async persistPreferences(){if(!this.storage)return;let e={};for(let[t,r]of this.preferences)e[t]=r;await this.storage.setItem(Co,e)}async persistWatches(){this.storage&&await this.storage.setItem(Eo,this.getAllWatches())}async persistMuteRules(){if(!this.storage)return;let e={};for(let[t,r]of this.muteRules)e[t]=r;await this.storage.setItem(_o,e)}shouldNotify(e,t,r){return e==="muted"?!1:t==="confirmed"||t==="failed"||t==="reorg"||t==="speedup"||t==="cancel"?!0:t==="pending"?e==="per-tx":!1}buildPayload(e,t,r){let o={pending:{title:"Transaction Pending",body:"Your transaction has been broadcast and is waiting for confirmation."},confirmed:{title:"Transaction Confirmed",body:"Your transaction has been confirmed on-chain."},failed:{title:"Transaction Failed",body:"The transaction reverted or failed. Check the block explorer for details."},reorg:{title:"Chain Reorg Detected",body:"A chain reorganization affected your transaction."},speedup:{title:"Transaction Accelerated",body:"Your transaction has been sped up with a higher gas price."},cancel:{title:"Transaction Cancelled",body:"Your transaction has been cancelled."}}[t]??{title:t,body:""};return{id:So(),userId:e.userId,txHash:e.txHash,chainId:e.txMetadata.chainId,chainName:e.txMetadata.chainId,status:t,title:o.title,body:o.body,value:r?.value??e.txMetadata.value,gasUsed:r?.gasUsed,gasCostUsd:r?.gasCostUsd,confirmations:r?.confirmations,timestamp:Date.now()}}async dispatchToChannels(e,t){let r=await Promise.allSettled(t.map(async s=>{let o=this.channels.get(s);!o||!o.isAvailable()||await o.send(e)}));for(let s of r)s.status==="rejected"&&console.error("[Notifier] Channel dispatch failed:",s.reason)}};async function m0(n){try{let e=await n.request({method:"wallet_getPermissions"});return e?.length>0?e:null}catch{return null}}async function y0(n){return await n.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]})}function x0(n){let e=n.find(r=>r.parentCapability==="eth_accounts");if(!e)return[];let t=e.caveats?.find(r=>r.type==="restrictReturnedAccounts");return t&&Array.isArray(t.value)?t.value:[]}function b0(n,e){return n?n.some(t=>t.parentCapability===e):!1}var be={"eip155:1":"https://eth.llamarpc.com","eip155:5":"https://goerli.llamarpc.com","eip155:11155111":"https://sepolia.llamarpc.com","eip155:137":"https://polygon.llamarpc.com","eip155:10":"https://optimism.llamarpc.com","eip155:42161":"https://arbitrum.llamarpc.com","eip155:8453":"https://base.llamarpc.com","solana:0":"https://api.mainnet-beta.solana.com","solana:1":"https://api.devnet.solana.com","solana:2":"https://api.testnet.solana.com"};function v0(n,e){return be[n]??e}Jt();te();var q=class extends Error{code;constructor(e,t,r){super(t),this.name="ResolutionError",this.code=e,r instanceof Error&&(this.cause=r)}},Pt=class{cache=new Map;ttlMs;constructor(e=3e5){this.ttlMs=e}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}set(e,t){this.cache.set(e,{value:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}prune(){let e=Date.now();for(let[t,r]of this.cache)e>r.expiresAt&&this.cache.delete(t)}};var Uc=new TextEncoder;function lr(n){return Uc.encode(n)}var Dc="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";var Lc=[{name:"resolver",type:"function",inputs:[{name:"node",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"owner",type:"function",inputs:[{name:"node",type:"bytes32"}],outputs:[{name:"",type:"address"}]}],To=[{name:"addr",type:"function",inputs:[{name:"node",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"name",type:"function",inputs:[{name:"node",type:"bytes32"}],outputs:[{name:"",type:"string"}]}],T0=`0x${"00".repeat(20)}`;function Po(n){let e=new Uint8Array(32).fill(0);if(n){let t=n.split(".");for(let r=t.length-1;r>=0;r--){let s=Et(lr(t[r].toLowerCase()));e=Et(z(e,s))}}return`0x${D(e)}`}function ar(n,e,t){let r=n.find(l=>l.name===e);if(!r)throw new Error(`Function ${e} not found in ABI`);let s=r.inputs.map(l=>l.type).join(","),o=`${e}(${s})`,i=Et(lr(o)).slice(0,4),a=t.map(l=>{if(typeof l=="string"&&l.startsWith("0x")){let w=l.slice(2).padStart(64,"0");return $(w)}let u=lr(l),p=new Uint8Array(32),d=new Uint8Array(32);new DataView(d.buffer).setBigUint64(24,BigInt(u.length),!1);let h=Math.ceil(u.length/32)*32,g=new Uint8Array(h);return g.set(u),z(p,d,g)}),c=z(i,...a);return`0x${D(c)}`}function Io(n){let e=$(n.slice(2));if(e.length<32)throw new q("INVALID_ADDRESS","Invalid response length for address decode");let t=e.slice(12,32);return`0x${D(t)}`}function Oc(n){let e=$(n.slice(2));if(e.length<32)throw new q("INVALID_ADDRESS","Invalid response for string decode");let t=e.slice(32,64),r=Number(new DataView(t.buffer).getBigUint64(24,!1)),s=e.slice(64,64+r);return new TextDecoder().decode(s)}async function cr(n,e){let t=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[e,"latest"]})});if(!t.ok)throw new q("PROVIDER_UNAVAILABLE",`ENS RPC call failed: ${t.status} ${t.statusText}`);let r=await t.json();if(r.error)throw new q("NAME_NOT_FOUND",`ENS lookup failed: ${r.error.message}`);return r.result??"0x"}var It=class{chainType="eip155";rpcUrl;constructor(e){this.rpcUrl=e}supportsName(e){return e.toLowerCase().endsWith(".eth")}async resolveName(e){let t=e.toLowerCase();if(!t.endsWith(".eth"))return null;let r=Po(t),s=await this.getResolver(r);if(!s||s==="0x0000000000000000000000000000000000000000")return null;let o=ar(To,"addr",[r]),i=await cr(this.rpcUrl,{to:s,data:o});return!i||i==="0x"||i==="0x0000000000000000000000000000000000000000000000000000000000000000"?null:{address:Io(i),chainType:"eip155",name:t}}async lookupAddress(e){let t=e.startsWith("0x")?e.toLowerCase():`0x${e.toLowerCase()}`,r=Po(`${t.slice(2).toLowerCase()}.addr.reverse`),s=await this.getResolver(r);if(!s||s==="0x0000000000000000000000000000000000000000")return null;let o=ar(To,"name",[r]),i=await cr(this.rpcUrl,{to:s,data:o});if(!i||i==="0x")return null;try{let a=Oc(i);return a?{name:a,chainType:"eip155",isPrimary:!0}:null}catch{return null}}async getResolver(e){let t=ar(Lc,"resolver",[e]);try{let r=await cr(this.rpcUrl,{to:Dc,data:t});return!r||r==="0x"?null:Io(r)}catch{return null}}};te();function Nc(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);let s=BigInt(32),o=BigInt(4294967295),i=Number(t>>s&o),a=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,i,r),n.setUint32(e+l,a,r)}function ko(n,e,t){return n&e^~n&t}function Ro(n,e,t){return n&e^n&t^e&t}var un=class extends Pe{constructor(e,t,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Xe(this.buffer)}update(e){me(this),e=ye(e),Z(e);let{view:t,buffer:r,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=Xe(e);for(;s<=o-i;i+=s)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){me(this),At(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,ie(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let p=i;p<s;p++)t[p]=0;Nc(r,s-8,BigInt(this.length*8),o),this.process(r,0);let a=Xe(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,u[p],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Re=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);te();var Fc=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ke=new Uint32Array(64),fn=class extends un{constructor(e=32){super(64,e,8,!1),this.A=Re[0]|0,this.B=Re[1]|0,this.C=Re[2]|0,this.D=Re[3]|0,this.E=Re[4]|0,this.F=Re[5]|0,this.G=Re[6]|0,this.H=Re[7]|0}get(){let{A:e,B:t,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,r,s,o,i,a,c]}set(e,t,r,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let p=0;p<16;p++,t+=4)Ke[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let d=Ke[p-15],f=Ke[p-2],h=de(d,7)^de(d,18)^d>>>3,g=de(f,17)^de(f,19)^f>>>10;Ke[p]=g+Ke[p-7]+h+Ke[p-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let p=0;p<64;p++){let d=de(a,6)^de(a,11)^de(a,25),f=u+d+ko(a,c,l)+Fc[p]+Ke[p]|0,g=(de(r,2)^de(r,13)^de(r,22))+Ro(r,s,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=s,s=r,r=f+g|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,s,o,i,a,c,l,u)}roundClean(){ie(Ke)}destroy(){this.set(0,0,0,0,0,0,0,0),ie(this.buffer)}};var pn=ct(()=>new fn);var we=pn;te();var Hc=new TextEncoder;function Bo(n){return Hc.encode(n)}var Mc="namesLPneVptA9Z5rqUDD9tMTWEJwofgaYwp8cawRkX",$c="58P1RCHjMiN1eS6LGpmmNvbTYGWCoh2vMGN4JmSScWdT",Gc="name_record";var Uo="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",dr=BigInt(58);function ur(n){let e=BigInt(0);for(let a of n){let c=Uo.indexOf(a);if(c===-1)throw new Error(`Invalid Base58 character: ${a}`);e=e*dr+BigInt(c)}let t=e.toString(16),r=t.length%2===0?t:`0${t}`,s=$(r),o=n.match(/^1*/)?.[0]?.length??0,i=new Uint8Array(o+s.length);return i.set(s,o),i}function Kc(n,e){for(let t=255;t>=0;t--){let r=z(...n,new Uint8Array([t]),e),s=we(r);if(!(s[31]&128))return[s,t]}throw new Error("Unable to find a valid bump seed")}function Vc(n){let e=ur(n),t={tag:e[0],parentName:D(e.slice(1,33)),owner:D(e.slice(33,65)),class:D(e.slice(65,97))},r=e.slice(97);return{header:t,content:D(r),rawBytes:e.length}}async function Wc(n,e){let t=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"getAccountInfo",params:[e,{encoding:"base58",commitment:"confirmed"}]})});if(!t.ok)throw new q("PROVIDER_UNAVAILABLE",`SNS RPC call failed: ${t.status} ${t.statusText}`);let r=await t.json();if(r.error)throw new q("NAME_NOT_FOUND",`SNS lookup failed: ${r.error.message}`);return r.result?.value??null}function jc(n){let e=ur($c),t=Bo(n.toLowerCase().replace(".sol","")),r=ur(Mc),s=[Bo(Gc),e,t],[o]=Kc(s,r);return D(o)}var kt=class{chainType="solana";rpcUrl;constructor(e){this.rpcUrl=e}supportsName(e){return e.toLowerCase().endsWith(".sol")}async resolveName(e){let t=e.toLowerCase().trim();if(!t.endsWith(".sol"))return null;let r=jc(t);try{let s=await Wc(this.rpcUrl,r.length===64?r:`0x${r}`);if(!s||!s.data||s.data.length===0)return null;let o=s.data[0],a=Vc(o).header.owner;return!a||a==="0000000000000000000000000000000000000000000000000000000000000000"?null:{address:this.hexToBase58(a),chainType:"solana",name:t}}catch(s){if(s instanceof q)throw s;return null}}async lookupAddress(e){return null}hexToBase58(e){let t=e.replace(/^0x/,"").padStart(64,"0"),r=$(t.slice(0,64)),s=BigInt(0);for(let a=0;a<r.length;a++)s=s*BigInt(256)+BigInt(r[a]);if(s===BigInt(0))return"11111111111111111111111111111111";let o=[];for(;s>BigInt(0);){let a=Number(s%dr);o.push(Uo[a]),s=s/dr}let i=0;for(let a of r)if(a===0)i++;else break;return"1".repeat(i)+o.reverse().join("")}};function qc(){return be["eip155:1"]??"https://eth.llamarpc.com"}function zc(){return be["solana:0"]??"https://api.mainnet-beta.solana.com"}function Yc(n){let e=n.toLowerCase().trim();return e.endsWith(".eth")?".eth":e.endsWith(".sol")?".sol":null}function Xc(n,e){let t=n.toLowerCase().trim().slice(0,-e.length);return!(!t||t.length<1||t.length>255||e===".eth"&&(!/^[a-z0-9]/.test(t)||/--/.test(t))||e===".sol"&&!/^[a-z0-9]/.test(t))}var fr=class{providers=new Map;cache;timeoutMs;constructor(e){this.cache=new Pt(e?.cache?.ttlMs??3e5),this.timeoutMs=e?.timeoutMs??1e4;let t=e?.providers?.ens?.rpcUrl??qc();this.registerProvider(new It(t));let r=e?.providers?.sns?.rpcUrl??zc();this.registerProvider(new kt(r))}registerProvider(e){this.providers.set(e.chainType,e)}async resolveName(e){let t=e.trim();if(!t)throw new q("INVALID_NAME","Name cannot be empty");let r=`resolve:${t.toLowerCase()}`,s=this.cache.get(r);if(s!==null)return s;let o=Yc(t);if(!o)throw new q("UNSUPPORTED_NAME_SERVICE",`Unsupported name service for "${t}". Supported suffixes: .eth, .sol`);if(!Xc(t,o))throw new q("INVALID_NAME",`Invalid name format: "${t}"`);let i=this.findProviderForName(t);if(!i)throw new q("UNSUPPORTED_NAME_SERVICE",`No provider found for name: "${t}"`);let a=await this.withTimeout(i.resolveName(t),"resolveName");return a&&this.cache.set(r,a),a}async lookupAddress(e,t){if(!e)throw new q("INVALID_ADDRESS","Address cannot be empty");let r=e.trim(),s=this.detectChainType(r,t),o=`lookup:${r.toLowerCase()}:${s}`,i=this.cache.get(o);if(i!==null)return i;let a=this.providers.get(s);if(!a)return null;let c=await this.withTimeout(a.lookupAddress(r),"lookupAddress");return c&&this.cache.set(o,c),c}async resolveNames(e){let t=new Map,r=[];return await Promise.allSettled(e.map(async s=>{try{let o=await this.resolveName(s);t.set(s,o)}catch(o){r.push({name:s,error:o instanceof Error?o:new Error(String(o))})}})),t}clearCache(){this.cache.clear()}findProviderForName(e){for(let t of this.providers.values())if(t.supportsName(e))return t}detectChainType(e,t){if(t){let r=t.split(":")[0];if(r==="eip155")return"eip155";if(r==="solana")return"solana";if(r==="xrpl")return"xrpl"}return/^0x[a-fA-F0-9]{40}$/.test(e)?"eip155":/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e)?"solana":"eip155"}async withTimeout(e,t){return Promise.race([e,new Promise((r,s)=>setTimeout(()=>s(new q("RESOLUTION_TIMEOUT",`${t} timed out after ${this.timeoutMs}ms`)),this.timeoutMs))])}};var he=class extends Error{constructor(t,r="unknown",s){super(t);this.code=r;this.name="StorageError",s&&(this.cause=s)}code};function Do(n){if(typeof globalThis<"u"&&n in globalThis){let e=globalThis[n];if(e!=null&&typeof e.getItem=="function")return e}return null}function Lo(n){if(typeof window>"u"){try{let e=Do("localStorage");if(e){let t="__storage_test__";return e.setItem(t,t),e.removeItem(t),!0}}catch{return!1}return!1}try{let e=n==="local"?window.localStorage:window.sessionStorage,t="__storage_test__";return e.setItem(t,t),e.removeItem(t),!0}catch{return!1}}function Zc(){return typeof window<"u"&&window.localStorage?window.localStorage:Do("localStorage")}var Je=class{prefix;_available=null;constructor(e=""){this.prefix=e}getKey(e){return`${this.prefix}${e}`}getStorage(){return Zc()}isAvailable(){return this._available===null&&(this._available=Lo("local")),this._available}async get(e){if(!this.isAvailable())return null;try{let t=this.getStorage();if(!t)return null;let r=t.getItem(this.getKey(e));return r===null?null:JSON.parse(r)}catch(t){throw new he(`Failed to parse storage item: ${e}`,"parse_error",t)}}async set(e,t){if(!this.isAvailable())throw new he("LocalStorage is not available","not_available");try{let r=this.getStorage();if(!r)throw new he("LocalStorage is not available","not_available");r.setItem(this.getKey(e),JSON.stringify(t))}catch(r){throw r instanceof DOMException&&r.name==="QuotaExceededError"?new he(`Storage quota exceeded for key: ${e}`,"quota_exceeded",r):new he(`Failed to set storage item: ${e}`,"unknown",r)}}async remove(e){if(!this.isAvailable())return;let t=this.getStorage();t&&t.removeItem(this.getKey(e))}async clear(){if(!this.isAvailable())return;let e=this.getStorage();if(!e)return;let t=this.prefix||"";if(!t){e.clear();return}let r=Object.keys(e);for(let s of r)s.startsWith(t)&&e.removeItem(s)}async has(e){return this.isAvailable()?await this.get(e)!==null:!1}},pr=class{prefix;_available=null;constructor(e=""){this.prefix=e}getKey(e){return`${this.prefix}${e}`}isAvailable(){return this._available===null&&(this._available=Lo("session")),this._available}async get(e){if(!this.isAvailable())return null;try{let t=window.sessionStorage.getItem(this.getKey(e));return t===null?null:JSON.parse(t)}catch(t){throw new he(`Failed to parse storage item: ${e}`,"parse_error",t)}}async set(e,t){if(!this.isAvailable())throw new he("SessionStorage is not available","not_available");try{window.sessionStorage.setItem(this.getKey(e),JSON.stringify(t))}catch(r){throw r instanceof DOMException&&r.name==="QuotaExceededError"?new he(`Storage quota exceeded for key: ${e}`,"quota_exceeded",r):new he(`Failed to set storage item: ${e}`,"unknown",r)}}async remove(e){this.isAvailable()&&window.sessionStorage.removeItem(this.getKey(e))}async clear(){if(!this.isAvailable())return;let e=this.prefix||"";if(!e){window.sessionStorage.clear();return}let t=Object.keys(window.sessionStorage);for(let r of t)r.startsWith(e)&&window.sessionStorage.removeItem(r)}async has(e){return this.isAvailable()?await this.get(e)!==null:!1}},et=class{store=new Map;isAvailable(){return!0}async get(e){let t=this.store.get(e);if(t===void 0)return null;if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}async set(e,t){this.store.set(e,typeof t=="object"?JSON.stringify(t):t)}async remove(e){this.store.delete(e)}async clear(){this.store.clear()}async has(e){return this.store.has(e)}},hr=class{isAvailable(){return!1}async get(e){return null}async set(e,t){}async remove(e){}async clear(){}async has(e){return!1}};function lt(n,e=""){switch(n){case"local":return new Je(e);case"session":return new pr(e);case"memory":return new et;default:return new hr}}function sf(n){let e=new Date().toISOString();return{id:n.id,topic:n.topic,walletId:n.walletId,walletType:n.walletType,namespaces:n.namespaces,platform:n.platform,auth:n.auth,createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}function of(n,e){return{...n,...e,updatedAt:e.updatedAt??new Date().toISOString()}}function No(n,e){return n.auth?.expiresAt?new Date(n.auth.expiresAt).getTime()<=e.getTime():!1}var Oo=class{adapter;innerKey;constructor(e="naculus_web3_session"){this.innerKey="session",this.adapter=new Je(e+":")}isAvailable(){return this.adapter.isAvailable()}async load(){if(!this.adapter.isAvailable())return null;try{return await this.adapter.get(this.innerKey)}catch{return null}}async save(e){if(this.adapter.isAvailable())try{await this.adapter.set(this.innerKey,e)}catch(t){O.warn("core/session","Failed to save session:",t)}}async clear(){this.adapter.isAvailable()&&await this.adapter.remove(this.innerKey)}};var Fo={session_key_not_found:"Session key not found. Check the session ID or create a new one.",session_key_expired:"Session key has expired. Please create a new session key.",session_key_revoked:"Session key has been revoked. Please create a new session key.",session_key_scope_exceeded:"Transaction exceeds the session key's permitted scope.",session_key_method_forbidden:"The requested method is forbidden for session keys.",session_key_contract_not_allowed:"The target contract is not in the session key's allowed list.",session_key_chain_not_allowed:"The target chain is not in the session key's allowed list.",session_key_storage_unavailable:"Session key storage is not available in this environment.",session_key_encryption_failed:"Failed to encrypt/decrypt session key data.",session_key_required_fields_missing:"Required session key fields are missing.",session_key_max_tx_count_exceeded:"Maximum transaction count for this session key has been reached.",session_key_value_limit_exceeded:"Transaction value exceeds the session key's remaining allowance.",session_key_gas_limit_exceeded:"Gas limit exceeds the session key's allowance."};function ae(n,e){return new ke(n,Fo[n],e)}te();var hn=class extends Pe{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ye(e);let r=ye(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),ie(o)}update(e){return me(this),this.iHash.update(e),this}digestInto(e){me(this),Z(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ve=(n,e,t)=>new hn(n,e).update(t).digest();ve.create=(n,e)=>new hn(n,e);te();te();te();var yr=BigInt(0),mr=BigInt(1);function Rt(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function Ve(n,e,t=""){let r=Fe(n),s=n?.length,o=e!==void 0;if(!r||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=r?`length=${s}`:`type=${typeof n}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return n}function Bt(n){let e=n.toString(16);return e.length&1?"0"+e:e}function Ho(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?yr:BigInt("0x"+n)}function dt(n){return Ho(D(n))}function xr(n){return Z(n),Ho(D(Uint8Array.from(n).reverse()))}function gn(n,e){return $(n.toString(16).padStart(e*2,"0"))}function br(n,e){return gn(n,e).reverse()}function J(n,e,t){let r;if(typeof e=="string")try{r=$(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(Fe(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");let s=r.length;if(typeof t=="number"&&s!==t)throw new Error(n+" of length "+t+" expected, got "+s);return r}var gr=n=>typeof n=="bigint"&&yr<=n;function Mo(n,e,t){return gr(n)&&gr(e)&&gr(t)&&e<=n&&n<t}function $o(n,e,t,r){if(!Mo(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function mn(n){let e;for(e=0;n>yr;n>>=mr,e+=1);return e}var We=n=>(mr<<BigInt(n))-mr;function Go(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=f=>new Uint8Array(f),s=f=>Uint8Array.of(f),o=r(n),i=r(n),a=0,c=()=>{o.fill(1),i.fill(0),a=0},l=(...f)=>t(i,o,...f),u=(f=r(0))=>{i=l(s(0),f),o=l(),f.length!==0&&(i=l(s(1),f),o=l())},p=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<e;){o=l();let g=o.slice();h.push(g),f+=o.length}return z(...h)};return(f,h)=>{c(),u(f);let g;for(;!(g=h(p()));)u();return c(),g}}function Ut(n,e,t={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(s,o,i){let a=n[s];if(i&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([s,o])=>r(s,o,!1)),Object.entries(t).forEach(([s,o])=>r(s,o,!0))}function wr(n){let e=new WeakMap;return(t,...r)=>{let s=e.get(t);if(s!==void 0)return s;let o=n(t,...r);return e.set(t,o),o}}var ne=BigInt(0),ee=BigInt(1),tt=BigInt(2),Wo=BigInt(3),jo=BigInt(4),qo=BigInt(5),Qc=BigInt(7),zo=BigInt(8),Jc=BigInt(9),Yo=BigInt(16);function ue(n,e){let t=n%e;return t>=ne?t:e+t}function ce(n,e,t){let r=n;for(;e-- >ne;)r*=r,r%=t;return r}function Ko(n,e){if(n===ne)throw new Error("invert: expected non-zero number");if(e<=ne)throw new Error("invert: expected positive modulus, got "+e);let t=ue(n,e),r=e,s=ne,o=ee,i=ee,a=ne;for(;t!==ne;){let l=r/t,u=r%t,p=s-i*l,d=o-a*l;r=t,t=u,s=i,o=a,i=p,a=d}if(r!==ee)throw new Error("invert: does not exist");return ue(s,e)}function vr(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Xo(n,e){let t=(n.ORDER+ee)/jo,r=n.pow(e,t);return vr(n,r,e),r}function el(n,e){let t=(n.ORDER-qo)/zo,r=n.mul(e,tt),s=n.pow(r,t),o=n.mul(e,s),i=n.mul(n.mul(o,tt),s),a=n.mul(o,n.sub(i,n.ONE));return vr(n,a,e),a}function tl(n){let e=je(n),t=Zo(n),r=t(e,e.neg(e.ONE)),s=t(e,r),o=t(e,e.neg(r)),i=(n+Qc)/Yo;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,r),p=a.mul(l,s),d=a.mul(l,o),f=a.eql(a.sqr(u),c),h=a.eql(a.sqr(p),c);l=a.cmov(l,u,f),u=a.cmov(d,p,h);let g=a.eql(a.sqr(u),c),w=a.cmov(l,u,g);return vr(a,w,c),w}}function Zo(n){if(n<Wo)throw new Error("sqrt is not defined for small field");let e=n-ee,t=0;for(;e%tt===ne;)e/=tt,t++;let r=tt,s=je(n);for(;Vo(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Xo;let o=s.pow(r,e),i=(e+ee)/tt;return function(c,l){if(c.is0(l))return l;if(Vo(c,l)!==1)throw new Error("Cannot find square root");let u=t,p=c.mul(c.ONE,o),d=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let h=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(h++,g=c.sqr(g),h===u)throw new Error("Cannot find square root");let w=ee<<BigInt(u-h-1),S=c.pow(p,w);u=h,p=c.sqr(S),d=c.mul(d,p),f=c.mul(f,S)}return f}}function nl(n){return n%jo===Wo?Xo:n%zo===qo?el:n%Yo===Jc?tl(n):Zo(n)}var rl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ar(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=rl.reduce((r,s)=>(r[s]="function",r),e);return Ut(n,t),n}function sl(n,e,t){if(t<ne)throw new Error("invalid exponent, negatives unsupported");if(t===ne)return n.ONE;if(t===ee)return e;let r=n.ONE,s=e;for(;t>ne;)t&ee&&(r=n.mul(r,s)),s=n.sqr(s),t>>=ee;return r}function yn(n,e,t=!1){let r=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((i,a,c)=>n.is0(a)?i:(r[c]=i,n.mul(i,a)),n.ONE),o=n.inv(s);return e.reduceRight((i,a,c)=>n.is0(a)?i:(r[c]=n.mul(i,r[c]),n.mul(i,a)),o),r}function Vo(n,e){let t=(n.ORDER-ee)/tt,r=n.pow(e,t),s=n.eql(r,n.ONE),o=n.eql(r,n.ZERO),i=n.eql(r,n.neg(n.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function xn(n,e){e!==void 0&&oe(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function je(n,e,t=!1,r={}){if(n<=ne)throw new Error("invalid field: expected ORDER > 0, got "+n);let s,o,i=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(s=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(s=e),r.sqrt&&(o=r.sqrt);let{nBitLength:c,nByteLength:l}=xn(n,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,p=Object.freeze({ORDER:n,isLE:t,BITS:c,BYTES:l,MASK:We(c),ZERO:ne,ONE:ee,allowedLengths:a,create:d=>ue(d,n),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return ne<=d&&d<n},is0:d=>d===ne,isValidNot0:d=>!p.is0(d)&&p.isValid(d),isOdd:d=>(d&ee)===ee,neg:d=>ue(-d,n),eql:(d,f)=>d===f,sqr:d=>ue(d*d,n),add:(d,f)=>ue(d+f,n),sub:(d,f)=>ue(d-f,n),mul:(d,f)=>ue(d*f,n),pow:(d,f)=>sl(p,d,f),div:(d,f)=>ue(d*Ko(f,n),n),sqrN:d=>d*d,addN:(d,f)=>d+f,subN:(d,f)=>d-f,mulN:(d,f)=>d*f,inv:d=>Ko(d,n),sqrt:o||(d=>(u||(u=nl(n)),u(p,d))),toBytes:d=>t?br(d,l):gn(d,l),fromBytes:(d,f=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let g=new Uint8Array(l);g.set(d,t?0:g.length-d.length),d=g}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let h=t?xr(d):dt(d);if(i&&(h=ue(h,n)),!f&&!p.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:d=>yn(p,d),cmov:(d,f,h)=>h?f:d});return Object.freeze(p)}function Qo(n){if(typeof n!="bigint")throw new Error("field order must be bigint");let e=n.toString(2).length;return Math.ceil(e/8)}function Sr(n){let e=Qo(n);return e+Math.ceil(e/2)}function Cr(n,e,t=!1){let r=n.length,s=Qo(e),o=Sr(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let i=t?xr(n):dt(n),a=ue(i,e-ee)+ee;return t?br(a,s):gn(a,s)}var ut=BigInt(0),nt=BigInt(1);function Dt(n,e){let t=e.negate();return n?t:e}function wn(n,e){let t=yn(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function ni(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function Er(n,e){ni(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,o=We(n),i=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function Jo(n,e,t){let{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(n&s),c=n>>i;a>r&&(a-=o,c+=nt);let l=e*r,u=l+Math.abs(a)-1,p=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:d,isNegF:f,offsetF:l}}function ol(n,e){if(!Array.isArray(n))throw new Error("array expected");n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function il(n,e){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}var _r=new WeakMap,ri=new WeakMap;function Tr(n){return ri.get(n)||1}function ei(n){if(n!==ut)throw new Error("invalid wNAF")}var bn=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>ut;)t&nt&&(r=r.add(s)),s=s.double(),t>>=nt;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=Er(t,this.bits),o=[],i=e,a=i;for(let c=0;c<r;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Er(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:d,offsetF:f}=Jo(r,a,i);r=c,u?o=o.add(Dt(d,t[f])):s=s.add(Dt(p,t[l]))}return ei(r),{p:s,f:o}}wNAFUnsafe(e,t,r,s=this.ZERO){let o=Er(e,this.bits);for(let i=0;i<o.windows&&r!==ut;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Jo(r,i,o);if(r=a,!l){let p=t[c];s=s.add(u?p.negate():p)}}return ei(r),s}getPrecomputes(e,t,r){let s=_r.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(s=r(s)),_r.set(t,s))),s}cached(e,t,r){let s=Tr(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)}unsafe(e,t,r,s){let o=Tr(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,s)}createCache(e,t){ni(t,this.bits),ri.set(e,t),_r.delete(e)}hasCache(e){return Tr(e)!==1}};function si(n,e,t,r){let s=e,o=n.ZERO,i=n.ZERO;for(;t>ut||r>ut;)t&nt&&(o=o.add(s)),r&nt&&(i=i.add(s)),s=s.double(),t>>=nt,r>>=nt;return{p1:o,p2:i}}function oi(n,e,t,r){ol(t,n),il(r,e);let s=t.length,o=r.length;if(s!==o)throw new Error("arrays of points and scalars must have equal length");let i=n.ZERO,a=mn(BigInt(s)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=We(c),u=new Array(Number(l)+1).fill(i),p=Math.floor((e.BITS-1)/c)*c,d=i;for(let f=p;f>=0;f-=c){u.fill(i);for(let g=0;g<o;g++){let w=r[g],S=Number(w>>BigInt(f)&l);u[S]=u[S].add(t[g])}let h=i;for(let g=u.length-1,w=i;g>0;g--)w=w.add(u[g]),h=h.add(w);if(d=d.add(h),f!==0)for(let g=0;g<c;g++)d=d.double()}return d}function ti(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ar(e),e}else return je(n,{isLE:t})}function ii(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>ut))throw new Error(`CURVE.${c} must be positive bigint`)}let s=ti(e.p,t.Fp,r),o=ti(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}var ai=(n,e)=>(n+(n>=0?e:-e)/ci)/e;function al(n,e,t){let[[r,s],[o,i]]=e,a=ai(i*n,t),c=ai(-s*n,t),l=n-a*r-c*o,u=-a*s-c*i,p=l<Ue,d=u<Ue;p&&(l=-l),d&&(u=-u);let f=We(Math.ceil(mn(t)/2))+pt;if(l<Ue||l>=f||u<Ue||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:p,k1:l,k2neg:d,k2:u}}function Ir(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function Pr(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return Rt(t.lowS,"lowS"),Rt(t.prehash,"prehash"),t.format!==void 0&&Ir(t.format),t}var kr=class extends Error{constructor(e=""){super(e)}},Be={Err:kr,_tlv:{encode:(n,e)=>{let{Err:t}=Be;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,s=Bt(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?Bt(s.length/2|128):"";return Bt(n)+o+s+e},decode(n,e){let{Err:t}=Be,r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");let s=e[r++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(r+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(n){let{Err:e}=Be;if(n<Ue)throw new e("integer: negative integers are not allowed");let t=Bt(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){let{Err:e}=Be;if(n[0]&128)throw new e("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return dt(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=Be,s=J("signature",n),{v:o,l:i}=r.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,o),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(n){let{_tlv:e,_int:t}=Be,r=e.encode(2,t.encode(n.r)),s=e.encode(2,t.encode(n.s)),o=r+s;return e.encode(48,o)}},Ue=BigInt(0),pt=BigInt(1),ci=BigInt(2),vn=BigInt(3),cl=BigInt(4);function ft(n,e){let{BYTES:t}=n,r;if(typeof e=="bigint")r=e;else{let s=J("private key",e);try{r=n.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!n.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function ll(n,e={}){let t=ii("weierstrass",n,e),{Fp:r,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;Ut(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!r.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=di(r,s);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(L,x,y){let{x:m,y:b}=x.toAffine(),v=r.toBytes(m);if(Rt(y,"isCompressed"),y){u();let _=!r.isOdd(b);return z(li(_),v)}else return z(Uint8Array.of(4),v,r.toBytes(b))}function d(L){Ve(L,void 0,"Point");let{publicKey:x,publicKeyUncompressed:y}=l,m=L.length,b=L[0],v=L.subarray(1);if(m===x&&(b===2||b===3)){let _=r.fromBytes(v);if(!r.isValid(_))throw new Error("bad point: is not on curve, wrong x");let E=g(_),A;try{A=r.sqrt(E)}catch(W){let F=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();let T=r.isOdd(A);return(b&1)===1!==T&&(A=r.neg(A)),{x:_,y:A}}else if(m===y&&b===4){let _=r.BYTES,E=r.fromBytes(v.subarray(0,_)),A=r.fromBytes(v.subarray(_,_*2));if(!w(E,A))throw new Error("bad point: is not on curve");return{x:E,y:A}}else throw new Error(`bad point: got length ${m}, expected compressed=${x} or uncompressed=${y}`)}let f=e.toBytes||p,h=e.fromBytes||d;function g(L){let x=r.sqr(L),y=r.mul(x,L);return r.add(r.add(y,r.mul(L,o.a)),o.b)}function w(L,x){let y=r.sqr(x),m=g(L);return r.eql(y,m)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=r.mul(r.pow(o.a,vn),cl),M=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(S,M)))throw new Error("bad curve params: a or b");function k(L,x,y=!1){if(!r.isValid(x)||y&&r.is0(x))throw new Error(`bad point coordinate ${L}`);return x}function N(L){if(!(L instanceof B))throw new Error("ProjectivePoint expected")}function re(L){if(!c||!c.basises)throw new Error("no endo");return al(L,c.basises,s.ORDER)}let Ae=wr((L,x)=>{let{X:y,Y:m,Z:b}=L;if(r.eql(b,r.ONE))return{x:y,y:m};let v=L.is0();x==null&&(x=v?r.ONE:r.inv(b));let _=r.mul(y,x),E=r.mul(m,x),A=r.mul(b,x);if(v)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:_,y:E}}),Se=wr(L=>{if(L.is0()){if(e.allowInfinityPoint&&!r.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x,y}=L.toAffine();if(!r.isValid(x)||!r.isValid(y))throw new Error("bad point: x or y not field elements");if(!w(x,y))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Le(L,x,y,m,b){return y=new B(r.mul(y.X,L),y.Y,y.Z),x=Dt(m,x),y=Dt(b,y),x.add(y)}class B{constructor(x,y,m){this.X=k("x",x),this.Y=k("y",y,!0),this.Z=k("z",m),Object.freeze(this)}static CURVE(){return o}static fromAffine(x){let{x:y,y:m}=x||{};if(!x||!r.isValid(y)||!r.isValid(m))throw new Error("invalid affine point");if(x instanceof B)throw new Error("projective point not allowed");return r.is0(y)&&r.is0(m)?B.ZERO:new B(y,m,r.ONE)}static fromBytes(x){let y=B.fromAffine(h(Ve(x,void 0,"point")));return y.assertValidity(),y}static fromHex(x){return B.fromBytes(J("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,y=!0){return qe.createCache(this,x),y||this.multiply(vn),this}assertValidity(){Se(this)}hasEvenY(){let{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){N(x);let{X:y,Y:m,Z:b}=this,{X:v,Y:_,Z:E}=x,A=r.eql(r.mul(y,E),r.mul(v,b)),T=r.eql(r.mul(m,E),r.mul(_,b));return A&&T}negate(){return new B(this.X,r.neg(this.Y),this.Z)}double(){let{a:x,b:y}=o,m=r.mul(y,vn),{X:b,Y:v,Z:_}=this,E=r.ZERO,A=r.ZERO,T=r.ZERO,I=r.mul(b,b),W=r.mul(v,v),F=r.mul(_,_),U=r.mul(b,v);return U=r.add(U,U),T=r.mul(b,_),T=r.add(T,T),E=r.mul(x,T),A=r.mul(m,F),A=r.add(E,A),E=r.sub(W,A),A=r.add(W,A),A=r.mul(E,A),E=r.mul(U,E),T=r.mul(m,T),F=r.mul(x,F),U=r.sub(I,F),U=r.mul(x,U),U=r.add(U,T),T=r.add(I,I),I=r.add(T,I),I=r.add(I,F),I=r.mul(I,U),A=r.add(A,I),F=r.mul(v,_),F=r.add(F,F),I=r.mul(F,U),E=r.sub(E,I),T=r.mul(F,W),T=r.add(T,T),T=r.add(T,T),new B(E,A,T)}add(x){N(x);let{X:y,Y:m,Z:b}=this,{X:v,Y:_,Z:E}=x,A=r.ZERO,T=r.ZERO,I=r.ZERO,W=o.a,F=r.mul(o.b,vn),U=r.mul(y,v),K=r.mul(m,_),j=r.mul(b,E),se=r.add(y,m),V=r.add(v,_);se=r.mul(se,V),V=r.add(U,K),se=r.sub(se,V),V=r.add(y,b);let Y=r.add(v,E);return V=r.mul(V,Y),Y=r.add(U,j),V=r.sub(V,Y),Y=r.add(m,b),A=r.add(_,E),Y=r.mul(Y,A),A=r.add(K,j),Y=r.sub(Y,A),I=r.mul(W,V),A=r.mul(F,j),I=r.add(A,I),A=r.sub(K,I),I=r.add(K,I),T=r.mul(A,I),K=r.add(U,U),K=r.add(K,U),j=r.mul(W,j),V=r.mul(F,V),K=r.add(K,j),j=r.sub(U,j),j=r.mul(W,j),V=r.add(V,j),U=r.mul(K,V),T=r.add(T,U),U=r.mul(Y,V),A=r.mul(se,A),A=r.sub(A,U),U=r.mul(se,K),I=r.mul(Y,I),I=r.add(I,U),new B(A,T,I)}subtract(x){return this.add(x.negate())}is0(){return this.equals(B.ZERO)}multiply(x){let{endo:y}=e;if(!s.isValidNot0(x))throw new Error("invalid scalar: out of range");let m,b,v=_=>qe.cached(this,_,E=>wn(B,E));if(y){let{k1neg:_,k1:E,k2neg:A,k2:T}=re(x),{p:I,f:W}=v(E),{p:F,f:U}=v(T);b=W.add(U),m=Le(y.beta,I,F,_,A)}else{let{p:_,f:E}=v(x);m=_,b=E}return wn(B,[m,b])[0]}multiplyUnsafe(x){let{endo:y}=e,m=this;if(!s.isValid(x))throw new Error("invalid scalar: out of range");if(x===Ue||m.is0())return B.ZERO;if(x===pt)return m;if(qe.hasCache(this))return this.multiply(x);if(y){let{k1neg:b,k1:v,k2neg:_,k2:E}=re(x),{p1:A,p2:T}=si(B,m,v,E);return Le(y.beta,A,T,b,_)}else return qe.unsafe(m,x)}multiplyAndAddUnsafe(x,y,m){let b=this.multiplyUnsafe(y).add(x.multiplyUnsafe(m));return b.is0()?void 0:b}toAffine(x){return Ae(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return i===pt?!0:x?x(B,this):qe.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===pt?this:x?x(B,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return Rt(x,"isCompressed"),this.assertValidity(),f(B,this,x)}toHex(x=!0){return D(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return wn(B,x)}static msm(x,y){return oi(B,s,x,y)}static fromPrivateKey(x){return B.BASE.multiply(ft(s,x))}}B.BASE=new B(o.Gx,o.Gy,r.ONE),B.ZERO=new B(r.ZERO,r.ONE,r.ZERO),B.Fp=r,B.Fn=s;let Mt=s.BITS,qe=new bn(B,e.endo?Math.ceil(Mt/2):Mt);return B.BASE.precompute(8),B}function li(n){return Uint8Array.of(n?2:3)}function di(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function dl(n,e={}){let{Fn:t}=n,r=e.randomBytes||xe,s=Object.assign(di(n.Fp,t),{seed:Sr(t.ORDER)});function o(f){try{return!!ft(t,f)}catch{return!1}}function i(f,h){let{publicKey:g,publicKeyUncompressed:w}=s;try{let S=f.length;return h===!0&&S!==g||h===!1&&S!==w?!1:!!n.fromBytes(f)}catch{return!1}}function a(f=r(s.seed)){return Cr(Ve(f,s.seed,"seed"),t.ORDER)}function c(f,h=!0){return n.BASE.multiply(ft(t,f)).toBytes(h)}function l(f){let h=a(f);return{secretKey:h,publicKey:c(h)}}function u(f){if(typeof f=="bigint")return!1;if(f instanceof n)return!0;let{secretKey:h,publicKey:g,publicKeyUncompressed:w}=s;if(t.allowedLengths||h===g)return;let S=J("key",f).length;return S===g||S===w}function p(f,h,g=!0){if(u(f)===!0)throw new Error("first arg must be private key");if(u(h)===!1)throw new Error("second arg must be public key");let w=ft(t,f);return n.fromHex(h).multiply(w).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:p,keygen:l,Point:n,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:f=>ft(t,f),precompute(f=8,h=n.BASE){return h.precompute(f,!1)}},lengths:s})}function ul(n,e,t={}){Ye(e),Ut(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||xe,s=t.hmac||((y,...m)=>ve(e,y,z(...m))),{Fp:o,Fn:i}=n,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:d,lengths:f}=dl(n,t),h={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(y){let m=a>>pt;return y>m}function S(y,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return m}function M(y,m){Ir(m);let b=f.signature,v=m==="compact"?b:m==="recovered"?b+1:void 0;return Ve(y,v,`${m} signature`)}class k{constructor(m,b,v){this.r=S("r",m),this.s=S("s",b),v!=null&&(this.recovery=v),Object.freeze(this)}static fromBytes(m,b=g){M(m,b);let v;if(b==="der"){let{r:T,s:I}=Be.toSig(Ve(m));return new k(T,I)}b==="recovered"&&(v=m[0],b="compact",m=m.subarray(1));let _=i.BYTES,E=m.subarray(0,_),A=m.subarray(_,_*2);return new k(i.fromBytes(E),i.fromBytes(A),v)}static fromHex(m,b){return this.fromBytes($(m),b)}addRecoveryBit(m){return new k(this.r,this.s,m)}recoverPublicKey(m){let b=o.ORDER,{r:v,s:_,recovery:E}=this;if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");if(a*ci<b&&E>1)throw new Error("recovery id is ambiguous for h>1 curve");let T=E===2||E===3?v+a:v;if(!o.isValid(T))throw new Error("recovery id 2 or 3 invalid");let I=o.toBytes(T),W=n.fromBytes(z(li((E&1)===0),I)),F=i.inv(T),U=re(J("msgHash",m)),K=i.create(-U*F),j=i.create(_*F),se=n.BASE.multiplyUnsafe(K).add(W.multiplyUnsafe(j));if(se.is0())throw new Error("point at infinify");return se.assertValidity(),se}hasHighS(){return w(this.s)}toBytes(m=g){if(Ir(m),m==="der")return $(Be.hexFromSig(this));let b=i.toBytes(this.r),v=i.toBytes(this.s);if(m==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return z(Uint8Array.of(this.recovery),b,v)}return z(b,v)}toHex(m){return D(this.toBytes(m))}assertValidity(){}static fromCompact(m){return k.fromBytes(J("sig",m),"compact")}static fromDER(m){return k.fromBytes(J("sig",m),"der")}normalizeS(){return this.hasHighS()?new k(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return D(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return D(this.toBytes("compact"))}}let N=t.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");let b=dt(m),v=m.length*8-c;return v>0?b>>BigInt(v):b},re=t.bits2int_modN||function(m){return i.create(N(m))},Ae=We(c);function Se(y){return $o("num < 2^"+c,y,Ue,Ae),i.toBytes(y)}function Le(y,m){return Ve(y,void 0,"message"),m?Ve(e(y),void 0,"prehashed message"):y}function B(y,m,b){if(["recovered","canonical"].some(K=>K in b))throw new Error("sign() legacy options not supported");let{lowS:v,prehash:_,extraEntropy:E}=Pr(b,h);y=Le(y,_);let A=re(y),T=ft(i,m),I=[Se(T),Se(A)];if(E!=null&&E!==!1){let K=E===!0?r(f.secretKey):E;I.push(J("extraEntropy",K))}let W=z(...I),F=A;function U(K){let j=N(K);if(!i.isValidNot0(j))return;let se=i.inv(j),V=n.BASE.multiply(j).toAffine(),Y=i.create(V.x);if(Y===Ue)return;let $t=i.create(se*i.create(F+Y*T));if($t===Ue)return;let qr=(V.x===Y?0:2)|Number(V.y&pt),zr=$t;return v&&w($t)&&(zr=i.neg($t),qr^=1),new k(Y,zr,qr)}return{seed:W,k2sig:U}}function Mt(y,m,b={}){y=J("message",y);let{seed:v,k2sig:_}=B(y,m,b);return Go(e.outputLen,i.BYTES,s)(v,_)}function qe(y){let m,b=typeof y=="string"||Fe(y),v=!b&&y!==null&&typeof y=="object"&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!b&&!v)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(v)m=new k(y.r,y.s);else if(b){try{m=k.fromBytes(J("sig",y),"der")}catch(_){if(!(_ instanceof Be.Err))throw _}if(!m)try{m=k.fromBytes(J("sig",y),"compact")}catch{return!1}}return m||!1}function L(y,m,b,v={}){let{lowS:_,prehash:E,format:A}=Pr(v,h);if(b=J("publicKey",b),m=Le(J("message",m),E),"strict"in v)throw new Error("options.strict was renamed to lowS");let T=A===void 0?qe(y):k.fromBytes(J("sig",y),A);if(T===!1)return!1;try{let I=n.fromBytes(b);if(_&&T.hasHighS())return!1;let{r:W,s:F}=T,U=re(m),K=i.inv(F),j=i.create(U*K),se=i.create(W*K),V=n.BASE.multiplyUnsafe(j).add(I.multiplyUnsafe(se));return V.is0()?!1:i.create(V.x)===W}catch{return!1}}function x(y,m,b={}){let{prehash:v}=Pr(b,h);return m=Le(m,v),k.fromBytes(y,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:d,lengths:f,Point:n,sign:Mt,verify:L,recoverPublicKey:x,Signature:k,hash:e})}function fl(n){let e={a:n.a,b:n.b,p:n.Fp.ORDER,n:n.n,h:n.h,Gx:n.Gx,Gy:n.Gy},t=n.Fp,r=n.allowedPrivateKeyLengths?Array.from(new Set(n.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,s=je(e.n,{BITS:n.nBitLength,allowedLengths:r,modFromBytes:n.wrapPrivateKey}),o={Fp:t,Fn:s,allowInfinityPoint:n.allowInfinityPoint,endo:n.endo,isTorsionFree:n.isTorsionFree,clearCofactor:n.clearCofactor,fromBytes:n.fromBytes,toBytes:n.toBytes};return{CURVE:e,curveOpts:o}}function pl(n){let{CURVE:e,curveOpts:t}=fl(n),r={hmac:n.hmac,randomBytes:n.randomBytes,lowS:n.lowS,bits2int:n.bits2int,bits2int_modN:n.bits2int_modN};return{CURVE:e,curveOpts:t,hash:n.hash,ecdsaOpts:r}}function hl(n,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},n,xn(t.Fn.ORDER,t.Fn.BITS))})}function ui(n){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:s}=pl(n),o=ll(e,t),i=ul(o,r,s);return hl(n,i)}function fi(n,e){let t=r=>ui({...n,hash:r});return{...t(e),create:t}}var Br={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},gl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var pi=BigInt(2);function ml(n){let e=Br.p,t=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=n*n*n%e,u=l*l*n%e,p=ce(u,t,e)*u%e,d=ce(p,t,e)*u%e,f=ce(d,pi,e)*l%e,h=ce(f,s,e)*f%e,g=ce(h,o,e)*h%e,w=ce(g,a,e)*g%e,S=ce(w,c,e)*w%e,M=ce(S,a,e)*g%e,k=ce(M,t,e)*u%e,N=ce(k,i,e)*h%e,re=ce(N,r,e)*l%e,Ae=ce(re,pi,e);if(!Rr.eql(Rr.sqr(Ae),n))throw new Error("Cannot find square root");return Ae}var Rr=je(Br.p,{sqrt:ml}),An=fi({...Br,Fp:Rr,lowS:!0,endo:gl},pn);te();te();function yl(n,e,t,r){Ye(n);let s=$n({dkLen:32,asyncTick:10},r),{c:o,dkLen:i,asyncTick:a}=s;if(oe(o),oe(i),oe(a),o<1)throw new Error("iterations (c) should be >= 1");let c=Zt(e),l=Zt(t),u=new Uint8Array(i),p=ve.create(n,c),d=p._cloneInto().update(l);return{c:o,dkLen:i,asyncTick:a,DK:u,PRF:p,PRFSalt:d}}function xl(n,e,t,r,s){return n.destroy(),e.destroy(),r&&r.destroy(),ie(s),t}function hi(n,e,t,r){let{c:s,dkLen:o,DK:i,PRF:a,PRFSalt:c}=yl(n,e,t,r),l,u=new Uint8Array(4),p=Xe(u),d=new Uint8Array(a.outputLen);for(let f=1,h=0;h<o;f++,h+=a.outputLen){let g=i.subarray(h,h+a.outputLen);p.setInt32(0,f,!1),(l=c._cloneInto(l)).update(u).digestInto(d),g.set(d.subarray(0,g.length));for(let w=1;w<s;w++){a._cloneInto(l).update(d).digestInto(d);for(let S=0;S<g.length;S++)g[S]^=d[S]}}return xl(a,c,i,l,d)}te();var bl=32,wl=12,vl=16,Al=6e5,Ur="session_keys";function mi(n,e,t){return hi(we,n,e,{c:t??Al,dkLen:bl})}function Sl(n,e,t){let s=Math.ceil((n.length+16)/16),o=new Uint8Array(s*32),i=new Uint8Array(t),a=0n;for(let p=0;p<t.length;p++)a=a<<8n|BigInt(t[p]);for(let p=0;p<s;p++){let d=new Uint8Array(8),f=a+BigInt(p);for(let w=7;w>=0;w--)d[w]=Number(f&0xffn),f>>=8n;let h=new Uint8Array(t.length+8);h.set(t.slice(0,4),0),h.set(d,4);let g=ve(we,e,h);o.set(g,p*32)}let c=new Uint8Array(n.length);for(let p=0;p<n.length;p++)c[p]=n[p]^o[p];let l=new Uint8Array(t.length+c.length);l.set(t),l.set(c,t.length);let u=ve(we,e,l).slice(0,16);return{ciphertext:c,tag:u}}function Cl(n,e,t,r){let s=new Uint8Array(t.length+n.length);s.set(t),s.set(n,t.length);let o=ve(we,e,s).slice(0,16),i=r.length===o.length;if(i){for(let d=0;d<r.length;d++)if(r[d]!==o[d]){i=!1;break}}if(!i)throw ae("session_key_encryption_failed","Tag verification failed");let c=Math.ceil(n.length/16),l=new Uint8Array(c*32),u=0n;for(let d=0;d<t.length;d++)u=u<<8n|BigInt(t[d]);for(let d=0;d<c;d++){let f=new Uint8Array(8),h=u+BigInt(d);for(let S=7;S>=0;S--)f[S]=Number(h&0xffn),h>>=8n;let g=new Uint8Array(t.length+8);g.set(t.slice(0,4),0),g.set(f,4);let w=ve(we,e,g);l.set(w,d*32)}let p=new Uint8Array(n.length);for(let d=0;d<n.length;d++)p[d]=n[d]^l[d];return p}function Dr(n,e,t,r,s){let o=$(n.slice(2)),i=t??xe(vl),a=xe(wl),c=mi(e,i,r),{ciphertext:l,tag:u}=Sl(o,c,a),p=new Uint8Array(u.length+l.length);return p.set(u,0),p.set(l,u.length),{publicKey:s??`0x${D(o)}`,encryptedPrivateKey:D(p),iv:D(a),salt:D(i)}}function Lr(n,e,t){let r=$(n.encryptedPrivateKey),s=r.slice(0,16),o=r.slice(16),i=$(n.iv),a=$(n.salt),c=mi(e,a,t),l=Cl(o,c,i,s);return`0x${D(l)}`}function El(n,e){return typeof e=="bigint"?{__bigint__:e.toString()}:e}function gi(n,e){return e!==null&&typeof e=="object"&&"__bigint__"in e?BigInt(e.__bigint__):e}var Lt=class{adapter;constructor(e){this.adapter=e??new et}isAvailable(){return this.adapter.isAvailable()}async loadAll(){try{let e=await this.adapter.get(Ur);return e?JSON.parse(typeof e=="string"?e:JSON.stringify(e),gi):[]}catch{return[]}}async persistAll(e){let t=JSON.stringify(e,El);await this.adapter.set(Ur,t)}async save(e){let t=await this.loadAll(),r=t.findIndex(s=>s.id===e.id);r>=0?t[r]=e:t.push(e),await this.persistAll(t)}async get(e){return(await this.loadAll()).find(r=>r.id===e)??null}async remove(e){let r=(await this.loadAll()).filter(s=>s.id!==e);await this.persistAll(r)}async updateStatus(e,t){let r=await this.loadAll(),s=r.find(o=>o.id===e);if(!s)throw ae("session_key_not_found",e);s.status=t,await this.persistAll(r)}async incrementUsage(e){let t=await this.loadAll(),r=t.find(s=>s.id===e);if(!r)throw ae("session_key_not_found",e);r.useCount+=1,r.lastUsedAt=Date.now(),await this.persistAll(t)}async clear(){await this.adapter.remove(Ur)}};var Sn={storagePrefix:"naculus_session_keys",defaultMaxTotalValue:BigInt("100000000000000000"),defaultMaxTxCount:50,defaultExpiryMs:864e5,requireAllowedContracts:!0,forbiddenMethods:["0x095ea7b3","0xdd62ed3e","0xa22cb465"],encryptionSalt:"",encryptionKey:"",pbkdf2Iterations:6e5};function _l(){let n=xe(16);n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=D(n);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Tl(n){if(n.encryptionKey&&n.encryptionKey.length>0)return n.encryptionKey;let e=`${n.storagePrefix??Sn.storagePrefix}::session_key_encryption_v1`;return we(e).reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"")}var Or=class{config;storage;encryptionPassword;activeBundle=null;cache=new Map;constructor(e,t){this.config={...Sn,...e},this.storage=new Lt(t),this.encryptionPassword=Tl(this.config)}isStorageAvailable(){return this.storage.isAvailable()}async createSessionKey(e,t){let r=this.resolveScope(e);if(this.config.requireAllowedContracts&&(!r.allowedContracts||r.allowedContracts.length===0))throw ae("session_key_required_fields_missing","allowedContracts is required when requireAllowedContracts is enabled");let s=An.utils.randomPrivateKey(),o=An.getPublicKey(s),i=`0x${D(o)}`,a=`0x${D(s)}`,c=Dr(a,this.encryptionPassword,void 0,this.config.pbkdf2Iterations,i),l=Date.now(),u={id:_l(),keyPair:c,scope:r,authorization:{signerAddress:t??"0x0000000000000000000000000000000000000000",type:r.mode,rawSignature:void 0},status:"active",createdAt:l,lastUsedAt:l,useCount:0};return await this.storage.save(u),this.cache.set(u.id,u),this.toSessionKeyInfo(u)}async listSessions(){return(await this.refreshCache()).map(t=>this.toSessionKeyInfo(t))}async listActiveSessions(){return(await this.refreshCache()).filter(t=>t.status==="active").map(t=>this.toSessionKeyInfo(t))}async revokeSession(e){await this.storage.updateStatus(e,"revoked"),this.cache.delete(e),this.activeBundle?.id===e&&(this.activeBundle=null)}async getSessionBundle(e){if(this.activeBundle?.id===e)return this.activeBundle;let t=await this.storage.get(e)??this.cache.get(e)??null;if(!t)throw ae("session_key_not_found",e);this.validateSessionStatus(t);let r=Lr(t.keyPair,this.encryptionPassword,this.config.pbkdf2Iterations),s={id:t.id,privateKey:r,scope:t.scope,authorization:t.authorization,signerAddress:t.authorization.signerAddress};return this.activeBundle=s,s}async signWithSessionKey(e,t){let r=await this.getSessionBundle(e),s=$(t.slice(2)),o=An.sign(s,$(r.privateKey.slice(2))),i=o.toCompactHex(),a=o.recovery!==null?o.recovery+27:27,c=i.slice(0,64),l=i.slice(64,128),u=a.toString(16).padStart(2,"0");try{await this.storage.incrementUsage(e)}catch{}return`0x${c}${l}${u}`}async checkSessionScope(e,t){let r=this.cache.get(e)??null;if(r||(r=await this.storage.get(e)??null),!r)return{valid:!1,reason:"Session key not found"};try{this.validateSessionStatus(r)}catch(s){return{valid:!1,reason:s.message??"Session key invalid"}}return this.checkScopeAgainstTx(r.scope,r.useCount,t)}async setAuthorization(e,t){let s=(await this.storage.loadAll()).find(o=>o.id===e);if(!s)throw ae("session_key_not_found",e);s.authorization=t,await this.storage.save(s),this.cache.set(s.id,s)}async clearAll(){await this.storage.clear(),this.cache.clear(),this.activeBundle=null}resolveScope(e){let t=Math.floor(Date.now()/1e3),r=Math.floor((Date.now()+this.config.defaultExpiryMs)/1e3);return{expiry:e?.expiry??r,maxTotalValue:e?.maxTotalValue??this.config.defaultMaxTotalValue,maxTotalGas:e?.maxTotalGas??void 0,maxGasPerTx:e?.maxGasPerTx??void 0,maxValuePerTx:e?.maxValuePerTx??void 0,maxTxCount:e?.maxTxCount??this.config.defaultMaxTxCount,allowedContracts:e?.allowedContracts??(this.config.requireAllowedContracts?[]:void 0),allowedMethods:e?.allowedMethods??void 0,tokenAllowances:e?.tokenAllowances??void 0,allowedChainIds:e?.allowedChainIds??void 0,mode:e?.mode??"offchain"}}validateSessionStatus(e){if(e.status==="revoked")throw ae("session_key_revoked",e.id);if(e.status==="expired")throw ae("session_key_expired",e.id);let t=Math.floor(Date.now()/1e3);if(e.scope.expiry<t)throw this.storage.updateStatus(e.id,"expired").catch(()=>{}),ae("session_key_expired",e.id);if(e.scope.maxTxCount!==void 0&&e.useCount>=e.scope.maxTxCount)throw ae("session_key_max_tx_count_exceeded",e.id)}checkScopeAgainstTx(e,t,r){let s={valid:!0},o=r.value?BigInt(r.value):0n,i=r.gas?BigInt(r.gas):0n;if(e.allowedChainIds&&e.allowedChainIds.length>0&&r.chainId!==void 0&&!e.allowedChainIds.includes(r.chainId))return{valid:!1,reason:`Chain ${r.chainId} not in allowed list: ${e.allowedChainIds.join(", ")}`};if(e.allowedContracts&&e.allowedContracts.length>0&&r.to){let a=r.to.toLowerCase();if(!e.allowedContracts.some(l=>l.toLowerCase()===a))return{valid:!1,reason:`Contract ${r.to} not in allowed list`}}if(this.config.forbiddenMethods.length>0&&r.data&&r.data.length>=10){let a=r.data.slice(0,10);if(this.config.forbiddenMethods.includes(a))return{valid:!1,reason:`Method ${a} is forbidden for session keys`}}if(e.allowedMethods&&e.allowedMethods.length>0&&r.data&&r.data.length>=10){let a=r.data.slice(0,10);if(!e.allowedMethods.includes(a))return{valid:!1,reason:`Method ${a} not in allowed list`}}return e.maxValuePerTx!==void 0&&o>e.maxValuePerTx?{valid:!1,reason:`Transaction value ${o} exceeds max per-tx value ${e.maxValuePerTx}`}:e.maxTotalValue!==void 0&&o>e.maxTotalValue?{valid:!1,reason:`Transaction value ${o} exceeds max total value ${e.maxTotalValue}`}:e.maxGasPerTx!==void 0&&i>e.maxGasPerTx?{valid:!1,reason:`Gas ${i} exceeds max per-tx gas ${e.maxGasPerTx}`}:e.maxTxCount!==void 0&&t>=e.maxTxCount?{valid:!1,reason:`Tx count ${t} exceeds max ${e.maxTxCount}`}:(e.maxTotalValue!==void 0&&(s.remainingValue=e.maxTotalValue-o),e.maxGasPerTx!==void 0&&(s.remainingGas=e.maxGasPerTx-i),e.maxTxCount!==void 0&&(s.remainingTxCount=e.maxTxCount-t-1),s)}async refreshCache(){let e=await this.storage.loadAll(),t=Math.floor(Date.now()/1e3),r=!1;for(let s of e)s.status==="active"&&s.scope.expiry<t&&(s.status="expired",r=!0),this.cache.set(s.id,s);if(r)for(let s of e)s.status==="expired"&&await this.storage.save(s);return e}toSessionKeyInfo(e){return{id:e.id,publicKey:e.keyPair.publicKey,scope:e.scope,status:e.status,createdAt:e.createdAt,expiresAt:e.scope.expiry*1e3,useCount:e.useCount,signerAddress:e.authorization.signerAddress}}};var yi={no_active_session:"No active session. Please connect your wallet first.",chain_switch_rejected:"Chain switch was rejected by the user.",chain_unsupported:"The requested chain is not supported by this wallet.",fee_rpc_error:"Failed to fetch fee estimation. Using cached values.",method_unsupported:"This method is not supported by the current connector.",invalid_chain:"Invalid chain ID format. Expected CAIP-2 format (e.g., eip155:1)."};function De(n,e){return new ke(n,yi[n],e)}var Ot=class{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){let r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e))}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}emit(e,t){let r=this.listeners.get(e);if(r)for(let s of r)try{s(t)}catch(o){console.error(`[SessionEventEmitter] Error in handler for "${e}":`,o)}}};var Pl="naculus_web3_session_manager",Nt=class{adapter;key;constructor(e,t){this.key=e??Pl,this.adapter=t??new Je("naculus_sm:")}isAvailable(){return this.adapter.isAvailable()}async load(){if(!this.adapter.isAvailable())return null;try{return await this.adapter.get(this.key)}catch(e){return O.warn("session/persistence","Failed to load persisted session:",e),await this.adapter.remove(this.key),null}}async save(e){if(this.adapter.isAvailable())try{await this.adapter.set(this.key,e)}catch(t){O.warn("session/persistence","Failed to save session:",t)}}async clear(){this.adapter.isAvailable()&&await this.adapter.remove(this.key)}serializeBundle(e){let t={};return e.chainSessions.forEach((r,s)=>{t[s]=r}),{walletSession:e.walletSession,lastActiveChainId:e.activeChainId,chainSessions:t,lastConnectedAt:e.lastActiveAt}}deserializeToBundle(e){if(No(e.walletSession,new Date))return O.warn("session/persistence","Persisted session is expired, ignoring"),null;let t=new Map;for(let[r,s]of Object.entries(e.chainSessions))t.set(r,s);return{walletSession:e.walletSession,chainSessions:t,activeChainId:e.lastActiveChainId,lastActiveAt:e.lastConnectedAt}}};function Nr(n,e){return!e&&!(typeof globalThis<"u"&&typeof globalThis.localStorage<"u")?new Nt(n,new et):new Nt(n,e)}function Ft(n){let e=n.split(":");if(e.length!==2||!e[0]||!e[1])throw new Error(`Invalid CAIP-2 chain ID: "${n}". Expected format: "namespace:reference"`);return{namespace:e[0],reference:e[1]}}function Cn(n){let{namespace:e,reference:t}=Ft(n),r=["eip155","solana","xrpl"];if(!r.includes(e))throw new Error(`Unsupported namespace "${e}" in chain ID "${n}". Supported: ${r.join(", ")}`);if(!/^\d+$/.test(t))throw new Error(`Invalid reference "${t}" in chain ID "${n}". Reference must be numeric.`)}var Il={"eip155:1":{name:"Ether",symbol:"ETH",decimals:18},"eip155:137":{name:"MATIC",symbol:"MATIC",decimals:18},"eip155:10":{name:"Ether",symbol:"ETH",decimals:18},"eip155:42161":{name:"Ether",symbol:"ETH",decimals:18},"eip155:8453":{name:"Ether",symbol:"ETH",decimals:18},"eip155:11155111":{name:"Sepolia Ether",symbol:"ETH",decimals:18},"solana:0":{name:"SOL",symbol:"SOL",decimals:9},"solana:1":{name:"SOL",symbol:"SOL",decimals:9}},kl={"eip155:1":"https://etherscan.io","eip155:137":"https://polygonscan.com","eip155:10":"https://optimistic.etherscan.io","eip155:42161":"https://arbiscan.io","eip155:8453":"https://basescan.org","eip155:11155111":"https://sepolia.etherscan.io"},En=class extends Ot{constructor(t,r){super();this.connectorManager=t;this.config={autoRefreshFeeOnSwitch:r?.autoRefreshFeeOnSwitch??!0,maxActiveSessions:r?.maxActiveSessions??10,defaultRpcUrls:r?.defaultRpcUrls,defaultCurrencies:r?.defaultCurrencies,defaultExplorers:r?.defaultExplorers},this.persistence=Nr()}connectorManager;bundles=new Map;activeBundleId=null;userFeeOverrides={};config;persistence;async connect(t,r,s){if(Cn(r),this.bundles.size>=this.config.maxActiveSessions){let c=Array.from(this.bundles.entries()).reduce((l,u)=>l[1].lastActiveAt<u[1].lastActiveAt?l:u);this.bundles.delete(c[0])}let o=await this.connectorManager.connect(s),i=this.buildBundle(o,r,t),a=this.getBundleId(o);return this.bundles.set(a,i),this.activeBundleId=a,await this.persistBundle(i),this.emit("sessionConnected",{bundle:i}),i}async switchChain(t){Cn(t);let r=this.getActiveBundle();if(!r)throw De("no_active_session");let s=r.activeChainId;if(s===t)return;let o=this.resolveConnector(r.walletSession);if(!o.switchChain)throw De("method_unsupported");try{await o.switchChain(r.walletSession,t)}catch(i){throw i?.code===4001||i?.message?.includes("rejected")?De("chain_switch_rejected"):De("chain_unsupported")}if(!r.chainSessions.has(t)){let i=this.createChainSession(t,r.walletSession.walletType);r.chainSessions.set(t,i),this.emit("chainSessionAdded",{bundle:r,chainSession:i})}if(r.activeChainId=t,r.lastActiveAt=new Date().toISOString(),this.updateSessionNamespace(r.walletSession,t),this.emit("chainChanged",{bundle:r,previousChainId:s,newChainId:t}),this.config.autoRefreshFeeOnSwitch)try{await this.refreshFees(t)}catch(i){O.warn("session-manager",`Fee refresh failed after chain switch to ${t}:`,i)}await this.persistBundle(r)}async disconnect(){let t=this.getActiveBundle();if(!t)return;let r=this.resolveConnector(t.walletSession);try{await r.disconnect(t.walletSession)}catch(a){O.warn("session-manager","Disconnect error:",a)}let s=t.walletSession.walletType,o=t.walletSession.topic,i=this.activeBundleId;i&&this.bundles.delete(i),this.activeBundleId=null,await this.persistence.clear(),this.emit("sessionDisconnected",{connectorId:s,topic:o})}async disconnectChain(t){let r=this.getActiveBundle();if(!r)throw De("no_active_session");if(r.chainSessions.delete(t)){if(this.emit("chainSessionRemoved",{bundle:r,chainId:t}),r.activeChainId===t){let o=Array.from(r.chainSessions.keys());r.activeChainId=o[0]??r.activeChainId}await this.persistBundle(r)}}getActiveChainSession(){let t=this.getActiveBundle();if(t)return t.chainSessions.get(t.activeChainId)}getAllChainSessions(){let t=[];for(let r of this.bundles.values())r.chainSessions.forEach(s=>{t.push(s)});return t}getAllActiveSessions(){return Array.from(this.bundles.values())}getActiveBundle(){return this.activeBundleId?this.bundles.get(this.activeBundleId)??null:null}async refreshFees(t,r){let s=this.getActiveBundle();if(!s)throw De("no_active_session");let o=t??s.activeChainId,i=s.chainSessions.get(o);if(!i)return null;try{let a={rpcUrl:i.rpcUrl,chainId:o},c=this.userFeeOverrides[o];c&&(c.type&&(a.type=c.type),c.maxPriorityFeePerGas!==void 0&&(a.maxPriorityFeePerGas=c.maxPriorityFeePerGas),c.baseFeeMultiplier!==void 0&&(a.baseFeeMultiplier=c.baseFeeMultiplier)),r?.userOverrides&&Object.assign(a,r.userOverrides);let l=await tr(a);return i.lastKnownFees=l,i.lastFeeUpdatedAt=new Date().toISOString(),this.emit("feesUpdated",{chainId:o,fees:l}),l}catch(a){return O.warn("session-manager",`Fee refresh failed for ${o}:`,a),i.lastKnownFees??null}}setUserFeeOverrides(t,r){let s=this.userFeeOverrides[t]??{};this.userFeeOverrides[t]={...s,...r}}getUserFeeOverrides(t){return this.userFeeOverrides[t]}clearUserFeeOverrides(t){t?delete this.userFeeOverrides[t]:this.userFeeOverrides={}}async restoreFromPersistence(){let t=await this.persistence.load();if(!t)return!1;let r=this.persistence.deserializeToBundle(t);if(!r)return await this.persistence.clear(),!1;let s=this.getBundleId(r.walletSession);return this.bundles.set(s,r),this.activeBundleId=s,this.emit("sessionConnected",{bundle:r}),!0}on(t,r){super.on(t,r)}off(t,r){super.off(t,r)}buildBundle(t,r,s){let o=new Map;for(let[,i]of Object.entries(t.namespaces)){let a=i;for(let c of a.chains)o.has(c)||o.set(c,this.createChainSession(c,s))}return o.has(r)||o.set(r,this.createChainSession(r,s)),{walletSession:t,chainSessions:o,activeChainId:r,lastActiveAt:new Date().toISOString()}}createChainSession(t,r){let{namespace:s}=Ft(t),o=this.config.defaultCurrencies?.[t]??Il[t]??{name:t,symbol:t.includes(":")?t.split(":")[1]:t,decimals:18},i=this.config.defaultRpcUrls?.[t]??be[t]??"",a=this.config.defaultExplorers?.[t]??kl[t];return{chainId:t,connectorId:r,rpcUrl:i,nativeCurrency:o,blockExplorer:a}}updateSessionNamespace(t,r){let{namespace:s,reference:o}=Ft(r);t.namespaces[s]||(t.namespaces[s]={chains:[],accounts:[],methods:[],events:[]});let i=t.namespaces[s];i.chains.includes(r)||i.chains.push(r)}resolveConnector(t){let r=this.connectorManager.get(t.walletType);if(!r)throw De("chain_unsupported",`No connector found for wallet type: ${t.walletType}`);return r}getBundleId(t){return t.topic??t.id}async persistBundle(t){let r=this.persistence.serializeBundle(t);await this.persistence.save(r)}};function Rl(n,e){return new En(n,e)}var xi=[1,137,42161,10,56,43114,8453,250,25,324],Bl={1:"ethereum",137:"polygon",42161:"arbitrum",10:"optimism",56:"bsc",43114:"avalanche",8453:"base",250:"fantom",25:"cronos",324:"zksync"},Ul="https://api.blowfish.xyz";function Dl(n){return Bl[n]??`eip155:${n}`}function Ll(n){switch(n){case"NONE":return"safe";case"WARN":return"warning";case"BLOCK":return"malicious";default:return"unknown"}}function Ol(n){if(!n||!Array.isArray(n))return[];let e=[];for(let t of n)t?.kind==="APPROVAL_TO_EOA"&&e.push({category:"phishing",severity:"critical",message:t.description??"Approval to an Externally Owned Account (EOA)"}),t?.kind==="UNLIMITED_ALLOWANCE"&&e.push({category:"unlimited_approval",severity:"high",message:t.description??"Unlimited token approval requested"}),t?.kind==="MALICIOUS_DOMAIN"&&e.push({category:"malicious_domain",severity:"critical",message:t.description??"Suspicious domain detected"}),t?.kind==="KNOWN_MALICIOUS"&&e.push({category:"phishing",severity:"critical",message:t.description??"Known malicious contract detected"}),t?.kind==="SIMULATION_ERROR"&&e.push({category:"simulation_failed",severity:"medium",message:t.description??"Simulation encountered an error"}),t?.kind&&!["APPROVAL_TO_EOA","UNLIMITED_ALLOWANCE","MALICIOUS_DOMAIN","KNOWN_MALICIOUS","SIMULATION_ERROR"].includes(t.kind)&&e.push({category:"other",severity:t.severity==="CRITICAL"?"critical":t.severity==="HIGH"?"high":t.severity==="MEDIUM"?"medium":"low",message:t.description??`Unexpected scan result: ${t.kind}`});return e}function Nl(n){if(!n||!Array.isArray(n))return[];let e=[];for(let t of n){if(!t?.contractInfo)continue;let r=t.humanReadableDiff?.match(/^(Send|Receive|Approve|Revoke)\s+(.+?)(?:\s+\(([^)]+)\))?\s*(.+)?$/i),s="out",o=t.humanReadableDiff??"";/^Receive/i.test(o)&&(s="in");let i=t.rawInfo?.amount??t.amount??"0",a=t.contractInfo.name??"",c=t.contractInfo.address??"0x0000000000000000000000000000000000000000",l=t.contractInfo.decimals??18;e.push({tokenAddress:c,tokenSymbol:a,tokenDecimals:l,amount:typeof i=="bigint"?i.toString():String(i),direction:s,from:t.from??"0x0000000000000000000000000000000000000000",to:t.to??"0x0000000000000000000000000000000000000000",humanReadable:o})}return e}function Fl(n){if(!n||!Array.isArray(n))return[];let e=[];for(let t of n){if(!t?.humanReadableDiff||!/^Approve/i.test(t.humanReadableDiff))continue;let s=t.rawInfo?.amount??t.amount??"0",o=s==="0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"||s==="115792089237316195423570985008687907853269984665640564039457584007913129639935";e.push({tokenAddress:t.contractInfo?.address??"0x0000000000000000000000000000000000000000",tokenSymbol:t.contractInfo?.name??"",owner:t.from??"0x0000000000000000000000000000000000000000",spender:t.to??"0x0000000000000000000000000000000000000000",amount:String(s),isUnlimited:o,humanReadable:t.humanReadableDiff})}return e}function Hl(n){if(n)return{gasLimit:n.gasLimit?BigInt(n.gasLimit):0n,gasPrice:n.gasPrice?BigInt(n.gasPrice):void 0,estimatedFeeEth:n.estimatedFeeEth,estimatedFeeUsd:n.estimatedFeeUsd}}function Ml(n,e){if(n?.description)return n.description;if(e.length>0){let t=e.slice(0,3).map(r=>r.humanReadable).join(", ");return t.length>0?t:"State changes detected"}return"No significant state changes detected"}var ht=class{name="blowfish";supportedChains=xi;apiKey;constructor(e){if(!e||e.trim().length===0)throw new Error("BlowfishProvider requires an API key. Get one at https://blowfish.xyz");this.apiKey=e}async simulate(e,t,r){try{let s=r?.origin?Dl(this._inferChainId(r.origin)):"ethereum",o=await fetch(`${Ul}/v1/solana/mainnet/transaction/simulate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({transactions:[e.data],userAccount:t,metadata:{origin:r?.origin??""}})});if(!o.ok)return o.status===429?{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"low",message:"Blowfish: Rate limited. Falling back to basic simulation."}]},provider:this.name,summary:"Simulation unavailable (rate limited)",changesDetected:!1}:o.status>=500?{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:`Blowfish: Server error (${o.status}). Falling back to basic simulation.`}]},provider:this.name,summary:"Simulation unavailable (server error)",changesDetected:!1}:{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:`Blowfish: HTTP ${o.status}. Falling back.`}]},provider:this.name,summary:"Simulation unavailable",changesDetected:!1};let i=await o.json(),a=i.simulationResult??i,c=Nl(a.expectedStateChanges),l=Fl(a.expectedStateChanges),u=a.suggestedAction??"NONE",p=Ll(u),d=a.scanResults??[],f=Ol(d),h=0;p==="warning"&&(h=40),p==="malicious"&&(h=80);for(let g of f)g.severity==="critical"?h+=20:g.severity==="high"?h+=10:g.severity==="medium"&&(h+=5);return h=Math.min(h,100),{status:a.status==="REVERTED"?"reverted":"success",revertReason:a.error?.message,balanceChanges:c,approvalChanges:l,riskAssessment:{level:p,score:h,warnings:f},gasInfo:Hl(a.gasInfo),provider:this.name,summary:Ml(a,c),changesDetected:a.status==="CHANGES_DETECTED"||c.length>0,raw:a}}catch(s){return{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:`Blowfish: Network error: ${s instanceof Error?s.message:"Unknown error"}`}]},provider:this.name,summary:"Simulation unavailable (network error)",changesDetected:!1}}}isAvailable(e){return xi.includes(e)}_inferChainId(e){return 1}};var $l=[1,5,11155111,10,42161,421614,8453,84532],Gl=[137,80002],Kl=[56,97];function Vl(n){let e=n.startsWith("0x")?n.slice(2):n;if(e.length>=10&&e.startsWith("08c379a0"))try{let t=e.slice(8),r=t.slice(64,128),s=parseInt(r,16);if(s>0&&s*2<=t.length-128){let o=t.slice(128,128+s*2),i=new Uint8Array(s);for(let a=0;a<s;a++)i[a]=parseInt(o.slice(a*2,a*2+2),16);return new TextDecoder().decode(i)}}catch{}if(e.length>=10&&e.startsWith("4e487b71")){let t=e.slice(8,72),r=BigInt(`0x${t}`);return{0:"Generic panic",1:"Assert failed",17:"Arithmetic overflow/underflow",18:"Division by zero",33:"Enum conversion out of bounds",34:"Storage array access out of bounds",49:"pop() on empty array",50:"Index out of bounds",65:"Allocate too much memory",81:"Call to non-existent function"}[r.toString()]??`Panic code ${r}`}if(e.length>0)return e}function Wl(n){return $l.includes(n)?"ETH":Gl.includes(n)?"MATIC":Kl.includes(n)?"BNB":"ETH"}function jl(n,e,t){let r=Wl(t);return{status:"success",balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:n,summary:"Transaction simulation succeeded (basic revert check only)",changesDetected:!0}}function ql(n,e){return{status:"reverted",revertReason:n,balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:n?`Transaction would revert: ${n}`:"Transaction would revert (no reason provided)"}]},provider:e,summary:n?`Transaction reverted: ${n}`:"Transaction reverted",changesDetected:!1}}var Ht=class{name="eth_call";supportedChains=[];defaultRpcUrl;constructor(e){this.defaultRpcUrl=e}async simulate(e,t,r){let s=r?.rpcUrl??this.defaultRpcUrl;if(!s)return{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:"EthCallProvider: No RPC URL configured"}]},provider:this.name,summary:"Simulation unavailable: no RPC URL",changesDetected:!1};let o={to:e.to,from:t,data:e.data,value:e.value||"0x0"};e.gas&&(o.gas=e.gas);try{let a=await(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"eth_call",params:[o,"latest"]})})).json();if(a.error){let c=Vl(a.error.data??a.error.message);return ql(c,this.name)}return jl(this.name,t,this._extractChainId(r?.rpcUrl??this.defaultRpcUrl))}catch(i){return{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:`EthCallProvider: Network error during simulation: ${i instanceof Error?i.message:"Unknown error"}`}]},provider:this.name,summary:"Simulation unavailable due to network error",changesDetected:!1}}}isAvailable(e){return!0}_extractChainId(e){return 0}};async function zl(n,e={}){let t=e.timeoutMs??1e4,r=new AbortController,s=setTimeout(()=>r.abort(),t);try{return await fetch(n,{...e,signal:r.signal})}finally{clearTimeout(s)}}async function Fr(n,e,t,r){let s=await zl(n,{method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify({jsonrpc:"2.0",id:1,method:e,params:t}),timeoutMs:r?.timeoutMs??1e4});if(!s.ok)throw new Error(`RPC returned status ${s.status}`);let o=await s.json();if(o.error)throw new Error(o.error.message);return o.result}var Yl=[{name:"transfer",type:"function",stateMutability:"nonpayable",inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"success",type:"bool"}]},{name:"approve",type:"function",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"success",type:"bool"}]},{name:"transferFrom",type:"function",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"success",type:"bool"}]},{name:"allowance",type:"function",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"remaining",type:"uint256"}]},{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"balance",type:"uint256"}]},{name:"decimals",type:"function",stateMutability:"view",inputs:[],outputs:[{name:"decimals",type:"uint8"}]},{name:"symbol",type:"function",stateMutability:"view",inputs:[],outputs:[{name:"symbol",type:"string"}]},{name:"name",type:"function",stateMutability:"view",inputs:[],outputs:[{name:"name",type:"string"}]},{name:"totalSupply",type:"function",stateMutability:"view",inputs:[],outputs:[{name:"totalSupply",type:"uint256"}]}],ge={transfer:"transfer(address,uint256)",approve:"approve(address,uint256)",transferFrom:"transferFrom(address,address,uint256)",allowance:"allowance(address,address)",balanceOf:"balanceOf(address)",decimals:"decimals()",symbol:"symbol()",name:"name()",totalSupply:"totalSupply()"};sn();Tt();function mt(n){return n.startsWith("0x")?n.slice(2):n}function Ai(n){return n.padStart(64,"0")}async function Xl(n){let{keccak_256:e}=await Promise.resolve().then(()=>(Jt(),Kn)),{bytesToHex:t}=await Promise.resolve().then(()=>(te(),Gn));return t(e(n))}function rt(n){if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new G("invalid_address",`Invalid EVM address: "${n}". Expected 0x-prefixed 40-char hex.`);return`0x${Ai(mt(n.toLowerCase()))}`}function Tn(n){if(n<0n)throw new G("invalid_amount",`Cannot encode negative uint256: ${n}`);let e=n.toString(16),t=e.length%2===0?e:`0${e}`;return`0x${Ai(t)}`}async function $r(n){return`0x${(await Xl(new TextEncoder().encode(n))).slice(0,8)}`}async function Pn(n,...e){let t=await $r(n),r=e.map(s=>mt(s)).join("");return`${t}${r}`}async function Zl(n,e){return Pn(ge.transfer,rt(n),Tn(e))}async function Ql(n,e){return Pn(ge.approve,rt(n),Tn(e))}async function Jl(n,e,t){return Pn(ge.transferFrom,rt(n),rt(e),Tn(t))}function _n(n,e){if(e?.rpcUrl)return e.rpcUrl;let t=be[`eip155:${n}`];if(!t)throw new G("rpc_error",`No default RPC URL for chain ID ${n}. Provide options.rpcUrl.`);return t}async function Hr(n,e,t){try{return await Fr(n,"eth_call",[{to:e,data:t},"latest"])}catch(r){throw new G("rpc_error",`RPC eth_call error: ${r}`,r)}}function Mr(n){let e=mt(n);return BigInt(`0x${e}`)}function bi(n){let e=mt(n);if(e.length<128)return"";let t=e.slice(64,128),r=parseInt(t,16),s=e.slice(128,128+r*2),o=new Uint8Array(r);for(let i=0;i<r;i++)o[i]=parseInt(s.slice(i*2,i*2+2),16);return new TextDecoder().decode(o)}function wi(n){return Number(Mr(n))}var vi=new Map;async function gt(n){let e=vi.get(n);if(e)return e;let t=await $r(n);return vi.set(n,t),t}var yt=class n{static async buildTransferTx(e,t){let r=typeof e.amount=="string"?Ze(e.amount,t):e.amount,s=await Zl(e.to,r);return{to:e.token.address,from:e.from,data:s,value:"0x0"}}static async buildApproveTx(e,t){let r=typeof e.amount=="string"?Ze(e.amount,t):e.amount,s=await Ql(e.spender,r);return{to:e.token.address,from:e.owner,data:s,value:"0x0"}}static async buildTransferFromTx(e,t){let r=typeof e.amount=="string"?Ze(e.amount,t):e.amount,s=await Jl(e.from,e.to,r);return{to:e.token.address,from:e.from,data:s,value:"0x0"}}static async getAllowance(e,t,r,s){let o=_n(e.chainId,s),a=`${await gt(ge.allowance)}${mt(rt(t))}${mt(rt(r))}`,c=await Hr(o,e.address,a);return Mr(c)}static async getTokenInfo(e,t){let r=_n(e.chainId,t),s=e.address,o=await gt(ge.name),i=await gt(ge.symbol),a=await gt(ge.decimals),c=await gt(ge.totalSupply),l=async u=>Hr(r,s,u);try{let[u,p,d,f]=await Promise.all([l(o),l(i),l(a),l(c)]),h=bi(u),g=bi(p),w=wi(d),S=Mr(f);return{name:h,symbol:g,decimals:w,totalSupply:S}}catch(u){throw u instanceof G?u:new G("token_info_fetch_failed","Failed to fetch token metadata from chain.",u)}}static async isTokenDeployed(e,t){let r=_n(e.chainId,t);try{let s=await Fr(r,"eth_getCode",[e.address,"latest"]);return s!=="0x"&&s!=="0x0"}catch(s){throw new G("rpc_error",`RPC eth_getCode error: ${s}`,s)}}static async getDecimals(e,t){if(e.decimals!==void 0)return e.decimals;let r=_n(e.chainId,t),o=await gt(ge.decimals);try{let i=await Hr(r,e.address,o);return wi(i)}catch(i){throw new G("decimals_fetch_failed",`Failed to fetch decimals for token ${e.address} on chain ${e.chainId}.`,i)}}static async parseToRawAmount(e,t,r){let s=await n.getDecimals(e,r);return Ze(t,s)}static async formatRawAmount(e,t,r){let s=await n.getDecimals(e,r),{formatUnits:o}=await Promise.resolve().then(()=>(Tt(),mo));return o(t,s)}};var Gr={level:"unknown",score:0,warnings:[]},Kr=class{providers=new Map;_defaultProvider;_enabled;blowfishApiKey;constructor(e){this._enabled=e?.enabled??!0,this._defaultProvider=e?.defaultProvider??"auto",this.blowfishApiKey=e?.blowfishApiKey,this.providers.set("eth_call",new Ht(e?.rpcUrl)),this.blowfishApiKey&&this.providers.set("blowfish",new ht(this.blowfishApiKey))}async simulate(e,t,r){if(!this._enabled)return{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{...Gr},provider:"auto",summary:"Simulation is disabled",changesDetected:!1};let s=r?.chainId??this._estimateChainId(t),o=this._selectProvider(s);if(!o)return{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{...Gr,warnings:[{category:"simulation_failed",severity:"low",message:"No simulation provider available for this chain"}]},provider:"auto",summary:"No simulation provider available",changesDetected:!1};let i=r?.rpcUrl??this._resolveRpcUrl(s),a=await o.simulate(e,t,{origin:r?.origin,rpcUrl:i});if(a.status==="unavailable"&&o.name!=="eth_call"){let c=this.providers.get("eth_call");if(c){let l=await c.simulate(e,t,{rpcUrl:i});return{...l,riskAssessment:{...l.riskAssessment,warnings:[...a.riskAssessment.warnings,...l.riskAssessment.warnings]}}}}return a}async simulateERC20Transfer(e,t,r,s,o){try{let i=e.decimals??await yt.getDecimals(e),a=await yt.buildTransferTx({token:e,from:t,to:r,amount:s},i);return this.simulate({to:a.to,data:a.data,value:"0x0",from:t},t,{chainId:o})}catch(i){return{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{...Gr,warnings:[{category:"simulation_failed",severity:"low",message:`Failed to build transfer calldata: ${i instanceof Error?i.message:String(i)}`}]},provider:"auto",summary:"Failed to prepare simulation",changesDetected:!1}}}isAvailable(e){return this._enabled?this._selectProvider(e)!==void 0:!1}setEnabled(e){this._enabled=e}get enabled(){return this._enabled}registerProvider(e,t){this.providers.set(e,t)}setBlowfishApiKey(e){this.blowfishApiKey=e,this.providers.set("blowfish",new ht(e))}unregisterProvider(e){this.providers.delete(e)}_selectProvider(e){if(this._defaultProvider==="eth_call")return this.providers.get("eth_call");if(this._defaultProvider==="blowfish")return this.providers.get("blowfish");let t=this.providers.get("blowfish");return t&&t.isAvailable(e)?t:this.providers.get("eth_call")}_estimateChainId(e){return 0}_resolveRpcUrl(e){if(e>0)return be[`eip155:${e}`]}};function ed(n,e){let t=[];return n.status==="success"&&e==="reverted"&&t.push("Simulation predicted success but transaction reverted"),n.status==="reverted"&&e==="success"&&t.push("Simulation predicted revert but transaction succeeded"),{match:t.length===0,discrepancies:t.length>0?t:void 0}}sn();Tt();var In="naculus_auto_detected_tokens",td=10080*60*1e3;async function nd(n,e,t,r){if(!r?.skipCache){let d=await sd(n,e);if(d)return d}let s=n.startsWith("0x")?n:`0x${n}`,o="0x06fdde03",i="0x95d89b41",a="0x313ce567",[c,l,u]=await Promise.all([Vr(t,s,o),Vr(t,s,i),Vr(t,s,a)]),p={address:s,chainId:e,name:Si(c),symbol:Si(l),decimals:id(u),source:"auto-detect",tags:["custom"]};return await od(p),p}async function rd(){await lt("local","").remove(In)}async function sd(n,e){let t=lt("local","");try{let r=await t.get(In);if(!r)return null;let s=`${e}:${n.toLowerCase()}`,o=r[s];return!o||Date.now()-o.timestamp>td?null:o.token}catch{return null}}async function od(n){let e=lt("local","");try{let t=await e.get(In)??{},r=`${n.chainId}:${n.address.toLowerCase()}`;t[r]={token:n,timestamp:Date.now()},await e.set(In,t)}catch{}}async function Vr(n,e,t){let r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e,data:t},"latest"]})});if(!r.ok)throw new Error(`RPC call failed: HTTP ${r.status}`);let s=await r.json();if(s.error)throw new Error(`RPC error: ${s.error.message}`);return s.result}function Si(n){let e=n.startsWith("0x")?n.slice(2):n;if(e.length<128)try{let i=Buffer.from(e,"hex");return new TextDecoder().decode(i).replace(/\0/g,"")}catch{return""}let t=e.slice(64,128),r=parseInt(t,16);if(r<=0||r*2>e.length-128)return"";let s=e.slice(128,128+r*2),o=new Uint8Array(r);for(let i=0;i<r;i++)o[i]=parseInt(s.slice(i*2,i*2+2),16);return new TextDecoder().decode(o)}function id(n){let e=n.startsWith("0x")?n.slice(2):n;return parseInt(e||"0",16)}var Ci=[{chainId:1,address:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",name:"Wrapped Ether",symbol:"WETH",decimals:18,logoURI:"https://cryptologos.cc/logos/ethereum-eth-logo.png",tags:["wrapped","gas-token"]},{chainId:1,address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",name:"USD Coin",symbol:"USDC",decimals:6,logoURI:"https://cryptologos.cc/logos/usd-coin-usdc-logo.png",tags:["stablecoin"]},{chainId:1,address:"0xdAC17F958D2ee523a2206206994597C13D831ec7",name:"Tether USD",symbol:"USDT",decimals:6,logoURI:"https://cryptologos.cc/logos/tether-usdt-logo.png",tags:["stablecoin"]},{chainId:1,address:"0x6B175474E89094C44Da98b954EedeAC495271d0F",name:"Dai Stablecoin",symbol:"DAI",decimals:18,logoURI:"https://cryptologos.cc/logos/multi-collateral-dai-dai-logo.png",tags:["stablecoin"]},{chainId:1,address:"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",name:"Wrapped Bitcoin",symbol:"WBTC",decimals:8,logoURI:"https://cryptologos.cc/logos/wrapped-bitcoin-wbtc-logo.png",tags:["wrapped","btc"]},{chainId:1,address:"0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9",name:"Aave",symbol:"AAVE",decimals:18,logoURI:"https://cryptologos.cc/logos/aave-aave-logo.png",tags:["defi"]},{chainId:1,address:"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",name:"Uniswap",symbol:"UNI",decimals:18,logoURI:"https://cryptologos.cc/logos/uniswap-uni-logo.png",tags:["defi"]},{chainId:1,address:"0x514910771AF9Ca656af840dff83E8264EcF986CA",name:"ChainLink Token",symbol:"LINK",decimals:18,logoURI:"https://cryptologos.cc/logos/chainlink-link-logo.png",tags:["oracle"]},{chainId:1,address:"0x853d955aCEf822Db058eb8505911ED77F175b99e",name:"Frax",symbol:"FRAX",decimals:18,logoURI:"https://cryptologos.cc/logos/frax-frax-logo.png",tags:["stablecoin"]},{chainId:1,address:"0x4Fabb145d64652a948d72533023f6E7A623C7C53",name:"Binance USD",symbol:"BUSD",decimals:18,logoURI:"https://cryptologos.cc/logos/binance-usd-busd-logo.png",tags:["stablecoin"]},{chainId:1,address:"0xA0b73E1Ff0B80914AB6fe0444E65848C4C34450b",name:"Cronos Token",symbol:"CRO",decimals:8,logoURI:"https://cryptologos.cc/logos/crypto-com-coin-cro-logo.png",tags:[]},{chainId:1,address:"0x3845badAde8e6dFF049820680d1F14bD3903a5d0",name:"The Sandbox",symbol:"SAND",decimals:18,logoURI:"https://cryptologos.cc/logos/the-sandbox-sand-logo.png",tags:["gaming"]},{chainId:1,address:"0x0D8775F648430679A709E98d2b0Cb6250d2887EF",name:"Basic Attention Token",symbol:"BAT",decimals:18,logoURI:"https://cryptologos.cc/logos/basic-attention-token-bat-logo.png",tags:["privacy"]},{chainId:1,address:"0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0",name:"Polygon",symbol:"MATIC",decimals:18,logoURI:"https://cryptologos.cc/logos/polygon-matic-logo.png",tags:["layer2"]}],Ei=[{chainId:137,address:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",name:"Wrapped MATIC",symbol:"WMATIC",decimals:18,logoURI:"https://cryptologos.cc/logos/polygon-matic-logo.png",tags:["wrapped","gas-token"]},{chainId:137,address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",name:"USD Coin (PoS)",symbol:"USDC",decimals:6,logoURI:"https://cryptologos.cc/logos/usd-coin-usdc-logo.png",tags:["stablecoin"]},{chainId:137,address:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",name:"Tether USD (PoS)",symbol:"USDT",decimals:6,logoURI:"https://cryptologos.cc/logos/tether-usdt-logo.png",tags:["stablecoin"]},{chainId:137,address:"0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",name:"Dai Stablecoin (PoS)",symbol:"DAI",decimals:18,logoURI:"https://cryptologos.cc/logos/multi-collateral-dai-dai-logo.png",tags:["stablecoin"]},{chainId:137,address:"0x1BFd67037B42Cf73acF2047067bd4F2C47D9BfD6",name:"Wrapped BTC (PoS)",symbol:"WBTC",decimals:8,logoURI:"https://cryptologos.cc/logos/wrapped-bitcoin-wbtc-logo.png",tags:["wrapped","btc"]},{chainId:137,address:"0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",name:"Wrapped Ether (PoS)",symbol:"WETH",decimals:18,logoURI:"https://cryptologos.cc/logos/ethereum-eth-logo.png",tags:["wrapped"]},{chainId:137,address:"0x53E0bca35eC356BD5ddDFebbD1Fc0fD03FaBad39",name:"ChainLink Token (PoS)",symbol:"LINK",decimals:18,logoURI:"https://cryptologos.cc/logos/chainlink-link-logo.png",tags:["oracle"]}],_i=[{chainId:10,address:"0x4200000000000000000000000000000000000006",name:"Wrapped Ether",symbol:"WETH",decimals:18,logoURI:"https://cryptologos.cc/logos/ethereum-eth-logo.png",tags:["wrapped","gas-token"]},{chainId:10,address:"0x7F5c764cBc14f9669B88837ca1490cCa17c31607",name:"USD Coin (Optimism)",symbol:"USDC",decimals:6,logoURI:"https://cryptologos.cc/logos/usd-coin-usdc-logo.png",tags:["stablecoin"]},{chainId:10,address:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",name:"Tether USD (Optimism)",symbol:"USDT",decimals:6,logoURI:"https://cryptologos.cc/logos/tether-usdt-logo.png",tags:["stablecoin"]},{chainId:10,address:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",name:"Dai Stablecoin (Optimism)",symbol:"DAI",decimals:18,logoURI:"https://cryptologos.cc/logos/multi-collateral-dai-dai-logo.png",tags:["stablecoin"]},{chainId:10,address:"0x4200000000000000000000000000000000000042",name:"Optimism",symbol:"OP",decimals:18,logoURI:"https://cryptologos.cc/logos/optimism-ethereum-op-logo.png",tags:["layer2"]}],Ti=[{chainId:42161,address:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",name:"Wrapped Ether",symbol:"WETH",decimals:18,logoURI:"https://cryptologos.cc/logos/ethereum-eth-logo.png",tags:["wrapped","gas-token"]},{chainId:42161,address:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",name:"USD Coin (Arbitrum)",symbol:"USDC",decimals:6,logoURI:"https://cryptologos.cc/logos/usd-coin-usdc-logo.png",tags:["stablecoin"]},{chainId:42161,address:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",name:"Tether USD (Arbitrum)",symbol:"USDT",decimals:6,logoURI:"https://cryptologos.cc/logos/tether-usdt-logo.png",tags:["stablecoin"]},{chainId:42161,address:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",name:"Dai Stablecoin (Arbitrum)",symbol:"DAI",decimals:18,logoURI:"https://cryptologos.cc/logos/multi-collateral-dai-dai-logo.png",tags:["stablecoin"]},{chainId:42161,address:"0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f",name:"Wrapped BTC (Arbitrum)",symbol:"WBTC",decimals:8,logoURI:"https://cryptologos.cc/logos/wrapped-bitcoin-wbtc-logo.png",tags:["wrapped","btc"]},{chainId:42161,address:"0x912CE59144191C1204E64559FE8253a0e49E6548",name:"Arbitrum",symbol:"ARB",decimals:18,logoURI:"https://cryptologos.cc/logos/arbitrum-arb-logo.png",tags:["layer2"]}],Pi=[{chainId:8453,address:"0x4200000000000000000000000000000000000006",name:"Wrapped Ether",symbol:"WETH",decimals:18,logoURI:"https://cryptologos.cc/logos/ethereum-eth-logo.png",tags:["wrapped","gas-token"]},{chainId:8453,address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",name:"USD Coin (Base)",symbol:"USDC",decimals:6,logoURI:"https://cryptologos.cc/logos/usd-coin-usdc-logo.png",tags:["stablecoin"]},{chainId:8453,address:"0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA",name:"USD Base Coin",symbol:"USDbC",decimals:6,logoURI:"https://cryptologos.cc/logos/usd-coin-usdc-logo.png",tags:["stablecoin","bridged"]}],Ii={1:Ci,137:Ei,10:_i,42161:Ti,8453:Pi};function ki(){return Object.values(Ii).flat()}var Wr=[{name:"built-in",tokens:ki(),enabled:!0},{name:"uniswap-default",url:"https://tokens.uniswap.org",enabled:!0,refreshInterval:1440*60*1e3},{name:"coinbase",url:"https://api.coinbase.com/v2/tokens",enabled:!1,refreshInterval:1440*60*1e3}];var ad="naculus_token_list_cache",Ri=1440*60*1e3,cd=1e4,jr=class{config;tokens=[];sourceStatus=new Map;storage;constructor(e){this.config={sources:e?.sources??Wr,cacheKey:e?.cacheKey??ad,cacheTtl:e?.cacheTtl??Ri,sourcePriority:e?.sourcePriority,fetchTimeout:e?.fetchTimeout??cd},this.storage=lt("local","");for(let t of this.config.sources)this.sourceStatus.set(t.name,{name:t.name,enabled:t.enabled,state:"loading",tokenCount:0,lastUpdated:null})}async load(){let e=await this.loadFromCache();if(e&&!this.isCacheExpired(e.timestamp))return this.tokens=e.tokens,this.updateSourceStatuses("loaded"),this.tokens;let t=this.config.sources.filter(o=>o.enabled),r=await Promise.allSettled(t.map(o=>this.fetchSource(o))),s=[];for(let o=0;o<t.length;o++){let i=r[o],a=t[o];if(i.status==="fulfilled")s.push(...i.value),this.sourceStatus.set(a.name,{name:a.name,enabled:a.enabled,state:"loaded",tokenCount:i.value.length,lastUpdated:Date.now()});else{let c=await this.loadFromCache(),l=c?.tokens.filter(u=>u.source===a.name)??[];s.push(...l),this.sourceStatus.set(a.name,{name:a.name,enabled:a.enabled,state:"error",tokenCount:l.length,lastUpdated:c?.timestamp??null,error:i.reason instanceof Error?i.reason.message:String(i.reason)})}}return this.tokens=this.deduplicate(s),await this.saveToCache(this.tokens),this.tokens}async refresh(){return this.tokens=[],this.load()}getTokens(e){let t=this.tokens;return e?.chainId!==void 0&&(t=t.filter(r=>r.chainId===e.chainId)),e?.source!==void 0&&(t=t.filter(r=>r.source===e.source)),t}search(e,t){let r=t?.limit??20,s=e.trim().toLowerCase();if(!s)return{exact:[],fuzzy:[],hasMore:!1};let o=[],i=[],a=this.tokens;t?.chainId!==void 0&&(a=a.filter(h=>h.chainId===t.chainId));let c=/^0x[0-9a-fA-F]{40}$/.test(s)||/^0x[0-9a-fA-F]{40}$/.test(e.trim());for(let h of a){if(c){h.address.toLowerCase()===s&&o.push({token:h,score:1,matchField:"address"});continue}let g=h.symbol.toLowerCase(),w=h.name.toLowerCase();if(g===s){o.push({token:h,score:1,matchField:"symbol"});continue}if(w===s){o.push({token:h,score:.95,matchField:"name"});continue}if(g.startsWith(s)){i.push({token:h,score:.8,matchField:"symbol"});continue}if(w.includes(s)){i.push({token:h,score:.6,matchField:"name"});continue}g.includes(s)&&i.push({token:h,score:.4,matchField:"symbol"})}o.sort((h,g)=>g.score-h.score),i.sort((h,g)=>g.score-h.score);let u=o.length+i.length>r,p=o.slice(0,Math.min(o.length,Math.ceil(r/2))),d=r-p.length,f=i.slice(0,d);return{exact:p,fuzzy:f,hasMore:u}}getToken(e,t){return this.tokens.find(r=>r.address.toLowerCase()===e.toLowerCase()&&r.chainId===t)}clearCache(){this.tokens=[],this.storage.remove(this.config.cacheKey),this.sourceStatus.clear()}getSourcesStatus(){return Array.from(this.sourceStatus.values())}async fetchSource(e){if(e.tokens&&e.tokens.length>0)return e.tokens.map(s=>({...s,source:e.name}));if(!e.url)return[];let t=new AbortController,r=setTimeout(()=>t.abort(),this.config.fetchTimeout);try{let s=await fetch(e.url,{signal:t.signal});if(!s.ok)throw new Error(`Failed to fetch token list "${e.name}": HTTP ${s.status}`);let o=s.headers.get("content-type")??"",i;if(o.includes("application/json")||o.includes("text/plain"))i=await s.json();else{let c=await s.text();i=JSON.parse(c)}let a;return Array.isArray(i)?a=i:i&&typeof i=="object"?a=i.tokens??[]:a=[],e.chainFilter&&e.chainFilter.length>0&&(a=a.filter(c=>e.chainFilter.includes(c.chainId))),a.map(c=>({...c,source:e.name}))}finally{clearTimeout(r)}}deduplicate(e){let t=new Map,r=this.config.sourcePriority??this.config.sources.map(s=>s.name);for(let s of e){let o=`${s.chainId}:${s.address.toLowerCase()}`,i=t.get(o);if(!i){t.set(o,s);continue}let a=r.indexOf(i.source??""),c=r.indexOf(s.source??"");c>=0&&(a<0||c<a)&&t.set(o,s)}return Array.from(t.values())}async loadFromCache(){try{return await this.storage.get(this.config.cacheKey)}catch{return null}}async saveToCache(e){try{await this.storage.set(this.config.cacheKey,{timestamp:Date.now(),tokens:e})}catch{}}isCacheExpired(e){return Date.now()-e>(this.config.cacheTtl??Ri)}updateSourceStatuses(e){for(let[t,r]of this.sourceStatus)r.state=e,r.tokenCount=this.tokens.filter(s=>s.source===t).length,r.lastUpdated=Date.now()}};var ld=8;function dd(n){return parseInt(n.split(":")[1]??"0",10)}async function ud(n,e){let t=dd(n),s=Qn[t]?.chainlinkEthUsdFeed;if(!s||!e)return null;let o=[{inputs:[],name:"latestRoundData",outputs:[{name:"roundId",type:"uint80"},{name:"answer",type:"int256"},{name:"startedAt",type:"uint256"},{name:"updatedAt",type:"uint256"},{name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];try{let i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:s,data:"0xfeaf968c"},"latest"]}),signal:AbortSignal.timeout(5e3)});if(!i.ok)return null;let a=await i.json();if(a.error)return null;let c=a.result;if(!c)return null;let l=c.startsWith("0x")?c.slice(2):c,u=BigInt("0x"+l.slice(64,128));return Number(u)/10**ld}catch{return null}}export{Yr as AA_ERROR_MESSAGES,Vt as AA_SUPPORTED_CHAINS,Ti as ARBITRUM_TOKENS,e0 as AUTO_RECONNECT_TIMEOUT_MS,R as AccountAbstractionError,qn as AutoReconnectManager,tn as AxelarProvider,Pi as BASE_TOKENS,ht as BlowfishProvider,Qn as CHAINS,Au as CONNECTOR_ERROR_MESSAGES,Q as ChainAbstractionError,Jn as ConnectorManager,Ii as DEFAULT_BUILTIN_TOKENS,fe as DEFAULT_CALL_GAS_LIMIT,Oi as DEFAULT_ENTRY_POINT,Wu as DEFAULT_EVM_CHAIN,Qu as DEFAULT_NONCE_LENGTH,le as DEFAULT_PRE_VERIFICATION_GAS,be as DEFAULT_RPC_URLS,Sn as DEFAULT_SESSION_KEY_CONFIG,ju as DEFAULT_SOLANA_CLUSTER,Wr as DEFAULT_SOURCES,pe as DEFAULT_VERIFICATION_GAS_LIMIT,qu as DEFAULT_XRPL_NETWORK,Ou as EIP155_ARBITRUM,Nu as EIP155_ARBITRUM_GOERLI,Mu as EIP155_BASE,Bu as EIP155_GOERLI,xc as EIP155_MAINNET,Lu as EIP155_MUMBAI,Fu as EIP155_OPTIMISM,Hu as EIP155_OPTIMISM_GOERLI,Du as EIP155_POLYGON,Uu as EIP155_SEPOLIA,It as ENSProvider,Kt as ENTRY_POINT_V0_6,xt as ENTRY_POINT_V0_7,G as ERC20TokenError,yt as ERC20TokenHelper,ge as ERC20_FUNCTION_SIGNATURES,Yl as ERC20_MIN_ABI,Ci as ETHEREUM_MAINNET_TOKENS,Ht as EthCallProvider,er as FEE_ERROR_MESSAGES,Ge as FeeEstimationError,rr as InAppChannel,rn as LiFiProvider,Je as LocalStorageAdapter,Oo as LocalStorageSessionStorage,et as MemoryStorageAdapter,gc as NAMESPACE_EIP155,mc as NAMESPACE_SOLANA,yc as NAMESPACE_XRPL,fr as NameResolver,or as NoopChannel,hr as NoopStorageAdapter,ir as Notifier,_i as OPTIMISM_TOKENS,Ei as POLYGON_TOKENS,ot as PaymasterService,q as ResolutionError,Pt as ResolverCache,on as RouteEngine,yi as SESSION_ERROR_MESSAGES,Fo as SESSION_KEY_ERROR_MESSAGES,Ju as SESSION_TIMEOUT_MS,Ce as SIMPLE_ACCOUNT_FACTORY,kt as SNSProvider,$u as SOLANA_DEVNET,bc as SOLANA_MAINNET,Gu as SOLANA_TESTNET,Zu as STORAGE_KEYS,Ru as SUPPORTED_NAMESPACES,Ot as SessionEventEmitter,Or as SessionKeyManager,Lt as SessionKeyStorage,En as SessionManager,Nt as SessionPersistence,pr as SessionStorageAdapter,Kr as SimulationManager,jn as SmartAccountManager,he as StorageError,sr as TelegramChannel,jr as TokenListManager,Xu as WC_DISCONNECT_SESSION_EXPIRED,Yu as WC_DISCONNECT_TIMEOUT,zu as WC_DISCONNECT_USER,ke as WalletError,Vu as XRPL_DEVNET,wc as XRPL_MAINNET,Ku as XRPL_TESTNET,rt as abiEncodeAddress,Pn as abiEncodeFunctionCall,Tn as abiEncodeUint256,$r as abiFunctionSelector,Da as buildCallData,Vn as buildUserOperation,rd as clearAutoDetectCache,Tc as clearChainFeeEstimators,ed as compareSimulationVsActual,zd as createAutoReconnectManager,Iu as createConnectorManager,sf as createEmptySession,Li as createPaymasterService,hc as createRouteEngine,De as createSessionError,ae as createSessionKeyError,Rl as createSessionManager,Nr as createSessionPersistence,lt as createStorageAdapter,Za as decodeGasLimits,Lr as decryptPrivateKey,Eu as detectPlatform,nd as detectTokenInfo,ao as encodeGasLimits,Dr as encryptPrivateKey,tr as estimateFees,an as estimateMaxPriorityFeePerGas,Wa as estimateUserOperationGas,yu as extractAccounts,x0 as extractAccountsFromPermissions,Qe as formatUnits,ki as getAllBuiltinTokens,Pc as getChainId,xu as getChainsFromNamespaces,wu as getEventsFromNamespaces,Ic as getFeeData,vo as getGasPrice,cn as getLatestBaseFee,bu as getMethodsFromNamespaces,ud as getNativeTokenPriceUsd,m0 as getPermissions,v0 as getRpcUrl,b0 as hasPermission,oo as hashUserOperation,Di as isAAError,Wd as isBurnAddress,lc as isChainAbstractionError,cc as isERC20TokenError,Cc as isFeeEstimationError,bo as isMobileBrowser,No as isSessionExpired,jd as isValidAddress,Su as isWalletError,Vd as isZeroAddress,O as logger,Ac as parseBigInt,Ft as parseChainId,Ze as parseUnits,Ec as registerChainFeeEstimator,y0 as requestPermissions,Va as sendUserOperation,tc as setLogLevel,nc as setLogSink,Ga as signUserOperation,vc as toDecString,Sc as toHumanReadable,_c as unregisterChainFeeEstimator,of as updateSession,Cn as validateChainId};
5
+ /*! Bundled license information:
6
+
7
+ @noble/hashes/utils.js:
8
+ @noble/hashes/esm/utils.js:
9
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
10
+
11
+ @noble/curves/esm/utils.js:
12
+ @noble/curves/esm/abstract/modular.js:
13
+ @noble/curves/esm/abstract/curve.js:
14
+ @noble/curves/esm/abstract/weierstrass.js:
15
+ @noble/curves/esm/_shortw_utils.js:
16
+ @noble/curves/esm/secp256k1.js:
17
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
18
+ */
19
+ //# sourceMappingURL=index.js.map