@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/LICENSE +21 -0
- package/dist/index.cjs +19 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3884 -0
- package/dist/index.d.ts +3884 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/package.json +29 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Naculus
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";var ha=Object.create;var en=Object.defineProperty;var ga=Object.getOwnPropertyDescriptor;var ma=Object.getOwnPropertyNames;var ya=Object.getPrototypeOf,xa=Object.prototype.hasOwnProperty;var ct=(n,e)=>()=>(n&&(e=n(n=0)),e);var tn=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),nn=(n,e)=>{for(var t in e)en(n,t,{get:e[t],enumerable:!0})},fs=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ma(e))!xa.call(n,s)&&s!==t&&en(n,s,{get:()=>e[s],enumerable:!(r=ga(e,s))||r.enumerable});return n};var ba=(n,e,t)=>(t=n!=null?ha(ya(n)):{},fs(e||!n||!n.__esModule?en(t,"default",{value:n,enumerable:!0}):t,n)),wa=n=>fs(en({},"__esModule",{value:!0}),n);var Ns=tn(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=ks;P.fromBig=nr;P.split=ms;var rn=BigInt(2**32-1),tr=BigInt(32);function nr(n,e=!1){return e?{h:Number(n&rn),l:Number(n>>tr&rn)}:{h:Number(n>>tr&rn)|0,l:Number(n&rn)|0}}function ms(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}=nr(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var ys=(n,e)=>BigInt(n>>>0)<<tr|BigInt(e>>>0);P.toBig=ys;var xs=(n,e,t)=>n>>>t;P.shrSH=xs;var bs=(n,e,t)=>n<<32-t|e>>>t;P.shrSL=bs;var ws=(n,e,t)=>n>>>t|e<<32-t;P.rotrSH=ws;var vs=(n,e,t)=>n<<32-t|e>>>t;P.rotrSL=vs;var As=(n,e,t)=>n<<64-t|e>>>t-32;P.rotrBH=As;var Ss=(n,e,t)=>n>>>t-32|e<<64-t;P.rotrBL=Ss;var Cs=(n,e)=>e;P.rotr32H=Cs;var Es=(n,e)=>n;P.rotr32L=Es;var _s=(n,e,t)=>n<<t|e>>>32-t;P.rotlSH=_s;var Ts=(n,e,t)=>e<<t|n>>>32-t;P.rotlSL=Ts;var Ps=(n,e,t)=>e<<t-32|n>>>64-t;P.rotlBH=Ps;var Is=(n,e,t)=>n<<t-32|e>>>64-t;P.rotlBL=Is;function ks(n,e,t,r){let s=(e>>>0)+(r>>>0);return{h:n+t+(s/2**32|0)|0,l:s|0}}var Rs=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0);P.add3L=Rs;var Bs=(n,e,t,r)=>e+t+r+(n/2**32|0)|0;P.add3H=Bs;var Us=(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0);P.add4L=Us;var Ds=(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0;P.add4H=Ds;var Ls=(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0);P.add5L=Ls;var Os=(n,e,t,r,s,o)=>e+t+r+s+o+(n/2**32|0)|0;P.add5H=Os;var va={fromBig:nr,split:ms,toBig:ys,shrSH:xs,shrSL:bs,rotrSH:ws,rotrSL:vs,rotrBH:As,rotrBL:Ss,rotr32H:Cs,rotr32L:Es,rotlSH:_s,rotlSL:Ts,rotlBH:Ps,rotlBL:Is,add:ks,add3L:Rs,add3H:Bs,add4L:Us,add4H:Ds,add5H:Os,add5L:Ls};P.default=va});var Fs=tn(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.crypto=void 0;var Ne=require("crypto");sn.crypto=Ne&&typeof Ne=="object"&&"webcrypto"in Ne?Ne.webcrypto:Ne&&typeof Ne=="object"&&"randomBytes"in Ne?Ne:void 0});var ar=tn(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=Ms;C.anumber=rr;C.abytes=ut;C.ahash=Aa;C.aexists=Sa;C.aoutput=Ca;C.u8=Ea;C.u32=_a;C.clean=Ta;C.createView=Pa;C.rotr=Ia;C.rotl=ka;C.byteSwap=or;C.byteSwap32=$s;C.bytesToHex=Ba;C.hexToBytes=Ua;C.asyncLoop=La;C.utf8ToBytes=ir;C.bytesToUtf8=Oa;C.toBytes=on;C.kdfInputToBytes=Na;C.concatBytes=Fa;C.checkOpts=Ha;C.createHasher=Ks;C.createOptHasher=Vs;C.createXOFer=Ws;C.randomBytes=Ma;var dt=Fs();function Ms(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function rr(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function ut(n,...e){if(!Ms(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 Aa(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");rr(n.outputLen),rr(n.blockLen)}function Sa(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 Ca(n,e){ut(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Ea(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function _a(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function Ta(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function Pa(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Ia(n,e){return n<<32-e|n>>>e}function ka(n,e){return n<<e|n>>>32-e>>>0}C.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function or(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}C.swap8IfBE=C.isLE?n=>n:n=>or(n);C.byteSwapIfBE=C.swap8IfBE;function $s(n){for(let e=0;e<n.length;e++)n[e]=or(n[e]);return n}C.swap32IfBE=C.isLE?n=>n:$s;var Gs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ra=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function Ba(n){if(ut(n),Gs)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Ra[n[t]];return e}var Te={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hs(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 Ua(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(Gs)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=Hs(n.charCodeAt(o)),a=Hs(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 Da=async()=>{};C.nextTick=Da;async function La(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 ir(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function Oa(n){return new TextDecoder().decode(n)}function on(n){return typeof n=="string"&&(n=ir(n)),ut(n),n}function Na(n){return typeof n=="string"&&(n=ir(n)),ut(n),n}function Fa(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];ut(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 Ha(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 sr=class{};C.Hash=sr;function Ks(n){let e=r=>n().update(on(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function Vs(n){let e=(r,s)=>n(s).update(on(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}function Ws(n){let e=(r,s)=>n(s).update(on(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}C.wrapConstructor=Ks;C.wrapConstructorWithOpts=Vs;C.wrapXOFConstructorWithOpts=Ws;function Ma(n=32){if(dt.crypto&&typeof dt.crypto.getRandomValues=="function")return dt.crypto.getRandomValues(new Uint8Array(n));if(dt.crypto&&typeof dt.crypto.randomBytes=="function")return Uint8Array.from(dt.crypto.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}});var eo=tn(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=Qs;var kt=Ns(),Z=ar(),$a=BigInt(0),It=BigInt(1),Ga=BigInt(2),Ka=BigInt(7),Va=BigInt(256),Wa=BigInt(113),zs=[],Ys=[],Xs=[];for(let n=0,e=It,t=1,r=0;n<24;n++){[t,r]=[r,(2*t+3*r)%5],zs.push(2*(5*r+t)),Ys.push((n+1)*(n+2)/2%64);let s=$a;for(let o=0;o<7;o++)e=(e<<It^(e>>Ka)*Wa)%Va,e&Ga&&(s^=It<<(It<<BigInt(o))-It);Xs.push(s)}var Zs=(0,kt.split)(Xs,!0),ja=Zs[0],qa=Zs[1],js=(n,e,t)=>t>32?(0,kt.rotlBH)(n,e,t):(0,kt.rotlSH)(n,e,t),qs=(n,e,t)=>t>32?(0,kt.rotlBL)(n,e,t):(0,kt.rotlSL)(n,e,t);function Qs(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=js(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=Ys[i],c=js(s,o,a),l=qs(s,o,a),u=zs[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]^=ja[r],n[1]^=qa[r]}(0,Z.clean)(t)}var Rt=class n extends Z.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,Z.anumber)(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=(0,Z.u32)(this.state)}clone(){return this._cloneInto()}keccak(){(0,Z.swap32IfBE)(this.state32),Qs(this.state32,this.rounds),(0,Z.swap32IfBE)(this.state32),this.posOut=0,this.pos=0}update(e){(0,Z.aexists)(this),e=(0,Z.toBytes)(e),(0,Z.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,Z.aexists)(this,!1),(0,Z.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,Z.anumber)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,Z.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,Z.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=Rt;var Fe=(n,e,t)=>(0,Z.createHasher)(()=>new Rt(e,n,t));H.sha3_224=Fe(6,144,224/8);H.sha3_256=Fe(6,136,256/8);H.sha3_384=Fe(6,104,384/8);H.sha3_512=Fe(6,72,512/8);H.keccak_224=Fe(1,144,224/8);H.keccak_256=Fe(1,136,256/8);H.keccak_384=Fe(1,104,384/8);H.keccak_512=Fe(1,72,512/8);var Js=(n,e,t)=>(0,Z.createXOFer)((r={})=>new Rt(e,n,r.dkLen===void 0?t:r.dkLen,!0));H.shake128=Js(31,168,128/8);H.shake256=Js(31,136,256/8)});function za(n,e=!1){return e?{h:Number(n&an),l:Number(n>>to&an)}:{h:Number(n>>to&an)|0,l:Number(n&an)|0}}function no(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}=za(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var an,to,ro,so,oo,io,ao=ct(()=>{"use strict";an=BigInt(4294967295),to=BigInt(32);ro=(n,e,t)=>n<<t|e>>>32-t,so=(n,e,t)=>e<<t|n>>>32-t,oo=(n,e,t)=>e<<t-32|n>>>64-t,io=(n,e,t)=>n<<t-32|e>>>64-t});var Pe,et,co=ct(()=>{"use strict";Pe=ba(require("crypto"),1),et=Pe&&typeof Pe=="object"&&"webcrypto"in Pe?Pe.webcrypto:Pe&&typeof Pe=="object"&&"randomBytes"in Pe?Pe:void 0});var fr={};nn(fr,{Hash:()=>ke,abytes:()=>Q,aexists:()=>xe,ahash:()=>tt,anumber:()=>ae,aoutput:()=>Bt,asyncLoop:()=>go,byteSwap:()=>dr,byteSwap32:()=>fo,byteSwapIfBE:()=>Za,bytesToHex:()=>D,bytesToUtf8:()=>mo,checkOpts:()=>ur,clean:()=>ce,concatBytes:()=>z,createHasher:()=>ft,createOptHasher:()=>yo,createView:()=>nt,createXOFer:()=>un,hexToBytes:()=>G,isBytes:()=>He,isLE:()=>lr,kdfInputToBytes:()=>dn,nextTick:()=>ho,randomBytes:()=>we,rotl:()=>Xa,rotr:()=>fe,swap32IfBE:()=>cn,swap8IfBE:()=>uo,toBytes:()=>be,u32:()=>cr,u8:()=>Ya,utf8ToBytes:()=>ln,wrapConstructor:()=>Ja,wrapConstructorWithOpts:()=>ec,wrapXOFConstructorWithOpts:()=>tc});function He(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function ae(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Q(n,...e){if(!He(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 tt(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ae(n.outputLen),ae(n.blockLen)}function xe(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 Bt(n,e){Q(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Ya(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function cr(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function ce(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function nt(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function fe(n,e){return n<<32-e|n>>>e}function Xa(n,e){return n<<e|n>>>32-e>>>0}function dr(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function fo(n){for(let e=0;e<n.length;e++)n[e]=dr(n[e]);return n}function D(n){if(Q(n),po)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Qa[n[t]];return e}function lo(n){if(n>=Ie._0&&n<=Ie._9)return n-Ie._0;if(n>=Ie.A&&n<=Ie.F)return n-(Ie.A-10);if(n>=Ie.a&&n<=Ie.f)return n-(Ie.a-10)}function G(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(po)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=lo(n.charCodeAt(o)),a=lo(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 go(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 ho(),r+=o)}}function ln(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function mo(n){return new TextDecoder().decode(n)}function be(n){return typeof n=="string"&&(n=ln(n)),Q(n),n}function dn(n){return typeof n=="string"&&(n=ln(n)),Q(n),n}function z(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];Q(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 ur(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 ft(n){let e=r=>n().update(be(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function yo(n){let e=(r,s)=>n(s).update(be(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}function un(n){let e=(r,s)=>n(s).update(be(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}function we(n=32){if(et&&typeof et.getRandomValues=="function")return et.getRandomValues(new Uint8Array(n));if(et&&typeof et.randomBytes=="function")return Uint8Array.from(et.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}var lr,uo,Za,cn,po,Qa,Ie,ho,ke,Ja,ec,tc,te=ct(()=>{"use strict";co();lr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;uo=lr?n=>n:n=>dr(n),Za=uo;cn=lr?n=>n:fo,po=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qa=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));Ie={_0:48,_9:57,A:65,F:70,a:97,f:102};ho=async()=>{};ke=class{};Ja=ft,ec=yo,tc=un});var pr={};nn(pr,{Keccak:()=>Dt,keccakP:()=>Co,keccak_224:()=>pc,keccak_256:()=>Lt,keccak_384:()=>hc,keccak_512:()=>gc,sha3_224:()=>lc,sha3_256:()=>dc,sha3_384:()=>uc,sha3_512:()=>fc,shake128:()=>mc,shake256:()=>yc});function Co(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=xo(l,u,1)^t[a],d=bo(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=vo[i],c=xo(s,o,a),l=bo(s,o,a),u=wo[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]^=ac[r],n[1]^=cc[r]}ce(t)}var nc,Ut,rc,sc,oc,ic,wo,vo,Ao,So,ac,cc,xo,bo,Dt,Me,lc,dc,uc,fc,pc,Lt,hc,gc,Eo,mc,yc,fn=ct(()=>{"use strict";ao();te();nc=BigInt(0),Ut=BigInt(1),rc=BigInt(2),sc=BigInt(7),oc=BigInt(256),ic=BigInt(113),wo=[],vo=[],Ao=[];for(let n=0,e=Ut,t=1,r=0;n<24;n++){[t,r]=[r,(2*t+3*r)%5],wo.push(2*(5*r+t)),vo.push((n+1)*(n+2)/2%64);let s=nc;for(let o=0;o<7;o++)e=(e<<Ut^(e>>sc)*ic)%oc,e&rc&&(s^=Ut<<(Ut<<BigInt(o))-Ut);Ao.push(s)}So=no(Ao,!0),ac=So[0],cc=So[1],xo=(n,e,t)=>t>32?oo(n,e,t):ro(n,e,t),bo=(n,e,t)=>t>32?io(n,e,t):so(n,e,t);Dt=class n extends ke{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,ae(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=cr(this.state)}clone(){return this._cloneInto()}keccak(){cn(this.state32),Co(this.state32,this.rounds),cn(this.state32),this.posOut=0,this.pos=0}update(e){xe(this),e=be(e),Q(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){xe(this,!1),Q(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 ae(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Bt(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,ce(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}},Me=(n,e,t)=>ft(()=>new Dt(e,n,t)),lc=Me(6,144,224/8),dc=Me(6,136,256/8),uc=Me(6,104,384/8),fc=Me(6,72,512/8),pc=Me(1,144,224/8),Lt=Me(1,136,256/8),hc=Me(1,104,384/8),gc=Me(1,72,512/8),Eo=(n,e,t)=>un((r={})=>new Dt(e,n,r.dkLen===void 0?t:r.dkLen,!0)),mc=Eo(31,168,128/8),yc=Eo(31,136,256/8)});function $o(n){return n instanceof $}var Gc,$,xn=ct(()=>{"use strict";Gc={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."},$=class extends Error{constructor(t,r,s){super(r??Gc[t]);this.code=t;this.cause=s;this.name="ERC20TokenError"}code;cause;hasCode(t){return this.code===t}}});var Go={};nn(Go,{formatUnits:()=>Ve,parseUnits:()=>Ke});function Ke(n,e){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new $("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 $("invalid_amount",`Amount is not a finite number: ${n}`);if(n<0)throw new $("invalid_amount",`Amount must be non-negative, got: ${n}`);t=n.toString()}else t=n.trim();if(t===""||t===".")throw new $("invalid_amount",`Amount string is empty or invalid: "${n}"`);if(!/^[0-9]*\.?[0-9]*$/.test(t))throw new $("invalid_amount",`Amount contains invalid characters: "${n}"`);if(t.startsWith("-"))throw new $("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 $("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 $("invalid_amount",`Failed to parse amount as bigint: "${n}"`)}}function Ve(n,e){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new $("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 Ht=ct(()=>{"use strict";xn()});var cu={};nn(cu,{AA_ERROR_MESSAGES:()=>er,AA_SUPPORTED_CHAINS:()=>Pt,ARBITRUM_TOKENS:()=>is,AUTO_RECONNECT_TIMEOUT_MS:()=>Cl,AccountAbstractionError:()=>R,AutoReconnectManager:()=>mn,AxelarProvider:()=>Nt,BASE_TOKENS:()=>as,BlowfishProvider:()=>it,CHAINS:()=>bn,CONNECTOR_ERROR_MESSAGES:()=>Zc,ChainAbstractionError:()=>Y,ConnectorManager:()=>wn,DEFAULT_BUILTIN_TOKENS:()=>cs,DEFAULT_CALL_GAS_LIMIT:()=>de,DEFAULT_ENTRY_POINT:()=>gs,DEFAULT_EVM_CHAIN:()=>gl,DEFAULT_NONCE_LENGTH:()=>Al,DEFAULT_PRE_VERIFICATION_GAS:()=>ie,DEFAULT_RPC_URLS:()=>me,DEFAULT_SESSION_KEY_CONFIG:()=>qt,DEFAULT_SOLANA_CLUSTER:()=>ml,DEFAULT_SOURCES:()=>Qn,DEFAULT_VERIFICATION_GAS_LIMIT:()=>ue,DEFAULT_XRPL_NETWORK:()=>yl,EIP155_ARBITRUM:()=>il,EIP155_ARBITRUM_GOERLI:()=>al,EIP155_BASE:()=>dl,EIP155_GOERLI:()=>nl,EIP155_MAINNET:()=>Xo,EIP155_MUMBAI:()=>ol,EIP155_OPTIMISM:()=>cl,EIP155_OPTIMISM_GOERLI:()=>ll,EIP155_POLYGON:()=>sl,EIP155_SEPOLIA:()=>rl,ENSProvider:()=>ht,ENTRY_POINT_V0_6:()=>Tt,ENTRY_POINT_V0_7:()=>lt,ERC20TokenError:()=>$,ERC20TokenHelper:()=>at,ERC20_FUNCTION_SIGNATURES:()=>ge,ERC20_MIN_ABI:()=>ra,ETHEREUM_MAINNET_TOKENS:()=>rs,EthCallProvider:()=>Ct,FEE_ERROR_MESSAGES:()=>vn,FeeEstimationError:()=>Be,InAppChannel:()=>En,LiFiProvider:()=>Ft,LocalStorageAdapter:()=>je,LocalStorageSessionStorage:()=>Ir,MemoryStorageAdapter:()=>qe,NAMESPACE_EIP155:()=>qo,NAMESPACE_SOLANA:()=>zo,NAMESPACE_XRPL:()=>Yo,NameResolver:()=>Bn,NoopChannel:()=>Tn,NoopStorageAdapter:()=>Dn,Notifier:()=>Pn,OPTIMISM_TOKENS:()=>os,POLYGON_TOKENS:()=>ss,PaymasterService:()=>Je,ResolutionError:()=>W,ResolverCache:()=>pt,RouteEngine:()=>Mt,SESSION_ERROR_MESSAGES:()=>Zr,SESSION_KEY_ERROR_MESSAGES:()=>Rr,SESSION_TIMEOUT_MS:()=>Sl,SIMPLE_ACCOUNT_FACTORY:()=>ye,SNSProvider:()=>gt,SOLANA_DEVNET:()=>ul,SOLANA_MAINNET:()=>Zo,SOLANA_TESTNET:()=>fl,STORAGE_KEYS:()=>vl,SUPPORTED_NAMESPACES:()=>tl,SessionEventEmitter:()=>vt,SessionKeyManager:()=>jn,SessionKeyStorage:()=>wt,SessionManager:()=>Yt,SessionPersistence:()=>At,SessionStorageAdapter:()=>Un,SimulationManager:()=>Xn,SmartAccountManager:()=>gn,StorageError:()=>pe,TelegramChannel:()=>_n,TokenListManager:()=>Jn,WC_DISCONNECT_SESSION_EXPIRED:()=>wl,WC_DISCONNECT_TIMEOUT:()=>bl,WC_DISCONNECT_USER:()=>xl,WalletError:()=>ve,XRPL_DEVNET:()=>hl,XRPL_MAINNET:()=>Qo,XRPL_TESTNET:()=>pl,abiEncodeAddress:()=>Ze,abiEncodeFunctionCall:()=>Zt,abiEncodeUint256:()=>Xt,abiFunctionSelector:()=>Yn,buildCallData:()=>_o,buildUserOperation:()=>hn,clearAutoDetectCache:()=>ua,clearChainFeeEstimators:()=>ii,compareSimulationVsActual:()=>ca,createAutoReconnectManager:()=>Nc,createConnectorManager:()=>el,createEmptySession:()=>Ql,createPaymasterService:()=>hs,createRouteEngine:()=>jo,createSessionError:()=>Ce,createSessionKeyError:()=>oe,createSessionManager:()=>ta,createSessionPersistence:()=>qn,createStorageAdapter:()=>rt,decodeGasLimits:()=>Ro,decryptPrivateKey:()=>Wn,detectPlatform:()=>Jc,detectTokenInfo:()=>da,encodeGasLimits:()=>mr,encryptPrivateKey:()=>Vn,estimateFees:()=>Cn,estimateMaxPriorityFeePerGas:()=>$t,estimateUserOperationGas:()=>Io,extractAccounts:()=>qc,extractAccountsFromPermissions:()=>kl,formatUnits:()=>Ve,getAllBuiltinTokens:()=>ls,getChainId:()=>ai,getChainsFromNamespaces:()=>zc,getEventsFromNamespaces:()=>Xc,getFeeData:()=>ci,getGasPrice:()=>Ar,getLatestBaseFee:()=>Gt,getMethodsFromNamespaces:()=>Yc,getNativeTokenPriceUsd:()=>pa,getPermissions:()=>Pl,getRpcUrl:()=>Bl,hasPermission:()=>Rl,hashUserOperation:()=>hr,isAAError:()=>ps,isBurnAddress:()=>Lc,isChainAbstractionError:()=>Ko,isERC20TokenError:()=>$o,isFeeEstimationError:()=>ni,isMobileBrowser:()=>vr,isSessionExpired:()=>kr,isValidAddress:()=>Oc,isWalletError:()=>Qc,isZeroAddress:()=>Dc,logger:()=>O,parseBigInt:()=>ei,parseChainId:()=>St,parseUnits:()=>Ke,registerChainFeeEstimator:()=>si,requestPermissions:()=>Il,sendUserOperation:()=>Po,setLogLevel:()=>Uo,setLogSink:()=>Do,signUserOperation:()=>To,toDecString:()=>Jo,toHumanReadable:()=>ti,unregisterChainFeeEstimator:()=>oi,updateSession:()=>Jl,validateChainId:()=>zt});module.exports=wa(cu);var er={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??er[t]);this.code=t;this.cause=s;this.name="AccountAbstractionError"}code;cause;hasCode(t){return this.code===t}};function ps(n){return n instanceof R}var Je=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 hs(n){return new Je({url:n.url,type:n.type,policy:n.policy})}var Tt="0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",lt="0x0000000071727De22E5E9d8BAf0edAc6f37da032",gs=lt,ye="0x9406Cc6185a346906296840746125a0E44976454",de=100000n,ue=100000n,ie=50000n,Pt={"eip155:1":{entryPoint:lt,factory:ye},"eip155:137":{entryPoint:Tt,factory:ye},"eip155:10":{entryPoint:Tt,factory:ye},"eip155:42161":{entryPoint:Tt,factory:ye},"eip155:8453":{entryPoint:lt,factory:ye},"eip155:11155111":{entryPoint:lt,factory:ye}};function hn(n){return{sender:n.sender??"0x",nonce:n.nonce??0n,initCode:n.initCode??"0x",callData:n.callData??"0x",accountGasLimits:n.accountGasLimits??Cc(ue,de),preVerificationGas:n.preVerificationGas??ie,maxFeePerGas:n.maxFeePerGas??0n,maxPriorityFeePerGas:n.maxPriorityFeePerGas??0n,paymasterAndData:n.paymasterAndData??"0x",signature:n.signature??"0x"}}function _o(n){if(!n.length)throw new R("aa_no_calls");return n.length===1?xc(n[0].to,n[0].value,n[0].data):bc(n)}function xc(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 bc(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 wc(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=Re(s("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")),a=Re(s("Account")),c=Re(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),Re(t(i,a,c,d,h))}function hr(n,e,t){let{sender:r,nonce:s,initCode:o,callData:i,accountGasLimits:a,preVerificationGas:c,maxFeePerGas:l,maxPriorityFeePerGas:u,paymasterAndData:p}=n,d=vc({sender:r,nonce:s,initCode:o,callData:i,accountGasLimits:a,preVerificationGas:c,maxFeePerGas:l,maxPriorityFeePerGas:u,paymasterAndData:p}),f=Re(d),h=wc(e,t),{concatBytes:g}={concatBytes:(...k)=>{let N=k.reduce((_e,Oe)=>_e+Oe.length,0),re=new Uint8Array(N),Ee=0;for(let _e of k)re.set(_e,Ee),Ee+=_e.length;return re}},w=new Uint8Array([25,1]),S=Re(g(w,h,f)),{bytesToHex:M}=Sc();return`0x${M(S)}`}function vc(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),Re(r(n.initCode)),Re(r(n.callData)),r(n.accountGasLimits),s(n.preVerificationGas),s(n.maxFeePerGas),s(n.maxPriorityFeePerGas),Re(r(n.paymasterAndData)))}function Re(n){let{keccak_256:e}=Ac();return e(n)}var pn=null;function Ac(){if(pn)return{keccak_256:pn};try{pn=eo().keccak_256}catch{throw new R("aa_encode_error","keccak256 not available. @noble/hashes is required.")}return{keccak_256:pn}}var Ot=null;function Sc(){if(Ot)return{bytesToHex:Ot};try{Ot=ar().bytesToHex}catch{Ot=n=>Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}return{bytesToHex:Ot}}function Cc(n,e){let t=n.toString(16).padStart(32,"0"),r=e.toString(16).padStart(32,"0");return`0x${t}${r}`}async function To(n,e,t,r){try{let s=hr(n,t,r),o=await Ec(s),i=await e(o);return{...n,signature:i}}catch(s){throw new R("aa_signature_failed","Failed to sign UserOperation",s)}}async function Ec(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(()=>(fn(),pr)),{bytesToHex:c}=await Promise.resolve().then(()=>(te(),fr));return`0x${c(a(i))}`}async function Po(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 Io(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${ue.toString(16).padStart(32,"0")}${de.toString(16).padStart(32,"0")}`,preVerificationGas:`0x${(n.preVerificationGas??ie).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:de,verificationGasLimit:ue,preVerificationGas:ie}}if(!i.ok)return{callGasLimit:de,verificationGasLimit:ue,preVerificationGas:ie};let a=await i.json().catch(()=>({}));if(a.error||!a.result)return{callGasLimit:de,verificationGasLimit:ue,preVerificationGas:ie};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):ie,accountGasLimits:c.accountGasLimits}}return{callGasLimit:c.callGasLimit?BigInt(c.callGasLimit):de,verificationGasLimit:c.verificationGasLimit?BigInt(c.verificationGasLimit):ue,preVerificationGas:c.preVerificationGas?BigInt(c.preVerificationGas):ie}}finally{clearTimeout(o)}}function _c(n,e){return ye}function Tc(n){let e=Pt[n];return e?e.entryPoint:null}function ko(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 Pc(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 Ic(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}${kc(n)}`}function kc(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 gr(n,e){return await $e(n,"eth_getCode",[e,"latest"])!=="0x"}async function $e(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 gn=class{config;constructor(e){this.config=e}isAASupported(e){return(e??this.config.chainId)in Pt}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=ko(e.owner,o),a=await $e(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 gr(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 gr(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:ko(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 gr(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?Pc(t[0].to,t[0].value,t[0].data):Ic(t),u;try{u=await this.estimateUserOperationGas(a,{sender:o,nonce:c,initCode:i,callData:l,paymasterAndData:"0x",signature:"0x"})}catch{u={callGasLimit:de,verificationGasLimit:ue,preVerificationGas:ie}}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=mr(d,p),S=hn({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 Je({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 $e(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 $e(r,"eth_estimateUserOperationGas",[s,e]);return{callGasLimit:o.callGasLimit?BigInt(o.callGasLimit):de,verificationGasLimit:o.verificationGasLimit?BigInt(o.verificationGasLimit):ue,preVerificationGas:o.preVerificationGas?BigInt(o.preVerificationGas):ie,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 $e(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 $e(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 $e(this.config.rpcUrl,"eth_getBlockByNumber",["latest",!1]);if(e?.baseFeePerGas)return BigInt(e.baseFeePerGas)}catch{}return 10000000000n}async getPriorityFee(){try{let e=await $e(this.config.rpcUrl,"eth_maxPriorityFeePerGas",[]);return BigInt(e)}catch{return 1000000000n}}getEntryPoint(e){let t=Tc(e);if(!t)throw new R("aa_no_entry_point");return t}getFactory(e,t){let r=_c(e,t);if(!r)throw new R("aa_no_factory");return r}};function mr(n,e){let t=n.toString(16).padStart(32,"0"),r=e.toString(16).padStart(32,"0");return`0x${t}${r}`}function Ro(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 Rc=["dead","deaf","deed","deec","deed"],Bc="0x0000000000000000000000000000000000000000",Uc=/^0x[a-fA-F0-9]{40}$/;function Dc(n){return n.toLowerCase()===Bc}function Lc(n){let e=n.toLowerCase().replace(/^0x/,"");return Rc.some(t=>e.startsWith(t))||e==="0000000000000000000000000000000000000000"}function Oc(n,e){return!n||typeof n!="string"?!1:e==="eip155"||!e?Uc.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 mn=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 Nc(n){return new mn(n)}var Bo={debug:0,info:1,warn:2,error:3,silent:999},xr="warn",yr=null;function Uo(n){xr=n}function Do(n){yr=n}function Fc(n){return Bo[n]>=Bo[xr]}function Ge(n,e,...t){if(!Fc(n))return;if(yr){yr(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 Hc(n){return{debug:(...e)=>Ge("debug",n,...e),info:(...e)=>Ge("info",n,...e),warn:(...e)=>Ge("warn",n,...e),error:(...e)=>Ge("error",n,...e)}}var O={debug:(n,...e)=>Ge("debug",n,...e),info:(n,...e)=>Ge("info",n,...e),warn:(n,...e)=>Ge("warn",n,...e),error:(n,...e)=>Ge("error",n,...e),for:Hc,setLogLevel:Uo,setLogSink:Do,getLogLevel:()=>xr};var wr={"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"},Wu=Object.fromEntries(Object.entries(wr).map(([n,e])=>[e,n]));function br(n){return wr[n]??(n.startsWith("eip155:")?n.slice(7):n)}var Lo=new Set(Object.keys(wr)),No={"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 Oo(n,e){let t=No[n];return!t||e.startsWith("0x")&&e.length===42?e:t[e.toUpperCase()]??e}var Nt=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=Oo(e,r),a=Oo(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=br(e),a=br(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=No[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=br(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 Mc={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"},$c=Object.fromEntries(Object.entries(Mc).map(([n,e])=>[e,n]));function yn(n){let e=$c[n];return e||(n.startsWith("eip155:")?n.slice(7):n)}var Fo=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"]),Mo={"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=Mo[n];return!t||e.startsWith("0x")&&e.length===42?e:t[e.toUpperCase()]??e}var Ft=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=yn(e),a=yn(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:yn(e.fromChain),toChain:yn(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 Fo.has(e)&&Fo.has(t)}supportsToken(e,t){let r=Mo[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"}}};Ht();var Y=class extends Error{code;details;constructor(e,t,r){super(t??e),this.name="ChainAbstractionError",this.code=e,this.details=r}};function Ko(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 Kc=3e4,Vc=2e3,Wc=.5,Vo={"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"},Wo={"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},Mt=class{providers=new Map;config;quoteCache=new Map;routeStore=new Map;constructor(e){this.config={quoteCacheTtl:e?.quoteCacheTtl??Kc,statusPollInterval:e?.statusPollInterval??Vc,defaultSlippage:e?.defaultSlippage??Wc,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 Y("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 Y("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 Y("no_routes_available",`No routes found from ${e} to ${t}. Provider errors: ${l.map(d=>`${d.provider}: ${d.error}`).join("; ")}`,{errors:l}):new Y("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 Y("route_expired","This quote has expired. Please fetch a new quote.");let s=this.routeStore.get(e.routeId);if(!s)throw new Y("no_routes_available",`Route ${e.routeId} not found. It may have expired.`);let o=this.providers.get(e.provider);if(!o)throw new Y("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 Y("execution_failed","No cross-chain transaction parameters returned by provider");if(c&&r?.autoApprove!==!1)throw new Y("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 Y?a:new Y("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 Y("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=Wo[e[0]?.fromChain??"eip155:1"]??18,s=Wo[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=Ve(u,r),g=Ve(c,s),w=Ve(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 Vo[e]??"UNKNOWN";for(let[r,s]of Object.entries(jc))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":Ve(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=Vo[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"}},jc={"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 jo(n){return new Mt(n)}var bn={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 qc(n){return Object.values(n).flatMap(e=>e.accounts)}function zc(n){let e=new Set;return Object.values(n).forEach(t=>{t.chains.forEach(r=>e.add(r))}),Array.from(e)}function Yc(n){let e=new Set;return Object.values(n).forEach(t=>{t.methods.forEach(r=>e.add(r))}),Array.from(e)}function Xc(n){let e=new Set;return Object.values(n).forEach(t=>{t.events.forEach(r=>e.add(r))}),Array.from(e)}var Zc={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."},ve=class extends Error{code;details;constructor(e,t,r){super(t??e),this.name="WalletError",this.code=e,this.details=r}};function Qc(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 Jc(){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 vr(){if(typeof navigator>"u")return!1;let n=navigator.userAgent.toLowerCase();return/(iphone|ipad|ipod|android|mobile)/i.test(n)}var wn=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 ve("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 ve("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=vr();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 el(n){return new wn(n)}var qo="eip155",zo="solana",Yo="xrpl",tl=[qo,zo,Yo],Xo="eip155:1",nl="eip155:5",rl="eip155:11155111",sl="eip155:137",ol="eip155:80001",il="eip155:42161",al="eip155:421613",cl="eip155:10",ll="eip155:420",dl="eip155:8453",Zo="solana:0",ul="solana:1",fl="solana:2",Qo="xrpl:0",pl="xrpl:1",hl="xrpl:2",gl=Xo,ml=Zo,yl=Qo,xl=6e3,bl=6001,wl=6002,vl={SESSION:"naculus_web3_session",POCKET:"naculus_pocket",PASSKEYS_CREDENTIAL:"naculus_passkeys_credential"},Al=16,Sl=300*1e3,Cl=30*1e3;function Jo(n){return n.toString()}function ei(n){return BigInt(n)}function ti(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 Be=class extends Error{code;details;constructor(e,t,r){super(t??e),this.name="FeeEstimationError",this.code=e,this.details=r}};function ni(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 vn={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 An=new Map;function si(n){An.set(n.chainId,n)}function oi(n){An.delete(n)}function ii(){An.clear()}async function Sn(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 Be("fee_rpc_error",`RPC returned status ${o.status}`);let i=await o.json();if(i.error)throw new Be("fee_rpc_error",i.error.message,{code:i.error.code});return i.result}finally{clearTimeout(s)}}async function $t(n){let e=await Sn(n,"eth_maxPriorityFeePerGas",[]);return BigInt(e)}async function Gt(n){let e=await Sn(n,"eth_getBlockByNumber",["latest",!1]);return e&&typeof e.baseFeePerGas=="string"?BigInt(e.baseFeePerGas):null}async function Ar(n){let e=await Sn(n,"eth_gasPrice",[]);return BigInt(e)}async function ai(n){let e=await Sn(n,"eth_chainId",[]);return BigInt(e)}async function ci(n){let e=await Gt(n);if(e!==null)try{let t=await $t(n);return{eip1559:!0,latestBaseFee:e,recommendedPriorityFee:t}}catch{return{eip1559:!0,latestBaseFee:e}}return{eip1559:!1}}function El(n){if(n)return An.get(n)}function _l(n){return n.type==="eip1559"||n.type==="legacy"?n.type:"auto"}function ri(n,e,t){let r=t.baseFeeMultiplier??2n,s=t.maxPriorityFeePerGas??e;return{type:"eip1559",maxFeePerGas:n*r+s,maxPriorityFeePerGas:s}}async function Cn(n){let{rpcUrl:e,chainId:t}=n,r=El(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(_l(n)==="eip1559"){let o=n.maxPriorityFeePerGas??await $t(e),i=await Gt(e);if(i===null)throw new Be("fee_estimation_failed","EIP-1559 forced but chain does not support base fee");return ri(i,o,n)}try{let o=await $t(e),i=await Gt(e);if(i!==null)return ri(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 Ar(e)}}catch(o){throw new Be("fee_estimation_failed",vn.ESTIMATION_FAILED,{error:o})}}var Sr="naculus_notif_",En=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(Sr+"history")}get unreadCount(){return this.history.filter(e=>!e.read).length}async persist(){if(this.storage)try{await this.storage.setItem(Sr+"history",this.history)}catch{}}async restore(){if(this.storage)try{let e=await this.storage.getItem(Sr+"history");e&&Array.isArray(e)&&(this.history=e.slice(-this.maxHistory))}catch{}}},_n=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"}}},Tn=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 li=0;function di(){return li++,`notif_${Date.now()}_${li}_${Math.random().toString(36).slice(2,8)}`}var ui="naculus_notif_prefs",fi="naculus_notif_watches",pi="naculus_notif_mute_rules",Tl={channels:["inapp"],frequency:"final-only",confirmInterval:6,pendingTimeout:300},Pn=class{channels=new Map;watches=new Map;preferences=new Map;muteRules=new Map;statusCallbacks=new Map;defaultPreferences;storage;constructor(e){this.defaultPreferences={...Tl,...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:di(),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(ui);if(e)for(let[s,o]of Object.entries(e))this.preferences.set(s,o);let t=await this.storage.getItem(fi);if(t)for(let s of t)s.resolvedAt||this.watches.set(s.txHash,s);let r=await this.storage.getItem(pi);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(ui,e)}async persistWatches(){this.storage&&await this.storage.setItem(fi,this.getAllWatches())}async persistMuteRules(){if(!this.storage)return;let e={};for(let[t,r]of this.muteRules)e[t]=r;await this.storage.setItem(pi,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:di(),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 Pl(n){try{let e=await n.request({method:"wallet_getPermissions"});return e?.length>0?e:null}catch{return null}}async function Il(n){return await n.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]})}function kl(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 Rl(n,e){return n?n.some(t=>t.parentCapability===e):!1}var me={"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 Bl(n,e){return me[n]??e}fn();te();var W=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 Ul=new TextEncoder;function _r(n){return Ul.encode(n)}var Dl="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";var Ll=[{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"}]}],hi=[{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"}]}],N0=`0x${"00".repeat(20)}`;function gi(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=Lt(_r(t[r].toLowerCase()));e=Lt(z(e,s))}}return`0x${D(e)}`}function Cr(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=Lt(_r(o)).slice(0,4),a=t.map(l=>{if(typeof l=="string"&&l.startsWith("0x")){let w=l.slice(2).padStart(64,"0");return G(w)}let u=_r(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 mi(n){let e=G(n.slice(2));if(e.length<32)throw new W("INVALID_ADDRESS","Invalid response length for address decode");let t=e.slice(12,32);return`0x${D(t)}`}function Ol(n){let e=G(n.slice(2));if(e.length<32)throw new W("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 Er(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 W("PROVIDER_UNAVAILABLE",`ENS RPC call failed: ${t.status} ${t.statusText}`);let r=await t.json();if(r.error)throw new W("NAME_NOT_FOUND",`ENS lookup failed: ${r.error.message}`);return r.result??"0x"}var ht=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=gi(t),s=await this.getResolver(r);if(!s||s==="0x0000000000000000000000000000000000000000")return null;let o=Cr(hi,"addr",[r]),i=await Er(this.rpcUrl,{to:s,data:o});return!i||i==="0x"||i==="0x0000000000000000000000000000000000000000000000000000000000000000"?null:{address:mi(i),chainType:"eip155",name:t}}async lookupAddress(e){let t=e.startsWith("0x")?e.toLowerCase():`0x${e.toLowerCase()}`,r=gi(`${t.slice(2).toLowerCase()}.addr.reverse`),s=await this.getResolver(r);if(!s||s==="0x0000000000000000000000000000000000000000")return null;let o=Cr(hi,"name",[r]),i=await Er(this.rpcUrl,{to:s,data:o});if(!i||i==="0x")return null;try{let a=Ol(i);return a?{name:a,chainType:"eip155",isPrimary:!0}:null}catch{return null}}async getResolver(e){let t=Cr(Ll,"resolver",[e]);try{let r=await Er(this.rpcUrl,{to:Dl,data:t});return!r||r==="0x"?null:mi(r)}catch{return null}}};te();function Nl(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 yi(n,e,t){return n&e^~n&t}function xi(n,e,t){return n&e^n&t^e&t}var In=class extends ke{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=nt(this.buffer)}update(e){xe(this),e=be(e),Q(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=nt(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){xe(this),Bt(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,ce(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let p=i;p<s;p++)t[p]=0;Nl(r,s-8,BigInt(this.length*8),o),this.process(r,0);let a=nt(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()}},Ue=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);te();var Fl=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]),We=new Uint32Array(64),kn=class extends In{constructor(e=32){super(64,e,8,!1),this.A=Ue[0]|0,this.B=Ue[1]|0,this.C=Ue[2]|0,this.D=Ue[3]|0,this.E=Ue[4]|0,this.F=Ue[5]|0,this.G=Ue[6]|0,this.H=Ue[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)We[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let d=We[p-15],f=We[p-2],h=fe(d,7)^fe(d,18)^d>>>3,g=fe(f,17)^fe(f,19)^f>>>10;We[p]=g+We[p-7]+h+We[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=fe(a,6)^fe(a,11)^fe(a,25),f=u+d+yi(a,c,l)+Fl[p]+We[p]|0,g=(fe(r,2)^fe(r,13)^fe(r,22))+xi(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(){ce(We)}destroy(){this.set(0,0,0,0,0,0,0,0),ce(this.buffer)}};var Rn=ft(()=>new kn);var Ae=Rn;te();var Hl=new TextEncoder;function bi(n){return Hl.encode(n)}var Ml="namesLPneVptA9Z5rqUDD9tMTWEJwofgaYwp8cawRkX",$l="58P1RCHjMiN1eS6LGpmmNvbTYGWCoh2vMGN4JmSScWdT",Gl="name_record";var wi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Tr=BigInt(58);function Pr(n){let e=BigInt(0);for(let a of n){let c=wi.indexOf(a);if(c===-1)throw new Error(`Invalid Base58 character: ${a}`);e=e*Tr+BigInt(c)}let t=e.toString(16),r=t.length%2===0?t:`0${t}`,s=G(r),o=n.match(/^1*/)?.[0]?.length??0,i=new Uint8Array(o+s.length);return i.set(s,o),i}function Kl(n,e){for(let t=255;t>=0;t--){let r=z(...n,new Uint8Array([t]),e),s=Ae(r);if(!(s[31]&128))return[s,t]}throw new Error("Unable to find a valid bump seed")}function Vl(n){let e=Pr(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 Wl(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 W("PROVIDER_UNAVAILABLE",`SNS RPC call failed: ${t.status} ${t.statusText}`);let r=await t.json();if(r.error)throw new W("NAME_NOT_FOUND",`SNS lookup failed: ${r.error.message}`);return r.result?.value??null}function jl(n){let e=Pr($l),t=bi(n.toLowerCase().replace(".sol","")),r=Pr(Ml),s=[bi(Gl),e,t],[o]=Kl(s,r);return D(o)}var gt=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=jl(t);try{let s=await Wl(this.rpcUrl,r.length===64?r:`0x${r}`);if(!s||!s.data||s.data.length===0)return null;let o=s.data[0],a=Vl(o).header.owner;return!a||a==="0000000000000000000000000000000000000000000000000000000000000000"?null:{address:this.hexToBase58(a),chainType:"solana",name:t}}catch(s){if(s instanceof W)throw s;return null}}async lookupAddress(e){return null}hexToBase58(e){let t=e.replace(/^0x/,"").padStart(64,"0"),r=G(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%Tr);o.push(wi[a]),s=s/Tr}let i=0;for(let a of r)if(a===0)i++;else break;return"1".repeat(i)+o.reverse().join("")}};function ql(){return me["eip155:1"]??"https://eth.llamarpc.com"}function zl(){return me["solana:0"]??"https://api.mainnet-beta.solana.com"}function Yl(n){let e=n.toLowerCase().trim();return e.endsWith(".eth")?".eth":e.endsWith(".sol")?".sol":null}function Xl(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 Bn=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??ql();this.registerProvider(new ht(t));let r=e?.providers?.sns?.rpcUrl??zl();this.registerProvider(new gt(r))}registerProvider(e){this.providers.set(e.chainType,e)}async resolveName(e){let t=e.trim();if(!t)throw new W("INVALID_NAME","Name cannot be empty");let r=`resolve:${t.toLowerCase()}`,s=this.cache.get(r);if(s!==null)return s;let o=Yl(t);if(!o)throw new W("UNSUPPORTED_NAME_SERVICE",`Unsupported name service for "${t}". Supported suffixes: .eth, .sol`);if(!Xl(t,o))throw new W("INVALID_NAME",`Invalid name format: "${t}"`);let i=this.findProviderForName(t);if(!i)throw new W("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 W("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 W("RESOLUTION_TIMEOUT",`${t} timed out after ${this.timeoutMs}ms`)),this.timeoutMs))])}};var pe=class extends Error{constructor(t,r="unknown",s){super(t);this.code=r;this.name="StorageError",s&&(this.cause=s)}code};function vi(n){if(typeof globalThis<"u"&&n in globalThis){let e=globalThis[n];if(e!=null&&typeof e.getItem=="function")return e}return null}function Ai(n){if(typeof window>"u"){try{let e=vi("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 Zl(){return typeof window<"u"&&window.localStorage?window.localStorage:vi("localStorage")}var je=class{prefix;_available=null;constructor(e=""){this.prefix=e}getKey(e){return`${this.prefix}${e}`}getStorage(){return Zl()}isAvailable(){return this._available===null&&(this._available=Ai("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 pe(`Failed to parse storage item: ${e}`,"parse_error",t)}}async set(e,t){if(!this.isAvailable())throw new pe("LocalStorage is not available","not_available");try{let r=this.getStorage();if(!r)throw new pe("LocalStorage is not available","not_available");r.setItem(this.getKey(e),JSON.stringify(t))}catch(r){throw r instanceof DOMException&&r.name==="QuotaExceededError"?new pe(`Storage quota exceeded for key: ${e}`,"quota_exceeded",r):new pe(`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}},Un=class{prefix;_available=null;constructor(e=""){this.prefix=e}getKey(e){return`${this.prefix}${e}`}isAvailable(){return this._available===null&&(this._available=Ai("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 pe(`Failed to parse storage item: ${e}`,"parse_error",t)}}async set(e,t){if(!this.isAvailable())throw new pe("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 pe(`Storage quota exceeded for key: ${e}`,"quota_exceeded",r):new pe(`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}},qe=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)}},Dn=class{isAvailable(){return!1}async get(e){return null}async set(e,t){}async remove(e){}async clear(){}async has(e){return!1}};function rt(n,e=""){switch(n){case"local":return new je(e);case"session":return new Un(e);case"memory":return new qe;default:return new Dn}}function Ql(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 Jl(n,e){return{...n,...e,updatedAt:e.updatedAt??new Date().toISOString()}}function kr(n,e){return n.auth?.expiresAt?new Date(n.auth.expiresAt).getTime()<=e.getTime():!1}var Ir=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 Rr={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 oe(n,e){return new ve(n,Rr[n],e)}te();var Ln=class extends ke{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,tt(e);let r=be(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),ce(o)}update(e){return xe(this),this.iHash.update(e),this}digestInto(e){xe(this),Q(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()}},Se=(n,e,t)=>new Ln(n,e).update(t).digest();Se.create=(n,e)=>new Ln(n,e);te();te();te();var Dr=BigInt(0),Ur=BigInt(1);function Kt(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function ze(n,e,t=""){let r=He(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 Vt(n){let e=n.toString(16);return e.length&1?"0"+e:e}function Si(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?Dr:BigInt("0x"+n)}function mt(n){return Si(D(n))}function Lr(n){return Q(n),Si(D(Uint8Array.from(n).reverse()))}function On(n,e){return G(n.toString(16).padStart(e*2,"0"))}function Or(n,e){return On(n,e).reverse()}function J(n,e,t){let r;if(typeof e=="string")try{r=G(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(He(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 Br=n=>typeof n=="bigint"&&Dr<=n;function Ci(n,e,t){return Br(n)&&Br(e)&&Br(t)&&e<=n&&n<t}function Ei(n,e,t,r){if(!Ci(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function Nn(n){let e;for(e=0;n>Dr;n>>=Ur,e+=1);return e}var Ye=n=>(Ur<<BigInt(n))-Ur;function _i(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 Wt(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 Nr(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),st=BigInt(2),Ii=BigInt(3),ki=BigInt(4),Ri=BigInt(5),ed=BigInt(7),Bi=BigInt(8),td=BigInt(9),Ui=BigInt(16);function he(n,e){let t=n%e;return t>=ne?t:e+t}function le(n,e,t){let r=n;for(;e-- >ne;)r*=r,r%=t;return r}function Ti(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=he(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 he(s,e)}function Fr(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Di(n,e){let t=(n.ORDER+ee)/ki,r=n.pow(e,t);return Fr(n,r,e),r}function nd(n,e){let t=(n.ORDER-Ri)/Bi,r=n.mul(e,st),s=n.pow(r,t),o=n.mul(e,s),i=n.mul(n.mul(o,st),s),a=n.mul(o,n.sub(i,n.ONE));return Fr(n,a,e),a}function rd(n){let e=Xe(n),t=Li(n),r=t(e,e.neg(e.ONE)),s=t(e,r),o=t(e,e.neg(r)),i=(n+ed)/Ui;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 Fr(a,w,c),w}}function Li(n){if(n<Ii)throw new Error("sqrt is not defined for small field");let e=n-ee,t=0;for(;e%st===ne;)e/=st,t++;let r=st,s=Xe(n);for(;Pi(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Di;let o=s.pow(r,e),i=(e+ee)/st;return function(c,l){if(c.is0(l))return l;if(Pi(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 sd(n){return n%ki===Ii?Di:n%Bi===Ri?nd:n%Ui===td?rd(n):Li(n)}var od=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Hr(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=od.reduce((r,s)=>(r[s]="function",r),e);return Wt(n,t),n}function id(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 Fn(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 Pi(n,e){let t=(n.ORDER-ee)/st,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 Hn(n,e){e!==void 0&&ae(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Xe(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}=Hn(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:Ye(c),ZERO:ne,ONE:ee,allowedLengths:a,create:d=>he(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=>he(-d,n),eql:(d,f)=>d===f,sqr:d=>he(d*d,n),add:(d,f)=>he(d+f,n),sub:(d,f)=>he(d-f,n),mul:(d,f)=>he(d*f,n),pow:(d,f)=>id(p,d,f),div:(d,f)=>he(d*Ti(f,n),n),sqrN:d=>d*d,addN:(d,f)=>d+f,subN:(d,f)=>d-f,mulN:(d,f)=>d*f,inv:d=>Ti(d,n),sqrt:o||(d=>(u||(u=sd(n)),u(p,d))),toBytes:d=>t?Or(d,l):On(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?Lr(d):mt(d);if(i&&(h=he(h,n)),!f&&!p.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:d=>Fn(p,d),cmov:(d,f,h)=>h?f:d});return Object.freeze(p)}function Oi(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 Mr(n){let e=Oi(n);return e+Math.ceil(e/2)}function $r(n,e,t=!1){let r=n.length,s=Oi(e),o=Mr(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let i=t?Lr(n):mt(n),a=he(i,e-ee)+ee;return t?Or(a,s):On(a,s)}var yt=BigInt(0),ot=BigInt(1);function jt(n,e){let t=e.negate();return n?t:e}function $n(n,e){let t=Fn(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function Mi(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function Gr(n,e){Mi(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,o=Ye(n),i=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function Ni(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+=ot);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 ad(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 cd(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 Kr=new WeakMap,$i=new WeakMap;function Vr(n){return $i.get(n)||1}function Fi(n){if(n!==yt)throw new Error("invalid wNAF")}var Mn=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>yt;)t&ot&&(r=r.add(s)),s=s.double(),t>>=ot;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=Gr(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=Gr(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:d,offsetF:f}=Ni(r,a,i);r=c,u?o=o.add(jt(d,t[f])):s=s.add(jt(p,t[l]))}return Fi(r),{p:s,f:o}}wNAFUnsafe(e,t,r,s=this.ZERO){let o=Gr(e,this.bits);for(let i=0;i<o.windows&&r!==yt;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Ni(r,i,o);if(r=a,!l){let p=t[c];s=s.add(u?p.negate():p)}}return Fi(r),s}getPrecomputes(e,t,r){let s=Kr.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(s=r(s)),Kr.set(t,s))),s}cached(e,t,r){let s=Vr(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)}unsafe(e,t,r,s){let o=Vr(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,s)}createCache(e,t){Mi(t,this.bits),$i.set(e,t),Kr.delete(e)}hasCache(e){return Vr(e)!==1}};function Gi(n,e,t,r){let s=e,o=n.ZERO,i=n.ZERO;for(;t>yt||r>yt;)t&ot&&(o=o.add(s)),r&ot&&(i=i.add(s)),s=s.double(),t>>=ot,r>>=ot;return{p1:o,p2:i}}function Ki(n,e,t,r){ad(t,n),cd(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=Nn(BigInt(s)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Ye(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 Hi(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Hr(e),e}else return Xe(n,{isLE:t})}function Vi(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>yt))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Hi(e.p,t.Fp,r),o=Hi(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 Wi=(n,e)=>(n+(n>=0?e:-e)/ji)/e;function ld(n,e,t){let[[r,s],[o,i]]=e,a=Wi(i*n,t),c=Wi(-s*n,t),l=n-a*r-c*o,u=-a*s-c*i,p=l<Le,d=u<Le;p&&(l=-l),d&&(u=-u);let f=Ye(Math.ceil(Nn(t)/2))+bt;if(l<Le||l>=f||u<Le||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:p,k1:l,k2neg:d,k2:u}}function jr(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function Wr(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return Kt(t.lowS,"lowS"),Kt(t.prehash,"prehash"),t.format!==void 0&&jr(t.format),t}var qr=class extends Error{constructor(e=""){super(e)}},De={Err:qr,_tlv:{encode:(n,e)=>{let{Err:t}=De;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=Vt(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?Vt(s.length/2|128):"";return Vt(n)+o+s+e},decode(n,e){let{Err:t}=De,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}=De;if(n<Le)throw new e("integer: negative integers are not allowed");let t=Vt(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}=De;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 mt(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=De,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}=De,r=e.encode(2,t.encode(n.r)),s=e.encode(2,t.encode(n.s)),o=r+s;return e.encode(48,o)}},Le=BigInt(0),bt=BigInt(1),ji=BigInt(2),Gn=BigInt(3),dd=BigInt(4);function xt(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 ud(n,e={}){let t=Vi("weierstrass",n,e),{Fp:r,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;Wt(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=zi(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(Kt(y,"isCompressed"),y){u();let _=!r.isOdd(b);return z(qi(_),v)}else return z(Uint8Array.of(4),v,r.toBytes(b))}function d(L){ze(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(j){let F=j instanceof Error?": "+j.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,Gn),dd),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 ld(L,c.basises,s.ORDER)}let Ee=Nr((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}}),_e=Nr(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 Oe(L,x,y,m,b){return y=new B(r.mul(y.X,L),y.Y,y.Z),x=jt(m,x),y=jt(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(ze(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(Gn),this}assertValidity(){_e(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,Gn),{X:b,Y:v,Z:_}=this,E=r.ZERO,A=r.ZERO,T=r.ZERO,I=r.mul(b,b),j=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(j,A),A=r.add(j,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,j),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,j=o.a,F=r.mul(o.b,Gn),U=r.mul(y,v),K=r.mul(m,_),q=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 X=r.add(v,E);return V=r.mul(V,X),X=r.add(U,q),V=r.sub(V,X),X=r.add(m,b),A=r.add(_,E),X=r.mul(X,A),A=r.add(K,q),X=r.sub(X,A),I=r.mul(j,V),A=r.mul(F,q),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),q=r.mul(j,q),V=r.mul(F,V),K=r.add(K,q),q=r.sub(U,q),q=r.mul(j,q),V=r.add(V,q),U=r.mul(K,V),T=r.add(T,U),U=r.mul(X,V),A=r.mul(se,A),A=r.sub(A,U),U=r.mul(se,K),I=r.mul(X,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=>$n(B,E));if(y){let{k1neg:_,k1:E,k2neg:A,k2:T}=re(x),{p:I,f:j}=v(E),{p:F,f:U}=v(T);b=j.add(U),m=Oe(y.beta,I,F,_,A)}else{let{p:_,f:E}=v(x);m=_,b=E}return $n(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===Le||m.is0())return B.ZERO;if(x===bt)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}=Gi(B,m,v,E);return Oe(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 Ee(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return i===bt?!0:x?x(B,this):Qe.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===bt?this:x?x(B,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return Kt(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 $n(B,x)}static msm(x,y){return Ki(B,s,x,y)}static fromPrivateKey(x){return B.BASE.multiply(xt(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 Qt=s.BITS,Qe=new Mn(B,e.endo?Math.ceil(Qt/2):Qt);return B.BASE.precompute(8),B}function qi(n){return Uint8Array.of(n?2:3)}function zi(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function fd(n,e={}){let{Fn:t}=n,r=e.randomBytes||we,s=Object.assign(zi(n.Fp,t),{seed:Mr(t.ORDER)});function o(f){try{return!!xt(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 $r(ze(f,s.seed,"seed"),t.ORDER)}function c(f,h=!0){return n.BASE.multiply(xt(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=xt(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=>xt(t,f),precompute(f=8,h=n.BASE){return h.precompute(f,!1)}},lengths:s})}function pd(n,e,t={}){tt(e),Wt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||we,s=t.hmac||((y,...m)=>Se(e,y,z(...m))),{Fp:o,Fn:i}=n,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:d,lengths:f}=fd(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>>bt;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){jr(m);let b=f.signature,v=m==="compact"?b:m==="recovered"?b+1:void 0;return ze(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}=De.toSig(ze(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(G(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*ji<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),j=n.fromBytes(z(qi((E&1)===0),I)),F=i.inv(T),U=re(J("msgHash",m)),K=i.create(-U*F),q=i.create(_*F),se=n.BASE.multiplyUnsafe(K).add(j.multiplyUnsafe(q));if(se.is0())throw new Error("point at infinify");return se.assertValidity(),se}hasHighS(){return w(this.s)}toBytes(m=g){if(jr(m),m==="der")return G(De.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=mt(m),v=m.length*8-c;return v>0?b>>BigInt(v):b},re=t.bits2int_modN||function(m){return i.create(N(m))},Ee=Ye(c);function _e(y){return Ei("num < 2^"+c,y,Le,Ee),i.toBytes(y)}function Oe(y,m){return ze(y,void 0,"message"),m?ze(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}=Wr(b,h);y=Oe(y,_);let A=re(y),T=xt(i,m),I=[_e(T),_e(A)];if(E!=null&&E!==!1){let K=E===!0?r(f.secretKey):E;I.push(J("extraEntropy",K))}let j=z(...I),F=A;function U(K){let q=N(K);if(!i.isValidNot0(q))return;let se=i.inv(q),V=n.BASE.multiply(q).toAffine(),X=i.create(V.x);if(X===Le)return;let Jt=i.create(se*i.create(F+X*T));if(Jt===Le)return;let ds=(V.x===X?0:2)|Number(V.y&bt),us=Jt;return v&&w(Jt)&&(us=i.neg(Jt),ds^=1),new k(X,us,ds)}return{seed:j,k2sig:U}}function Qt(y,m,b={}){y=J("message",y);let{seed:v,k2sig:_}=B(y,m,b);return _i(e.outputLen,i.BYTES,s)(v,_)}function Qe(y){let m,b=typeof y=="string"||He(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 De.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}=Wr(v,h);if(b=J("publicKey",b),m=Oe(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:j,s:F}=T,U=re(m),K=i.inv(F),q=i.create(U*K),se=i.create(j*K),V=n.BASE.multiplyUnsafe(q).add(I.multiplyUnsafe(se));return V.is0()?!1:i.create(V.x)===j}catch{return!1}}function x(y,m,b={}){let{prehash:v}=Wr(b,h);return m=Oe(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:Qt,verify:L,recoverPublicKey:x,Signature:k,hash:e})}function hd(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=Xe(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 gd(n){let{CURVE:e,curveOpts:t}=hd(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 md(n,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},n,Hn(t.Fn.ORDER,t.Fn.BITS))})}function Yi(n){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:s}=gd(n),o=ud(e,t),i=pd(o,r,s);return md(n,i)}function Xi(n,e){let t=r=>Yi({...n,hash:r});return{...t(e),create:t}}var Yr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Zi=BigInt(2);function xd(n){let e=Yr.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=le(u,t,e)*u%e,d=le(p,t,e)*u%e,f=le(d,Zi,e)*l%e,h=le(f,s,e)*f%e,g=le(h,o,e)*h%e,w=le(g,a,e)*g%e,S=le(w,c,e)*w%e,M=le(S,a,e)*g%e,k=le(M,t,e)*u%e,N=le(k,i,e)*h%e,re=le(N,r,e)*l%e,Ee=le(re,Zi,e);if(!zr.eql(zr.sqr(Ee),n))throw new Error("Cannot find square root");return Ee}var zr=Xe(Yr.p,{sqrt:xd}),Kn=Xi({...Yr,Fp:zr,lowS:!0,endo:yd},Rn);te();te();function bd(n,e,t,r){tt(n);let s=ur({dkLen:32,asyncTick:10},r),{c:o,dkLen:i,asyncTick:a}=s;if(ae(o),ae(i),ae(a),o<1)throw new Error("iterations (c) should be >= 1");let c=dn(e),l=dn(t),u=new Uint8Array(i),p=Se.create(n,c),d=p._cloneInto().update(l);return{c:o,dkLen:i,asyncTick:a,DK:u,PRF:p,PRFSalt:d}}function wd(n,e,t,r,s){return n.destroy(),e.destroy(),r&&r.destroy(),ce(s),t}function Qi(n,e,t,r){let{c:s,dkLen:o,DK:i,PRF:a,PRFSalt:c}=bd(n,e,t,r),l,u=new Uint8Array(4),p=nt(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 wd(a,c,i,l,d)}te();var vd=32,Ad=12,Sd=16,Cd=6e5,Xr="session_keys";function ea(n,e,t){return Qi(Ae,n,e,{c:t??Cd,dkLen:vd})}function Ed(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=Se(Ae,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=Se(Ae,e,l).slice(0,16);return{ciphertext:c,tag:u}}function _d(n,e,t,r){let s=new Uint8Array(t.length+n.length);s.set(t),s.set(n,t.length);let o=Se(Ae,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 oe("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=Se(Ae,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 Vn(n,e,t,r,s){let o=G(n.slice(2)),i=t??we(Sd),a=we(Ad),c=ea(e,i,r),{ciphertext:l,tag:u}=Ed(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 Wn(n,e,t){let r=G(n.encryptedPrivateKey),s=r.slice(0,16),o=r.slice(16),i=G(n.iv),a=G(n.salt),c=ea(e,a,t),l=_d(o,c,i,s);return`0x${D(l)}`}function Td(n,e){return typeof e=="bigint"?{__bigint__:e.toString()}:e}function Ji(n,e){return e!==null&&typeof e=="object"&&"__bigint__"in e?BigInt(e.__bigint__):e}var wt=class{adapter;constructor(e){this.adapter=e??new qe}isAvailable(){return this.adapter.isAvailable()}async loadAll(){try{let e=await this.adapter.get(Xr);return e?JSON.parse(typeof e=="string"?e:JSON.stringify(e),Ji):[]}catch{return[]}}async persistAll(e){let t=JSON.stringify(e,Td);await this.adapter.set(Xr,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 oe("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 oe("session_key_not_found",e);r.useCount+=1,r.lastUsedAt=Date.now(),await this.persistAll(t)}async clear(){await this.adapter.remove(Xr)}};var qt={storagePrefix:"naculus_session_keys",defaultMaxTotalValue:BigInt("100000000000000000"),defaultMaxTxCount:50,defaultExpiryMs:864e5,requireAllowedContracts:!0,forbiddenMethods:["0x095ea7b3","0xdd62ed3e","0xa22cb465"],encryptionSalt:"",encryptionKey:"",pbkdf2Iterations:6e5};function Pd(){let n=we(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 Id(n){if(n.encryptionKey&&n.encryptionKey.length>0)return n.encryptionKey;let e=`${n.storagePrefix??qt.storagePrefix}::session_key_encryption_v1`;return Ae(e).reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"")}var jn=class{config;storage;encryptionPassword;activeBundle=null;cache=new Map;constructor(e,t){this.config={...qt,...e},this.storage=new wt(t),this.encryptionPassword=Id(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 oe("session_key_required_fields_missing","allowedContracts is required when requireAllowedContracts is enabled");let s=Kn.utils.randomPrivateKey(),o=Kn.getPublicKey(s),i=`0x${D(o)}`,a=`0x${D(s)}`,c=Vn(a,this.encryptionPassword,void 0,this.config.pbkdf2Iterations,i),l=Date.now(),u={id:Pd(),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 oe("session_key_not_found",e);this.validateSessionStatus(t);let r=Wn(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=G(t.slice(2)),o=Kn.sign(s,G(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 oe("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 oe("session_key_revoked",e.id);if(e.status==="expired")throw oe("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(()=>{}),oe("session_key_expired",e.id);if(e.scope.maxTxCount!==void 0&&e.useCount>=e.scope.maxTxCount)throw oe("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 Zr={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 Ce(n,e){return new ve(n,Zr[n],e)}var vt=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 kd="naculus_web3_session_manager",At=class{adapter;key;constructor(e,t){this.key=e??kd,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(kr(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 qn(n,e){return!e&&!(typeof globalThis<"u"&&typeof globalThis.localStorage<"u")?new At(n,new qe):new At(n,e)}function St(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 zt(n){let{namespace:e,reference:t}=St(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 Rd={"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}},Bd={"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"},Yt=class extends vt{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=qn()}connectorManager;bundles=new Map;activeBundleId=null;userFeeOverrides={};config;persistence;async connect(t,r,s){if(zt(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){zt(t);let r=this.getActiveBundle();if(!r)throw Ce("no_active_session");let s=r.activeChainId;if(s===t)return;let o=this.resolveConnector(r.walletSession);if(!o.switchChain)throw Ce("method_unsupported");try{await o.switchChain(r.walletSession,t)}catch(i){throw i?.code===4001||i?.message?.includes("rejected")?Ce("chain_switch_rejected"):Ce("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 Ce("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 Ce("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 Cn(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}=St(t),o=this.config.defaultCurrencies?.[t]??Rd[t]??{name:t,symbol:t.includes(":")?t.split(":")[1]:t,decimals:18},i=this.config.defaultRpcUrls?.[t]??me[t]??"",a=this.config.defaultExplorers?.[t]??Bd[t];return{chainId:t,connectorId:r,rpcUrl:i,nativeCurrency:o,blockExplorer:a}}updateSessionNamespace(t,r){let{namespace:s,reference:o}=St(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 Ce("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 ta(n,e){return new Yt(n,e)}var na=[1,137,42161,10,56,43114,8453,250,25,324],Ud={1:"ethereum",137:"polygon",42161:"arbitrum",10:"optimism",56:"bsc",43114:"avalanche",8453:"base",250:"fantom",25:"cronos",324:"zksync"},Dd="https://api.blowfish.xyz";function Ld(n){return Ud[n]??`eip155:${n}`}function Od(n){switch(n){case"NONE":return"safe";case"WARN":return"warning";case"BLOCK":return"malicious";default:return"unknown"}}function Nd(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 Fd(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 Hd(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 Md(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 $d(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 it=class{name="blowfish";supportedChains=na;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?Ld(this._inferChainId(r.origin)):"ethereum",o=await fetch(`${Dd}/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=Fd(a.expectedStateChanges),l=Hd(a.expectedStateChanges),u=a.suggestedAction??"NONE",p=Od(u),d=a.scanResults??[],f=Nd(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:Md(a.gasInfo),provider:this.name,summary:$d(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 na.includes(e)}_inferChainId(e){return 1}};var Gd=[1,5,11155111,10,42161,421614,8453,84532],Kd=[137,80002],Vd=[56,97];function Wd(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 jd(n){return Gd.includes(n)?"ETH":Kd.includes(n)?"MATIC":Vd.includes(n)?"BNB":"ETH"}function qd(n,e,t){let r=jd(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 zd(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 Ct=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=Wd(a.error.data??a.error.message);return zd(c,this.name)}return qd(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 Yd(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 Qr(n,e,t,r){let s=await Yd(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 ra=[{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()"};xn();Ht();function _t(n){return n.startsWith("0x")?n.slice(2):n}function aa(n){return n.padStart(64,"0")}async function Xd(n){let{keccak_256:e}=await Promise.resolve().then(()=>(fn(),pr)),{bytesToHex:t}=await Promise.resolve().then(()=>(te(),fr));return t(e(n))}function Ze(n){if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new $("invalid_address",`Invalid EVM address: "${n}". Expected 0x-prefixed 40-char hex.`);return`0x${aa(_t(n.toLowerCase()))}`}function Xt(n){if(n<0n)throw new $("invalid_amount",`Cannot encode negative uint256: ${n}`);let e=n.toString(16),t=e.length%2===0?e:`0${e}`;return`0x${aa(t)}`}async function Yn(n){return`0x${(await Xd(new TextEncoder().encode(n))).slice(0,8)}`}async function Zt(n,...e){let t=await Yn(n),r=e.map(s=>_t(s)).join("");return`${t}${r}`}async function Zd(n,e){return Zt(ge.transfer,Ze(n),Xt(e))}async function Qd(n,e){return Zt(ge.approve,Ze(n),Xt(e))}async function Jd(n,e,t){return Zt(ge.transferFrom,Ze(n),Ze(e),Xt(t))}function zn(n,e){if(e?.rpcUrl)return e.rpcUrl;let t=me[`eip155:${n}`];if(!t)throw new $("rpc_error",`No default RPC URL for chain ID ${n}. Provide options.rpcUrl.`);return t}async function Jr(n,e,t){try{return await Qr(n,"eth_call",[{to:e,data:t},"latest"])}catch(r){throw new $("rpc_error",`RPC eth_call error: ${r}`,r)}}function es(n){let e=_t(n);return BigInt(`0x${e}`)}function sa(n){let e=_t(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 oa(n){return Number(es(n))}var ia=new Map;async function Et(n){let e=ia.get(n);if(e)return e;let t=await Yn(n);return ia.set(n,t),t}var at=class n{static async buildTransferTx(e,t){let r=typeof e.amount=="string"?Ke(e.amount,t):e.amount,s=await Zd(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"?Ke(e.amount,t):e.amount,s=await Qd(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"?Ke(e.amount,t):e.amount,s=await Jd(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=zn(e.chainId,s),a=`${await Et(ge.allowance)}${_t(Ze(t))}${_t(Ze(r))}`,c=await Jr(o,e.address,a);return es(c)}static async getTokenInfo(e,t){let r=zn(e.chainId,t),s=e.address,o=await Et(ge.name),i=await Et(ge.symbol),a=await Et(ge.decimals),c=await Et(ge.totalSupply),l=async u=>Jr(r,s,u);try{let[u,p,d,f]=await Promise.all([l(o),l(i),l(a),l(c)]),h=sa(u),g=sa(p),w=oa(d),S=es(f);return{name:h,symbol:g,decimals:w,totalSupply:S}}catch(u){throw u instanceof $?u:new $("token_info_fetch_failed","Failed to fetch token metadata from chain.",u)}}static async isTokenDeployed(e,t){let r=zn(e.chainId,t);try{let s=await Qr(r,"eth_getCode",[e.address,"latest"]);return s!=="0x"&&s!=="0x0"}catch(s){throw new $("rpc_error",`RPC eth_getCode error: ${s}`,s)}}static async getDecimals(e,t){if(e.decimals!==void 0)return e.decimals;let r=zn(e.chainId,t),o=await Et(ge.decimals);try{let i=await Jr(r,e.address,o);return oa(i)}catch(i){throw new $("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 Ke(t,s)}static async formatRawAmount(e,t,r){let s=await n.getDecimals(e,r),{formatUnits:o}=await Promise.resolve().then(()=>(Ht(),Go));return o(t,s)}};var ts={level:"unknown",score:0,warnings:[]},Xn=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 Ct(e?.rpcUrl)),this.blowfishApiKey&&this.providers.set("blowfish",new it(this.blowfishApiKey))}async simulate(e,t,r){if(!this._enabled)return{status:"unavailable",balanceChanges:[],approvalChanges:[],riskAssessment:{...ts},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:{...ts,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 at.getDecimals(e),a=await at.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:{...ts,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 it(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 me[`eip155:${e}`]}};function ca(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}}xn();Ht();var Zn="naculus_auto_detected_tokens",eu=10080*60*1e3;async function da(n,e,t,r){if(!r?.skipCache){let d=await tu(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([ns(t,s,o),ns(t,s,i),ns(t,s,a)]),p={address:s,chainId:e,name:la(c),symbol:la(l),decimals:ru(u),source:"auto-detect",tags:["custom"]};return await nu(p),p}async function ua(){await rt("local","").remove(Zn)}async function tu(n,e){let t=rt("local","");try{let r=await t.get(Zn);if(!r)return null;let s=`${e}:${n.toLowerCase()}`,o=r[s];return!o||Date.now()-o.timestamp>eu?null:o.token}catch{return null}}async function nu(n){let e=rt("local","");try{let t=await e.get(Zn)??{},r=`${n.chainId}:${n.address.toLowerCase()}`;t[r]={token:n,timestamp:Date.now()},await e.set(Zn,t)}catch{}}async function ns(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 la(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 ru(n){let e=n.startsWith("0x")?n.slice(2):n;return parseInt(e||"0",16)}var rs=[{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"]}],ss=[{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"]}],os=[{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"]}],is=[{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"]}],as=[{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"]}],cs={1:rs,137:ss,10:os,42161:is,8453:as};function ls(){return Object.values(cs).flat()}var Qn=[{name:"built-in",tokens:ls(),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 su="naculus_token_list_cache",fa=1440*60*1e3,ou=1e4,Jn=class{config;tokens=[];sourceStatus=new Map;storage;constructor(e){this.config={sources:e?.sources??Qn,cacheKey:e?.cacheKey??su,cacheTtl:e?.cacheTtl??fa,sourcePriority:e?.sourcePriority,fetchTimeout:e?.fetchTimeout??ou},this.storage=rt("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??fa)}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 iu=8;function au(n){return parseInt(n.split(":")[1]??"0",10)}async function pa(n,e){let t=au(n),s=bn[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**iu}catch{return null}}0&&(module.exports={AA_ERROR_MESSAGES,AA_SUPPORTED_CHAINS,ARBITRUM_TOKENS,AUTO_RECONNECT_TIMEOUT_MS,AccountAbstractionError,AutoReconnectManager,AxelarProvider,BASE_TOKENS,BlowfishProvider,CHAINS,CONNECTOR_ERROR_MESSAGES,ChainAbstractionError,ConnectorManager,DEFAULT_BUILTIN_TOKENS,DEFAULT_CALL_GAS_LIMIT,DEFAULT_ENTRY_POINT,DEFAULT_EVM_CHAIN,DEFAULT_NONCE_LENGTH,DEFAULT_PRE_VERIFICATION_GAS,DEFAULT_RPC_URLS,DEFAULT_SESSION_KEY_CONFIG,DEFAULT_SOLANA_CLUSTER,DEFAULT_SOURCES,DEFAULT_VERIFICATION_GAS_LIMIT,DEFAULT_XRPL_NETWORK,EIP155_ARBITRUM,EIP155_ARBITRUM_GOERLI,EIP155_BASE,EIP155_GOERLI,EIP155_MAINNET,EIP155_MUMBAI,EIP155_OPTIMISM,EIP155_OPTIMISM_GOERLI,EIP155_POLYGON,EIP155_SEPOLIA,ENSProvider,ENTRY_POINT_V0_6,ENTRY_POINT_V0_7,ERC20TokenError,ERC20TokenHelper,ERC20_FUNCTION_SIGNATURES,ERC20_MIN_ABI,ETHEREUM_MAINNET_TOKENS,EthCallProvider,FEE_ERROR_MESSAGES,FeeEstimationError,InAppChannel,LiFiProvider,LocalStorageAdapter,LocalStorageSessionStorage,MemoryStorageAdapter,NAMESPACE_EIP155,NAMESPACE_SOLANA,NAMESPACE_XRPL,NameResolver,NoopChannel,NoopStorageAdapter,Notifier,OPTIMISM_TOKENS,POLYGON_TOKENS,PaymasterService,ResolutionError,ResolverCache,RouteEngine,SESSION_ERROR_MESSAGES,SESSION_KEY_ERROR_MESSAGES,SESSION_TIMEOUT_MS,SIMPLE_ACCOUNT_FACTORY,SNSProvider,SOLANA_DEVNET,SOLANA_MAINNET,SOLANA_TESTNET,STORAGE_KEYS,SUPPORTED_NAMESPACES,SessionEventEmitter,SessionKeyManager,SessionKeyStorage,SessionManager,SessionPersistence,SessionStorageAdapter,SimulationManager,SmartAccountManager,StorageError,TelegramChannel,TokenListManager,WC_DISCONNECT_SESSION_EXPIRED,WC_DISCONNECT_TIMEOUT,WC_DISCONNECT_USER,WalletError,XRPL_DEVNET,XRPL_MAINNET,XRPL_TESTNET,abiEncodeAddress,abiEncodeFunctionCall,abiEncodeUint256,abiFunctionSelector,buildCallData,buildUserOperation,clearAutoDetectCache,clearChainFeeEstimators,compareSimulationVsActual,createAutoReconnectManager,createConnectorManager,createEmptySession,createPaymasterService,createRouteEngine,createSessionError,createSessionKeyError,createSessionManager,createSessionPersistence,createStorageAdapter,decodeGasLimits,decryptPrivateKey,detectPlatform,detectTokenInfo,encodeGasLimits,encryptPrivateKey,estimateFees,estimateMaxPriorityFeePerGas,estimateUserOperationGas,extractAccounts,extractAccountsFromPermissions,formatUnits,getAllBuiltinTokens,getChainId,getChainsFromNamespaces,getEventsFromNamespaces,getFeeData,getGasPrice,getLatestBaseFee,getMethodsFromNamespaces,getNativeTokenPriceUsd,getPermissions,getRpcUrl,hasPermission,hashUserOperation,isAAError,isBurnAddress,isChainAbstractionError,isERC20TokenError,isFeeEstimationError,isMobileBrowser,isSessionExpired,isValidAddress,isWalletError,isZeroAddress,logger,parseBigInt,parseChainId,parseUnits,registerChainFeeEstimator,requestPermissions,sendUserOperation,setLogLevel,setLogSink,signUserOperation,toDecString,toHumanReadable,unregisterChainFeeEstimator,updateSession,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.cjs.map
|