keyring-chatbot-agent-sdk-test 0.3.15 → 0.3.16

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.
@@ -17,7 +17,7 @@ return e(n,{children:Pn(o||"")&&/* @__PURE__ */t("div",{className:"chat-user-inf
17
17
  /* @__PURE__ */e("button",{type:"button",className:"action-form-pct-btn action-form-max-btn",onClick:()=>v("amount",l.balanceFormatted),disabled:c||u,children:f("formMax")})]})]}),(()=>{const n=!1===a.editable&&!!o[a.key]||u,t=c||n,i=[A[a.key]?"error":"",n?"readonly":""].filter(Boolean).join(" ");return"address"===a.type?/* @__PURE__ */e("textarea",{rows:2,placeholder:a.placeholder,value:m[a.key]||"",onChange:e=>v(a.key,e.target.value),className:i,disabled:t||u}):/* @__PURE__ */e("input",{type:"number"===a.type?"number":"text",placeholder:a.placeholder,value:m[a.key]||"",onChange:e=>v(a.key,e.target.value),className:i,disabled:t||u})})(),A[a.key]&&/* @__PURE__ */e("span",{className:"field-error",children:A[a.key]})]},a.key))}),!u&&/* @__PURE__ */t("div",{className:"action-form-actions",children:[
18
18
  /* @__PURE__ */e("button",{className:"message-button",onClick:s,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},Mo=({scrollContainerRef:n,threshold:t=200})=>{const[o,r]=a(!1);return i(()=>{const e=n.current;if(!e)return;const o=()=>{const{scrollTop:n,scrollHeight:o,clientHeight:a}=e;r(o-n-a>t)};return e.addEventListener("scroll",o,{passive:!0}),o(),()=>{e.removeEventListener("scroll",o)}},[n,t]),o?/* @__PURE__ */e("button",{className:"scroll-to-bottom-btn",onClick:()=>{n.current?.scrollTo({top:n.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},Po={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",10:"0x4200000000000000000000000000000000000006",56:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",137:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},Ho=[{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"}]}],Jo=[{name:"deposit",type:"function",stateMutability:"payable",inputs:[],outputs:[]},{name:"withdraw",type:"function",stateMutability:"nonpayable",inputs:[{name:"wad",type:"uint256"}],outputs:[]}],Yo=[{name:"safeTransferFrom",type:"function",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]}],qo=[{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 Go(e,n){if(n)return n;const t=Dt[e];return t?.rpcUrls?.default?.http?.[0]}async function Wo(e){const{transactionHash:n,chainId:t,pollingInterval:o=3e3,timeout:a=12e4,rpcUrl:i}=e,r=Go(t,i);if(!r)throw new Error(`No RPC endpoint for chain ${t}`);const s=Date.now();for(;Date.now()-s<a;){try{const e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[n]})}),t=await e.json();if(t.result){const e=t.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,o))}throw new Error(`Transaction ${n} was not mined within ${a/1e3}s`)}async function Vo(e){const{tokenAddress:n,ownerAddress:t,spenderAddress:o,chainId:a,rpcUrl:i}=e,r=Go(a,i);if(!r)return BigInt(0);try{const e=Rt({abi:Ho,functionName:"allowance",args:[t,o]}),a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:n,data:e},"latest"]})}),i=await a.json();return i.result&&"0x"!==i.result?BigInt(i.result):BigInt(0)}catch(s){return BigInt(0)}}function zo(e){const{tokenAddress:n,spenderAddress:t,fromAddress:o,chainId:a,tokenSymbol:i,amount:r}=e,s=r&&BigInt(r)>0n?BigInt(r):ie;return{from:o,to:n,data:Rt({abi:Ho,functionName:"approve",args:[t,s]}),value:"0",chainId:a,description:`Approve ${i||"token"} for swap`}}async function jo(e){const{address:n,chainId:t,rpcUrl:o}=e,a=Go(t,o);if(!a)return new xo(0);try{const e=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getBalance",params:[n,"latest"]})}),t=await e.json();return t.result&&"0x"!==t.result?new xo(BigInt(t.result).toString()):new xo(0)}catch(i){return new xo(0)}}async function Xo(e){const{from:n,to:t,data:o,value:a,chainId:i,rpcUrl:r}=e,s=Go(i,r);if(!s)return new xo(0);try{const[e,i]=await Promise.all([fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_estimateGas",params:[{from:n,to:t,data:o,...a&&"0"!==a?{value:a}:{}}]})}),fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:2,method:"eth_gasPrice",params:[]})})]),[r,c]=await Promise.all([e.json(),i.json()]),l=r.result?new xo(BigInt(r.result).toString()):new xo(0),d=c.result?new xo(BigInt(c.result).toString()):new xo(0);return l.times(d).times(1.1)}catch(c){return new xo(0)}}async function Qo(e){const{chainId:n,rpcUrl:t}=e,o=Go(n,t);if(!o)return new xo(0);try{const e=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})}),n=await e.json();return n.result&&"0x"!==n.result?new xo(BigInt(n.result).toString()):new xo(0)}catch(a){return new xo(0)}}var Ko,Zo,_o={},$o={exports:{}},ea=$o.exports;var na=function(){if(Zo)return _o;Zo=1,Object.defineProperty(_o,"p",{value:!0});var e,n,t,a=o,i=(e=a)&&"object"==typeof e&&"default"in e?e.default:e,r=(Ko||(Ko=1,n=$o,t=$o.exports,function(e,o){var a="function",i="undefined",r="object",s="string",c="major",l="model",d="name",u="type",f="vendor",p="version",h="architecture",m="console",w="mobile",b="tablet",g="smarttv",A="wearable",y="embedded",v="Amazon",k="Apple",x="ASUS",C="BlackBerry",T="Browser",E="Chrome",I="Firefox",N="Google",S="Honor",B="Huawei",F="LG",R="Microsoft",O="Motorola",D="Nvidia",U="OnePlus",L="Opera",M="OPPO",P="Samsung",H="Sharp",J="Sony",Y="Xiaomi",q="Zebra",G="Facebook",W="Chromium OS",V="Mac OS",z=" Browser",j=function(e){for(var n={},t=0;t<e.length;t++)n[e[t].toUpperCase()]=e[t];return n},X=function(e,n){return typeof e===s&&-1!==Q(n).indexOf(Q(e))},Q=function(e){return e.toLowerCase()},K=function(e,n){if(typeof e===s)return e=e.replace(/^\s\s*/,""),typeof n===i?e:e.substring(0,500)},Z=function(e,n){for(var t,i,s,c,l,d,u=0;u<n.length&&!l;){var f=n[u],p=n[u+1];for(t=i=0;t<f.length&&!l&&f[t];)if(l=f[t++].exec(e))for(s=0;s<p.length;s++)d=l[++i],typeof(c=p[s])===r&&c.length>0?2===c.length?typeof c[1]==a?this[c[0]]=c[1].call(this,d):this[c[0]]=c[1]:3===c.length?typeof c[1]!==a||c[1].exec&&c[1].test?this[c[0]]=d?d.replace(c[1],c[2]):o:this[c[0]]=d?c[1].call(this,d,c[2]):o:4===c.length&&(this[c[0]]=d?c[3].call(this,d.replace(c[1],c[2])):o):this[c]=d||o;u+=2}},_=function(e,n){for(var t in n)if(typeof n[t]===r&&n[t].length>0){for(var a=0;a<n[t].length;a++)if(X(n[t][a],e))return"?"===t?o:t}else if(X(n[t],e))return"?"===t?o:t;return n.hasOwnProperty("*")?n["*"]:e},$={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"},ee={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,p],[/opios[\/ ]+([\w\.]+)/i],[p,[d,L+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[p,[d,L+" GX"]],[/\bopr\/([\w\.]+)/i],[p,[d,L]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[p,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[p,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/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|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,p],[/quark(?:pc)?\/([-\w\.]+)/i],[p,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[p,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[d,"UC"+T]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[p,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[p,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[p,[d,"Smart Lenovo "+T]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+T],p],[/\bfocus\/([\w\.]+)/i],[p,[d,I+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[d,L+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[d,L+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[d,"MIUI"+z]],[/fxios\/([\w\.-]+)/i],[p,[d,I]],[/\bqihoobrowser\/?([\w\.]*)/i],[p,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],p],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+z],p],[/samsungbrowser\/([\w\.]+)/i],[p,[d,P+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[p,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,p],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[p,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,G],p],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\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],[d,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[p,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[d,E+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,E+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[d,"Android "+T]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[p,_,{"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],[d,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],p],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[d,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,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[d,[p,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[p,/master.|lts./,""]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[h,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[h,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[h,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[h,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[h,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[h,/ower/,"",Q]],[/ sun4\w[;\)]/i],[[h,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[h,Q]]],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],[l,[f,P],[u,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],[l,[f,P],[u,w]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[f,k],[u,w]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[f,k],[u,b]],[/(macintosh);/i],[l,[f,k]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[f,H],[u,w]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[l,[f,S],[u,b]],[/honor([-\w ]+)[;\)]/i],[l,[f,S],[u,w]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[l,[f,B],[u,b]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[f,B],[u,w]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[l,/_/g," "],[f,Y],[u,b]],[/\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,/ ([\w ]+) miui\/v?\d/i],[[l,/_/g," "],[f,Y],[u,w]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[f,M],[u,w]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[l,[f,_,{OnePlus:["304","403","203"],"*":M}],[u,b]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[f,"Vivo"],[u,w]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[f,"Realme"],[u,w]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[f,O],[u,w]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[f,O],[u,b]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[f,F],[u,b]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[f,F],[u,w]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[l,[f,"Lenovo"],[u,b]],[/(nokia) (t[12][01])/i],[f,l,[u,b]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[l,/_/g," "],[u,w],[f,"Nokia"]],[/(pixel (c|tablet))\b/i],[l,[f,N],[u,b]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[f,N],[u,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],[l,[f,J],[u,w]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[f,J],[u,b]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[f,U],[u,w]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[f,v],[u,b]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[f,v],[u,w]],[/(playbook);[-\w\),; ]+(rim)/i],[l,f,[u,b]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[f,C],[u,w]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[f,x],[u,b]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[f,x],[u,w]],[/(nexus 9)/i],[l,[f,"HTC"],[u,b]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[f,[l,/_/g," "],[u,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],[l,[f,"TCL"],[u,b]],[/(itel) ((\w+))/i],[[f,Q],l,[u,_,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[f,"Acer"],[u,b]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[f,"Meizu"],[u,w]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[f,"Ulefone"],[u,w]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[f,"Energizer"],[u,w]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[f,"Cat"],[u,w]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[f,"Smartfren"],[u,w]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[f,"Nothing"],[u,w]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[l,[f,"Archos"],[u,b]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[l,[f,"Archos"],[u,w]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[f,l,[u,b]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[f,l,[u,w]],[/(kobo)\s(ereader|touch)/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,l,[u,b]],[/(surface duo)/i],[l,[f,R],[u,b]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[f,"Fairphone"],[u,w]],[/(u304aa)/i],[l,[f,"AT&T"],[u,w]],[/\bsie-(\w*)/i],[l,[f,"Siemens"],[u,w]],[/\b(rct\w+) b/i],[l,[f,"RCA"],[u,b]],[/\b(venue[\d ]{2,7}) b/i],[l,[f,"Dell"],[u,b]],[/\b(q(?:mv|ta)\w+) b/i],[l,[f,"Verizon"],[u,b]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[f,"Barnes & Noble"],[u,b]],[/\b(tm\d{3}\w+) b/i],[l,[f,"NuVision"],[u,b]],[/\b(k88) b/i],[l,[f,"ZTE"],[u,b]],[/\b(nx\d{3}j) b/i],[l,[f,"ZTE"],[u,w]],[/\b(gen\d{3}) b.+49h/i],[l,[f,"Swiss"],[u,w]],[/\b(zur\d{3}) b/i],[l,[f,"Swiss"],[u,b]],[/\b((zeki)?tb.*\b) b/i],[l,[f,"Zeki"],[u,b]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[f,"Dragon Touch"],l,[u,b]],[/\b(ns-?\w{0,9}) b/i],[l,[f,"Insignia"],[u,b]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[f,"NextBook"],[u,b]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[f,"Voice"],l,[u,w]],[/\b(lvtel\-)?(v1[12]) b/i],[[f,"LvTel"],l,[u,w]],[/\b(ph-1) /i],[l,[f,"Essential"],[u,w]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[f,"Envizen"],[u,b]],[/\b(trio[-\w\. ]+) b/i],[l,[f,"MachSpeed"],[u,b]],[/\btu_(1491) b/i],[l,[f,"Rotor"],[u,b]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[l,[f,D],[u,b]],[/(sprint) (\w+)/i],[f,l,[u,w]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[f,R],[u,w]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[f,q],[u,b]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[f,q],[u,w]],[/smart-tv.+(samsung)/i],[f,[u,g]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[f,P],[u,g]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[f,F],[u,g]],[/(apple) ?tv/i],[f,[l,k+" TV"],[u,g]],[/crkey/i],[[l,E+"cast"],[f,N],[u,g]],[/droid.+aft(\w+)( bui|\))/i],[l,[f,v],[u,g]],[/(shield \w+ tv)/i],[l,[f,D],[u,g]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[f,H],[u,g]],[/(bravia[\w ]+)( bui|\))/i],[l,[f,J],[u,g]],[/(mi(tv|box)-?\w+) bui/i],[l,[f,Y],[u,g]],[/Hbbtv.*(technisat) (.*);/i],[f,l,[u,g]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[f,K],[l,K],[u,g]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[l,[u,g]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,g]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[f,l,[u,m]],[/droid.+; (shield)( bui|\))/i],[l,[f,D],[u,m]],[/(playstation \w+)/i],[l,[f,J],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[f,R],[u,m]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[l,[f,P],[u,A]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[f,l,[u,A]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[l,[f,M],[u,A]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[f,k],[u,A]],[/(opwwe\d{3})/i],[l,[f,U],[u,A]],[/(moto 360)/i],[l,[f,O],[u,A]],[/(smartwatch 3)/i],[l,[f,J],[u,A]],[/(g watch r)/i],[l,[f,F],[u,A]],[/droid.+; (wt63?0{2,3})\)/i],[l,[f,q],[u,A]],[/droid.+; (glass) \d/i],[l,[f,N],[u,A]],[/(pico) (4|neo3(?: link|pro)?)/i],[f,l,[u,A]],[/; (quest( \d| pro)?)/i],[l,[f,G],[u,A]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[f,[u,y]],[/(aeobc)\b/i],[l,[f,v],[u,y]],[/(homepod).+mac os/i],[l,[f,k],[u,y]],[/windows iot/i],[[u,y]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[u,w]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[u,b]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,b]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,w]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[l,[f,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,p],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,p],[/ladybird\//i],[[d,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,p],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[d,[p,_,$]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[p,_,$],[d,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,V],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,d],[/(ubuntu) ([\w\.]+) like android/i],[[d,/(.+)/,"$1 Touch"],p],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[d,p],[/\(bb(10);/i],[p,[d,C]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[p,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[d,I+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[d,E+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,W],p],[/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)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,p],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,p]]},ne=function(n,t){if(typeof n===r&&(t=n,n=o),!(this instanceof ne))return new ne(n,t).getResult();var m=typeof e!==i&&e.navigator?e.navigator:o,g=n||(m&&m.userAgent?m.userAgent:""),A=m&&m.userAgentData?m.userAgentData:o,y=t?function(e,n){var t={};for(var o in e)n[o]&&n[o].length%2==0?t[o]=n[o].concat(e[o]):t[o]=e[o];return t}(ee,t):ee,v=m&&m.userAgent==g;return this.getBrowser=function(){var e,n={};return n[d]=o,n[p]=o,Z.call(n,g,y.browser),n[c]=typeof(e=n[p])===s?e.replace(/[^\d\.]/g,"").split(".")[0]:o,v&&m&&m.brave&&typeof m.brave.isBrave==a&&(n[d]="Brave"),n},this.getCPU=function(){var e={};return e[h]=o,Z.call(e,g,y.cpu),e},this.getDevice=function(){var e={};return e[f]=o,e[l]=o,e[u]=o,Z.call(e,g,y.device),v&&!e[u]&&A&&A.mobile&&(e[u]=w),v&&"Macintosh"==e[l]&&m&&typeof m.standalone!==i&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[l]="iPad",e[u]=b),e},this.getEngine=function(){var e={};return e[d]=o,e[p]=o,Z.call(e,g,y.engine),e},this.getOS=function(){var e={};return e[d]=o,e[p]=o,Z.call(e,g,y.os),v&&!e[d]&&A&&A.platform&&"Unknown"!=A.platform&&(e[d]=A.platform.replace(/chrome os/i,W).replace(/macos/i,V)),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===s&&e.length>500?K(e,500):e,this},this.setUA(g),this};ne.VERSION="1.0.41",ne.BROWSER=j([d,p,c]),ne.CPU=j([h]),ne.DEVICE=j([l,f,u,m,w,g,b,A,y]),ne.ENGINE=ne.OS=j([d,p]),n.exports&&(t=n.exports=ne),t.UAParser=ne;var te=typeof e!==i&&(e.jQuery||e.Zepto);if(te&&!te.ua){var oe=new ne;te.ua=oe.getResult(),te.ua.get=function(){return oe.getUA()},te.ua.set=function(e){oe.setUA(e);var n=oe.getResult();for(var t in n)te.ua[t]=n[t]}}}("object"==typeof window?window:ea)),$o.exports),s=new r,c=s.getBrowser(),l=s.getCPU(),d=s.getDevice(),u=s.getEngine(),f=s.getOS(),p=s.getUA(),h=function(e){return s.setUA(e)},m=function(e){if(e){var n=new r(e);return{UA:n,browser:n.getBrowser(),cpu:n.getCPU(),device:n.getDevice(),engine:n.getEngine(),os:n.getOS(),ua:n.getUA(),setUserAgent:function(e){return n.setUA(e)}}}},w=/* @__PURE__ */Object.freeze({ClientUAInstance:s,browser:c,cpu:l,device:d,engine:u,os:f,ua:p,setUa:h,parseUserAgent:m});function b(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);n&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),t.push.apply(t,o)}return t}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 A(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function y(){return y=Object.assign||function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},y.apply(this,arguments)}function v(e){return(v=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function k(e,n){return(k=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function x(e,n){if(null==e)return{};var t,o,a=function(e,n){if(null==e)return{};var t,o,a={},i=Object.keys(e);for(o=0;o<i.length;o++)t=i[o],n.indexOf(t)>=0||(a[t]=e[t]);return a}(e,n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)t=i[o],n.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(a[t]=e[t])}return a}function C(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function T(e,n){(null==n||n>e.length)&&(n=e.length);for(var t=0,o=new Array(n);t<n;t++)o[t]=e[t];return o}var E="mobile",I="tablet",N="smarttv",S="console",B="wearable",F="embedded",R=void 0,O={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"},D={IOS:"iOS",Android:"Android",WindowsPhone:"Windows Phone",Windows:"Windows",MAC_OS:"Mac OS"},U={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")},M=function(){return!("undefined"==typeof window||!window.navigator&&!navigator)&&(window.navigator||navigator)},P=function(e){var n=M();return n&&n.platform&&(-1!==n.platform.indexOf(e)||"MacIntel"===n.platform&&n.maxTouchPoints>1&&!window.MSStream)},H=function(e){return e.type===E},J=function(e){return e.type===I},Y=function(e){var n=e.type;return n===E||n===I},q=function(e){return e.type===N},G=function(e){return e.type===R},W=function(e){return e.type===B},V=function(e){return e.type===S},z=function(e){return e.type===F},j=function(e){var n=e.vendor;return L(n)},X=function(e){var n=e.model;return L(n)},Q=function(e){var n=e.type;return L(n,"browser")},K=function(e){return e.name===D.Android},Z=function(e){return e.name===D.Windows},_=function(e){return e.name===D.MAC_OS},$=function(e){return e.name===D.WindowsPhone},ee=function(e){return e.name===D.IOS},ne=function(e){var n=e.version;return L(n)},te=function(e){var n=e.name;return L(n)},oe=function(e){return e.name===O.Chrome},ae=function(e){return e.name===O.Firefox},ie=function(e){return e.name===O.Chromium},re=function(e){return e.name===O.Edge},se=function(e){return e.name===O.Yandex},ce=function(e){var n=e.name;return n===O.Safari||n===O.MobileSafari},le=function(e){return e.name===O.MobileSafari},de=function(e){return e.name===O.Opera},ue=function(e){var n=e.name;return n===O.InternetExplorer||n===O.Ie},fe=function(e){return e.name===O.MIUI},pe=function(e){return e.name===O.SamsungBrowser},he=function(e){var n=e.version;return L(n)},me=function(e){var n=e.major;return L(n)},we=function(e){var n=e.name;return L(n)},be=function(e){var n=e.name;return L(n)},ge=function(e){var n=e.version;return L(n)},Ae=function(){var e=M(),n=e&&e.userAgent&&e.userAgent.toLowerCase();return"string"==typeof n&&/electron/.test(n)},ye=function(e){return"string"==typeof e&&-1!==e.indexOf("Edg/")},ve=function(){var e=M();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")},Ce=function(){return P("iPod")},Te=function(e){return L(e)};function Ee(e){var n=e||w,t=n.device,o=n.browser,a=n.os,i=n.engine,r=n.ua;return{isSmartTV:q(t),isConsole:V(t),isWearable:W(t),isEmbedded:z(t),isMobileSafari:le(o)||ke(),isChromium:ie(o),isMobile:Y(t)||ke(),isMobileOnly:H(t),isTablet:J(t)||ke(),isBrowser:G(t),isDesktop:G(t),isAndroid:K(a),isWinPhone:$(a),isIOS:ee(a)||ke(),isChrome:oe(o),isFirefox:ae(o),isSafari:ce(o),isOpera:de(o),isIE:ue(o),osVersion:ne(a),osName:te(a),fullBrowserVersion:he(o),browserVersion:me(o),browserName:we(o),mobileVendor:j(t),mobileModel:X(t),engineName:be(i),engineVersion:ge(i),getUA:Te(r),isEdge:re(o)||ye(r),isYandex:se(o),deviceType:Q(t),isIOS13:ve(),isIPad13:ke(),isIPhone13:xe(),isIPod13:Ce(),isElectron:Ae(),isEdgeChromium:ye(r),isLegacyEdge:re(o)&&!ye(r),isWindows:Z(a),isMacOs:_(a),isMIUI:fe(o),isSamsungBrowser:pe(o)}}var Ie=q(d),Ne=V(d),Se=W(d),Be=z(d),Fe=le(c)||ke(),Re=ie(c),Oe=Y(d)||ke(),De=H(d),Ue=J(d)||ke(),Le=G(d),Me=G(d),Pe=K(f),He=$(f),Je=ee(f)||ke(),Ye=oe(c),qe=ae(c),Ge=ce(c),We=de(c),Ve=ue(c),ze=ne(f),je=te(f),Xe=he(c),Qe=me(c),Ke=we(c),Ze=j(d),_e=X(d),$e=be(u),en=ge(u),nn=Te(p),tn=re(c)||ye(p),on=se(c),an=Q(d),rn=ve(),sn=ke(),cn=xe(),ln=Ce(),dn=Ae(),un=ye(p),fn=re(c)&&!ye(p),pn=Z(f),hn=_(f),mn=fe(c),wn=pe(c);function bn(e){var n=e||window.navigator.userAgent;return m(n)}return _o.AndroidView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Pe?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.BrowserTypes=O,_o.BrowserView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Le?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.ConsoleView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Ne?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.CustomView=function(e){var n=e.renderWithFragment,t=e.children;e.viewClassName,e.style;var o=e.condition,r=x(e,["renderWithFragment","children","viewClassName","style","condition"]);return o?n?i.createElement(a.Fragment,null,t):i.createElement("div",r,t):null},_o.IEView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Ve?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.IOSView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Je?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.MobileOnlyView=function(e){var n=e.renderWithFragment,t=e.children;e.viewClassName,e.style;var o=x(e,["renderWithFragment","children","viewClassName","style"]);return De?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.MobileView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Oe?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.OsTypes=D,_o.SmartTVView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Ie?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.TabletView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Ue?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.WearableView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return Se?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.WinPhoneView=function(e){var n=e.renderWithFragment,t=e.children,o=x(e,["renderWithFragment","children"]);return He?n?i.createElement(a.Fragment,null,t):i.createElement("div",o,t):null},_o.browserName=Ke,_o.browserVersion=Qe,_o.deviceDetect=function(e){var n=e?m(e):w,t=n.device,o=n.browser,a=n.engine,i=n.os,r=n.ua,s=function(e){switch(e){case E:return{isMobile:!0};case I:return{isTablet:!0};case N:return{isSmartTV:!0};case S:return{isConsole:!0};case B:return{isWearable:!0};case R:return{isBrowser:!0};case F:return{isEmbedded:!0};default:return U}}(t.type),c=s.isBrowser,l=s.isMobile,d=s.isTablet,u=s.isSmartTV,f=s.isConsole,p=s.isWearable,h=s.isEmbedded;return c?function(e,n,t,o,a){return{isBrowser:e,browserMajorVersion:L(n.major),browserFullVersion:L(n.version),browserName:L(n.name),engineName:L(t.name),engineVersion:L(t.version),osName:L(o.name),osVersion:L(o.version),userAgent:L(a)}}(c,o,a,i,r):u?function(e,n,t,o){return{isSmartTV:e,engineName:L(n.name),engineVersion:L(n.version),osName:L(t.name),osVersion:L(t.version),userAgent:L(o)}}(u,a,i,r):f?function(e,n,t,o){return{isConsole:e,engineName:L(n.name),engineVersion:L(n.version),osName:L(t.name),osVersion:L(t.version),userAgent:L(o)}}(f,a,i,r):l||d?function(e,n,t,o){return function(e){for(var n=1;n<arguments.length;n++){var t=null!=arguments[n]?arguments[n]:{};n%2?b(Object(t),!0).forEach(function(n){A(e,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):b(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})}return e}({},e,{vendor:L(n.vendor),model:L(n.model),os:L(t.name),osVersion:L(t.version),ua:L(o)})}(s,t,i,r):p?function(e,n,t,o){return{isWearable:e,engineName:L(n.name),engineVersion:L(n.version),osName:L(t.name),osVersion:L(t.version),userAgent:L(o)}}(p,a,i,r):h?function(e,n,t,o,a){return{isEmbedded:e,vendor:L(n.vendor),model:L(n.model),engineName:L(t.name),engineVersion:L(t.version),osName:L(o.name),osVersion:L(o.version),userAgent:L(a)}}(h,t,a,i,r):void 0},_o.deviceType=an,_o.engineName=$e,_o.engineVersion=en,_o.fullBrowserVersion=Xe,_o.getSelectorsByUserAgent=function(e){if(e&&"string"==typeof e){var n=m(e);return Ee({device:n.device,browser:n.browser,os:n.os,engine:n.engine,ua:n.ua})}},_o.getUA=nn,_o.isAndroid=Pe,_o.isBrowser=Le,_o.isChrome=Ye,_o.isChromium=Re,_o.isConsole=Ne,_o.isDesktop=Me,_o.isEdge=tn,_o.isEdgeChromium=un,_o.isElectron=dn,_o.isEmbedded=Be,_o.isFirefox=qe,_o.isIE=Ve,_o.isIOS=Je,_o.isIOS13=rn,_o.isIPad13=sn,_o.isIPhone13=cn,_o.isIPod13=ln,_o.isLegacyEdge=fn,_o.isMIUI=mn,_o.isMacOs=hn,_o.isMobile=Oe,_o.isMobileOnly=De,_o.isMobileSafari=Fe,_o.isOpera=We,_o.isSafari=Ge,_o.isSamsungBrowser=wn,_o.isSmartTV=Ie,_o.isTablet=Ue,_o.isWearable=Se,_o.isWinPhone=He,_o.isWindows=pn,_o.isYandex=on,_o.mobileModel=_e,_o.mobileVendor=Ze,_o.osName=je,_o.osVersion=ze,_o.parseUserAgent=m,_o.setUserAgent=function(e){return h(e)},_o.useDeviceData=bn,_o.useDeviceSelectors=function(e){var n=bn(e||window.navigator.userAgent);return[Ee(n),n]},_o.useMobileOrientation=function(){var e,n,t=(e=a.useState(function(){var e=window.innerWidth>window.innerHeight?90:0;return{isPortrait:0===e,isLandscape:90===e,orientation:0===e?"portrait":"landscape"}}),n=2,function(e){if(Array.isArray(e))return e}(e)||function(e,n){var t=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=t){var o,a,i=[],r=!0,s=!1;try{for(t=t.call(e);!(r=(o=t.next()).done)&&(i.push(o.value),!n||i.length!==n);r=!0);}catch(c){s=!0,a=c}finally{try{r||null==t.return||t.return()}finally{if(s)throw a}}return i}}(e,n)||function(e,n){if(e){if("string"==typeof e)return T(e,n);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?T(e,n):void 0}}(e,n)||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.")}()),o=t[0],i=t[1],r=a.useCallback(function(){var e=window.innerWidth>window.innerHeight?90:0,n={isPortrait:0===e,isLandscape:90===e,orientation:0===e?"portrait":"landscape"};o.orientation!==n.orientation&&i(n)},[o.orientation]);return a.useEffect(function(){return void 0!==("undefined"==typeof window?"undefined":g(window))&&Oe&&(r(),window.addEventListener("load",r,!1),window.addEventListener("resize",r,!1)),function(){window.removeEventListener("resize",r,!1),window.removeEventListener("load",r,!1)}},[r]),o},_o.withOrientationChange=function(e){/* @__PURE__ */
20
- return function(n){function t(e){var n;return function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,n){if(n&&("object"==typeof n||"function"==typeof n))return n;if(void 0!==n)throw new TypeError("Derived constructors may only return object or undefined");return C(e)}(this,v(t).call(this,e))).isEventListenerAdded=!1,n.handleOrientationChange=n.handleOrientationChange.bind(C(n)),n.onOrientationChange=n.onOrientationChange.bind(C(n)),n.onPageLoad=n.onPageLoad.bind(C(n)),n.state={isLandscape:!1,isPortrait:!1},n}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&k(e,n)}(t,n),o=t,(a=[{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))&&Oe&&(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 i.createElement(e,y({},this.props,{isLandscape:this.state.isLandscape,isPortrait:this.state.isPortrait}))}}])&&function(e,n){for(var t=0;t<n.length;t++){var o=n[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}(o.prototype,a),t;var o,a}(i.Component)},_o}();const ta="gemini-2.0-flash-lite",oa=new class extends Co{enableGoogleSearch=!0;constructor(){super("https://nft-demo.keyring.app")}async generateContent(e,n){try{const t=`\nBelow is the system context and conversation history. Use it for context but prioritize the instructions at the end.\n---\nSYSTEM CONTEXT & HISTORY:\n${n}\n---\n\n---\nCURRENT USER QUESTION:\n${e}\n---\n\n---\n### MANDATORY RULES:\n1. **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.\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`,o="/api/gemini-cortex/proxy",a={model:"gemini-2.5-flash-lite",data:{contents:[{parts:[{text:t}]}],tools:[{googleSearch:{}}]}};this.enableGoogleSearch||delete a.data.tools;const i=await this.post(o,a);return i?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||i?.data?.candidates?.[0]?.content?.parts?.[0]?.text}catch(t){if((t?.message?.includes("search_grounding_request_per_project_per_day")||t?.data?.error?.message?.includes("search_grounding_request_per_project_per_day"))&&this.enableGoogleSearch)return this.enableGoogleSearch=!1,await this.generateContent(e,n);throw t}}async checkTypeQuestion(e,n){try{const t=n+`---\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\nOtherwise, respond with ONLY the word "no" (lowercase, nothing else).\nDo not provide any explanation or additional text.`,o="/api/gemini-cortex/proxy",a={model:ta,data:{contents:[{parts:[{text:t}]}]}},i=await this.post(o,a);return i?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||i?.data?.candidates?.[0]?.content?.parts?.[0]?.text}catch(t){throw t}}async checkIsQuestionActionWeb3(e,n){try{const t=n+`---\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.`,o="/api/gemini-cortex/proxy",a={model:ta,data:{contents:[{parts:[{text:t}]}]}},i=await this.post(o,a);return i?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||i?.data?.candidates?.[0]?.content?.parts?.[0]?.text}catch(t){throw t}}};function aa(n){const t=[],o=/!\[([^\]]*)\]\(([^)]+)\)|\[([^\]]*)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)|\*\*(.+?)\*\*|__(.+?)__|\*(.+?)\*|_(.+?)_|~~(.+?)~~|`([^`]+)`/g;let a,i=0;for(;null!==(a=o.exec(n));)a.index>i&&t.push(n.slice(i,a.index)),void 0!==a[1]||void 0!==a[2]?t.push(
20
+ return function(n){function t(e){var n;return function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,n){if(n&&("object"==typeof n||"function"==typeof n))return n;if(void 0!==n)throw new TypeError("Derived constructors may only return object or undefined");return C(e)}(this,v(t).call(this,e))).isEventListenerAdded=!1,n.handleOrientationChange=n.handleOrientationChange.bind(C(n)),n.onOrientationChange=n.onOrientationChange.bind(C(n)),n.onPageLoad=n.onPageLoad.bind(C(n)),n.state={isLandscape:!1,isPortrait:!1},n}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),n&&k(e,n)}(t,n),o=t,(a=[{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))&&Oe&&(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 i.createElement(e,y({},this.props,{isLandscape:this.state.isLandscape,isPortrait:this.state.isPortrait}))}}])&&function(e,n){for(var t=0;t<n.length;t++){var o=n[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}(o.prototype,a),t;var o,a}(i.Component)},_o}();const ta="gemini-2.0-flash-lite",oa=new class extends Co{enableGoogleSearch=!0;constructor(){super("https://nft-demo.keyring.app")}async generateContent(e,n){try{const t=`\nBelow is the system context and conversation history. Use it for context but prioritize the instructions at the end.\n---\nSYSTEM CONTEXT & HISTORY:\n${n}\n---\n\n---\nCURRENT USER QUESTION:\n${e}\n---\n\n---\n### MANDATORY RULES:\n1. **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.\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`,o="/api/gemini-cortex/proxy",a={model:"gemini-2.5-flash-lite",data:{contents:[{parts:[{text:t}]}],tools:[{googleSearch:{}}]}};this.enableGoogleSearch||delete a.data.tools;const i=await this.post(o,a);return i?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||i?.data?.candidates?.[0]?.content?.parts?.[0]?.text}catch(t){if((t?.message?.includes("search_grounding_request_per_project_per_day")||t?.data?.error?.message?.includes("search_grounding_request_per_project_per_day"))&&this.enableGoogleSearch)return this.enableGoogleSearch=!1,await this.generateContent(e,n);throw t}}async checkIsQuestionNormal(e,n){try{const t=n+`---\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\nOtherwise, respond with ONLY the word "no" (lowercase, nothing else).\nDo not provide any explanation or additional text.`,o="/api/gemini-cortex/proxy",a={model:ta,data:{contents:[{parts:[{text:t}]}]}},i=await this.post(o,a),r=i?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||i?.data?.candidates?.[0]?.content?.parts?.[0]?.text;return r?.toLowerCase()?.startsWith("no")}catch(t){throw t}}async checkIsQuestionActionWeb3(e,n){try{const t=n+`---\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.`,o="/api/gemini-cortex/proxy",a={model:ta,data:{contents:[{parts:[{text:t}]}]}},i=await this.post(o,a),r=i?.data?.data?.candidates?.[0]?.content?.parts?.[0]?.text||i?.data?.candidates?.[0]?.content?.parts?.[0]?.text;return r?.toLowerCase()?.startsWith("yes")}catch(t){throw t}}};function aa(n){const t=[],o=/!\[([^\]]*)\]\(([^)]+)\)|\[([^\]]*)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)|\*\*(.+?)\*\*|__(.+?)__|\*(.+?)\*|_(.+?)_|~~(.+?)~~|`([^`]+)`/g;let a,i=0;for(;null!==(a=o.exec(n));)a.index>i&&t.push(n.slice(i,a.index)),void 0!==a[1]||void 0!==a[2]?t.push(
21
21
  /* @__PURE__ */e("img",{src:a[2],alt:a[1],className:"mc-image",onError:e=>{e.target.src="data:image/svg+xml,%3csvg%20width='180'%20height='180'%20viewBox='0%200%20180%20180'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20opacity='0.1'%3e%3cpath%20d='M102.392%20118.157L102.417%20109.35L89.7594%20102.042C89.5768%20101.937%2089.3953%20101.826%2089.2149%20101.71L89.1861%20101.692C89.012%20101.581%2088.839%20101.47%2088.666%20101.346C88.6061%20101.305%2088.5473%20101.262%2088.4874%20101.22C88.3765%20101.139%2088.259%20101.057%2088.1459%20100.972C88.0749%20100.919%2088.0051%20100.861%2087.9352%20100.811C87.8321%20100.733%2087.73%20100.653%2087.6291%20100.571C87.5552%20100.51%2087.4813%20100.449%2087.4073%20100.387C87.3098%20100.306%2087.2125%20100.224%2087.1157%20100.141C87.0418%20100.075%2086.9678%20100.009%2086.8939%2099.9421C86.7985%2099.8578%2086.7039%2099.772%2086.61%2099.6848C86.5346%2099.6149%2086.4592%2099.5462%2086.3882%2099.4752C86.2929%2099.3843%2086.1986%2099.2922%2086.1044%2099.2002C86.0356%2099.1325%2085.9657%2099.0649%2085.897%2098.9961C85.7983%2098.8963%2085.7007%2098.7954%2085.6031%2098.6934C85.541%2098.628%2085.4778%2098.5637%2085.4168%2098.4982C85.3059%2098.3763%2085.195%2098.2521%2085.0786%2098.1267L84.9533%2097.9881C84.7995%2097.8137%2084.648%2097.6366%2084.4986%2097.457C84.4643%2097.4159%2084.4321%2097.3738%2084.3977%2097.3328C84.2868%2097.1919%2084.1671%2097.05%2084.054%2096.9069C83.9172%2096.7325%2083.7826%2096.5558%2083.6503%2096.3769L83.5827%2096.2881C83.3675%2095.9965%2083.1591%2095.6971%2082.955%2095.3943L82.8441%2095.228C82.5876%2094.8421%2082.341%2094.4495%2082.1045%2094.0503L82.0135%2093.8984C81.8487%2093.616%2081.6886%2093.3306%2081.5334%2093.0423C81.4768%2092.937%2081.4225%2092.8316%2081.3681%2092.7263C81.3138%2092.6209%2081.2572%2092.5045%2081.1952%2092.3936C81.1164%2092.2361%2081.0399%2092.0787%2080.9634%2091.9201C80.939%2091.8691%2080.9135%2091.8181%2080.8891%2091.7671C80.793%2091.5623%2080.6995%2091.3564%2080.6085%2091.1494C80.5852%2091.095%2080.562%2091.0385%2080.5398%2090.9875C80.4732%2090.8337%2080.4082%2090.6792%2080.3446%2090.524L80.2592%2090.3121C80.2008%2090.1643%2080.1435%2090.0164%2080.0873%2089.8686C80.0629%2089.8043%2080.0385%2089.7388%2080.0141%2089.6745C79.9454%2089.486%2079.8789%2089.2971%2079.8145%2089.1079L79.789%2089.0347C79.7151%2088.8218%2079.6471%2088.6088%2079.585%2088.3959C79.5639%2088.3283%2079.5451%2088.2606%2079.5262%2088.193C79.483%2088.0444%2079.4397%2087.8958%2079.3998%2087.7494C79.3776%2087.6685%2079.3566%2087.5875%2079.3355%2087.5066C79.3%2087.3691%2079.2656%2087.2319%2079.2324%2087.0952C79.2131%2087.0138%2079.1943%2086.9325%2079.1758%2086.8512C79.1436%2086.7104%2079.1137%2086.5695%2079.0849%2086.4298C79.0693%2086.3555%2079.0538%2086.2801%2079.0394%2086.208C79.0047%2086.0276%2078.9725%2085.848%2078.9429%2085.6691C78.9429%2085.638%2078.9318%2085.607%2078.9274%2085.5759C78.8941%2085.366%2078.8646%2085.1564%2078.8387%2084.9472C78.832%2084.8906%2078.8265%2084.8363%2078.8198%2084.7775C78.8028%2084.6259%2078.7873%2084.4748%2078.7733%2084.3239C78.7666%2084.253%2078.7622%2084.182%2078.7566%2084.1121C78.7455%2083.9702%2078.7378%2083.8294%2078.7311%2083.6885C78.7311%2083.622%2078.7245%2083.5544%2078.7222%2083.4878C78.7156%2083.2882%2078.71%2083.0897%2078.7112%2082.8934L78.7466%2069.3645L77.6377%2068.7258L71.9567%2065.45C70.7912%2064.7503%2069.5073%2064.2703%2068.1686%2064.0339V64.0417C68.1597%2064.1105%2068.1542%2064.1825%2068.1464%2064.2513C68.1387%2064.32%2068.1298%2064.4021%2068.1231%2064.4797C68.1231%2064.5119%2068.1165%2064.5418%2068.1132%2064.574C68.1043%2064.676%2068.0999%2064.7802%2068.0943%2064.8845C68.0943%2064.941%2068.0865%2064.9954%2068.0843%2065.0541V65.0952C68.0769%2065.2704%2068.0729%2065.4482%2068.0721%2065.6286V65.6607L68.0078%2089.1023C68.0078%2089.2679%2068.01%2089.4339%2068.0145%2089.6002C68.0145%2089.6324%2068.0145%2089.6634%2068.0145%2089.6956C68.0145%2089.7632%2068.0211%2089.832%2068.0244%2089.8996C68.0278%2089.9673%2068.03%2090.056%2068.0355%2090.1347C68.0355%2090.1957%2068.0455%2090.2578%2068.05%2090.3199C68.0544%2090.382%2068.061%2090.463%2068.0677%2090.535C68.0677%2090.5805%2068.0743%2090.6271%2068.0788%2090.6725C68.0888%2090.7757%2068.1021%2090.8799%2068.1132%2090.9842C68.1198%2091.0418%2068.1254%2091.095%2068.132%2091.1583L68.1387%2091.2137C68.1623%2091.3985%2068.1886%2091.5833%2068.2174%2091.7682V91.7837C68.2174%2091.8147%2068.2285%2091.8469%2068.234%2091.8779C68.2584%2092.0277%2068.2839%2092.1774%2068.3117%2092.3282C68.3172%2092.357%2068.3239%2092.3858%2068.3294%2092.4147C68.3438%2092.4901%2068.3604%2092.5655%2068.376%2092.6365C68.3915%2092.7074%2068.4104%2092.8128%2068.4292%2092.9004C68.4403%2092.9525%2068.4536%2093.0046%2068.4658%2093.0556C68.4843%2093.1362%2068.5031%2093.2172%2068.5224%2093.2985C68.5368%2093.3595%2068.5501%2093.4205%2068.5645%2093.4803C68.5789%2093.5402%2068.6055%2093.6345%2068.6255%2093.711C68.6454%2093.7875%2068.6676%2093.8729%2068.6887%2093.9527C68.6998%2093.9916%2068.7087%2094.0304%2068.7186%2094.0636C68.7486%2094.1745%2068.7818%2094.2854%2068.8151%2094.3963C68.8351%2094.464%2068.8539%2094.5316%2068.8739%2094.5993L68.8894%2094.6547C68.9478%2094.8462%2069.0092%2095.0376%2069.0735%2095.2291V95.2391L69.099%2095.3123C69.1533%2095.4731%2069.2099%2095.6339%2069.2676%2095.7947C69.2775%2095.8224%2069.2886%2095.8501%2069.2986%2095.8778C69.3219%2095.9422%2069.3463%2096.0054%2069.3707%2096.0697C69.4039%2096.1595%2069.4372%2096.2482%2069.4716%2096.338C69.4949%2096.3979%2069.5193%2096.4567%2069.5437%2096.5166L69.628%2096.7262C69.649%2096.7761%2069.6679%2096.8271%2069.6889%2096.877C69.7322%2096.9812%2069.7777%2097.0855%2069.8231%2097.1897C69.8464%2097.244%2069.8686%2097.3006%2069.893%2097.3516L69.9174%2097.4082C69.9972%2097.5878%2070.0789%2097.7671%2070.1625%2097.946L70.1735%2097.9704C70.1979%2098.0214%2070.2234%2098.0724%2070.2478%2098.1234C70.3133%2098.2598%2070.3776%2098.3973%2070.4452%2098.5326L70.4785%2098.5969C70.5351%2098.7078%2070.5894%2098.8187%2070.6515%2098.9296C70.6981%2099.0194%2070.7424%2099.1093%2070.7901%2099.198L70.8167%2099.2456C70.9712%2099.534%2071.1313%2099.8193%2071.2969%20100.102C71.3113%20100.126%2071.3235%20100.151%2071.3379%20100.175C71.3523%20100.199%2071.3723%20100.227%2071.3878%20100.254C71.6244%20100.653%2071.8709%20101.045%2072.1275%20101.431C72.1419%20101.452%2072.1541%20101.475%2072.1685%20101.497C72.1829%20101.519%2072.2173%20101.564%2072.2406%20101.6C72.4446%20101.902%2072.652%20102.201%2072.8682%20102.493L72.9314%20102.575C73.0645%20102.754%2073.1994%20102.931%2073.3362%20103.107L73.3595%20103.137C73.4704%20103.272%2073.5746%20103.405%2073.6833%20103.537L73.7798%20103.656L73.7875%20103.665C73.9287%20103.835%2074.0718%20104.002%2074.2167%20104.167L74.2344%20104.187L74.3597%20104.326C74.4551%20104.437%2074.5516%20104.541%2074.6481%20104.646L74.698%20104.698C74.7601%20104.764%2074.8222%20104.828%2074.8843%20104.893C74.9464%20104.959%2075.0284%20105.046%2075.106%20105.122L75.1814%20105.197C75.2502%20105.266%2075.319%20105.334%2075.3888%20105.401C75.4587%20105.469%2075.5108%20105.524%2075.5729%20105.583L75.6727%20105.676C75.747%20105.747%2075.8224%20105.817%2075.8945%20105.886C75.9488%20105.936%2076.0054%20105.987%2076.0564%20106.036L76.1784%20106.146L76.4002%20106.345C76.4478%20106.386%2076.4944%20106.429%2076.5432%20106.469C76.592%20106.509%2076.643%20106.55%2076.6918%20106.59L76.9136%20106.774C76.9535%20106.806%2076.9923%20106.84%2077.0322%20106.872C77.0943%20106.921%2077.1576%20106.967%2077.2197%20107.015C77.2818%20107.062%2077.3594%20107.126%2077.4292%20107.174L77.5168%20107.241C77.6011%20107.303%2077.6876%20107.362%2077.7719%20107.423C77.8307%20107.465%2077.8894%20107.508%2077.9493%20107.549L77.997%20107.584C78.1523%20107.69%2078.3086%20107.794%2078.4661%20107.894L78.4905%20107.91C78.6357%20108.002%2078.7821%20108.092%2078.9341%20108.178L79.0449%20108.241L98.4999%20119.478C98.6175%20119.546%2098.7346%20119.611%2098.8515%20119.674L98.9867%20119.744L99.1653%20119.836C99.2119%20119.859%2099.2584%20119.885%2099.3039%20119.908C99.3793%20119.946%2099.4547%20119.979%2099.5257%20120.019L99.6832%20120.093L99.7464%20120.123C99.8942%20120.19%20100.042%20120.252%20100.19%20120.311L100.208%20120.317C100.35%20120.374%20100.492%20120.428%20100.633%20120.477L100.693%20120.497L100.856%20120.55C100.93%20120.575%20101.004%20120.6%20101.078%20120.622L101.189%20120.655L101.385%20120.709C101.434%20120.722%20101.484%20120.738%20101.532%20120.75C101.579%20120.762%20101.643%20120.773%20101.693%20120.785L101.888%20120.829L101.986%20120.851L102.085%20120.867C102.158%20120.553%20102.219%20120.227%20102.266%20119.886C102.346%20119.313%20102.388%20118.736%20102.392%20118.157Z'%20fill='url(%23paint0_linear_302_6100)'/%3e%3cpath%20d='M91.4307%2064.3019L78.0005%2056.5472L75.8214%2055.2885L71.9957%2053.0796C59.9427%2046.1222%2050.1032%2051.73%2050.0633%2065.5794L50.0001%2087.9076C49.9613%20101.769%2059.7365%20118.694%2071.7894%20125.652L91.2244%20136.872C103.276%20143.831%20113.117%20138.227%20113.156%20124.373L113.183%20114.546V113.668L113.217%20102.041C113.259%2088.1926%20103.482%2071.2604%2091.4307%2064.3019ZM102.419%20108.881V109.349L102.395%20118.156C102.394%20118.733%20102.355%20119.309%20102.278%20119.881C102.232%20120.222%20102.167%20120.547%20102.097%20120.863C100.943%20125.853%2096.5184%20127.534%2091.2621%20124.5L71.8249%20113.283C65.708%20109.753%2060.7478%20101.16%2060.7678%2094.1275L60.831%2071.7949C60.8454%2066.777%2063.3948%2063.8927%2067.0787%2063.9382C67.4454%2063.9447%2067.8112%2063.9777%2068.1732%2064.0369C69.5103%2064.2737%2070.7927%2064.7537%2071.9568%2065.453L77.6312%2068.7232L78.7401%2069.3619L91.3974%2076.6697C97.512%2080.205%20102.476%2088.7947%20102.452%2095.8275L102.419%20108.881Z'%20fill='url(%23paint1_linear_302_6100)'/%3e%3cpath%20d='M129.993%2090.9695C129.993%2090.9063%20129.987%2090.842%20129.985%2090.7788C129.985%2090.648%20129.972%2090.516%20129.966%2090.3851C129.958%2090.2288%20129.953%2090.0746%20129.944%2089.9172C129.936%2089.7952%20129.924%2089.671%20129.914%2089.5479C129.904%2089.4248%20129.892%2089.2707%20129.88%2089.1309C129.873%2089.04%20129.867%2088.9491%20129.858%2088.8582C129.838%2088.6519%20129.813%2088.4445%20129.789%2088.2383C129.776%2088.1274%20129.766%2088.0165%20129.752%2087.9056C129.752%2087.869%20129.744%2087.8324%20129.739%2087.7947C129.694%2087.431%20129.642%2087.0658%20129.583%2086.6991L129.578%2086.6669C129.568%2086.6037%20129.555%2086.5405%20129.544%2086.4773C129.497%2086.1845%20129.448%2085.8918%20129.392%2085.5979C129.381%2085.5391%20129.368%2085.4815%20129.357%2085.4227C129.328%2085.2752%20129.297%2085.1277%20129.267%2084.9791C129.232%2084.805%20129.199%2084.632%20129.156%2084.459C129.134%2084.3559%20129.107%2084.2528%20129.084%2084.1497C129.048%2083.99%20129.011%2083.8303%20128.973%2083.6706C128.944%2083.5519%20128.92%2083.4333%20128.89%2083.3146C128.852%2083.1627%20128.809%2083.0097%20128.77%2082.8566C128.731%2082.7036%20128.688%2082.5395%20128.645%2082.3809C128.625%2082.3055%20128.606%2082.2301%20128.585%2082.1591C128.524%2081.9373%20128.458%2081.7222%20128.393%2081.5038C128.354%2081.3729%20128.318%2081.2409%20128.282%2081.1101C128.271%2081.0746%20128.262%2081.0391%20128.251%2080.9992C128.135%2080.6214%20128.014%2080.244%20127.889%2079.867L127.881%2079.8448C127.863%2079.7927%20127.844%2079.7417%20127.827%2079.6896C127.716%2079.3768%20127.613%2079.063%20127.494%2078.7503C127.474%2078.6948%20127.452%2078.6394%20127.432%2078.584C127.385%2078.4564%20127.336%2078.3289%20127.288%2078.2014C127.222%2078.0273%20127.159%2077.8532%20127.091%2077.6791C127.046%2077.5615%20126.997%2077.4451%20126.949%2077.3275C126.894%2077.1886%20126.838%2077.0499%20126.782%2076.9117C126.742%2076.813%20126.704%2076.7143%20126.663%2076.6167C126.577%2076.4094%20126.487%2076.2042%20126.398%2075.9979C126.353%2075.8871%20126.308%2075.7861%20126.262%2075.6797L126.215%2075.5688C126.059%2075.2147%20125.898%2074.8617%20125.733%2074.5098L125.711%2074.4632C125.661%2074.3523%20125.608%2074.2525%20125.558%2074.146C125.431%2073.881%20125.305%2073.616%20125.174%2073.3532C125.153%2073.311%20125.13%2073.2689%20125.109%2073.2256C124.998%2073.0038%20124.887%2072.7821%20124.768%2072.5669C124.677%2072.3906%20124.589%2072.2143%20124.495%2072.0391C124.478%2072.0069%20124.459%2071.9759%20124.441%2071.9426C124.136%2071.3756%20123.821%2070.8137%20123.495%2070.257C123.467%2070.2094%20123.443%2070.1617%20123.415%2070.114C123.333%2069.9743%20123.247%2069.8379%20123.164%2069.6992C123.024%2069.4675%20122.885%2069.2357%20122.742%2069.0062C122.618%2068.8066%20122.492%2068.6092%20122.365%2068.4118C122.22%2068.19%20122.076%2067.9604%20121.927%2067.7364C121.877%2067.6599%20121.829%2067.5823%20121.778%2067.5069C121.727%2067.4315%20121.682%2067.3727%20121.635%2067.304C121.233%2066.7085%20120.824%2066.1196%20120.4%2065.5441L120.395%2065.5352C120.354%2065.4787%20120.309%2065.4243%20120.268%2065.3689C120.006%2065.017%20119.741%2064.6688%20119.472%2064.3243L119.425%2064.2633C119.215%2063.996%20119%2063.7343%20118.786%2063.4715C118.722%2063.395%20118.661%2063.3163%20118.598%2063.2398L118.584%2063.222C118.306%2062.8879%20118.024%2062.5581%20117.739%2062.2328L117.702%2062.1929C117.621%2062.0998%20117.537%2062.0111%20117.455%2061.919C117.266%2061.7083%20117.078%2061.4954%20116.886%2061.2892L116.788%2061.1871C116.666%2061.0563%20116.542%2060.9288%20116.418%2060.799C116.276%2060.6504%20116.135%2060.4985%20115.991%2060.3554C115.942%2060.3055%20115.891%2060.2579%20115.841%2060.208C115.706%2060.0716%20115.57%2059.9385%20115.433%2059.8043C115.297%2059.6701%20115.193%2059.5626%20115.071%2059.445C115.005%2059.3829%20114.939%2059.323%20114.873%2059.2609C114.726%2059.1212%20114.577%2058.9837%20114.43%2058.8473C114.319%2058.7497%20114.219%2058.6488%20114.112%2058.5523C114.034%2058.4814%20113.953%2058.4137%20113.873%2058.3427C113.725%2058.2104%20113.575%2058.0796%20113.424%2057.9502C113.33%2057.8692%20113.238%2057.7849%20113.142%2057.7051C113.047%2057.6253%20112.946%2057.5465%20112.848%2057.4656C112.7%2057.3443%20112.553%2057.2242%20112.405%2057.1052C112.326%2057.042%20112.248%2056.9754%20112.169%2056.9122C112.045%2056.8157%20111.921%2056.7248%20111.798%2056.6294C111.675%2056.5341%20111.523%2056.4176%20111.386%2056.3145C111.328%2056.2713%20111.275%2056.2258%20111.213%2056.1826C111.045%2056.0595%20110.88%2055.943%20110.707%2055.8233C110.596%2055.7412%20110.476%2055.6569%20110.36%2055.5771L110.265%2055.5094C109.958%2055.2995%20109.651%2055.0958%20109.341%2054.8984H109.334L109.288%2054.8696C109%2054.6877%20108.711%2054.5092%20108.42%2054.3384L108.206%2054.2142L88.7824%2042.9941C88.551%2042.8603%2088.3204%2042.7313%2088.0904%2042.6071C88.0017%2042.5594%2087.9141%2042.5162%2087.8254%2042.4696L87.4717%2042.2866C87.3807%2042.24%2087.2887%2042.1901%2087.1989%2042.1447C87.0492%2042.0704%2086.9017%2042.0049%2086.7553%2041.9351C86.6511%2041.8863%2086.5479%2041.8353%2086.4448%2041.7887L86.3195%2041.7299C86.0238%2041.5991%2085.7332%2041.476%2085.4479%2041.3607L85.4035%2041.344C85.1252%2041.2331%2084.8491%2041.1289%2084.5729%2041.0313L84.4465%2040.9847C84.3356%2040.9481%2084.2336%2040.9149%2084.1271%2040.8805C83.9819%2040.8328%2083.8366%2040.7818%2083.6924%2040.7385C83.6159%2040.7153%2083.5405%2040.6975%2083.464%2040.6753C83.3354%2040.6376%2083.2078%2040.6033%2083.0792%2040.5644C82.9827%2040.5389%2082.8851%2040.5079%2082.7898%2040.4846C82.6944%2040.4613%2082.5802%2040.4436%2082.4737%2040.4192C82.3462%2040.3903%2082.2176%2040.3604%2082.0912%2040.3327C82.0268%2040.3194%2081.9603%2040.3016%2081.896%2040.2894C81.7729%2040.265%2081.6531%2040.2506%2081.53%2040.2295C81.3826%2040.204%2081.234%2040.1774%2081.0865%2040.1564C81.0388%2040.1508%2080.9878%2040.1397%2080.939%2040.1331C80.8148%2040.1109%2080.6928%2040.1109%2080.5697%2040.0954C80.4122%2040.0776%2080.2548%2040.0599%2080.0995%2040.0477C80.0563%2040.0477%2080.0108%2040.0377%2079.9676%2040.0344C79.8567%2040.0266%2079.7558%2040.0288%2079.6482%2040.0233C79.4608%2040.0144%2079.2756%2040.0067%2079.0893%2040C79.0394%2040%2078.9884%2040%2078.9385%2040C78.8575%2040%2078.7799%2040.01%2078.699%2040.0111C78.4661%2040.0111%2078.2354%2040.0266%2078.0081%2040.0432C77.9405%2040.0432%2077.8706%2040.0432%2077.8041%2040.0532C77.7054%2040.0621%2077.61%2040.0765%2077.5124%2040.0876L77.3017%2040.1109C77.0455%2040.1453%2076.7916%2040.1841%2076.5421%2040.2351L76.5144%2040.244C76.4401%2040.2595%2076.368%2040.2794%2076.2926%2040.2961C76.0897%2040.3415%2075.8878%2040.3892%2075.6904%2040.4447C75.5895%2040.4735%2075.4919%2040.5068%2075.3921%2040.5389C75.2646%2040.5789%2075.1349%2040.6143%2075.0085%2040.6598C74.9752%2040.6709%2074.9441%2040.6875%2074.912%2040.6986C74.7146%2040.7707%2074.5239%2040.8517%2074.332%2040.9348C74.2389%2040.9747%2074.1435%2041.0113%2074.0526%2041.0535C73.7731%2041.1843%2073.4981%2041.3252%2073.2331%2041.4793L62.5375%2047.6893C62.8036%2047.5351%2063.0775%2047.3943%2063.3559%2047.2635C63.4479%2047.2202%2063.5433%2047.1847%2063.6364%2047.1437C63.8272%2047.0605%2064.019%2046.9796%2064.2153%2046.9075C64.3727%2046.8498%2064.5335%2046.7966%2064.6954%2046.7478C64.7952%2046.7168%2064.8928%2046.6824%2064.9937%2046.6536C65.1911%2046.5981%2065.3941%2046.5504%2065.5959%2046.505C65.6691%2046.4883%2065.7412%2046.4684%2065.8177%2046.4528C66.0761%2046.4007%2066.3389%2046.3586%2066.605%2046.3231C66.6749%2046.3142%2066.7458%2046.3065%2066.8157%2046.2987C66.9798%2046.2798%2067.1484%2046.2665%2067.3114%2046.2543C67.5387%2046.2366%2067.7694%2046.2266%2068.0023%2046.2211C68.132%2046.2211%2068.2606%2046.2133%2068.3915%2046.2144C68.5756%2046.2144%2068.763%2046.2244%2068.946%2046.2333C69.0957%2046.2399%2069.2454%2046.2455%2069.3973%2046.2577C69.5492%2046.2699%2069.71%2046.2887%2069.8675%2046.3054C70.0249%2046.322%2070.2112%2046.3431%2070.3865%2046.3675C70.5328%2046.3885%2070.6803%2046.4151%2070.83%2046.4406C71.0163%2046.4728%2071.2026%2046.505%2071.3911%2046.5449C71.5176%2046.5715%2071.6462%2046.6003%2071.7737%2046.6303C71.9748%2046.6768%2072.177%2046.7271%2072.3803%2046.7811C72.5078%2046.8155%2072.6365%2046.8498%2072.764%2046.892C72.9858%2046.9552%2073.2076%2047.025%2073.4293%2047.0971C73.5402%2047.1315%2073.6411%2047.1648%2073.7476%2047.2014C74.0625%2047.3123%2074.3786%2047.4231%2074.698%2047.5529L74.7423%2047.5695C75.075%2047.7026%2075.4077%2047.8479%2075.7403%2047.9998C75.8435%2048.0464%2075.9466%2048.0974%2076.0508%2048.1462C76.2896%2048.2585%2076.5295%2048.3757%2076.7705%2048.4977C76.8881%2048.5576%2077.006%2048.6186%2077.1243%2048.6807C77.4414%2048.8481%2077.7597%2049.0189%2078.0802%2049.2041L97.5219%2060.4253C97.8834%2060.6338%2098.2427%2060.8515%2098.5997%2061.0785L98.6507%2061.1095C98.9945%2061.3313%2099.3361%2061.5531%2099.6754%2061.7915C99.7918%2061.8724%2099.9072%2061.9567%20100.022%2062.0388C100.244%2062.1996%20100.476%2062.3626%20100.701%2062.53C100.839%2062.6332%20100.975%2062.7385%20101.113%2062.8439C101.316%2062.9999%20101.518%2063.1588%20101.72%2063.3207C101.868%2063.439%20102.016%2063.5588%20102.164%2063.68C102.357%2063.8397%20102.549%2064.0016%20102.739%2064.1657C102.887%2064.2951%20103.035%2064.4256%20103.183%2064.5572C103.37%2064.7228%20103.555%2064.8909%20103.737%2065.0617C103.886%2065.1981%20104.035%2065.3356%20104.181%2065.4753C104.369%2065.6539%20104.557%2065.8357%20104.743%2066.0187C104.878%2066.1518%20105.015%2066.2849%20105.149%2066.4202C105.343%2066.6153%20105.534%2066.8149%20105.726%2067.0145C105.85%2067.1443%20105.974%2067.2718%20106.097%2067.4038C106.319%2067.6433%20106.541%2067.8884%20106.763%2068.1334C106.845%2068.2255%20106.929%2068.3153%20107.011%2068.4085C107.313%2068.7522%20107.612%2069.1015%20107.907%2069.4564C107.97%2069.5329%20108.031%2069.6116%20108.094%2069.6882C108.325%2069.9698%20108.556%2070.2526%20108.781%2070.5409C109.05%2070.8847%20109.315%2071.2329%20109.576%2071.5855C109.619%2071.6443%20109.665%2071.6964%20109.709%2071.7607C110.133%2072.3363%20110.543%2072.9251%20110.944%2073.5195C111.042%2073.6637%20111.141%2073.8078%20111.236%2073.9531C111.383%2074.1749%20111.529%2074.4022%20111.674%2074.6284C111.8%2074.8258%20111.927%2075.0232%20112.051%2075.2228C112.194%2075.4524%20112.333%2075.6841%20112.472%2075.9159C112.583%2076.1011%20112.694%2076.2863%20112.805%2076.4703C113.13%2077.027%20113.446%2077.5893%20113.751%2078.157C113.862%2078.3633%20113.973%2078.5706%20114.076%2078.7769C114.179%2078.9832%20114.307%2079.2205%20114.417%2079.4423C114.57%2079.7472%20114.72%2080.0544%20114.867%2080.3616C114.918%2080.4725%20114.97%2080.5723%20115.02%2080.6787C115.209%2081.0816%20115.394%2081.4882%20115.574%2081.8985C115.621%2082.0094%20115.666%2082.1126%20115.712%2082.2201C115.842%2082.5232%20115.97%2082.8274%20116.095%2083.1328C116.152%2083.2718%20116.208%2083.4104%20116.263%2083.5486C116.379%2083.8399%20116.49%2084.1315%20116.595%2084.4236C116.643%2084.5511%20116.692%2084.6786%20116.74%2084.8061C116.874%2085.1758%20117.004%2085.5454%20117.129%2085.9151C117.147%2085.9661%20117.165%2086.0182%20117.183%2086.0692C117.324%2086.4891%20117.457%2086.909%20117.585%2087.3289C117.624%2087.4609%20117.661%2087.5929%20117.695%2087.7248C117.782%2088.0176%20117.866%2088.3103%20117.945%2088.6031C117.988%2088.7628%20118.029%2088.9225%20118.071%2089.0833C118.142%2089.3531%20118.209%2089.6229%20118.273%2089.8928C118.312%2090.0532%20118.349%2090.2133%20118.384%2090.3729C118.447%2090.6494%20118.506%2090.9259%20118.561%2091.2024C118.591%2091.3499%20118.622%2091.4974%20118.651%2091.646C118.719%2091.9986%20118.782%2092.3502%20118.839%2092.7006C118.849%2092.7638%20118.862%2092.827%20118.872%2092.8902C118.938%2093.3042%20118.996%2093.7167%20119.046%2094.1278C119.061%2094.2387%20119.07%2094.3496%20119.084%2094.4604C119.118%2094.7562%20119.148%2095.0537%20119.175%2095.3531C119.187%2095.4929%20119.198%2095.6315%20119.208%2095.7701C119.229%2096.0495%20119.246%2096.3279%20119.259%2096.6051C119.266%2096.7371%20119.272%2096.869%20119.278%2097.001C119.292%2097.3936%20119.301%2097.7839%20119.3%2098.172L119.237%20120.505C119.237%20120.912%20119.225%20121.31%20119.207%20121.702C119.207%20121.813%20119.192%20121.924%20119.187%20122.035C119.171%20122.304%20119.154%20122.572%20119.129%20122.835C119.116%20122.986%20119.099%20123.135%20119.083%20123.285C119.058%20123.507%20119.033%20123.728%20119.003%20123.95C118.981%20124.11%20118.957%20124.266%20118.932%20124.423C118.9%20124.624%20118.866%20124.822%20118.829%20125.018C118.795%20125.193%20118.761%20125.367%20118.725%20125.538C118.688%20125.71%20118.648%20125.884%20118.605%20126.06C118.556%20126.262%20118.504%20126.461%20118.449%20126.657C118.406%20126.811%20118.363%20126.964%20118.316%20127.115C118.244%20127.349%20118.168%20127.577%20118.088%20127.804C118.044%20127.928%20118.001%20128.053%20117.956%20128.175C117.811%20128.557%20117.657%20128.928%20117.488%20129.284C117.357%20129.561%20117.221%20129.832%20117.077%20130.092C117.061%20130.121%20117.042%20130.148%20117.027%20130.177C116.895%20130.412%20116.758%20130.64%20116.616%20130.862C116.582%20130.915%20116.545%20130.966%20116.506%20131.02C116.386%20131.199%20116.263%20131.375%20116.136%20131.546C116.084%20131.616%20116.031%20131.686%20115.978%20131.755C115.855%20131.913%20115.729%20132.067%20115.6%20132.216C115.552%20132.273%20115.504%20132.327%20115.455%20132.385C115.279%20132.582%20115.097%20132.774%20114.91%20132.956C114.881%20132.983%20114.85%20133.01%20114.821%20133.038C114.66%20133.191%20114.495%20133.339%20114.327%20133.481C114.264%20133.533%20114.2%20133.584%20114.137%20133.635C113.989%20133.753%20113.841%20133.866%20113.693%20133.975C113.63%20134.02%20113.568%20134.067%20113.504%20134.11C113.292%20134.255%20113.077%20134.395%20112.855%20134.524L123.549%20128.314C123.771%20128.185%20123.986%20128.045%20124.199%20127.9C124.264%20127.857%20124.326%20127.81%20124.388%20127.765C124.539%20127.656%20124.687%20127.543%20124.831%20127.425C124.895%20127.374%20124.959%20127.323%20125.021%20127.271C125.19%20127.129%20125.356%20126.982%20125.518%20126.828C125.547%20126.801%20125.577%20126.776%20125.604%20126.748C125.792%20126.566%20125.974%20126.374%20126.15%20126.177C126.199%20126.121%20126.246%20126.066%20126.295%20126.007C126.424%20125.859%20126.55%20125.706%20126.673%20125.546C126.727%20125.477%20126.784%20125.407%20126.832%20125.337C126.958%20125.167%20127.081%20124.991%20127.2%20124.812C127.236%20124.759%20127.272%20124.707%20127.311%20124.653L127.344%20124.604C127.475%20124.399%20127.598%20124.186%20127.72%20123.971C127.737%20123.941%20127.756%20123.915%20127.772%20123.885C127.911%20123.633%20128.044%20123.375%20128.17%20123.108L128.184%20123.076C128.352%20122.72%20128.506%20122.349%20128.652%20121.967C128.665%20121.933%20128.68%20121.902%20128.694%20121.868C128.726%20121.78%20128.753%20121.686%20128.784%20121.597C128.863%20121.375%20128.941%20121.141%20129.013%20120.907C129.033%20120.843%20129.056%20120.783%20129.075%20120.719C129.101%20120.632%20129.121%20120.539%20129.145%20120.451C129.2%20120.255%20129.252%20120.056%20129.301%20119.854C129.321%20119.769%20129.347%20119.691%20129.366%20119.605C129.385%20119.52%20129.401%20119.423%20129.42%20119.334C129.457%20119.161%20129.492%20118.987%20129.525%20118.811C129.543%20118.719%20129.564%20118.631%20129.581%20118.537C129.598%20118.444%20129.612%20118.323%20129.629%20118.218C129.653%20118.062%20129.677%20117.904%20129.7%20117.745C129.711%20117.661%20129.726%20117.582%20129.736%20117.497C129.753%20117.362%20129.764%20117.221%20129.779%20117.085C129.795%20116.948%20129.813%20116.785%20129.826%20116.632C129.832%20116.57%20129.84%20116.51%20129.845%20116.448C129.861%20116.249%20129.87%20116.041%20129.883%20115.837C129.889%20115.726%20129.898%20115.615%20129.904%20115.505C129.904%20115.477%20129.904%20115.45%20129.904%20115.422C129.918%20115.077%20129.927%20114.726%20129.928%20114.37V114.308L129.991%2091.9753C130.002%2091.6331%20130.003%2091.2978%20129.993%2090.9695Z'%20fill='%230B0E11'/%3e%3c/g%3e%3cdefs%3e%3clinearGradient%20id='paint0_linear_302_6100'%20x1='68.0078'%20y1='92.449'%20x2='102.417'%20y2='92.449'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%23313131'/%3e%3cstop%20offset='1'%20stop-color='%230B0E11'/%3e%3c/linearGradient%3e%3clinearGradient%20id='paint1_linear_302_6100'%20x1='50.0001'%20y1='94.977'%20x2='113.22'%20y2='94.977'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%234E4E4E'/%3e%3cstop%20offset='1'%20stop-color='%230B0E11'/%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e"}},a.index)):void 0!==a[3]?t.push(
22
22
  /* @__PURE__ */e("a",{href:a[4],target:"_blank",rel:"noopener noreferrer",className:"mc-link",children:a[3]},a.index)):void 0!==a[5]?t.push(
23
23
  /* @__PURE__ */e("a",{href:a[5],target:"_blank",rel:"noopener noreferrer",className:"mc-link",children:a[5]},a.index)):void 0!==a[6]?t.push(/* @__PURE__ */e("strong",{children:aa(a[6])},a.index)):void 0!==a[7]?t.push(/* @__PURE__ */e("strong",{children:aa(a[7])},a.index)):void 0!==a[8]?t.push(/* @__PURE__ */e("em",{children:aa(a[8])},a.index)):void 0!==a[9]?t.push(/* @__PURE__ */e("em",{children:aa(a[9])},a.index)):void 0!==a[10]?t.push(/* @__PURE__ */e("del",{children:aa(a[10])},a.index)):void 0!==a[11]&&t.push(
@@ -27,7 +27,7 @@ return function(n){function t(e){var n;return function(e,n){if(!(e instanceof n)
27
27
  /* @__PURE__ */e("div",{className:`mc-heading mc-h${n}`,children:aa(t)},`h-${i}`)),i++;continue}if(n.trimStart().startsWith("> ")){const n=[];for(;i<o.length&&o[i].trimStart().startsWith("> ");)n.push(o[i].replace(/^\s*>\s?/,"")),i++;a.push(
28
28
  /* @__PURE__ */e("div",{className:"mc-blockquote",children:n.map((n,t)=>/* @__PURE__ */e("div",{children:aa(n)},t))},`bq-${i}`));continue}""!==n?.trim()?(a.push(
29
29
  /* @__PURE__ */e("div",{className:"mc-line",children:aa(n)},`line-${i}`)),i++):(a.push(/* @__PURE__ */e("div",{className:"mc-empty-line"},`empty-${i}`)),i++)}/* @__PURE__ */
30
- return e("div",{className:"message-content",children:a})},ra="https://nft-demo.keyring.app";function sa(e,n,t){if(!e)return e;const o=e.toLowerCase().trim();if("max"===o||"all"===o)return n||e;const a=o.match(/^(\d+(?:\.\d+)?)%$/);if(a){const e=parseFloat(a[1])/100;return((parseFloat(n)||0)*e).toFixed(8).replace(/\.?0+$/,"")||"0"}const i=o.match(/^\$?(\d+(?:\.\d+)?)\$?$/),r=o.startsWith("$")||o.endsWith("$")||/\d(usd|dollar|dollars|đô|đồng)$/.test(o);if(i&&r){const n=parseFloat(i[1]);return t&&t>0?(n/t).toFixed(8).replace(/\.?0+$/,"")||"0":e}const s=o.match(/^(\d+(?:\.\d+)?)\s*(?:usd|dollar|dollars|đô|đồng)$/);if(s){const n=parseFloat(s[1]);return t&&t>0?(n/t).toFixed(8).replace(/\.?0+$/,"")||"0":e}return e}const ca=({isOpen:o,onClose:s,onTransaction:l,position:f="bottom-right",modalChatStyle:p={}})=>{const{t:h,ti:m}=w(),{messages:b,addMessage:g,updateMessageAction:A,updateMessageActionParameters:y,updateMessageText:v,clearMessagesById:k,updateMessageType:x}=function(){const{account:e}=zt(),{t:n}=w(),t=(o=e?.address,s=e?.chainId,o&&s?`${o}_${s}`:"");var o,s;const c=d(()=>_t(n("welcomeMessage")),[n]),[l,u]=a(()=>t||"pending"),[f,p]=a(()=>{const e=eo();return t?e&&e.owner===t?e.messages:_t(n("welcomeMessage")):e?.messages??_t(n("welcomeMessage"))});if("pending"===l&&t){const e=eo();e&&e.owner===t?p(e.messages):no(t,f),u(t)}else"pending"!==l&&t&&l!==t&&(p(c),no(t,c),u(t));const h=d(()=>f.map(e=>e.id===Zt?{...e,text:n("welcomeMessage")}:e),[f,n]);i(()=>{"pending"!==l&&no(l,f)},[f,l]),i(()=>{const e=[];for(let n=0;n<Yt.length;n++){const t=Yt.key(n);t&&t.startsWith(Qt+"_")&&e.push(t)}e.forEach(e=>Yt.removeItem(e))},[]);const m=r(()=>{p(c),no(t,c)},[t,c]),b=r(e=>{p(n=>{const t=n.filter(n=>!e.includes(n.id));return t.length>Kt?t.slice(t.length-Kt):t})},[]);return{messages:h,setMessages:p,addMessage:(e,n,t,o,a,i="web3")=>{const r=t?f.find(e=>e.id===t):void 0,s={id:Math.random().toString(36).substring(2,12),text:e,sender:n,timestamp:/* @__PURE__ */new Date,typeChat:i,...r&&{replyTo:{id:r.id,text:r.text,sender:r.sender}},...o&&{buttons:o},...a&&{actionData:a}};return p(e=>{const n=[...e,s];return n.length>Kt?n.slice(n.length-Kt):n}),s},updateMessageAction:(e,n)=>{p(t=>t.map(t=>t.id===e&&t.actionData?{...t,actionData:{...t.actionData,status:n}}:t))},updateMessageActionParameters:(e,n)=>{p(t=>t.map(t=>t.id===e&&t.actionData?{...t,actionData:{...t.actionData,parameters:{...t.actionData.parameters,...n}}}:t))},updateMessageText:(e,n)=>{p(t=>t.map(t=>t.id===e?{...t,text:n}:t))},getMessageById:e=>f.find(n=>n.id===e),clearMessages:m,clearMessagesById:b,updateMessageType:(e,n)=>{p(t=>t.map(t=>t.id===e?{...t,typeChat:n}:t))}}}(),[C,T]=a(""),[E,I]=a(!1),[N,S]=a(!0),[B,F]=a(null),R=u(null),O=u(null),D=u(null),U=u(null),L=u(null),M=u(!1),P=u(N);i(()=>{P.current=N},[N]);const{account:H,chainData:J,chainType:Y,chainTypeMoralis:q,chainId:G,isChainSupported:W}=zt(),{config:V}=(()=>{const e=c(to);if(!e)throw new Error("useConfig must be used within ConfigProvider");return e})(),z=G&&V?.rpcUrls?.[G]||void 0,j=r(()=>{const e=Yt.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=r(e=>{Yt.setItem("dataBuyToken",JSON.stringify(e))},[]),Q=r(e=>{const n={...j(),...e};X(n)},[j,X]),K=r(e=>{F(e),na.isDesktop&&D.current?.focus()},[]),Z=r(async(e,n)=>{Q({descTokenAddress:e,descTokenDecimals:n||18});try{I(!0);const e=await No({address:H?.address||"",chain:q});if(e?.success&&e?.data?.result){const n=e.data.result;if(n?.length>0){const e=n.map(e=>({id:e.token_address,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${xo(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(h("walletFetchFailed"),"bot")}catch(t){g(h("walletFetchError"),"bot")}finally{I(!1)}},[Q,H?.address,q,g,J?.name,h,m]),_=r(async(e,n,t,o)=>{Q({srcTokenAddress:e,srcTokenDecimals:o||18});let a=t||"0";if(e===Wt)try{const e=await Qo({chainId:G,rpcUrl:z});if(e.isGreaterThan(0)){const n=e.times(1e6),i=new xo(Gt(t,o||18).toString()).minus(n);a=i.isGreaterThan(0)?xo(ge(BigInt(i.toFixed(0)),18)).toFixed():"0"}}catch(r){}const i=[25,50,75,100].map(t=>({id:`percent-${t}`,text:`${t}%`,value:m("buttonUsePercent",{percent:String(t),symbol:n}),action:"select_percent",extraData:{percent:t,tokenAddress:e,tokenSymbol:n,tokenDecimals:o||18,tokenBalance:a}}));xo(a).isZero()?g(m("insufficientFeeToken",{symbol:n}),"bot"):g(m("selectAmountOf",{symbol:n,balance:a}),"bot",void 0,i)},[g,G,z,Q,m]),$=r(async(e,n,t,o)=>{const a={amount:xo(n).times(e/100).decimalPlaces(6,xo.ROUND_DOWN).toFixed()};void 0!==t&&(a.srcTokenAddress=t),void 0!==o&&(a.srcTokenDecimals=o),Q(a);const i=j(),r=Gt(i.amount,i.srcTokenDecimals||18).toString(),s=await Oo({chainId:G,tokenIn:i.srcTokenAddress,tokenInAmount:r,tokenOut:i.descTokenAddress,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(s.success&&s.data){const e=s.data,n=e.tokenIn,t=e.tokenOut,o=xo(ge(BigInt(n.amount||0),n.decimals)).decimalPlaces(6).toFormat(),a=xo(ge(BigInt(t.amount||0),t.decimals)).decimalPlaces(6).toFormat();let l=!1;if(i.srcTokenAddress!==Wt&&""!==i.srcTokenAddress&&H?.address&&e.tx?.to)try{const n=await Vo({tokenAddress:i.srcTokenAddress,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:G,rpcUrl:z});l=xo(n.toString()).isLessThan(r)}catch(c){l=!0}const d=e.estimatedTransactionFee?.total?xo(e.estimatedTransactionFee.total):xo(0);let u=xo(0);if(l&&H?.address)try{const n=zo({tokenAddress:i.srcTokenAddress,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:G,amount:r});u=await Xo({from:H.address,to:n.to,data:n.data,chainId:G,rpcUrl:z})}catch(c){}const f=d.plus(u),p=J?.nativeCurrency?.symbol||"native";let w="",b=!1;if(H?.address&&f.isGreaterThan(0))try{const e=await jo({address:H.address,chainId:G,rpcUrl:z});if(e.isLessThan(f)){b=!0;const n=xo(ge(BigInt(e.toFixed(0)),18)).decimalPlaces(6).toFormat(),t=xo(ge(BigInt(f.toFixed(0)),18)).decimalPlaces(6).toFormat();w=m("swapFeeWarning",{symbol:p,balance:n,needed:t})}}catch(c){}const A=`From: ${o} ${n.symbol}\n⬇️\nTo: ${a} ${t.symbol}\n\n`+w+"\n";if(b)g(A,"bot");else if(l){const t=A+m("swapNeedApprove",{symbol:n.symbol}),o=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:n.symbol}),value:m("swapApproveValue",{symbol:n.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:i.srcTokenAddress,spenderAddress:e.tx.to,tokenSymbol:n.symbol,amountInWei:r,tx:e.tx}}];g(t,"bot",void 0,o)}else{const n=[{id:"confirm-swap",text:h("swapConfirmButton"),value:h("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(A+h("swapReadyToProceed"),"bot",void 0,n)}}else g(m("swapEstimationError",{error:s.errorMessage||s.error||"Unknown error"}),"bot")},[j,Q,g,G,H?.address,J?.nativeCurrency?.symbol,z,h,m]),ee=r(async(e,n,t)=>{try{if("suggested_action"===n)return U.current=e,void T(e);if(g(e,"user"),S(!1),I(!0),n)switch(await Mt(500),n){case"click_buy_item_token_button":await Z(t?.tokenAddress||"",t?.decimals||18);break;case"click_balance_item_user_to_buy_button":await _(t?.tokenAddress||"",t?.symbol||"",t?.balance||"",t?.decimals||18);break;case"select_percent":await $(t?.percent||0,t?.tokenBalance||"",t?.tokenAddress||void 0,t?.tokenDecimals||void 0);break;case"confirm_swap":if(t?.tx&&l){const e=t.tx,n={from:H?.address||"",to:e.to,data:e.data,value:e.value,chainId:G},i=g(h("txProcessing"),"bot");try{I(!1);const e=await l(n);if("success"===e.status&&e.transactionHash){const n=J?.blockExplorers?.default?.url,t=n?` [View on Explorer](${n}/tx/${e.transactionHash})`:` Tx: ${e.transactionHash}`;v(i.id,h("txSubmitted")+t);try{await Mt(2e3),"success"===(await Wo({transactionHash:e.transactionHash,chainId:G||1,rpcUrl:z})).status?v(i.id,h("txConfirmedSwap")+t):v(i.id,h("txRevertedSwap")+t)}catch(o){v(i.id,h("txTimeout")+t)}}else if("success"===e.status)v(i.id,h("txSuccessfulSwap"));else{const n=e.error?`\nError: ${e.error}`:"";v(i.id,h("txFailed")+n)}}catch(a){v(i.id,h("txFailed"))}}else g(h("txDataNotAvailable"),"bot");break;case"approve_for_swap":{const e=t?.tokenAddress||"",n=t?.spenderAddress||"",i=t?.tokenSymbol||"token",r=t?.tx;if(!e||!n||!l){g(h("approvalDataNotAvailable"),"bot");break}const s=t?.amountInWei||void 0,c=zo({tokenAddress:e,spenderAddress:n,fromAddress:H?.address||"",chainId:G,tokenSymbol:i,amount:s}),d={from:c.from,to:c.to,data:c.data,value:c.value,chainId:c.chainId};g(m("approving",{symbol:i}),"bot");try{I(!1);const e=await l(d);let n="success"===e.status;if("success"===e.status&&e.transactionHash)try{n="success"===(await Wo({transactionHash:e.transactionHash,chainId:G||1,rpcUrl:z})).status}catch(o){n=!0}if(n){g(m("approvalSuccess",{symbol:i}),"bot");const e=[{id:"confirm-swap-after-approve",text:h("confirmSwapButton"),value:h("swapConfirmValue"),action:"confirm_swap",fullWidth:!0,extraData:{tx:r}}];g(h("approvalConfirmSwap"),"bot",void 0,e)}else{const n=e.error?`\nError: ${e.error}`:"";g(h("approvalFailed")+n,"bot")}}catch(a){g(h("approvalFailed"),"bot")}break}case"click_swap_dest_token":{const e=t?.tokenAddress||"",n=t?.symbol||"";Q({descTokenAddress:e,descTokenDecimals:t?.decimals||18});const o=j(),a=o.srcTokenAddress||"",s=a===Wt,c=o.amount||"";try{const t=await No({address:H?.address||"",chain:q});if(t?.success&&t?.data?.result){const r=t.data.result;let l,d="",u="0";if(s){const e=r.find(e=>e.native_token);d=J?.nativeCurrency?.symbol||"ETH",u=e?.balance_formatted||"0",l=e?.usd_price}else{const e=r.find(e=>e.token_address.toLowerCase()===a.toLowerCase());e&&(d=e.symbol,u=e.balance_formatted,l=e.usd_price)}if(c&&d){const n=sa(c,u,l),t=o.srcTokenDecimals||18,r=s?Wt:a;Q({amount:n});try{const o=Gt(n,t).toString(),a=await Oo({chainId:G,tokenIn:r,tokenInAmount:o,tokenOut:e,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(a.success&&a.data){const e=a.data,n=e.tokenIn,t=e.tokenOut,i=xo(ge(BigInt(n.amount||0),n.decimals)).decimalPlaces(6).toFormat(),c=xo(ge(BigInt(t.amount||0),t.decimals)).decimalPlaces(6).toFormat();let l=!1;if(!s&&H?.address&&e.tx?.to)try{const n=await Vo({tokenAddress:r,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:G,rpcUrl:z});l=xo(n.toString()).isLessThan(o)}catch{l=!0}const d=e.estimatedTransactionFee?.total?xo(e.estimatedTransactionFee.total):xo(0);let u=xo(0);if(l&&H?.address)try{const n=zo({tokenAddress:r,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:G,amount:o});u=await Xo({from:H.address,to:n.to,data:n.data,chainId:G,rpcUrl:z})}catch{}const f=d.plus(u),p=J?.nativeCurrency?.symbol||"native";let w="",b=!1;if(H?.address&&f.isGreaterThan(0))try{const e=await jo({address:H.address,chainId:G,rpcUrl:z});if(e.isLessThan(f)){b=!0;const n=xo(ge(BigInt(e.toFixed(0)),18)).decimalPlaces(6).toFormat(),t=xo(ge(BigInt(f.toFixed(0)),18)).decimalPlaces(6).toFormat();w=m("swapFeeWarning",{symbol:p,balance:n,needed:t})}}catch{}const A=`From: ${i} ${n.symbol}\n⬇️\nTo: ${c} ${t.symbol}\n\n`+w+"\n";if(b)g(A,"bot");else if(l){const t=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:n.symbol}),value:m("swapApproveValue",{symbol:n.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:r,spenderAddress:e.tx.to,tokenSymbol:n.symbol,amountInWei:o,tx:e.tx}}];g(A+m("swapNeedApprove",{symbol:n.symbol}),"bot",void 0,t)}else{const n=[{id:"confirm-swap",text:h("swapConfirmYes"),value:h("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(A+h("swapReadyToProceed"),"bot",void 0,n)}}else g(m("swapEstimationError",{error:a.errorMessage||a.error||"Unknown error"}),"bot")}catch(i){g(h("swapEstimationFailed"),"bot")}}else if(d&&parseFloat(u)>0){const e=[25,50,75,100],t=o.srcTokenDecimals||18,i=e.map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:d}),action:"select_percent",extraData:{percent:e,tokenAddress:a,tokenSymbol:d,tokenDecimals:t,tokenBalance:u}}));g(m("swapSelectAmount",{from:d,to:n,balance:u}),"bot",void 0,i)}else g(h("swapNoSourceToken"),"bot")}else g(h("couldNotFetchBalance"),"bot")}catch(r){g(h("couldNotLoadBalance"),"bot")}break}case"select_nft_to_send":{const e=t?.name||"NFT",n=t?.contractAddress||"",o=t?.tokenId||"",a=t?.tokenStandard||"ERC721",i=t?.amount||"1",r=t?.image||"",s={contract_address:n,token_id:o,to_address:t?.toAddress||"",token_standard:a,amount:"1",maxAmount:i,nft_name:e};g(m("nftSendReview",{name:e,standard:a,tokenId:o}),"bot",void 0,void 0,{action:"send_nft",parameters:s,status:"pending",nftInfo:{name:e,image:r||void 0,tokenId:o,contractAddress:n,tokenStandard:a}});break}default:g(m("actionExecutedFor",{action:n,value:e}),"bot")}else await Mt(500),g(m("receivedButtonValue",{value:e}),"bot");I(!1),na.isDesktop&&D.current?.focus()}catch(a){g(h("errorProcessingRequest"),"bot"),I(!1)}},[H?.address,g,v,J?.blockExplorers?.default?.url,J?.nativeCurrency?.symbol,G,q,j,Z,_,l,$,Q,z,h,m]),ne=r(async()=>{try{I(!0);const e=J?.tokenTrendingDefault||[],[n,t]=await Promise.allSettled([Fo.getTopGainers(Y,"24h",5),Fo.getTokensDetails(e,Y)]);let o=[];"fulfilled"===n.status&&n.value?.data&&(o=[...n.value.data]),"fulfilled"===t.status&&t.value?.data&&(o=[...t.value.data,...o]),o=o.filter((e,n,t)=>n===t.findIndex(n=>n.address.toLowerCase()===e.address.toLowerCase()));const a=o.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 Mt(1e3),I(!1),g(m("trendingTokensHeader",{chain:J?.name||"Unknown"}),"bot");const i=o.map((e,n)=>`${n+1}. ${e.name} (${e?.auditGoplus?.token_symbol||e.symbol||"Unknown"})\n$${xo(e?.price||0).decimalPlaces(4).toFormat()} (${e.price_change_percentage_24h||e.priceChange}%)\n\n---\n`).join("\n");g(`${i}${h("trendingTokensQuestion")}`,"bot",void 0,a)}catch(e){g(h("trendingTokensError"),"bot")}finally{I(!1)}},[g,J?.name,J?.tokenTrendingDefault,Y,h,m]),te=r(async()=>{try{g(m("viewNftViaWebsite",{link:ra}),"bot"),I(!1)}catch(e){I(!1),g(h("nftFetchError"),"bot")}},[g,h,m]),oe=r(async()=>{try{I(!0);const e=await No({address:H?.address||"",chain:q});if(e?.success&&e?.data?.result&&e.data.result.length>0){const n=e.data.result.map((e,n)=>{const t=void 0!==e.usd_value?` ≈ $${xo(e.usd_value).decimalPlaces(2).toFormat()}`:"";return`${n+1}. **${e.name}** (${e.symbol})\n Balance: ${e.balance_formatted}${t}`}).join("\n\n");await Mt(500),I(!1),g(m("viewBalancesHeader",{chain:J?.name||"this chain",list:n}),"bot",void 0)}else I(!1),g(h("viewBalancesEmpty"),"bot")}catch(e){I(!1),g(h("viewBalancesFetchError"),"bot")}},[H?.address,q,g,J?.name,h,m]),ae=d(()=>[{id:"ask",icon:"❓",text:h("suggestionAskText"),action:async()=>{S(!1),I(!0),g(h("suggestionAskUserMessage"),"user"),await Mt(1e3),I(!1),g(h("suggestionAskBotReply"),"bot")}},{id:"buy",icon:"💰",text:h("suggestionBuyText"),action:async()=>{S(!1),g(h("suggestionBuyText"),"user"),Pn(H?.address||"")&&W?await ne():(I(!0),await Mt(1e3),Pn(H?.address||"")&&!W?g(h("walletConnectedChainUnsupported"),"bot"):g(h("walletNotConnected"),"bot"),I(!1))}}],[g,H?.address,ne,h,W]),re=e=>{if(0===e)return!0;const n=b[e],t=b[e-1],o=new Date(n.timestamp),a=new Date(t.timestamp);return o.setHours(0,0,0,0),a.setHours(0,0,0,0),o.getTime()!==a.getTime()};i(()=>{R.current?.scrollIntoView({behavior:"smooth"})},[b]),i(()=>{o?(D.current&&na.isDesktop&&D.current.focus(),R.current?.scrollIntoView({behavior:"instant"}),M.current&&L.current?Date.now()-L.current>12e5&&S(!0):S(!0),L.current=null,M.current=!1,setTimeout(()=>{R.current?.scrollIntoView({behavior:"smooth"})},50)):(L.current=Date.now(),M.current=!P.current)},[o]),i(()=>{const e=e=>{"Escape"===e.key&&o&&s()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o,s]);const se=r(async()=>{if(""===C?.trim()||E)return;const e=B,n=g(C?.trim(),"user",B?.id);T(""),F(null),I(!0),S(!1),I(!0);try{let l,d;const u=b.slice(-20);let f="";if(u.length>0){f="\n\n## CONVERSATION HISTORY:\n";for(const e of u)"user"===e.sender?f+=`User: ${e.text}\n`:f+=`Assistant: ${e.text.length>400?e.text.substring(0,400)+"...":e.text}\n`;f+="\n---\n"}let p=C?.trim();e&&(p=`[Replying to ${"user"===e.sender?"my previous":"your"} message: "${e.text}"]\n\n${p}`);try{const e=await oa.checkTypeQuestion(p,f);if(e?.startsWith("no")){x(n.id,"normal");const e=b.filter(e=>"normal"===e.typeChat);let t="";if(e.slice(-20).length>0){t="\n\n## CONVERSATION HISTORY:\n";for(const n of e.slice(-20))"normal"===n.typeChat&&("user"===n.sender?t+=`User: ${n.text}\n`:t+=`Assistant: ${n.text.length>400?n.text.substring(0,400)+"...":n.text}\n\n`)}const o=await oa.generateContent(p,t);let a=null;try{let e=o?.trim();e.startsWith("```json")?e=e.replace(/^```json\s*/,"").replace(/\s*```$/,""):e.startsWith("```")&&(e=e.replace(/^```\s*/,"").replace(/\s*```$/,"")),a=JSON.parse(e)}catch{a=null}return I(!1),void g(a?.message||o,"bot",void 0,void 0,void 0,"normal")}}catch(o){}if(H?.address&&W)try{const[e,n]=await Promise.allSettled([No({address:H.address,chain:q}),Bo({address:H.address,chain:q,limit:100,exclude_spam:!0})]);"fulfilled"===e.status&&e.value?.success&&e.value?.data?.result&&(l=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"===n.status&&n.value?.success&&n.value?.data?.result&&(d=n.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 w=function(e){const{walletAddress:n,chainName:t,chainId:o,nativeSymbol:a,walletTokens:i,walletNfts:r}=e;if(!n)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- **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.\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- **CRITICAL - LANGUAGE**: Respond in the language of the user\'s CURRENT question only. Do NOT follow language from conversation history.';if(n&&!Dt[o]?.isSupported)return`You are a Web3 wallet assistant for the Keyring crypto EVM wallet app.\n The user's wallet address is: ${n}\n The user is selected on (chainId: ${o}) 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: ${o}) 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 - **CRITICAL - LANGUAGE**: Respond in the language of the user's CURRENT question only. Ignore language from previous messages in conversation history. If current question is English → English. Vietnamese → Vietnamese. NEVER default to Chinese or any other language.\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 - 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 - **CRITICAL - LANGUAGE**: Respond in the language of the user's CURRENT question only. Do NOT follow language from conversation history.`;const s=i&&i.length>0?`\n## USER'S CURRENT WALLET BALANCE:\n${i.map(e=>{const n=void 0!==e.usd_value?` (~$${e.usd_value.toFixed(2)})`:"";return`- ${e.name} (${e.symbol})(Price: ${e.price||"N/A"}): ${e.balance_formatted}${n}${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`:"",c=r&&r.length>0?`\n## USER'S NFT COLLECTION:\n${r.map(e=>{const n="ERC1155"===e.contract_type?` (x${e.amount})`:"";return`- ${e.name}${n} | ${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`:"";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**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 (${t}), proactively tell the user which of these supported chains DO have it: ${Object.values(Dt).filter(e=>e.isSupported).map(e=>e.customName||e.name).join(", ")}. 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: ${n} | Chain: ${t} (chainId: ${o}) | Native: ${a}${s}${c}\n\n## WHEN TO USE WHICH ACTION:\n- "send_native": user wants to send the native token (${a}) 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 (with fiat or another token, single target 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 ${o} only.\nFor "chat" action: no chain restriction — use cross-chain knowledge freely.\n\n## OUTPUT FORMAT:\nRaw JSON only. No markdown code blocks. Respond in the language of the user's CURRENT question (ignore conversation history language).\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- For ERC20 actions: provide correct contract_address on chainId ${o}. If token doesn't exist on this chain, inform user.\n- send_native: ONLY for ${a}. 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).\n- token_mentions: ONLY include when the token EXISTS on the CURRENT chain (chainId ${o}). If the token is on another chain or doesn't exist on the current chain, set token_mentions to [] — but still answer the question fully with cross-chain info (which chains have it, contract addresses on those chains, etc.). Format: {"symbol":"","contract_address":"<address on chainId ${o}>","decimals":<n>}. 2+ tokens → [], use suggested_actions. Non-crypto → [].\n\n## ACTION PARAMS REFERENCE:\nValid actions: send_native, send_token, swap_token, buy_token, 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":"","contract_address":"(REQ)","decimals":""}. Both tokens → swap_token.\n5. approve_token: {"contract_address":"(REQ)","token_symbol":"","spender_address":"","amount":"","decimals":""}\n6. wrap_native: {"amount":""}\n7. unwrap_native: {"amount":""}\n8. send_nft: {"contract_address":"(opt)","token_id":"","to_address":"","token_standard":"","amount":"(def 1)","nft_name":""}\n9. view_nfts: {}\n10. view_balances: {} — use ONLY when user wants to see all balances/tokens, NOT for single token price/info queries\n11. 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// --- 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:G||void 0,nativeSymbol:J?.nativeCurrency?.symbol||void 0,walletTokens:l,walletNfts:d}),A=await async function(e){const{prompt:n,model:t="gpt-4.1-mini",stream:a=!1,systemPrompt:i}=e;if(!n)throw new Error("Prompt is required");const r=new Co(Eo),s=i?`${i}\n\n---\n\n Current User's question: ${n}`:n;let c="Unknown error";for(let l=1;l<=5;l++)try{const e=(await r.post("api/moralis-cortex/proxy/chat",{prompt:s,model:t,stream:a},{headers:{Accept:"application/json","Content-Type":"application/json"}})).data;if(!e?.text?.trim()){c="Empty response from Cortex AI";continue}return{success:!0,data:e}}catch(o){c=o instanceof Error?o.message:"Unknown error"}return{success:!1,error:c}}({prompt:p,model:"gpt-4.1-mini",stream:!1,systemPrompt:w+f});if(A.success&&A.data){const e=A.data.text||"";let l=null;try{let n=e?.trim();n.startsWith("```json")?n=n.replace(/^```json\s*/,"").replace(/\s*```$/,""):n.startsWith("```")&&(n=n.replace(/^```\s*/,"").replace(/\s*```$/,"")),l=JSON.parse(n)}catch{l=null}if(l&&l.action&&"chat"!==l.action)if("buy_token"===l.action){const e=l.parameters?.token_symbol||"";let t=l.parameters?.contract_address||"",o=18;if("native"===t.toLowerCase()&&(t=Wt),t&&t!==Wt)try{const e=await Fo.getTokensDetails([t],Y);e?.data?.[0]&&(o=e.data[0].decimals||18)}catch(a){}if(!t&&e&&H?.address)try{const n=await No({address:H.address,chain:q});if(n?.success&&n?.data?.result){const a=n.data.result,i=a.find(e=>e.token_address.toLowerCase()===t.toLowerCase())||a.find(n=>n.symbol.toUpperCase()===e.toUpperCase());i&&(t=i.token_address,o=i.decimals)}if(!t){const n=J.tokenTrendingDefault||[],[a,i]=await Promise.allSettled([Fo.getTopGainers(Y,"24h",10),Fo.getTokensDetails(n,Y)]),r=[];"fulfilled"===a.status&&a.value?.data&&r.push(...a.value.data),"fulfilled"===i.status&&i.value?.data&&r.push(...i.value.data);const s=r.find(e=>e.address?.toLowerCase()===t.toLowerCase())||r.find(n=>n.symbol?.toUpperCase()===e.toUpperCase());s&&(t=s.address,o=s.decimals||18)}}catch(a){}t?(g(l.message||m("buyTokenHelp",{symbol:e}),"bot",n.id),await Z(t,o)):(g(l.message||m("tokenNotFoundOnChain",{symbol:e}),"bot",n.id),await ne())}else if("swap_token"===l.action){const e={...l.parameters||{}},t="native"===e.token_in||e.token_in_symbol?.toUpperCase()===J?.nativeCurrency?.symbol?.toUpperCase(),o="native"===e.token_out||e.token_out_symbol?.toUpperCase()===J?.nativeCurrency?.symbol?.toUpperCase();o&&(e.token_out=Wt);let d=[];if(H?.address)try{const e=await No({address:H.address,chain:q});e?.success&&e?.data?.result&&(d=e.data.result)}catch(a){}if(!t&&(e.token_in||e.token_in_symbol)&&d.length>0){const n=e.token_in?d.find(n=>n.token_address.toLowerCase()===e.token_in.toLowerCase()):d.find(n=>n.symbol.toUpperCase()===e.token_in_symbol.toUpperCase());n&&(e.token_in=n.token_address,e.token_in_decimals=String(n.decimals))}if(!o&&(e.token_out||e.token_out_symbol)&&d.length>0){const n=e.token_out?d.find(n=>n.token_address.toLowerCase()===e.token_out.toLowerCase()):d.find(n=>n.symbol.toUpperCase()===e.token_out_symbol.toUpperCase());n&&(e.token_out=n.token_address,e.token_out_decimals=String(n.decimals))}const u=!(!e.token_in&&!t),f=!!e.token_out,p=!!e.amount;if(u&&d.length>0)if(t){const e=d.find(e=>e.native_token);if(!e||xo(e.balance_formatted||"0").isZero())return g(m("formInsufficientBalance",{balance:"0",symbol:J?.nativeCurrency?.symbol||"native"}),"bot",n.id),void I(!1)}else if(e.token_in){const t=d.find(n=>n.token_address.toLowerCase()===e.token_in.toLowerCase());if(!t)return g(m("swapTokenNotInWallet",{symbol:e.token_in_symbol||e.token_in}),"bot",n.id),void I(!1);if(xo(t.balance_formatted||"0").isZero())return g(m("formInsufficientBalance",{balance:"0",symbol:t.symbol}),"bot",n.id),void I(!1)}if(u&&f&&p)try{const n=[];e.token_out&&n.push(e.token_out),e.token_in&&!t&&n.push(e.token_in);let o=18,c=18;if(n.length>0)try{const a=await Fo.getTokensDetails(n,Y);if(a?.data)for(const n of a.data)t||n.address.toLowerCase()!==e.token_in?.toLowerCase()||(o=n.decimals||18),n.address.toLowerCase()===e.token_out?.toLowerCase()&&(c=n.decimals||18)}catch(i){}if(H?.address)try{if(d.length>0)if(t){const n=d.find(e=>e.native_token);let t=n?.balance_formatted||"0";try{const e=await Qo({chainId:G,rpcUrl:z});if(e.isGreaterThan(0)){const o=e.times(1e6),a=new xo(n?.balance||"0").minus(o);t=a.isGreaterThan(0)?xo(ge(BigInt(a.toFixed(0)),n?.decimals||18)).toFixed():"0"}}catch(r){}e.amount=sa(e.amount,t,n?.usd_price);const o=parseFloat(t),a=parseFloat(e.amount);if(xo(o).lte(0))return g(m("formInsufficientBalance",{balance:xo(o).decimalPlaces(6).toFixed(),symbol:J?.nativeCurrency?.symbol||"native"}),"bot"),void I(!1);if(xo(o).lt(a))return g(m("swapInsufficientNativeBalance",{balance:xo(o).decimalPlaces(6).toFixed(),symbol:J?.nativeCurrency?.symbol||"native",amount:e.amount}),"bot"),void I(!1)}else{const n=d.find(n=>n.token_address.toLowerCase()===e.token_in?.toLowerCase());if(!n)return g(m("swapTokenNotInWallet",{symbol:e.token_in_symbol||e.token_in}),"bot"),void I(!1);e.amount=sa(e.amount,n.balance_formatted||"0",n.usd_price);const t=parseFloat(n.balance_formatted||"0"),o=parseFloat(e.amount);if(xo(t).lt(o))return g(m("swapInsufficientTokenBalance",{balance:xo(t).decimalPlaces(6).toFixed(),symbol:n.symbol,amount:e.amount}),"bot"),void I(!1)}}catch(s){}const l=t?Wt:e.token_in;Q({srcTokenAddress:l,descTokenAddress:e.token_out,amount:e.amount,srcTokenDecimals:o,descTokenDecimals:c});const u=Gt(e.amount,o).toString(),f=await Oo({chainId:G,tokenIn:l,tokenInAmount:u,tokenOut:e.token_out,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(f.success&&f.data){const e=f.data,n=e.tokenIn,o=e.tokenOut,i=xo(ge(BigInt(n.amount||0),n.decimals)).decimalPlaces(6).toFormat(),r=xo(ge(BigInt(o.amount||0),o.decimals)).decimalPlaces(6).toFormat();let s=!1;if(!t&&H?.address&&e.tx?.to)try{const n=await Vo({tokenAddress:l,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:G,rpcUrl:z});s=xo(n.toString()).isLessThan(u)}catch(a){s=!0}const c=e.estimatedTransactionFee?.total?xo(e.estimatedTransactionFee.total):xo(0);let d=xo(0);if(s&&H?.address)try{const n=zo({tokenAddress:l,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:G,amount:u});d=await Xo({from:H.address,to:n.to,data:n.data,chainId:G,rpcUrl:z})}catch(a){}const p=c.plus(d),w=J?.nativeCurrency?.symbol||"native";let b="",A=!1;if(H?.address&&p.isGreaterThan(0))try{const e=await jo({address:H.address,chainId:G,rpcUrl:z});if(e.isLessThan(p)){A=!0;const n=xo(ge(BigInt(e.toFixed(0)),18)).decimalPlaces(6).toFormat(),t=xo(ge(BigInt(p.toFixed(0)),18)).decimalPlaces(6).toFormat();b=m("swapFeeWarning",{symbol:w,balance:n,needed:t})}}catch(a){}const y=`From: ${i} ${n.symbol}\n⬇️\nTo: ${r} ${o.symbol}\n\n`+b+"\n";if(A)g(y,"bot");else if(s){const t=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:n.symbol}),value:m("swapApproveValue",{symbol:n.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:l,spenderAddress:e.tx.to,tokenSymbol:n.symbol,amountInWei:u,tx:e.tx}}];g(y+m("swapNeedApprove",{symbol:n.symbol}),"bot",void 0,t)}else{const n=[{id:"confirm-swap",text:h("swapConfirmYes"),value:h("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(y+h("swapReadyToProceed"),"bot",void 0,n)}}else g(m("swapEstimationError",{error:f.errorMessage||f.error||"Unknown error"}),"bot")}catch(c){g(h("swapEstimationFailed"),"bot")}else if(u&&f&&!p){let o=t?18:parseInt(e.token_in_decimals||"18",10),s=parseInt(e.token_out_decimals||"18",10);const c=[];if(e.token_out&&c.push(e.token_out),e.token_in&&!t&&c.push(e.token_in),c.length>0)try{const n=await Fo.getTokensDetails(c,Y);if(n?.data)for(const a of n.data)t||a.address.toLowerCase()!==e.token_in?.toLowerCase()||(o=a.decimals||o),a.address.toLowerCase()===e.token_out?.toLowerCase()&&(s=a.decimals||s)}catch(i){}if(Q({descTokenAddress:e.token_out,descTokenDecimals:s}),t)try{if(d.length>0){const e=d.find(e=>e.native_token),t=J?.nativeCurrency?.symbol||"ETH";let a=e?.balance_formatted||"0";try{const n=await Qo({chainId:G,rpcUrl:z});if(n.isGreaterThan(0)){const t=n.times(1e6),o=new xo(e?.balance||"0").minus(t);a=o.isGreaterThan(0)?xo(ge(BigInt(o.toFixed(0)),e?.decimals||18)).toFixed():"0"}}catch(r){}Q({srcTokenAddress:Wt,srcTokenDecimals:o});const i=[25,50,75,100].map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:t}),action:"select_percent",extraData:{percent:e,tokenAddress:Wt,tokenSymbol:t,tokenDecimals:o,tokenBalance:a}}));g(m("selectAmountToSwap",{symbol:t,balance:a}),"bot",n.id,i)}else g(h("couldNotFetchBalance"),"bot")}catch(a){g(h("couldNotFetchBalanceRetry"),"bot")}else{const t=e.token_in_symbol||"Token";Q({srcTokenAddress:e.token_in,srcTokenDecimals:o});try{if(d.length>0){const o=d.find(n=>n.token_address.toLowerCase()===e.token_in?.toLowerCase());if(!o)return g(m("swapTokenNotInWallet",{symbol:t}),"bot"),void I(!1);const a=[25,50,75,100].map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:o.symbol}),action:"select_percent",extraData:{percent:e,tokenAddress:o.token_address,tokenSymbol:o.symbol,tokenDecimals:o.decimals||18,tokenBalance:o.balance_formatted}}));g(m("selectAmountToSwap",{symbol:o.symbol,balance:`${o.balance_formatted} (~$${o.usd_value?.toFixed(2)||"0"})`}),"bot",n.id,a)}else g(h("couldNotFetchBalance"),"bot")}catch(a){g(h("couldNotFetchBalanceRetry"),"bot")}}}else if(!u&&f){g(l.message||h("swapChooseFrom"),"bot",n.id);let t=parseInt(e.token_out_decimals||"18",10);if(e.token_out)try{const n=await Fo.getTokensDetails([e.token_out],Y);n?.data?.[0]&&(t=n.data[0].decimals||t)}catch(i){}await Z(e.token_out,t)}else if(u&&!f){let o=t?18:parseInt(e.token_in_decimals||"18",10);if(e.token_in&&!t)try{const n=await Fo.getTokensDetails([e.token_in],Y);n?.data?.[0]&&(o=n.data[0].decimals||o)}catch(i){}Q(t?{srcTokenAddress:Wt,srcTokenDecimals:18,...p?{amount:e.amount}:{}}:{srcTokenAddress:e.token_in,srcTokenDecimals:o,...p?{amount:e.amount}:{}}),g(l.message||m("swapChooseTo",{symbol:e.token_in_symbol||"your token"}),"bot",n.id);try{I(!0);const e=J?.tokenTrendingDefault||[],[n,t]=await Promise.allSettled([Fo.getTopGainers(Y,"24h",5),Fo.getTokensDetails(e,Y)]);let o=[];"fulfilled"===n.status&&n.value?.data&&(o=[...n.value.data]),"fulfilled"===t.status&&t.value?.data&&(o=[...t.value.data,...o]),o=o.filter((e,n,t)=>n===t.findIndex(n=>n.address.toLowerCase()===e.address.toLowerCase()));const a=o.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,a)}catch(a){g(h("couldNotLoadTokenList"),"bot")}finally{I(!1)}}else if(g(l.message||h("swapChooseToken"),"bot",n.id),H?.address)try{I(!0);const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result&&e.data.result.length>0){const n=e.data.result.map(e=>({id:`swap-select-${e.token_address}`,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${xo(e?.usd_value||0).decimalPlaces(2).toFixed()||"0"})`,value:`Swap ${e.symbol}`,action:"suggested_action",fullWidth:!0}));await Mt(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(a){I(!1),g(h("walletFetchError"),"bot")}}else if("view_balances"===l.action)await oe();else if("view_nfts"===l.action)await te();else if("send_token"!==l.action||l.parameters?.contract_address||l.parameters?.token_symbol||!H?.address)if("send_nft"!==l.action||l.parameters?.contract_address||l.parameters?.token_id||l.parameters?.nft_name||!H?.address)if("send_nft"===l.action&&!Pn(l.parameters?.contract_address||"")&&(l.parameters?.nft_name||l.parameters?.token_id)&&H?.address)try{I(!0);const e=await Bo({address:H.address,chain:q,limit:100,exclude_spam:!1});if(e?.success&&e?.data?.result){const t=e.data.result,o=(l.parameters?.nft_name||"").toLowerCase(),a=l.parameters?.token_id||"",i=e=>{const n=(e.normalized_metadata?.name||e.name||"").toLowerCase(),t=(e.name||"").toLowerCase(),i=o&&(n.includes(o)||t.includes(o)),r=a&&e.token_id===a;return o&&a?i&&r:o?i:r},r=!o&&!!a,s=r?t.filter(i):[],c=r?1===s.length?s[0]:null:t.find(i);if(r&&s.length>1){const e=s.map(e=>{const n=e.normalized_metadata?.name||e.name||`#${e.token_id}`,t=e.normalized_metadata?.image||e.media?.original_media_url||"";return{id:`${e.token_address}-${e.token_id}`,text:`${n} (${e.symbol||e.contract_type}) #${e.token_id}`,value:m("buttonSendNft",{name:n}),action:"select_nft_to_send",fullWidth:!0,extraData:{contractAddress:e.token_address,tokenId:e.token_id,tokenStandard:e.contract_type,name:n,symbol:e.symbol,amount:e.amount,image:t,toAddress:l.parameters?.to_address||""}}}),t=s.map((e,n)=>{const t=e.normalized_metadata?.name||e.name||`#${e.token_id}`,o=e.normalized_metadata?.image||e.media?.original_media_url||"";return`${n+1}. ${o?`![${t}](${o})\n`:"🖼️ "}**${t}**\n ${e.symbol||e.contract_type} | Token ID: ${e.token_id}`}).join("\n\n");I(!1),g(m("nftMultipleMatchesForTokenId",{count:String(s.length),tokenId:a})+"\n\n"+t,"bot",n.id,e)}else if(c){const e=c.normalized_metadata?.name||c.name||`#${c.token_id}`,t=c.normalized_metadata?.image||c.media?.original_media_url||"",o={contract_address:c.token_address,token_id:c.token_id,to_address:l.parameters?.to_address||"",token_standard:c.contract_type||"",amount:"1",maxAmount:c.amount||"1",nft_name:e};g(l.message||m("nftSendReview",{name:e,standard:c.contract_type||"NFT",tokenId:c.token_id}),"bot",n.id,void 0,{action:"send_nft",parameters:o,status:"pending",nftInfo:{name:e,image:t||void 0,tokenId:c.token_id,contractAddress:c.token_address,tokenStandard:c.contract_type||void 0}})}else g(m("nftNotFoundInWallet",{name:o||a}),"bot",n.id)}else g(h("nftNoCollection"),"bot",n.id)}catch(a){g(h("nftFetchError"),"bot",n.id)}finally{I(!1)}else{const i=(t=l.action,["send_native","send_token","approve_token","wrap_native","unwrap_native","send_nft"].includes(t));let s,c,d={...l.parameters||{}};const u=["send_token","approve_token"].includes(l.action)&&(d.contract_address||d.token_symbol),f="send_native"===l.action||"wrap_native"===l.action,p="unwrap_native"===l.action,h="send_nft"===l.action&&d.contract_address;if(u&&H?.address)try{const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result){const n=e.data.result,t=d.contract_address?n.find(e=>e.token_address.toLowerCase()===d.contract_address.toLowerCase()):n.find(e=>e.symbol.toUpperCase()===d.token_symbol.toUpperCase());t&&(d={...d,contract_address:t.token_address,decimals:String(t.decimals)},s={symbol:t.symbol,name:t.name,balance:t.balance,balanceFormatted:t.balance_formatted,usdValue:t.usd_value,usdPrice:t.usd_price,decimals:t.decimals,logo:t.logo||t.thumbnail,contractAddress:t.token_address})}}catch(a){}if(u&&!s&&"send_token"===l.action){const e=d.token_symbol||d.contract_address||"this token";return g(m("sendTokenNotInWallet",{symbol:e}),"bot",n.id),void I(!1)}if(u&&!s&&d.contract_address)try{const e=await So({address:d.contract_address,chain:q});if(e?.success&&e?.data){const n=e.data;s={symbol:n.symbol,name:n.name,balance:"0",balanceFormatted:"0",usdPrice:n.usd_price,decimals:n.decimals,logo:n.logo,contractAddress:d.contract_address},d={...d,decimals:String(n.decimals)}}}catch(a){}if(f&&H?.address)try{const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result){const n=e.data.result.find(e=>e.native_token);if(n){let e=n.balance_formatted,t=n.balance;try{const o=new xo(n.balance),a="0x"+BigInt(o.toFixed(0)).toString(16),i=await Xo({from:H.address,to:H.address,data:"0x",value:a,chainId:G,rpcUrl:z});if(i.isGreaterThan(0)){const a=o.minus(i);a.isGreaterThan(0)?(t=a.toFixed(0),e=xo(ge(BigInt(a.toFixed(0)),n.decimals)).toFixed()):(t="0",e="0")}}catch(r){}s={symbol:n.symbol,name:n.name,balance:t,balanceFormatted:e,usdValue:n.usd_value,usdPrice:n.usd_price,decimals:n.decimals,logo:n.logo||n.thumbnail,contractAddress:Wt}}else{const e=await So({address:Wt,chain:q});if(e?.success&&e?.data){const n=e.data;s={symbol:n.symbol,name:n.name,balance:"0",balanceFormatted:"0",usdValue:0,usdPrice:n.usd_price,decimals:n.decimals,logo:n.logo||n.thumbnail,contractAddress:Wt}}}}}catch(a){}if(p&&H?.address)try{const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result){const n=e.data.result,t=`W${J?.nativeCurrency?.symbol||"ETH"}`,o=n.find(e=>e.symbol.toUpperCase()===t.toUpperCase());o&&(s={symbol:o.symbol,name:o.name,balance:o.balance,balanceFormatted:o.balance_formatted,usdValue:o.usd_value,usdPrice:o.usd_price,decimals:o.decimals,logo:o.logo||o.thumbnail,contractAddress:o.token_address})}}catch(a){}if(h){try{const e=await async function(e){const{address:n,chain:t="base"}=e;if(!n)throw new Error("Contract address is required");try{return{success:!0,data:(await Io.get(`api/moralis/proxy/nft/${encodeURIComponent(n)}/metadata`,{query:{chain:t}})).data}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}({address:d.contract_address,chain:q});if(e?.success&&e?.data){const n=e.data;n.contract_type&&(d={...d,token_standard:n.contract_type}),!d.nft_name&&n.name&&(d={...d,nft_name:n.name})}}catch(a){}if(H?.address)try{const e=await Bo({address:H.address,chain:q,limit:100,exclude_spam:!1});if(e?.success&&e?.data?.result){const t=e.data.result.find(e=>e.token_address.toLowerCase()===d.contract_address.toLowerCase()&&e.token_id===d.token_id);if(!t){const e=d.nft_name||`#${d.token_id||d.contract_address}`;return g(m("nftNotFoundInWallet",{name:e}),"bot",n.id),void I(!1)}{d={...d,amount:"1",maxAmount:t.amount||"1"};const e=t.normalized_metadata?.image||t.media?.original_media_url||"";c={name:t.normalized_metadata?.name||t.name||d.nft_name||`#${t.token_id}`,image:e||void 0,tokenId:t.token_id,contractAddress:t.token_address,tokenStandard:t.contract_type||d.token_standard||void 0}}}}catch(a){}}if(d.amount&&s?.balanceFormatted&&("send_token"===l.action||"send_native"===l.action||"wrap_native"===l.action||"unwrap_native"===l.action)&&(d.amount=sa(d.amount,s.balanceFormatted,s.usdPrice)),i){const e=l.message||"Please review and complete the form below.";g(e,"bot",n.id,void 0,{action:l.action,parameters:d,status:"pending",tokenInfo:s,nftInfo:c})}else g(l.message||e,"bot",n.id)}else g(m("sendNftViaWebsite",{link:ra}),"bot");else try{const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result&&e.data.result.length>0){g(h("sendTokenChoose"),"bot",n.id),I(!0),await Mt(500);const t=e.data.result.map(e=>({id:`send-select-${e.token_address}`,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${xo(e?.usd_value||0).decimalPlaces(2).toFixed()||"0"})`,value:m("buttonSendToken",{symbol:e.symbol}),action:"suggested_action",fullWidth:!0}));await Mt(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(a){I(!1),g(h("walletFetchError"),"bot")}else if(l&&"chat"===l.action){const t=l.token_mentions||[],o=l.suggested_actions||[],a=[];t.length>0&&t.forEach(e=>{a.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||18},fullWidth:!0})}),o.length>0&&o.forEach((e,n)=>{a.push({id:`suggested-${n}-${e.label}`,text:e.label,value:e.prompt,action:"suggested_action",fullWidth:!0})}),a.length>0?g(l.message||e,"bot",n.id,a):g(l.message||e,"bot",n.id)}else g(e,"bot",n.id)}else g(h("errorProcessingRequest"),"bot",n.id)}catch(o){g(h("errorProcessingRequest"),"bot",n.id)}var t;I(!1),await Mt(50),na.isDesktop&&D.current?.focus()},[C,E,B,g,b,H?.address,W,J?.name,J?.nativeCurrency?.symbol,J?.tokenTrendingDefault,G,x,q,Y,m,Z,ne,h,Q,z,oe,te]);i(()=>{U.current&&C===U.current&&(U.current=null,se())},[C,se]);const ce=r(async(e,n,t)=>{try{if(S(!1),A(t,"submitted"),"swap_token"===e){let e=18;if(n.token_in&&n.token_in!==Wt)try{const t=await Fo.getTokensDetails([n.token_in],Y);t?.data?.[0]&&(e=t.data[0].decimals||18)}catch(o){}const i=Gt(n.amount||"0",e).toString(),r=await Oo({chainId:G,tokenIn:n.token_in||"",tokenInAmount:i,tokenOut:n.token_out||"",tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(r.success&&r.data){const e=r.data,o=e.tokenIn,s=e.tokenOut,c=xo(ge(BigInt(o.amount||0),o.decimals)).decimalPlaces(6).toFormat(),l=xo(ge(BigInt(s.amount||0),s.decimals)).decimalPlaces(6).toFormat(),d=!n.token_in||n.token_in===Wt;let u=!1;if(!d&&H?.address&&e.tx?.to)try{const t=await Vo({tokenAddress:n.token_in,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:G,rpcUrl:z});u=xo(t.toString()).isLessThan(i)}catch(a){}const f=e.estimatedTransactionFee?.total?xo(e.estimatedTransactionFee.total):xo(0);let p=xo(0);if(u&&H?.address)try{const t=zo({tokenAddress:n.token_in,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:G,amount:i});p=await Xo({from:H.address,to:t.to,data:t.data,chainId:G,rpcUrl:z})}catch(a){}const w=f.plus(p),b=J?.nativeCurrency?.symbol||"native";let y="",v=!1;if(H?.address&&w.isGreaterThan(0))try{const e=await jo({address:H.address,chainId:G,rpcUrl:z});if(e.isLessThan(w)){v=!0;const n=xo(ge(BigInt(e.toFixed(0)),18)).decimalPlaces(6).toFormat(),t=xo(ge(BigInt(w.toFixed(0)),18)).decimalPlaces(6).toFormat();y=m("swapFeeWarning",{symbol:b,balance:n,needed:t})}}catch(a){}const k=`From: ${c} ${o.symbol}\n⬇️\nTo: ${l} ${s.symbol}\n\n`+y+"\n";if(v)A(t,"pending"),g(k,"bot");else if(u){const a=[{id:"approve-swap-actionform",text:m("swapApproveButton",{symbol:o.symbol}),value:m("swapApproveValue",{symbol:o.symbol}),action:"approve_for_swap",extraData:{tokenAddress:n.token_in,spenderAddress:e.tx.to,tokenSymbol:o.symbol,amountInWei:i,tx:e.tx},fullWidth:!0}];A(t,"success"),g(k+m("swapApprovalRequired",{symbol:o.symbol}),"bot",void 0,a)}else{const n=[{id:"confirm-swap-actionform",text:h("swapConfirmYes"),value:h("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];A(t,"success"),g(k+h("swapReadyToProceed"),"bot",void 0,n)}}else A(t,"pending"),g(m("swapEstimationError",{error:r.errorMessage||r.error||"Unknown error"}),"bot")}else{const o=function(e){const{action:n,parameters:t,fromAddress:o,chainId:a}=e;switch(n){case"send_native":return function(e,n,t){const{to_address:o,amount:a}=e;if(!o)throw new Error("Recipient address is required");if(!a)throw new Error("Amount is required");return{from:n,to:o,data:"0x",value:Gt(a,18).toString(),chainId:t,description:`Send ${a} native token to ${o}`}}(t,o,a);case"send_token":return function(e,n,t){const{contract_address:o,to_address:a,amount:i,decimals:r,token_symbol:s}=e;if(!o)throw new Error("Token contract address is required");if(!a)throw new Error("Recipient address is required");if(!i)throw new Error("Amount is required");const c=Gt(i,parseInt(r)||18);return{from:n,to:o,data:Rt({abi:Ho,functionName:"transfer",args:[a,c]}),value:"0",chainId:t,description:`Send ${i} ${s||"tokens"} to ${a}`}}(t,o,a);case"approve_token":return function(e,n,t){const{contract_address:o,spender_address:a,amount:i,token_symbol:r}=e;if(!o)throw new Error("Token contract address is required");if(!a)throw new Error("Spender address is required");const s=i&&""!==i?.trim()?Gt(i,18):ie;return{from:n,to:o,data:Rt({abi:Ho,functionName:"approve",args:[a,s]}),value:"0",chainId:t,description:`Approve ${i||"unlimited"} ${r||"tokens"} for ${a}`}}(t,o,a);case"wrap_native":return function(e,n,t){const{amount:o}=e;if(!o)throw new Error("Amount is required");const a=Po[t];if(!a)throw new Error(`WETH not supported on chain ${t}`);const i=Gt(o,18).toString();return{from:n,to:a,data:Rt({abi:Jo,functionName:"deposit"}),value:i,chainId:t,description:`Wrap ${o} native token`}}(t,o,a);case"unwrap_native":return function(e,n,t){const{amount:o}=e;if(!o)throw new Error("Amount is required");const a=Po[t];if(!a)throw new Error(`WETH not supported on chain ${t}`);const i=Gt(o,18);return{from:n,to:a,data:Rt({abi:Jo,functionName:"withdraw",args:[i]}),value:"0",chainId:t,description:`Unwrap ${o} WETH`}}(t,o,a);case"send_nft":return function(e,n,t){const{contract_address:o,token_id:a,to_address:i,token_standard:r,amount:s,nft_name:c}=e;if(!o)throw new Error("NFT contract address is required");if(!a)throw new Error("Token ID is required");if(!i)throw new Error("Recipient address is required");const l=(r||"ERC721").toUpperCase(),d=BigInt(a);let u,f;if("ERC1155"===l){const e=BigInt(s||"1");u=Rt({abi:qo,functionName:"safeTransferFrom",args:[n,i,d,e,"0x"]}),f=`Send ${e>1n?e.toString()+"x ":""}${c||"NFT"} (ERC1155 #${a}) to ${i}`}else u=Rt({abi:Yo,functionName:"safeTransferFrom",args:[n,i,d]}),f=`Send ${c||"NFT"} (ERC721 #${a}) to ${i}`;return{from:n,to:o,data:u,value:"0",chainId:t,description:f}}(t,o,a);default:throw new Error(`Action "${n}" does not produce a transaction`)}}({action:e,parameters:n,fromAddress:H?.address||"",chainId:G||1}),a={from:o.from,to:o.to,data:o.data,value:o.value,chainId:o.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",n=await Xo({from:o.from,to:o.to,data:o.data,value:o.value&&"0"!==o.value?`0x${BigInt(o.value).toString(16)}`:void 0,chainId:G,rpcUrl:z});if(n.isGreaterThan(0)){const o=await jo({address:H.address,chainId:G,rpcUrl:z});if(o.isLessThan(n)){const a=xo(ge(BigInt(o.toFixed(0)),18)).decimalPlaces(6).toFormat(),i=xo(ge(BigInt(n.toFixed(0)),18)).decimalPlaces(6).toFormat();return A(t,"pending"),void g(m("txInsufficientGas",{symbol:e,balance:a,fee:i}),"bot")}}}catch(i){}if(l){I(!1);const o=await l(a);if("success"===o.status&&o.transactionHash){const a=J?.blockExplorers?.default?.url,i=a?` [View on Explorer](${a}/tx/${o.transactionHash})`:` Tx: ${o.transactionHash}`;try{if(await Mt(4e3),"success"===(await Wo({transactionHash:o.transactionHash,chainId:G||1,rpcUrl:z})).status){if(A(t,"success"),y(t,n),"approve_token"===e&&g(m("approvalSuccess",{symbol:n.token_symbol||n.contract_address||"Token"})+i,"bot"),"send_token"===e||"send_native"===e||"send_nft"===e){const t=n.to_address||n.recipient||"",o=t?`${t.slice(0,6)}...${t.slice(-4)}`:"";g("send_nft"===e?m("txSuccessfulSendNft",{name:n.nft_name||n.token_symbol||"NFT",tokenId:n.token_id||"",to:o})+i:m("send_native"===e?"txSuccessfulSendNative":"txSuccessfulSendToken",{amount:n.amount||"",symbol:n.token_symbol||("send_native"===e?J?.nativeCurrency?.symbol||"native":"Token"),to:o})+i,"bot")}if("wrap_native"===e){const e=J?.nativeCurrency?.symbol||"native";g(m("txSuccessfulWrapNative",{amount:n.amount||"",from:e,to:`W${e}`})+i,"bot")}if("unwrap_native"===e){const e=J?.nativeCurrency?.symbol||"native";g(m("txSuccessfulUnwrapNative",{amount:n.amount||"",from:`W${e}`,to:e})+i,"bot")}}else A(t,"pending"),g(h("txReverted")+"\n"+i,"bot")}catch(r){A(t,"success"),g(h("txTimeout")+"\n"+i,"bot")}}else if("success"===o.status)A(t,"success");else{A(t,"pending");const e=o.error?`\nError: ${o.error}`:"";g(h("txFailed")+e,"bot")}}else A(t,"pending"),g(h("txNoHandler"),"bot")}}catch(s){A(t,"pending"),g(m("txError",{message:s instanceof Error?s.message:"Unknown error"}),"bot")}},[A,G,H?.address,Y,J?.nativeCurrency?.symbol,J?.blockExplorers?.default?.url,z,m,g,h,l,y]),le=r(e=>{k([e])},[k]),[de,ue]=a({}),fe=r(async(e,n,t)=>{ue(e=>({...e,[t]:!0}));try{await ce(e,n,t)}finally{ue(e=>({...e,[t]:!1}))}},[ce]),pe=r(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),se())},[se]),he=r(()=>{const e=window.getSelection();e&&e.toString().length>0||s()},[s]);return o?/* @__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__ */t("div",{className:"chat-modal",style:p,onClick:e=>e.stopPropagation(),children:[
30
+ return e("div",{className:"message-content",children:a})},ra="https://nft-demo.keyring.app";function sa(e,n,t){if(!e)return e;const o=e.toLowerCase().trim();if("max"===o||"all"===o)return n||e;const a=o.match(/^(\d+(?:\.\d+)?)%$/);if(a){const e=parseFloat(a[1])/100;return((parseFloat(n)||0)*e).toFixed(8).replace(/\.?0+$/,"")||"0"}const i=o.match(/^\$?(\d+(?:\.\d+)?)\$?$/),r=o.startsWith("$")||o.endsWith("$")||/\d(usd|dollar|dollars|đô|đồng)$/.test(o);if(i&&r){const n=parseFloat(i[1]);return t&&t>0?(n/t).toFixed(8).replace(/\.?0+$/,"")||"0":e}const s=o.match(/^(\d+(?:\.\d+)?)\s*(?:usd|dollar|dollars|đô|đồng)$/);if(s){const n=parseFloat(s[1]);return t&&t>0?(n/t).toFixed(8).replace(/\.?0+$/,"")||"0":e}return e}const ca=({isOpen:o,onClose:s,onTransaction:l,position:f="bottom-right",modalChatStyle:p={}})=>{const{t:h,ti:m}=w(),{messages:b,addMessage:g,updateMessageAction:A,updateMessageActionParameters:y,updateMessageText:v,clearMessagesById:k,updateMessageType:x}=function(){const{account:e}=zt(),{t:n}=w(),t=(o=e?.address,s=e?.chainId,o&&s?`${o}_${s}`:"");var o,s;const c=d(()=>_t(n("welcomeMessage")),[n]),[l,u]=a(()=>t||"pending"),[f,p]=a(()=>{const e=eo();return t?e&&e.owner===t?e.messages:_t(n("welcomeMessage")):e?.messages??_t(n("welcomeMessage"))});if("pending"===l&&t){const e=eo();e&&e.owner===t?p(e.messages):no(t,f),u(t)}else"pending"!==l&&t&&l!==t&&(p(c),no(t,c),u(t));const h=d(()=>f.map(e=>e.id===Zt?{...e,text:n("welcomeMessage")}:e),[f,n]);i(()=>{"pending"!==l&&no(l,f)},[f,l]),i(()=>{const e=[];for(let n=0;n<Yt.length;n++){const t=Yt.key(n);t&&t.startsWith(Qt+"_")&&e.push(t)}e.forEach(e=>Yt.removeItem(e))},[]);const m=r(()=>{p(c),no(t,c)},[t,c]),b=r(e=>{p(n=>{const t=n.filter(n=>!e.includes(n.id));return t.length>Kt?t.slice(t.length-Kt):t})},[]);return{messages:h,setMessages:p,addMessage:(e,n,t,o,a,i="web3")=>{const r=t?f.find(e=>e.id===t):void 0,s={id:Math.random().toString(36).substring(2,12),text:e,sender:n,timestamp:/* @__PURE__ */new Date,typeChat:i,...r&&{replyTo:{id:r.id,text:r.text,sender:r.sender}},...o&&{buttons:o},...a&&{actionData:a}};return p(e=>{const n=[...e,s];return n.length>Kt?n.slice(n.length-Kt):n}),s},updateMessageAction:(e,n)=>{p(t=>t.map(t=>t.id===e&&t.actionData?{...t,actionData:{...t.actionData,status:n}}:t))},updateMessageActionParameters:(e,n)=>{p(t=>t.map(t=>t.id===e&&t.actionData?{...t,actionData:{...t.actionData,parameters:{...t.actionData.parameters,...n}}}:t))},updateMessageText:(e,n)=>{p(t=>t.map(t=>t.id===e?{...t,text:n}:t))},getMessageById:e=>f.find(n=>n.id===e),clearMessages:m,clearMessagesById:b,updateMessageType:(e,n)=>{p(t=>t.map(t=>t.id===e?{...t,typeChat:n}:t))}}}(),[C,T]=a(""),[E,I]=a(!1),[N,S]=a(!0),[B,F]=a(null),R=u(null),O=u(null),D=u(null),U=u(null),L=u(null),M=u(!1),P=u(N);i(()=>{P.current=N},[N]);const{account:H,chainData:J,chainType:Y,chainTypeMoralis:q,chainId:G,isChainSupported:W}=zt(),{config:V}=(()=>{const e=c(to);if(!e)throw new Error("useConfig must be used within ConfigProvider");return e})(),z=G&&V?.rpcUrls?.[G]||void 0,j=r(()=>{const e=Yt.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=r(e=>{Yt.setItem("dataBuyToken",JSON.stringify(e))},[]),Q=r(e=>{const n={...j(),...e};X(n)},[j,X]),K=r(e=>{F(e),na.isDesktop&&D.current?.focus()},[]),Z=r(async(e,n)=>{Q({descTokenAddress:e,descTokenDecimals:n||18});try{I(!0);const e=await No({address:H?.address||"",chain:q});if(e?.success&&e?.data?.result){const n=e.data.result;if(n?.length>0){const e=n.map(e=>({id:e.token_address,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${xo(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(h("walletFetchFailed"),"bot")}catch(t){g(h("walletFetchError"),"bot")}finally{I(!1)}},[Q,H?.address,q,g,J?.name,h,m]),_=r(async(e,n,t,o)=>{Q({srcTokenAddress:e,srcTokenDecimals:o||18});let a=t||"0";if(e===Wt)try{const e=await Qo({chainId:G,rpcUrl:z});if(e.isGreaterThan(0)){const n=e.times(1e6),i=new xo(Gt(t,o||18).toString()).minus(n);a=i.isGreaterThan(0)?xo(ge(BigInt(i.toFixed(0)),18)).toFixed():"0"}}catch(r){}const i=[25,50,75,100].map(t=>({id:`percent-${t}`,text:`${t}%`,value:m("buttonUsePercent",{percent:String(t),symbol:n}),action:"select_percent",extraData:{percent:t,tokenAddress:e,tokenSymbol:n,tokenDecimals:o||18,tokenBalance:a}}));xo(a).isZero()?g(m("insufficientFeeToken",{symbol:n}),"bot"):g(m("selectAmountOf",{symbol:n,balance:a}),"bot",void 0,i)},[g,G,z,Q,m]),$=r(async(e,n,t,o)=>{const a={amount:xo(n).times(e/100).decimalPlaces(6,xo.ROUND_DOWN).toFixed()};void 0!==t&&(a.srcTokenAddress=t),void 0!==o&&(a.srcTokenDecimals=o),Q(a);const i=j(),r=Gt(i.amount,i.srcTokenDecimals||18).toString(),s=await Oo({chainId:G,tokenIn:i.srcTokenAddress,tokenInAmount:r,tokenOut:i.descTokenAddress,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(s.success&&s.data){const e=s.data,n=e.tokenIn,t=e.tokenOut,o=xo(ge(BigInt(n.amount||0),n.decimals)).decimalPlaces(6).toFormat(),a=xo(ge(BigInt(t.amount||0),t.decimals)).decimalPlaces(6).toFormat();let l=!1;if(i.srcTokenAddress!==Wt&&""!==i.srcTokenAddress&&H?.address&&e.tx?.to)try{const n=await Vo({tokenAddress:i.srcTokenAddress,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:G,rpcUrl:z});l=xo(n.toString()).isLessThan(r)}catch(c){l=!0}const d=e.estimatedTransactionFee?.total?xo(e.estimatedTransactionFee.total):xo(0);let u=xo(0);if(l&&H?.address)try{const n=zo({tokenAddress:i.srcTokenAddress,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:G,amount:r});u=await Xo({from:H.address,to:n.to,data:n.data,chainId:G,rpcUrl:z})}catch(c){}const f=d.plus(u),p=J?.nativeCurrency?.symbol||"native";let w="",b=!1;if(H?.address&&f.isGreaterThan(0))try{const e=await jo({address:H.address,chainId:G,rpcUrl:z});if(e.isLessThan(f)){b=!0;const n=xo(ge(BigInt(e.toFixed(0)),18)).decimalPlaces(6).toFormat(),t=xo(ge(BigInt(f.toFixed(0)),18)).decimalPlaces(6).toFormat();w=m("swapFeeWarning",{symbol:p,balance:n,needed:t})}}catch(c){}const A=`From: ${o} ${n.symbol}\n⬇️\nTo: ${a} ${t.symbol}\n\n`+w+"\n";if(b)g(A,"bot");else if(l){const t=A+m("swapNeedApprove",{symbol:n.symbol}),o=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:n.symbol}),value:m("swapApproveValue",{symbol:n.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:i.srcTokenAddress,spenderAddress:e.tx.to,tokenSymbol:n.symbol,amountInWei:r,tx:e.tx}}];g(t,"bot",void 0,o)}else{const n=[{id:"confirm-swap",text:h("swapConfirmButton"),value:h("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(A+h("swapReadyToProceed"),"bot",void 0,n)}}else g(m("swapEstimationError",{error:s.errorMessage||s.error||"Unknown error"}),"bot")},[j,Q,g,G,H?.address,J?.nativeCurrency?.symbol,z,h,m]),ee=r(async(e,n,t)=>{try{if("suggested_action"===n)return U.current=e,void T(e);if(g(e,"user"),S(!1),I(!0),n)switch(await Mt(500),n){case"click_buy_item_token_button":await Z(t?.tokenAddress||"",t?.decimals||18);break;case"click_balance_item_user_to_buy_button":await _(t?.tokenAddress||"",t?.symbol||"",t?.balance||"",t?.decimals||18);break;case"select_percent":await $(t?.percent||0,t?.tokenBalance||"",t?.tokenAddress||void 0,t?.tokenDecimals||void 0);break;case"confirm_swap":if(t?.tx&&l){const e=t.tx,n={from:H?.address||"",to:e.to,data:e.data,value:e.value,chainId:G},i=g(h("txProcessing"),"bot");try{I(!1);const e=await l(n);if("success"===e.status&&e.transactionHash){const n=J?.blockExplorers?.default?.url,t=n?` [View on Explorer](${n}/tx/${e.transactionHash})`:` Tx: ${e.transactionHash}`;v(i.id,h("txSubmitted")+t);try{await Mt(2e3),"success"===(await Wo({transactionHash:e.transactionHash,chainId:G||1,rpcUrl:z})).status?v(i.id,h("txConfirmedSwap")+t):v(i.id,h("txRevertedSwap")+t)}catch(o){v(i.id,h("txTimeout")+t)}}else if("success"===e.status)v(i.id,h("txSuccessfulSwap"));else{const n=e.error?`\nError: ${e.error}`:"";v(i.id,h("txFailed")+n)}}catch(a){v(i.id,h("txFailed"))}}else g(h("txDataNotAvailable"),"bot");break;case"approve_for_swap":{const e=t?.tokenAddress||"",n=t?.spenderAddress||"",i=t?.tokenSymbol||"token",r=t?.tx;if(!e||!n||!l){g(h("approvalDataNotAvailable"),"bot");break}const s=t?.amountInWei||void 0,c=zo({tokenAddress:e,spenderAddress:n,fromAddress:H?.address||"",chainId:G,tokenSymbol:i,amount:s}),d={from:c.from,to:c.to,data:c.data,value:c.value,chainId:c.chainId};g(m("approving",{symbol:i}),"bot");try{I(!1);const e=await l(d);let n="success"===e.status;if("success"===e.status&&e.transactionHash)try{n="success"===(await Wo({transactionHash:e.transactionHash,chainId:G||1,rpcUrl:z})).status}catch(o){n=!0}if(n){g(m("approvalSuccess",{symbol:i}),"bot");const e=[{id:"confirm-swap-after-approve",text:h("confirmSwapButton"),value:h("swapConfirmValue"),action:"confirm_swap",fullWidth:!0,extraData:{tx:r}}];g(h("approvalConfirmSwap"),"bot",void 0,e)}else{const n=e.error?`\nError: ${e.error}`:"";g(h("approvalFailed")+n,"bot")}}catch(a){g(h("approvalFailed"),"bot")}break}case"click_swap_dest_token":{const e=t?.tokenAddress||"",n=t?.symbol||"";Q({descTokenAddress:e,descTokenDecimals:t?.decimals||18});const o=j(),a=o.srcTokenAddress||"",s=a===Wt,c=o.amount||"";try{const t=await No({address:H?.address||"",chain:q});if(t?.success&&t?.data?.result){const r=t.data.result;let l,d="",u="0";if(s){const e=r.find(e=>e.native_token);d=J?.nativeCurrency?.symbol||"ETH",u=e?.balance_formatted||"0",l=e?.usd_price}else{const e=r.find(e=>e.token_address.toLowerCase()===a.toLowerCase());e&&(d=e.symbol,u=e.balance_formatted,l=e.usd_price)}if(c&&d){const n=sa(c,u,l),t=o.srcTokenDecimals||18,r=s?Wt:a;Q({amount:n});try{const o=Gt(n,t).toString(),a=await Oo({chainId:G,tokenIn:r,tokenInAmount:o,tokenOut:e,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(a.success&&a.data){const e=a.data,n=e.tokenIn,t=e.tokenOut,i=xo(ge(BigInt(n.amount||0),n.decimals)).decimalPlaces(6).toFormat(),c=xo(ge(BigInt(t.amount||0),t.decimals)).decimalPlaces(6).toFormat();let l=!1;if(!s&&H?.address&&e.tx?.to)try{const n=await Vo({tokenAddress:r,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:G,rpcUrl:z});l=xo(n.toString()).isLessThan(o)}catch{l=!0}const d=e.estimatedTransactionFee?.total?xo(e.estimatedTransactionFee.total):xo(0);let u=xo(0);if(l&&H?.address)try{const n=zo({tokenAddress:r,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:G,amount:o});u=await Xo({from:H.address,to:n.to,data:n.data,chainId:G,rpcUrl:z})}catch{}const f=d.plus(u),p=J?.nativeCurrency?.symbol||"native";let w="",b=!1;if(H?.address&&f.isGreaterThan(0))try{const e=await jo({address:H.address,chainId:G,rpcUrl:z});if(e.isLessThan(f)){b=!0;const n=xo(ge(BigInt(e.toFixed(0)),18)).decimalPlaces(6).toFormat(),t=xo(ge(BigInt(f.toFixed(0)),18)).decimalPlaces(6).toFormat();w=m("swapFeeWarning",{symbol:p,balance:n,needed:t})}}catch{}const A=`From: ${i} ${n.symbol}\n⬇️\nTo: ${c} ${t.symbol}\n\n`+w+"\n";if(b)g(A,"bot");else if(l){const t=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:n.symbol}),value:m("swapApproveValue",{symbol:n.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:r,spenderAddress:e.tx.to,tokenSymbol:n.symbol,amountInWei:o,tx:e.tx}}];g(A+m("swapNeedApprove",{symbol:n.symbol}),"bot",void 0,t)}else{const n=[{id:"confirm-swap",text:h("swapConfirmYes"),value:h("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(A+h("swapReadyToProceed"),"bot",void 0,n)}}else g(m("swapEstimationError",{error:a.errorMessage||a.error||"Unknown error"}),"bot")}catch(i){g(h("swapEstimationFailed"),"bot")}}else if(d&&parseFloat(u)>0){const e=[25,50,75,100],t=o.srcTokenDecimals||18,i=e.map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:d}),action:"select_percent",extraData:{percent:e,tokenAddress:a,tokenSymbol:d,tokenDecimals:t,tokenBalance:u}}));g(m("swapSelectAmount",{from:d,to:n,balance:u}),"bot",void 0,i)}else g(h("swapNoSourceToken"),"bot")}else g(h("couldNotFetchBalance"),"bot")}catch(r){g(h("couldNotLoadBalance"),"bot")}break}case"select_nft_to_send":{const e=t?.name||"NFT",n=t?.contractAddress||"",o=t?.tokenId||"",a=t?.tokenStandard||"ERC721",i=t?.amount||"1",r=t?.image||"",s={contract_address:n,token_id:o,to_address:t?.toAddress||"",token_standard:a,amount:"1",maxAmount:i,nft_name:e};g(m("nftSendReview",{name:e,standard:a,tokenId:o}),"bot",void 0,void 0,{action:"send_nft",parameters:s,status:"pending",nftInfo:{name:e,image:r||void 0,tokenId:o,contractAddress:n,tokenStandard:a}});break}default:g(m("actionExecutedFor",{action:n,value:e}),"bot")}else await Mt(500),g(m("receivedButtonValue",{value:e}),"bot");I(!1),na.isDesktop&&D.current?.focus()}catch(a){g(h("errorProcessingRequest"),"bot"),I(!1)}},[H?.address,g,v,J?.blockExplorers?.default?.url,J?.nativeCurrency?.symbol,G,q,j,Z,_,l,$,Q,z,h,m]),ne=r(async()=>{try{I(!0);const e=J?.tokenTrendingDefault||[],[n,t]=await Promise.allSettled([Fo.getTopGainers(Y,"24h",5),Fo.getTokensDetails(e,Y)]);let o=[];"fulfilled"===n.status&&n.value?.data&&(o=[...n.value.data]),"fulfilled"===t.status&&t.value?.data&&(o=[...t.value.data,...o]),o=o.filter((e,n,t)=>n===t.findIndex(n=>n.address.toLowerCase()===e.address.toLowerCase()));const a=o.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 Mt(1e3),I(!1),g(m("trendingTokensHeader",{chain:J?.name||"Unknown"}),"bot");const i=o.map((e,n)=>`${n+1}. ${e.name} (${e?.auditGoplus?.token_symbol||e.symbol||"Unknown"})\n$${xo(e?.price||0).decimalPlaces(4).toFormat()} (${e.price_change_percentage_24h||e.priceChange}%)\n\n---\n`).join("\n");g(`${i}${h("trendingTokensQuestion")}`,"bot",void 0,a)}catch(e){g(h("trendingTokensError"),"bot")}finally{I(!1)}},[g,J?.name,J?.tokenTrendingDefault,Y,h,m]),te=r(async()=>{try{g(m("viewNftViaWebsite",{link:ra}),"bot"),I(!1)}catch(e){I(!1),g(h("nftFetchError"),"bot")}},[g,h,m]),oe=r(async()=>{try{I(!0);const e=await No({address:H?.address||"",chain:q});if(e?.success&&e?.data?.result&&e.data.result.length>0){const n=e.data.result.map((e,n)=>{const t=void 0!==e.usd_value?` ≈ $${xo(e.usd_value).decimalPlaces(2).toFormat()}`:"";return`${n+1}. **${e.name}** (${e.symbol})\n Balance: ${e.balance_formatted}${t}`}).join("\n\n");await Mt(500),I(!1),g(m("viewBalancesHeader",{chain:J?.name||"this chain",list:n}),"bot",void 0)}else I(!1),g(h("viewBalancesEmpty"),"bot")}catch(e){I(!1),g(h("viewBalancesFetchError"),"bot")}},[H?.address,q,g,J?.name,h,m]),ae=d(()=>[{id:"ask",icon:"❓",text:h("suggestionAskText"),action:async()=>{S(!1),I(!0),g(h("suggestionAskUserMessage"),"user"),await Mt(1e3),I(!1),g(h("suggestionAskBotReply"),"bot")}},{id:"buy",icon:"💰",text:h("suggestionBuyText"),action:async()=>{S(!1),g(h("suggestionBuyText"),"user"),Pn(H?.address||"")&&W?await ne():(I(!0),await Mt(1e3),Pn(H?.address||"")&&!W?g(h("walletConnectedChainUnsupported"),"bot"):g(h("walletNotConnected"),"bot"),I(!1))}}],[g,H?.address,ne,h,W]),re=e=>{if(0===e)return!0;const n=b[e],t=b[e-1],o=new Date(n.timestamp),a=new Date(t.timestamp);return o.setHours(0,0,0,0),a.setHours(0,0,0,0),o.getTime()!==a.getTime()};i(()=>{R.current?.scrollIntoView({behavior:"smooth"})},[b]),i(()=>{o?(D.current&&na.isDesktop&&D.current.focus(),R.current?.scrollIntoView({behavior:"instant"}),M.current&&L.current?Date.now()-L.current>12e5&&S(!0):S(!0),L.current=null,M.current=!1,setTimeout(()=>{R.current?.scrollIntoView({behavior:"smooth"})},50)):(L.current=Date.now(),M.current=!P.current)},[o]),i(()=>{const e=e=>{"Escape"===e.key&&o&&s()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o,s]);const se=r(async()=>{if(""===C?.trim()||E)return;const e=B,n=g(C?.trim(),"user",B?.id);T(""),F(null),I(!0),S(!1),I(!0);try{let l,d;const u=b.slice(-20);let f="";if(u.length>0){f="\n\n## CONVERSATION HISTORY:\n";for(const e of u)"user"===e.sender?f+=`User: ${e.text}\n`:f+=`Assistant: ${e.text.length>400?e.text.substring(0,400)+"...":e.text}\n`;f+="\n---\n"}let p=C?.trim();e&&(p=`[Replying to ${"user"===e.sender?"my previous":"your"} message: "${e.text}"]\n\n${p}`);try{if(await oa.checkIsQuestionNormal(p,f)){x(n.id,"normal");const e=b.filter(e=>"normal"===e.typeChat);let t="";if(e.slice(-20).length>0){t="\n\n## CONVERSATION HISTORY:\n";for(const n of e.slice(-20))"normal"===n.typeChat&&("user"===n.sender?t+=`User: ${n.text}\n`:t+=`Assistant: ${n.text.length>400?n.text.substring(0,400)+"...":n.text}\n\n`)}const o=await oa.generateContent(p,t);let a=null;try{let e=o?.trim();e.startsWith("```json")?e=e.replace(/^```json\s*/,"").replace(/\s*```$/,""):e.startsWith("```")&&(e=e.replace(/^```\s*/,"").replace(/\s*```$/,"")),a=JSON.parse(e)}catch{a=null}return I(!1),void g(a?.message||o,"bot",void 0,void 0,void 0,"normal")}}catch(o){}if(H?.address&&W)try{const[e,n]=await Promise.allSettled([No({address:H.address,chain:q}),Bo({address:H.address,chain:q,limit:100,exclude_spam:!0})]);"fulfilled"===e.status&&e.value?.success&&e.value?.data?.result&&(l=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"===n.status&&n.value?.success&&n.value?.data?.result&&(d=n.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 w=function(e){const{walletAddress:n,chainName:t,chainId:o,nativeSymbol:a,walletTokens:i,walletNfts:r}=e;if(!n)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- **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.\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- **CRITICAL - LANGUAGE**: Respond in the language of the user\'s CURRENT question only. Do NOT follow language from conversation history.';if(n&&!Dt[o]?.isSupported)return`You are a Web3 wallet assistant for the Keyring crypto EVM wallet app.\n The user's wallet address is: ${n}\n The user is selected on (chainId: ${o}) 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: ${o}) 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 - **CRITICAL - LANGUAGE**: Respond in the language of the user's CURRENT question only. Ignore language from previous messages in conversation history. If current question is English → English. Vietnamese → Vietnamese. NEVER default to Chinese or any other language.\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 - 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 - **CRITICAL - LANGUAGE**: Respond in the language of the user's CURRENT question only. Do NOT follow language from conversation history.`;const s=i&&i.length>0?`\n## USER'S CURRENT WALLET BALANCE:\n${i.map(e=>{const n=void 0!==e.usd_value?` (~$${e.usd_value.toFixed(2)})`:"";return`- ${e.name} (${e.symbol})(Price: ${e.price||"N/A"}): ${e.balance_formatted}${n}${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`:"",c=r&&r.length>0?`\n## USER'S NFT COLLECTION:\n${r.map(e=>{const n="ERC1155"===e.contract_type?` (x${e.amount})`:"";return`- ${e.name}${n} | ${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`:"";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**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 (${t}), proactively tell the user which of these supported chains DO have it: ${Object.values(Dt).filter(e=>e.isSupported).map(e=>e.customName||e.name).join(", ")}. 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: ${n} | Chain: ${t} (chainId: ${o}) | Native: ${a}${s}${c}\n\n## WHEN TO USE WHICH ACTION:\n- "send_native": user wants to send the native token (${a}) 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 (with fiat or another token, single target 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 ${o} only.\nFor "chat" action: no chain restriction — use cross-chain knowledge freely.\n\n## OUTPUT FORMAT:\nRaw JSON only. No markdown code blocks. Respond in the language of the user's CURRENT question (ignore conversation history language).\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- For ERC20 actions: provide correct contract_address on chainId ${o}. If token doesn't exist on this chain, inform user.\n- send_native: ONLY for ${a}. 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).\n- token_mentions: ONLY include when the token EXISTS on the CURRENT chain (chainId ${o}). If the token is on another chain or doesn't exist on the current chain, set token_mentions to [] — but still answer the question fully with cross-chain info (which chains have it, contract addresses on those chains, etc.). Format: {"symbol":"","contract_address":"<address on chainId ${o}>","decimals":<n>}. 2+ tokens → [], use suggested_actions. Non-crypto → [].\n\n## ACTION PARAMS REFERENCE:\nValid actions: send_native, send_token, swap_token, buy_token, 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":"","contract_address":"(REQ)","decimals":""}. Both tokens → swap_token.\n5. approve_token: {"contract_address":"(REQ)","token_symbol":"","spender_address":"","amount":"","decimals":""}\n6. wrap_native: {"amount":""}\n7. unwrap_native: {"amount":""}\n8. send_nft: {"contract_address":"(opt)","token_id":"","to_address":"","token_standard":"","amount":"(def 1)","nft_name":""}\n9. view_nfts: {}\n10. view_balances: {} — use ONLY when user wants to see all balances/tokens, NOT for single token price/info queries\n11. 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// --- 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:G||void 0,nativeSymbol:J?.nativeCurrency?.symbol||void 0,walletTokens:l,walletNfts:d}),A=await async function(e){const{prompt:n,model:t="gpt-4.1-mini",stream:a=!1,systemPrompt:i}=e;if(!n)throw new Error("Prompt is required");const r=new Co(Eo),s=i?`${i}\n\n---\n\n Current User's question: ${n}`:n;let c="Unknown error";for(let l=1;l<=5;l++)try{const e=(await r.post("api/moralis-cortex/proxy/chat",{prompt:s,model:t,stream:a},{headers:{Accept:"application/json","Content-Type":"application/json"}})).data;if(!e?.text?.trim()){c="Empty response from Cortex AI";continue}return{success:!0,data:e}}catch(o){c=o instanceof Error?o.message:"Unknown error"}return{success:!1,error:c}}({prompt:p,model:"gpt-4.1-mini",stream:!1,systemPrompt:w+f});if(A.success&&A.data){const e=A.data.text||"";let l=null;try{let n=e?.trim();n.startsWith("```json")?n=n.replace(/^```json\s*/,"").replace(/\s*```$/,""):n.startsWith("```")&&(n=n.replace(/^```\s*/,"").replace(/\s*```$/,"")),l=JSON.parse(n)}catch{l=null}if(l&&l.action&&"chat"!==l.action)if("buy_token"===l.action){const e=l.parameters?.token_symbol||"";let t=l.parameters?.contract_address||"",o=18;if("native"===t.toLowerCase()&&(t=Wt),t&&t!==Wt)try{const e=await Fo.getTokensDetails([t],Y);e?.data?.[0]&&(o=e.data[0].decimals||18)}catch(a){}if(!t&&e&&H?.address)try{const n=await No({address:H.address,chain:q});if(n?.success&&n?.data?.result){const a=n.data.result,i=a.find(e=>e.token_address.toLowerCase()===t.toLowerCase())||a.find(n=>n.symbol.toUpperCase()===e.toUpperCase());i&&(t=i.token_address,o=i.decimals)}if(!t){const n=J.tokenTrendingDefault||[],[a,i]=await Promise.allSettled([Fo.getTopGainers(Y,"24h",10),Fo.getTokensDetails(n,Y)]),r=[];"fulfilled"===a.status&&a.value?.data&&r.push(...a.value.data),"fulfilled"===i.status&&i.value?.data&&r.push(...i.value.data);const s=r.find(e=>e.address?.toLowerCase()===t.toLowerCase())||r.find(n=>n.symbol?.toUpperCase()===e.toUpperCase());s&&(t=s.address,o=s.decimals||18)}}catch(a){}t?(g(l.message||m("buyTokenHelp",{symbol:e}),"bot",n.id),await Z(t,o)):(g(l.message||m("tokenNotFoundOnChain",{symbol:e}),"bot",n.id),await ne())}else if("swap_token"===l.action){const e={...l.parameters||{}},t="native"===e.token_in||e.token_in_symbol?.toUpperCase()===J?.nativeCurrency?.symbol?.toUpperCase(),o="native"===e.token_out||e.token_out_symbol?.toUpperCase()===J?.nativeCurrency?.symbol?.toUpperCase();o&&(e.token_out=Wt);let d=[];if(H?.address)try{const e=await No({address:H.address,chain:q});e?.success&&e?.data?.result&&(d=e.data.result)}catch(a){}if(!t&&(e.token_in||e.token_in_symbol)&&d.length>0){const n=e.token_in?d.find(n=>n.token_address.toLowerCase()===e.token_in.toLowerCase()):d.find(n=>n.symbol.toUpperCase()===e.token_in_symbol.toUpperCase());n&&(e.token_in=n.token_address,e.token_in_decimals=String(n.decimals))}if(!o&&(e.token_out||e.token_out_symbol)&&d.length>0){const n=e.token_out?d.find(n=>n.token_address.toLowerCase()===e.token_out.toLowerCase()):d.find(n=>n.symbol.toUpperCase()===e.token_out_symbol.toUpperCase());n&&(e.token_out=n.token_address,e.token_out_decimals=String(n.decimals))}const u=!(!e.token_in&&!t),f=!!e.token_out,p=!!e.amount;if(u&&d.length>0)if(t){const e=d.find(e=>e.native_token);if(!e||xo(e.balance_formatted||"0").isZero())return g(m("formInsufficientBalance",{balance:"0",symbol:J?.nativeCurrency?.symbol||"native"}),"bot",n.id),void I(!1)}else if(e.token_in){const t=d.find(n=>n.token_address.toLowerCase()===e.token_in.toLowerCase());if(!t)return g(m("swapTokenNotInWallet",{symbol:e.token_in_symbol||e.token_in}),"bot",n.id),void I(!1);if(xo(t.balance_formatted||"0").isZero())return g(m("formInsufficientBalance",{balance:"0",symbol:t.symbol}),"bot",n.id),void I(!1)}if(u&&f&&p)try{const n=[];e.token_out&&n.push(e.token_out),e.token_in&&!t&&n.push(e.token_in);let o=18,c=18;if(n.length>0)try{const a=await Fo.getTokensDetails(n,Y);if(a?.data)for(const n of a.data)t||n.address.toLowerCase()!==e.token_in?.toLowerCase()||(o=n.decimals||18),n.address.toLowerCase()===e.token_out?.toLowerCase()&&(c=n.decimals||18)}catch(i){}if(H?.address)try{if(d.length>0)if(t){const n=d.find(e=>e.native_token);let t=n?.balance_formatted||"0";try{const e=await Qo({chainId:G,rpcUrl:z});if(e.isGreaterThan(0)){const o=e.times(1e6),a=new xo(n?.balance||"0").minus(o);t=a.isGreaterThan(0)?xo(ge(BigInt(a.toFixed(0)),n?.decimals||18)).toFixed():"0"}}catch(r){}e.amount=sa(e.amount,t,n?.usd_price);const o=parseFloat(t),a=parseFloat(e.amount);if(xo(o).lte(0))return g(m("formInsufficientBalance",{balance:xo(o).decimalPlaces(6).toFixed(),symbol:J?.nativeCurrency?.symbol||"native"}),"bot"),void I(!1);if(xo(o).lt(a))return g(m("swapInsufficientNativeBalance",{balance:xo(o).decimalPlaces(6).toFixed(),symbol:J?.nativeCurrency?.symbol||"native",amount:e.amount}),"bot"),void I(!1)}else{const n=d.find(n=>n.token_address.toLowerCase()===e.token_in?.toLowerCase());if(!n)return g(m("swapTokenNotInWallet",{symbol:e.token_in_symbol||e.token_in}),"bot"),void I(!1);e.amount=sa(e.amount,n.balance_formatted||"0",n.usd_price);const t=parseFloat(n.balance_formatted||"0"),o=parseFloat(e.amount);if(xo(t).lt(o))return g(m("swapInsufficientTokenBalance",{balance:xo(t).decimalPlaces(6).toFixed(),symbol:n.symbol,amount:e.amount}),"bot"),void I(!1)}}catch(s){}const l=t?Wt:e.token_in;Q({srcTokenAddress:l,descTokenAddress:e.token_out,amount:e.amount,srcTokenDecimals:o,descTokenDecimals:c});const u=Gt(e.amount,o).toString(),f=await Oo({chainId:G,tokenIn:l,tokenInAmount:u,tokenOut:e.token_out,tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(f.success&&f.data){const e=f.data,n=e.tokenIn,o=e.tokenOut,i=xo(ge(BigInt(n.amount||0),n.decimals)).decimalPlaces(6).toFormat(),r=xo(ge(BigInt(o.amount||0),o.decimals)).decimalPlaces(6).toFormat();let s=!1;if(!t&&H?.address&&e.tx?.to)try{const n=await Vo({tokenAddress:l,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:G,rpcUrl:z});s=xo(n.toString()).isLessThan(u)}catch(a){s=!0}const c=e.estimatedTransactionFee?.total?xo(e.estimatedTransactionFee.total):xo(0);let d=xo(0);if(s&&H?.address)try{const n=zo({tokenAddress:l,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:G,amount:u});d=await Xo({from:H.address,to:n.to,data:n.data,chainId:G,rpcUrl:z})}catch(a){}const p=c.plus(d),w=J?.nativeCurrency?.symbol||"native";let b="",A=!1;if(H?.address&&p.isGreaterThan(0))try{const e=await jo({address:H.address,chainId:G,rpcUrl:z});if(e.isLessThan(p)){A=!0;const n=xo(ge(BigInt(e.toFixed(0)),18)).decimalPlaces(6).toFormat(),t=xo(ge(BigInt(p.toFixed(0)),18)).decimalPlaces(6).toFormat();b=m("swapFeeWarning",{symbol:w,balance:n,needed:t})}}catch(a){}const y=`From: ${i} ${n.symbol}\n⬇️\nTo: ${r} ${o.symbol}\n\n`+b+"\n";if(A)g(y,"bot");else if(s){const t=[{id:"approve-for-swap",text:m("swapApproveButton",{symbol:n.symbol}),value:m("swapApproveValue",{symbol:n.symbol}),action:"approve_for_swap",fullWidth:!0,extraData:{tokenAddress:l,spenderAddress:e.tx.to,tokenSymbol:n.symbol,amountInWei:u,tx:e.tx}}];g(y+m("swapNeedApprove",{symbol:n.symbol}),"bot",void 0,t)}else{const n=[{id:"confirm-swap",text:h("swapConfirmYes"),value:h("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];g(y+h("swapReadyToProceed"),"bot",void 0,n)}}else g(m("swapEstimationError",{error:f.errorMessage||f.error||"Unknown error"}),"bot")}catch(c){g(h("swapEstimationFailed"),"bot")}else if(u&&f&&!p){let o=t?18:parseInt(e.token_in_decimals||"18",10),s=parseInt(e.token_out_decimals||"18",10);const c=[];if(e.token_out&&c.push(e.token_out),e.token_in&&!t&&c.push(e.token_in),c.length>0)try{const n=await Fo.getTokensDetails(c,Y);if(n?.data)for(const a of n.data)t||a.address.toLowerCase()!==e.token_in?.toLowerCase()||(o=a.decimals||o),a.address.toLowerCase()===e.token_out?.toLowerCase()&&(s=a.decimals||s)}catch(i){}if(Q({descTokenAddress:e.token_out,descTokenDecimals:s}),t)try{if(d.length>0){const e=d.find(e=>e.native_token),t=J?.nativeCurrency?.symbol||"ETH";let a=e?.balance_formatted||"0";try{const n=await Qo({chainId:G,rpcUrl:z});if(n.isGreaterThan(0)){const t=n.times(1e6),o=new xo(e?.balance||"0").minus(t);a=o.isGreaterThan(0)?xo(ge(BigInt(o.toFixed(0)),e?.decimals||18)).toFixed():"0"}}catch(r){}Q({srcTokenAddress:Wt,srcTokenDecimals:o});const i=[25,50,75,100].map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:t}),action:"select_percent",extraData:{percent:e,tokenAddress:Wt,tokenSymbol:t,tokenDecimals:o,tokenBalance:a}}));g(m("selectAmountToSwap",{symbol:t,balance:a}),"bot",n.id,i)}else g(h("couldNotFetchBalance"),"bot")}catch(a){g(h("couldNotFetchBalanceRetry"),"bot")}else{const t=e.token_in_symbol||"Token";Q({srcTokenAddress:e.token_in,srcTokenDecimals:o});try{if(d.length>0){const o=d.find(n=>n.token_address.toLowerCase()===e.token_in?.toLowerCase());if(!o)return g(m("swapTokenNotInWallet",{symbol:t}),"bot"),void I(!1);const a=[25,50,75,100].map(e=>({id:`percent-${e}`,text:`${e}%`,value:m("buttonUsePercent",{percent:String(e),symbol:o.symbol}),action:"select_percent",extraData:{percent:e,tokenAddress:o.token_address,tokenSymbol:o.symbol,tokenDecimals:o.decimals||18,tokenBalance:o.balance_formatted}}));g(m("selectAmountToSwap",{symbol:o.symbol,balance:`${o.balance_formatted} (~$${o.usd_value?.toFixed(2)||"0"})`}),"bot",n.id,a)}else g(h("couldNotFetchBalance"),"bot")}catch(a){g(h("couldNotFetchBalanceRetry"),"bot")}}}else if(!u&&f){g(l.message||h("swapChooseFrom"),"bot",n.id);let t=parseInt(e.token_out_decimals||"18",10);if(e.token_out)try{const n=await Fo.getTokensDetails([e.token_out],Y);n?.data?.[0]&&(t=n.data[0].decimals||t)}catch(i){}await Z(e.token_out,t)}else if(u&&!f){let o=t?18:parseInt(e.token_in_decimals||"18",10);if(e.token_in&&!t)try{const n=await Fo.getTokensDetails([e.token_in],Y);n?.data?.[0]&&(o=n.data[0].decimals||o)}catch(i){}Q(t?{srcTokenAddress:Wt,srcTokenDecimals:18,...p?{amount:e.amount}:{}}:{srcTokenAddress:e.token_in,srcTokenDecimals:o,...p?{amount:e.amount}:{}}),g(l.message||m("swapChooseTo",{symbol:e.token_in_symbol||"your token"}),"bot",n.id);try{I(!0);const e=J?.tokenTrendingDefault||[],[n,t]=await Promise.allSettled([Fo.getTopGainers(Y,"24h",5),Fo.getTokensDetails(e,Y)]);let o=[];"fulfilled"===n.status&&n.value?.data&&(o=[...n.value.data]),"fulfilled"===t.status&&t.value?.data&&(o=[...t.value.data,...o]),o=o.filter((e,n,t)=>n===t.findIndex(n=>n.address.toLowerCase()===e.address.toLowerCase()));const a=o.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,a)}catch(a){g(h("couldNotLoadTokenList"),"bot")}finally{I(!1)}}else if(g(l.message||h("swapChooseToken"),"bot",n.id),H?.address)try{I(!0);const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result&&e.data.result.length>0){const n=e.data.result.map(e=>({id:`swap-select-${e.token_address}`,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${xo(e?.usd_value||0).decimalPlaces(2).toFixed()||"0"})`,value:`Swap ${e.symbol}`,action:"suggested_action",fullWidth:!0}));await Mt(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(a){I(!1),g(h("walletFetchError"),"bot")}}else if("view_balances"===l.action)await oe();else if("view_nfts"===l.action)await te();else if("send_token"!==l.action||l.parameters?.contract_address||l.parameters?.token_symbol||!H?.address)if("send_nft"!==l.action||l.parameters?.contract_address||l.parameters?.token_id||l.parameters?.nft_name||!H?.address)if("send_nft"===l.action&&!Pn(l.parameters?.contract_address||"")&&(l.parameters?.nft_name||l.parameters?.token_id)&&H?.address)try{I(!0);const e=await Bo({address:H.address,chain:q,limit:100,exclude_spam:!1});if(e?.success&&e?.data?.result){const t=e.data.result,o=(l.parameters?.nft_name||"").toLowerCase(),a=l.parameters?.token_id||"",i=e=>{const n=(e.normalized_metadata?.name||e.name||"").toLowerCase(),t=(e.name||"").toLowerCase(),i=o&&(n.includes(o)||t.includes(o)),r=a&&e.token_id===a;return o&&a?i&&r:o?i:r},r=!o&&!!a,s=r?t.filter(i):[],c=r?1===s.length?s[0]:null:t.find(i);if(r&&s.length>1){const e=s.map(e=>{const n=e.normalized_metadata?.name||e.name||`#${e.token_id}`,t=e.normalized_metadata?.image||e.media?.original_media_url||"";return{id:`${e.token_address}-${e.token_id}`,text:`${n} (${e.symbol||e.contract_type}) #${e.token_id}`,value:m("buttonSendNft",{name:n}),action:"select_nft_to_send",fullWidth:!0,extraData:{contractAddress:e.token_address,tokenId:e.token_id,tokenStandard:e.contract_type,name:n,symbol:e.symbol,amount:e.amount,image:t,toAddress:l.parameters?.to_address||""}}}),t=s.map((e,n)=>{const t=e.normalized_metadata?.name||e.name||`#${e.token_id}`,o=e.normalized_metadata?.image||e.media?.original_media_url||"";return`${n+1}. ${o?`![${t}](${o})\n`:"🖼️ "}**${t}**\n ${e.symbol||e.contract_type} | Token ID: ${e.token_id}`}).join("\n\n");I(!1),g(m("nftMultipleMatchesForTokenId",{count:String(s.length),tokenId:a})+"\n\n"+t,"bot",n.id,e)}else if(c){const e=c.normalized_metadata?.name||c.name||`#${c.token_id}`,t=c.normalized_metadata?.image||c.media?.original_media_url||"",o={contract_address:c.token_address,token_id:c.token_id,to_address:l.parameters?.to_address||"",token_standard:c.contract_type||"",amount:"1",maxAmount:c.amount||"1",nft_name:e};g(l.message||m("nftSendReview",{name:e,standard:c.contract_type||"NFT",tokenId:c.token_id}),"bot",n.id,void 0,{action:"send_nft",parameters:o,status:"pending",nftInfo:{name:e,image:t||void 0,tokenId:c.token_id,contractAddress:c.token_address,tokenStandard:c.contract_type||void 0}})}else g(m("nftNotFoundInWallet",{name:o||a}),"bot",n.id)}else g(h("nftNoCollection"),"bot",n.id)}catch(a){g(h("nftFetchError"),"bot",n.id)}finally{I(!1)}else{const i=(t=l.action,["send_native","send_token","approve_token","wrap_native","unwrap_native","send_nft"].includes(t));let s,c,d={...l.parameters||{}};const u=["send_token","approve_token"].includes(l.action)&&(d.contract_address||d.token_symbol),f="send_native"===l.action||"wrap_native"===l.action,p="unwrap_native"===l.action,h="send_nft"===l.action&&d.contract_address;if(u&&H?.address)try{const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result){const n=e.data.result,t=d.contract_address?n.find(e=>e.token_address.toLowerCase()===d.contract_address.toLowerCase()):n.find(e=>e.symbol.toUpperCase()===d.token_symbol.toUpperCase());t&&(d={...d,contract_address:t.token_address,decimals:String(t.decimals)},s={symbol:t.symbol,name:t.name,balance:t.balance,balanceFormatted:t.balance_formatted,usdValue:t.usd_value,usdPrice:t.usd_price,decimals:t.decimals,logo:t.logo||t.thumbnail,contractAddress:t.token_address})}}catch(a){}if(u&&!s&&"send_token"===l.action){const e=d.token_symbol||d.contract_address||"this token";return g(m("sendTokenNotInWallet",{symbol:e}),"bot",n.id),void I(!1)}if(u&&!s&&d.contract_address)try{const e=await So({address:d.contract_address,chain:q});if(e?.success&&e?.data){const n=e.data;s={symbol:n.symbol,name:n.name,balance:"0",balanceFormatted:"0",usdPrice:n.usd_price,decimals:n.decimals,logo:n.logo,contractAddress:d.contract_address},d={...d,decimals:String(n.decimals)}}}catch(a){}if(f&&H?.address)try{const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result){const n=e.data.result.find(e=>e.native_token);if(n){let e=n.balance_formatted,t=n.balance;try{const o=new xo(n.balance),a="0x"+BigInt(o.toFixed(0)).toString(16),i=await Xo({from:H.address,to:H.address,data:"0x",value:a,chainId:G,rpcUrl:z});if(i.isGreaterThan(0)){const a=o.minus(i);a.isGreaterThan(0)?(t=a.toFixed(0),e=xo(ge(BigInt(a.toFixed(0)),n.decimals)).toFixed()):(t="0",e="0")}}catch(r){}s={symbol:n.symbol,name:n.name,balance:t,balanceFormatted:e,usdValue:n.usd_value,usdPrice:n.usd_price,decimals:n.decimals,logo:n.logo||n.thumbnail,contractAddress:Wt}}else{const e=await So({address:Wt,chain:q});if(e?.success&&e?.data){const n=e.data;s={symbol:n.symbol,name:n.name,balance:"0",balanceFormatted:"0",usdValue:0,usdPrice:n.usd_price,decimals:n.decimals,logo:n.logo||n.thumbnail,contractAddress:Wt}}}}}catch(a){}if(p&&H?.address)try{const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result){const n=e.data.result,t=`W${J?.nativeCurrency?.symbol||"ETH"}`,o=n.find(e=>e.symbol.toUpperCase()===t.toUpperCase());o&&(s={symbol:o.symbol,name:o.name,balance:o.balance,balanceFormatted:o.balance_formatted,usdValue:o.usd_value,usdPrice:o.usd_price,decimals:o.decimals,logo:o.logo||o.thumbnail,contractAddress:o.token_address})}}catch(a){}if(h){try{const e=await async function(e){const{address:n,chain:t="base"}=e;if(!n)throw new Error("Contract address is required");try{return{success:!0,data:(await Io.get(`api/moralis/proxy/nft/${encodeURIComponent(n)}/metadata`,{query:{chain:t}})).data}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}({address:d.contract_address,chain:q});if(e?.success&&e?.data){const n=e.data;n.contract_type&&(d={...d,token_standard:n.contract_type}),!d.nft_name&&n.name&&(d={...d,nft_name:n.name})}}catch(a){}if(H?.address)try{const e=await Bo({address:H.address,chain:q,limit:100,exclude_spam:!1});if(e?.success&&e?.data?.result){const t=e.data.result.find(e=>e.token_address.toLowerCase()===d.contract_address.toLowerCase()&&e.token_id===d.token_id);if(!t){const e=d.nft_name||`#${d.token_id||d.contract_address}`;return g(m("nftNotFoundInWallet",{name:e}),"bot",n.id),void I(!1)}{d={...d,amount:"1",maxAmount:t.amount||"1"};const e=t.normalized_metadata?.image||t.media?.original_media_url||"";c={name:t.normalized_metadata?.name||t.name||d.nft_name||`#${t.token_id}`,image:e||void 0,tokenId:t.token_id,contractAddress:t.token_address,tokenStandard:t.contract_type||d.token_standard||void 0}}}}catch(a){}}if(d.amount&&s?.balanceFormatted&&("send_token"===l.action||"send_native"===l.action||"wrap_native"===l.action||"unwrap_native"===l.action)&&(d.amount=sa(d.amount,s.balanceFormatted,s.usdPrice)),i){const e=l.message||"Please review and complete the form below.";g(e,"bot",n.id,void 0,{action:l.action,parameters:d,status:"pending",tokenInfo:s,nftInfo:c})}else g(l.message||e,"bot",n.id)}else g(m("sendNftViaWebsite",{link:ra}),"bot");else try{const e=await No({address:H.address,chain:q});if(e?.success&&e?.data?.result&&e.data.result.length>0){g(h("sendTokenChoose"),"bot",n.id),I(!0),await Mt(500);const t=e.data.result.map(e=>({id:`send-select-${e.token_address}`,text:`${e.name}: ${e.balance_formatted} ${e.symbol} ($${xo(e?.usd_value||0).decimalPlaces(2).toFixed()||"0"})`,value:m("buttonSendToken",{symbol:e.symbol}),action:"suggested_action",fullWidth:!0}));await Mt(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(a){I(!1),g(h("walletFetchError"),"bot")}else if(l&&"chat"===l.action){const t=l.token_mentions||[],o=l.suggested_actions||[],a=[];t.length>0&&t.forEach(e=>{a.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||18},fullWidth:!0})}),o.length>0&&o.forEach((e,n)=>{a.push({id:`suggested-${n}-${e.label}`,text:e.label,value:e.prompt,action:"suggested_action",fullWidth:!0})}),a.length>0?g(l.message||e,"bot",n.id,a):g(l.message||e,"bot",n.id)}else g(e,"bot",n.id)}else g(h("errorProcessingRequest"),"bot",n.id)}catch(o){g(h("errorProcessingRequest"),"bot",n.id)}var t;I(!1),await Mt(50),na.isDesktop&&D.current?.focus()},[C,E,B,g,b,H?.address,W,J?.name,J?.nativeCurrency?.symbol,J?.tokenTrendingDefault,G,x,q,Y,m,Z,ne,h,Q,z,oe,te]);i(()=>{U.current&&C===U.current&&(U.current=null,se())},[C,se]);const ce=r(async(e,n,t)=>{try{if(S(!1),A(t,"submitted"),"swap_token"===e){let e=18;if(n.token_in&&n.token_in!==Wt)try{const t=await Fo.getTokensDetails([n.token_in],Y);t?.data?.[0]&&(e=t.data[0].decimals||18)}catch(o){}const i=Gt(n.amount||"0",e).toString(),r=await Oo({chainId:G,tokenIn:n.token_in||"",tokenInAmount:i,tokenOut:n.token_out||"",tokenOutRecipient:H?.address||"",slippage:"auto",accesstoken:"d6c45897b8f6"});if(r.success&&r.data){const e=r.data,o=e.tokenIn,s=e.tokenOut,c=xo(ge(BigInt(o.amount||0),o.decimals)).decimalPlaces(6).toFormat(),l=xo(ge(BigInt(s.amount||0),s.decimals)).decimalPlaces(6).toFormat(),d=!n.token_in||n.token_in===Wt;let u=!1;if(!d&&H?.address&&e.tx?.to)try{const t=await Vo({tokenAddress:n.token_in,ownerAddress:H.address,spenderAddress:e.tx.to,chainId:G,rpcUrl:z});u=xo(t.toString()).isLessThan(i)}catch(a){}const f=e.estimatedTransactionFee?.total?xo(e.estimatedTransactionFee.total):xo(0);let p=xo(0);if(u&&H?.address)try{const t=zo({tokenAddress:n.token_in,spenderAddress:e.tx?.to||"",fromAddress:H.address,chainId:G,amount:i});p=await Xo({from:H.address,to:t.to,data:t.data,chainId:G,rpcUrl:z})}catch(a){}const w=f.plus(p),b=J?.nativeCurrency?.symbol||"native";let y="",v=!1;if(H?.address&&w.isGreaterThan(0))try{const e=await jo({address:H.address,chainId:G,rpcUrl:z});if(e.isLessThan(w)){v=!0;const n=xo(ge(BigInt(e.toFixed(0)),18)).decimalPlaces(6).toFormat(),t=xo(ge(BigInt(w.toFixed(0)),18)).decimalPlaces(6).toFormat();y=m("swapFeeWarning",{symbol:b,balance:n,needed:t})}}catch(a){}const k=`From: ${c} ${o.symbol}\n⬇️\nTo: ${l} ${s.symbol}\n\n`+y+"\n";if(v)A(t,"pending"),g(k,"bot");else if(u){const a=[{id:"approve-swap-actionform",text:m("swapApproveButton",{symbol:o.symbol}),value:m("swapApproveValue",{symbol:o.symbol}),action:"approve_for_swap",extraData:{tokenAddress:n.token_in,spenderAddress:e.tx.to,tokenSymbol:o.symbol,amountInWei:i,tx:e.tx},fullWidth:!0}];A(t,"success"),g(k+m("swapApprovalRequired",{symbol:o.symbol}),"bot",void 0,a)}else{const n=[{id:"confirm-swap-actionform",text:h("swapConfirmYes"),value:h("swapConfirmValue"),action:"confirm_swap",extraData:{tx:e.tx}}];A(t,"success"),g(k+h("swapReadyToProceed"),"bot",void 0,n)}}else A(t,"pending"),g(m("swapEstimationError",{error:r.errorMessage||r.error||"Unknown error"}),"bot")}else{const o=function(e){const{action:n,parameters:t,fromAddress:o,chainId:a}=e;switch(n){case"send_native":return function(e,n,t){const{to_address:o,amount:a}=e;if(!o)throw new Error("Recipient address is required");if(!a)throw new Error("Amount is required");return{from:n,to:o,data:"0x",value:Gt(a,18).toString(),chainId:t,description:`Send ${a} native token to ${o}`}}(t,o,a);case"send_token":return function(e,n,t){const{contract_address:o,to_address:a,amount:i,decimals:r,token_symbol:s}=e;if(!o)throw new Error("Token contract address is required");if(!a)throw new Error("Recipient address is required");if(!i)throw new Error("Amount is required");const c=Gt(i,parseInt(r)||18);return{from:n,to:o,data:Rt({abi:Ho,functionName:"transfer",args:[a,c]}),value:"0",chainId:t,description:`Send ${i} ${s||"tokens"} to ${a}`}}(t,o,a);case"approve_token":return function(e,n,t){const{contract_address:o,spender_address:a,amount:i,token_symbol:r}=e;if(!o)throw new Error("Token contract address is required");if(!a)throw new Error("Spender address is required");const s=i&&""!==i?.trim()?Gt(i,18):ie;return{from:n,to:o,data:Rt({abi:Ho,functionName:"approve",args:[a,s]}),value:"0",chainId:t,description:`Approve ${i||"unlimited"} ${r||"tokens"} for ${a}`}}(t,o,a);case"wrap_native":return function(e,n,t){const{amount:o}=e;if(!o)throw new Error("Amount is required");const a=Po[t];if(!a)throw new Error(`WETH not supported on chain ${t}`);const i=Gt(o,18).toString();return{from:n,to:a,data:Rt({abi:Jo,functionName:"deposit"}),value:i,chainId:t,description:`Wrap ${o} native token`}}(t,o,a);case"unwrap_native":return function(e,n,t){const{amount:o}=e;if(!o)throw new Error("Amount is required");const a=Po[t];if(!a)throw new Error(`WETH not supported on chain ${t}`);const i=Gt(o,18);return{from:n,to:a,data:Rt({abi:Jo,functionName:"withdraw",args:[i]}),value:"0",chainId:t,description:`Unwrap ${o} WETH`}}(t,o,a);case"send_nft":return function(e,n,t){const{contract_address:o,token_id:a,to_address:i,token_standard:r,amount:s,nft_name:c}=e;if(!o)throw new Error("NFT contract address is required");if(!a)throw new Error("Token ID is required");if(!i)throw new Error("Recipient address is required");const l=(r||"ERC721").toUpperCase(),d=BigInt(a);let u,f;if("ERC1155"===l){const e=BigInt(s||"1");u=Rt({abi:qo,functionName:"safeTransferFrom",args:[n,i,d,e,"0x"]}),f=`Send ${e>1n?e.toString()+"x ":""}${c||"NFT"} (ERC1155 #${a}) to ${i}`}else u=Rt({abi:Yo,functionName:"safeTransferFrom",args:[n,i,d]}),f=`Send ${c||"NFT"} (ERC721 #${a}) to ${i}`;return{from:n,to:o,data:u,value:"0",chainId:t,description:f}}(t,o,a);default:throw new Error(`Action "${n}" does not produce a transaction`)}}({action:e,parameters:n,fromAddress:H?.address||"",chainId:G||1}),a={from:o.from,to:o.to,data:o.data,value:o.value,chainId:o.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",n=await Xo({from:o.from,to:o.to,data:o.data,value:o.value&&"0"!==o.value?`0x${BigInt(o.value).toString(16)}`:void 0,chainId:G,rpcUrl:z});if(n.isGreaterThan(0)){const o=await jo({address:H.address,chainId:G,rpcUrl:z});if(o.isLessThan(n)){const a=xo(ge(BigInt(o.toFixed(0)),18)).decimalPlaces(6).toFormat(),i=xo(ge(BigInt(n.toFixed(0)),18)).decimalPlaces(6).toFormat();return A(t,"pending"),void g(m("txInsufficientGas",{symbol:e,balance:a,fee:i}),"bot")}}}catch(i){}if(l){I(!1);const o=await l(a);if("success"===o.status&&o.transactionHash){const a=J?.blockExplorers?.default?.url,i=a?` [View on Explorer](${a}/tx/${o.transactionHash})`:` Tx: ${o.transactionHash}`;try{if(await Mt(4e3),"success"===(await Wo({transactionHash:o.transactionHash,chainId:G||1,rpcUrl:z})).status){if(A(t,"success"),y(t,n),"approve_token"===e&&g(m("approvalSuccess",{symbol:n.token_symbol||n.contract_address||"Token"})+i,"bot"),"send_token"===e||"send_native"===e||"send_nft"===e){const t=n.to_address||n.recipient||"",o=t?`${t.slice(0,6)}...${t.slice(-4)}`:"";g("send_nft"===e?m("txSuccessfulSendNft",{name:n.nft_name||n.token_symbol||"NFT",tokenId:n.token_id||"",to:o})+i:m("send_native"===e?"txSuccessfulSendNative":"txSuccessfulSendToken",{amount:n.amount||"",symbol:n.token_symbol||("send_native"===e?J?.nativeCurrency?.symbol||"native":"Token"),to:o})+i,"bot")}if("wrap_native"===e){const e=J?.nativeCurrency?.symbol||"native";g(m("txSuccessfulWrapNative",{amount:n.amount||"",from:e,to:`W${e}`})+i,"bot")}if("unwrap_native"===e){const e=J?.nativeCurrency?.symbol||"native";g(m("txSuccessfulUnwrapNative",{amount:n.amount||"",from:`W${e}`,to:e})+i,"bot")}}else A(t,"pending"),g(h("txReverted")+"\n"+i,"bot")}catch(r){A(t,"success"),g(h("txTimeout")+"\n"+i,"bot")}}else if("success"===o.status)A(t,"success");else{A(t,"pending");const e=o.error?`\nError: ${o.error}`:"";g(h("txFailed")+e,"bot")}}else A(t,"pending"),g(h("txNoHandler"),"bot")}}catch(s){A(t,"pending"),g(m("txError",{message:s instanceof Error?s.message:"Unknown error"}),"bot")}},[A,G,H?.address,Y,J?.nativeCurrency?.symbol,J?.blockExplorers?.default?.url,z,m,g,h,l,y]),le=r(e=>{k([e])},[k]),[de,ue]=a({}),fe=r(async(e,n,t)=>{ue(e=>({...e,[t]:!0}));try{await ce(e,n,t)}finally{ue(e=>({...e,[t]:!1}))}},[ce]),pe=r(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),se())},[se]),he=r(()=>{const e=window.getSelection();e&&e.toString().length>0||s()},[s]);return o?/* @__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__ */t("div",{className:"chat-modal",style:p,onClick:e=>e.stopPropagation(),children:[
31
31
  /* @__PURE__ */t("div",{className:"chat-modal-header",children:[
32
32
  /* @__PURE__ */t("div",{className:"chat-modal-header-title",children:[
33
33
  /* @__PURE__ */t("div",{className:"chat-modal-header-left",children:[