keyring-chatbot-agent 1.0.6 → 1.0.7

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.
@@ -6,7 +6,7 @@ return e(t,{children:oh(r||"")&&/* @__PURE__ */n("div",{className:"chat-user-inf
6
6
  /* @__PURE__ */n("span",{className:"user-wallet",children:[
7
7
  /* @__PURE__ */n("span",{className:"mr-2",children:[Fn[o]?.customName||Fn[o]?.name||`Chain ${o}`,":"]}),
8
8
  /* @__PURE__ */e("a",{style:{pointerEvents:u?"auto":"none"},href:Fn[o]?.blockExplorers?.default?.url+"/address/"+r,target:"_blank",rel:"noopener noreferrer",children:th(r)||"Not connected"})]}),
9
- /* @__PURE__ */e("button",{className:"copy-address-btn",onClick:l,"aria-label":"Copy wallet address",type:"button",title:a?"Copied!":"Copy address",children:/* @__PURE__ */e("svg",a?{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:/* @__PURE__ */e("path",{d:"M13.3333 4L6 11.3333L2.66667 8",stroke:"#0B3988",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}:{width:"14",height:"14",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:/* @__PURE__ */e("path",{d:"M8.1 15.75H13.23C12.9638 16.4152 12.5041 16.9852 11.9105 17.3863C11.3168 17.7874 10.6165 18.0012 9.9 18H3.6C2.64522 18 1.72955 17.6207 1.05442 16.9456C0.379285 16.2704 0 15.3548 0 14.4V7.2C0.00104929 6.32332 0.321408 5.47704 0.901163 4.81944C1.48092 4.16183 2.28037 3.73792 3.15 3.627V10.8C3.15238 12.1121 3.67466 13.3698 4.60245 14.2975C5.53024 15.2253 6.78791 15.7476 8.1 15.75ZM15.75 3.825H17.658C17.6027 3.74389 17.5393 3.66852 17.469 3.6L14.4 0.531C14.3337 0.460854 14.258 0.400274 14.175 0.351V2.25C14.1769 2.66713 14.3434 3.06664 14.6384 3.3616C14.9334 3.65656 15.3329 3.8231 15.75 3.825ZM15.75 5.175C14.9747 5.17357 14.2315 4.86494 13.6833 4.31671C13.1351 3.76847 12.8264 3.02532 12.825 2.25V0H8.1C7.14522 0 6.22955 0.379285 5.55442 1.05442C4.87928 1.72955 4.5 2.64522 4.5 3.6V10.8C4.5 11.7548 4.87928 12.6704 5.55442 13.3456C6.22955 14.0207 7.14522 14.4 8.1 14.4H14.4C15.3548 14.4 16.2705 14.0207 16.9456 13.3456C17.6207 12.6704 18 11.7548 18 10.8V5.175H15.75Z",fill:"#0B3988"})})})]})})},lh="chat_widget_messages",dh=200,fh="welcome-message";function hh(e){return[{id:fh,text:e,sender:"bot",timestamp:/* @__PURE__ */new Date}]}function ph(e){return e.map(e=>({...e,timestamp:new Date(e.timestamp)}))}function mh(){const e=ih.getItem(lh);if(!e)return null;try{const t=JSON.parse(e);if(t&&void 0!==t.owner&&Array.isArray(t.messages))return{owner:t.owner,messages:ph(t.messages)};if(Array.isArray(t))return{owner:"",messages:ph(t)}}catch{}return null}function wh(e,t){ih.setItem(lh,JSON.stringify({owner:e,messages:t}))}const bh=a(void 0),gh=({children:t,initialConfig:n})=>/* @__PURE__ */e(bh.Provider,{value:{config:n||null},children:t});var yh=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,vh=Math.ceil,Ah=Math.floor,kh="[BigNumber Error] ",xh=kh+"Number primitive has more than 15 significant digits: ",Eh=1e14,Th=14,Ch=9007199254740991,Ih=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Sh=1e7,Nh=1e9;function Bh(e){var t=0|e;return e>0||e===t?t:t-1}function Mh(e){for(var t,n,r=1,i=e.length,o=e[0]+"";r<i;){for(t=e[r++]+"",n=Th-t.length;n--;t="0"+t);o+=t}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function Uh(e,t){var n,r,i=e.c,o=t.c,s=e.s,a=t.s,c=e.e,u=t.e;if(!s||!a)return null;if(n=i&&!i[0],r=o&&!o[0],n||r)return n?r?0:-a:s;if(s!=a)return s;if(n=s<0,r=c==u,!i||!o)return r?0:!i^n?1:-1;if(!r)return c>u^n?1:-1;for(a=(c=i.length)<(u=o.length)?c:u,s=0;s<a;s++)if(i[s]!=o[s])return i[s]>o[s]^n?1:-1;return c==u?0:c>u^n?1:-1}function Rh(e,t,n,r){if(e<t||e>n||e!==Ah(e))throw Error(kh+(r||"Argument")+("number"==typeof e?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function Oh(e){var t=e.c.length-1;return Bh(e.e/Th)==t&&e.c[t]%2!=0}function Fh(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function Lh(e,t,n){var r,i;if(t<0){for(i=n+".";++t;i+=n);e=i+e}else if(++t>(r=e.length)){for(i=n,t-=r;--t;i+=n);e+=i}else t<r&&(e=e.slice(0,t)+"."+e.slice(t));return e}var Dh=function e(t){var n,r,i,o,s,a=A.prototype={constructor:A,toString:null,valueOf:null},c=new A(1),u=20,l=4,d=-7,f=21,h=-1e7,p=1e7,m=!1,w=1,b=0,g={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},y="0123456789abcdefghijklmnopqrstuvwxyz",v=!0;function A(e,t){var n,o,s,a,c,d,f,m,w=this;if(!(w instanceof A))return new A(e,t);if(null==t){if(e&&!0===e.Me)return w.s=e.s,void(!e.c||e.e>p?w.c=w.e=null:e.e<h?w.c=[w.e=0]:(w.e=e.e,w.c=e.c.slice()));if((d="number"==typeof e)&&0*e==0){if(w.s=1/e<0?(e=-e,-1):1,e===~~e){for(a=0,c=e;c>=10;c/=10,a++);return void(a>p?w.c=w.e=null:(w.e=a,w.c=[e]))}m=String(e)}else{if(!yh.test(m=String(e)))return i(w,m,d);w.s=45==m.charCodeAt(0)?(m=m.slice(1),-1):1}(a=m.indexOf("."))>-1&&(m=m.replace(".","")),(c=m.search(/e/i))>0?(a<0&&(a=c),a+=+m.slice(c+1),m=m.substring(0,c)):a<0&&(a=m.length)}else{if(Rh(t,2,y.length,"Base"),10==t&&v)return T(w=new A(e),u+w.e+1,l);if(m=String(e),d="number"==typeof e){if(0*e!=0)return i(w,m,d,t);if(w.s=1/e<0?(m=m.slice(1),-1):1,A.DEBUG&&m.replace(/^0\.0*|\./,"").length>15)throw Error(xh+e)}else w.s=45===m.charCodeAt(0)?(m=m.slice(1),-1):1;for(n=y.slice(0,t),a=c=0,f=m.length;c<f;c++)if(n.indexOf(o=m.charAt(c))<0){if("."==o){if(c>a){a=f;continue}}else if(!s&&(m==m.toUpperCase()&&(m=m.toLowerCase())||m==m.toLowerCase()&&(m=m.toUpperCase()))){s=!0,c=-1,a=0;continue}return i(w,String(e),d,t)}d=!1,(a=(m=r(m,t,10,w.s)).indexOf("."))>-1?m=m.replace(".",""):a=m.length}for(c=0;48===m.charCodeAt(c);c++);for(f=m.length;48===m.charCodeAt(--f););if(m=m.slice(c,++f)){if(f-=c,d&&A.DEBUG&&f>15&&(e>Ch||e!==Ah(e)))throw Error(xh+w.s*e);if((a=a-c-1)>p)w.c=w.e=null;else if(a<h)w.c=[w.e=0];else{if(w.e=a,w.c=[],c=(a+1)%Th,a<0&&(c+=Th),c<f){for(c&&w.c.push(+m.slice(0,c)),f-=Th;c<f;)w.c.push(+m.slice(c,c+=Th));c=Th-(m=m.slice(c)).length}else c-=f;for(;c--;m+="0");w.c.push(+m)}}else w.c=[w.e=0]}function k(e,t,n,r){var i,o,s,a,c;if(null==n?n=l:Rh(n,0,8),!e.c)return e.toString();if(i=e.c[0],s=e.e,null==t)c=Mh(e.c),c=1==r||2==r&&(s<=d||s>=f)?Fh(c,s):Lh(c,s,"0");else if(o=(e=T(new A(e),t,n)).e,a=(c=Mh(e.c)).length,1==r||2==r&&(t<=o||o<=d)){for(;a<t;c+="0",a++);c=Fh(c,o)}else if(t-=s+(2===r&&o>s),c=Lh(c,o,"0"),o+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=o-a)>0)for(o+1==a&&(c+=".");t--;c+="0");return e.s<0&&i?"-"+c:c}function x(e,t){for(var n,r,i=1,o=new A(e[0]);i<e.length;i++)(!(r=new A(e[i])).s||(n=Uh(o,r))===t||0===n&&o.s===t)&&(o=r);return o}function E(e,t,n){for(var r=1,i=t.length;!t[--i];t.pop());for(i=t[0];i>=10;i/=10,r++);return(n=r+n*Th-1)>p?e.c=e.e=null:n<h?e.c=[e.e=0]:(e.e=n,e.c=t),e}function T(e,t,n,r){var i,o,s,a,c,u,l,d=e.c,f=Ih;if(d){e:{for(i=1,a=d[0];a>=10;a/=10,i++);if((o=t-i)<0)o+=Th,s=t,c=d[u=0],l=Ah(c/f[i-s-1]%10);else if((u=vh((o+1)/Th))>=d.length){if(!r)break e;for(;d.length<=u;d.push(0));c=l=0,i=1,s=(o%=Th)-Th+1}else{for(c=a=d[u],i=1;a>=10;a/=10,i++);l=(s=(o%=Th)-Th+i)<0?0:Ah(c/f[i-s-1]%10)}if(r=r||t<0||null!=d[u+1]||(s<0?c:c%f[i-s-1]),r=n<4?(l||r)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||r||6==n&&(o>0?s>0?c/f[i-s]:0:d[u-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,r?(t-=e.e+1,d[0]=f[(Th-t%Th)%Th],e.e=-t||0):d[0]=e.e=0,e;if(0==o?(d.length=u,a=1,u--):(d.length=u+1,a=f[Th-o],d[u]=s>0?Ah(c/f[i-s]%f[s])*a:0),r)for(;;){if(0==u){for(o=1,s=d[0];s>=10;s/=10,o++);for(s=d[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(e.e++,d[0]==Eh&&(d[0]=1));break}if(d[u]+=a,d[u]!=Eh)break;d[u--]=0,a=1}for(o=d.length;0===d[--o];d.pop());}e.e>p?e.c=e.e=null:e.e<h&&(e.c=[e.e=0])}return e}function C(e){var t,n=e.e;return null===n?e.toString():(t=Mh(e.c),t=n<=d||n>=f?Fh(t,n):Lh(t,n,"0"),e.s<0?"-"+t:t)}return A.clone=e,A.ROUND_UP=0,A.ROUND_DOWN=1,A.ROUND_CEIL=2,A.ROUND_FLOOR=3,A.ROUND_HALF_UP=4,A.ROUND_HALF_DOWN=5,A.ROUND_HALF_EVEN=6,A.ROUND_HALF_CEIL=7,A.ROUND_HALF_FLOOR=8,A.EUCLID=9,A.config=A.set=function(e){var t,n;if(null!=e){if("object"!=typeof e)throw Error(kh+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(Rh(n=e[t],0,Nh,t),u=n),e.hasOwnProperty(t="ROUNDING_MODE")&&(Rh(n=e[t],0,8,t),l=n),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((n=e[t])&&n.pop?(Rh(n[0],-Nh,0,t),Rh(n[1],0,Nh,t),d=n[0],f=n[1]):(Rh(n,-Nh,Nh,t),d=-(f=n<0?-n:n))),e.hasOwnProperty(t="RANGE"))if((n=e[t])&&n.pop)Rh(n[0],-Nh,-1,t),Rh(n[1],1,Nh,t),h=n[0],p=n[1];else{if(Rh(n,-Nh,Nh,t),!n)throw Error(kh+t+" cannot be zero: "+n);h=-(p=n<0?-n:n)}if(e.hasOwnProperty(t="CRYPTO")){if((n=e[t])!==!!n)throw Error(kh+t+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw m=!n,Error(kh+"crypto unavailable");m=n}else m=n}if(e.hasOwnProperty(t="MODULO_MODE")&&(Rh(n=e[t],0,9,t),w=n),e.hasOwnProperty(t="POW_PRECISION")&&(Rh(n=e[t],0,Nh,t),b=n),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(n=e[t]))throw Error(kh+t+" not an object: "+n);g=n}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(n=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(kh+t+" invalid: "+n);v="0123456789"==n.slice(0,10),y=n}}return{DECIMAL_PLACES:u,ROUNDING_MODE:l,EXPONENTIAL_AT:[d,f],RANGE:[h,p],CRYPTO:m,MODULO_MODE:w,POW_PRECISION:b,FORMAT:g,ALPHABET:y}},A.isBigNumber=function(e){if(!e||!0!==e.Me)return!1;if(!A.DEBUG)return!0;var t,n,r=e.c,i=e.e,o=e.s;e:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Nh&&i<=Nh&&i===Ah(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break e}if((t=(i+1)%Th)<1&&(t+=Th),String(r[0]).length==t){for(t=0;t<r.length;t++)if((n=r[t])<0||n>=Eh||n!==Ah(n))break e;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(kh+"Invalid BigNumber: "+e)},A.maximum=A.max=function(){return x(arguments,-1)},A.minimum=A.min=function(){return x(arguments,1)},A.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Ah(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,n,r,i,o,a=0,l=[],d=new A(c);if(null==e?e=u:Rh(e,0,Nh),i=vh(e/Th),m)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(i*=2));a<i;)(o=131072*t[a]+(t[a+1]>>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),t[a]=n[0],t[a+1]=n[1]):(l.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw m=!1,Error(kh+"crypto unavailable");for(t=crypto.randomBytes(i*=7);a<i;)(o=281474976710656*(31&t[a])+1099511627776*t[a+1]+4294967296*t[a+2]+16777216*t[a+3]+(t[a+4]<<16)+(t[a+5]<<8)+t[a+6])>=9e15?crypto.randomBytes(7).copy(t,a):(l.push(o%1e14),a+=7);a=i/7}if(!m)for(;a<i;)(o=s())<9e15&&(l[a++]=o%1e14);for(i=l[--a],e%=Th,i&&e&&(o=Ih[Th-e],l[a]=Ah(i/o)*o);0===l[a];l.pop(),a--);if(a<0)l=[r=0];else{for(r=-1;0===l[0];l.splice(0,1),r-=Th);for(a=1,o=l[0];o>=10;o/=10,a++);a<Th&&(r-=Th-a)}return d.e=r,d.c=l,d}),A.sum=function(){for(var e=1,t=arguments,n=new A(t[0]);e<t.length;)n=n.plus(t[e++]);return n},r=/* @__PURE__ */function(){var e="0123456789";function t(e,t,n,r){for(var i,o,s=[0],a=0,c=e.length;a<c;){for(o=s.length;o--;s[o]*=t);for(s[0]+=r.indexOf(e.charAt(a++)),i=0;i<s.length;i++)s[i]>n-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var c,d,f,h,p,m,w,g,v=r.indexOf("."),k=u,x=l;for(v>=0&&(h=b,b=0,r=r.replace(".",""),m=(g=new A(i)).pow(r.length-v),b=h,g.c=t(Lh(Mh(m.c),m.e,"0"),10,o,e),g.e=g.c.length),f=h=(w=t(r,i,o,a?(c=y,e):(c=e,y))).length;0==w[--h];w.pop());if(!w[0])return c.charAt(0);if(v<0?--f:(m.c=w,m.e=f,m.s=s,w=(m=n(m,g,k,x,o)).c,p=m.r,f=m.e),v=w[d=f+k+1],h=o/2,p=p||d<0||null!=w[d+1],p=x<4?(null!=v||p)&&(0==x||x==(m.s<0?3:2)):v>h||v==h&&(4==x||p||6==x&&1&w[d-1]||x==(m.s<0?8:7)),d<1||!w[0])r=p?Lh(c.charAt(1),-k,c.charAt(0)):c.charAt(0);else{if(w.length=d,p)for(--o;++w[--d]>o;)w[d]=0,d||(++f,w=[1].concat(w));for(h=w.length;!w[--h];);for(v=0,r="";v<=h;r+=c.charAt(w[v++]));r=Lh(r,f,c.charAt(0))}return r}}(),n=/* @__PURE__ */function(){function e(e,t,n){var r,i,o,s,a=0,c=e.length,u=t%Sh,l=t/Sh|0;for(e=e.slice();c--;)a=((i=u*(o=e[c]%Sh)+(r=l*o+(s=e[c]/Sh|0)*u)%Sh*Sh+a)/n|0)+(r/Sh|0)+l*s,e[c]=i%n;return a&&(e=[a].concat(e)),e}function t(e,t,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;i<n;i++)if(e[i]!=t[i]){o=e[i]>t[i]?1:-1;break}return o}function n(e,t,n,r){for(var i=0;n--;)e[n]-=i,i=e[n]<t[n]?1:0,e[n]=i*r+e[n]-t[n];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(r,i,o,s,a){var c,u,l,d,f,h,p,m,w,b,g,y,v,k,x,E,C,I=r.s==i.s?1:-1,S=r.c,N=i.c;if(!(S&&S[0]&&N&&N[0]))return new A(r.s&&i.s&&(S?!N||S[0]!=N[0]:N)?S&&0==S[0]||!N?0*I:I/0:NaN);for(w=(m=new A(I)).c=[],I=o+(u=r.e-i.e)+1,a||(a=Eh,u=Bh(r.e/Th)-Bh(i.e/Th),I=I/Th|0),l=0;N[l]==(S[l]||0);l++);if(N[l]>(S[l]||0)&&u--,I<0)w.push(1),d=!0;else{for(k=S.length,E=N.length,l=0,I+=2,(f=Ah(a/(N[0]+1)))>1&&(N=e(N,f,a),S=e(S,f,a),E=N.length,k=S.length),v=E,g=(b=S.slice(0,E)).length;g<E;b[g++]=0);C=N.slice(),C=[0].concat(C),x=N[0],N[1]>=a/2&&x++;do{if(f=0,(c=t(N,b,E,g))<0){if(y=b[0],E!=g&&(y=y*a+(b[1]||0)),(f=Ah(y/x))>1)for(f>=a&&(f=a-1),p=(h=e(N,f,a)).length,g=b.length;1==t(h,b,p,g);)f--,n(h,E<p?C:N,p,a),p=h.length,c=1;else 0==f&&(c=f=1),p=(h=N.slice()).length;if(p<g&&(h=[0].concat(h)),n(b,h,g,a),g=b.length,-1==c)for(;t(N,b,E,g)<1;)f++,n(b,E<g?C:N,g,a),g=b.length}else 0===c&&(f++,b=[0]);w[l++]=f,b[0]?b[g++]=S[v]||0:(b=[S[v]],g=1)}while((v++<k||null!=b[0])&&I--);d=null!=b[0],w[0]||w.splice(0,1)}if(a==Eh){for(l=1,I=w[0];I>=10;I/=10,l++);T(m,o+(m.e=l+u*Th-1)+1,s,d)}else m.e=u,m.r=+d;return m}}(),i=/* @__PURE__ */function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,t=/^([^.]+)\.$/,n=/^\.([^.]+)$/,r=/^-?(Infinity|NaN)$/,i=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,s,a,c){var u,l=a?s:s.replace(i,"");if(r.test(l))o.s=isNaN(l)?null:l<0?-1:1;else{if(!a&&(l=l.replace(e,function(e,t,n){return u="x"==(n=n.toLowerCase())?16:"b"==n?2:8,c&&c!=u?e:t}),c&&(u=c,l=l.replace(t,"$1").replace(n,"0.$1")),s!=l))return new A(l,u);if(A.DEBUG)throw Error(kh+"Not a"+(c?" base "+c:"")+" number: "+s);o.s=null}o.c=o.e=null}}(),a.absoluteValue=a.abs=function(){var e=new A(this);return e.s<0&&(e.s=1),e},a.comparedTo=function(e,t){return Uh(this,new A(e,t))},a.decimalPlaces=a.dp=function(e,t){var n,r,i,o=this;if(null!=e)return Rh(e,0,Nh),null==t?t=l:Rh(t,0,8),T(new A(o),e+o.e+1,t);if(!(n=o.c))return null;if(r=((i=n.length-1)-Bh(this.e/Th))*Th,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},a.dividedBy=a.div=function(e,t){return n(this,new A(e,t),u,l)},a.dividedToIntegerBy=a.idiv=function(e,t){return n(this,new A(e,t),0,1)},a.exponentiatedBy=a.pow=function(e,t){var n,r,i,o,s,a,u,d,f=this;if((e=new A(e)).c&&!e.isInteger())throw Error(kh+"Exponent not an integer: "+C(e));if(null!=t&&(t=new A(t)),s=e.e>14,!f.c||!f.c[0]||1==f.c[0]&&!f.e&&1==f.c.length||!e.c||!e.c[0])return d=new A(Math.pow(+C(f),s?e.s*(2-Oh(e)):+C(e))),t?d.mod(t):d;if(a=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new A(NaN);(r=!a&&f.isInteger()&&t.isInteger())&&(f=f.mod(t))}else{if(e.e>9&&(f.e>0||f.e<-1||(0==f.e?f.c[0]>1||s&&f.c[1]>=24e7:f.c[0]<8e13||s&&f.c[0]<=9999975e7)))return o=f.s<0&&Oh(e)?-0:0,f.e>-1&&(o=1/o),new A(a?1/o:o);b&&(o=vh(b/Th+2))}for(s?(n=new A(.5),a&&(e.s=1),u=Oh(e)):u=(i=Math.abs(+C(e)))%2,d=new A(c);;){if(u){if(!(d=d.times(f)).c)break;o?d.c.length>o&&(d.c.length=o):r&&(d=d.mod(t))}if(i){if(0===(i=Ah(i/2)))break;u=i%2}else if(T(e=e.times(n),e.e+1,1),e.e>14)u=Oh(e);else{if(0===(i=+C(e)))break;u=i%2}f=f.times(f),o?f.c&&f.c.length>o&&(f.c.length=o):r&&(f=f.mod(t))}return r?d:(a&&(d=c.div(d)),t?d.mod(t):o?T(d,b,l,void 0):d)},a.integerValue=function(e){var t=new A(this);return null==e?e=l:Rh(e,0,8),T(t,t.e+1,e)},a.isEqualTo=a.eq=function(e,t){return 0===Uh(this,new A(e,t))},a.isFinite=function(){return!!this.c},a.isGreaterThan=a.gt=function(e,t){return Uh(this,new A(e,t))>0},a.isGreaterThanOrEqualTo=a.gte=function(e,t){return 1===(t=Uh(this,new A(e,t)))||0===t},a.isInteger=function(){return!!this.c&&Bh(this.e/Th)>this.c.length-2},a.isLessThan=a.lt=function(e,t){return Uh(this,new A(e,t))<0},a.isLessThanOrEqualTo=a.lte=function(e,t){return-1===(t=Uh(this,new A(e,t)))||0===t},a.isNaN=function(){return!this.s},a.isNegative=function(){return this.s<0},a.isPositive=function(){return this.s>0},a.isZero=function(){return!!this.c&&0==this.c[0]},a.minus=function(e,t){var n,r,i,o,s=this,a=s.s;if(t=(e=new A(e,t)).s,!a||!t)return new A(NaN);if(a!=t)return e.s=-t,s.plus(e);var c=s.e/Th,u=e.e/Th,d=s.c,f=e.c;if(!c||!u){if(!d||!f)return d?(e.s=-t,e):new A(f?s:NaN);if(!d[0]||!f[0])return f[0]?(e.s=-t,e):new A(d[0]?s:3==l?-0:0)}if(c=Bh(c),u=Bh(u),d=d.slice(),a=c-u){for((o=a<0)?(a=-a,i=d):(u=c,i=f),i.reverse(),t=a;t--;i.push(0));i.reverse()}else for(r=(o=(a=d.length)<(t=f.length))?a:t,a=t=0;t<r;t++)if(d[t]!=f[t]){o=d[t]<f[t];break}if(o&&(i=d,d=f,f=i,e.s=-e.s),(t=(r=f.length)-(n=d.length))>0)for(;t--;d[n++]=0);for(t=Eh-1;r>a;){if(d[--r]<f[r]){for(n=r;n&&!d[--n];d[n]=t);--d[n],d[r]+=Eh}d[r]-=f[r]}for(;0==d[0];d.splice(0,1),--u);return d[0]?E(e,d,u):(e.s=3==l?-1:1,e.c=[e.e=0],e)},a.modulo=a.mod=function(e,t){var r,i,o=this;return e=new A(e,t),!o.c||!e.s||e.c&&!e.c[0]?new A(NaN):!e.c||o.c&&!o.c[0]?new A(o):(9==w?(i=e.s,e.s=1,r=n(o,e,0,3),e.s=i,r.s*=i):r=n(o,e,0,w),(e=o.minus(r.times(e))).c[0]||1!=w||(e.s=o.s),e)},a.multipliedBy=a.times=function(e,t){var n,r,i,o,s,a,c,u,l,d,f,h,p,m,w,b=this,g=b.c,y=(e=new A(e,t)).c;if(!(g&&y&&g[0]&&y[0]))return!b.s||!e.s||g&&!g[0]&&!y||y&&!y[0]&&!g?e.c=e.e=e.s=null:(e.s*=b.s,g&&y?(e.c=[0],e.e=0):e.c=e.e=null),e;for(r=Bh(b.e/Th)+Bh(e.e/Th),e.s*=b.s,(c=g.length)<(d=y.length)&&(p=g,g=y,y=p,i=c,c=d,d=i),i=c+d,p=[];i--;p.push(0));for(m=Eh,w=Sh,i=d;--i>=0;){for(n=0,f=y[i]%w,h=y[i]/w|0,o=i+(s=c);o>i;)n=((u=f*(u=g[--s]%w)+(a=h*u+(l=g[s]/w|0)*f)%w*w+p[o]+n)/m|0)+(a/w|0)+h*l,p[o--]=u%m;p[o]=n}return n?++r:p.splice(0,1),E(e,p,r)},a.negated=function(){var e=new A(this);return e.s=-e.s||null,e},a.plus=function(e,t){var n,r=this,i=r.s;if(t=(e=new A(e,t)).s,!i||!t)return new A(NaN);if(i!=t)return e.s=-t,r.minus(e);var o=r.e/Th,s=e.e/Th,a=r.c,c=e.c;if(!o||!s){if(!a||!c)return new A(i/0);if(!a[0]||!c[0])return c[0]?e:new A(a[0]?r:0*i)}if(o=Bh(o),s=Bh(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=c):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(t=c.length)<0&&(n=c,c=a,a=n,t=i),i=0;t;)i=(a[--t]=a[t]+c[t]+i)/Eh|0,a[t]=Eh===a[t]?0:a[t]%Eh;return i&&(a=[i].concat(a),++s),E(e,a,s)},a.precision=a.sd=function(e,t){var n,r,i,o=this;if(null!=e&&e!==!!e)return Rh(e,1,Nh),null==t?t=l:Rh(t,0,8),T(new A(o),e,t);if(!(n=o.c))return null;if(r=(i=n.length-1)*Th+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return e&&o.e+1>r&&(r=o.e+1),r},a.shiftedBy=function(e){return Rh(e,-9007199254740991,Ch),this.times("1e"+e)},a.squareRoot=a.sqrt=function(){var e,t,r,i,o,s=this,a=s.c,c=s.s,d=s.e,f=u+4,h=new A("0.5");if(1!==c||!a||!a[0])return new A(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(c=Math.sqrt(+C(s)))||c==1/0?(((t=Mh(a)).length+d)%2==0&&(t+="0"),c=Math.sqrt(+t),d=Bh((d+1)/2)-(d<0||d%2),r=new A(t=c==1/0?"5e"+d:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+d)):r=new A(c+""),r.c[0])for((c=(d=r.e)+f)<3&&(c=0);;)if(o=r,r=h.times(o.plus(n(s,o,f,1))),Mh(o.c).slice(0,c)===(t=Mh(r.c)).slice(0,c)){if(r.e<d&&--c,"9999"!=(t=t.slice(c-3,c+1))&&(i||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(T(r,r.e+u+2,1),e=!r.times(r).eq(s));break}if(!i&&(T(o,o.e+u+2,0),o.times(o).eq(s))){r=o;break}f+=4,c+=4,i=1}return T(r,r.e+u+1,l,e)},a.toExponential=function(e,t){return null!=e&&(Rh(e,0,Nh),e++),k(this,e,t,1)},a.toFixed=function(e,t){return null!=e&&(Rh(e,0,Nh),e=e+this.e+1),k(this,e,t)},a.toFormat=function(e,t,n){var r,i=this;if(null==n)null!=e&&t&&"object"==typeof t?(n=t,t=null):e&&"object"==typeof e?(n=e,e=t=null):n=g;else if("object"!=typeof n)throw Error(kh+"Argument not an object: "+n);if(r=i.toFixed(e,t),i.c){var o,s=r.split("."),a=+n.groupSize,c=+n.secondaryGroupSize,u=n.groupSeparator||"",l=s[0],d=s[1],f=i.s<0,h=f?l.slice(1):l,p=h.length;if(c&&(o=a,a=c,c=o,p-=o),a>0&&p>0){for(o=p%a||a,l=h.substr(0,o);o<p;o+=a)l+=u+h.substr(o,a);c>0&&(l+=u+h.slice(o)),f&&(l="-"+l)}r=d?l+(n.decimalSeparator||"")+((c=+n.fractionGroupSize)?d.replace(new RegExp("\\d{"+c+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):d):l}return(n.prefix||"")+r+(n.suffix||"")},a.toFraction=function(e){var t,r,i,o,s,a,u,d,f,h,m,w,b=this,g=b.c;if(null!=e&&(!(u=new A(e)).isInteger()&&(u.c||1!==u.s)||u.lt(c)))throw Error(kh+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+C(u));if(!g)return new A(b);for(t=new A(c),f=r=new A(c),i=d=new A(c),w=Mh(g),s=t.e=w.length-b.e-1,t.c[0]=Ih[(a=s%Th)<0?Th+a:a],e=!e||u.comparedTo(t)>0?s>0?t:f:u,a=p,p=1/0,u=new A(w),d.c[0]=0;h=n(u,t,0,1),1!=(o=r.plus(h.times(i))).comparedTo(e);)r=i,i=o,f=d.plus(h.times(o=f)),d=o,t=u.minus(h.times(o=t)),u=o;return o=n(e.minus(r),i,0,1),d=d.plus(o.times(f)),r=r.plus(o.times(i)),d.s=f.s=b.s,m=n(f,i,s*=2,l).minus(b).abs().comparedTo(n(d,r,s,l).minus(b).abs())<1?[f,i]:[d,r],p=a,m},a.toNumber=function(){return+C(this)},a.toPrecision=function(e,t){return null!=e&&Rh(e,1,Nh),k(this,e,t,2)},a.toString=function(e){var t,n=this,i=n.s,o=n.e;return null===o?i?(t="Infinity",i<0&&(t="-"+t)):t="NaN":(null==e?t=o<=d||o>=f?Fh(Mh(n.c),o):Lh(Mh(n.c),o,"0"):10===e&&v?t=Lh(Mh((n=T(new A(n),u+o+1,l)).c),n.e,"0"):(Rh(e,2,y.length,"Base"),t=r(Lh(Mh(n.c),o,"0"),10,e,i,!0)),i<0&&n.c[0]&&(t="-"+t)),t},a.valueOf=a.toJSON=function(){return C(this)},a.Me=!0,a[Symbol.toStringTag]="BigNumber",a[/* @__PURE__ */Symbol.for("nodejs.util.inspect.custom")]=a.valueOf,null!=t&&A.set(t),A}();class Ph{baseUrl;constructor(e){this.baseUrl=e}buildUrl(e,t){const n=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([e,t])=>{null!=t&&n.searchParams.append(e,String(t))}),n.toString()}async get(e,t={}){const n=this.buildUrl(e,t.query),r=await fetch(n,{method:"GET",headers:t.headers||{},signal:t.signal});if(!r.ok){let e=null;try{e=await r.json()}catch{try{const t=await r.text();t&&(e={message:t})}catch{}}const t=new Error(e?.message||e?.errorMessage||`HTTP ${r.status}: ${r.statusText}`);throw t.status=r.status,t.statusText=r.statusText,e&&(t.data=e),t}return{data:await r.json(),status:r.status}}async post(e,t,n={}){const r=this.buildUrl(e,n.query),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...n.headers},body:JSON.stringify(t),signal:n.signal});if(!i.ok){let e=null;try{e=await i.json()}catch{try{const t=await i.text();t&&(e={message:t})}catch{}}const t=new Error(e?.message||e?.errorMessage||`HTTP ${i.status}: ${i.statusText}`);throw t.status=i.status,t.statusText=i.statusText,e&&(t.data=e),t}return{data:await i.json(),status:i.status}}}function Hh(e,t){return new Promise(n=>{const r=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}const jh=new Ph("https://wallet-api.pantograph.app"),zh="https://nft-demo.keyring.app",Jh=new Ph(zh);async function qh(e){const{address:t,chain:n="base",token_addresses:r,exclude_spam:i,exclude_unverified_contracts:o}=e;if(!t)throw new Error("Address is required");let s="Unknown error";for(let u=1;u<=5;u++)try{const e={chain:n,exclude_spam:i??!1,exclude_unverified_contracts:o??!1};r&&(e.token_addresses=r);const s=(await Jh.get(`api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens`,{query:e})).data;if(s?.result?.length>0){s.result=s.result.filter(e=>new Dh(e?.balance||0).gt(0)),s.result=s.result.map(e=>({...e,token_address:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"===e.token_address?xn:e.token_address}));try{if(s.result.length>0){const e=Ln(n)??n,t=s.result.map(e=>e.token_address),r=await jh.get(`/keyrings/tokens/${e}/v2`,{query:{addresses:t.join(",")}});if(Array.isArray(r.data)){const e=/* @__PURE__ */new Map;for(const t of r.data)t.address&&e.set(t.address.toLowerCase(),{price:null!=t.price?parseFloat(String(t.price)):NaN,icon_image:t.icon_image});s.result=s.result.map(t=>{const n=e.get(t.token_address.toLowerCase());if(!n)return t;const r={...t};return n.icon_image&&(r.logo=n.icon_image,r.thumbnail=n.icon_image),isNaN(n.price)||(r.usd_price=n.price,r.usd_value=Dh(t.balance_formatted||"0").multipliedBy(n.price).toNumber()),r}),s.result=s.result.filter(e=>null==e.usd_value||new Dh(e.usd_value).gte(.01))}}}catch(a){}}return{success:!0,data:s}}catch(c){s=c instanceof Error?c.message:"Unknown error",u<5&&await Hh(1e3)}return{success:!1,error:s}}async function Vh(e){const{address:t,chain:n="base",signal:r}=e;if(!t)throw new Error("Token address is required");let i="Unknown error";for(let s=1;s<=5;s++){if(r?.aborted)return{success:!1,error:"Request cancelled"};try{const e=Ln(n)??n,o=await jh.get(`/keyrings/tokens/${e}/v2`,{query:{addresses:t},signal:r}),a=t===xn,c=(Array.isArray(o.data)?o.data:[]).find(e=>e.address?.toLowerCase()===t.toLowerCase()||a&&""===e.address)??null;if(c)return{success:!0,data:{token_address:c.address??t,name:c.name??"",symbol:c.symbol??"",decimals:null!=c.decimals?Number(c.decimals):18,logo:c.icon_image||c.logo,thumbnail:c.icon_image||c.logo,usd_price:null!=c.price?parseFloat(c.price):void 0,usd_price_24hr_percent_change:c.price_change_percentage_24h??void 0,usd_price_24hr_usd_change:c.price_change_24h??void 0}};const[u,l]=await Promise.allSettled([Jh.get("api/moralis/proxy/erc20/metadata",{query:{chain:n,addresses:[t]},signal:r}),Jh.get(`api/moralis/proxy/erc20/${encodeURIComponent(t)}/price`,{query:{chain:n,include:"percent_change"},signal:r})]),d="fulfilled"===u.status?u.value.data:[];if(!d||0===d.length){if(i="Token metadata not found",s<5&&await Hh(1e3,r),r?.aborted)return{success:!1,error:"Request cancelled"};continue}const f=d[0],h="fulfilled"===l.status?l.value.data:void 0;return{success:!0,data:{token_address:f.token_address,name:f.name,symbol:f.symbol,decimals:f.decimals,logo:f.logo||f.thumbnail,thumbnail:f.thumbnail,usd_price:h?.usdPrice??void 0,usd_price_24hr_percent_change:h?.["24hrPercentChange"]?parseFloat(h["24hrPercentChange"]):void 0,usd_price_24hr_usd_change:h?.usdPriceChange24hr??void 0}}}catch(o){if(r?.aborted)return{success:!1,error:"Request cancelled"};if(i=o instanceof Error?o.message:"Unknown error",s<5&&await Hh(1e3,r),r?.aborted)return{success:!1,error:"Request cancelled"}}}return{success:!1,error:i}}async function Yh(e){const{address:t,chain:n="base",limit:r=100,exclude_spam:i=!0,cursor:o,signal:s}=e;if(!t)throw new Error("Address is required");let a="Unknown error";for(let u=1;u<=5;u++){if(s?.aborted)return{success:!1,error:"Request cancelled"};try{const e={chain:n,format:"decimal",limit:r,exclude_spam:i,media_items:!0,normalizeMetadata:!0};o&&(e.cursor=o);return{success:!0,data:(await Jh.get(`api/moralis/proxy/${encodeURIComponent(t)}/nft`,{query:e,signal:s})).data}}catch(c){if(s?.aborted)return{success:!1,error:"Request cancelled"};if(a=c instanceof Error?c.message:"Unknown error",u<5&&await Hh(1e3,s),s?.aborted)return{success:!1,error:"Request cancelled"}}}return{success:!1,error:a}}const Gh=new class extends Ph{constructor(){super("https://wallet-api.pantograph.app")}async getTokensDetails(e,t="base"){try{if(!e||!Array.isArray(e)||0===e.length)throw new Error("Addresses must be a non-empty array");const n=e.join(","),r=await this.get(`/keyrings/tokens/${t}/v2`,{query:{addresses:n}});return Array.isArray(r.data)&&(r.data=r.data.filter((e,t,n)=>t===n.findIndex(t=>t.address.toLowerCase()===e.address.toLowerCase())),Array.isArray(e)&&e.length>0&&(r.data=r.data.filter(t=>e.some(e=>e.toLowerCase()===t.address.toLowerCase())),r.data.sort((t,n)=>e.findIndex(e=>e.toLowerCase()===t.address.toLowerCase())-e.findIndex(e=>e.toLowerCase()===n.address.toLowerCase())))),r}catch(n){throw n}}async getTokenDetail(e,t="base"){try{if(!e)throw new Error("Address is required");const n=await this.getTokensDetails([e],t);return{data:n.data[0]||null,status:n.status}}catch(n){throw n}}async getTopGainers(e="base",t="24h",n=3){try{return await this.get(`/token-list/top-gainers/${e}`,{query:{duration:t,limit:n}})}catch(r){throw r}}async searchTokensByKey(e,t){try{if(!e)throw new Error("key is required");const n=await this.get("/token-list",{query:{chainId:t,key:e}});let r=n.data;return r=Object.values(r).flat(),Array.isArray(r)&&(r=r.map(e=>({...e,decimals:null!=e.decimals?Number(e.decimals):18,price:null!=e.price?Number(e.price):void 0}))),n.data=r,n}catch(n){throw n}}},Wh=new Ph("https://dln.debridge.finance");async function Xh(e){const{chainId:t,tokenIn:n,tokenInAmount:r,tokenOut:i,accesstoken:o,slippage:s="auto",tokenOutRecipient:a}=e;if(!(t&&n&&r&&i))throw new Error("Missing required parameters: chainId, tokenIn, tokenInAmount, tokenOut");try{const e=await fetch("https://exchange-api.keyring.app/admin/setting?configs=others",{method:"GET"}),c=await e.json(),u=c?.others||{},l=u?.AFFILIATE_FEE_PERENT,d=u?.AFFILIATE_FEE_RECIPIENT,f=await Wh.get("/v1.0/chain/transaction",{query:{chainId:String(t),tokenIn:n,tokenInAmount:r,tokenOut:i,slippage:String(s),tokenOutRecipient:a,accesstoken:o,affiliateFeePercent:l,affiliateFeeRecipient:d}});if(f.data?.error)throw new Error(`DeBridge API Error: ${f.data.error}`);return{success:!0,data:f.data}}catch(c){let e=c instanceof Error?c.message:"Unknown error";const t=c;t.data?.errorMessage?e=t.data.errorMessage:t.response?.data?.errorMessage?e=t.response.data.errorMessage:t.data?.message?e=t.data.message:t.response?.data?.message&&(e=t.response.data.message);const n=t.status||t.response?.status||t.statusCode||t.data?.status;return{success:!1,error:c instanceof Error?c.message:"Unknown error",status:n,errorMessage:e,errorCode:t.data?.errorCode,errorId:t.data?.errorId}}}const Kh={send_native:{label:"actionSendNativeLabel",description:"actionSendNativeDesc",fields:[{key:"to_address",label:"fieldToAddress",type:"address",placeholder:"0x...",required:!0,validation:"address"},{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},send_token:{label:"actionSendTokenLabel",description:"actionSendTokenDesc",fields:[{key:"contract_address",label:"fieldTokenContract",type:"address",placeholder:"0x... token contract",required:!0,validation:"address",editable:!1},{key:"token_symbol",label:"fieldTokenSymbol",type:"text",placeholder:"e.g. USDC",required:!1,editable:!1},{key:"decimals",label:"fieldDecimals",type:"number",placeholder:"18",required:!1,editable:!1},{key:"to_address",label:"fieldToAddress",type:"address",placeholder:"0x...",required:!0,validation:"address"},{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},swap_token:{label:"actionSwapTokenLabel",description:"actionSwapTokenDesc",fields:[{key:"token_in",label:"fieldTokenIn",type:"address",placeholder:"0x... or native",required:!0,editable:!1},{key:"token_in_symbol",label:"fieldTokenInSymbol",type:"text",placeholder:"e.g. ETH",required:!1,editable:!1},{key:"token_out",label:"fieldTokenOut",type:"address",placeholder:"0x...",required:!0,editable:!1},{key:"token_out_symbol",label:"fieldTokenOutSymbol",type:"text",placeholder:"e.g. USDC",required:!1,editable:!1},{key:"token_in_decimals",label:"fieldTokenInDecimals",type:"number",placeholder:"18",required:!1,editable:!1},{key:"token_out_decimals",label:"fieldTokenOutDecimals",type:"number",placeholder:"18",required:!1,editable:!1},{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},approve_token:{label:"actionApproveTokenLabel",description:"actionApproveTokenDesc",fields:[{key:"contract_address",label:"fieldTokenContract",type:"address",placeholder:"0x... token contract",required:!0,validation:"address",editable:!1},{key:"token_symbol",label:"fieldTokenSymbol",type:"text",placeholder:"e.g. USDC",required:!1,editable:!1},{key:"spender_address",label:"fieldSpenderAddress",type:"address",placeholder:"0x... spender contract",required:!0,validation:"address",editable:!1},{key:"amount",label:"fieldAmountUnlimited",type:"amount",placeholder:"0.0 or leave empty for max",required:!1,validation:"amount"},{key:"decimals",label:"fieldDecimals",type:"number",placeholder:"18",required:!1,editable:!1}]},wrap_native:{label:"actionWrapNativeLabel",description:"actionWrapNativeDesc",fields:[{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},unwrap_native:{label:"actionUnwrapNativeLabel",description:"actionUnwrapNativeDesc",fields:[{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},send_nft:{label:"actionSendNftLabel",description:"actionSendNftDesc",fields:[{key:"contract_address",label:"fieldNftContract",type:"address",placeholder:"0x... NFT contract",required:!0,validation:"address",editable:!1},{key:"token_id",label:"fieldTokenId",type:"text",placeholder:"e.g. 1234",required:!0,editable:!1},{key:"to_address",label:"fieldToAddress",type:"address",placeholder:"0x...",required:!0,validation:"address"},{key:"token_standard",label:"fieldTokenStandard",type:"text",placeholder:"ERC721 or ERC1155",required:!0,editable:!1},{key:"amount",label:"fieldAmount",type:"text",placeholder:"1",required:!0},{key:"maxAmount",label:"fieldMaxAmount",type:"text",placeholder:"",required:!1,editable:!1,hidden:!0},{key:"nft_name",label:"fieldNftName",type:"text",placeholder:"e.g. Bored Ape #1234",required:!1,editable:!1}]}};function Qh(e){if(!e||""===e?.trim())return!1;const t=parseFloat(e);return!isNaN(t)&&t>0}const Zh=({action:t,initialValues:r,onSubmit:o,onCancel:a,isSubmitting:c=!1,tokenInfo:u,nftInfo:l,disabled:d=!1})=>{const{t:f,ti:h}=w(),p=Kh[t],[m,b]=i(()=>{if(!p)return{};const e={};return p.fields.forEach(t=>{e[t.key]=r[t.key]||""}),e}),[g]=i(()=>["send_native","send_token","swap_token"].includes(t)&&!u&&m.contract_address?f("formTokenNotFound"):null),[y,v]=i(()=>{const e={};if(["send_native","send_token","swap_token"].includes(t)&&u){const t=parseFloat(u.balanceFormatted||"0");if(t<=0)e.amount=h("formNoBalance",{symbol:u.symbol??""});else{const n=r.amount?.trim();n&&Qh(n)&&parseFloat(n)>t&&(e.amount=h("formInsufficientBalance",{balance:u.balanceFormatted,symbol:u.symbol??""}))}}return e}),A=s((e,t)=>{b(n=>({...n,[e]:t})),y[e]&&v(t=>{const n={...t};return delete n[e],n})},[y]),k=s(()=>{if(!p)return!1;const e={};if(p.fields.forEach(n=>{const r=m[n.key]?.trim()||"";!n.required||r||"send_nft"===t&&"amount"===n.key?r&&("address"!==n.validation||Ye(r)||(e[n.key]=f("formInvalidAddress")),"amount"!==n.validation||Qh(r)||(e[n.key]=f("formMustBePositive")),"amount"===n.key&&r&&Qh(r)&&u?.balanceFormatted&&parseFloat(r)>parseFloat(u.balanceFormatted)&&(e[n.key]=h("formInsufficientBalance",{balance:u.balanceFormatted,symbol:u.symbol??""})),"positive_number"===n.validation&&(isNaN(Number(r))||Number(r)<0)&&(e[n.key]=f("formMustBeValidNumber"))):e[n.key]=h("formFieldRequired",{field:f(n.label)})}),"send_nft"===t&&"ERC1155"===m.token_standard?.toUpperCase()){const t=m.amount?.trim();if(t)if(!/^\d+$/.test(t)||parseInt(t,10)<1)e.amount=f("formMustBePositiveInteger");else{const n=parseInt(r.maxAmount||"0",10);n>0&&parseInt(t,10)>n&&(e.amount=h("formAmountExceedsNft",{max:String(n)}))}else e.amount=h("formFieldRequired",{field:f("fieldAmount")})}return v(e),0===Object.keys(e).length},[p,m,u,t,r,f,h]),x=s(()=>{k()&&o(t,m)},[k,o,t,m]);return p?/* @__PURE__ */n("div",{className:"action-form",children:[
9
+ /* @__PURE__ */e("button",{className:"copy-address-btn",onClick:l,"aria-label":"Copy wallet address",type:"button",title:a?"Copied!":"Copy address",children:/* @__PURE__ */e("svg",a?{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:/* @__PURE__ */e("path",{d:"M13.3333 4L6 11.3333L2.66667 8",stroke:"#0B3988",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}:{width:"14",height:"14",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:/* @__PURE__ */e("path",{d:"M8.1 15.75H13.23C12.9638 16.4152 12.5041 16.9852 11.9105 17.3863C11.3168 17.7874 10.6165 18.0012 9.9 18H3.6C2.64522 18 1.72955 17.6207 1.05442 16.9456C0.379285 16.2704 0 15.3548 0 14.4V7.2C0.00104929 6.32332 0.321408 5.47704 0.901163 4.81944C1.48092 4.16183 2.28037 3.73792 3.15 3.627V10.8C3.15238 12.1121 3.67466 13.3698 4.60245 14.2975C5.53024 15.2253 6.78791 15.7476 8.1 15.75ZM15.75 3.825H17.658C17.6027 3.74389 17.5393 3.66852 17.469 3.6L14.4 0.531C14.3337 0.460854 14.258 0.400274 14.175 0.351V2.25C14.1769 2.66713 14.3434 3.06664 14.6384 3.3616C14.9334 3.65656 15.3329 3.8231 15.75 3.825ZM15.75 5.175C14.9747 5.17357 14.2315 4.86494 13.6833 4.31671C13.1351 3.76847 12.8264 3.02532 12.825 2.25V0H8.1C7.14522 0 6.22955 0.379285 5.55442 1.05442C4.87928 1.72955 4.5 2.64522 4.5 3.6V10.8C4.5 11.7548 4.87928 12.6704 5.55442 13.3456C6.22955 14.0207 7.14522 14.4 8.1 14.4H14.4C15.3548 14.4 16.2705 14.0207 16.9456 13.3456C17.6207 12.6704 18 11.7548 18 10.8V5.175H15.75Z",fill:"#0B3988"})})})]})})},lh="chat_widget_messages",dh=200,fh="welcome-message";function hh(e){return[{id:fh,text:e,sender:"bot",timestamp:/* @__PURE__ */new Date}]}function ph(e){return e.map(e=>({...e,timestamp:new Date(e.timestamp)}))}function mh(){const e=ih.getItem(lh);if(!e)return null;try{const t=JSON.parse(e);if(t&&void 0!==t.owner&&Array.isArray(t.messages))return{owner:t.owner,messages:ph(t.messages)};if(Array.isArray(t))return{owner:"",messages:ph(t)}}catch{}return null}function wh(e,t){ih.setItem(lh,JSON.stringify({owner:e,messages:t}))}const bh=a(void 0),gh=({children:t,initialConfig:n})=>/* @__PURE__ */e(bh.Provider,{value:{config:n||null},children:t});var yh=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,vh=Math.ceil,Ah=Math.floor,kh="[BigNumber Error] ",xh=kh+"Number primitive has more than 15 significant digits: ",Eh=1e14,Th=14,Ch=9007199254740991,Ih=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Sh=1e7,Nh=1e9;function Bh(e){var t=0|e;return e>0||e===t?t:t-1}function Mh(e){for(var t,n,r=1,i=e.length,o=e[0]+"";r<i;){for(t=e[r++]+"",n=Th-t.length;n--;t="0"+t);o+=t}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function Uh(e,t){var n,r,i=e.c,o=t.c,s=e.s,a=t.s,c=e.e,u=t.e;if(!s||!a)return null;if(n=i&&!i[0],r=o&&!o[0],n||r)return n?r?0:-a:s;if(s!=a)return s;if(n=s<0,r=c==u,!i||!o)return r?0:!i^n?1:-1;if(!r)return c>u^n?1:-1;for(a=(c=i.length)<(u=o.length)?c:u,s=0;s<a;s++)if(i[s]!=o[s])return i[s]>o[s]^n?1:-1;return c==u?0:c>u^n?1:-1}function Rh(e,t,n,r){if(e<t||e>n||e!==Ah(e))throw Error(kh+(r||"Argument")+("number"==typeof e?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function Oh(e){var t=e.c.length-1;return Bh(e.e/Th)==t&&e.c[t]%2!=0}function Fh(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function Lh(e,t,n){var r,i;if(t<0){for(i=n+".";++t;i+=n);e=i+e}else if(++t>(r=e.length)){for(i=n,t-=r;--t;i+=n);e+=i}else t<r&&(e=e.slice(0,t)+"."+e.slice(t));return e}var Dh=function e(t){var n,r,i,o,s,a=A.prototype={constructor:A,toString:null,valueOf:null},c=new A(1),u=20,l=4,d=-7,f=21,h=-1e7,p=1e7,m=!1,w=1,b=0,g={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},y="0123456789abcdefghijklmnopqrstuvwxyz",v=!0;function A(e,t){var n,o,s,a,c,d,f,m,w=this;if(!(w instanceof A))return new A(e,t);if(null==t){if(e&&!0===e.Me)return w.s=e.s,void(!e.c||e.e>p?w.c=w.e=null:e.e<h?w.c=[w.e=0]:(w.e=e.e,w.c=e.c.slice()));if((d="number"==typeof e)&&0*e==0){if(w.s=1/e<0?(e=-e,-1):1,e===~~e){for(a=0,c=e;c>=10;c/=10,a++);return void(a>p?w.c=w.e=null:(w.e=a,w.c=[e]))}m=String(e)}else{if(!yh.test(m=String(e)))return i(w,m,d);w.s=45==m.charCodeAt(0)?(m=m.slice(1),-1):1}(a=m.indexOf("."))>-1&&(m=m.replace(".","")),(c=m.search(/e/i))>0?(a<0&&(a=c),a+=+m.slice(c+1),m=m.substring(0,c)):a<0&&(a=m.length)}else{if(Rh(t,2,y.length,"Base"),10==t&&v)return T(w=new A(e),u+w.e+1,l);if(m=String(e),d="number"==typeof e){if(0*e!=0)return i(w,m,d,t);if(w.s=1/e<0?(m=m.slice(1),-1):1,A.DEBUG&&m.replace(/^0\.0*|\./,"").length>15)throw Error(xh+e)}else w.s=45===m.charCodeAt(0)?(m=m.slice(1),-1):1;for(n=y.slice(0,t),a=c=0,f=m.length;c<f;c++)if(n.indexOf(o=m.charAt(c))<0){if("."==o){if(c>a){a=f;continue}}else if(!s&&(m==m.toUpperCase()&&(m=m.toLowerCase())||m==m.toLowerCase()&&(m=m.toUpperCase()))){s=!0,c=-1,a=0;continue}return i(w,String(e),d,t)}d=!1,(a=(m=r(m,t,10,w.s)).indexOf("."))>-1?m=m.replace(".",""):a=m.length}for(c=0;48===m.charCodeAt(c);c++);for(f=m.length;48===m.charCodeAt(--f););if(m=m.slice(c,++f)){if(f-=c,d&&A.DEBUG&&f>15&&(e>Ch||e!==Ah(e)))throw Error(xh+w.s*e);if((a=a-c-1)>p)w.c=w.e=null;else if(a<h)w.c=[w.e=0];else{if(w.e=a,w.c=[],c=(a+1)%Th,a<0&&(c+=Th),c<f){for(c&&w.c.push(+m.slice(0,c)),f-=Th;c<f;)w.c.push(+m.slice(c,c+=Th));c=Th-(m=m.slice(c)).length}else c-=f;for(;c--;m+="0");w.c.push(+m)}}else w.c=[w.e=0]}function k(e,t,n,r){var i,o,s,a,c;if(null==n?n=l:Rh(n,0,8),!e.c)return e.toString();if(i=e.c[0],s=e.e,null==t)c=Mh(e.c),c=1==r||2==r&&(s<=d||s>=f)?Fh(c,s):Lh(c,s,"0");else if(o=(e=T(new A(e),t,n)).e,a=(c=Mh(e.c)).length,1==r||2==r&&(t<=o||o<=d)){for(;a<t;c+="0",a++);c=Fh(c,o)}else if(t-=s+(2===r&&o>s),c=Lh(c,o,"0"),o+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=o-a)>0)for(o+1==a&&(c+=".");t--;c+="0");return e.s<0&&i?"-"+c:c}function x(e,t){for(var n,r,i=1,o=new A(e[0]);i<e.length;i++)(!(r=new A(e[i])).s||(n=Uh(o,r))===t||0===n&&o.s===t)&&(o=r);return o}function E(e,t,n){for(var r=1,i=t.length;!t[--i];t.pop());for(i=t[0];i>=10;i/=10,r++);return(n=r+n*Th-1)>p?e.c=e.e=null:n<h?e.c=[e.e=0]:(e.e=n,e.c=t),e}function T(e,t,n,r){var i,o,s,a,c,u,l,d=e.c,f=Ih;if(d){e:{for(i=1,a=d[0];a>=10;a/=10,i++);if((o=t-i)<0)o+=Th,s=t,c=d[u=0],l=Ah(c/f[i-s-1]%10);else if((u=vh((o+1)/Th))>=d.length){if(!r)break e;for(;d.length<=u;d.push(0));c=l=0,i=1,s=(o%=Th)-Th+1}else{for(c=a=d[u],i=1;a>=10;a/=10,i++);l=(s=(o%=Th)-Th+i)<0?0:Ah(c/f[i-s-1]%10)}if(r=r||t<0||null!=d[u+1]||(s<0?c:c%f[i-s-1]),r=n<4?(l||r)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||r||6==n&&(o>0?s>0?c/f[i-s]:0:d[u-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,r?(t-=e.e+1,d[0]=f[(Th-t%Th)%Th],e.e=-t||0):d[0]=e.e=0,e;if(0==o?(d.length=u,a=1,u--):(d.length=u+1,a=f[Th-o],d[u]=s>0?Ah(c/f[i-s]%f[s])*a:0),r)for(;;){if(0==u){for(o=1,s=d[0];s>=10;s/=10,o++);for(s=d[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(e.e++,d[0]==Eh&&(d[0]=1));break}if(d[u]+=a,d[u]!=Eh)break;d[u--]=0,a=1}for(o=d.length;0===d[--o];d.pop());}e.e>p?e.c=e.e=null:e.e<h&&(e.c=[e.e=0])}return e}function C(e){var t,n=e.e;return null===n?e.toString():(t=Mh(e.c),t=n<=d||n>=f?Fh(t,n):Lh(t,n,"0"),e.s<0?"-"+t:t)}return A.clone=e,A.ROUND_UP=0,A.ROUND_DOWN=1,A.ROUND_CEIL=2,A.ROUND_FLOOR=3,A.ROUND_HALF_UP=4,A.ROUND_HALF_DOWN=5,A.ROUND_HALF_EVEN=6,A.ROUND_HALF_CEIL=7,A.ROUND_HALF_FLOOR=8,A.EUCLID=9,A.config=A.set=function(e){var t,n;if(null!=e){if("object"!=typeof e)throw Error(kh+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(Rh(n=e[t],0,Nh,t),u=n),e.hasOwnProperty(t="ROUNDING_MODE")&&(Rh(n=e[t],0,8,t),l=n),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((n=e[t])&&n.pop?(Rh(n[0],-Nh,0,t),Rh(n[1],0,Nh,t),d=n[0],f=n[1]):(Rh(n,-Nh,Nh,t),d=-(f=n<0?-n:n))),e.hasOwnProperty(t="RANGE"))if((n=e[t])&&n.pop)Rh(n[0],-Nh,-1,t),Rh(n[1],1,Nh,t),h=n[0],p=n[1];else{if(Rh(n,-Nh,Nh,t),!n)throw Error(kh+t+" cannot be zero: "+n);h=-(p=n<0?-n:n)}if(e.hasOwnProperty(t="CRYPTO")){if((n=e[t])!==!!n)throw Error(kh+t+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw m=!n,Error(kh+"crypto unavailable");m=n}else m=n}if(e.hasOwnProperty(t="MODULO_MODE")&&(Rh(n=e[t],0,9,t),w=n),e.hasOwnProperty(t="POW_PRECISION")&&(Rh(n=e[t],0,Nh,t),b=n),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(n=e[t]))throw Error(kh+t+" not an object: "+n);g=n}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(n=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(kh+t+" invalid: "+n);v="0123456789"==n.slice(0,10),y=n}}return{DECIMAL_PLACES:u,ROUNDING_MODE:l,EXPONENTIAL_AT:[d,f],RANGE:[h,p],CRYPTO:m,MODULO_MODE:w,POW_PRECISION:b,FORMAT:g,ALPHABET:y}},A.isBigNumber=function(e){if(!e||!0!==e.Me)return!1;if(!A.DEBUG)return!0;var t,n,r=e.c,i=e.e,o=e.s;e:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Nh&&i<=Nh&&i===Ah(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break e}if((t=(i+1)%Th)<1&&(t+=Th),String(r[0]).length==t){for(t=0;t<r.length;t++)if((n=r[t])<0||n>=Eh||n!==Ah(n))break e;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(kh+"Invalid BigNumber: "+e)},A.maximum=A.max=function(){return x(arguments,-1)},A.minimum=A.min=function(){return x(arguments,1)},A.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Ah(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,n,r,i,o,a=0,l=[],d=new A(c);if(null==e?e=u:Rh(e,0,Nh),i=vh(e/Th),m)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(i*=2));a<i;)(o=131072*t[a]+(t[a+1]>>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),t[a]=n[0],t[a+1]=n[1]):(l.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw m=!1,Error(kh+"crypto unavailable");for(t=crypto.randomBytes(i*=7);a<i;)(o=281474976710656*(31&t[a])+1099511627776*t[a+1]+4294967296*t[a+2]+16777216*t[a+3]+(t[a+4]<<16)+(t[a+5]<<8)+t[a+6])>=9e15?crypto.randomBytes(7).copy(t,a):(l.push(o%1e14),a+=7);a=i/7}if(!m)for(;a<i;)(o=s())<9e15&&(l[a++]=o%1e14);for(i=l[--a],e%=Th,i&&e&&(o=Ih[Th-e],l[a]=Ah(i/o)*o);0===l[a];l.pop(),a--);if(a<0)l=[r=0];else{for(r=-1;0===l[0];l.splice(0,1),r-=Th);for(a=1,o=l[0];o>=10;o/=10,a++);a<Th&&(r-=Th-a)}return d.e=r,d.c=l,d}),A.sum=function(){for(var e=1,t=arguments,n=new A(t[0]);e<t.length;)n=n.plus(t[e++]);return n},r=/* @__PURE__ */function(){var e="0123456789";function t(e,t,n,r){for(var i,o,s=[0],a=0,c=e.length;a<c;){for(o=s.length;o--;s[o]*=t);for(s[0]+=r.indexOf(e.charAt(a++)),i=0;i<s.length;i++)s[i]>n-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var c,d,f,h,p,m,w,g,v=r.indexOf("."),k=u,x=l;for(v>=0&&(h=b,b=0,r=r.replace(".",""),m=(g=new A(i)).pow(r.length-v),b=h,g.c=t(Lh(Mh(m.c),m.e,"0"),10,o,e),g.e=g.c.length),f=h=(w=t(r,i,o,a?(c=y,e):(c=e,y))).length;0==w[--h];w.pop());if(!w[0])return c.charAt(0);if(v<0?--f:(m.c=w,m.e=f,m.s=s,w=(m=n(m,g,k,x,o)).c,p=m.r,f=m.e),v=w[d=f+k+1],h=o/2,p=p||d<0||null!=w[d+1],p=x<4?(null!=v||p)&&(0==x||x==(m.s<0?3:2)):v>h||v==h&&(4==x||p||6==x&&1&w[d-1]||x==(m.s<0?8:7)),d<1||!w[0])r=p?Lh(c.charAt(1),-k,c.charAt(0)):c.charAt(0);else{if(w.length=d,p)for(--o;++w[--d]>o;)w[d]=0,d||(++f,w=[1].concat(w));for(h=w.length;!w[--h];);for(v=0,r="";v<=h;r+=c.charAt(w[v++]));r=Lh(r,f,c.charAt(0))}return r}}(),n=/* @__PURE__ */function(){function e(e,t,n){var r,i,o,s,a=0,c=e.length,u=t%Sh,l=t/Sh|0;for(e=e.slice();c--;)a=((i=u*(o=e[c]%Sh)+(r=l*o+(s=e[c]/Sh|0)*u)%Sh*Sh+a)/n|0)+(r/Sh|0)+l*s,e[c]=i%n;return a&&(e=[a].concat(e)),e}function t(e,t,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;i<n;i++)if(e[i]!=t[i]){o=e[i]>t[i]?1:-1;break}return o}function n(e,t,n,r){for(var i=0;n--;)e[n]-=i,i=e[n]<t[n]?1:0,e[n]=i*r+e[n]-t[n];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(r,i,o,s,a){var c,u,l,d,f,h,p,m,w,b,g,y,v,k,x,E,C,I=r.s==i.s?1:-1,S=r.c,N=i.c;if(!(S&&S[0]&&N&&N[0]))return new A(r.s&&i.s&&(S?!N||S[0]!=N[0]:N)?S&&0==S[0]||!N?0*I:I/0:NaN);for(w=(m=new A(I)).c=[],I=o+(u=r.e-i.e)+1,a||(a=Eh,u=Bh(r.e/Th)-Bh(i.e/Th),I=I/Th|0),l=0;N[l]==(S[l]||0);l++);if(N[l]>(S[l]||0)&&u--,I<0)w.push(1),d=!0;else{for(k=S.length,E=N.length,l=0,I+=2,(f=Ah(a/(N[0]+1)))>1&&(N=e(N,f,a),S=e(S,f,a),E=N.length,k=S.length),v=E,g=(b=S.slice(0,E)).length;g<E;b[g++]=0);C=N.slice(),C=[0].concat(C),x=N[0],N[1]>=a/2&&x++;do{if(f=0,(c=t(N,b,E,g))<0){if(y=b[0],E!=g&&(y=y*a+(b[1]||0)),(f=Ah(y/x))>1)for(f>=a&&(f=a-1),p=(h=e(N,f,a)).length,g=b.length;1==t(h,b,p,g);)f--,n(h,E<p?C:N,p,a),p=h.length,c=1;else 0==f&&(c=f=1),p=(h=N.slice()).length;if(p<g&&(h=[0].concat(h)),n(b,h,g,a),g=b.length,-1==c)for(;t(N,b,E,g)<1;)f++,n(b,E<g?C:N,g,a),g=b.length}else 0===c&&(f++,b=[0]);w[l++]=f,b[0]?b[g++]=S[v]||0:(b=[S[v]],g=1)}while((v++<k||null!=b[0])&&I--);d=null!=b[0],w[0]||w.splice(0,1)}if(a==Eh){for(l=1,I=w[0];I>=10;I/=10,l++);T(m,o+(m.e=l+u*Th-1)+1,s,d)}else m.e=u,m.r=+d;return m}}(),i=/* @__PURE__ */function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,t=/^([^.]+)\.$/,n=/^\.([^.]+)$/,r=/^-?(Infinity|NaN)$/,i=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,s,a,c){var u,l=a?s:s.replace(i,"");if(r.test(l))o.s=isNaN(l)?null:l<0?-1:1;else{if(!a&&(l=l.replace(e,function(e,t,n){return u="x"==(n=n.toLowerCase())?16:"b"==n?2:8,c&&c!=u?e:t}),c&&(u=c,l=l.replace(t,"$1").replace(n,"0.$1")),s!=l))return new A(l,u);if(A.DEBUG)throw Error(kh+"Not a"+(c?" base "+c:"")+" number: "+s);o.s=null}o.c=o.e=null}}(),a.absoluteValue=a.abs=function(){var e=new A(this);return e.s<0&&(e.s=1),e},a.comparedTo=function(e,t){return Uh(this,new A(e,t))},a.decimalPlaces=a.dp=function(e,t){var n,r,i,o=this;if(null!=e)return Rh(e,0,Nh),null==t?t=l:Rh(t,0,8),T(new A(o),e+o.e+1,t);if(!(n=o.c))return null;if(r=((i=n.length-1)-Bh(this.e/Th))*Th,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},a.dividedBy=a.div=function(e,t){return n(this,new A(e,t),u,l)},a.dividedToIntegerBy=a.idiv=function(e,t){return n(this,new A(e,t),0,1)},a.exponentiatedBy=a.pow=function(e,t){var n,r,i,o,s,a,u,d,f=this;if((e=new A(e)).c&&!e.isInteger())throw Error(kh+"Exponent not an integer: "+C(e));if(null!=t&&(t=new A(t)),s=e.e>14,!f.c||!f.c[0]||1==f.c[0]&&!f.e&&1==f.c.length||!e.c||!e.c[0])return d=new A(Math.pow(+C(f),s?e.s*(2-Oh(e)):+C(e))),t?d.mod(t):d;if(a=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new A(NaN);(r=!a&&f.isInteger()&&t.isInteger())&&(f=f.mod(t))}else{if(e.e>9&&(f.e>0||f.e<-1||(0==f.e?f.c[0]>1||s&&f.c[1]>=24e7:f.c[0]<8e13||s&&f.c[0]<=9999975e7)))return o=f.s<0&&Oh(e)?-0:0,f.e>-1&&(o=1/o),new A(a?1/o:o);b&&(o=vh(b/Th+2))}for(s?(n=new A(.5),a&&(e.s=1),u=Oh(e)):u=(i=Math.abs(+C(e)))%2,d=new A(c);;){if(u){if(!(d=d.times(f)).c)break;o?d.c.length>o&&(d.c.length=o):r&&(d=d.mod(t))}if(i){if(0===(i=Ah(i/2)))break;u=i%2}else if(T(e=e.times(n),e.e+1,1),e.e>14)u=Oh(e);else{if(0===(i=+C(e)))break;u=i%2}f=f.times(f),o?f.c&&f.c.length>o&&(f.c.length=o):r&&(f=f.mod(t))}return r?d:(a&&(d=c.div(d)),t?d.mod(t):o?T(d,b,l,void 0):d)},a.integerValue=function(e){var t=new A(this);return null==e?e=l:Rh(e,0,8),T(t,t.e+1,e)},a.isEqualTo=a.eq=function(e,t){return 0===Uh(this,new A(e,t))},a.isFinite=function(){return!!this.c},a.isGreaterThan=a.gt=function(e,t){return Uh(this,new A(e,t))>0},a.isGreaterThanOrEqualTo=a.gte=function(e,t){return 1===(t=Uh(this,new A(e,t)))||0===t},a.isInteger=function(){return!!this.c&&Bh(this.e/Th)>this.c.length-2},a.isLessThan=a.lt=function(e,t){return Uh(this,new A(e,t))<0},a.isLessThanOrEqualTo=a.lte=function(e,t){return-1===(t=Uh(this,new A(e,t)))||0===t},a.isNaN=function(){return!this.s},a.isNegative=function(){return this.s<0},a.isPositive=function(){return this.s>0},a.isZero=function(){return!!this.c&&0==this.c[0]},a.minus=function(e,t){var n,r,i,o,s=this,a=s.s;if(t=(e=new A(e,t)).s,!a||!t)return new A(NaN);if(a!=t)return e.s=-t,s.plus(e);var c=s.e/Th,u=e.e/Th,d=s.c,f=e.c;if(!c||!u){if(!d||!f)return d?(e.s=-t,e):new A(f?s:NaN);if(!d[0]||!f[0])return f[0]?(e.s=-t,e):new A(d[0]?s:3==l?-0:0)}if(c=Bh(c),u=Bh(u),d=d.slice(),a=c-u){for((o=a<0)?(a=-a,i=d):(u=c,i=f),i.reverse(),t=a;t--;i.push(0));i.reverse()}else for(r=(o=(a=d.length)<(t=f.length))?a:t,a=t=0;t<r;t++)if(d[t]!=f[t]){o=d[t]<f[t];break}if(o&&(i=d,d=f,f=i,e.s=-e.s),(t=(r=f.length)-(n=d.length))>0)for(;t--;d[n++]=0);for(t=Eh-1;r>a;){if(d[--r]<f[r]){for(n=r;n&&!d[--n];d[n]=t);--d[n],d[r]+=Eh}d[r]-=f[r]}for(;0==d[0];d.splice(0,1),--u);return d[0]?E(e,d,u):(e.s=3==l?-1:1,e.c=[e.e=0],e)},a.modulo=a.mod=function(e,t){var r,i,o=this;return e=new A(e,t),!o.c||!e.s||e.c&&!e.c[0]?new A(NaN):!e.c||o.c&&!o.c[0]?new A(o):(9==w?(i=e.s,e.s=1,r=n(o,e,0,3),e.s=i,r.s*=i):r=n(o,e,0,w),(e=o.minus(r.times(e))).c[0]||1!=w||(e.s=o.s),e)},a.multipliedBy=a.times=function(e,t){var n,r,i,o,s,a,c,u,l,d,f,h,p,m,w,b=this,g=b.c,y=(e=new A(e,t)).c;if(!(g&&y&&g[0]&&y[0]))return!b.s||!e.s||g&&!g[0]&&!y||y&&!y[0]&&!g?e.c=e.e=e.s=null:(e.s*=b.s,g&&y?(e.c=[0],e.e=0):e.c=e.e=null),e;for(r=Bh(b.e/Th)+Bh(e.e/Th),e.s*=b.s,(c=g.length)<(d=y.length)&&(p=g,g=y,y=p,i=c,c=d,d=i),i=c+d,p=[];i--;p.push(0));for(m=Eh,w=Sh,i=d;--i>=0;){for(n=0,f=y[i]%w,h=y[i]/w|0,o=i+(s=c);o>i;)n=((u=f*(u=g[--s]%w)+(a=h*u+(l=g[s]/w|0)*f)%w*w+p[o]+n)/m|0)+(a/w|0)+h*l,p[o--]=u%m;p[o]=n}return n?++r:p.splice(0,1),E(e,p,r)},a.negated=function(){var e=new A(this);return e.s=-e.s||null,e},a.plus=function(e,t){var n,r=this,i=r.s;if(t=(e=new A(e,t)).s,!i||!t)return new A(NaN);if(i!=t)return e.s=-t,r.minus(e);var o=r.e/Th,s=e.e/Th,a=r.c,c=e.c;if(!o||!s){if(!a||!c)return new A(i/0);if(!a[0]||!c[0])return c[0]?e:new A(a[0]?r:0*i)}if(o=Bh(o),s=Bh(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=c):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(t=c.length)<0&&(n=c,c=a,a=n,t=i),i=0;t;)i=(a[--t]=a[t]+c[t]+i)/Eh|0,a[t]=Eh===a[t]?0:a[t]%Eh;return i&&(a=[i].concat(a),++s),E(e,a,s)},a.precision=a.sd=function(e,t){var n,r,i,o=this;if(null!=e&&e!==!!e)return Rh(e,1,Nh),null==t?t=l:Rh(t,0,8),T(new A(o),e,t);if(!(n=o.c))return null;if(r=(i=n.length-1)*Th+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return e&&o.e+1>r&&(r=o.e+1),r},a.shiftedBy=function(e){return Rh(e,-9007199254740991,Ch),this.times("1e"+e)},a.squareRoot=a.sqrt=function(){var e,t,r,i,o,s=this,a=s.c,c=s.s,d=s.e,f=u+4,h=new A("0.5");if(1!==c||!a||!a[0])return new A(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(c=Math.sqrt(+C(s)))||c==1/0?(((t=Mh(a)).length+d)%2==0&&(t+="0"),c=Math.sqrt(+t),d=Bh((d+1)/2)-(d<0||d%2),r=new A(t=c==1/0?"5e"+d:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+d)):r=new A(c+""),r.c[0])for((c=(d=r.e)+f)<3&&(c=0);;)if(o=r,r=h.times(o.plus(n(s,o,f,1))),Mh(o.c).slice(0,c)===(t=Mh(r.c)).slice(0,c)){if(r.e<d&&--c,"9999"!=(t=t.slice(c-3,c+1))&&(i||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(T(r,r.e+u+2,1),e=!r.times(r).eq(s));break}if(!i&&(T(o,o.e+u+2,0),o.times(o).eq(s))){r=o;break}f+=4,c+=4,i=1}return T(r,r.e+u+1,l,e)},a.toExponential=function(e,t){return null!=e&&(Rh(e,0,Nh),e++),k(this,e,t,1)},a.toFixed=function(e,t){return null!=e&&(Rh(e,0,Nh),e=e+this.e+1),k(this,e,t)},a.toFormat=function(e,t,n){var r,i=this;if(null==n)null!=e&&t&&"object"==typeof t?(n=t,t=null):e&&"object"==typeof e?(n=e,e=t=null):n=g;else if("object"!=typeof n)throw Error(kh+"Argument not an object: "+n);if(r=i.toFixed(e,t),i.c){var o,s=r.split("."),a=+n.groupSize,c=+n.secondaryGroupSize,u=n.groupSeparator||"",l=s[0],d=s[1],f=i.s<0,h=f?l.slice(1):l,p=h.length;if(c&&(o=a,a=c,c=o,p-=o),a>0&&p>0){for(o=p%a||a,l=h.substr(0,o);o<p;o+=a)l+=u+h.substr(o,a);c>0&&(l+=u+h.slice(o)),f&&(l="-"+l)}r=d?l+(n.decimalSeparator||"")+((c=+n.fractionGroupSize)?d.replace(new RegExp("\\d{"+c+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):d):l}return(n.prefix||"")+r+(n.suffix||"")},a.toFraction=function(e){var t,r,i,o,s,a,u,d,f,h,m,w,b=this,g=b.c;if(null!=e&&(!(u=new A(e)).isInteger()&&(u.c||1!==u.s)||u.lt(c)))throw Error(kh+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+C(u));if(!g)return new A(b);for(t=new A(c),f=r=new A(c),i=d=new A(c),w=Mh(g),s=t.e=w.length-b.e-1,t.c[0]=Ih[(a=s%Th)<0?Th+a:a],e=!e||u.comparedTo(t)>0?s>0?t:f:u,a=p,p=1/0,u=new A(w),d.c[0]=0;h=n(u,t,0,1),1!=(o=r.plus(h.times(i))).comparedTo(e);)r=i,i=o,f=d.plus(h.times(o=f)),d=o,t=u.minus(h.times(o=t)),u=o;return o=n(e.minus(r),i,0,1),d=d.plus(o.times(f)),r=r.plus(o.times(i)),d.s=f.s=b.s,m=n(f,i,s*=2,l).minus(b).abs().comparedTo(n(d,r,s,l).minus(b).abs())<1?[f,i]:[d,r],p=a,m},a.toNumber=function(){return+C(this)},a.toPrecision=function(e,t){return null!=e&&Rh(e,1,Nh),k(this,e,t,2)},a.toString=function(e){var t,n=this,i=n.s,o=n.e;return null===o?i?(t="Infinity",i<0&&(t="-"+t)):t="NaN":(null==e?t=o<=d||o>=f?Fh(Mh(n.c),o):Lh(Mh(n.c),o,"0"):10===e&&v?t=Lh(Mh((n=T(new A(n),u+o+1,l)).c),n.e,"0"):(Rh(e,2,y.length,"Base"),t=r(Lh(Mh(n.c),o,"0"),10,e,i,!0)),i<0&&n.c[0]&&(t="-"+t)),t},a.valueOf=a.toJSON=function(){return C(this)},a.Me=!0,a[Symbol.toStringTag]="BigNumber",a[/* @__PURE__ */Symbol.for("nodejs.util.inspect.custom")]=a.valueOf,null!=t&&A.set(t),A}();class Ph{baseUrl;constructor(e){this.baseUrl=e}buildUrl(e,t){const n=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([e,t])=>{null!=t&&n.searchParams.append(e,String(t))}),n.toString()}async get(e,t={}){const n=this.buildUrl(e,t.query),r=await fetch(n,{method:"GET",headers:t.headers||{},signal:t.signal});if(!r.ok){let e=null;try{e=await r.json()}catch{try{const t=await r.text();t&&(e={message:t})}catch{}}const t=new Error(e?.message||e?.errorMessage||`HTTP ${r.status}: ${r.statusText}`);throw t.status=r.status,t.statusText=r.statusText,e&&(t.data=e),t}return{data:await r.json(),status:r.status}}async post(e,t,n={}){const r=this.buildUrl(e,n.query),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...n.headers},body:JSON.stringify(t),signal:n.signal});if(!i.ok){let e=null;try{e=await i.json()}catch{try{const t=await i.text();t&&(e={message:t})}catch{}}const t=new Error(e?.message||e?.errorMessage||`HTTP ${i.status}: ${i.statusText}`);throw t.status=i.status,t.statusText=i.statusText,e&&(t.data=e),t}return{data:await i.json(),status:i.status}}}function Hh(e,t){return new Promise(n=>{const r=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}const jh=new Ph("https://wallet-api.pantograph.app"),zh="https://nft.keyring.app",Jh=new Ph(zh);async function qh(e){const{address:t,chain:n="base",token_addresses:r,exclude_spam:i,exclude_unverified_contracts:o}=e;if(!t)throw new Error("Address is required");let s="Unknown error";for(let u=1;u<=5;u++)try{const e={chain:n,exclude_spam:i??!1,exclude_unverified_contracts:o??!1};r&&(e.token_addresses=r);const s=(await Jh.get(`api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens`,{query:e})).data;if(s?.result?.length>0){s.result=s.result.filter(e=>new Dh(e?.balance||0).gt(0)),s.result=s.result.map(e=>({...e,token_address:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"===e.token_address?xn:e.token_address}));try{if(s.result.length>0){const e=Ln(n)??n,t=s.result.map(e=>e.token_address),r=await jh.get(`/keyrings/tokens/${e}/v2`,{query:{addresses:t.join(",")}});if(Array.isArray(r.data)){const e=/* @__PURE__ */new Map;for(const t of r.data)t.address&&e.set(t.address.toLowerCase(),{price:null!=t.price?parseFloat(String(t.price)):NaN,icon_image:t.icon_image});s.result=s.result.map(t=>{const n=e.get(t.token_address.toLowerCase());if(!n)return t;const r={...t};return n.icon_image&&(r.logo=n.icon_image,r.thumbnail=n.icon_image),isNaN(n.price)||(r.usd_price=n.price,r.usd_value=Dh(t.balance_formatted||"0").multipliedBy(n.price).toNumber()),r}),s.result=s.result.filter(e=>null==e.usd_value||new Dh(e.usd_value).gte(.01))}}}catch(a){}}return{success:!0,data:s}}catch(c){s=c instanceof Error?c.message:"Unknown error",u<5&&await Hh(1e3)}return{success:!1,error:s}}async function Vh(e){const{address:t,chain:n="base",signal:r}=e;if(!t)throw new Error("Token address is required");let i="Unknown error";for(let s=1;s<=5;s++){if(r?.aborted)return{success:!1,error:"Request cancelled"};try{const e=Ln(n)??n,o=await jh.get(`/keyrings/tokens/${e}/v2`,{query:{addresses:t},signal:r}),a=t===xn,c=(Array.isArray(o.data)?o.data:[]).find(e=>e.address?.toLowerCase()===t.toLowerCase()||a&&""===e.address)??null;if(c)return{success:!0,data:{token_address:c.address??t,name:c.name??"",symbol:c.symbol??"",decimals:null!=c.decimals?Number(c.decimals):18,logo:c.icon_image||c.logo,thumbnail:c.icon_image||c.logo,usd_price:null!=c.price?parseFloat(c.price):void 0,usd_price_24hr_percent_change:c.price_change_percentage_24h??void 0,usd_price_24hr_usd_change:c.price_change_24h??void 0}};const[u,l]=await Promise.allSettled([Jh.get("api/moralis/proxy/erc20/metadata",{query:{chain:n,addresses:[t]},signal:r}),Jh.get(`api/moralis/proxy/erc20/${encodeURIComponent(t)}/price`,{query:{chain:n,include:"percent_change"},signal:r})]),d="fulfilled"===u.status?u.value.data:[];if(!d||0===d.length){if(i="Token metadata not found",s<5&&await Hh(1e3,r),r?.aborted)return{success:!1,error:"Request cancelled"};continue}const f=d[0],h="fulfilled"===l.status?l.value.data:void 0;return{success:!0,data:{token_address:f.token_address,name:f.name,symbol:f.symbol,decimals:f.decimals,logo:f.logo||f.thumbnail,thumbnail:f.thumbnail,usd_price:h?.usdPrice??void 0,usd_price_24hr_percent_change:h?.["24hrPercentChange"]?parseFloat(h["24hrPercentChange"]):void 0,usd_price_24hr_usd_change:h?.usdPriceChange24hr??void 0}}}catch(o){if(r?.aborted)return{success:!1,error:"Request cancelled"};if(i=o instanceof Error?o.message:"Unknown error",s<5&&await Hh(1e3,r),r?.aborted)return{success:!1,error:"Request cancelled"}}}return{success:!1,error:i}}async function Yh(e){const{address:t,chain:n="base",limit:r=100,exclude_spam:i=!0,cursor:o,signal:s}=e;if(!t)throw new Error("Address is required");let a="Unknown error";for(let u=1;u<=5;u++){if(s?.aborted)return{success:!1,error:"Request cancelled"};try{const e={chain:n,format:"decimal",limit:r,exclude_spam:i,media_items:!0,normalizeMetadata:!0};o&&(e.cursor=o);return{success:!0,data:(await Jh.get(`api/moralis/proxy/${encodeURIComponent(t)}/nft`,{query:e,signal:s})).data}}catch(c){if(s?.aborted)return{success:!1,error:"Request cancelled"};if(a=c instanceof Error?c.message:"Unknown error",u<5&&await Hh(1e3,s),s?.aborted)return{success:!1,error:"Request cancelled"}}}return{success:!1,error:a}}const Gh=new class extends Ph{constructor(){super("https://wallet-api.pantograph.app")}async getTokensDetails(e,t="base"){try{if(!e||!Array.isArray(e)||0===e.length)throw new Error("Addresses must be a non-empty array");const n=e.join(","),r=await this.get(`/keyrings/tokens/${t}/v2`,{query:{addresses:n}});return Array.isArray(r.data)&&(r.data=r.data.filter((e,t,n)=>t===n.findIndex(t=>t.address.toLowerCase()===e.address.toLowerCase())),Array.isArray(e)&&e.length>0&&(r.data=r.data.filter(t=>e.some(e=>e.toLowerCase()===t.address.toLowerCase())),r.data.sort((t,n)=>e.findIndex(e=>e.toLowerCase()===t.address.toLowerCase())-e.findIndex(e=>e.toLowerCase()===n.address.toLowerCase())))),r}catch(n){throw n}}async getTokenDetail(e,t="base"){try{if(!e)throw new Error("Address is required");const n=await this.getTokensDetails([e],t);return{data:n.data[0]||null,status:n.status}}catch(n){throw n}}async getTopGainers(e="base",t="24h",n=3){try{return await this.get(`/token-list/top-gainers/${e}`,{query:{duration:t,limit:n}})}catch(r){throw r}}async searchTokensByKey(e,t){try{if(!e)throw new Error("key is required");const n=await this.get("/token-list",{query:{chainId:t,key:e}});let r=n.data;return r=Object.values(r).flat(),Array.isArray(r)&&(r=r.map(e=>({...e,decimals:null!=e.decimals?Number(e.decimals):18,price:null!=e.price?Number(e.price):void 0}))),n.data=r,n}catch(n){throw n}}},Wh=new Ph("https://dln.debridge.finance");async function Xh(e){const{chainId:t,tokenIn:n,tokenInAmount:r,tokenOut:i,accesstoken:o,slippage:s="auto",tokenOutRecipient:a}=e;if(!(t&&n&&r&&i))throw new Error("Missing required parameters: chainId, tokenIn, tokenInAmount, tokenOut");try{const e=await fetch("https://exchange-api.keyring.app/admin/setting?configs=others",{method:"GET"}),c=await e.json(),u=c?.others||{},l=u?.AFFILIATE_FEE_PERENT,d=u?.AFFILIATE_FEE_RECIPIENT,f=await Wh.get("/v1.0/chain/transaction",{query:{chainId:String(t),tokenIn:n,tokenInAmount:r,tokenOut:i,slippage:String(s),tokenOutRecipient:a,accesstoken:o,affiliateFeePercent:l,affiliateFeeRecipient:d}});if(f.data?.error)throw new Error(`DeBridge API Error: ${f.data.error}`);return{success:!0,data:f.data}}catch(c){let e=c instanceof Error?c.message:"Unknown error";const t=c;t.data?.errorMessage?e=t.data.errorMessage:t.response?.data?.errorMessage?e=t.response.data.errorMessage:t.data?.message?e=t.data.message:t.response?.data?.message&&(e=t.response.data.message);const n=t.status||t.response?.status||t.statusCode||t.data?.status;return{success:!1,error:c instanceof Error?c.message:"Unknown error",status:n,errorMessage:e,errorCode:t.data?.errorCode,errorId:t.data?.errorId}}}const Kh={send_native:{label:"actionSendNativeLabel",description:"actionSendNativeDesc",fields:[{key:"to_address",label:"fieldToAddress",type:"address",placeholder:"0x...",required:!0,validation:"address"},{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},send_token:{label:"actionSendTokenLabel",description:"actionSendTokenDesc",fields:[{key:"contract_address",label:"fieldTokenContract",type:"address",placeholder:"0x... token contract",required:!0,validation:"address",editable:!1},{key:"token_symbol",label:"fieldTokenSymbol",type:"text",placeholder:"e.g. USDC",required:!1,editable:!1},{key:"decimals",label:"fieldDecimals",type:"number",placeholder:"18",required:!1,editable:!1},{key:"to_address",label:"fieldToAddress",type:"address",placeholder:"0x...",required:!0,validation:"address"},{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},swap_token:{label:"actionSwapTokenLabel",description:"actionSwapTokenDesc",fields:[{key:"token_in",label:"fieldTokenIn",type:"address",placeholder:"0x... or native",required:!0,editable:!1},{key:"token_in_symbol",label:"fieldTokenInSymbol",type:"text",placeholder:"e.g. ETH",required:!1,editable:!1},{key:"token_out",label:"fieldTokenOut",type:"address",placeholder:"0x...",required:!0,editable:!1},{key:"token_out_symbol",label:"fieldTokenOutSymbol",type:"text",placeholder:"e.g. USDC",required:!1,editable:!1},{key:"token_in_decimals",label:"fieldTokenInDecimals",type:"number",placeholder:"18",required:!1,editable:!1},{key:"token_out_decimals",label:"fieldTokenOutDecimals",type:"number",placeholder:"18",required:!1,editable:!1},{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},approve_token:{label:"actionApproveTokenLabel",description:"actionApproveTokenDesc",fields:[{key:"contract_address",label:"fieldTokenContract",type:"address",placeholder:"0x... token contract",required:!0,validation:"address",editable:!1},{key:"token_symbol",label:"fieldTokenSymbol",type:"text",placeholder:"e.g. USDC",required:!1,editable:!1},{key:"spender_address",label:"fieldSpenderAddress",type:"address",placeholder:"0x... spender contract",required:!0,validation:"address",editable:!1},{key:"amount",label:"fieldAmountUnlimited",type:"amount",placeholder:"0.0 or leave empty for max",required:!1,validation:"amount"},{key:"decimals",label:"fieldDecimals",type:"number",placeholder:"18",required:!1,editable:!1}]},wrap_native:{label:"actionWrapNativeLabel",description:"actionWrapNativeDesc",fields:[{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},unwrap_native:{label:"actionUnwrapNativeLabel",description:"actionUnwrapNativeDesc",fields:[{key:"amount",label:"fieldAmount",type:"amount",placeholder:"0.0",required:!0,validation:"amount"}]},send_nft:{label:"actionSendNftLabel",description:"actionSendNftDesc",fields:[{key:"contract_address",label:"fieldNftContract",type:"address",placeholder:"0x... NFT contract",required:!0,validation:"address",editable:!1},{key:"token_id",label:"fieldTokenId",type:"text",placeholder:"e.g. 1234",required:!0,editable:!1},{key:"to_address",label:"fieldToAddress",type:"address",placeholder:"0x...",required:!0,validation:"address"},{key:"token_standard",label:"fieldTokenStandard",type:"text",placeholder:"ERC721 or ERC1155",required:!0,editable:!1},{key:"amount",label:"fieldAmount",type:"text",placeholder:"1",required:!0},{key:"maxAmount",label:"fieldMaxAmount",type:"text",placeholder:"",required:!1,editable:!1,hidden:!0},{key:"nft_name",label:"fieldNftName",type:"text",placeholder:"e.g. Bored Ape #1234",required:!1,editable:!1}]}};function Qh(e){if(!e||""===e?.trim())return!1;const t=parseFloat(e);return!isNaN(t)&&t>0}const Zh=({action:t,initialValues:r,onSubmit:o,onCancel:a,isSubmitting:c=!1,tokenInfo:u,nftInfo:l,disabled:d=!1})=>{const{t:f,ti:h}=w(),p=Kh[t],[m,b]=i(()=>{if(!p)return{};const e={};return p.fields.forEach(t=>{e[t.key]=r[t.key]||""}),e}),[g]=i(()=>["send_native","send_token","swap_token"].includes(t)&&!u&&m.contract_address?f("formTokenNotFound"):null),[y,v]=i(()=>{const e={};if(["send_native","send_token","swap_token"].includes(t)&&u){const t=parseFloat(u.balanceFormatted||"0");if(t<=0)e.amount=h("formNoBalance",{symbol:u.symbol??""});else{const n=r.amount?.trim();n&&Qh(n)&&parseFloat(n)>t&&(e.amount=h("formInsufficientBalance",{balance:u.balanceFormatted,symbol:u.symbol??""}))}}return e}),A=s((e,t)=>{b(n=>({...n,[e]:t})),y[e]&&v(t=>{const n={...t};return delete n[e],n})},[y]),k=s(()=>{if(!p)return!1;const e={};if(p.fields.forEach(n=>{const r=m[n.key]?.trim()||"";!n.required||r||"send_nft"===t&&"amount"===n.key?r&&("address"!==n.validation||Ye(r)||(e[n.key]=f("formInvalidAddress")),"amount"!==n.validation||Qh(r)||(e[n.key]=f("formMustBePositive")),"amount"===n.key&&r&&Qh(r)&&u?.balanceFormatted&&parseFloat(r)>parseFloat(u.balanceFormatted)&&(e[n.key]=h("formInsufficientBalance",{balance:u.balanceFormatted,symbol:u.symbol??""})),"positive_number"===n.validation&&(isNaN(Number(r))||Number(r)<0)&&(e[n.key]=f("formMustBeValidNumber"))):e[n.key]=h("formFieldRequired",{field:f(n.label)})}),"send_nft"===t&&"ERC1155"===m.token_standard?.toUpperCase()){const t=m.amount?.trim();if(t)if(!/^\d+$/.test(t)||parseInt(t,10)<1)e.amount=f("formMustBePositiveInteger");else{const n=parseInt(r.maxAmount||"0",10);n>0&&parseInt(t,10)>n&&(e.amount=h("formAmountExceedsNft",{max:String(n)}))}else e.amount=h("formFieldRequired",{field:f("fieldAmount")})}return v(e),0===Object.keys(e).length},[p,m,u,t,r,f,h]),x=s(()=>{k()&&o(t,m)},[k,o,t,m]);return p?/* @__PURE__ */n("div",{className:"action-form",children:[
10
10
  /* @__PURE__ */e("div",{className:"action-form-title",children:/* @__PURE__ */e("span",{children:f(p.label)})}),g&&/* @__PURE__ */n("div",{className:"action-form-general-error",children:["⚠️ ",g]}),u&&/* @__PURE__ */e("div",{className:"action-form-token-info",children:/* @__PURE__ */n("div",{className:"token-info-row",children:[u.logo&&/* @__PURE__ */e("img",{src:u.logo,alt:u.symbol,className:"token-info-logo",width:20,height:20}),
11
11
  /* @__PURE__ */n("div",{className:"token-info-details",children:[
12
12
  /* @__PURE__ */n("span",{className:"token-info-name",children:[u.name," (",u.symbol,")"]}),
@@ -17,7 +17,7 @@ return e(t,{children:oh(r||"")&&/* @__PURE__ */n("div",{className:"chat-user-inf
17
17
  /* @__PURE__ */e("button",{type:"button",className:"action-form-pct-btn action-form-max-btn",onClick:()=>A("amount",u.balanceFormatted),disabled:c||d,children:f("formMax")})]}),"amount"===i.key&&"send_nft"===t&&l&&/* @__PURE__ */e("div",{className:"action-form-pct-btns",children:/* @__PURE__ */e("button",{type:"button",className:"action-form-pct-btn action-form-max-btn",onClick:()=>A("amount",r.maxAmount||""),disabled:c||d,children:f("formMax")})})]}),(()=>{const t=!1===i.editable&&!!r[i.key]||d,n=c||t,o=[y[i.key]?"error":"",t?"readonly":""].filter(Boolean).join(" ");return"address"===i.type?/* @__PURE__ */e("textarea",{rows:2,placeholder:i.placeholder,value:m[i.key]||"",onChange:e=>A(i.key,e.target.value),className:o,disabled:n||d}):/* @__PURE__ */e("input",{type:"number"===i.type?"number":"text",placeholder:i.placeholder,value:m[i.key]||"",onChange:e=>A(i.key,e.target.value),className:o,disabled:n||d})})(),y[i.key]&&/* @__PURE__ */e("span",{className:"field-error",children:y[i.key]})]},i.key))}),!d&&/* @__PURE__ */n("div",{className:"action-form-actions",children:[
18
18
  /* @__PURE__ */e("button",{className:"message-button",onClick:a,type:"button",disabled:c,children:f("formCancel")}),
19
19
  /* @__PURE__ */e("button",{className:"message-button",onClick:x,type:"button",disabled:c,children:f(c?"formProcessing":"formExecute")})]})]}):null},_h=({scrollContainerRef:t,threshold:n=200})=>{const[r,s]=i(!1);return o(()=>{const e=t.current;if(!e)return;const r=()=>{const{scrollTop:t,scrollHeight:r,clientHeight:i}=e;s(r-t-i>n)};return e.addEventListener("scroll",r,{passive:!0}),r(),()=>{e.removeEventListener("scroll",r)}},[t,n]),r?/* @__PURE__ */e("button",{className:"scroll-to-bottom-btn",onClick:()=>{t.current?.scrollTo({top:t.current.scrollHeight,behavior:"smooth"})},"aria-label":"Scroll to bottom",type:"button",children:/* @__PURE__ */e("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",children:/* @__PURE__ */e("path",{d:"M9 3V15M9 15L4 10M9 15L14 10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):null},$h=e=>e?`**CRITICAL - LANGUAGE**: Respond in the specified language: "${e||"detect from current question"}". Do NOT follow language from conversation history.`:"**CRITICAL - LANGUAGE**: You MUST detect the language of the user's CURRENT question and respond ONLY in that exact language. Ignore the language of previous messages in conversation history — only the current question matters. If the current question is in English, respond in English. If in Vietnamese, respond in Vietnamese. NEVER default to Chinese or any other language.",ep={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",10:"0x4200000000000000000000000000000000000006",56:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",137:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},tp=[{name:"transfer",type:"function",stateMutability:"nonpayable",inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{name:"approve",type:"function",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{name:"allowance",type:"function",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]}],np=[{name:"deposit",type:"function",stateMutability:"payable",inputs:[],outputs:[]},{name:"withdraw",type:"function",stateMutability:"nonpayable",inputs:[{name:"wad",type:"uint256"}],outputs:[]}],rp=[{name:"safeTransferFrom",type:"function",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]}],ip=[{name:"safeTransferFrom",type:"function",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"id",type:"uint256"},{name:"amount",type:"uint256"},{name:"data",type:"bytes"}],outputs:[]}];function op(e,t){if(t)return t;const n=Fn[e];return n?.rpcUrls?.default?.http?.[0]}async function sp(e){const{transactionHash:t,chainId:n,pollingInterval:r=3e3,timeout:i=12e4,rpcUrl:o}=e,s=op(n,o);if(!s)throw new Error(`No RPC endpoint for chain ${n}`);const a=Date.now();for(;Date.now()-a<i;){try{const e=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[t]})}),n=await e.json();if(n.result){const e=n.result;return{status:"0x1"===e.status?"success":"fail",blockNumber:e.blockNumber,gasUsed:e.gasUsed,effectiveGasPrice:e.effectiveGasPrice}}}catch(c){}await new Promise(e=>setTimeout(e,r))}throw new Error(`Transaction ${t} was not mined within ${i/1e3}s`)}async function ap(e){const{tokenAddress:t,ownerAddress:n,spenderAddress:r,chainId:i,rpcUrl:o}=e,s=op(i,o);if(!s)return BigInt(0);try{const e=st({abi:tp,functionName:"allowance",args:[n,r]}),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:e},"latest"]})}),o=await i.json();return o.result&&"0x"!==o.result?BigInt(o.result):BigInt(0)}catch(a){return BigInt(0)}}function cp(e){const{tokenAddress:t,spenderAddress:n,fromAddress:r,chainId:i,tokenSymbol:o,amount:s}=e,a=s&&BigInt(s)>0n?BigInt(s):Jt;return{from:r,to:t,data:st({abi:tp,functionName:"approve",args:[n,a]}),value:"0",chainId:i,description:`Approve ${o||"token"} for swap`}}async function up(e){const{address:t,chainId:n,rpcUrl:r}=e,i=op(n,r);if(!i)return new Dh(0);try{const e=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getBalance",params:[t,"latest"]})}),n=await e.json();return n.result&&"0x"!==n.result?new Dh(BigInt(n.result).toString()):new Dh(0)}catch(o){return new Dh(0)}}async function lp(e){const{from:t,to:n,data:r,value:i,chainId:o,rpcUrl:s}=e,a=op(o,s);if(!a)return new Dh(0);try{const[e,o]=await Promise.all([fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_estimateGas",params:[{from:t,to:n,data:r,...i&&"0"!==i?{value:i}:{}}]})}),fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:2,method:"eth_gasPrice",params:[]})})]),[s,c]=await Promise.all([e.json(),o.json()]),u=s.result?new Dh(BigInt(s.result).toString()):new Dh(0),l=c.result?new Dh(BigInt(c.result).toString()):new Dh(0);return u.times(l).times(1.1)}catch(c){return new Dh(0)}}async function dp(e){const{chainId:t,rpcUrl:n}=e,r=op(t,n);if(!r)return new Dh(0);try{const e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})}),t=await e.json();return t.result&&"0x"!==t.result?new Dh(BigInt(t.result).toString()):new Dh(0)}catch(i){return new Dh(0)}}var fp,hp,pp={},mp={exports:{}},wp=mp.exports;var bp=function(){if(hp)return pp;hp=1,Object.defineProperty(pp,"u",{value:!0});var e,t,n,i=r,o=(e=i)&&"object"==typeof e&&"default"in e?e.default:e,s=(fp||(fp=1,t=mp,n=mp.exports,function(e,r){var i="function",o="undefined",s="object",a="string",c="major",u="model",l="name",d="type",f="vendor",h="version",p="architecture",m="console",w="mobile",b="tablet",g="smarttv",y="wearable",v="embedded",A="Amazon",k="Apple",x="ASUS",E="BlackBerry",T="Browser",C="Chrome",I="Firefox",S="Google",N="Huawei",B="LG",M="Microsoft",U="Motorola",R="Opera",O="Samsung",F="Sharp",L="Sony",D="Xiaomi",P="Zebra",H="Facebook",j="Chromium OS",z="Mac OS",J=" Browser",q=function(e){for(var t={},n=0;n<e.length;n++)t[e[n].toUpperCase()]=e[n];return t},V=function(e,t){return typeof e===a&&-1!==Y(t).indexOf(Y(e))},Y=function(e){return e.toLowerCase()},G=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===o?e:e.substring(0,500)},W=function(e,t){for(var n,o,a,c,u,l,d=0;d<t.length&&!u;){var f=t[d],h=t[d+1];for(n=o=0;n<f.length&&!u&&f[n];)if(u=f[n++].exec(e))for(a=0;a<h.length;a++)l=u[++o],typeof(c=h[a])===s&&c.length>0?2===c.length?typeof c[1]==i?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==i||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):r:this[c[0]]=l?c[1].call(this,l,c[2]):r:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):r):this[c]=l||r;d+=2}},X=function(e,t){for(var n in t)if(typeof t[n]===s&&t[n].length>0){for(var i=0;i<t[n].length;i++)if(V(t[n][i],e))return"?"===n?r:n}else if(V(t[n],e))return"?"===n?r:n;return t.hasOwnProperty("*")?t["*"]:e},K={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Q={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,h],[/opios[\/ ]+([\w\.]+)/i],[h,[l,R+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[l,R+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[l,R]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[l,"Baidu"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim)\s?(?:browser)?[\/ ]?([\w\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[l,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[l,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[l,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[l,"UC"+T]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[l,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[l,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[l,"Smart Lenovo "+T]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+T],h],[/\bfocus\/([\w\.]+)/i],[h,[l,I+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[l,R+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[l,R+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[l,"MIUI "+T]],[/fxios\/([-\w\.]+)/i],[h,[l,I]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360"+J]],[/\b(qq)\/([\w\.]+)/i],[[l,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1"+J],h],[/samsungbrowser\/([\w\.]+)/i],[h,[l,O+" Internet"]],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],h],[/metasr[\/ ]?([\d\.]+)/i],[h,[l,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[l,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i],[l,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,H],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[l,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[l,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[l,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[l,C+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,C+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[l,"Android "+T]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[h,X,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],h],[/(wolvic)\/([\w\.]+)/i],[l,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[l,I+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[l,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[l,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[p,"amd64"]],[/(ia32(?=;))/i],[[p,Y]],[/((?:i[346]|x)86)[;\)]/i],[[p,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[p,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[p,"armhf"]],[/windows (ce|mobile); ppc;/i],[[p,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[p,/ower/,"",Y]],[/(sun4\w)[;\)]/i],[[p,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[p,Y]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[u,[f,O],[d,b]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[f,O],[d,w]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[f,k],[d,w]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[f,k],[d,b]],[/(macintosh);/i],[u,[f,k]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[f,F],[d,w]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[u,[f,N],[d,b]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[f,N],[d,w]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[u,/_/g," "],[f,D],[d,w]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[u,/_/g," "],[f,D],[d,b]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[f,"OPPO"],[d,w]],[/\b(opd2\d{3}a?) bui/i],[u,[f,"OPPO"],[d,b]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[f,"Vivo"],[d,w]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[f,"Realme"],[d,w]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[u,[f,U],[d,w]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[f,U],[d,b]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[f,B],[d,b]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[f,B],[d,w]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[u,[f,"Lenovo"],[d,b]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[u,/_/g," "],[f,"Nokia"],[d,w]],[/(pixel c)\b/i],[u,[f,S],[d,b]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[f,S],[d,w]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[u,[f,L],[d,w]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[f,L],[d,b]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[f,"OnePlus"],[d,w]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[f,A],[d,b]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[f,A],[d,w]],[/(playbook);[-\w\),; ]+(rim)/i],[u,f,[d,b]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[f,E],[d,w]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[f,x],[d,b]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[f,x],[d,w]],[/(nexus 9)/i],[u,[f,"HTC"],[d,b]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[f,[u,/_/g," "],[d,w]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[u,[f,"TCL"],[d,b]],[/(itel) ((\w+))/i],[[f,Y],u,[d,X,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[f,"Acer"],[d,b]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[f,"Meizu"],[d,w]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[f,"Ulefone"],[d,w]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[f,"Nothing"],[d,w]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[f,u,[d,w]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[f,u,[d,b]],[/(surface duo)/i],[u,[f,M],[d,b]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[f,"Fairphone"],[d,w]],[/(u304aa)/i],[u,[f,"AT&T"],[d,w]],[/\bsie-(\w*)/i],[u,[f,"Siemens"],[d,w]],[/\b(rct\w+) b/i],[u,[f,"RCA"],[d,b]],[/\b(venue[\d ]{2,7}) b/i],[u,[f,"Dell"],[d,b]],[/\b(q(?:mv|ta)\w+) b/i],[u,[f,"Verizon"],[d,b]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[u,[f,"Barnes & Noble"],[d,b]],[/\b(tm\d{3}\w+) b/i],[u,[f,"NuVision"],[d,b]],[/\b(k88) b/i],[u,[f,"ZTE"],[d,b]],[/\b(nx\d{3}j) b/i],[u,[f,"ZTE"],[d,w]],[/\b(gen\d{3}) b.+49h/i],[u,[f,"Swiss"],[d,w]],[/\b(zur\d{3}) b/i],[u,[f,"Swiss"],[d,b]],[/\b((zeki)?tb.*\b) b/i],[u,[f,"Zeki"],[d,b]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[f,"Dragon Touch"],u,[d,b]],[/\b(ns-?\w{0,9}) b/i],[u,[f,"Insignia"],[d,b]],[/\b((nxa|next)-?\w{0,9}) b/i],[u,[f,"NextBook"],[d,b]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[f,"Voice"],u,[d,w]],[/\b(lvtel\-)?(v1[12]) b/i],[[f,"LvTel"],u,[d,w]],[/\b(ph-1) /i],[u,[f,"Essential"],[d,w]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[u,[f,"Envizen"],[d,b]],[/\b(trio[-\w\. ]+) b/i],[u,[f,"MachSpeed"],[d,b]],[/\btu_(1491) b/i],[u,[f,"Rotor"],[d,b]],[/(shield[\w ]+) b/i],[u,[f,"Nvidia"],[d,b]],[/(sprint) (\w+)/i],[f,u,[d,w]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[f,M],[d,w]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[f,P],[d,b]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[f,P],[d,w]],[/smart-tv.+(samsung)/i],[f,[d,g]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[f,O],[d,g]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[f,B],[d,g]],[/(apple) ?tv/i],[f,[u,k+" TV"],[d,g]],[/crkey/i],[[u,C+"cast"],[f,S],[d,g]],[/droid.+aft(\w+)( bui|\))/i],[u,[f,A],[d,g]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[f,F],[d,g]],[/(bravia[\w ]+)( bui|\))/i],[u,[f,L],[d,g]],[/(mitv-\w{5}) bui/i],[u,[f,D],[d,g]],[/Hbbtv.*(technisat) (.*);/i],[f,u,[d,g]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[f,G],[u,G],[d,g]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,g]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[f,u,[d,m]],[/droid.+; (shield) bui/i],[u,[f,"Nvidia"],[d,m]],[/(playstation [345portablevi]+)/i],[u,[f,L],[d,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[f,M],[d,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[u,[f,O],[d,y]],[/((pebble))app/i],[f,u,[d,y]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[f,k],[d,y]],[/droid.+; (glass) \d/i],[u,[f,S],[d,y]],[/droid.+; (wt63?0{2,3})\)/i],[u,[f,P],[d,y]],[/(quest( \d| pro)?)/i],[u,[f,H],[d,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[f,[d,v]],[/(aeobc)\b/i],[u,[f,A],[d,v]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[d,w]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[d,b]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,b]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,w]],[/(android[-\w\. ]{0,9});.+buil/i],[u,[f,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[l,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,h],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[l,[h,X,K]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,X,K],[l,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,z],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,h],[/\(bb(10);/i],[h,[l,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[l,I+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[l,C+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,j],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,h],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[l,h]]},Z=function(t,n){if(typeof t===s&&(n=t,t=r),!(this instanceof Z))return new Z(t,n).getResult();var m=typeof e!==o&&e.navigator?e.navigator:r,g=t||(m&&m.userAgent?m.userAgent:""),y=m&&m.userAgentData?m.userAgentData:r,v=n?function(e,t){var n={};for(var r in e)t[r]&&t[r].length%2==0?n[r]=t[r].concat(e[r]):n[r]=e[r];return n}(Q,n):Q,A=m&&m.userAgent==g;return this.getBrowser=function(){var e,t={};return t[l]=r,t[h]=r,W.call(t,g,v.browser),t[c]=typeof(e=t[h])===a?e.replace(/[^\d\.]/g,"").split(".")[0]:r,A&&m&&m.brave&&typeof m.brave.isBrave==i&&(t[l]="Brave"),t},this.getCPU=function(){var e={};return e[p]=r,W.call(e,g,v.cpu),e},this.getDevice=function(){var e={};return e[f]=r,e[u]=r,e[d]=r,W.call(e,g,v.device),A&&!e[d]&&y&&y.mobile&&(e[d]=w),A&&"Macintosh"==e[u]&&m&&typeof m.standalone!==o&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[u]="iPad",e[d]=b),e},this.getEngine=function(){var e={};return e[l]=r,e[h]=r,W.call(e,g,v.engine),e},this.getOS=function(){var e={};return e[l]=r,e[h]=r,W.call(e,g,v.os),A&&!e[l]&&y&&y.platform&&"Unknown"!=y.platform&&(e[l]=y.platform.replace(/chrome os/i,j).replace(/macos/i,z)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return g},this.setUA=function(e){return g=typeof e===a&&e.length>500?G(e,500):e,this},this.setUA(g),this};Z.VERSION="1.0.39",Z.BROWSER=q([l,h,c]),Z.CPU=q([p]),Z.DEVICE=q([u,f,d,m,w,g,b,y,v]),Z.ENGINE=Z.OS=q([l,h]),t.exports&&(n=t.exports=Z),n.UAParser=Z;var _=typeof e!==o&&(e.jQuery||e.Zepto);if(_&&!_.ua){var $=new Z;_.ua=$.getResult(),_.ua.get=function(){return $.getUA()},_.ua.set=function(e){$.setUA(e);var t=$.getResult();for(var n in t)_.ua[n]=t[n]}}}("object"==typeof window?window:wp)),mp.exports),a=new s,c=a.getBrowser(),u=a.getCPU(),l=a.getDevice(),d=a.getEngine(),f=a.getOS(),h=a.getUA(),p=function(e){return a.setUA(e)},m=function(e){if(e){var t=new s(e);return{UA:t,browser:t.getBrowser(),cpu:t.getCPU(),device:t.getDevice(),engine:t.getEngine(),os:t.getOS(),ua:t.getUA(),setUserAgent:function(e){return t.setUA(e)}}}},w=/* @__PURE__ */Object.freeze({ClientUAInstance:a,browser:c,cpu:u,device:l,engine:d,os:f,ua:h,setUa:p,parseUserAgent:m});function b(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function g(e){return(g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function y(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function v(){return v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},v.apply(this,arguments)}function A(e){return(A=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function k(e,t){return(k=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function x(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function E(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function T(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var C="mobile",I="tablet",S="smarttv",N="console",B="wearable",M="embedded",U=void 0,R={Chrome:"Chrome",Firefox:"Firefox",Opera:"Opera",Yandex:"Yandex",Safari:"Safari",InternetExplorer:"Internet Explorer",Edge:"Edge",Chromium:"Chromium",Ie:"IE",MobileSafari:"Mobile Safari",EdgeChromium:"Edge Chromium",MIUI:"MIUI Browser",SamsungBrowser:"Samsung Browser"},O={IOS:"iOS",Android:"Android",WindowsPhone:"Windows Phone",Windows:"Windows",MAC_OS:"Mac OS"},F={isMobile:!1,isTablet:!1,isBrowser:!1,isSmartTV:!1,isConsole:!1,isWearable:!1},L=function(e){return e||(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"none")},D=function(){return!("undefined"==typeof window||!window.navigator&&!navigator)&&(window.navigator||navigator)},P=function(e){var t=D();return t&&t.platform&&(-1!==t.platform.indexOf(e)||"MacIntel"===t.platform&&t.maxTouchPoints>1&&!window.MSStream)},H=function(e){return e.type===C},j=function(e){return e.type===I},z=function(e){var t=e.type;return t===C||t===I},J=function(e){return e.type===S},q=function(e){return e.type===U},V=function(e){return e.type===B},Y=function(e){return e.type===N},G=function(e){return e.type===M},W=function(e){var t=e.vendor;return L(t)},X=function(e){var t=e.model;return L(t)},K=function(e){var t=e.type;return L(t,"browser")},Q=function(e){return e.name===O.Android},Z=function(e){return e.name===O.Windows},_=function(e){return e.name===O.MAC_OS},$=function(e){return e.name===O.WindowsPhone},ee=function(e){return e.name===O.IOS},te=function(e){var t=e.version;return L(t)},ne=function(e){var t=e.name;return L(t)},re=function(e){return e.name===R.Chrome},ie=function(e){return e.name===R.Firefox},oe=function(e){return e.name===R.Chromium},se=function(e){return e.name===R.Edge},ae=function(e){return e.name===R.Yandex},ce=function(e){var t=e.name;return t===R.Safari||t===R.MobileSafari},ue=function(e){return e.name===R.MobileSafari},le=function(e){return e.name===R.Opera},de=function(e){var t=e.name;return t===R.InternetExplorer||t===R.Ie},fe=function(e){return e.name===R.MIUI},he=function(e){return e.name===R.SamsungBrowser},pe=function(e){var t=e.version;return L(t)},me=function(e){var t=e.major;return L(t)},we=function(e){var t=e.name;return L(t)},be=function(e){var t=e.name;return L(t)},ge=function(e){var t=e.version;return L(t)},ye=function(){var e=D(),t=e&&e.userAgent&&e.userAgent.toLowerCase();return"string"==typeof t&&/electron/.test(t)},ve=function(e){return"string"==typeof e&&-1!==e.indexOf("Edg/")},Ae=function(){var e=D();return e&&(/iPad|iPhone|iPod/.test(e.platform)||"MacIntel"===e.platform&&e.maxTouchPoints>1)&&!window.MSStream},ke=function(){return P("iPad")},xe=function(){return P("iPhone")},Ee=function(){return P("iPod")},Te=function(e){return L(e)};function Ce(e){var t=e||w,n=t.device,r=t.browser,i=t.os,o=t.engine,s=t.ua;return{isSmartTV:J(n),isConsole:Y(n),isWearable:V(n),isEmbedded:G(n),isMobileSafari:ue(r)||ke(),isChromium:oe(r),isMobile:z(n)||ke(),isMobileOnly:H(n),isTablet:j(n)||ke(),isBrowser:q(n),isDesktop:q(n),isAndroid:Q(i),isWinPhone:$(i),isIOS:ee(i)||ke(),isChrome:re(r),isFirefox:ie(r),isSafari:ce(r),isOpera:le(r),isIE:de(r),osVersion:te(i),osName:ne(i),fullBrowserVersion:pe(r),browserVersion:me(r),browserName:we(r),mobileVendor:W(n),mobileModel:X(n),engineName:be(o),engineVersion:ge(o),getUA:Te(s),isEdge:se(r)||ve(s),isYandex:ae(r),deviceType:K(n),isIOS13:Ae(),isIPad13:ke(),isIPhone13:xe(),isIPod13:Ee(),isElectron:ye(),isEdgeChromium:ve(s),isLegacyEdge:se(r)&&!ve(s),isWindows:Z(i),isMacOs:_(i),isMIUI:fe(r),isSamsungBrowser:he(r)}}var Ie=J(l),Se=Y(l),Ne=V(l),Be=G(l),Me=ue(c)||ke(),Ue=oe(c),Re=z(l)||ke(),Oe=H(l),Fe=j(l)||ke(),Le=q(l),De=q(l),Pe=Q(f),He=$(f),je=ee(f)||ke(),ze=re(c),Je=ie(c),qe=ce(c),Ve=le(c),Ye=de(c),Ge=te(f),We=ne(f),Xe=pe(c),Ke=me(c),Qe=we(c),Ze=W(l),_e=X(l),$e=be(d),et=ge(d),tt=Te(h),nt=se(c)||ve(h),rt=ae(c),it=K(l),ot=Ae(),st=ke(),at=xe(),ct=Ee(),ut=ye(),lt=ve(h),dt=se(c)&&!ve(h),ft=Z(f),ht=_(f),pt=fe(c),mt=he(c);function wt(e){var t=e||window.navigator.userAgent;return m(t)}return pp.AndroidView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return Pe?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.BrowserTypes=R,pp.BrowserView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return Le?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.ConsoleView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return Se?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.CustomView=function(e){var t=e.renderWithFragment,n=e.children;e.viewClassName,e.style;var r=e.condition,s=x(e,["renderWithFragment","children","viewClassName","style","condition"]);return r?t?o.createElement(i.Fragment,null,n):o.createElement("div",s,n):null},pp.IEView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return Ye?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.IOSView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return je?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.MobileOnlyView=function(e){var t=e.renderWithFragment,n=e.children;e.viewClassName,e.style;var r=x(e,["renderWithFragment","children","viewClassName","style"]);return Oe?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.MobileView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return Re?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.OsTypes=O,pp.SmartTVView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return Ie?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.TabletView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return Fe?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.WearableView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return Ne?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.WinPhoneView=function(e){var t=e.renderWithFragment,n=e.children,r=x(e,["renderWithFragment","children"]);return He?t?o.createElement(i.Fragment,null,n):o.createElement("div",r,n):null},pp.browserName=Qe,pp.browserVersion=Ke,pp.deviceDetect=function(e){var t=e?m(e):w,n=t.device,r=t.browser,i=t.engine,o=t.os,s=t.ua,a=function(e){switch(e){case C:return{isMobile:!0};case I:return{isTablet:!0};case S:return{isSmartTV:!0};case N:return{isConsole:!0};case B:return{isWearable:!0};case U:return{isBrowser:!0};case M:return{isEmbedded:!0};default:return F}}(n.type),c=a.isBrowser,u=a.isMobile,l=a.isTablet,d=a.isSmartTV,f=a.isConsole,h=a.isWearable,p=a.isEmbedded;return c?function(e,t,n,r,i){return{isBrowser:e,browserMajorVersion:L(t.major),browserFullVersion:L(t.version),browserName:L(t.name),engineName:L(n.name),engineVersion:L(n.version),osName:L(r.name),osVersion:L(r.version),userAgent:L(i)}}(c,r,i,o,s):d?function(e,t,n,r){return{isSmartTV:e,engineName:L(t.name),engineVersion:L(t.version),osName:L(n.name),osVersion:L(n.version),userAgent:L(r)}}(d,i,o,s):f?function(e,t,n,r){return{isConsole:e,engineName:L(t.name),engineVersion:L(t.version),osName:L(n.name),osVersion:L(n.version),userAgent:L(r)}}(f,i,o,s):u||l?function(e,t,n,r){return function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?b(Object(n),!0).forEach(function(t){y(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):b(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({},e,{vendor:L(t.vendor),model:L(t.model),os:L(n.name),osVersion:L(n.version),ua:L(r)})}(a,n,o,s):h?function(e,t,n,r){return{isWearable:e,engineName:L(t.name),engineVersion:L(t.version),osName:L(n.name),osVersion:L(n.version),userAgent:L(r)}}(h,i,o,s):p?function(e,t,n,r,i){return{isEmbedded:e,vendor:L(t.vendor),model:L(t.model),engineName:L(n.name),engineVersion:L(n.version),osName:L(r.name),osVersion:L(r.version),userAgent:L(i)}}(p,n,i,o,s):void 0},pp.deviceType=it,pp.engineName=$e,pp.engineVersion=et,pp.fullBrowserVersion=Xe,pp.getSelectorsByUserAgent=function(e){if(e&&"string"==typeof e){var t=m(e);return Ce({device:t.device,browser:t.browser,os:t.os,engine:t.engine,ua:t.ua})}},pp.getUA=tt,pp.isAndroid=Pe,pp.isBrowser=Le,pp.isChrome=ze,pp.isChromium=Ue,pp.isConsole=Se,pp.isDesktop=De,pp.isEdge=nt,pp.isEdgeChromium=lt,pp.isElectron=ut,pp.isEmbedded=Be,pp.isFirefox=Je,pp.isIE=Ye,pp.isIOS=je,pp.isIOS13=ot,pp.isIPad13=st,pp.isIPhone13=at,pp.isIPod13=ct,pp.isLegacyEdge=dt,pp.isMIUI=pt,pp.isMacOs=ht,pp.isMobile=Re,pp.isMobileOnly=Oe,pp.isMobileSafari=Me,pp.isOpera=Ve,pp.isSafari=qe,pp.isSamsungBrowser=mt,pp.isSmartTV=Ie,pp.isTablet=Fe,pp.isWearable=Ne,pp.isWinPhone=He,pp.isWindows=ft,pp.isYandex=rt,pp.mobileModel=_e,pp.mobileVendor=Ze,pp.osName=We,pp.osVersion=Ge,pp.parseUserAgent=m,pp.setUserAgent=function(e){return p(e)},pp.useDeviceData=wt,pp.useDeviceSelectors=function(e){var t=wt(e||window.navigator.userAgent);return[Ce(t),t]},pp.useMobileOrientation=function(){var e=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o=[],s=!0,a=!1;try{for(n=n.call(e);!(s=(r=n.next()).done)&&(o.push(r.value),!t||o.length!==t);s=!0);}catch(c){a=!0,i=c}finally{try{s||null==n.return||n.return()}finally{if(a)throw i}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return T(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?T(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(i.useState(function(){var e=window.innerWidth>window.innerHeight?90:0;return{isPortrait:0===e,isLandscape:90===e,orientation:0===e?"portrait":"landscape"}}),2),t=e[0],n=e[1],r=i.useCallback(function(){var e=window.innerWidth>window.innerHeight?90:0,r={isPortrait:0===e,isLandscape:90===e,orientation:0===e?"portrait":"landscape"};t.orientation!==r.orientation&&n(r)},[t.orientation]);return i.useEffect(function(){return void 0!==("undefined"==typeof window?"undefined":g(window))&&Re&&(r(),window.addEventListener("load",r,!1),window.addEventListener("resize",r,!1)),function(){window.removeEventListener("resize",r,!1),window.removeEventListener("load",r,!1)}},[r]),t},pp.withOrientationChange=function(e){/* @__PURE__ */
20
- return function(t){function n(e){var t;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,n),(t=function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return E(e)}(this,A(n).call(this,e))).isEventListenerAdded=!1,t.handleOrientationChange=t.handleOrientationChange.bind(E(t)),t.onOrientationChange=t.onOrientationChange.bind(E(t)),t.onPageLoad=t.onPageLoad.bind(E(t)),t.state={isLandscape:!1,isPortrait:!1},t}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&k(e,t)}(n,t),r=n,(i=[{key:"handleOrientationChange",value:function(){this.isEventListenerAdded||(this.isEventListenerAdded=!0);var e=window.innerWidth>window.innerHeight?90:0;this.setState({isPortrait:0===e,isLandscape:90===e})}},{key:"onOrientationChange",value:function(){this.handleOrientationChange()}},{key:"onPageLoad",value:function(){this.handleOrientationChange()}},{key:"componentDidMount",value:function(){void 0!==("undefined"==typeof window?"undefined":g(window))&&Re&&(this.isEventListenerAdded?window.removeEventListener("load",this.onPageLoad,!1):(this.handleOrientationChange(),window.addEventListener("load",this.onPageLoad,!1)),window.addEventListener("resize",this.onOrientationChange,!1))}},{key:"componentWillUnmount",value:function(){window.removeEventListener("resize",this.onOrientationChange,!1)}},{key:"render",value:function(){return o.createElement(e,v({},this.props,{isLandscape:this.state.isLandscape,isPortrait:this.state.isPortrait}))}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(r.prototype,i),n;var r,i}(o.Component)},pp}();const gp="gemini-2.5-flash-lite",yp=new class extends Ph{enableGoogleSearch=!0;constructor(){super("https://nft-demo.keyring.app")}getRuleLanguage(e){return e?`**LANGUAGE ADHERENCE**: You MUST respond ONLY in the language specified as: "${e||"the language of the user's current question"}". Ignore any language bias from context or history. If no language is explicitly provided, detect and follow the current question's language.`:'\n **LANGUAGE ADHERENCE**:\n - **DETECT** the language of the section labeled "CURRENT USER QUESTION" below.\n - **RESPOND ONLY** in that same language.\n - **IGNORE** any language bias from the context or history.\n '}async generateContent(e,t,n){try{const r=`\nBelow is the system context and conversation history. Use it for context but prioritize the instructions at the end.\n---\nSYSTEM CONTEXT & HISTORY:\n${t}\n---\n\n---\nCURRENT USER QUESTION:\n${e}\n---\n\n---\n### MANDATORY RULES:\n1. ${this.getRuleLanguage(n)}\n2. **HISTORY CLEANING**:\n - If any assistant response in the conversation history says it **"doesn't know"**, **"doesn't have data"**, **"cannot find info"**, or similar, you MUST **IGNORE that specific history segment**. \n - Do not let previous data failures prevent you from answering the CURRENT USER QUESTION if the information is available now or in your core knowledge.\n3. **BREVITY**: Keep your answer extremely concise (under 3000 characters).\n4. **DATA INTEGRITY**: Do not mention data gaps or historical missing info; just answer based on available info.\n---\n`,i="/api/gemini-cortex/proxy",o={model:gp,data:{contents:[{parts:[{text:r}]}],tools:[{googleSearch:{}}]}};this.enableGoogleSearch||delete o.data.tools;const s=await this.post(i,o);return s?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||s?.data?.candidates?.[0]?.content?.parts?.[0]?.text}catch(r){if((r?.message?.includes("search_grounding_request_per_project_per_day")||r?.data?.error?.message?.includes("search_grounding_request_per_project_per_day"))&&this.enableGoogleSearch)return this.enableGoogleSearch=!1,await this.generateContent(e,t,n);throw r}}async checkInfoQuestion(e,t){try{const r=t+`---\nCURRENT USER QUESTION:\n${e}\n---\n\nAnalyze this question and determine its category.\nIMPORTANT: The following topics should ALWAYS be classified as "yes" (crypto-related):\n- Greetings (in ANY language): hello, hi, xin chào, bonjour, etc.\n- Cryptocurrency, blockchain, crypto trading, DeFi, NFT, etc.\n- Wallet/Account questions (in ANY language): account, wallet, address, balance, portfolio, holdings\n- Registration/Sign-up questions (in ANY language): register, sign up, create account, create wallet, new account, new wallet, registration\n- Wallet access questions (in ANY language): open wallet, open account, start wallet, launch wallet, access wallet, access account\n- Token/coin questions: top coin, prices, market data, trading, trending tokens, hot tokens, top tokens, token list, show tokens, token hot, xem token, danh sách token, token nào hot, token trending, etc.\n- Chain questions: ETH, Base, Optimism, BSC, Polygon, Arbitrum, etc.\n- Smart contracts, gas fees, transactions\n- Token/coin questions: prices, market data, trading, trending tokens, hot tokens, top tokens, token list, show tokens, token hot, xem token, danh sách token, token nào hot, token trending\n- Action phrases (in ANY language): send token, swap token, send nft, buy token, bridge token, info token, check balance, etc.\n\nCRITICAL: Detect these concepts in ANY language (English, Japanese, Chinese, Vietnamese, Korean, Spanish, etc.)\nThe user may ask in their native language, so recognize the MEANING, not just specific words.\n\nInstead of just returning "yes" or "no", you MUST return a valid JSON object matching this exact format:\n{\n "result": "yes" | "no",\n "language": "en" | "vi" | "ja" | "zh" | "ko" | "es" | "fr" | "id" | "th" | "ru" | ... // etc.\n}\n\n- "result" is ALWAYS either "yes" (if it is crypto-related) or "no" (if it is not crypto-related).\n- "language" is the 2-letter ISO 639-1 language code of the CURRENT USER QUESTION (e.g. "en" for English, "vi" for Vietnamese, "ja" for Japanese, "zh" for Chinese, etc.). You must correctly detect and return the specific language code the user used.\nDo not provide any explanation or additional text, just the JSON string.`,i="/api/gemini-cortex/proxy",o={model:gp,data:{contents:[{parts:[{text:r}]}]}},s=await this.post(i,o),a=s?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||s?.data?.candidates?.[0]?.content?.parts?.[0]?.text;let c={result:"yes",language:"en"};try{let e=a?.trim()||"";e.startsWith("```json")?e=e.replace(/^```json\s*/,"").replace(/\s*```$/,""):e.startsWith("```")&&(e=e.replace(/^```\s*/,"").replace(/\s*```$/,""));const t=e.match(/\{[\s\S]*?\}/);t&&(c=JSON.parse(t[0]))}catch(n){}return c}catch(r){throw r}}async checkIsQuestionActionWeb3(e,t){try{const n=t+`---\nCURRENT USER QUESTION:\n${e}\n---\n\n #### Analyze this question and determine its category.\nIMPORTANT: The following topics should ALWAYS be classified as "yes" (action-oriented):\n- Greetings (in ANY language): hello, hi, xin chào, bonjour, etc.\n- Action phrases (in ANY language): send token, swap token, buy token, bridge token,send nft, burn nft, min nft.\n- Wallet/Account questions (in ANY language): account, wallet, address, balance, portfolio, holdings\n- Registration/Sign-up questions (in ANY language): register, sign up, create account, create wallet, new account, new wallet, registration\n- Wallet access questions (in ANY language): open wallet, open account, start wallet, launch wallet, access wallet, access account\n\nIMPORTANT: The user may ask in their native language, so recognize the MEANING, not just specific words.\n\nOtherwise, respond with ONLY the word "no" (lowercase, nothing else).\nDo not provide any explanation or additional text.`,r="/api/gemini-cortex/proxy",i={model:gp,data:{contents:[{parts:[{text:n}]}]}},o=await this.post(r,i),s=o?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||o?.data?.candidates?.[0]?.content?.parts?.[0]?.text;return s?.toLowerCase()?.startsWith("yes")}catch(n){throw n}}},vp="keyring_link_preview_cache",Ap=function(){const e=/* @__PURE__ */new Map,t=ih.getItem(vp);if(!t)return e;try{const n=JSON.parse(t);if(Array.isArray(n))for(const[t,r]of n)e.set(t,r)}catch{}return e}();function kp(e){if(e)return function(e){const t={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&apos;":"'","&nbsp;":" "};return e.replace(/&(?:amp|lt|gt|quot|apos|nbsp|#39);/gi,e=>t[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(Number(t))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16)))}(e.replace(/<[^>]*>/g,"")).trim()||void 0}const xp=[e=>`https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(e)}`,e=>`https://api.allorigins.win/raw?url=${encodeURIComponent(e)}`];const Ep=({url:t})=>{const[r,s]=i(null),[a,c]=i(!0),[u,l]=i(!1);if(o(()=>{let e=!1;return async function(e){if(Ap.has(e))return Ap.get(e)??null;try{const t=await async function(e){for(const t of xp)try{const n=t(e),r=await fetch(n,{signal:AbortSignal.timeout(6e3)});if(r.ok)return await r.text()}catch{}return null}(e);if(!t)return Ap.set(e,null),null;const n=(e,t)=>{const n=[new RegExp(`<meta[^>]*property=["']${e}["'][^>]*content=["']([^"']*)["']`,"i"),new RegExp(`<meta[^>]*content=["']([^"']*)["'][^>]*property=["']${e}["']`,"i"),new RegExp(`<meta[^>]*name=["']${e}["'][^>]*content=["']([^"']*)["']`,"i"),new RegExp(`<meta[^>]*content=["']([^"']*)["'][^>]*name=["']${e}["']`,"i")];for(const r of n){const e=t.match(r);if(e?.[1])return e[1]}},r=n("og:title",t)??n("twitter:title",t)??t.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1],i=n("og:description",t)??n("twitter:description",t)??n("description",t);let o=n("og:image",t)??n("twitter:image",t);if(o&&!o.startsWith("http"))try{o=new URL(o,e).toString()}catch{}const s=n("og:site_name",t);let a;const c=t.match(/<link[^>]*rel=["'](?:shortcut )?icon["'][^>]*href=["']([^"']*)["']/i);if(c?.[1]&&(a=c[1],!a.startsWith("http")))try{a=new URL(a,e).toString()}catch{a=void 0}const u=kp(r),l=kp(i),d=kp(s);if(!u&&!l&&!o)return Ap.set(e,null),null;const f={title:u,description:l,image:o,siteName:d,url:e,favicon:a};return Ap.set(e,f),function(){const e=[...Ap.entries()].filter(([,e])=>null!==e).slice(-100);ih.setItem(vp,JSON.stringify(e))}(),f}catch{return Ap.set(e,null),null}}(t).then(t=>{e||(s(t),c(!1))}).catch(()=>{e||c(!1)}),()=>{e=!0}},[t]),a)/* @__PURE__ */
20
+ return function(t){function n(e){var t;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,n),(t=function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return E(e)}(this,A(n).call(this,e))).isEventListenerAdded=!1,t.handleOrientationChange=t.handleOrientationChange.bind(E(t)),t.onOrientationChange=t.onOrientationChange.bind(E(t)),t.onPageLoad=t.onPageLoad.bind(E(t)),t.state={isLandscape:!1,isPortrait:!1},t}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&k(e,t)}(n,t),r=n,(i=[{key:"handleOrientationChange",value:function(){this.isEventListenerAdded||(this.isEventListenerAdded=!0);var e=window.innerWidth>window.innerHeight?90:0;this.setState({isPortrait:0===e,isLandscape:90===e})}},{key:"onOrientationChange",value:function(){this.handleOrientationChange()}},{key:"onPageLoad",value:function(){this.handleOrientationChange()}},{key:"componentDidMount",value:function(){void 0!==("undefined"==typeof window?"undefined":g(window))&&Re&&(this.isEventListenerAdded?window.removeEventListener("load",this.onPageLoad,!1):(this.handleOrientationChange(),window.addEventListener("load",this.onPageLoad,!1)),window.addEventListener("resize",this.onOrientationChange,!1))}},{key:"componentWillUnmount",value:function(){window.removeEventListener("resize",this.onOrientationChange,!1)}},{key:"render",value:function(){return o.createElement(e,v({},this.props,{isLandscape:this.state.isLandscape,isPortrait:this.state.isPortrait}))}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(r.prototype,i),n;var r,i}(o.Component)},pp}();const gp="gemini-2.5-flash-lite",yp=new class extends Ph{enableGoogleSearch=!0;constructor(){super("https://nft.keyring.app")}getRuleLanguage(e){return e?`**LANGUAGE ADHERENCE**: You MUST respond ONLY in the language specified as: "${e||"the language of the user's current question"}". Ignore any language bias from context or history. If no language is explicitly provided, detect and follow the current question's language.`:'\n **LANGUAGE ADHERENCE**:\n - **DETECT** the language of the section labeled "CURRENT USER QUESTION" below.\n - **RESPOND ONLY** in that same language.\n - **IGNORE** any language bias from the context or history.\n '}async generateContent(e,t,n){try{const r=`\nBelow is the system context and conversation history. Use it for context but prioritize the instructions at the end.\n---\nSYSTEM CONTEXT & HISTORY:\n${t}\n---\n\n---\nCURRENT USER QUESTION:\n${e}\n---\n\n---\n### MANDATORY RULES:\n1. ${this.getRuleLanguage(n)}\n2. **HISTORY CLEANING**:\n - If any assistant response in the conversation history says it **"doesn't know"**, **"doesn't have data"**, **"cannot find info"**, or similar, you MUST **IGNORE that specific history segment**. \n - Do not let previous data failures prevent you from answering the CURRENT USER QUESTION if the information is available now or in your core knowledge.\n3. **BREVITY**: Keep your answer extremely concise (under 3000 characters).\n4. **DATA INTEGRITY**: Do not mention data gaps or historical missing info; just answer based on available info.\n---\n`,i="/api/gemini-cortex/proxy",o={model:gp,data:{contents:[{parts:[{text:r}]}],tools:[{googleSearch:{}}]}};this.enableGoogleSearch||delete o.data.tools;const s=await this.post(i,o);return s?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||s?.data?.candidates?.[0]?.content?.parts?.[0]?.text}catch(r){if((r?.message?.includes("search_grounding_request_per_project_per_day")||r?.data?.error?.message?.includes("search_grounding_request_per_project_per_day"))&&this.enableGoogleSearch)return this.enableGoogleSearch=!1,await this.generateContent(e,t,n);throw r}}async checkInfoQuestion(e,t){try{const r=t+`---\nCURRENT USER QUESTION:\n${e}\n---\n\nAnalyze this question and determine its category.\nIMPORTANT: The following topics should ALWAYS be classified as "yes" (crypto-related):\n- Greetings (in ANY language): hello, hi, xin chào, bonjour, etc.\n- Cryptocurrency, blockchain, crypto trading, DeFi, NFT, etc.\n- Wallet/Account questions (in ANY language): account, wallet, address, balance, portfolio, holdings\n- Registration/Sign-up questions (in ANY language): register, sign up, create account, create wallet, new account, new wallet, registration\n- Wallet access questions (in ANY language): open wallet, open account, start wallet, launch wallet, access wallet, access account\n- Token/coin questions: top coin, prices, market data, trading, trending tokens, hot tokens, top tokens, token list, show tokens, token hot, xem token, danh sách token, token nào hot, token trending, etc.\n- Chain questions: ETH, Base, Optimism, BSC, Polygon, Arbitrum, etc.\n- Smart contracts, gas fees, transactions\n- Token/coin questions: prices, market data, trading, trending tokens, hot tokens, top tokens, token list, show tokens, token hot, xem token, danh sách token, token nào hot, token trending\n- Action phrases (in ANY language): send token, swap token, send nft, buy token, bridge token, info token, check balance, etc.\n\nCRITICAL: Detect these concepts in ANY language (English, Japanese, Chinese, Vietnamese, Korean, Spanish, etc.)\nThe user may ask in their native language, so recognize the MEANING, not just specific words.\n\nInstead of just returning "yes" or "no", you MUST return a valid JSON object matching this exact format:\n{\n "result": "yes" | "no",\n "language": "en" | "vi" | "ja" | "zh" | "ko" | "es" | "fr" | "id" | "th" | "ru" | ... // etc.\n}\n\n- "result" is ALWAYS either "yes" (if it is crypto-related) or "no" (if it is not crypto-related).\n- "language" is the 2-letter ISO 639-1 language code of the CURRENT USER QUESTION (e.g. "en" for English, "vi" for Vietnamese, "ja" for Japanese, "zh" for Chinese, etc.). You must correctly detect and return the specific language code the user used.\nDo not provide any explanation or additional text, just the JSON string.`,i="/api/gemini-cortex/proxy",o={model:gp,data:{contents:[{parts:[{text:r}]}]}},s=await this.post(i,o),a=s?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||s?.data?.candidates?.[0]?.content?.parts?.[0]?.text;let c={result:"yes",language:"en"};try{let e=a?.trim()||"";e.startsWith("```json")?e=e.replace(/^```json\s*/,"").replace(/\s*```$/,""):e.startsWith("```")&&(e=e.replace(/^```\s*/,"").replace(/\s*```$/,""));const t=e.match(/\{[\s\S]*?\}/);t&&(c=JSON.parse(t[0]))}catch(n){}return c}catch(r){throw r}}async checkIsQuestionActionWeb3(e,t){try{const n=t+`---\nCURRENT USER QUESTION:\n${e}\n---\n\n #### Analyze this question and determine its category.\nIMPORTANT: The following topics should ALWAYS be classified as "yes" (action-oriented):\n- Greetings (in ANY language): hello, hi, xin chào, bonjour, etc.\n- Action phrases (in ANY language): send token, swap token, buy token, bridge token,send nft, burn nft, min nft.\n- Wallet/Account questions (in ANY language): account, wallet, address, balance, portfolio, holdings\n- Registration/Sign-up questions (in ANY language): register, sign up, create account, create wallet, new account, new wallet, registration\n- Wallet access questions (in ANY language): open wallet, open account, start wallet, launch wallet, access wallet, access account\n\nIMPORTANT: The user may ask in their native language, so recognize the MEANING, not just specific words.\n\nOtherwise, respond with ONLY the word "no" (lowercase, nothing else).\nDo not provide any explanation or additional text.`,r="/api/gemini-cortex/proxy",i={model:gp,data:{contents:[{parts:[{text:n}]}]}},o=await this.post(r,i),s=o?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||o?.data?.candidates?.[0]?.content?.parts?.[0]?.text;return s?.toLowerCase()?.startsWith("yes")}catch(n){throw n}}},vp="keyring_link_preview_cache",Ap=function(){const e=/* @__PURE__ */new Map,t=ih.getItem(vp);if(!t)return e;try{const n=JSON.parse(t);if(Array.isArray(n))for(const[t,r]of n)e.set(t,r)}catch{}return e}();function kp(e){if(e)return function(e){const t={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&apos;":"'","&nbsp;":" "};return e.replace(/&(?:amp|lt|gt|quot|apos|nbsp|#39);/gi,e=>t[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(Number(t))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16)))}(e.replace(/<[^>]*>/g,"")).trim()||void 0}const xp=[e=>`https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(e)}`,e=>`https://api.allorigins.win/raw?url=${encodeURIComponent(e)}`];const Ep=({url:t})=>{const[r,s]=i(null),[a,c]=i(!0),[u,l]=i(!1);if(o(()=>{let e=!1;return async function(e){if(Ap.has(e))return Ap.get(e)??null;try{const t=await async function(e){for(const t of xp)try{const n=t(e),r=await fetch(n,{signal:AbortSignal.timeout(6e3)});if(r.ok)return await r.text()}catch{}return null}(e);if(!t)return Ap.set(e,null),null;const n=(e,t)=>{const n=[new RegExp(`<meta[^>]*property=["']${e}["'][^>]*content=["']([^"']*)["']`,"i"),new RegExp(`<meta[^>]*content=["']([^"']*)["'][^>]*property=["']${e}["']`,"i"),new RegExp(`<meta[^>]*name=["']${e}["'][^>]*content=["']([^"']*)["']`,"i"),new RegExp(`<meta[^>]*content=["']([^"']*)["'][^>]*name=["']${e}["']`,"i")];for(const r of n){const e=t.match(r);if(e?.[1])return e[1]}},r=n("og:title",t)??n("twitter:title",t)??t.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1],i=n("og:description",t)??n("twitter:description",t)??n("description",t);let o=n("og:image",t)??n("twitter:image",t);if(o&&!o.startsWith("http"))try{o=new URL(o,e).toString()}catch{}const s=n("og:site_name",t);let a;const c=t.match(/<link[^>]*rel=["'](?:shortcut )?icon["'][^>]*href=["']([^"']*)["']/i);if(c?.[1]&&(a=c[1],!a.startsWith("http")))try{a=new URL(a,e).toString()}catch{a=void 0}const u=kp(r),l=kp(i),d=kp(s);if(!u&&!l&&!o)return Ap.set(e,null),null;const f={title:u,description:l,image:o,siteName:d,url:e,favicon:a};return Ap.set(e,f),function(){const e=[...Ap.entries()].filter(([,e])=>null!==e).slice(-100);ih.setItem(vp,JSON.stringify(e))}(),f}catch{return Ap.set(e,null),null}}(t).then(t=>{e||(s(t),c(!1))}).catch(()=>{e||c(!1)}),()=>{e=!0}},[t]),a)/* @__PURE__ */
21
21
  return e("div",{className:"link-preview link-preview--loading",children:/* @__PURE__ */e("div",{className:"link-preview__skeleton",children:/* @__PURE__ */n("div",{className:"link-preview__skeleton-text",children:[
22
22
  /* @__PURE__ */e("div",{className:"link-preview__skeleton-line link-preview__skeleton-line--title"}),
23
23
  /* @__PURE__ */e("div",{className:"link-preview__skeleton-line link-preview__skeleton-line--desc"}),
@@ -35,7 +35,7 @@ return n("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"link-p
35
35
  /* @__PURE__ */e("div",{className:`mc-heading mc-h${t}`,children:Tp(n)},`h-${o}`)),o++;continue}if(t.trimStart().startsWith("> ")){const t=[];for(;o<r.length&&r[o].trimStart().startsWith("> ");)t.push(r[o].replace(/^\s*>\s?/,"")),o++;i.push(
36
36
  /* @__PURE__ */e("div",{className:"mc-blockquote",children:t.map((t,n)=>/* @__PURE__ */e("div",{children:Tp(t)},n))},`bq-${o}`));continue}""!==t?.trim()?(i.push(
37
37
  /* @__PURE__ */e("div",{className:"mc-line",children:Tp(t)},`line-${o}`)),o++):(i.push(/* @__PURE__ */e("div",{className:"mc-empty-line"},`empty-${o}`)),o++)}const s=function(e){const t=e.match(/https?:\/\/[^\s<>)\]]+/g);return t?[...new Set(t)]:[]}(t).slice(0,3);/* @__PURE__ */
38
- return n("div",{className:"message-content",children:[i,s.length>0&&/* @__PURE__ */e("div",{className:"mc-link-previews",children:s.map(t=>/* @__PURE__ */e(Ep,{url:t},t))})]})},Ip="https://nft-demo.keyring.app";function Sp(e){const t=e.indexOf("{");if(-1===t)return e;let n=0,r=!1,i=!1;for(let o=t;o<e.length;o++){const s=e[o];if(i)i=!1;else if("\\"===s&&r)i=!0;else if('"'!==s){if(!r)if("{"===s)n++;else if("}"===s&&(n--,0===n))return e.slice(t,o+1)}else r=!r}return e}function Np(e,t,n){if(!e)return e;const r=e.toLowerCase().trim();if("max"===r||"all"===r)return t||e;const i=r.match(/^(\d+(?:\.\d+)?)%$/);if(i){const e=parseFloat(i[1])/100;return((parseFloat(t)||0)*e).toFixed(8).replace(/\.?0+$/,"")||"0"}const o=r.match(/^\$?(\d+(?:\.\d+)?)\$?$/),s=r.startsWith("$")||r.endsWith("$")||/\d(usd|dollar|dollars|đô|đồng)$/.test(r);if(o&&s){const t=parseFloat(o[1]);return n&&n>0?(t/n).toFixed(8).replace(/\.?0+$/,"")||"0":e}const a=r.match(/^(\d+(?:\.\d+)?)\s*(?:usd|dollar|dollars|đô|đồng)$/);if(a){const t=parseFloat(a[1]);return n&&n>0?(t/n).toFixed(8).replace(/\.?0+$/,"")||"0":e}return e}const Bp=({isOpen:r,onClose:a,onTransaction:u,position:f="bottom-right",modalChatStyle:h={}})=>{const{t:p,ti:m}=w(),{messages:b,addMessage:g,updateMessageAction:y,updateMessageActionParameters:v,updateMessageText:A,clearMessagesById:k,updateMessageType:x}=function(){const{account:e}=ah(),{t:t}=w(),n=(r=e?.address,a=e?.chainId,r&&a?`${r}_${a}`:"");var r,a;const c=l(()=>hh(t("welcomeMessage")),[t]),[u,d]=i(()=>n||"pending"),[f,h]=i(()=>{const e=mh();return n?e&&e.owner===n?e.messages:hh(t("welcomeMessage")):e?.messages??hh(t("welcomeMessage"))});if("pending"===u&&n){const e=mh();e&&e.owner===n?h(e.messages):wh(n,f),d(n)}else"pending"!==u&&n&&u!==n&&(h(c),wh(n,c),d(n));const p=l(()=>f.map(e=>e.id===fh?{...e,text:t("welcomeMessage")}:e),[f,t]);o(()=>{"pending"!==u&&wh(u,f)},[f,u]),o(()=>{const e=[];for(let t=0;t<ih.length;t++){const n=ih.key(t);n&&n.startsWith(lh+"_")&&e.push(n)}e.forEach(e=>ih.removeItem(e))},[]);const m=s(()=>{h(c),wh(n,c)},[n,c]),b=s(e=>{h(t=>{const n=t.filter(t=>!e.includes(t.id));return n.length>dh?n.slice(n.length-dh):n})},[]);return{messages:p,setMessages:h,addMessage:(e,t,n,r,i,o="web3")=>{const s=n?f.find(e=>e.id===n):void 0,a={id:Math.random().toString(36).substring(2,12),text:e,sender:t,timestamp:/* @__PURE__ */new Date,typeChat:o,...s&&{replyTo:{id:s.id,text:s.text,sender:s.sender}},...r&&{buttons:r},...i&&{actionData:i}};return h(e=>{const t=[...e,a];return t.length>dh?t.slice(t.length-dh):t}),a},updateMessageAction:(e,t)=>{h(n=>n.map(n=>n.id===e&&n.actionData?{...n,actionData:{...n.actionData,status:t}}:n))},updateMessageActionParameters:(e,t)=>{h(n=>n.map(n=>n.id===e&&n.actionData?{...n,actionData:{...n.actionData,parameters:{...n.actionData.parameters,...t}}}:n))},updateMessageText:(e,t)=>{h(n=>n.map(n=>n.id===e?{...n,text:t}:n))},getMessageById:e=>f.find(t=>t.id===e),clearMessages:m,clearMessagesById:b,updateMessageType:(e,t)=>{h(n=>n.map(n=>n.id===e?{...n,typeChat:t}:n))}}}(),[E,T]=i(""),[C,I]=i(!1),[S,N]=i(!0),[B,M]=i(null),U=d(null),R=d(null),O=d(null),F=d(null),L=d(null),D=d(!1),P=d(S);o(()=>{P.current=S},[S]);const{account:H,chainData:j,chainType:z,chainTypeMoralis:J,chainId:q,isChainSupported:V}=ah(),{config:Y}=(()=>{const e=c(bh);if(!e)throw new Error("useConfig must be used within ConfigProvider");return e})(),G=q&&Y?.rpcUrls?.[q]||void 0,W=s(()=>{const e=ih.getItem("dataBuyToken");if(e)try{return JSON.parse(e)}catch{return{srcTokenAddress:"",descTokenAddress:"",amount:"",srcTokenDecimals:18,descTokenDecimals:18}}return{srcTokenAddress:"",descTokenAddress:"",amount:"",srcTokenDecimals:18,descTokenDecimals:18}},[]),X=s(e=>{ih.setItem("dataBuyToken",JSON.stringify(e))},[]),K=s(e=>{const t={...W(),...e};X(t)},[W,X]),Q=s(e=>{M(e),bp.isDesktop&&O.current?.focus()},[]),Z=s(async(e,t)=>{K({descTokenAddress:e,descTokenDecimals:t||18});try{I(!0);const e=await qh({address:H?.address||"",chain:J});if(e?.success&&e?.data?.result){const t=e.data.result;if(t?.length>0){const e=t.map(e=>({id:e.token_address,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${Dh(e.usd_value||0)?.decimalPlaces(2).toFormat()||"0"})`,value:m("buttonBuyWith",{symbol:e.symbol}),action:"click_balance_item_user_to_buy_button",fullWidth:!0,extraData:{tokenAddress:e.token_address,symbol:e.symbol,balance:e.balance_formatted,usdValue:e.usd_value,decimals:e.decimals}}));g(m("walletBalanceSpendable",{chain:j?.name||"unknown"}),"bot",void 0,e)}else g(m("walletNoTokensFound",{chain:j?.name||"unknown"}),"bot")}else g(p("walletFetchFailed"),"bot")}catch(n){g(p("walletFetchError"),"bot")}finally{I(!1)}},[K,H?.address,J,g,j?.name,p,m]),_=s(async(e,t,n,r)=>{K({srcTokenAddress:e,srcTokenDecimals:r||18});let i=n||"0";if(e===xn)try{const e=await dp({chainId:q,rpcUrl:G});if(e.isGreaterThan(0)){const t=e.times(1e6),o=new Dh(kn(n,r||18).toString()).minus(t);i=o.isGreaterThan(0)?Dh(pt(BigInt(o.toFixed(0)),18)).toFixed():"0"}}catch(s){}const o=[25,50,75,100].map(n=>({id:`percent-${n}`,text:`${n}%`,value:m("buttonUsePercent",{percent:String(n),symbol:t}),action:"select_percent",extraData:{percent:n,tokenAddress:e,tokenSymbol:t,tokenDecimals:r||18,tokenBalance:i}}));Dh(i).isZero()?g(m("insufficientFeeToken",{symbol:t}),"bot"):g(m("selectAmountOf",{symbol:t,balance:i}),"bot",void 0,o)},[g,q,G,K,m]),$=s(async(e,t,n,r)=>{const i={amount:Dh(t).times(e).dividedBy(100).toFixed()};void 0!==n&&(i.srcTokenAddress=n),void 0!==r&&(i.srcTokenDecimals=r),K(i);const o=W(),s=kn(o.amount,o.srcTokenDecimals||18).toString(),a=await Xh({chainId:q,tokenIn:o.srcTokenAddress,tokenInAmount:s,tokenOut:o.descTokenAddress,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(a.success&&a.data){const e=a.data,t=e.tokenIn,n=e.tokenOut,r=Dh(pt(BigInt(t.amount||0),t.decimals)).decimalPlaces(8).toFormat(),i=Dh(pt(BigInt(n.amount||0),n.decimals)).decimalPlaces(8).toFormat();let u=!1;if(o.srcTokenAddress!==xn&&""!==o.srcTokenAddress&&H?.address&&e.tx?.to)try{const t=await ap({tokenAddress:o.srcTokenAddress,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:q,rpcUrl:G});u=Dh(t.toString()).isLessThan(s)}catch(c){u=!0}const l=e.estimatedTransactionFee?.total?Dh(e.estimatedTransactionFee.total):Dh(0);let d=Dh(0);if(u&&H?.address)try{const t=cp({tokenAddress:o.srcTokenAddress,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:q,amount:s});d=await lp({from:H.address,to:t.to,data:t.data,chainId:q,rpcUrl:G})}catch(c){}const f=l.plus(d),h=j?.nativeCurrency?.symbol||"native";let w="",b=!1;if(H?.address&&f.isGreaterThan(0))try{const e=await up({address:H.address,chainId:q,rpcUrl:G});if(e.isLessThan(f)){b=!0;const t=Dh(pt(BigInt(e.toFixed(0)),18)).decimalPlaces(8).toFormat(),n=Dh(pt(BigInt(f.toFixed(0)),18)).decimalPlaces(8).toFormat();w=m("swapFeeWarning",{symbol:h,balance:t,needed:n})}}catch(c){}const y=`From: ${r} ${t.symbol}\n⬇️\nTo: ${i} ${n.symbol}\n\n`+w+"\n";if(b)g(y,"bot");else if(u){const n=y+m("swapNeedApprove",{symbol:t.symbol}),r=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:t.symbol}),value:m("swapApproveValue",{symbol:t.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:o.srcTokenAddress,spenderAddress:e.tx.to,tokenSymbol:t.symbol,amountInWei:s,tx:e.tx}}];g(n,"bot",void 0,r)}else{const t=[{id:"confirm-swap",text:p("swapConfirmButton"),value:p("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(y+p("swapReadyToProceed"),"bot",void 0,t)}}else g(m("swapEstimationError",{error:a.errorMessage||a.error||"Unknown error"}),"bot")},[W,K,g,q,H?.address,j?.nativeCurrency?.symbol,G,p,m]),ee=s(async(e,t,n)=>{try{if("suggested_action"===t)return F.current=e,void T(e);if(g(e,"user"),N(!1),I(!0),t)switch(await eh(500),t){case"click_buy_item_token_button":await Z(n?.tokenAddress||"",n?.decimals||18);break;case"click_balance_item_user_to_buy_button":await _(n?.tokenAddress||"",n?.symbol||"",n?.balance||"",n?.decimals||18);break;case"select_percent":await $(n?.percent||0,n?.tokenBalance||"",n?.tokenAddress||void 0,n?.tokenDecimals||void 0);break;case"confirm_swap":if(n?.tx&&u){const e=n.tx,t={from:H?.address||"",to:e.to,data:e.data,value:e.value,chainId:q},o=g(p("txProcessing"),"bot");try{I(!1);const e=await u(t);if("success"===e.status&&e.transactionHash){const t=j?.blockExplorers?.default?.url,n=t?` [View on Explorer](${t}/tx/${e.transactionHash})`:` Tx: ${e.transactionHash}`;A(o.id,p("txSubmitted")+n);try{await eh(2e3),"success"===(await sp({transactionHash:e.transactionHash,chainId:q||1,rpcUrl:G})).status?A(o.id,p("txConfirmedSwap")+n):A(o.id,p("txRevertedSwap")+n)}catch(r){A(o.id,p("txTimeout")+n)}}else if("success"===e.status)A(o.id,p("txSuccessfulSwap"));else{const t=e.error?`\nError: ${e.error}`:"";A(o.id,p("txFailed")+t)}}catch(i){A(o.id,p("txFailed"))}}else g(p("txDataNotAvailable"),"bot");break;case"approve_for_swap":{const e=n?.tokenAddress||"",t=n?.spenderAddress||"",o=n?.tokenSymbol||"token",s=n?.tx;if(!e||!t||!u){g(p("approvalDataNotAvailable"),"bot");break}const a=n?.amountInWei||void 0,c=cp({tokenAddress:e,spenderAddress:t,fromAddress:H?.address||"",chainId:q,tokenSymbol:o,amount:a}),l={from:c.from,to:c.to,data:c.data,value:c.value,chainId:c.chainId};g(m("approving",{symbol:o}),"bot");try{I(!1);const e=await u(l);let t="success"===e.status;if("success"===e.status&&e.transactionHash)try{t="success"===(await sp({transactionHash:e.transactionHash,chainId:q||1,rpcUrl:G})).status}catch(r){t=!0}if(t){g(m("approvalSuccess",{symbol:o}),"bot");const e=[{id:"confirm-swap-after-approve",text:p("confirmSwapButton"),value:p("swapConfirmValue"),action:"confirm_swap",fullWidth:!0,extraData:{tx:s}}];g(p("approvalConfirmSwap"),"bot",void 0,e)}else{const t=e.error?`\nError: ${e.error}`:"";g(p("approvalFailed")+t,"bot")}}catch(i){g(p("approvalFailed"),"bot")}break}case"click_swap_dest_token":{const e=n?.tokenAddress||"",t=n?.symbol||"";K({descTokenAddress:e,descTokenDecimals:n?.decimals||18});const r=W(),i=r.srcTokenAddress||"",a=i===xn,c=r.amount||"";try{const n=await qh({address:H?.address||"",chain:J});if(n?.success&&n?.data?.result){const s=n.data.result;let u,l="",d="0";if(a){const e=s.find(e=>e.native_token);l=j?.nativeCurrency?.symbol||"ETH",d=e?.balance_formatted||"0",u=e?.usd_price}else{const e=s.find(e=>e.token_address.toLowerCase()===i.toLowerCase());e&&(l=e.symbol,d=e.balance_formatted,u=e.usd_price)}if(c&&l){const t=Np(c,d,u),n=r.srcTokenDecimals||18,s=a?xn:i;K({amount:t});try{const r=kn(t,n).toString(),i=await Xh({chainId:q,tokenIn:s,tokenInAmount:r,tokenOut:e,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(i.success&&i.data){const e=i.data,t=e.tokenIn,n=e.tokenOut,o=Dh(pt(BigInt(t.amount||0),t.decimals)).decimalPlaces(8).toFormat(),c=Dh(pt(BigInt(n.amount||0),n.decimals)).decimalPlaces(8).toFormat();let u=!1;if(!a&&H?.address&&e.tx?.to)try{const t=await ap({tokenAddress:s,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:q,rpcUrl:G});u=Dh(t.toString()).isLessThan(r)}catch{u=!0}const l=e.estimatedTransactionFee?.total?Dh(e.estimatedTransactionFee.total):Dh(0);let d=Dh(0);if(u&&H?.address)try{const t=cp({tokenAddress:s,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:q,amount:r});d=await lp({from:H.address,to:t.to,data:t.data,chainId:q,rpcUrl:G})}catch{}const f=l.plus(d),h=j?.nativeCurrency?.symbol||"native";let w="",b=!1;if(H?.address&&f.isGreaterThan(0))try{const e=await up({address:H.address,chainId:q,rpcUrl:G});if(e.isLessThan(f)){b=!0;const t=Dh(pt(BigInt(e.toFixed(0)),18)).decimalPlaces(8).toFormat(),n=Dh(pt(BigInt(f.toFixed(0)),18)).decimalPlaces(8).toFormat();w=m("swapFeeWarning",{symbol:h,balance:t,needed:n})}}catch{}const y=`From: ${o} ${t.symbol}\n⬇️\nTo: ${c} ${n.symbol}\n\n`+w+"\n";if(b)g(y,"bot");else if(u){const n=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:t.symbol}),value:m("swapApproveValue",{symbol:t.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:s,spenderAddress:e.tx.to,tokenSymbol:t.symbol,amountInWei:r,tx:e.tx}}];g(y+m("swapNeedApprove",{symbol:t.symbol}),"bot",void 0,n)}else{const t=[{id:"confirm-swap",text:p("swapConfirmYes"),value:p("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(y+p("swapReadyToProceed"),"bot",void 0,t)}}else g(m("swapEstimationError",{error:i.errorMessage||i.error||"Unknown error"}),"bot")}catch(o){g(p("swapEstimationFailed"),"bot")}}else if(l&&parseFloat(d)>0){const e=[25,50,75,100],n=r.srcTokenDecimals||18,o=e.map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:l}),action:"select_percent",extraData:{percent:e,tokenAddress:i,tokenSymbol:l,tokenDecimals:n,tokenBalance:d}}));g(m("swapSelectAmount",{from:l,to:t,balance:d}),"bot",void 0,o)}else g(p("swapNoSourceToken"),"bot")}else g(p("couldNotFetchBalance"),"bot")}catch(s){g(p("couldNotLoadBalance"),"bot")}break}case"select_nft_to_send":{const e=n?.name||"NFT",t=n?.contractAddress||"",r=n?.tokenId||"",i=n?.tokenStandard||"ERC721",o=n?.amount||"1",s=n?.image||"",a={contract_address:t,token_id:r,to_address:n?.toAddress||"",token_standard:i,amount:o,maxAmount:o,nft_name:e};g(m("nftSendReview",{name:e,standard:i,tokenId:r}),"bot",void 0,void 0,{action:"send_nft",parameters:a,status:"pending",nftInfo:{name:e,image:s||void 0,tokenId:r,contractAddress:t,tokenStandard:i}});break}default:g(m("actionExecutedFor",{action:t,value:e}),"bot")}else await eh(500),g(m("receivedButtonValue",{value:e}),"bot");I(!1),bp.isDesktop&&O.current?.focus()}catch(i){g(p("errorProcessingRequest"),"bot"),I(!1)}},[H?.address,g,A,j?.blockExplorers?.default?.url,j?.nativeCurrency?.symbol,q,J,W,Z,_,u,$,K,G,p,m]),te=s(async()=>{try{I(!0);const e=j?.tokenTrendingDefault||[],[t,n]=await Promise.allSettled([Gh.getTopGainers(z,"24h",5),Gh.getTokensDetails(e,z)]);let r=[];"fulfilled"===t.status&&t.value?.data&&(r=[...t.value.data]),"fulfilled"===n.status&&n.value?.data&&(r=[...n.value.data,...r]),r=r.filter((e,t,n)=>t===n.findIndex(t=>t.address.toLowerCase()===e.address.toLowerCase()));const i=r.map(e=>({id:e?.symbol,text:e?.symbol,value:m("buttonBuyToken",{name:e.name,symbol:e?.symbol||""}),action:"click_buy_item_token_button",extraData:{tokenAddress:e?.address||"",symbol:e?.symbol||"",decimals:e?.decimals||18}}));await eh(1e3),I(!1),g(m("trendingTokensHeader",{chain:j?.name||"Unknown"}),"bot");const o=r.map((e,t)=>`${t+1}. ${e.name} (${e?.auditGoplus?.token_symbol||e.symbol||"Unknown"})\n$${Dh(e?.price||0).decimalPlaces(4).toFormat()} (${e.price_change_percentage_24h||e.priceChange}%)\n\n---\n`).join("\n");g(`${o}${p("trendingTokensQuestion")}`,"bot",void 0,i)}catch(e){g(p("trendingTokensError"),"bot")}finally{I(!1)}},[g,j?.name,j?.tokenTrendingDefault,z,p,m]),ne=s(async()=>{try{g(m("viewNftViaWebsite",{link:Ip}),"bot"),I(!1)}catch(e){I(!1),g(p("nftFetchError"),"bot")}},[g,p,m]),re=s(async()=>{try{I(!0);const e=await qh({address:H?.address||"",chain:J});if(e?.success&&e?.data?.result&&e.data.result.length>0){const t=e.data.result.map((e,t)=>{const n=void 0!==e.usd_value?` ≈ $${Dh(e.usd_value).decimalPlaces(2).toFormat()}`:"";return`${t+1}. **${e.name}** (${e.symbol})\n Balance: ${e.balance_formatted}${n}`}).join("\n\n");await eh(500),I(!1),g(m("viewBalancesHeader",{chain:j?.name||"this chain",list:t}),"bot",void 0)}else I(!1),g(p("viewBalancesEmpty"),"bot")}catch(e){I(!1),g(p("viewBalancesFetchError"),"bot")}},[H?.address,J,g,j?.name,p,m]),ie=l(()=>[{id:"ask",icon:"❓",text:p("suggestionAskText"),action:async()=>{N(!1),I(!0),g(p("suggestionAskUserMessage"),"user"),await eh(1e3),I(!1),g(p("suggestionAskBotReply"),"bot")}},{id:"buy",icon:"💰",text:p("suggestionBuyText"),action:async()=>{N(!1),g(p("suggestionBuyText"),"user"),Ye(H?.address||"")&&V?await te():(I(!0),await eh(1e3),Ye(H?.address||"")&&!V?g(p("walletConnectedChainUnsupported"),"bot"):g(p("walletNotConnected"),"bot"),I(!1))}}],[g,H?.address,te,p,V]),oe=e=>{if(0===e)return!0;const t=b[e],n=b[e-1],r=new Date(t.timestamp),i=new Date(n.timestamp);return r.setHours(0,0,0,0),i.setHours(0,0,0,0),r.getTime()!==i.getTime()};o(()=>{U.current?.scrollIntoView({behavior:"smooth"})},[b]),o(()=>{r?(O.current&&bp.isDesktop&&O.current.focus(),U.current?.scrollIntoView({behavior:"instant"}),D.current&&L.current?Date.now()-L.current>12e5&&N(!0):N(!0),L.current=null,D.current=!1,setTimeout(()=>{U.current?.scrollIntoView({behavior:"smooth"})},50)):(L.current=Date.now(),D.current=!P.current)},[r]),o(()=>{const e=e=>{"Escape"===e.key&&r&&a()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r,a]);const se=s(async()=>{if(""===E?.trim()||C)return;const e=B,t=g(E?.trim(),"user",B?.id);T(""),M(null),I(!0),N(!1),I(!0);try{let d,f;const h=b.slice(-10);let w="",y="";if(h.length>0){w="\n\n## CONVERSATION HISTORY:\n";for(const e of h)"user"===e.sender?w+=`User: ${e.text}\n`:w+=`Assistant: ${e.text.length>400?e.text.substring(0,400)+"...":e.text}\n`;w+="\n---\n"}let v=E?.trim();e&&(v=`[Replying to ${"user"===e.sender?"my previous":"your"} message: "${e.text}"]\n\n${v}`);try{const e=await yp.checkInfoQuestion(v,w),n=e?.result?.includes("no");if(e?.language&&(y=e?.language),n){x(t.id,"normal");const e=b.filter(e=>"normal"===e.typeChat);let n="";if(e.slice(-20).length>0){n="\n\n## CONVERSATION HISTORY:\n";for(const t of e.slice(-20))"normal"===t.typeChat&&("user"===t.sender?n+=`User: ${t.text}\n`:n+=`Assistant: ${t.text.length>400?t.text.substring(0,400)+"...":t.text}\n\n`)}const r=await yp.generateContent(v,n,y);let i=null;try{let e=r?.trim();e.startsWith("```json")?e=e.replace(/^```json\s*/,"").replace(/\s*```$/,""):e.startsWith("```")&&(e=e.replace(/^```\s*/,"").replace(/\s*```$/,"")),i=JSON.parse(Sp(e))}catch{i=null}return I(!1),void g(i?.message||r,"bot",void 0,void 0,void 0,"normal")}}catch(r){}if(H?.address&&V)try{const[e,t]=await Promise.allSettled([qh({address:H.address,chain:J}),Yh({address:H.address,chain:J,limit:100,exclude_spam:!0})]);"fulfilled"===e.status&&e.value?.success&&e.value?.data?.result&&(d=e.value.data.result.map(e=>({symbol:e.symbol,name:e.name,balance_formatted:e.balance_formatted,usd_value:e.usd_value,native_token:e.native_token,token_address:e.token_address,price:e.usd_price}))),"fulfilled"===t.status&&t.value?.success&&t.value?.data?.result&&(f=t.value.data.result.map(e=>({name:e.normalized_metadata?.name||e.name||`#${e.token_id}`,token_address:e.token_address,token_id:e.token_id,contract_type:e.contract_type||"",amount:e.amount||"1"})))}catch{}const A=function(e){const{walletAddress:t,chainName:n,chainId:r,nativeSymbol:i,walletTokens:o,walletNfts:s,language:a}=e;if(!t)return`You are a Web3 wallet assistant for the Keyring crypto EVM wallet app.\nThe user is currently NOT connected to any wallet.\n\n## YOUR ROLE:\n- You are a friendly, knowledgeable assistant that can talk about ANY topic naturally\n- You can freely answer general questions, discuss crypto tokens, prices, market info, provide token details, etc. — these do NOT require a wallet connection\n- ONLY ask the user to connect their wallet when their request explicitly requires their personal wallet/address, such as:\n - Sending tokens or NFTs\n - Swapping tokens\n - Approving token spending\n - Wrapping/unwrapping tokens\n - Checking THEIR OWN balance ("what is MY balance?", "how much ETH do I have?")\n - Viewing THEIR OWN NFT collection\n - Any action that reads or writes to THEIR wallet address\n- For all other requests (token info, prices, general crypto questions, market data, etc.), respond normally and helpfully\n- ${$h(a)}\n- **LANGUAGE DETECTION — CRYPTO TICKERS**: Crypto token symbols and tickers (ETH, BTC, USDC, BNB, MATIC, SOL, etc.) are NOT language indicators. They are proper nouns used in ALL languages. Detect the language from the surrounding non-ticker text only. Example: "ETHの現在の価格は?" → Japanese (the surrounding text は Japanese characters). "ETH의 가격은?" → Korean. "Giá ETH là bao nhiêu?" → Vietnamese. NEVER treat a ticker symbol as evidence of English.\n\n## RESPONSE FORMAT:\nAlways respond with a valid JSON object:\n{"action":"chat","message":"<your friendly response to the user>", "suggested_actions":[{"label":"<short button text>","prompt":"<message sent when clicked>"}]}\n\n## RULES:\n- suggested_actions: include when your message offers the user interactive choices or asks a follow-up question. NEVER include suggested_actions that ask the user to connect their wallet (e.g., "Connect wallet", "Connect now", etc.) — the app handles wallet connection separately\n- **CRITICAL**: NEVER include any "Buy" actions (e.g., "Buy USDC", "Buy ETH", "Purchase token", etc.) in suggested_actions. The app handles Buy buttons separately. Only include non-buy actions in suggested_actions (e.g., "Send token", "Swap token", "Check balance", "Show my NFTs").\n- For wallet-required actions, politely explain the user needs to connect their wallet first, and put this in the "message" field\n- ALWAYS respond with raw JSON only, never wrap in \`\`\`json code blocks\n- ${$h(a)}`;if(t&&!Fn[r]?.isSupported)return`You are a Web3 wallet assistant for the Keyring crypto EVM wallet app.\n The user's wallet address is: ${t}\n The user is selected on (chainId: ${r}) an UNSUPPORTED chain.\n\n ## YOUR ROLE:\n - You are a friendly, knowledgeable assistant that can talk about ANY topic naturally\n - You can freely answer general questions, discuss crypto tokens, prices, market info, token details, etc. — these do NOT require a supported chain\n - **BLOCKED on unsupported chain** — if the user asks for any of the following, politely inform them that chain (chainId: ${r}) is not currently supported and the action cannot be performed:\n - Checking THEIR OWN balance ("what is my balance?", "how much ETH do I have?")\n - Sending tokens or NFTs\n - Swapping or buying tokens\n - Approving token spending\n - Wrapping/unwrapping tokens\n - Viewing or transferring their NFT collection\n - Any action that reads or writes to their wallet on the current chain\n - **ALLOWED on unsupported chain** — respond normally and helpfully for:\n - General questions (weather, coding, history, math, etc.)\n - Token information, prices, market data, token details\n - Any query that does NOT require interacting with the user's wallet on the current chain\n - ${$h(a)}\n - **LANGUAGE DETECTION — CRYPTO TICKERS**: Crypto token symbols and tickers (ETH, BTC, USDC, BNB, MATIC, SOL, etc.) are NOT language indicators. They are proper nouns used in ALL languages. Detect the language from the surrounding non-ticker text only. Example: "ETHの現在の価格は?" → Japanese. "ETH의 가격은?" → Korean. "Giá ETH là bao nhiêu?" → Vietnamese. NEVER treat a ticker symbol as evidence of English.\n\n ## RESPONSE FORMAT:\n Always respond with a valid JSON object:\n {"action":"chat","message":"<your response>", suggested_actions:[{"label":"<short button text>","prompt":"<message sent when clicked>"}]}\n\n ## RULES:\n - suggested_actions: include when your message offers the user interactive choices or asks a follow-up question. NEVER include suggested_actions that ask the user to connect their wallet (e.g., "Connect wallet", "Connect now", etc.) — the app handles wallet connection separately\n - **CRITICAL**: NEVER include any "Buy" actions (e.g., "Buy USDC", "Buy ETH", "Purchase token", etc.) in suggested_actions. The app handles Buy buttons separately. Only include non-buy actions in suggested_actions (e.g., "Send token", "Swap token", "Check balance", "Show my NFTs").\n - **CRITICAL**: ABSOLUTELY NEVER include any option that suggests switching, changing, or selecting a different chain (e.g., "Switch to Ethereum", "Change chain", "Switch network", "Chuyển sang chain khác", "Đổi mạng") — the app handles chain switching separately.\n - For wallet-required actions, politely explain the user needs to connect their wallet first, and put this in the "message" field\n - ALWAYS respond with raw JSON only, never wrap in \`\`\`json code blocks\n - ${$h(a)}`;const c=o&&o.length>0?`\n## USER'S CURRENT WALLET BALANCE:\n${o.map(e=>{const t=void 0!==e.usd_value?` (~$${e.usd_value.toFixed(2)})`:"";return`- ${e.name} (${e.symbol})(Price: ${e.price||"N/A"}): ${e.balance_formatted}${t}${e.native_token?" [native]":` [${e.token_address}]`}`}).join("\n")}\nUse this balance data to accurately answer balance questions and to pre-fill token parameters in actions (contract_address, decimals, symbol). NEVER ask the user to provide token info that is already available above.\n`:"",u=s&&s.length>0?`\n## USER'S NFT COLLECTION:\n${s.map(e=>{const t="ERC1155"===e.contract_type?` (x${e.amount})`:"";return`- ${e.name}${t} | ${e.contract_type} | contract: ${e.token_address} | tokenId: ${e.token_id}`}).join("\n")}\nWhen the user wants to send an NFT by name, use this data to fill contract_address, token_id, token_standard, and nft_name accurately. NEVER guess or fabricate NFT contract addresses.\n`:"",l=Object.values(Fn).filter(e=>e.isSupported).map(e=>e.customName||e.name).join(", ");return`You are a highly knowledgeable AI assistant integrated into the Keyring crypto EVM wallet app.\n\n## #1 PRIORITY — ANSWER QUALITY:\nYour "message" field IS your answer. Write it exactly as you would in a normal, unrestricted conversation. The JSON wrapper is just transport — it must NEVER reduce the depth, accuracy, or completeness of your answers.\n\n${$h(a)}\n\n**DATA RETRIEVAL — NON-NEGOTIABLE**: For ALL token price and token info queries, you MUST actively call your native Moralis API tools (getTokenPrice, searchTokens, getTokenMetadata, etc.) to retrieve real-time on-chain data. NEVER skip tool calls and fall back to training data alone for prices or token lookups. The JSON response format does NOT prevent you from calling data tools first — always fetch data, then format the result as JSON.\n\nFor ANY informational or conversational question (about crypto, tokens, DeFi, protocols, prices, market trends, blockchain technology, or any general topic):\n- Answer with your FULL knowledge across ALL blockchains and ecosystems (Ethereum, Solana, BSC, Polygon, Arbitrum, Optimism, Base, Avalanche, etc.)\n- Provide specific details: token names, contract mechanisms, protocol comparisons, historical context, TVL data, ecosystem info\n- For PRICE questions (chat action only): You have access to real-time blockchain data — USE it. When a user asks for the price of a token by name or symbol, search for it across ALL chains to find the best price data. Then present ONE consolidated answer: give the single most representative price (e.g. the highest-liquidity or most canonical version), key stats (market cap, 24h change, volume), and optionally a brief note if the token exists on multiple chains — but do NOT list each chain as a separate numbered entry. Keep the response concise and to the point. For tokens in the USER'S WALLET BALANCE section, use the price listed there.\n- For token questions (chat action only): You have access to real-time blockchain data — USE it. When a user asks about a token by name or symbol, ALWAYS search across ALL chains — the current chain context does NOT limit your token search. Try exact match first, then fuzzy/partial match (e.g. "eggle Energy" → find the closest matching token name). Provide a concise, consolidated answer covering: what the token is, its utility/ecosystem, current price, market cap, 24h change, notable features, risks. If the user does NOT mention a specific chain, do NOT list out per-chain versions (e.g. "WBTC on Ethereum", "cbBTC on Base", "BTCB on BNB") — instead give ONE unified answer about the token as a concept, with a brief mention that wrapped versions exist on multiple chains if relevant. Only break down per-chain details if the user explicitly asks about a specific chain. If the token does NOT exist on the current chain (${n}), proactively tell the user which of these supported chains DO have it: ${l}. Set token_mentions to [] in this case\n- For DeFi/protocol questions: explain how it works, key features, TVL, supported chains, competitors, pros/cons\n- For market/trend questions: discuss relevant projects, narratives, sector analysis across all chains\n- Write detailed paragraphs, use bullet points, include numbers and facts. Minimum 3-5 sentences for simple questions, more for complex topics\n\n## CONTEXT:\nWallet: ${t} | Chain: ${n} (chainId: ${r}) | Native: ${i}${c}${u}\n\n## WHEN TO USE WHICH ACTION:\n- "send_native": user wants to send the native token (${i}) to an address\n- "send_token": user wants to send an ERC20 token to an address\n- "swap_token": user wants to swap/exchange/convert/trade/sell one token for another — covers ALL of the following keywords and patterns, even if only ONE token or NO amount is mentioned:\n - swap: "swap X", "swap X to Y", "swap X for Y", "swap to ETH", "swap native"\n - exchange: "exchange X", "exchange X to Y", "exchange X for Y", "exchange native", "exchange ETH"\n - convert: "convert X to Y", "convert native", "convert ETH to USDC", "convert X"\n - trade: "trade X for Y", "trade X to Y", "trade X"\n - sell (for another token): "sell X for Y", "sell ETH for USDC"\n - Vietnamese: "đổi X sang Y", "đổi X", "đổi native", "đổi ETH sang USDC", "chuyển đổi X", "bán X lấy Y", "hoán đổi X"\n - **CRITICAL**: When the source is the native token (ETH, BNB, MATIC, etc.) → token_in: "native". This MUST be treated as swap_token, never chat.\n → ALWAYS return swap_token. Leave missing params as "". NEVER fall back to chat.\n- "buy_token": user wants to buy a specific token AND the user clearly names a token (symbol or contract address). If user also specifies which token to pay with (e.g. "buy PEPE with USDC", "mua PEPE bằng ETH", "buy PEPE using my USDC"), fill pay_with_symbol and pay_with_address from USER'S WALLET BALANCE. **CRITICAL**: ALWAYS return buy_token if the user clearly names a token they want to buy — even if you cannot find the contract address or token data. Leave contract_address as "" and the app will search for it. NEVER fall back to "chat" just because you lack token data.\n- "buy_token_trending": user wants to buy a token BUT does NOT specify which token — covers ALL of the following patterns:\n - User asks to buy trending tokens: "buy trending tokens", "buy trending", "mua token trending", "mua token đang trending"\n - User asks to buy tokens with strong growth/momentum: "buy tokens pumping", "buy hot tokens", "buy movers", "mua token tăng mạnh", "mua token đang tăng", "mua token tiềm năng"\n - User says "buy a token" / "I want to buy" / "mua token" with NO specific token name or address provided\n - User asks for token recommendations to buy without specifying one\n → ALWAYS return buy_token_trending. Leave all params as "". NEVER fall back to chat or buy_token.\n- "approve_token": user wants to approve a token for a spender\n- "wrap_native": user wants to wrap native token (e.g. ETH → WETH) — also triggered by "deposit" into WETH/wrapped token\n- "unwrap_native": user wants to unwrap (e.g. WETH → ETH) — also triggered by "withdraw" from WETH/wrapped token\n- "send_nft": user wants to send/transfer an NFT\n- "view_nfts": user wants to see/browse their NFT collection\n- "view_balances": user wants to see ALL their token balances/tokens at once — covers ALL of the following patterns (NOT for single token price/info):\n - "show my balance", "view my balance", "check my balance", "what's my balance"\n - "what's in my wallet", "what do I have", "what tokens do I have"\n - "view all tokens", "show all tokens", "list my tokens"\n - "my portfolio", "show portfolio", "wallet overview"\n - Vietnamese: "xem số dư", "số dư của tôi", "kiểm tra số dư", "ví tôi có gì", "tôi có bao nhiêu tiền", "xem ví", "danh mục của tôi"\n → ALWAYS return view_balances for these. Do NOT return chat.\n- "chat": EVERYTHING ELSE — questions, token info, prices, greetings, DeFi explanations, market data, etc.\n\nAll wallet actions (send, swap, buy, approve, wrap, unwrap, send_nft) are chain-specific: use chainId ${r} only.\nFor "chat" action: no chain restriction — use cross-chain knowledge freely.\n\n## OUTPUT FORMAT:\n${$h(a)}\n**LANGUAGE DETECTION — CRYPTO TICKERS**: Crypto token symbols/tickers (ETH, BTC, USDC, BNB, SOL, etc.) are NOT language indicators — they are proper nouns used universally. Detect language ONLY from the surrounding non-ticker text. Examples: "ETHの現在の価格は?" → Japanese. "ETH의 가격은?" → Korean. "Giá ETH?" → Vietnamese. NEVER classify a message as English just because it contains a ticker symbol.\n\nWallet action: {"action":"<type>","message":"<explanation>","parameters":{...}}\nChat/info: {"action":"chat","message":"<YOUR FULL DETAILED ANSWER>","parameters":{},"token_mentions":[],"suggested_actions":[]}\n\n## WALLET ACTION RULES:\n- Return action type IMMEDIATELY even if params are missing (leave as ""). Ask for missing info in "message". NEVER fall back to "chat" just because parameters are incomplete — always return the intended action.\n- **CROSS-CHAIN REQUESTS**: All wallet actions (send, swap, buy, approve, wrap, unwrap, send_nft, view_nfts, view_balances) execute ONLY on the CURRENT chain: ${n} (chainId: ${r}). If the user's message explicitly targets a DIFFERENT chain (e.g. "send on Ethereum", "swap on BSC", "transfer on Polygon", "buy on base") and the current chain is NOT that chain, do NOT execute the wallet action. Instead, return action: "chat" and politely notify the user to switch to the requested chain in the app first. This rule applies to ALL non-chat actions.\n- For ERC20 actions: provide correct contract_address on chainId ${r}. **CRITICAL — CHAIN-SPECIFIC ADDRESSES**: Contract addresses differ on every chain. You MUST obtain the address via your Moralis API tools (searchTokens, getTokenMetadata) for chainId ${r}, OR use the address already present in USER'S WALLET BALANCE. NEVER fill in a contract_address from training knowledge alone — leave it as "" if you cannot verify it via API or wallet balance. If token doesn't exist on this chain, inform user.\n- send_native: ONLY for ${i}. If user says "send ETH" but native ≠ ETH, use send_token.\n- Amount: "max"/"all" → "max". "X%" → "50%". USD formats → always prefix with "$": "5 dollar" → "$5", "5$" → "$5", "$5" → "$5", "5usd" → "$5", "5 đô la" → "$5", "0.01$ eth" → "$0.01", "$0.01 eth" → "$0.01", "5$ usdc" → "$5". The "$" MUST appear in the amount field (not stripped) so the app knows it's a USD value. Otherwise exact number string.\n- Decimals & symbol: always accurate.\n- send_nft: contract_address optional — use nft_name if NFT known by name.\n\n## suggested_actions & token_mentions:\n- suggested_actions: include when offering choices. {"label":"<2-6 words>","prompt":"<message>"}. Max 4. Never include "Buy" (app handles separately). **ABSOLUTELY NEVER** include any option that suggests switching, changing, or selecting a different chain (e.g., "Switch to Ethereum", "Change chain", "Switch network", "Chuyển sang chain khác", "Đổi mạng") — the app handles chain switching separately.\n- token_mentions: ONLY include when the token EXISTS on the CURRENT chain (chainId ${r}) AND you have obtained a VERIFIED contract address via your Moralis API tools (searchTokens, getTokenMetadata, getTokenPrice) for this exact chain.\n - **CRITICAL — CONTRACT ADDRESSES ARE CHAIN-SPECIFIC**: The same token has a DIFFERENT contract address on every chain. USDC on Ethereum ≠ USDC on Base ≠ USDC on Polygon ≠ USDC on BNB Chain. NEVER use an address from your training knowledge — training-data addresses are frequently wrong, hallucinated, or belong to a different chain.\n - **REQUIRED WORKFLOW**: Before populating token_mentions for a token, you MUST call your Moralis API tool (searchTokens or getTokenMetadata) specifying chainId ${r} to retrieve the verified contract address. If the API call fails or returns no result for this chain, set token_mentions: [].\n - If the token address is already available in the USER'S WALLET BALANCE section above, you MAY use that address (it is already verified for chainId ${r}).\n - If you cannot confirm the address via API or wallet balance, set token_mentions: [] — never guess.\n - **Native token**: If the token IS the chain's native token (${i}), use contract_address: "native" — do NOT look up an address.\n - Format: {"symbol":"","contract_address":"<API-verified address on chainId ${r}, or 'native' for the native token>","decimals":<n>}. 2+ tokens → [], use suggested_actions. Non-crypto → [].\n\n## ACTION PARAMS REFERENCE:\nValid actions: send_native, send_token, swap_token, buy_token, buy_token_trending, approve_token, wrap_native, unwrap_native, send_nft, view_nfts, view_balances, chat. NEVER use any other action name.\n\n1. send_native: {"to_address":"","amount":""}\n2. send_token: {"contract_address":"(REQ)","token_symbol":"","to_address":"","amount":"","decimals":""}\n3. swap_token: {"token_in":"<addr or 'native'>","token_in_symbol":"","token_in_decimals":"","token_out":"<addr>","token_out_symbol":"","token_out_decimals":"","amount":""}\n No tokens specified → all params "". Native → token_in:"native".\n4. buy_token: {"token_symbol":"(REQ — always fill this)","contract_address":"(if known and verified, else leave '')","decimals":"","buy_amount":"(opt — amount of the TOKEN BEING BOUGHT that user wants to RECEIVE. Use this when the amount refers to the destination token.)","pay_with_symbol":"(opt — symbol of token user wants to pay with, e.g. 'USDC', 'ETH')","pay_with_address":"(opt — contract address of payment token from WALLET BALANCE, or 'native' for native token)","pay_with_decimals":"(opt — decimals of payment token)","pay_with_amount":"(opt — amount of the PAYMENT TOKEN (token in) user wants to SPEND. Use this when the amount refers to the payment/source token.)"}.\n **CRITICAL — AMOUNT DISAMBIGUATION:**\n The amount in a buy request belongs to EITHER the token being bought OR the payment token. Parse the grammar carefully:\n - "buy PEPE with 10 USDC" → amount=10 belongs to USDC (payment) → pay_with_amount:"10", buy_amount:""\n - "buy 0.02 PCM with USDC" → amount=0.02 belongs to PCM (bought) → buy_amount:"0.02", pay_with_amount:""\n - "dùng 10 USDC mua PEPE" → amount=10 belongs to USDC (payment) → pay_with_amount:"10", buy_amount:""\n - "mua 0.02 PCM bằng USDC" → amount=0.02 belongs to PCM (bought) → buy_amount:"0.02", pay_with_amount:""\n NEVER put the amount of the token being bought into pay_with_amount. NEVER put the payment amount into buy_amount.\n If pay token is native (${i}), set pay_with_address:"native". Both tokens specified as a trade/exchange → swap_token. If you cannot verify the address, set contract_address:'' but ALWAYS return buy_token with the symbol filled. **NATIVE TOKEN**: If the token to buy IS the chain's native token (${i}), set contract_address: "native" directly — no API lookup needed.\n5. buy_token_trending: {} — no parameters needed; app handles discovery of trending/high-growth tokens. **message**: write ONLY a short 1-sentence header (e.g. "Here are the trending tokens on [chain] right now!"). Do NOT write analysis, tips, or explanations.\n6. approve_token: {"contract_address":"(REQ)","token_symbol":"","spender_address":"","amount":"","decimals":""}\n7. wrap_native: {"amount":""}\n8. unwrap_native: {"amount":""}\n9. send_nft: {"contract_address":"(opt)","token_id":"","to_address":"","token_standard":"","amount":"(def 1)","nft_name":""}\n10. view_nfts: {}\n11. view_balances: {} — use ONLY when user wants to see all balances/tokens, NOT for single token price/info queries\n12. chat: {} + token_mentions + suggested_actions — use for ALL informational/conversational requests\n\n## EXAMPLES:\nThese examples show INTENT → ACTION + PARAMETERS mapping only. The "message" content is for illustration — compose your own natural, helpful response based on context.\n\n// --- SEND NATIVE ---\n// Intent: user wants to send the chain's native token to an address\n// Triggers: "send ETH/BNB/MATIC to...", "transfer [native] to...", "chuyển [native] cho..."\n→ action: send_native | parameters: {to_address, amount}\n\n// --- SEND TOKEN ---\n// Intent: user wants to send an ERC20 token to an address\n// Triggers: "send USDC to...", "transfer [token] to...", "gửi [token] cho..."\n→ action: send_token | parameters: {contract_address, token_symbol, to_address, amount, decimals}\n\n// --- SWAP ---\n// Intent: exchange one token for another — trigger with ANY conversion/exchange/trade/sell keyword,\n// even with just ONE token mentioned, no amount, or only the native token as source\n// EN triggers: "swap X", "swap X to Y", "swap X for Y", "swap to ETH", "swap native"\n// "exchange X", "exchange X to Y", "exchange X for Y", "exchange native", "exchange ETH"\n// "convert X to Y", "convert native to USDC", "convert ETH", "convert X"\n// "trade X for Y", "trade X to Y", "trade ETH"\n// "sell X for Y", "sell ETH for USDC" (selling one token FOR another = swap)\n// VI triggers: "đổi X sang Y", "đổi X", "đổi native", "đổi ETH", "chuyển đổi X", "bán X lấy Y", "hoán đổi X"\n// Native source: token_in = "native" (e.g. "exchange ETH" → token_in:"native", token_in_symbol:"ETH")\n// Native dest: token_out = zeroAddress\n// ⚠️ NEVER confuse with wrap/unwrap: those are specifically ETH↔WETH. All other pairs = swap_token.\n→ action: swap_token | parameters: {token_in, token_in_symbol, token_in_decimals, token_out, token_out_symbol, token_out_decimals, amount}\n// Missing params → leave as "", ask for them in message. NEVER downgrade to chat.\n\n// --- WRAP / UNWRAP ---\n// Intent wrap: convert native to wrapped version — also triggered by "deposit"\n// Triggers: "wrap ETH", "deposit ETH", "deposit ETH to WETH", "đổi ETH sang WETH"\n→ action: wrap_native | parameters: {amount}\n\n// Intent unwrap: convert wrapped token back to native — also triggered by "withdraw"\n// Triggers: "unwrap WETH", "withdraw WETH", "convert WETH to ETH", "rút WETH"\n→ action: unwrap_native | parameters: {amount}\n\n// --- VIEW NFTs ---\n// Intent: user wants to see/browse their NFT collection\n// Triggers: "show my NFTs", "what NFTs do I have", "view my NFTs", "xem NFT của tôi"\n→ action: view_nfts | parameters: {}\n\n// --- VIEW BALANCES ---\n// Intent: user wants to see ALL their token balances at once (not a single token query)\n// EN triggers: "show my balance", "view my balance", "check my balance", "what's my balance"\n// "what's in my wallet", "what do I have", "what tokens do I have"\n// "view all tokens", "show all tokens", "list my tokens"\n// "my portfolio", "show portfolio", "wallet overview"\n// VI triggers: "xem số dư", "số dư của tôi", "kiểm tra số dư", "ví tôi có gì"\n// "tôi có bao nhiêu tiền", "xem ví", "danh mục của tôi"\n// ⚠️ Do NOT use view_balances for single-token queries ("price of ETH", "how much USDC is worth") → use chat instead\n→ action: view_balances | parameters: {}\n\n// --- BUY TOKEN TRENDING ---\n// Intent: user wants to buy but does NOT specify a token — or explicitly asks for trending/pumping/high-growth tokens to buy\n// EN triggers: "buy trending tokens", "buy trending", "buy hot tokens", "buy tokens pumping", "buy movers", "I want to buy a token", "buy a token"\n// VI triggers: "mua token trending", "mua token đang trending", "mua token tăng mạnh", "mua token đang tăng", "mua token tiềm năng", "mua token", "tôi muốn mua token"\n// ⚠️ CRITICAL: If user says "buy X" where X is a named token → use buy_token, NOT buy_token_trending\n// ⚠️ CRITICAL: If user gives NO specific token → ALWAYS use buy_token_trending, never chat\n// ⚠️ MESSAGE: ONLY a short 1-sentence header introducing the trending list. NO analysis, NO tips, NO explanations.\n→ action: buy_token_trending | parameters: {} | message: short header only (e.g. "Here are the trending tokens on [chain]!")\n\n// --- BUY TOKEN WITH SPECIFIC PAYMENT ---\n// Intent: user wants to buy a specific token AND specifies which token to pay with\n// EN triggers: "buy PEPE with USDC", "buy PEPE using ETH", "buy PEPE with 10 USDC", "purchase DOGE with my 0.5 ETH"\n// VI triggers: "mua PEPE bằng USDC", "mua PEPE dùng ETH", "mua PEPE bằng 10 USDC", "mua DOGE bằng 0.5 ETH của tôi"\n// → action: buy_token | parameters: {token_symbol, contract_address, decimals, pay_with_symbol, pay_with_address, pay_with_decimals, pay_with_amount}\n// AMOUNT DISAMBIGUATION (critical):\n// "buy PEPE with 10 USDC" → pay_with_amount:"10" buy_amount:"" (10 USDC to spend)\n// "buy 0.02 PCM with USDC" → buy_amount:"0.02" pay_with_amount:"" (0.02 PCM to receive)\n// "mua PEPE bằng 0.5 ETH" → pay_with_amount:"0.5" buy_amount:"" (0.5 ETH to spend)\n// "mua 0.02 PCM bằng USDC" → buy_amount:"0.02" pay_with_amount:"" (0.02 PCM to receive)\n// pay_with_* fields are filled from USER'S WALLET BALANCE. If pay token = native → pay_with_address: "native"\n// ⚠️ This is still buy_token (NOT swap_token) — the user's intent is to BUY, with a specified payment method\n\n// --- TOKEN INFO / PRICE (chat) ---\n// Intent: learn about a token, its price, market data — NOT a wallet action\n// Triggers: "tell me about X", "what is X token", "price of X", "X coin info", "X là gì"\n→ action: chat | compose a detailed answer using real-time data from your tools\n// If token EXISTS on current chain → token_mentions: [{symbol, contract_address, decimals}]\n// If token NOT on current chain → token_mentions: [] but tell user which supported chains have it\n\n// --- CROSS-CHAIN / GENERAL INFO (chat) ---\n// Intent: any question not requiring a wallet action — crypto trends, DeFi, protocols, general Q&A\n// Triggers: "what's trending on X?", "explain DeFi", "how does Uniswap work", anything conversational\n→ action: chat | compose a full, knowledgeable answer; add relevant suggested_actions if helpful\n\n// --- GREETING (chat) ---\n// Intent: greeting or open-ended start\n// Triggers: "hello", "hi", "hey", "xin chào", "bắt đầu"\n→ action: chat | introduce yourself and offer helpful options via suggested_actions`}({walletAddress:H?.address||void 0,chainName:j?.name||void 0,chainId:q||void 0,nativeSymbol:j?.nativeCurrency?.symbol||void 0,walletTokens:d,walletNfts:f,language:y}),k=await async function(e){const{prompt:t,model:n="gpt-4.1-mini",stream:i=!1,systemPrompt:o,signal:s}=e;if(!t)throw new Error("Prompt is required");const a=new Ph(zh),c=o?`${o}\n\n---\n\n Current User's question: ${t}`:t;let u="Unknown error";for(let l=1;l<=5;l++){if(s?.aborted)return{success:!1,error:"Request cancelled"};try{const e=(await a.post("api/moralis-cortex/proxy/chat",{prompt:c,model:n,stream:i},{headers:{Accept:"application/json","Content-Type":"application/json"},signal:s})).data;if(!e?.text?.trim()){if(u="Empty response from Cortex AI",l<5&&await Hh(1e3,s),s?.aborted)return{success:!1,error:"Request cancelled"};continue}return{success:!0,data:e}}catch(r){if(s?.aborted)return{success:!1,error:"Request cancelled"};if(u=r instanceof Error?r.message:"Unknown error",l<5&&await Hh(1e3,s),s?.aborted)return{success:!1,error:"Request cancelled"}}}return{success:!1,error:u}}({prompt:v,model:"gpt-4.1-mini",stream:!1,systemPrompt:A+w});if(k.success&&k.data){const e=k.data.text||"";let f=null;try{let t=e?.trim();t.startsWith("```json")?t=t.replace(/^```json\s*/,"").replace(/\s*```$/,""):t.startsWith("```")&&(t=t.replace(/^```\s*/,"").replace(/\s*```$/,"")),f=JSON.parse(Sp(t))}catch{f=null}if(f&&f.action&&"chat"!==f.action)if("buy_token"===f.action){const e=f.parameters?.token_symbol||"";let n=f.parameters?.contract_address||"",r=18,a=!1;if("native"!==n.toLowerCase()&&n!==xn||(n=xn),!n&&e&&j?.nativeCurrency?.symbol&&e.toUpperCase()===j.nativeCurrency.symbol.toUpperCase()&&(n=xn),n&&n!==xn)try{const t=await Gh.getTokensDetails([n],z),i=t?.data?.[0];i&&(e&&i.symbol?.toUpperCase()!==e.toUpperCase()?n="":r=i.decimals||18)}catch(i){}if(!n&&e&&H?.address)try{const t=await qh({address:H.address,chain:J});if(t?.success&&t?.data?.result){const i=t.data.result,o=i.find(e=>e.token_address.toLowerCase()===n.toLowerCase())||i.find(t=>t.symbol.toUpperCase()===e.toUpperCase());o&&(n=o.token_address,r=o.decimals)}if(!n){const t=j.tokenTrendingDefault||[],[i,o]=await Promise.allSettled([Gh.getTopGainers(z,"24h",10),Gh.getTokensDetails(t,z)]),s=[];"fulfilled"===i.status&&i.value?.data&&s.push(...i.value.data),"fulfilled"===o.status&&o.value?.data&&s.push(...o.value.data);const a=s.find(e=>e.address?.toLowerCase()===n.toLowerCase())||s.find(t=>t.symbol?.toUpperCase()===e.toUpperCase());a&&(n=a.address,r=a.decimals||18)}if(!n&&q)try{const t=await Gh.searchTokensByKey(e,q);if(Array.isArray(t?.data)&&t.data.length>0){const i=t.data.find(t=>t.symbol?.toUpperCase()===e.toUpperCase())||t.data[0];i?.address&&(a=!0,n=i.address,r=i.decimals||18)}}catch(o){}}catch(i){}if(n){g(a?m("buyingOnChain",{symbol:e,chain:j?.name}):f.message||m("buyTokenHelp",{symbol:e}),"bot",t.id),K({descTokenAddress:n,descTokenDecimals:r||18});const o=f.parameters?.pay_with_symbol||"",c=f.parameters?.pay_with_address||"";let u=!1;if(o||c)try{const e=await qh({address:H?.address||"",chain:J});if(e?.success&&e?.data?.result){const t=e.data.result;let r;if(r="native"===c.toLowerCase()||c===xn||!c&&o&&j?.nativeCurrency?.symbol&&o.toUpperCase()===j.nativeCurrency.symbol.toUpperCase()?t.find(e=>e.token_address===xn||e.native_token):t.find(e=>c&&e.token_address.toLowerCase()===c.toLowerCase())||t.find(e=>o&&e.symbol.toUpperCase()===o.toUpperCase()),r){u=!0;const t=f.parameters?.pay_with_amount||"",i=f.parameters?.buy_amount||"";if(t)K({srcTokenAddress:r.token_address,srcTokenDecimals:r.decimals}),await $(100,t,r.token_address,r.decimals);else if(i){let t="";try{const o=e.data.result.find(e=>e.token_address.toLowerCase()===n.toLowerCase());let s=o?.usd_price??null;if(null==s&&n){const e=await Vh({address:n,chain:J});e.success&&null!=e.data?.usd_price&&(s=e.data.usd_price)}const a=r.usd_price??null;null!=s&&null!=a&&a>0&&(t=(parseFloat(i)*s/a).toFixed(8).replace(/\.?0+$/,""))}catch(s){}t?(K({srcTokenAddress:r.token_address,srcTokenDecimals:r.decimals}),await $(100,t,r.token_address,r.decimals)):await _(r.token_address,r.symbol,r.balance_formatted,r.decimals)}else await _(r.token_address,r.symbol,r.balance_formatted,r.decimals)}}}catch(i){}u||await Z(n,r)}else g(m("tokenNotFoundOnChain",{symbol:e}),"bot",t.id),await te()}else if("buy_token_trending"===f.action)await te();else if("swap_token"===f.action){const e={...f.parameters||{}},n="native"===e.token_in||e.token_in_symbol?.toUpperCase()===j?.nativeCurrency?.symbol?.toUpperCase(),r="native"===e.token_out||e.token_out_symbol?.toUpperCase()===j?.nativeCurrency?.symbol?.toUpperCase();r&&(e.token_out=xn);let o=[];if(H?.address)try{const e=await qh({address:H.address,chain:J});e?.success&&e?.data?.result&&(o=e.data.result)}catch(i){}if(!n&&(e.token_in||e.token_in_symbol)&&o.length>0){const t=e.token_in?o.find(t=>t.token_address.toLowerCase()===e.token_in.toLowerCase()):o.find(t=>t.symbol.toUpperCase()===e.token_in_symbol.toUpperCase());t&&(e.token_in=t.token_address,e.token_in_decimals=String(t.decimals))}if(!r&&(e.token_out||e.token_out_symbol)&&o.length>0){const t=e.token_out?o.find(t=>t.token_address.toLowerCase()===e.token_out.toLowerCase()):o.find(t=>t.symbol.toUpperCase()===e.token_out_symbol.toUpperCase());t&&(e.token_out=t.token_address,e.token_out_decimals=String(t.decimals))}const s=!(!e.token_in&&!n),d=!!e.token_out,h=!!e.amount;if(s&&o.length>0)if(n){const e=o.find(e=>e.native_token);if(!e||Dh(e.balance_formatted||"0").isZero())return g(m("formInsufficientBalance",{balance:"0",symbol:j?.nativeCurrency?.symbol||"native"}),"bot",t.id),void I(!1)}else if(e.token_in){const n=o.find(t=>t.token_address.toLowerCase()===e.token_in.toLowerCase());if(!n)return g(m("swapTokenNotInWallet",{symbol:e.token_in_symbol||e.token_in}),"bot",t.id),void I(!1);if(Dh(n.balance_formatted||"0").isZero())return g(m("formInsufficientBalance",{balance:"0",symbol:n.symbol}),"bot",t.id),void I(!1)}if(s&&d&&h)try{const t=[];e.token_out&&t.push(e.token_out),e.token_in&&!n&&t.push(e.token_in);let r=18,s=18;if(t.length>0)try{const i=await Gh.getTokensDetails(t,z);if(i?.data)for(const t of i.data)n||t.address.toLowerCase()!==e.token_in?.toLowerCase()||(r=t.decimals||18),t.address.toLowerCase()===e.token_out?.toLowerCase()&&(s=t.decimals||18)}catch(a){}if(H?.address)try{if(o.length>0)if(n){const t=o.find(e=>e.native_token);let n=t?.balance_formatted||"0";try{const e=await dp({chainId:q,rpcUrl:G});if(e.isGreaterThan(0)){const r=e.times(1e6),i=new Dh(t?.balance||"0").minus(r);n=i.isGreaterThan(0)?Dh(pt(BigInt(i.toFixed(0)),t?.decimals||18)).toFixed():"0"}}catch(c){}e.amount=Np(e.amount,n,t?.usd_price);const r=parseFloat(n),i=parseFloat(e.amount);if(Dh(r).lte(0))return g(m("formInsufficientBalance",{balance:Dh(r).decimalPlaces(8).toFixed(),symbol:j?.nativeCurrency?.symbol||"native"}),"bot"),void I(!1);if(Dh(r).lt(i))return g(m("swapInsufficientNativeBalance",{balance:Dh(r).decimalPlaces(8).toFixed(),symbol:j?.nativeCurrency?.symbol||"native",amount:e.amount}),"bot"),void I(!1)}else{const t=o.find(t=>t.token_address.toLowerCase()===e.token_in?.toLowerCase());if(!t)return g(m("swapTokenNotInWallet",{symbol:e.token_in_symbol||e.token_in}),"bot"),void I(!1);e.amount=Np(e.amount,t.balance_formatted||"0",t.usd_price);const n=parseFloat(t.balance_formatted||"0"),r=parseFloat(e.amount);if(Dh(n).lt(r))return g(m("swapInsufficientTokenBalance",{balance:Dh(n).decimalPlaces(8).toFixed(),symbol:t.symbol,amount:e.amount}),"bot"),void I(!1)}}catch(u){}const l=n?xn:e.token_in;K({srcTokenAddress:l,descTokenAddress:e.token_out,amount:e.amount,srcTokenDecimals:r,descTokenDecimals:s});const d=kn(e.amount,r).toString(),f=await Xh({chainId:q,tokenIn:l,tokenInAmount:d,tokenOut:e.token_out,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(f.success&&f.data){const e=f.data,t=e.tokenIn,r=e.tokenOut,o=Dh(pt(BigInt(t.amount||0),t.decimals)).decimalPlaces(8).toFormat(),s=Dh(pt(BigInt(r.amount||0),r.decimals)).decimalPlaces(8).toFormat();let a=!1;if(!n&&H?.address&&e.tx?.to)try{const t=await ap({tokenAddress:l,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:q,rpcUrl:G});a=Dh(t.toString()).isLessThan(d)}catch(i){a=!0}const c=e.estimatedTransactionFee?.total?Dh(e.estimatedTransactionFee.total):Dh(0);let u=Dh(0);if(a&&H?.address)try{const t=cp({tokenAddress:l,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:q,amount:d});u=await lp({from:H.address,to:t.to,data:t.data,chainId:q,rpcUrl:G})}catch(i){}const h=c.plus(u),w=j?.nativeCurrency?.symbol||"native";let b="",y=!1;if(H?.address&&h.isGreaterThan(0))try{const e=await up({address:H.address,chainId:q,rpcUrl:G});if(e.isLessThan(h)){y=!0;const t=Dh(pt(BigInt(e.toFixed(0)),18)).decimalPlaces(8).toFormat(),n=Dh(pt(BigInt(h.toFixed(0)),18)).decimalPlaces(8).toFormat();b=m("swapFeeWarning",{symbol:w,balance:t,needed:n})}}catch(i){}const v=`From: ${o} ${t.symbol}\n⬇️\nTo: ${s} ${r.symbol}\n\n`+b+"\n";if(y)g(v,"bot");else if(a){const n=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:t.symbol}),value:m("swapApproveValue",{symbol:t.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:l,spenderAddress:e.tx.to,tokenSymbol:t.symbol,amountInWei:d,tx:e.tx}}];g(v+m("swapNeedApprove",{symbol:t.symbol}),"bot",void 0,n)}else{const t=[{id:"confirm-swap",text:p("swapConfirmYes"),value:p("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(v+p("swapReadyToProceed"),"bot",void 0,t)}}else g(m("swapEstimationError",{error:f.errorMessage||f.error||"Unknown error"}),"bot")}catch(l){g(p("swapEstimationFailed"),"bot")}else if(s&&d&&!h){let r=n?18:parseInt(e.token_in_decimals||"18",10),s=parseInt(e.token_out_decimals||"18",10);const u=[];if(e.token_out&&u.push(e.token_out),e.token_in&&!n&&u.push(e.token_in),u.length>0)try{const t=await Gh.getTokensDetails(u,z);if(t?.data)for(const i of t.data)n||i.address.toLowerCase()!==e.token_in?.toLowerCase()||(r=i.decimals||r),i.address.toLowerCase()===e.token_out?.toLowerCase()&&(s=i.decimals||s)}catch(a){}if(K({descTokenAddress:e.token_out,descTokenDecimals:s}),n)try{if(o.length>0){const e=o.find(e=>e.native_token),n=j?.nativeCurrency?.symbol||"ETH";let i=e?.balance_formatted||"0";try{const t=await dp({chainId:q,rpcUrl:G});if(t.isGreaterThan(0)){const n=t.times(1e6),r=new Dh(e?.balance||"0").minus(n);i=r.isGreaterThan(0)?Dh(pt(BigInt(r.toFixed(0)),e?.decimals||18)).toFixed():"0"}}catch(c){}K({srcTokenAddress:xn,srcTokenDecimals:r});const s=[25,50,75,100].map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:n}),action:"select_percent",extraData:{percent:e,tokenAddress:xn,tokenSymbol:n,tokenDecimals:r,tokenBalance:i}}));g(m("selectAmountToSwap",{symbol:n,balance:i}),"bot",t.id,s)}else g(p("couldNotFetchBalance"),"bot")}catch(i){g(p("couldNotFetchBalanceRetry"),"bot")}else{const n=e.token_in_symbol||"Token";K({srcTokenAddress:e.token_in,srcTokenDecimals:r});try{if(o.length>0){const r=o.find(t=>t.token_address.toLowerCase()===e.token_in?.toLowerCase());if(!r)return g(m("swapTokenNotInWallet",{symbol:n}),"bot"),void I(!1);const i=[25,50,75,100].map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:r.symbol}),action:"select_percent",extraData:{percent:e,tokenAddress:r.token_address,tokenSymbol:r.symbol,tokenDecimals:r.decimals||18,tokenBalance:r.balance_formatted}}));g(m("selectAmountToSwap",{symbol:r.symbol,balance:`${r.balance_formatted} (~$${r.usd_value?.toFixed(2)||"0"})`}),"bot",t.id,i)}else g(p("couldNotFetchBalance"),"bot")}catch(i){g(p("couldNotFetchBalanceRetry"),"bot")}}}else if(!s&&d){g(f.message||p("swapChooseFrom"),"bot",t.id);let n=parseInt(e.token_out_decimals||"18",10);if(e.token_out)try{const t=await Gh.getTokensDetails([e.token_out],z);t?.data?.[0]&&(n=t.data[0].decimals||n)}catch(a){}h&&K({descTokenAddress:e.token_out,descTokenDecimals:n,amount:e.amount}),await Z(e.token_out,n)}else if(s&&!d){let r=n?18:parseInt(e.token_in_decimals||"18",10);if(e.token_in&&!n)try{const t=await Gh.getTokensDetails([e.token_in],z);t?.data?.[0]&&(r=t.data[0].decimals||r)}catch(a){}if(K(n?{srcTokenAddress:xn,srcTokenDecimals:18,...h?{amount:e.amount}:{}}:{srcTokenAddress:e.token_in,srcTokenDecimals:r,...h?{amount:e.amount}:{}}),h&&o.length>0)if(n){const n=o.find(e=>e.native_token),r=Np(e.amount,n?.balance_formatted||"0",n?.usd_price);if(Dh(n?.balance_formatted||"0").lt(r))return g(m("swapInsufficientNativeBalance",{balance:Dh(n?.balance_formatted||"0").decimalPlaces(8).toFixed(),symbol:j?.nativeCurrency?.symbol||"native",amount:r}),"bot",t.id),void I(!1);e.amount=r,K({amount:r})}else if(e.token_in){const n=o.find(t=>t.token_address.toLowerCase()===e.token_in.toLowerCase());if(n){const r=Np(e.amount,n.balance_formatted||"0",n.usd_price);if(Dh(n.balance_formatted||"0").lt(r))return g(m("swapInsufficientTokenBalance",{balance:Dh(n.balance_formatted||"0").decimalPlaces(8).toFixed(),symbol:n.symbol,amount:r}),"bot",t.id),void I(!1);e.amount=r,K({amount:r})}}g(f.message||m("swapChooseTo",{symbol:e.token_in_symbol||"your token"}),"bot",t.id);try{I(!0);const e=j?.tokenTrendingDefault||[],[t,n]=await Promise.allSettled([Gh.getTopGainers(z,"24h",5),Gh.getTokensDetails(e,z)]);let r=[];"fulfilled"===t.status&&t.value?.data&&(r=[...t.value.data]),"fulfilled"===n.status&&n.value?.data&&(r=[...n.value.data,...r]),r=r.filter((e,t,n)=>t===n.findIndex(t=>t.address.toLowerCase()===e.address.toLowerCase()));const i=r.map(e=>({id:e?.symbol,text:e?.symbol,value:m("buttonSwapTo",{name:e.name,symbol:e?.symbol||""}),action:"click_swap_dest_token",extraData:{tokenAddress:e?.address||"",symbol:e?.symbol||"",decimals:e?.decimals||18}}));g(m("trendingTokensForReceive",{chain:j?.name||"Unknown"}),"bot",void 0,i)}catch(i){g(p("couldNotLoadTokenList"),"bot")}finally{I(!1)}}else if(h&&K({amount:e.amount}),g(f.message||p("swapChooseToken"),"bot",t.id),H?.address)try{I(!0);const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result&&e.data.result.length>0){const t=e.data.result.map(e=>({id:`swap-select-${e.token_address}`,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${Dh(e?.usd_value||0).decimalPlaces(2).toFixed()||"0"})`,value:`Swap ${e.symbol}`,action:"suggested_action",fullWidth:!0}));await eh(500),I(!1),g(m("walletBalanceSpendable",{chain:j?.name||"this chain"}),"bot",void 0,t)}else I(!1),g(m("walletNoTokensFound",{chain:j?.name||"this chain"}),"bot")}catch(i){I(!1),g(p("walletFetchError"),"bot")}}else if("view_balances"===f.action)await re();else if("view_nfts"===f.action)await ne();else if("send_token"!==f.action||f.parameters?.contract_address||f.parameters?.token_symbol||!H?.address)if("send_nft"!==f.action||f.parameters?.contract_address||f.parameters?.token_id||f.parameters?.nft_name||!H?.address)if("send_nft"===f.action&&!Ye(f.parameters?.contract_address||"")&&(f.parameters?.nft_name||f.parameters?.token_id)&&H?.address)try{I(!0);const e=await Yh({address:H.address,chain:J,limit:100,exclude_spam:!1});if(e?.success&&e?.data?.result){const n=e.data.result,r=(f.parameters?.nft_name||"").toLowerCase(),i=f.parameters?.token_id||"",o=e=>{const t=(e.normalized_metadata?.name||e.name||"").toLowerCase(),n=(e.name||"").toLowerCase(),o=r&&(t.includes(r)||n.includes(r)),s=i&&e.token_id===i;return r&&i?o&&s:r?o:s},s=!r&&!!i,a=s?n.filter(o):[],c=s?1===a.length?a[0]:null:n.find(o);if(s&&a.length>1){const e=a.map(e=>{const t=e.normalized_metadata?.name||e.name||`#${e.token_id}`,n=e.normalized_metadata?.image||e.media?.original_media_url||"";return{id:`${e.token_address}-${e.token_id}`,text:`${t} (${e.symbol||e.contract_type}) #${e.token_id}`,value:m("buttonSendNft",{name:t}),action:"select_nft_to_send",fullWidth:!0,extraData:{contractAddress:e.token_address,tokenId:e.token_id,tokenStandard:e.contract_type,name:t,symbol:e.symbol,amount:e.amount,image:n,toAddress:f.parameters?.to_address||""}}}),n=a.map((e,t)=>{const n=e.normalized_metadata?.name||e.name||`#${e.token_id}`,r=e.normalized_metadata?.image||e.media?.original_media_url||"";return`${t+1}. ${r?`![${n}](${r})\n`:"🖼️ "}**${n}**\n ${e.symbol||e.contract_type} | Token ID: ${e.token_id}`}).join("\n\n");I(!1),g(m("nftMultipleMatchesForTokenId",{count:String(a.length),tokenId:i})+"\n\n"+n,"bot",t.id,e)}else if(c){const e=c.normalized_metadata?.name||c.name||`#${c.token_id}`,n=c.normalized_metadata?.image||c.media?.original_media_url||"",r={contract_address:c.token_address,token_id:c.token_id,to_address:f.parameters?.to_address||"",token_standard:c.contract_type||"",amount:f.parameters?.amount||"1",maxAmount:c.amount||"1",nft_name:e};g(f.message||m("nftSendReview",{name:e,standard:c.contract_type||"NFT",tokenId:c.token_id}),"bot",t.id,void 0,{action:"send_nft",parameters:r,status:"pending",nftInfo:{name:e,image:n||void 0,tokenId:c.token_id,contractAddress:c.token_address,tokenStandard:c.contract_type||void 0}})}else g(m("nftNotFoundInWallet",{name:r||i}),"bot",t.id)}else g(p("nftNoCollection"),"bot",t.id)}catch(i){g(p("nftFetchError"),"bot",t.id)}finally{I(!1)}else{const o=(n=f.action,["send_native","send_token","approve_token","wrap_native","unwrap_native","send_nft"].includes(n));let s,a,u={...f.parameters||{}};const l=["send_token","approve_token"].includes(f.action)&&(u.contract_address||u.token_symbol),d="send_native"===f.action||"wrap_native"===f.action,h="unwrap_native"===f.action,p="send_nft"===f.action&&u.contract_address;if(l&&H?.address)try{const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result){const t=e.data.result,n=u.contract_address?t.find(e=>e.token_address.toLowerCase()===u.contract_address.toLowerCase()):t.find(e=>e.symbol.toUpperCase()===u.token_symbol.toUpperCase());n&&(u={...u,contract_address:n.token_address,decimals:String(n.decimals)},s={symbol:n.symbol,name:n.name,balance:n.balance,balanceFormatted:n.balance_formatted,usdValue:n.usd_value,usdPrice:n.usd_price,decimals:n.decimals,logo:n.logo||n.thumbnail,contractAddress:n.token_address})}}catch(i){}if(l&&!s&&"send_token"===f.action){const e=u.token_symbol||u.contract_address||"this token";return g(m("sendTokenNotInWallet",{symbol:e}),"bot",t.id),void I(!1)}if(l&&!s&&u.contract_address)try{const e=await Vh({address:u.contract_address,chain:J});if(e?.success&&e?.data){const t=e.data;s={symbol:t.symbol,name:t.name,balance:"0",balanceFormatted:"0",usdPrice:t.usd_price,decimals:t.decimals,logo:t.logo,contractAddress:u.contract_address},u={...u,decimals:String(t.decimals)}}}catch(i){}if(d&&H?.address)try{const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result){const t=e.data.result.find(e=>e.native_token);if(t){let e=t.balance_formatted,n=t.balance;try{const r=new Dh(t.balance),i="0x"+BigInt(r.toFixed(0)).toString(16),o=await lp({from:H.address,to:H.address,data:"0x",value:i,chainId:q,rpcUrl:G});if(o.isGreaterThan(0)){const i=r.minus(o);i.isGreaterThan(0)?(n=i.toFixed(0),e=Dh(pt(BigInt(i.toFixed(0)),t.decimals)).toFixed()):(n="0",e="0")}}catch(c){}s={symbol:t.symbol,name:t.name,balance:n,balanceFormatted:e,usdValue:t.usd_value,usdPrice:t.usd_price,decimals:t.decimals,logo:t.logo||t.thumbnail,contractAddress:xn}}else{const e=await Vh({address:xn,chain:J});if(e?.success&&e?.data){const t=e.data;s={symbol:t.symbol,name:t.name,balance:"0",balanceFormatted:"0",usdValue:0,usdPrice:t.usd_price,decimals:t.decimals,logo:t.logo||t.thumbnail,contractAddress:xn}}}}}catch(i){}if(h&&H?.address)try{const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result){const t=e.data.result,n=`W${j?.nativeCurrency?.symbol||"ETH"}`,r=t.find(e=>e.symbol.toUpperCase()===n.toUpperCase());r&&(s={symbol:r.symbol,name:r.name,balance:r.balance,balanceFormatted:r.balance_formatted,usdValue:r.usd_value,usdPrice:r.usd_price,decimals:r.decimals,logo:r.logo||r.thumbnail,contractAddress:r.token_address})}}catch(i){}if(p){try{const e=await async function(e){const{address:t,chain:n="base"}=e;if(!t)throw new Error("Contract address is required");try{return{success:!0,data:(await Jh.get(`api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata`,{query:{chain:n}})).data}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}({address:u.contract_address,chain:J});if(e?.success&&e?.data){const t=e.data;t.contract_type&&(u={...u,token_standard:t.contract_type}),!u.nft_name&&t.name&&(u={...u,nft_name:t.name})}}catch(i){}if(H?.address)try{const e=await Yh({address:H.address,chain:J,limit:100,exclude_spam:!1});if(e?.success&&e?.data?.result){const n=e.data.result.find(e=>e.token_address.toLowerCase()===u.contract_address.toLowerCase()&&e.token_id===u.token_id);if(!n){const e=u.nft_name||`#${u.token_id||u.contract_address}`;return g(m("nftNotFoundInWallet",{name:e}),"bot",t.id),void I(!1)}{u={...u,amount:u.amount||"1",maxAmount:n.amount||"1"};const e=n.normalized_metadata?.image||n.media?.original_media_url||"";a={name:n.normalized_metadata?.name||n.name||u.nft_name||`#${n.token_id}`,image:e||void 0,tokenId:n.token_id,contractAddress:n.token_address,tokenStandard:n.contract_type||u.token_standard||void 0}}}}catch(i){}}if(u.amount&&s?.balanceFormatted&&("send_token"===f.action||"send_native"===f.action||"wrap_native"===f.action||"unwrap_native"===f.action)&&(u.amount=Np(u.amount,s.balanceFormatted,s.usdPrice)),o){const e=f.message||"Please review and complete the form below.";g(e,"bot",t.id,void 0,{action:f.action,parameters:u,status:"pending",tokenInfo:s,nftInfo:a})}else g(f.message||e,"bot",t.id)}else g(m("sendNftViaWebsite",{link:Ip}),"bot");else try{const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result&&e.data.result.length>0){g(p("sendTokenChoose"),"bot",t.id),I(!0),await eh(500);const n=e.data.result.map(e=>({id:`send-select-${e.token_address}`,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${Dh(e?.usd_value||0).decimalPlaces(2).toFixed()||"0"})`,value:m("buttonSendToken",{symbol:e.symbol}),action:"suggested_action",fullWidth:!0}));await eh(500),I(!1),g(m("walletBalanceSpendable",{chain:j?.name||"this chain"}),"bot",void 0,n)}else I(!1),g(m("walletNoTokensFound",{chain:j?.name||"this chain"}),"bot")}catch(i){I(!1),g(p("walletFetchError"),"bot")}else if(f&&"chat"===f.action){const n=f.token_mentions||[],r=f.suggested_actions||[],i=[];n.length>0&&(await Promise.all(n.map(async e=>{let t=e.contract_address||"",n=e.decimals||18;if("native"===t.toLowerCase()&&(t=xn),t===xn){const t=d?.find(e=>e.native_token);return t?{symbol:e.symbol||t.symbol,contract_address:xn,decimals:18}:e.symbol?{symbol:e.symbol,contract_address:xn,decimals:18}:null}if(t&&t!==xn){const r=d?.find(n=>n.token_address.toLowerCase()===t.toLowerCase()&&n.symbol.toUpperCase()===e.symbol.toUpperCase());if(r){try{const e=await Gh.getTokensDetails([t],z);n=e?.data?.[0]?.decimals??n}catch{}return{symbol:e.symbol,contract_address:t,decimals:n}}try{const r=await Gh.getTokensDetails([t],z),i=r?.data?.[0];if(i&&i.symbol?.toUpperCase()===e.symbol.toUpperCase())return{symbol:e.symbol,contract_address:t,decimals:i.decimals??n};t=""}catch{t=""}}if(!t&&d){const r=d.find(t=>t.symbol.toUpperCase()===e.symbol.toUpperCase());if(r){t=r.token_address;try{const e=await Gh.getTokensDetails([t],z);n=e?.data?.[0]?.decimals??n}catch{}}}return t?{symbol:e.symbol,contract_address:t,decimals:n}:null}))).filter(e=>null!==e).forEach(e=>{i.push({id:`buy-${e.symbol}`,text:`💰 Buy ${e.symbol}`,value:m("buttonBuySymbol",{symbol:e.symbol}),action:"click_buy_item_token_button",extraData:{tokenAddress:e.contract_address,symbol:e.symbol,decimals:e.decimals},fullWidth:!0})}),r.length>0&&r.forEach((e,t)=>{i.push({id:`suggested-${t}-${e.label}`,text:e.label,value:e.prompt,action:"suggested_action",fullWidth:!0})}),i.length>0?g(f.message||e,"bot",t.id,i):g(f.message||e,"bot",t.id)}else g(e,"bot",t.id)}else g(p("errorProcessingRequest"),"bot",t.id)}catch(r){g(p("errorProcessingRequest"),"bot",t.id)}var n;I(!1),await eh(50),bp.isDesktop&&O.current?.focus()},[E,C,B,g,b,H?.address,V,j?.name,j?.nativeCurrency?.symbol,j?.tokenTrendingDefault,q,x,J,z,m,Z,_,$,te,p,K,G,re,ne]);o(()=>{F.current&&E===F.current&&(F.current=null,se())},[E,se]);const ae=s(async(e,t,n)=>{try{if(N(!1),y(n,"submitted"),"swap_token"===e){let e=18;if(t.token_in&&t.token_in!==xn)try{const n=await Gh.getTokensDetails([t.token_in],z);n?.data?.[0]&&(e=n.data[0].decimals||18)}catch(r){}const o=kn(t.amount||"0",e).toString(),s=await Xh({chainId:q,tokenIn:t.token_in||"",tokenInAmount:o,tokenOut:t.token_out||"",tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(s.success&&s.data){const e=s.data,r=e.tokenIn,a=e.tokenOut,c=Dh(pt(BigInt(r.amount||0),r.decimals)).decimalPlaces(8).toFormat(),u=Dh(pt(BigInt(a.amount||0),a.decimals)).decimalPlaces(8).toFormat(),l=!t.token_in||t.token_in===xn;let d=!1;if(!l&&H?.address&&e.tx?.to)try{const n=await ap({tokenAddress:t.token_in,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:q,rpcUrl:G});d=Dh(n.toString()).isLessThan(o)}catch(i){}const f=e.estimatedTransactionFee?.total?Dh(e.estimatedTransactionFee.total):Dh(0);let h=Dh(0);if(d&&H?.address)try{const n=cp({tokenAddress:t.token_in,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:q,amount:o});h=await lp({from:H.address,to:n.to,data:n.data,chainId:q,rpcUrl:G})}catch(i){}const w=f.plus(h),b=j?.nativeCurrency?.symbol||"native";let v="",A=!1;if(H?.address&&w.isGreaterThan(0))try{const e=await up({address:H.address,chainId:q,rpcUrl:G});if(e.isLessThan(w)){A=!0;const t=Dh(pt(BigInt(e.toFixed(0)),18)).decimalPlaces(8).toFormat(),n=Dh(pt(BigInt(w.toFixed(0)),18)).decimalPlaces(8).toFormat();v=m("swapFeeWarning",{symbol:b,balance:t,needed:n})}}catch(i){}const k=`From: ${c} ${r.symbol}\n⬇️\nTo: ${u} ${a.symbol}\n\n`+v+"\n";if(A)y(n,"pending"),g(k,"bot");else if(d){const i=[{id:"approve-swap-actionform",text:m("swapApproveButton",{symbol:r.symbol}),value:m("swapApproveValue",{symbol:r.symbol}),action:"approve_for_swap",extraData:{tokenAddress:t.token_in,spenderAddress:e.tx.to,tokenSymbol:r.symbol,amountInWei:o,tx:e.tx},fullWidth:!0}];y(n,"success"),g(k+m("swapApprovalRequired",{symbol:r.symbol}),"bot",void 0,i)}else{const t=[{id:"confirm-swap-actionform",text:p("swapConfirmYes"),value:p("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];y(n,"success"),g(k+p("swapReadyToProceed"),"bot",void 0,t)}}else y(n,"pending"),g(m("swapEstimationError",{error:s.errorMessage||s.error||"Unknown error"}),"bot")}else{const r=function(e){const{action:t,parameters:n,fromAddress:r,chainId:i}=e;switch(t){case"send_native":return function(e,t,n){const{to_address:r,amount:i}=e;if(!r)throw new Error("Recipient address is required");if(!i)throw new Error("Amount is required");return{from:t,to:r,data:"0x",value:kn(Dh(i).decimalPlaces(18,Dh.ROUND_DOWN).toFixed(),18).toString(),chainId:n,description:`Send ${i} native token to ${r}`}}(n,r,i);case"send_token":return function(e,t,n){const{contract_address:r,to_address:i,amount:o,decimals:s,token_symbol:a}=e;if(!r)throw new Error("Token contract address is required");if(!i)throw new Error("Recipient address is required");if(!o)throw new Error("Amount is required");const c=parseInt(s)||18,u=kn(Dh(o).decimalPlaces(c,Dh.ROUND_DOWN).toFixed(),c);return{from:t,to:r,data:st({abi:tp,functionName:"transfer",args:[i,u]}),value:"0",chainId:n,description:`Send ${o} ${a||"tokens"} to ${i}`}}(n,r,i);case"approve_token":return function(e,t,n){const{contract_address:r,spender_address:i,amount:o,decimals:s,token_symbol:a}=e;if(!r)throw new Error("Token contract address is required");if(!i)throw new Error("Spender address is required");const c=parseInt(s)||18,u=o&&""!==o?.trim()?kn(Dh(o).decimalPlaces(c,Dh.ROUND_DOWN).toFixed(),c):Jt;return{from:t,to:r,data:st({abi:tp,functionName:"approve",args:[i,u]}),value:"0",chainId:n,description:`Approve ${o||"unlimited"} ${a||"tokens"} for ${i}`}}(n,r,i);case"wrap_native":return function(e,t,n){const{amount:r}=e;if(!r)throw new Error("Amount is required");const i=ep[n];if(!i)throw new Error(`WETH not supported on chain ${n}`);const o=kn(Dh(r).decimalPlaces(18,Dh.ROUND_DOWN).toFixed(),18).toString();return{from:t,to:i,data:st({abi:np,functionName:"deposit"}),value:o,chainId:n,description:`Wrap ${r} native token`}}(n,r,i);case"unwrap_native":return function(e,t,n){const{amount:r}=e;if(!r)throw new Error("Amount is required");const i=ep[n];if(!i)throw new Error(`WETH not supported on chain ${n}`);const o=kn(Dh(r).decimalPlaces(18,Dh.ROUND_DOWN).toFixed(),18);return{from:t,to:i,data:st({abi:np,functionName:"withdraw",args:[o]}),value:"0",chainId:n,description:`Unwrap ${r} WETH`}}(n,r,i);case"send_nft":return function(e,t,n){const{contract_address:r,token_id:i,to_address:o,token_standard:s,amount:a,nft_name:c}=e;if(!r)throw new Error("NFT contract address is required");if(!i)throw new Error("Token ID is required");if(!o)throw new Error("Recipient address is required");const u=(s||"ERC721").toUpperCase(),l=BigInt(i);let d,f;if("ERC1155"===u){const e=BigInt(a||"1");d=st({abi:ip,functionName:"safeTransferFrom",args:[t,o,l,e,"0x"]}),f=`Send ${e>1n?e.toString()+"x ":""}${c||"NFT"} (ERC1155 #${i}) to ${o}`}else d=st({abi:rp,functionName:"safeTransferFrom",args:[t,o,l]}),f=`Send ${c||"NFT"} (ERC721 #${i}) to ${o}`;return{from:t,to:r,data:d,value:"0",chainId:n,description:f}}(n,r,i);default:throw new Error(`Action "${t}" does not produce a transaction`)}}({action:e,parameters:t,fromAddress:H?.address||"",chainId:q||1}),i={from:r.from,to:r.to,data:r.data,value:r.value,chainId:r.chainId};if(("send_token"===e||"send_native"===e||"send_nft"===e||"wrap_native"===e||"unwrap_native"===e||"approve_token"===e)&&H?.address)try{const e=j?.nativeCurrency?.symbol||"native",t=await lp({from:r.from,to:r.to,data:r.data,value:r.value&&"0"!==r.value?`0x${BigInt(r.value).toString(16)}`:void 0,chainId:q,rpcUrl:G});if(t.isGreaterThan(0)){const r=await up({address:H.address,chainId:q,rpcUrl:G});if(r.isLessThan(t)){const i=Dh(pt(BigInt(r.toFixed(0)),18)).decimalPlaces(8).toFormat(),o=Dh(pt(BigInt(t.toFixed(0)),18)).decimalPlaces(8).toFormat();return y(n,"pending"),void g(m("txInsufficientGas",{symbol:e,balance:i,fee:o}),"bot")}}}catch(o){}if(u){I(!1);const r=await u(i);if("success"===r.status&&r.transactionHash){const i=j?.blockExplorers?.default?.url,o=i?` [View on Explorer](${i}/tx/${r.transactionHash})`:` Tx: ${r.transactionHash}`;try{if(await eh(4e3),"success"===(await sp({transactionHash:r.transactionHash,chainId:q||1,rpcUrl:G})).status){if(y(n,"success"),v(n,t),"approve_token"===e&&g(m("approvalSuccess",{symbol:t.token_symbol||t.contract_address||"Token"})+o,"bot"),"send_token"===e||"send_native"===e||"send_nft"===e){const n=t.to_address||t.recipient||"",r=n?`${n.slice(0,6)}...${n.slice(-4)}`:"";g("send_nft"===e?m("txSuccessfulSendNft",{name:t.nft_name||t.token_symbol||"NFT",tokenId:t.token_id||"",to:r})+o:m("send_native"===e?"txSuccessfulSendNative":"txSuccessfulSendToken",{amount:t.amount||"",symbol:t.token_symbol||("send_native"===e?j?.nativeCurrency?.symbol||"native":"Token"),to:r})+o,"bot")}if("wrap_native"===e){const e=j?.nativeCurrency?.symbol||"native";g(m("txSuccessfulWrapNative",{amount:t.amount||"",from:e,to:`W${e}`})+o,"bot")}if("unwrap_native"===e){const e=j?.nativeCurrency?.symbol||"native";g(m("txSuccessfulUnwrapNative",{amount:t.amount||"",from:`W${e}`,to:e})+o,"bot")}}else y(n,"pending"),g(p("txReverted")+"\n"+o,"bot")}catch(s){y(n,"success"),g(p("txTimeout")+"\n"+o,"bot")}}else if("success"===r.status)y(n,"success");else{y(n,"pending");const e=r.error?`\nError: ${r.error}`:"";g(p("txFailed")+e,"bot")}}else y(n,"pending"),g(p("txNoHandler"),"bot")}}catch(a){y(n,"pending"),g(m("txError",{message:a instanceof Error?a.message:"Unknown error"}),"bot")}},[y,q,H?.address,z,j?.nativeCurrency?.symbol,j?.blockExplorers?.default?.url,G,m,g,p,u,v]),ce=s(e=>{k([e])},[k]),[ue,le]=i({}),de=s(async(e,t,n)=>{le(e=>({...e,[n]:!0}));try{await ae(e,t,n)}finally{le(e=>({...e,[n]:!1}))}},[ae]),fe=s(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),se())},[se]),he=s(()=>{const e=window.getSelection();e&&e.toString().length>0||a()},[a]);return r?/* @__PURE__ */e("div",{className:"chat-modal-overlay"+("bottom-left"===f?" chat-modal-overlay--left":""),onClick:he,role:"dialog","aria-modal":"true","aria-labelledby":"chat-modal-title",children:/* @__PURE__ */n("div",{className:"chat-modal",style:h,onClick:e=>e.stopPropagation(),children:[
38
+ return n("div",{className:"message-content",children:[i,s.length>0&&/* @__PURE__ */e("div",{className:"mc-link-previews",children:s.map(t=>/* @__PURE__ */e(Ep,{url:t},t))})]})},Ip="https://nft.keyring.app";function Sp(e){const t=e.indexOf("{");if(-1===t)return e;let n=0,r=!1,i=!1;for(let o=t;o<e.length;o++){const s=e[o];if(i)i=!1;else if("\\"===s&&r)i=!0;else if('"'!==s){if(!r)if("{"===s)n++;else if("}"===s&&(n--,0===n))return e.slice(t,o+1)}else r=!r}return e}function Np(e,t,n){if(!e)return e;const r=e.toLowerCase().trim();if("max"===r||"all"===r)return t||e;const i=r.match(/^(\d+(?:\.\d+)?)%$/);if(i){const e=parseFloat(i[1])/100;return((parseFloat(t)||0)*e).toFixed(8).replace(/\.?0+$/,"")||"0"}const o=r.match(/^\$?(\d+(?:\.\d+)?)\$?$/),s=r.startsWith("$")||r.endsWith("$")||/\d(usd|dollar|dollars|đô|đồng)$/.test(r);if(o&&s){const t=parseFloat(o[1]);return n&&n>0?(t/n).toFixed(8).replace(/\.?0+$/,"")||"0":e}const a=r.match(/^(\d+(?:\.\d+)?)\s*(?:usd|dollar|dollars|đô|đồng)$/);if(a){const t=parseFloat(a[1]);return n&&n>0?(t/n).toFixed(8).replace(/\.?0+$/,"")||"0":e}return e}const Bp=({isOpen:r,onClose:a,onTransaction:u,position:f="bottom-right",modalChatStyle:h={}})=>{const{t:p,ti:m}=w(),{messages:b,addMessage:g,updateMessageAction:y,updateMessageActionParameters:v,updateMessageText:A,clearMessagesById:k,updateMessageType:x}=function(){const{account:e}=ah(),{t:t}=w(),n=(r=e?.address,a=e?.chainId,r&&a?`${r}_${a}`:"");var r,a;const c=l(()=>hh(t("welcomeMessage")),[t]),[u,d]=i(()=>n||"pending"),[f,h]=i(()=>{const e=mh();return n?e&&e.owner===n?e.messages:hh(t("welcomeMessage")):e?.messages??hh(t("welcomeMessage"))});if("pending"===u&&n){const e=mh();e&&e.owner===n?h(e.messages):wh(n,f),d(n)}else"pending"!==u&&n&&u!==n&&(h(c),wh(n,c),d(n));const p=l(()=>f.map(e=>e.id===fh?{...e,text:t("welcomeMessage")}:e),[f,t]);o(()=>{"pending"!==u&&wh(u,f)},[f,u]),o(()=>{const e=[];for(let t=0;t<ih.length;t++){const n=ih.key(t);n&&n.startsWith(lh+"_")&&e.push(n)}e.forEach(e=>ih.removeItem(e))},[]);const m=s(()=>{h(c),wh(n,c)},[n,c]),b=s(e=>{h(t=>{const n=t.filter(t=>!e.includes(t.id));return n.length>dh?n.slice(n.length-dh):n})},[]);return{messages:p,setMessages:h,addMessage:(e,t,n,r,i,o="web3")=>{const s=n?f.find(e=>e.id===n):void 0,a={id:Math.random().toString(36).substring(2,12),text:e,sender:t,timestamp:/* @__PURE__ */new Date,typeChat:o,...s&&{replyTo:{id:s.id,text:s.text,sender:s.sender}},...r&&{buttons:r},...i&&{actionData:i}};return h(e=>{const t=[...e,a];return t.length>dh?t.slice(t.length-dh):t}),a},updateMessageAction:(e,t)=>{h(n=>n.map(n=>n.id===e&&n.actionData?{...n,actionData:{...n.actionData,status:t}}:n))},updateMessageActionParameters:(e,t)=>{h(n=>n.map(n=>n.id===e&&n.actionData?{...n,actionData:{...n.actionData,parameters:{...n.actionData.parameters,...t}}}:n))},updateMessageText:(e,t)=>{h(n=>n.map(n=>n.id===e?{...n,text:t}:n))},getMessageById:e=>f.find(t=>t.id===e),clearMessages:m,clearMessagesById:b,updateMessageType:(e,t)=>{h(n=>n.map(n=>n.id===e?{...n,typeChat:t}:n))}}}(),[E,T]=i(""),[C,I]=i(!1),[S,N]=i(!0),[B,M]=i(null),U=d(null),R=d(null),O=d(null),F=d(null),L=d(null),D=d(!1),P=d(S);o(()=>{P.current=S},[S]);const{account:H,chainData:j,chainType:z,chainTypeMoralis:J,chainId:q,isChainSupported:V}=ah(),{config:Y}=(()=>{const e=c(bh);if(!e)throw new Error("useConfig must be used within ConfigProvider");return e})(),G=q&&Y?.rpcUrls?.[q]||void 0,W=s(()=>{const e=ih.getItem("dataBuyToken");if(e)try{return JSON.parse(e)}catch{return{srcTokenAddress:"",descTokenAddress:"",amount:"",srcTokenDecimals:18,descTokenDecimals:18}}return{srcTokenAddress:"",descTokenAddress:"",amount:"",srcTokenDecimals:18,descTokenDecimals:18}},[]),X=s(e=>{ih.setItem("dataBuyToken",JSON.stringify(e))},[]),K=s(e=>{const t={...W(),...e};X(t)},[W,X]),Q=s(e=>{M(e),bp.isDesktop&&O.current?.focus()},[]),Z=s(async(e,t)=>{K({descTokenAddress:e,descTokenDecimals:t||18});try{I(!0);const e=await qh({address:H?.address||"",chain:J});if(e?.success&&e?.data?.result){const t=e.data.result;if(t?.length>0){const e=t.map(e=>({id:e.token_address,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${Dh(e.usd_value||0)?.decimalPlaces(2).toFormat()||"0"})`,value:m("buttonBuyWith",{symbol:e.symbol}),action:"click_balance_item_user_to_buy_button",fullWidth:!0,extraData:{tokenAddress:e.token_address,symbol:e.symbol,balance:e.balance_formatted,usdValue:e.usd_value,decimals:e.decimals}}));g(m("walletBalanceSpendable",{chain:j?.name||"unknown"}),"bot",void 0,e)}else g(m("walletNoTokensFound",{chain:j?.name||"unknown"}),"bot")}else g(p("walletFetchFailed"),"bot")}catch(n){g(p("walletFetchError"),"bot")}finally{I(!1)}},[K,H?.address,J,g,j?.name,p,m]),_=s(async(e,t,n,r)=>{K({srcTokenAddress:e,srcTokenDecimals:r||18});let i=n||"0";if(e===xn)try{const e=await dp({chainId:q,rpcUrl:G});if(e.isGreaterThan(0)){const t=e.times(1e6),o=new Dh(kn(n,r||18).toString()).minus(t);i=o.isGreaterThan(0)?Dh(pt(BigInt(o.toFixed(0)),18)).toFixed():"0"}}catch(s){}const o=[25,50,75,100].map(n=>({id:`percent-${n}`,text:`${n}%`,value:m("buttonUsePercent",{percent:String(n),symbol:t}),action:"select_percent",extraData:{percent:n,tokenAddress:e,tokenSymbol:t,tokenDecimals:r||18,tokenBalance:i}}));Dh(i).isZero()?g(m("insufficientFeeToken",{symbol:t}),"bot"):g(m("selectAmountOf",{symbol:t,balance:i}),"bot",void 0,o)},[g,q,G,K,m]),$=s(async(e,t,n,r)=>{const i={amount:Dh(t).times(e).dividedBy(100).toFixed()};void 0!==n&&(i.srcTokenAddress=n),void 0!==r&&(i.srcTokenDecimals=r),K(i);const o=W(),s=kn(o.amount,o.srcTokenDecimals||18).toString(),a=await Xh({chainId:q,tokenIn:o.srcTokenAddress,tokenInAmount:s,tokenOut:o.descTokenAddress,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(a.success&&a.data){const e=a.data,t=e.tokenIn,n=e.tokenOut,r=Dh(pt(BigInt(t.amount||0),t.decimals)).decimalPlaces(8).toFormat(),i=Dh(pt(BigInt(n.amount||0),n.decimals)).decimalPlaces(8).toFormat();let u=!1;if(o.srcTokenAddress!==xn&&""!==o.srcTokenAddress&&H?.address&&e.tx?.to)try{const t=await ap({tokenAddress:o.srcTokenAddress,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:q,rpcUrl:G});u=Dh(t.toString()).isLessThan(s)}catch(c){u=!0}const l=e.estimatedTransactionFee?.total?Dh(e.estimatedTransactionFee.total):Dh(0);let d=Dh(0);if(u&&H?.address)try{const t=cp({tokenAddress:o.srcTokenAddress,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:q,amount:s});d=await lp({from:H.address,to:t.to,data:t.data,chainId:q,rpcUrl:G})}catch(c){}const f=l.plus(d),h=j?.nativeCurrency?.symbol||"native";let w="",b=!1;if(H?.address&&f.isGreaterThan(0))try{const e=await up({address:H.address,chainId:q,rpcUrl:G});if(e.isLessThan(f)){b=!0;const t=Dh(pt(BigInt(e.toFixed(0)),18)).decimalPlaces(8).toFormat(),n=Dh(pt(BigInt(f.toFixed(0)),18)).decimalPlaces(8).toFormat();w=m("swapFeeWarning",{symbol:h,balance:t,needed:n})}}catch(c){}const y=`From: ${r} ${t.symbol}\n⬇️\nTo: ${i} ${n.symbol}\n\n`+w+"\n";if(b)g(y,"bot");else if(u){const n=y+m("swapNeedApprove",{symbol:t.symbol}),r=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:t.symbol}),value:m("swapApproveValue",{symbol:t.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:o.srcTokenAddress,spenderAddress:e.tx.to,tokenSymbol:t.symbol,amountInWei:s,tx:e.tx}}];g(n,"bot",void 0,r)}else{const t=[{id:"confirm-swap",text:p("swapConfirmButton"),value:p("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(y+p("swapReadyToProceed"),"bot",void 0,t)}}else g(m("swapEstimationError",{error:a.errorMessage||a.error||"Unknown error"}),"bot")},[W,K,g,q,H?.address,j?.nativeCurrency?.symbol,G,p,m]),ee=s(async(e,t,n)=>{try{if("suggested_action"===t)return F.current=e,void T(e);if(g(e,"user"),N(!1),I(!0),t)switch(await eh(500),t){case"click_buy_item_token_button":await Z(n?.tokenAddress||"",n?.decimals||18);break;case"click_balance_item_user_to_buy_button":await _(n?.tokenAddress||"",n?.symbol||"",n?.balance||"",n?.decimals||18);break;case"select_percent":await $(n?.percent||0,n?.tokenBalance||"",n?.tokenAddress||void 0,n?.tokenDecimals||void 0);break;case"confirm_swap":if(n?.tx&&u){const e=n.tx,t={from:H?.address||"",to:e.to,data:e.data,value:e.value,chainId:q},o=g(p("txProcessing"),"bot");try{I(!1);const e=await u(t);if("success"===e.status&&e.transactionHash){const t=j?.blockExplorers?.default?.url,n=t?` [View on Explorer](${t}/tx/${e.transactionHash})`:` Tx: ${e.transactionHash}`;A(o.id,p("txSubmitted")+n);try{await eh(2e3),"success"===(await sp({transactionHash:e.transactionHash,chainId:q||1,rpcUrl:G})).status?A(o.id,p("txConfirmedSwap")+n):A(o.id,p("txRevertedSwap")+n)}catch(r){A(o.id,p("txTimeout")+n)}}else if("success"===e.status)A(o.id,p("txSuccessfulSwap"));else{const t=e.error?`\nError: ${e.error}`:"";A(o.id,p("txFailed")+t)}}catch(i){A(o.id,p("txFailed"))}}else g(p("txDataNotAvailable"),"bot");break;case"approve_for_swap":{const e=n?.tokenAddress||"",t=n?.spenderAddress||"",o=n?.tokenSymbol||"token",s=n?.tx;if(!e||!t||!u){g(p("approvalDataNotAvailable"),"bot");break}const a=n?.amountInWei||void 0,c=cp({tokenAddress:e,spenderAddress:t,fromAddress:H?.address||"",chainId:q,tokenSymbol:o,amount:a}),l={from:c.from,to:c.to,data:c.data,value:c.value,chainId:c.chainId};g(m("approving",{symbol:o}),"bot");try{I(!1);const e=await u(l);let t="success"===e.status;if("success"===e.status&&e.transactionHash)try{t="success"===(await sp({transactionHash:e.transactionHash,chainId:q||1,rpcUrl:G})).status}catch(r){t=!0}if(t){g(m("approvalSuccess",{symbol:o}),"bot");const e=[{id:"confirm-swap-after-approve",text:p("confirmSwapButton"),value:p("swapConfirmValue"),action:"confirm_swap",fullWidth:!0,extraData:{tx:s}}];g(p("approvalConfirmSwap"),"bot",void 0,e)}else{const t=e.error?`\nError: ${e.error}`:"";g(p("approvalFailed")+t,"bot")}}catch(i){g(p("approvalFailed"),"bot")}break}case"click_swap_dest_token":{const e=n?.tokenAddress||"",t=n?.symbol||"";K({descTokenAddress:e,descTokenDecimals:n?.decimals||18});const r=W(),i=r.srcTokenAddress||"",a=i===xn,c=r.amount||"";try{const n=await qh({address:H?.address||"",chain:J});if(n?.success&&n?.data?.result){const s=n.data.result;let u,l="",d="0";if(a){const e=s.find(e=>e.native_token);l=j?.nativeCurrency?.symbol||"ETH",d=e?.balance_formatted||"0",u=e?.usd_price}else{const e=s.find(e=>e.token_address.toLowerCase()===i.toLowerCase());e&&(l=e.symbol,d=e.balance_formatted,u=e.usd_price)}if(c&&l){const t=Np(c,d,u),n=r.srcTokenDecimals||18,s=a?xn:i;K({amount:t});try{const r=kn(t,n).toString(),i=await Xh({chainId:q,tokenIn:s,tokenInAmount:r,tokenOut:e,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(i.success&&i.data){const e=i.data,t=e.tokenIn,n=e.tokenOut,o=Dh(pt(BigInt(t.amount||0),t.decimals)).decimalPlaces(8).toFormat(),c=Dh(pt(BigInt(n.amount||0),n.decimals)).decimalPlaces(8).toFormat();let u=!1;if(!a&&H?.address&&e.tx?.to)try{const t=await ap({tokenAddress:s,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:q,rpcUrl:G});u=Dh(t.toString()).isLessThan(r)}catch{u=!0}const l=e.estimatedTransactionFee?.total?Dh(e.estimatedTransactionFee.total):Dh(0);let d=Dh(0);if(u&&H?.address)try{const t=cp({tokenAddress:s,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:q,amount:r});d=await lp({from:H.address,to:t.to,data:t.data,chainId:q,rpcUrl:G})}catch{}const f=l.plus(d),h=j?.nativeCurrency?.symbol||"native";let w="",b=!1;if(H?.address&&f.isGreaterThan(0))try{const e=await up({address:H.address,chainId:q,rpcUrl:G});if(e.isLessThan(f)){b=!0;const t=Dh(pt(BigInt(e.toFixed(0)),18)).decimalPlaces(8).toFormat(),n=Dh(pt(BigInt(f.toFixed(0)),18)).decimalPlaces(8).toFormat();w=m("swapFeeWarning",{symbol:h,balance:t,needed:n})}}catch{}const y=`From: ${o} ${t.symbol}\n⬇️\nTo: ${c} ${n.symbol}\n\n`+w+"\n";if(b)g(y,"bot");else if(u){const n=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:t.symbol}),value:m("swapApproveValue",{symbol:t.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:s,spenderAddress:e.tx.to,tokenSymbol:t.symbol,amountInWei:r,tx:e.tx}}];g(y+m("swapNeedApprove",{symbol:t.symbol}),"bot",void 0,n)}else{const t=[{id:"confirm-swap",text:p("swapConfirmYes"),value:p("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(y+p("swapReadyToProceed"),"bot",void 0,t)}}else g(m("swapEstimationError",{error:i.errorMessage||i.error||"Unknown error"}),"bot")}catch(o){g(p("swapEstimationFailed"),"bot")}}else if(l&&parseFloat(d)>0){const e=[25,50,75,100],n=r.srcTokenDecimals||18,o=e.map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:l}),action:"select_percent",extraData:{percent:e,tokenAddress:i,tokenSymbol:l,tokenDecimals:n,tokenBalance:d}}));g(m("swapSelectAmount",{from:l,to:t,balance:d}),"bot",void 0,o)}else g(p("swapNoSourceToken"),"bot")}else g(p("couldNotFetchBalance"),"bot")}catch(s){g(p("couldNotLoadBalance"),"bot")}break}case"select_nft_to_send":{const e=n?.name||"NFT",t=n?.contractAddress||"",r=n?.tokenId||"",i=n?.tokenStandard||"ERC721",o=n?.amount||"1",s=n?.image||"",a={contract_address:t,token_id:r,to_address:n?.toAddress||"",token_standard:i,amount:o,maxAmount:o,nft_name:e};g(m("nftSendReview",{name:e,standard:i,tokenId:r}),"bot",void 0,void 0,{action:"send_nft",parameters:a,status:"pending",nftInfo:{name:e,image:s||void 0,tokenId:r,contractAddress:t,tokenStandard:i}});break}default:g(m("actionExecutedFor",{action:t,value:e}),"bot")}else await eh(500),g(m("receivedButtonValue",{value:e}),"bot");I(!1),bp.isDesktop&&O.current?.focus()}catch(i){g(p("errorProcessingRequest"),"bot"),I(!1)}},[H?.address,g,A,j?.blockExplorers?.default?.url,j?.nativeCurrency?.symbol,q,J,W,Z,_,u,$,K,G,p,m]),te=s(async()=>{try{I(!0);const e=j?.tokenTrendingDefault||[],[t,n]=await Promise.allSettled([Gh.getTopGainers(z,"24h",5),Gh.getTokensDetails(e,z)]);let r=[];"fulfilled"===t.status&&t.value?.data&&(r=[...t.value.data]),"fulfilled"===n.status&&n.value?.data&&(r=[...n.value.data,...r]),r=r.filter((e,t,n)=>t===n.findIndex(t=>t.address.toLowerCase()===e.address.toLowerCase()));const i=r.map(e=>({id:e?.symbol,text:e?.symbol,value:m("buttonBuyToken",{name:e.name,symbol:e?.symbol||""}),action:"click_buy_item_token_button",extraData:{tokenAddress:e?.address||"",symbol:e?.symbol||"",decimals:e?.decimals||18}}));await eh(1e3),I(!1),g(m("trendingTokensHeader",{chain:j?.name||"Unknown"}),"bot");const o=r.map((e,t)=>`${t+1}. ${e.name} (${e?.auditGoplus?.token_symbol||e.symbol||"Unknown"})\n$${Dh(e?.price||0).decimalPlaces(4).toFormat()} (${e.price_change_percentage_24h||e.priceChange}%)\n\n---\n`).join("\n");g(`${o}${p("trendingTokensQuestion")}`,"bot",void 0,i)}catch(e){g(p("trendingTokensError"),"bot")}finally{I(!1)}},[g,j?.name,j?.tokenTrendingDefault,z,p,m]),ne=s(async()=>{try{g(m("viewNftViaWebsite",{link:Ip}),"bot"),I(!1)}catch(e){I(!1),g(p("nftFetchError"),"bot")}},[g,p,m]),re=s(async()=>{try{I(!0);const e=await qh({address:H?.address||"",chain:J});if(e?.success&&e?.data?.result&&e.data.result.length>0){const t=e.data.result.map((e,t)=>{const n=void 0!==e.usd_value?` ≈ $${Dh(e.usd_value).decimalPlaces(2).toFormat()}`:"";return`${t+1}. **${e.name}** (${e.symbol})\n Balance: ${e.balance_formatted}${n}`}).join("\n\n");await eh(500),I(!1),g(m("viewBalancesHeader",{chain:j?.name||"this chain",list:t}),"bot",void 0)}else I(!1),g(p("viewBalancesEmpty"),"bot")}catch(e){I(!1),g(p("viewBalancesFetchError"),"bot")}},[H?.address,J,g,j?.name,p,m]),ie=l(()=>[{id:"ask",icon:"❓",text:p("suggestionAskText"),action:async()=>{N(!1),I(!0),g(p("suggestionAskUserMessage"),"user"),await eh(1e3),I(!1),g(p("suggestionAskBotReply"),"bot")}},{id:"buy",icon:"💰",text:p("suggestionBuyText"),action:async()=>{N(!1),g(p("suggestionBuyText"),"user"),Ye(H?.address||"")&&V?await te():(I(!0),await eh(1e3),Ye(H?.address||"")&&!V?g(p("walletConnectedChainUnsupported"),"bot"):g(p("walletNotConnected"),"bot"),I(!1))}}],[g,H?.address,te,p,V]),oe=e=>{if(0===e)return!0;const t=b[e],n=b[e-1],r=new Date(t.timestamp),i=new Date(n.timestamp);return r.setHours(0,0,0,0),i.setHours(0,0,0,0),r.getTime()!==i.getTime()};o(()=>{U.current?.scrollIntoView({behavior:"smooth"})},[b]),o(()=>{r?(O.current&&bp.isDesktop&&O.current.focus(),U.current?.scrollIntoView({behavior:"instant"}),D.current&&L.current?Date.now()-L.current>12e5&&N(!0):N(!0),L.current=null,D.current=!1,setTimeout(()=>{U.current?.scrollIntoView({behavior:"smooth"})},50)):(L.current=Date.now(),D.current=!P.current)},[r]),o(()=>{const e=e=>{"Escape"===e.key&&r&&a()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r,a]);const se=s(async()=>{if(""===E?.trim()||C)return;const e=B,t=g(E?.trim(),"user",B?.id);T(""),M(null),I(!0),N(!1),I(!0);try{let d,f;const h=b.slice(-10);let w="",y="";if(h.length>0){w="\n\n## CONVERSATION HISTORY:\n";for(const e of h)"user"===e.sender?w+=`User: ${e.text}\n`:w+=`Assistant: ${e.text.length>400?e.text.substring(0,400)+"...":e.text}\n`;w+="\n---\n"}let v=E?.trim();e&&(v=`[Replying to ${"user"===e.sender?"my previous":"your"} message: "${e.text}"]\n\n${v}`);try{const e=await yp.checkInfoQuestion(v,w),n=e?.result?.includes("no");if(e?.language&&(y=e?.language),n){x(t.id,"normal");const e=b.filter(e=>"normal"===e.typeChat);let n="";if(e.slice(-20).length>0){n="\n\n## CONVERSATION HISTORY:\n";for(const t of e.slice(-20))"normal"===t.typeChat&&("user"===t.sender?n+=`User: ${t.text}\n`:n+=`Assistant: ${t.text.length>400?t.text.substring(0,400)+"...":t.text}\n\n`)}const r=await yp.generateContent(v,n,y);let i=null;try{let e=r?.trim();e.startsWith("```json")?e=e.replace(/^```json\s*/,"").replace(/\s*```$/,""):e.startsWith("```")&&(e=e.replace(/^```\s*/,"").replace(/\s*```$/,"")),i=JSON.parse(Sp(e))}catch{i=null}return I(!1),void g(i?.message||r,"bot",void 0,void 0,void 0,"normal")}}catch(r){}if(H?.address&&V)try{const[e,t]=await Promise.allSettled([qh({address:H.address,chain:J}),Yh({address:H.address,chain:J,limit:100,exclude_spam:!0})]);"fulfilled"===e.status&&e.value?.success&&e.value?.data?.result&&(d=e.value.data.result.map(e=>({symbol:e.symbol,name:e.name,balance_formatted:e.balance_formatted,usd_value:e.usd_value,native_token:e.native_token,token_address:e.token_address,price:e.usd_price}))),"fulfilled"===t.status&&t.value?.success&&t.value?.data?.result&&(f=t.value.data.result.map(e=>({name:e.normalized_metadata?.name||e.name||`#${e.token_id}`,token_address:e.token_address,token_id:e.token_id,contract_type:e.contract_type||"",amount:e.amount||"1"})))}catch{}const A=function(e){const{walletAddress:t,chainName:n,chainId:r,nativeSymbol:i,walletTokens:o,walletNfts:s,language:a}=e;if(!t)return`You are a Web3 wallet assistant for the Keyring crypto EVM wallet app.\nThe user is currently NOT connected to any wallet.\n\n## YOUR ROLE:\n- You are a friendly, knowledgeable assistant that can talk about ANY topic naturally\n- You can freely answer general questions, discuss crypto tokens, prices, market info, provide token details, etc. — these do NOT require a wallet connection\n- ONLY ask the user to connect their wallet when their request explicitly requires their personal wallet/address, such as:\n - Sending tokens or NFTs\n - Swapping tokens\n - Approving token spending\n - Wrapping/unwrapping tokens\n - Checking THEIR OWN balance ("what is MY balance?", "how much ETH do I have?")\n - Viewing THEIR OWN NFT collection\n - Any action that reads or writes to THEIR wallet address\n- For all other requests (token info, prices, general crypto questions, market data, etc.), respond normally and helpfully\n- ${$h(a)}\n- **LANGUAGE DETECTION — CRYPTO TICKERS**: Crypto token symbols and tickers (ETH, BTC, USDC, BNB, MATIC, SOL, etc.) are NOT language indicators. They are proper nouns used in ALL languages. Detect the language from the surrounding non-ticker text only. Example: "ETHの現在の価格は?" → Japanese (the surrounding text は Japanese characters). "ETH의 가격은?" → Korean. "Giá ETH là bao nhiêu?" → Vietnamese. NEVER treat a ticker symbol as evidence of English.\n\n## RESPONSE FORMAT:\nAlways respond with a valid JSON object:\n{"action":"chat","message":"<your friendly response to the user>", "suggested_actions":[{"label":"<short button text>","prompt":"<message sent when clicked>"}]}\n\n## RULES:\n- suggested_actions: include when your message offers the user interactive choices or asks a follow-up question. NEVER include suggested_actions that ask the user to connect their wallet (e.g., "Connect wallet", "Connect now", etc.) — the app handles wallet connection separately\n- **CRITICAL**: NEVER include any "Buy" actions (e.g., "Buy USDC", "Buy ETH", "Purchase token", etc.) in suggested_actions. The app handles Buy buttons separately. Only include non-buy actions in suggested_actions (e.g., "Send token", "Swap token", "Check balance", "Show my NFTs").\n- For wallet-required actions, politely explain the user needs to connect their wallet first, and put this in the "message" field\n- ALWAYS respond with raw JSON only, never wrap in \`\`\`json code blocks\n- ${$h(a)}`;if(t&&!Fn[r]?.isSupported)return`You are a Web3 wallet assistant for the Keyring crypto EVM wallet app.\n The user's wallet address is: ${t}\n The user is selected on (chainId: ${r}) an UNSUPPORTED chain.\n\n ## YOUR ROLE:\n - You are a friendly, knowledgeable assistant that can talk about ANY topic naturally\n - You can freely answer general questions, discuss crypto tokens, prices, market info, token details, etc. — these do NOT require a supported chain\n - **BLOCKED on unsupported chain** — if the user asks for any of the following, politely inform them that chain (chainId: ${r}) is not currently supported and the action cannot be performed:\n - Checking THEIR OWN balance ("what is my balance?", "how much ETH do I have?")\n - Sending tokens or NFTs\n - Swapping or buying tokens\n - Approving token spending\n - Wrapping/unwrapping tokens\n - Viewing or transferring their NFT collection\n - Any action that reads or writes to their wallet on the current chain\n - **ALLOWED on unsupported chain** — respond normally and helpfully for:\n - General questions (weather, coding, history, math, etc.)\n - Token information, prices, market data, token details\n - Any query that does NOT require interacting with the user's wallet on the current chain\n - ${$h(a)}\n - **LANGUAGE DETECTION — CRYPTO TICKERS**: Crypto token symbols and tickers (ETH, BTC, USDC, BNB, MATIC, SOL, etc.) are NOT language indicators. They are proper nouns used in ALL languages. Detect the language from the surrounding non-ticker text only. Example: "ETHの現在の価格は?" → Japanese. "ETH의 가격은?" → Korean. "Giá ETH là bao nhiêu?" → Vietnamese. NEVER treat a ticker symbol as evidence of English.\n\n ## RESPONSE FORMAT:\n Always respond with a valid JSON object:\n {"action":"chat","message":"<your response>", suggested_actions:[{"label":"<short button text>","prompt":"<message sent when clicked>"}]}\n\n ## RULES:\n - suggested_actions: include when your message offers the user interactive choices or asks a follow-up question. NEVER include suggested_actions that ask the user to connect their wallet (e.g., "Connect wallet", "Connect now", etc.) — the app handles wallet connection separately\n - **CRITICAL**: NEVER include any "Buy" actions (e.g., "Buy USDC", "Buy ETH", "Purchase token", etc.) in suggested_actions. The app handles Buy buttons separately. Only include non-buy actions in suggested_actions (e.g., "Send token", "Swap token", "Check balance", "Show my NFTs").\n - **CRITICAL**: ABSOLUTELY NEVER include any option that suggests switching, changing, or selecting a different chain (e.g., "Switch to Ethereum", "Change chain", "Switch network", "Chuyển sang chain khác", "Đổi mạng") — the app handles chain switching separately.\n - For wallet-required actions, politely explain the user needs to connect their wallet first, and put this in the "message" field\n - ALWAYS respond with raw JSON only, never wrap in \`\`\`json code blocks\n - ${$h(a)}`;const c=o&&o.length>0?`\n## USER'S CURRENT WALLET BALANCE:\n${o.map(e=>{const t=void 0!==e.usd_value?` (~$${e.usd_value.toFixed(2)})`:"";return`- ${e.name} (${e.symbol})(Price: ${e.price||"N/A"}): ${e.balance_formatted}${t}${e.native_token?" [native]":` [${e.token_address}]`}`}).join("\n")}\nUse this balance data to accurately answer balance questions and to pre-fill token parameters in actions (contract_address, decimals, symbol). NEVER ask the user to provide token info that is already available above.\n`:"",u=s&&s.length>0?`\n## USER'S NFT COLLECTION:\n${s.map(e=>{const t="ERC1155"===e.contract_type?` (x${e.amount})`:"";return`- ${e.name}${t} | ${e.contract_type} | contract: ${e.token_address} | tokenId: ${e.token_id}`}).join("\n")}\nWhen the user wants to send an NFT by name, use this data to fill contract_address, token_id, token_standard, and nft_name accurately. NEVER guess or fabricate NFT contract addresses.\n`:"",l=Object.values(Fn).filter(e=>e.isSupported).map(e=>e.customName||e.name).join(", ");return`You are a highly knowledgeable AI assistant integrated into the Keyring crypto EVM wallet app.\n\n## #1 PRIORITY — ANSWER QUALITY:\nYour "message" field IS your answer. Write it exactly as you would in a normal, unrestricted conversation. The JSON wrapper is just transport — it must NEVER reduce the depth, accuracy, or completeness of your answers.\n\n${$h(a)}\n\n**DATA RETRIEVAL — NON-NEGOTIABLE**: For ALL token price and token info queries, you MUST actively call your native Moralis API tools (getTokenPrice, searchTokens, getTokenMetadata, etc.) to retrieve real-time on-chain data. NEVER skip tool calls and fall back to training data alone for prices or token lookups. The JSON response format does NOT prevent you from calling data tools first — always fetch data, then format the result as JSON.\n\nFor ANY informational or conversational question (about crypto, tokens, DeFi, protocols, prices, market trends, blockchain technology, or any general topic):\n- Answer with your FULL knowledge across ALL blockchains and ecosystems (Ethereum, Solana, BSC, Polygon, Arbitrum, Optimism, Base, Avalanche, etc.)\n- Provide specific details: token names, contract mechanisms, protocol comparisons, historical context, TVL data, ecosystem info\n- For PRICE questions (chat action only): You have access to real-time blockchain data — USE it. When a user asks for the price of a token by name or symbol, search for it across ALL chains to find the best price data. Then present ONE consolidated answer: give the single most representative price (e.g. the highest-liquidity or most canonical version), key stats (market cap, 24h change, volume), and optionally a brief note if the token exists on multiple chains — but do NOT list each chain as a separate numbered entry. Keep the response concise and to the point. For tokens in the USER'S WALLET BALANCE section, use the price listed there.\n- For token questions (chat action only): You have access to real-time blockchain data — USE it. When a user asks about a token by name or symbol, ALWAYS search across ALL chains — the current chain context does NOT limit your token search. Try exact match first, then fuzzy/partial match (e.g. "eggle Energy" → find the closest matching token name). Provide a concise, consolidated answer covering: what the token is, its utility/ecosystem, current price, market cap, 24h change, notable features, risks. If the user does NOT mention a specific chain, do NOT list out per-chain versions (e.g. "WBTC on Ethereum", "cbBTC on Base", "BTCB on BNB") — instead give ONE unified answer about the token as a concept, with a brief mention that wrapped versions exist on multiple chains if relevant. Only break down per-chain details if the user explicitly asks about a specific chain. If the token does NOT exist on the current chain (${n}), proactively tell the user which of these supported chains DO have it: ${l}. Set token_mentions to [] in this case\n- For DeFi/protocol questions: explain how it works, key features, TVL, supported chains, competitors, pros/cons\n- For market/trend questions: discuss relevant projects, narratives, sector analysis across all chains\n- Write detailed paragraphs, use bullet points, include numbers and facts. Minimum 3-5 sentences for simple questions, more for complex topics\n\n## CONTEXT:\nWallet: ${t} | Chain: ${n} (chainId: ${r}) | Native: ${i}${c}${u}\n\n## WHEN TO USE WHICH ACTION:\n- "send_native": user wants to send the native token (${i}) to an address\n- "send_token": user wants to send an ERC20 token to an address\n- "swap_token": user wants to swap/exchange/convert/trade/sell one token for another — covers ALL of the following keywords and patterns, even if only ONE token or NO amount is mentioned:\n - swap: "swap X", "swap X to Y", "swap X for Y", "swap to ETH", "swap native"\n - exchange: "exchange X", "exchange X to Y", "exchange X for Y", "exchange native", "exchange ETH"\n - convert: "convert X to Y", "convert native", "convert ETH to USDC", "convert X"\n - trade: "trade X for Y", "trade X to Y", "trade X"\n - sell (for another token): "sell X for Y", "sell ETH for USDC"\n - Vietnamese: "đổi X sang Y", "đổi X", "đổi native", "đổi ETH sang USDC", "chuyển đổi X", "bán X lấy Y", "hoán đổi X"\n - **CRITICAL**: When the source is the native token (ETH, BNB, MATIC, etc.) → token_in: "native". This MUST be treated as swap_token, never chat.\n → ALWAYS return swap_token. Leave missing params as "". NEVER fall back to chat.\n- "buy_token": user wants to buy a specific token AND the user clearly names a token (symbol or contract address). If user also specifies which token to pay with (e.g. "buy PEPE with USDC", "mua PEPE bằng ETH", "buy PEPE using my USDC"), fill pay_with_symbol and pay_with_address from USER'S WALLET BALANCE. **CRITICAL**: ALWAYS return buy_token if the user clearly names a token they want to buy — even if you cannot find the contract address or token data. Leave contract_address as "" and the app will search for it. NEVER fall back to "chat" just because you lack token data.\n- "buy_token_trending": user wants to buy a token BUT does NOT specify which token — covers ALL of the following patterns:\n - User asks to buy trending tokens: "buy trending tokens", "buy trending", "mua token trending", "mua token đang trending"\n - User asks to buy tokens with strong growth/momentum: "buy tokens pumping", "buy hot tokens", "buy movers", "mua token tăng mạnh", "mua token đang tăng", "mua token tiềm năng"\n - User says "buy a token" / "I want to buy" / "mua token" with NO specific token name or address provided\n - User asks for token recommendations to buy without specifying one\n → ALWAYS return buy_token_trending. Leave all params as "". NEVER fall back to chat or buy_token.\n- "approve_token": user wants to approve a token for a spender\n- "wrap_native": user wants to wrap native token (e.g. ETH → WETH) — also triggered by "deposit" into WETH/wrapped token\n- "unwrap_native": user wants to unwrap (e.g. WETH → ETH) — also triggered by "withdraw" from WETH/wrapped token\n- "send_nft": user wants to send/transfer an NFT\n- "view_nfts": user wants to see/browse their NFT collection\n- "view_balances": user wants to see ALL their token balances/tokens at once — covers ALL of the following patterns (NOT for single token price/info):\n - "show my balance", "view my balance", "check my balance", "what's my balance"\n - "what's in my wallet", "what do I have", "what tokens do I have"\n - "view all tokens", "show all tokens", "list my tokens"\n - "my portfolio", "show portfolio", "wallet overview"\n - Vietnamese: "xem số dư", "số dư của tôi", "kiểm tra số dư", "ví tôi có gì", "tôi có bao nhiêu tiền", "xem ví", "danh mục của tôi"\n → ALWAYS return view_balances for these. Do NOT return chat.\n- "chat": EVERYTHING ELSE — questions, token info, prices, greetings, DeFi explanations, market data, etc.\n\nAll wallet actions (send, swap, buy, approve, wrap, unwrap, send_nft) are chain-specific: use chainId ${r} only.\nFor "chat" action: no chain restriction — use cross-chain knowledge freely.\n\n## OUTPUT FORMAT:\n${$h(a)}\n**LANGUAGE DETECTION — CRYPTO TICKERS**: Crypto token symbols/tickers (ETH, BTC, USDC, BNB, SOL, etc.) are NOT language indicators — they are proper nouns used universally. Detect language ONLY from the surrounding non-ticker text. Examples: "ETHの現在の価格は?" → Japanese. "ETH의 가격은?" → Korean. "Giá ETH?" → Vietnamese. NEVER classify a message as English just because it contains a ticker symbol.\n\nWallet action: {"action":"<type>","message":"<explanation>","parameters":{...}}\nChat/info: {"action":"chat","message":"<YOUR FULL DETAILED ANSWER>","parameters":{},"token_mentions":[],"suggested_actions":[]}\n\n## WALLET ACTION RULES:\n- Return action type IMMEDIATELY even if params are missing (leave as ""). Ask for missing info in "message". NEVER fall back to "chat" just because parameters are incomplete — always return the intended action.\n- **CROSS-CHAIN REQUESTS**: All wallet actions (send, swap, buy, approve, wrap, unwrap, send_nft, view_nfts, view_balances) execute ONLY on the CURRENT chain: ${n} (chainId: ${r}). If the user's message explicitly targets a DIFFERENT chain (e.g. "send on Ethereum", "swap on BSC", "transfer on Polygon", "buy on base") and the current chain is NOT that chain, do NOT execute the wallet action. Instead, return action: "chat" and politely notify the user to switch to the requested chain in the app first. This rule applies to ALL non-chat actions.\n- For ERC20 actions: provide correct contract_address on chainId ${r}. **CRITICAL — CHAIN-SPECIFIC ADDRESSES**: Contract addresses differ on every chain. You MUST obtain the address via your Moralis API tools (searchTokens, getTokenMetadata) for chainId ${r}, OR use the address already present in USER'S WALLET BALANCE. NEVER fill in a contract_address from training knowledge alone — leave it as "" if you cannot verify it via API or wallet balance. If token doesn't exist on this chain, inform user.\n- send_native: ONLY for ${i}. If user says "send ETH" but native ≠ ETH, use send_token.\n- Amount: "max"/"all" → "max". "X%" → "50%". USD formats → always prefix with "$": "5 dollar" → "$5", "5$" → "$5", "$5" → "$5", "5usd" → "$5", "5 đô la" → "$5", "0.01$ eth" → "$0.01", "$0.01 eth" → "$0.01", "5$ usdc" → "$5". The "$" MUST appear in the amount field (not stripped) so the app knows it's a USD value. Otherwise exact number string.\n- Decimals & symbol: always accurate.\n- send_nft: contract_address optional — use nft_name if NFT known by name.\n\n## suggested_actions & token_mentions:\n- suggested_actions: include when offering choices. {"label":"<2-6 words>","prompt":"<message>"}. Max 4. Never include "Buy" (app handles separately). **ABSOLUTELY NEVER** include any option that suggests switching, changing, or selecting a different chain (e.g., "Switch to Ethereum", "Change chain", "Switch network", "Chuyển sang chain khác", "Đổi mạng") — the app handles chain switching separately.\n- token_mentions: ONLY include when the token EXISTS on the CURRENT chain (chainId ${r}) AND you have obtained a VERIFIED contract address via your Moralis API tools (searchTokens, getTokenMetadata, getTokenPrice) for this exact chain.\n - **CRITICAL — CONTRACT ADDRESSES ARE CHAIN-SPECIFIC**: The same token has a DIFFERENT contract address on every chain. USDC on Ethereum ≠ USDC on Base ≠ USDC on Polygon ≠ USDC on BNB Chain. NEVER use an address from your training knowledge — training-data addresses are frequently wrong, hallucinated, or belong to a different chain.\n - **REQUIRED WORKFLOW**: Before populating token_mentions for a token, you MUST call your Moralis API tool (searchTokens or getTokenMetadata) specifying chainId ${r} to retrieve the verified contract address. If the API call fails or returns no result for this chain, set token_mentions: [].\n - If the token address is already available in the USER'S WALLET BALANCE section above, you MAY use that address (it is already verified for chainId ${r}).\n - If you cannot confirm the address via API or wallet balance, set token_mentions: [] — never guess.\n - **Native token**: If the token IS the chain's native token (${i}), use contract_address: "native" — do NOT look up an address.\n - Format: {"symbol":"","contract_address":"<API-verified address on chainId ${r}, or 'native' for the native token>","decimals":<n>}. 2+ tokens → [], use suggested_actions. Non-crypto → [].\n\n## ACTION PARAMS REFERENCE:\nValid actions: send_native, send_token, swap_token, buy_token, buy_token_trending, approve_token, wrap_native, unwrap_native, send_nft, view_nfts, view_balances, chat. NEVER use any other action name.\n\n1. send_native: {"to_address":"","amount":""}\n2. send_token: {"contract_address":"(REQ)","token_symbol":"","to_address":"","amount":"","decimals":""}\n3. swap_token: {"token_in":"<addr or 'native'>","token_in_symbol":"","token_in_decimals":"","token_out":"<addr>","token_out_symbol":"","token_out_decimals":"","amount":""}\n No tokens specified → all params "". Native → token_in:"native".\n4. buy_token: {"token_symbol":"(REQ — always fill this)","contract_address":"(if known and verified, else leave '')","decimals":"","buy_amount":"(opt — amount of the TOKEN BEING BOUGHT that user wants to RECEIVE. Use this when the amount refers to the destination token.)","pay_with_symbol":"(opt — symbol of token user wants to pay with, e.g. 'USDC', 'ETH')","pay_with_address":"(opt — contract address of payment token from WALLET BALANCE, or 'native' for native token)","pay_with_decimals":"(opt — decimals of payment token)","pay_with_amount":"(opt — amount of the PAYMENT TOKEN (token in) user wants to SPEND. Use this when the amount refers to the payment/source token.)"}.\n **CRITICAL — AMOUNT DISAMBIGUATION:**\n The amount in a buy request belongs to EITHER the token being bought OR the payment token. Parse the grammar carefully:\n - "buy PEPE with 10 USDC" → amount=10 belongs to USDC (payment) → pay_with_amount:"10", buy_amount:""\n - "buy 0.02 PCM with USDC" → amount=0.02 belongs to PCM (bought) → buy_amount:"0.02", pay_with_amount:""\n - "dùng 10 USDC mua PEPE" → amount=10 belongs to USDC (payment) → pay_with_amount:"10", buy_amount:""\n - "mua 0.02 PCM bằng USDC" → amount=0.02 belongs to PCM (bought) → buy_amount:"0.02", pay_with_amount:""\n NEVER put the amount of the token being bought into pay_with_amount. NEVER put the payment amount into buy_amount.\n If pay token is native (${i}), set pay_with_address:"native". Both tokens specified as a trade/exchange → swap_token. If you cannot verify the address, set contract_address:'' but ALWAYS return buy_token with the symbol filled. **NATIVE TOKEN**: If the token to buy IS the chain's native token (${i}), set contract_address: "native" directly — no API lookup needed.\n5. buy_token_trending: {} — no parameters needed; app handles discovery of trending/high-growth tokens. **message**: write ONLY a short 1-sentence header (e.g. "Here are the trending tokens on [chain] right now!"). Do NOT write analysis, tips, or explanations.\n6. approve_token: {"contract_address":"(REQ)","token_symbol":"","spender_address":"","amount":"","decimals":""}\n7. wrap_native: {"amount":""}\n8. unwrap_native: {"amount":""}\n9. send_nft: {"contract_address":"(opt)","token_id":"","to_address":"","token_standard":"","amount":"(def 1)","nft_name":""}\n10. view_nfts: {}\n11. view_balances: {} — use ONLY when user wants to see all balances/tokens, NOT for single token price/info queries\n12. chat: {} + token_mentions + suggested_actions — use for ALL informational/conversational requests\n\n## EXAMPLES:\nThese examples show INTENT → ACTION + PARAMETERS mapping only. The "message" content is for illustration — compose your own natural, helpful response based on context.\n\n// --- SEND NATIVE ---\n// Intent: user wants to send the chain's native token to an address\n// Triggers: "send ETH/BNB/MATIC to...", "transfer [native] to...", "chuyển [native] cho..."\n→ action: send_native | parameters: {to_address, amount}\n\n// --- SEND TOKEN ---\n// Intent: user wants to send an ERC20 token to an address\n// Triggers: "send USDC to...", "transfer [token] to...", "gửi [token] cho..."\n→ action: send_token | parameters: {contract_address, token_symbol, to_address, amount, decimals}\n\n// --- SWAP ---\n// Intent: exchange one token for another — trigger with ANY conversion/exchange/trade/sell keyword,\n// even with just ONE token mentioned, no amount, or only the native token as source\n// EN triggers: "swap X", "swap X to Y", "swap X for Y", "swap to ETH", "swap native"\n// "exchange X", "exchange X to Y", "exchange X for Y", "exchange native", "exchange ETH"\n// "convert X to Y", "convert native to USDC", "convert ETH", "convert X"\n// "trade X for Y", "trade X to Y", "trade ETH"\n// "sell X for Y", "sell ETH for USDC" (selling one token FOR another = swap)\n// VI triggers: "đổi X sang Y", "đổi X", "đổi native", "đổi ETH", "chuyển đổi X", "bán X lấy Y", "hoán đổi X"\n// Native source: token_in = "native" (e.g. "exchange ETH" → token_in:"native", token_in_symbol:"ETH")\n// Native dest: token_out = zeroAddress\n// ⚠️ NEVER confuse with wrap/unwrap: those are specifically ETH↔WETH. All other pairs = swap_token.\n→ action: swap_token | parameters: {token_in, token_in_symbol, token_in_decimals, token_out, token_out_symbol, token_out_decimals, amount}\n// Missing params → leave as "", ask for them in message. NEVER downgrade to chat.\n\n// --- WRAP / UNWRAP ---\n// Intent wrap: convert native to wrapped version — also triggered by "deposit"\n// Triggers: "wrap ETH", "deposit ETH", "deposit ETH to WETH", "đổi ETH sang WETH"\n→ action: wrap_native | parameters: {amount}\n\n// Intent unwrap: convert wrapped token back to native — also triggered by "withdraw"\n// Triggers: "unwrap WETH", "withdraw WETH", "convert WETH to ETH", "rút WETH"\n→ action: unwrap_native | parameters: {amount}\n\n// --- VIEW NFTs ---\n// Intent: user wants to see/browse their NFT collection\n// Triggers: "show my NFTs", "what NFTs do I have", "view my NFTs", "xem NFT của tôi"\n→ action: view_nfts | parameters: {}\n\n// --- VIEW BALANCES ---\n// Intent: user wants to see ALL their token balances at once (not a single token query)\n// EN triggers: "show my balance", "view my balance", "check my balance", "what's my balance"\n// "what's in my wallet", "what do I have", "what tokens do I have"\n// "view all tokens", "show all tokens", "list my tokens"\n// "my portfolio", "show portfolio", "wallet overview"\n// VI triggers: "xem số dư", "số dư của tôi", "kiểm tra số dư", "ví tôi có gì"\n// "tôi có bao nhiêu tiền", "xem ví", "danh mục của tôi"\n// ⚠️ Do NOT use view_balances for single-token queries ("price of ETH", "how much USDC is worth") → use chat instead\n→ action: view_balances | parameters: {}\n\n// --- BUY TOKEN TRENDING ---\n// Intent: user wants to buy but does NOT specify a token — or explicitly asks for trending/pumping/high-growth tokens to buy\n// EN triggers: "buy trending tokens", "buy trending", "buy hot tokens", "buy tokens pumping", "buy movers", "I want to buy a token", "buy a token"\n// VI triggers: "mua token trending", "mua token đang trending", "mua token tăng mạnh", "mua token đang tăng", "mua token tiềm năng", "mua token", "tôi muốn mua token"\n// ⚠️ CRITICAL: If user says "buy X" where X is a named token → use buy_token, NOT buy_token_trending\n// ⚠️ CRITICAL: If user gives NO specific token → ALWAYS use buy_token_trending, never chat\n// ⚠️ MESSAGE: ONLY a short 1-sentence header introducing the trending list. NO analysis, NO tips, NO explanations.\n→ action: buy_token_trending | parameters: {} | message: short header only (e.g. "Here are the trending tokens on [chain]!")\n\n// --- BUY TOKEN WITH SPECIFIC PAYMENT ---\n// Intent: user wants to buy a specific token AND specifies which token to pay with\n// EN triggers: "buy PEPE with USDC", "buy PEPE using ETH", "buy PEPE with 10 USDC", "purchase DOGE with my 0.5 ETH"\n// VI triggers: "mua PEPE bằng USDC", "mua PEPE dùng ETH", "mua PEPE bằng 10 USDC", "mua DOGE bằng 0.5 ETH của tôi"\n// → action: buy_token | parameters: {token_symbol, contract_address, decimals, pay_with_symbol, pay_with_address, pay_with_decimals, pay_with_amount}\n// AMOUNT DISAMBIGUATION (critical):\n// "buy PEPE with 10 USDC" → pay_with_amount:"10" buy_amount:"" (10 USDC to spend)\n// "buy 0.02 PCM with USDC" → buy_amount:"0.02" pay_with_amount:"" (0.02 PCM to receive)\n// "mua PEPE bằng 0.5 ETH" → pay_with_amount:"0.5" buy_amount:"" (0.5 ETH to spend)\n// "mua 0.02 PCM bằng USDC" → buy_amount:"0.02" pay_with_amount:"" (0.02 PCM to receive)\n// pay_with_* fields are filled from USER'S WALLET BALANCE. If pay token = native → pay_with_address: "native"\n// ⚠️ This is still buy_token (NOT swap_token) — the user's intent is to BUY, with a specified payment method\n\n// --- TOKEN INFO / PRICE (chat) ---\n// Intent: learn about a token, its price, market data — NOT a wallet action\n// Triggers: "tell me about X", "what is X token", "price of X", "X coin info", "X là gì"\n→ action: chat | compose a detailed answer using real-time data from your tools\n// If token EXISTS on current chain → token_mentions: [{symbol, contract_address, decimals}]\n// If token NOT on current chain → token_mentions: [] but tell user which supported chains have it\n\n// --- CROSS-CHAIN / GENERAL INFO (chat) ---\n// Intent: any question not requiring a wallet action — crypto trends, DeFi, protocols, general Q&A\n// Triggers: "what's trending on X?", "explain DeFi", "how does Uniswap work", anything conversational\n→ action: chat | compose a full, knowledgeable answer; add relevant suggested_actions if helpful\n\n// --- GREETING (chat) ---\n// Intent: greeting or open-ended start\n// Triggers: "hello", "hi", "hey", "xin chào", "bắt đầu"\n→ action: chat | introduce yourself and offer helpful options via suggested_actions`}({walletAddress:H?.address||void 0,chainName:j?.name||void 0,chainId:q||void 0,nativeSymbol:j?.nativeCurrency?.symbol||void 0,walletTokens:d,walletNfts:f,language:y}),k=await async function(e){const{prompt:t,model:n="gpt-4.1-mini",stream:i=!1,systemPrompt:o,signal:s}=e;if(!t)throw new Error("Prompt is required");const a=new Ph(zh),c=o?`${o}\n\n---\n\n Current User's question: ${t}`:t;let u="Unknown error";for(let l=1;l<=5;l++){if(s?.aborted)return{success:!1,error:"Request cancelled"};try{const e=(await a.post("api/moralis-cortex/proxy/chat",{prompt:c,model:n,stream:i},{headers:{Accept:"application/json","Content-Type":"application/json"},signal:s})).data;if(!e?.text?.trim()){if(u="Empty response from Cortex AI",l<5&&await Hh(1e3,s),s?.aborted)return{success:!1,error:"Request cancelled"};continue}return{success:!0,data:e}}catch(r){if(s?.aborted)return{success:!1,error:"Request cancelled"};if(u=r instanceof Error?r.message:"Unknown error",l<5&&await Hh(1e3,s),s?.aborted)return{success:!1,error:"Request cancelled"}}}return{success:!1,error:u}}({prompt:v,model:"gpt-4.1-mini",stream:!1,systemPrompt:A+w});if(k.success&&k.data){const e=k.data.text||"";let f=null;try{let t=e?.trim();t.startsWith("```json")?t=t.replace(/^```json\s*/,"").replace(/\s*```$/,""):t.startsWith("```")&&(t=t.replace(/^```\s*/,"").replace(/\s*```$/,"")),f=JSON.parse(Sp(t))}catch{f=null}if(f&&f.action&&"chat"!==f.action)if("buy_token"===f.action){const e=f.parameters?.token_symbol||"";let n=f.parameters?.contract_address||"",r=18,a=!1;if("native"!==n.toLowerCase()&&n!==xn||(n=xn),!n&&e&&j?.nativeCurrency?.symbol&&e.toUpperCase()===j.nativeCurrency.symbol.toUpperCase()&&(n=xn),n&&n!==xn)try{const t=await Gh.getTokensDetails([n],z),i=t?.data?.[0];i&&(e&&i.symbol?.toUpperCase()!==e.toUpperCase()?n="":r=i.decimals||18)}catch(i){}if(!n&&e&&H?.address)try{const t=await qh({address:H.address,chain:J});if(t?.success&&t?.data?.result){const i=t.data.result,o=i.find(e=>e.token_address.toLowerCase()===n.toLowerCase())||i.find(t=>t.symbol.toUpperCase()===e.toUpperCase());o&&(n=o.token_address,r=o.decimals)}if(!n){const t=j.tokenTrendingDefault||[],[i,o]=await Promise.allSettled([Gh.getTopGainers(z,"24h",10),Gh.getTokensDetails(t,z)]),s=[];"fulfilled"===i.status&&i.value?.data&&s.push(...i.value.data),"fulfilled"===o.status&&o.value?.data&&s.push(...o.value.data);const a=s.find(e=>e.address?.toLowerCase()===n.toLowerCase())||s.find(t=>t.symbol?.toUpperCase()===e.toUpperCase());a&&(n=a.address,r=a.decimals||18)}if(!n&&q)try{const t=await Gh.searchTokensByKey(e,q);if(Array.isArray(t?.data)&&t.data.length>0){const i=t.data.find(t=>t.symbol?.toUpperCase()===e.toUpperCase())||t.data[0];i?.address&&(a=!0,n=i.address,r=i.decimals||18)}}catch(o){}}catch(i){}if(n){g(a?m("buyingOnChain",{symbol:e,chain:j?.name}):f.message||m("buyTokenHelp",{symbol:e}),"bot",t.id),K({descTokenAddress:n,descTokenDecimals:r||18});const o=f.parameters?.pay_with_symbol||"",c=f.parameters?.pay_with_address||"";let u=!1;if(o||c)try{const e=await qh({address:H?.address||"",chain:J});if(e?.success&&e?.data?.result){const t=e.data.result;let r;if(r="native"===c.toLowerCase()||c===xn||!c&&o&&j?.nativeCurrency?.symbol&&o.toUpperCase()===j.nativeCurrency.symbol.toUpperCase()?t.find(e=>e.token_address===xn||e.native_token):t.find(e=>c&&e.token_address.toLowerCase()===c.toLowerCase())||t.find(e=>o&&e.symbol.toUpperCase()===o.toUpperCase()),r){u=!0;const t=f.parameters?.pay_with_amount||"",i=f.parameters?.buy_amount||"";if(t)K({srcTokenAddress:r.token_address,srcTokenDecimals:r.decimals}),await $(100,t,r.token_address,r.decimals);else if(i){let t="";try{const o=e.data.result.find(e=>e.token_address.toLowerCase()===n.toLowerCase());let s=o?.usd_price??null;if(null==s&&n){const e=await Vh({address:n,chain:J});e.success&&null!=e.data?.usd_price&&(s=e.data.usd_price)}const a=r.usd_price??null;null!=s&&null!=a&&a>0&&(t=(parseFloat(i)*s/a).toFixed(8).replace(/\.?0+$/,""))}catch(s){}t?(K({srcTokenAddress:r.token_address,srcTokenDecimals:r.decimals}),await $(100,t,r.token_address,r.decimals)):await _(r.token_address,r.symbol,r.balance_formatted,r.decimals)}else await _(r.token_address,r.symbol,r.balance_formatted,r.decimals)}}}catch(i){}u||await Z(n,r)}else g(m("tokenNotFoundOnChain",{symbol:e}),"bot",t.id),await te()}else if("buy_token_trending"===f.action)await te();else if("swap_token"===f.action){const e={...f.parameters||{}},n="native"===e.token_in||e.token_in_symbol?.toUpperCase()===j?.nativeCurrency?.symbol?.toUpperCase(),r="native"===e.token_out||e.token_out_symbol?.toUpperCase()===j?.nativeCurrency?.symbol?.toUpperCase();r&&(e.token_out=xn);let o=[];if(H?.address)try{const e=await qh({address:H.address,chain:J});e?.success&&e?.data?.result&&(o=e.data.result)}catch(i){}if(!n&&(e.token_in||e.token_in_symbol)&&o.length>0){const t=e.token_in?o.find(t=>t.token_address.toLowerCase()===e.token_in.toLowerCase()):o.find(t=>t.symbol.toUpperCase()===e.token_in_symbol.toUpperCase());t&&(e.token_in=t.token_address,e.token_in_decimals=String(t.decimals))}if(!r&&(e.token_out||e.token_out_symbol)&&o.length>0){const t=e.token_out?o.find(t=>t.token_address.toLowerCase()===e.token_out.toLowerCase()):o.find(t=>t.symbol.toUpperCase()===e.token_out_symbol.toUpperCase());t&&(e.token_out=t.token_address,e.token_out_decimals=String(t.decimals))}const s=!(!e.token_in&&!n),d=!!e.token_out,h=!!e.amount;if(s&&o.length>0)if(n){const e=o.find(e=>e.native_token);if(!e||Dh(e.balance_formatted||"0").isZero())return g(m("formInsufficientBalance",{balance:"0",symbol:j?.nativeCurrency?.symbol||"native"}),"bot",t.id),void I(!1)}else if(e.token_in){const n=o.find(t=>t.token_address.toLowerCase()===e.token_in.toLowerCase());if(!n)return g(m("swapTokenNotInWallet",{symbol:e.token_in_symbol||e.token_in}),"bot",t.id),void I(!1);if(Dh(n.balance_formatted||"0").isZero())return g(m("formInsufficientBalance",{balance:"0",symbol:n.symbol}),"bot",t.id),void I(!1)}if(s&&d&&h)try{const t=[];e.token_out&&t.push(e.token_out),e.token_in&&!n&&t.push(e.token_in);let r=18,s=18;if(t.length>0)try{const i=await Gh.getTokensDetails(t,z);if(i?.data)for(const t of i.data)n||t.address.toLowerCase()!==e.token_in?.toLowerCase()||(r=t.decimals||18),t.address.toLowerCase()===e.token_out?.toLowerCase()&&(s=t.decimals||18)}catch(a){}if(H?.address)try{if(o.length>0)if(n){const t=o.find(e=>e.native_token);let n=t?.balance_formatted||"0";try{const e=await dp({chainId:q,rpcUrl:G});if(e.isGreaterThan(0)){const r=e.times(1e6),i=new Dh(t?.balance||"0").minus(r);n=i.isGreaterThan(0)?Dh(pt(BigInt(i.toFixed(0)),t?.decimals||18)).toFixed():"0"}}catch(c){}e.amount=Np(e.amount,n,t?.usd_price);const r=parseFloat(n),i=parseFloat(e.amount);if(Dh(r).lte(0))return g(m("formInsufficientBalance",{balance:Dh(r).decimalPlaces(8).toFixed(),symbol:j?.nativeCurrency?.symbol||"native"}),"bot"),void I(!1);if(Dh(r).lt(i))return g(m("swapInsufficientNativeBalance",{balance:Dh(r).decimalPlaces(8).toFixed(),symbol:j?.nativeCurrency?.symbol||"native",amount:e.amount}),"bot"),void I(!1)}else{const t=o.find(t=>t.token_address.toLowerCase()===e.token_in?.toLowerCase());if(!t)return g(m("swapTokenNotInWallet",{symbol:e.token_in_symbol||e.token_in}),"bot"),void I(!1);e.amount=Np(e.amount,t.balance_formatted||"0",t.usd_price);const n=parseFloat(t.balance_formatted||"0"),r=parseFloat(e.amount);if(Dh(n).lt(r))return g(m("swapInsufficientTokenBalance",{balance:Dh(n).decimalPlaces(8).toFixed(),symbol:t.symbol,amount:e.amount}),"bot"),void I(!1)}}catch(u){}const l=n?xn:e.token_in;K({srcTokenAddress:l,descTokenAddress:e.token_out,amount:e.amount,srcTokenDecimals:r,descTokenDecimals:s});const d=kn(e.amount,r).toString(),f=await Xh({chainId:q,tokenIn:l,tokenInAmount:d,tokenOut:e.token_out,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(f.success&&f.data){const e=f.data,t=e.tokenIn,r=e.tokenOut,o=Dh(pt(BigInt(t.amount||0),t.decimals)).decimalPlaces(8).toFormat(),s=Dh(pt(BigInt(r.amount||0),r.decimals)).decimalPlaces(8).toFormat();let a=!1;if(!n&&H?.address&&e.tx?.to)try{const t=await ap({tokenAddress:l,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:q,rpcUrl:G});a=Dh(t.toString()).isLessThan(d)}catch(i){a=!0}const c=e.estimatedTransactionFee?.total?Dh(e.estimatedTransactionFee.total):Dh(0);let u=Dh(0);if(a&&H?.address)try{const t=cp({tokenAddress:l,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:q,amount:d});u=await lp({from:H.address,to:t.to,data:t.data,chainId:q,rpcUrl:G})}catch(i){}const h=c.plus(u),w=j?.nativeCurrency?.symbol||"native";let b="",y=!1;if(H?.address&&h.isGreaterThan(0))try{const e=await up({address:H.address,chainId:q,rpcUrl:G});if(e.isLessThan(h)){y=!0;const t=Dh(pt(BigInt(e.toFixed(0)),18)).decimalPlaces(8).toFormat(),n=Dh(pt(BigInt(h.toFixed(0)),18)).decimalPlaces(8).toFormat();b=m("swapFeeWarning",{symbol:w,balance:t,needed:n})}}catch(i){}const v=`From: ${o} ${t.symbol}\n⬇️\nTo: ${s} ${r.symbol}\n\n`+b+"\n";if(y)g(v,"bot");else if(a){const n=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:t.symbol}),value:m("swapApproveValue",{symbol:t.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:l,spenderAddress:e.tx.to,tokenSymbol:t.symbol,amountInWei:d,tx:e.tx}}];g(v+m("swapNeedApprove",{symbol:t.symbol}),"bot",void 0,n)}else{const t=[{id:"confirm-swap",text:p("swapConfirmYes"),value:p("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(v+p("swapReadyToProceed"),"bot",void 0,t)}}else g(m("swapEstimationError",{error:f.errorMessage||f.error||"Unknown error"}),"bot")}catch(l){g(p("swapEstimationFailed"),"bot")}else if(s&&d&&!h){let r=n?18:parseInt(e.token_in_decimals||"18",10),s=parseInt(e.token_out_decimals||"18",10);const u=[];if(e.token_out&&u.push(e.token_out),e.token_in&&!n&&u.push(e.token_in),u.length>0)try{const t=await Gh.getTokensDetails(u,z);if(t?.data)for(const i of t.data)n||i.address.toLowerCase()!==e.token_in?.toLowerCase()||(r=i.decimals||r),i.address.toLowerCase()===e.token_out?.toLowerCase()&&(s=i.decimals||s)}catch(a){}if(K({descTokenAddress:e.token_out,descTokenDecimals:s}),n)try{if(o.length>0){const e=o.find(e=>e.native_token),n=j?.nativeCurrency?.symbol||"ETH";let i=e?.balance_formatted||"0";try{const t=await dp({chainId:q,rpcUrl:G});if(t.isGreaterThan(0)){const n=t.times(1e6),r=new Dh(e?.balance||"0").minus(n);i=r.isGreaterThan(0)?Dh(pt(BigInt(r.toFixed(0)),e?.decimals||18)).toFixed():"0"}}catch(c){}K({srcTokenAddress:xn,srcTokenDecimals:r});const s=[25,50,75,100].map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:n}),action:"select_percent",extraData:{percent:e,tokenAddress:xn,tokenSymbol:n,tokenDecimals:r,tokenBalance:i}}));g(m("selectAmountToSwap",{symbol:n,balance:i}),"bot",t.id,s)}else g(p("couldNotFetchBalance"),"bot")}catch(i){g(p("couldNotFetchBalanceRetry"),"bot")}else{const n=e.token_in_symbol||"Token";K({srcTokenAddress:e.token_in,srcTokenDecimals:r});try{if(o.length>0){const r=o.find(t=>t.token_address.toLowerCase()===e.token_in?.toLowerCase());if(!r)return g(m("swapTokenNotInWallet",{symbol:n}),"bot"),void I(!1);const i=[25,50,75,100].map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:r.symbol}),action:"select_percent",extraData:{percent:e,tokenAddress:r.token_address,tokenSymbol:r.symbol,tokenDecimals:r.decimals||18,tokenBalance:r.balance_formatted}}));g(m("selectAmountToSwap",{symbol:r.symbol,balance:`${r.balance_formatted} (~$${r.usd_value?.toFixed(2)||"0"})`}),"bot",t.id,i)}else g(p("couldNotFetchBalance"),"bot")}catch(i){g(p("couldNotFetchBalanceRetry"),"bot")}}}else if(!s&&d){g(f.message||p("swapChooseFrom"),"bot",t.id);let n=parseInt(e.token_out_decimals||"18",10);if(e.token_out)try{const t=await Gh.getTokensDetails([e.token_out],z);t?.data?.[0]&&(n=t.data[0].decimals||n)}catch(a){}h&&K({descTokenAddress:e.token_out,descTokenDecimals:n,amount:e.amount}),await Z(e.token_out,n)}else if(s&&!d){let r=n?18:parseInt(e.token_in_decimals||"18",10);if(e.token_in&&!n)try{const t=await Gh.getTokensDetails([e.token_in],z);t?.data?.[0]&&(r=t.data[0].decimals||r)}catch(a){}if(K(n?{srcTokenAddress:xn,srcTokenDecimals:18,...h?{amount:e.amount}:{}}:{srcTokenAddress:e.token_in,srcTokenDecimals:r,...h?{amount:e.amount}:{}}),h&&o.length>0)if(n){const n=o.find(e=>e.native_token),r=Np(e.amount,n?.balance_formatted||"0",n?.usd_price);if(Dh(n?.balance_formatted||"0").lt(r))return g(m("swapInsufficientNativeBalance",{balance:Dh(n?.balance_formatted||"0").decimalPlaces(8).toFixed(),symbol:j?.nativeCurrency?.symbol||"native",amount:r}),"bot",t.id),void I(!1);e.amount=r,K({amount:r})}else if(e.token_in){const n=o.find(t=>t.token_address.toLowerCase()===e.token_in.toLowerCase());if(n){const r=Np(e.amount,n.balance_formatted||"0",n.usd_price);if(Dh(n.balance_formatted||"0").lt(r))return g(m("swapInsufficientTokenBalance",{balance:Dh(n.balance_formatted||"0").decimalPlaces(8).toFixed(),symbol:n.symbol,amount:r}),"bot",t.id),void I(!1);e.amount=r,K({amount:r})}}g(f.message||m("swapChooseTo",{symbol:e.token_in_symbol||"your token"}),"bot",t.id);try{I(!0);const e=j?.tokenTrendingDefault||[],[t,n]=await Promise.allSettled([Gh.getTopGainers(z,"24h",5),Gh.getTokensDetails(e,z)]);let r=[];"fulfilled"===t.status&&t.value?.data&&(r=[...t.value.data]),"fulfilled"===n.status&&n.value?.data&&(r=[...n.value.data,...r]),r=r.filter((e,t,n)=>t===n.findIndex(t=>t.address.toLowerCase()===e.address.toLowerCase()));const i=r.map(e=>({id:e?.symbol,text:e?.symbol,value:m("buttonSwapTo",{name:e.name,symbol:e?.symbol||""}),action:"click_swap_dest_token",extraData:{tokenAddress:e?.address||"",symbol:e?.symbol||"",decimals:e?.decimals||18}}));g(m("trendingTokensForReceive",{chain:j?.name||"Unknown"}),"bot",void 0,i)}catch(i){g(p("couldNotLoadTokenList"),"bot")}finally{I(!1)}}else if(h&&K({amount:e.amount}),g(f.message||p("swapChooseToken"),"bot",t.id),H?.address)try{I(!0);const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result&&e.data.result.length>0){const t=e.data.result.map(e=>({id:`swap-select-${e.token_address}`,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${Dh(e?.usd_value||0).decimalPlaces(2).toFixed()||"0"})`,value:`Swap ${e.symbol}`,action:"suggested_action",fullWidth:!0}));await eh(500),I(!1),g(m("walletBalanceSpendable",{chain:j?.name||"this chain"}),"bot",void 0,t)}else I(!1),g(m("walletNoTokensFound",{chain:j?.name||"this chain"}),"bot")}catch(i){I(!1),g(p("walletFetchError"),"bot")}}else if("view_balances"===f.action)await re();else if("view_nfts"===f.action)await ne();else if("send_token"!==f.action||f.parameters?.contract_address||f.parameters?.token_symbol||!H?.address)if("send_nft"!==f.action||f.parameters?.contract_address||f.parameters?.token_id||f.parameters?.nft_name||!H?.address)if("send_nft"===f.action&&!Ye(f.parameters?.contract_address||"")&&(f.parameters?.nft_name||f.parameters?.token_id)&&H?.address)try{I(!0);const e=await Yh({address:H.address,chain:J,limit:100,exclude_spam:!1});if(e?.success&&e?.data?.result){const n=e.data.result,r=(f.parameters?.nft_name||"").toLowerCase(),i=f.parameters?.token_id||"",o=e=>{const t=(e.normalized_metadata?.name||e.name||"").toLowerCase(),n=(e.name||"").toLowerCase(),o=r&&(t.includes(r)||n.includes(r)),s=i&&e.token_id===i;return r&&i?o&&s:r?o:s},s=!r&&!!i,a=s?n.filter(o):[],c=s?1===a.length?a[0]:null:n.find(o);if(s&&a.length>1){const e=a.map(e=>{const t=e.normalized_metadata?.name||e.name||`#${e.token_id}`,n=e.normalized_metadata?.image||e.media?.original_media_url||"";return{id:`${e.token_address}-${e.token_id}`,text:`${t} (${e.symbol||e.contract_type}) #${e.token_id}`,value:m("buttonSendNft",{name:t}),action:"select_nft_to_send",fullWidth:!0,extraData:{contractAddress:e.token_address,tokenId:e.token_id,tokenStandard:e.contract_type,name:t,symbol:e.symbol,amount:e.amount,image:n,toAddress:f.parameters?.to_address||""}}}),n=a.map((e,t)=>{const n=e.normalized_metadata?.name||e.name||`#${e.token_id}`,r=e.normalized_metadata?.image||e.media?.original_media_url||"";return`${t+1}. ${r?`![${n}](${r})\n`:"🖼️ "}**${n}**\n ${e.symbol||e.contract_type} | Token ID: ${e.token_id}`}).join("\n\n");I(!1),g(m("nftMultipleMatchesForTokenId",{count:String(a.length),tokenId:i})+"\n\n"+n,"bot",t.id,e)}else if(c){const e=c.normalized_metadata?.name||c.name||`#${c.token_id}`,n=c.normalized_metadata?.image||c.media?.original_media_url||"",r={contract_address:c.token_address,token_id:c.token_id,to_address:f.parameters?.to_address||"",token_standard:c.contract_type||"",amount:f.parameters?.amount||"1",maxAmount:c.amount||"1",nft_name:e};g(f.message||m("nftSendReview",{name:e,standard:c.contract_type||"NFT",tokenId:c.token_id}),"bot",t.id,void 0,{action:"send_nft",parameters:r,status:"pending",nftInfo:{name:e,image:n||void 0,tokenId:c.token_id,contractAddress:c.token_address,tokenStandard:c.contract_type||void 0}})}else g(m("nftNotFoundInWallet",{name:r||i}),"bot",t.id)}else g(p("nftNoCollection"),"bot",t.id)}catch(i){g(p("nftFetchError"),"bot",t.id)}finally{I(!1)}else{const o=(n=f.action,["send_native","send_token","approve_token","wrap_native","unwrap_native","send_nft"].includes(n));let s,a,u={...f.parameters||{}};const l=["send_token","approve_token"].includes(f.action)&&(u.contract_address||u.token_symbol),d="send_native"===f.action||"wrap_native"===f.action,h="unwrap_native"===f.action,p="send_nft"===f.action&&u.contract_address;if(l&&H?.address)try{const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result){const t=e.data.result,n=u.contract_address?t.find(e=>e.token_address.toLowerCase()===u.contract_address.toLowerCase()):t.find(e=>e.symbol.toUpperCase()===u.token_symbol.toUpperCase());n&&(u={...u,contract_address:n.token_address,decimals:String(n.decimals)},s={symbol:n.symbol,name:n.name,balance:n.balance,balanceFormatted:n.balance_formatted,usdValue:n.usd_value,usdPrice:n.usd_price,decimals:n.decimals,logo:n.logo||n.thumbnail,contractAddress:n.token_address})}}catch(i){}if(l&&!s&&"send_token"===f.action){const e=u.token_symbol||u.contract_address||"this token";return g(m("sendTokenNotInWallet",{symbol:e}),"bot",t.id),void I(!1)}if(l&&!s&&u.contract_address)try{const e=await Vh({address:u.contract_address,chain:J});if(e?.success&&e?.data){const t=e.data;s={symbol:t.symbol,name:t.name,balance:"0",balanceFormatted:"0",usdPrice:t.usd_price,decimals:t.decimals,logo:t.logo,contractAddress:u.contract_address},u={...u,decimals:String(t.decimals)}}}catch(i){}if(d&&H?.address)try{const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result){const t=e.data.result.find(e=>e.native_token);if(t){let e=t.balance_formatted,n=t.balance;try{const r=new Dh(t.balance),i="0x"+BigInt(r.toFixed(0)).toString(16),o=await lp({from:H.address,to:H.address,data:"0x",value:i,chainId:q,rpcUrl:G});if(o.isGreaterThan(0)){const i=r.minus(o);i.isGreaterThan(0)?(n=i.toFixed(0),e=Dh(pt(BigInt(i.toFixed(0)),t.decimals)).toFixed()):(n="0",e="0")}}catch(c){}s={symbol:t.symbol,name:t.name,balance:n,balanceFormatted:e,usdValue:t.usd_value,usdPrice:t.usd_price,decimals:t.decimals,logo:t.logo||t.thumbnail,contractAddress:xn}}else{const e=await Vh({address:xn,chain:J});if(e?.success&&e?.data){const t=e.data;s={symbol:t.symbol,name:t.name,balance:"0",balanceFormatted:"0",usdValue:0,usdPrice:t.usd_price,decimals:t.decimals,logo:t.logo||t.thumbnail,contractAddress:xn}}}}}catch(i){}if(h&&H?.address)try{const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result){const t=e.data.result,n=`W${j?.nativeCurrency?.symbol||"ETH"}`,r=t.find(e=>e.symbol.toUpperCase()===n.toUpperCase());r&&(s={symbol:r.symbol,name:r.name,balance:r.balance,balanceFormatted:r.balance_formatted,usdValue:r.usd_value,usdPrice:r.usd_price,decimals:r.decimals,logo:r.logo||r.thumbnail,contractAddress:r.token_address})}}catch(i){}if(p){try{const e=await async function(e){const{address:t,chain:n="base"}=e;if(!t)throw new Error("Contract address is required");try{return{success:!0,data:(await Jh.get(`api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata`,{query:{chain:n}})).data}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}({address:u.contract_address,chain:J});if(e?.success&&e?.data){const t=e.data;t.contract_type&&(u={...u,token_standard:t.contract_type}),!u.nft_name&&t.name&&(u={...u,nft_name:t.name})}}catch(i){}if(H?.address)try{const e=await Yh({address:H.address,chain:J,limit:100,exclude_spam:!1});if(e?.success&&e?.data?.result){const n=e.data.result.find(e=>e.token_address.toLowerCase()===u.contract_address.toLowerCase()&&e.token_id===u.token_id);if(!n){const e=u.nft_name||`#${u.token_id||u.contract_address}`;return g(m("nftNotFoundInWallet",{name:e}),"bot",t.id),void I(!1)}{u={...u,amount:u.amount||"1",maxAmount:n.amount||"1"};const e=n.normalized_metadata?.image||n.media?.original_media_url||"";a={name:n.normalized_metadata?.name||n.name||u.nft_name||`#${n.token_id}`,image:e||void 0,tokenId:n.token_id,contractAddress:n.token_address,tokenStandard:n.contract_type||u.token_standard||void 0}}}}catch(i){}}if(u.amount&&s?.balanceFormatted&&("send_token"===f.action||"send_native"===f.action||"wrap_native"===f.action||"unwrap_native"===f.action)&&(u.amount=Np(u.amount,s.balanceFormatted,s.usdPrice)),o){const e=f.message||"Please review and complete the form below.";g(e,"bot",t.id,void 0,{action:f.action,parameters:u,status:"pending",tokenInfo:s,nftInfo:a})}else g(f.message||e,"bot",t.id)}else g(m("sendNftViaWebsite",{link:Ip}),"bot");else try{const e=await qh({address:H.address,chain:J});if(e?.success&&e?.data?.result&&e.data.result.length>0){g(p("sendTokenChoose"),"bot",t.id),I(!0),await eh(500);const n=e.data.result.map(e=>({id:`send-select-${e.token_address}`,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${Dh(e?.usd_value||0).decimalPlaces(2).toFixed()||"0"})`,value:m("buttonSendToken",{symbol:e.symbol}),action:"suggested_action",fullWidth:!0}));await eh(500),I(!1),g(m("walletBalanceSpendable",{chain:j?.name||"this chain"}),"bot",void 0,n)}else I(!1),g(m("walletNoTokensFound",{chain:j?.name||"this chain"}),"bot")}catch(i){I(!1),g(p("walletFetchError"),"bot")}else if(f&&"chat"===f.action){const n=f.token_mentions||[],r=f.suggested_actions||[],i=[];n.length>0&&(await Promise.all(n.map(async e=>{let t=e.contract_address||"",n=e.decimals||18;if("native"===t.toLowerCase()&&(t=xn),t===xn){const t=d?.find(e=>e.native_token);return t?{symbol:e.symbol||t.symbol,contract_address:xn,decimals:18}:e.symbol?{symbol:e.symbol,contract_address:xn,decimals:18}:null}if(t&&t!==xn){const r=d?.find(n=>n.token_address.toLowerCase()===t.toLowerCase()&&n.symbol.toUpperCase()===e.symbol.toUpperCase());if(r){try{const e=await Gh.getTokensDetails([t],z);n=e?.data?.[0]?.decimals??n}catch{}return{symbol:e.symbol,contract_address:t,decimals:n}}try{const r=await Gh.getTokensDetails([t],z),i=r?.data?.[0];if(i&&i.symbol?.toUpperCase()===e.symbol.toUpperCase())return{symbol:e.symbol,contract_address:t,decimals:i.decimals??n};t=""}catch{t=""}}if(!t&&d){const r=d.find(t=>t.symbol.toUpperCase()===e.symbol.toUpperCase());if(r){t=r.token_address;try{const e=await Gh.getTokensDetails([t],z);n=e?.data?.[0]?.decimals??n}catch{}}}return t?{symbol:e.symbol,contract_address:t,decimals:n}:null}))).filter(e=>null!==e).forEach(e=>{i.push({id:`buy-${e.symbol}`,text:`💰 Buy ${e.symbol}`,value:m("buttonBuySymbol",{symbol:e.symbol}),action:"click_buy_item_token_button",extraData:{tokenAddress:e.contract_address,symbol:e.symbol,decimals:e.decimals},fullWidth:!0})}),r.length>0&&r.forEach((e,t)=>{i.push({id:`suggested-${t}-${e.label}`,text:e.label,value:e.prompt,action:"suggested_action",fullWidth:!0})}),i.length>0?g(f.message||e,"bot",t.id,i):g(f.message||e,"bot",t.id)}else g(e,"bot",t.id)}else g(p("errorProcessingRequest"),"bot",t.id)}catch(r){g(p("errorProcessingRequest"),"bot",t.id)}var n;I(!1),await eh(50),bp.isDesktop&&O.current?.focus()},[E,C,B,g,b,H?.address,V,j?.name,j?.nativeCurrency?.symbol,j?.tokenTrendingDefault,q,x,J,z,m,Z,_,$,te,p,K,G,re,ne]);o(()=>{F.current&&E===F.current&&(F.current=null,se())},[E,se]);const ae=s(async(e,t,n)=>{try{if(N(!1),y(n,"submitted"),"swap_token"===e){let e=18;if(t.token_in&&t.token_in!==xn)try{const n=await Gh.getTokensDetails([t.token_in],z);n?.data?.[0]&&(e=n.data[0].decimals||18)}catch(r){}const o=kn(t.amount||"0",e).toString(),s=await Xh({chainId:q,tokenIn:t.token_in||"",tokenInAmount:o,tokenOut:t.token_out||"",tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(s.success&&s.data){const e=s.data,r=e.tokenIn,a=e.tokenOut,c=Dh(pt(BigInt(r.amount||0),r.decimals)).decimalPlaces(8).toFormat(),u=Dh(pt(BigInt(a.amount||0),a.decimals)).decimalPlaces(8).toFormat(),l=!t.token_in||t.token_in===xn;let d=!1;if(!l&&H?.address&&e.tx?.to)try{const n=await ap({tokenAddress:t.token_in,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:q,rpcUrl:G});d=Dh(n.toString()).isLessThan(o)}catch(i){}const f=e.estimatedTransactionFee?.total?Dh(e.estimatedTransactionFee.total):Dh(0);let h=Dh(0);if(d&&H?.address)try{const n=cp({tokenAddress:t.token_in,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:q,amount:o});h=await lp({from:H.address,to:n.to,data:n.data,chainId:q,rpcUrl:G})}catch(i){}const w=f.plus(h),b=j?.nativeCurrency?.symbol||"native";let v="",A=!1;if(H?.address&&w.isGreaterThan(0))try{const e=await up({address:H.address,chainId:q,rpcUrl:G});if(e.isLessThan(w)){A=!0;const t=Dh(pt(BigInt(e.toFixed(0)),18)).decimalPlaces(8).toFormat(),n=Dh(pt(BigInt(w.toFixed(0)),18)).decimalPlaces(8).toFormat();v=m("swapFeeWarning",{symbol:b,balance:t,needed:n})}}catch(i){}const k=`From: ${c} ${r.symbol}\n⬇️\nTo: ${u} ${a.symbol}\n\n`+v+"\n";if(A)y(n,"pending"),g(k,"bot");else if(d){const i=[{id:"approve-swap-actionform",text:m("swapApproveButton",{symbol:r.symbol}),value:m("swapApproveValue",{symbol:r.symbol}),action:"approve_for_swap",extraData:{tokenAddress:t.token_in,spenderAddress:e.tx.to,tokenSymbol:r.symbol,amountInWei:o,tx:e.tx},fullWidth:!0}];y(n,"success"),g(k+m("swapApprovalRequired",{symbol:r.symbol}),"bot",void 0,i)}else{const t=[{id:"confirm-swap-actionform",text:p("swapConfirmYes"),value:p("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];y(n,"success"),g(k+p("swapReadyToProceed"),"bot",void 0,t)}}else y(n,"pending"),g(m("swapEstimationError",{error:s.errorMessage||s.error||"Unknown error"}),"bot")}else{const r=function(e){const{action:t,parameters:n,fromAddress:r,chainId:i}=e;switch(t){case"send_native":return function(e,t,n){const{to_address:r,amount:i}=e;if(!r)throw new Error("Recipient address is required");if(!i)throw new Error("Amount is required");return{from:t,to:r,data:"0x",value:kn(Dh(i).decimalPlaces(18,Dh.ROUND_DOWN).toFixed(),18).toString(),chainId:n,description:`Send ${i} native token to ${r}`}}(n,r,i);case"send_token":return function(e,t,n){const{contract_address:r,to_address:i,amount:o,decimals:s,token_symbol:a}=e;if(!r)throw new Error("Token contract address is required");if(!i)throw new Error("Recipient address is required");if(!o)throw new Error("Amount is required");const c=parseInt(s)||18,u=kn(Dh(o).decimalPlaces(c,Dh.ROUND_DOWN).toFixed(),c);return{from:t,to:r,data:st({abi:tp,functionName:"transfer",args:[i,u]}),value:"0",chainId:n,description:`Send ${o} ${a||"tokens"} to ${i}`}}(n,r,i);case"approve_token":return function(e,t,n){const{contract_address:r,spender_address:i,amount:o,decimals:s,token_symbol:a}=e;if(!r)throw new Error("Token contract address is required");if(!i)throw new Error("Spender address is required");const c=parseInt(s)||18,u=o&&""!==o?.trim()?kn(Dh(o).decimalPlaces(c,Dh.ROUND_DOWN).toFixed(),c):Jt;return{from:t,to:r,data:st({abi:tp,functionName:"approve",args:[i,u]}),value:"0",chainId:n,description:`Approve ${o||"unlimited"} ${a||"tokens"} for ${i}`}}(n,r,i);case"wrap_native":return function(e,t,n){const{amount:r}=e;if(!r)throw new Error("Amount is required");const i=ep[n];if(!i)throw new Error(`WETH not supported on chain ${n}`);const o=kn(Dh(r).decimalPlaces(18,Dh.ROUND_DOWN).toFixed(),18).toString();return{from:t,to:i,data:st({abi:np,functionName:"deposit"}),value:o,chainId:n,description:`Wrap ${r} native token`}}(n,r,i);case"unwrap_native":return function(e,t,n){const{amount:r}=e;if(!r)throw new Error("Amount is required");const i=ep[n];if(!i)throw new Error(`WETH not supported on chain ${n}`);const o=kn(Dh(r).decimalPlaces(18,Dh.ROUND_DOWN).toFixed(),18);return{from:t,to:i,data:st({abi:np,functionName:"withdraw",args:[o]}),value:"0",chainId:n,description:`Unwrap ${r} WETH`}}(n,r,i);case"send_nft":return function(e,t,n){const{contract_address:r,token_id:i,to_address:o,token_standard:s,amount:a,nft_name:c}=e;if(!r)throw new Error("NFT contract address is required");if(!i)throw new Error("Token ID is required");if(!o)throw new Error("Recipient address is required");const u=(s||"ERC721").toUpperCase(),l=BigInt(i);let d,f;if("ERC1155"===u){const e=BigInt(a||"1");d=st({abi:ip,functionName:"safeTransferFrom",args:[t,o,l,e,"0x"]}),f=`Send ${e>1n?e.toString()+"x ":""}${c||"NFT"} (ERC1155 #${i}) to ${o}`}else d=st({abi:rp,functionName:"safeTransferFrom",args:[t,o,l]}),f=`Send ${c||"NFT"} (ERC721 #${i}) to ${o}`;return{from:t,to:r,data:d,value:"0",chainId:n,description:f}}(n,r,i);default:throw new Error(`Action "${t}" does not produce a transaction`)}}({action:e,parameters:t,fromAddress:H?.address||"",chainId:q||1}),i={from:r.from,to:r.to,data:r.data,value:r.value,chainId:r.chainId};if(("send_token"===e||"send_native"===e||"send_nft"===e||"wrap_native"===e||"unwrap_native"===e||"approve_token"===e)&&H?.address)try{const e=j?.nativeCurrency?.symbol||"native",t=await lp({from:r.from,to:r.to,data:r.data,value:r.value&&"0"!==r.value?`0x${BigInt(r.value).toString(16)}`:void 0,chainId:q,rpcUrl:G});if(t.isGreaterThan(0)){const r=await up({address:H.address,chainId:q,rpcUrl:G});if(r.isLessThan(t)){const i=Dh(pt(BigInt(r.toFixed(0)),18)).decimalPlaces(8).toFormat(),o=Dh(pt(BigInt(t.toFixed(0)),18)).decimalPlaces(8).toFormat();return y(n,"pending"),void g(m("txInsufficientGas",{symbol:e,balance:i,fee:o}),"bot")}}}catch(o){}if(u){I(!1);const r=await u(i);if("success"===r.status&&r.transactionHash){const i=j?.blockExplorers?.default?.url,o=i?` [View on Explorer](${i}/tx/${r.transactionHash})`:` Tx: ${r.transactionHash}`;try{if(await eh(4e3),"success"===(await sp({transactionHash:r.transactionHash,chainId:q||1,rpcUrl:G})).status){if(y(n,"success"),v(n,t),"approve_token"===e&&g(m("approvalSuccess",{symbol:t.token_symbol||t.contract_address||"Token"})+o,"bot"),"send_token"===e||"send_native"===e||"send_nft"===e){const n=t.to_address||t.recipient||"",r=n?`${n.slice(0,6)}...${n.slice(-4)}`:"";g("send_nft"===e?m("txSuccessfulSendNft",{name:t.nft_name||t.token_symbol||"NFT",tokenId:t.token_id||"",to:r})+o:m("send_native"===e?"txSuccessfulSendNative":"txSuccessfulSendToken",{amount:t.amount||"",symbol:t.token_symbol||("send_native"===e?j?.nativeCurrency?.symbol||"native":"Token"),to:r})+o,"bot")}if("wrap_native"===e){const e=j?.nativeCurrency?.symbol||"native";g(m("txSuccessfulWrapNative",{amount:t.amount||"",from:e,to:`W${e}`})+o,"bot")}if("unwrap_native"===e){const e=j?.nativeCurrency?.symbol||"native";g(m("txSuccessfulUnwrapNative",{amount:t.amount||"",from:`W${e}`,to:e})+o,"bot")}}else y(n,"pending"),g(p("txReverted")+"\n"+o,"bot")}catch(s){y(n,"success"),g(p("txTimeout")+"\n"+o,"bot")}}else if("success"===r.status)y(n,"success");else{y(n,"pending");const e=r.error?`\nError: ${r.error}`:"";g(p("txFailed")+e,"bot")}}else y(n,"pending"),g(p("txNoHandler"),"bot")}}catch(a){y(n,"pending"),g(m("txError",{message:a instanceof Error?a.message:"Unknown error"}),"bot")}},[y,q,H?.address,z,j?.nativeCurrency?.symbol,j?.blockExplorers?.default?.url,G,m,g,p,u,v]),ce=s(e=>{k([e])},[k]),[ue,le]=i({}),de=s(async(e,t,n)=>{le(e=>({...e,[n]:!0}));try{await ae(e,t,n)}finally{le(e=>({...e,[n]:!1}))}},[ae]),fe=s(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),se())},[se]),he=s(()=>{const e=window.getSelection();e&&e.toString().length>0||a()},[a]);return r?/* @__PURE__ */e("div",{className:"chat-modal-overlay"+("bottom-left"===f?" chat-modal-overlay--left":""),onClick:he,role:"dialog","aria-modal":"true","aria-labelledby":"chat-modal-title",children:/* @__PURE__ */n("div",{className:"chat-modal",style:h,onClick:e=>e.stopPropagation(),children:[
39
39
  /* @__PURE__ */n("div",{className:"chat-modal-header",children:[
40
40
  /* @__PURE__ */n("div",{className:"chat-modal-header-title",children:[
41
41
  /* @__PURE__ */n("div",{className:"chat-modal-header-left",children:[