keyring-agent-core 0.2.46 → 0.2.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var ya=Object.create;var ao=Object.defineProperty;var ba=Object.getOwnPropertyDescriptor;var wa=Object.getOwnPropertyNames;var ka=Object.getPrototypeOf,Ta=Object.prototype.hasOwnProperty;var va=(a,e)=>{for(var t in e)ao(a,t,{get:e[t],enumerable:!0})},Dr=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wa(e))!Ta.call(a,r)&&r!==t&&ao(a,r,{get:()=>e[r],enumerable:!(n=ba(e,r))||n.enumerable});return a};var Aa=(a,e,t)=>(t=a!=null?ya(ka(a)):{},Dr(e||!a||!a.__esModule?ao(t,"default",{value:a,enumerable:!0}):t,a)),Sa=a=>Dr(ao({},"__esModule",{value:!0}),a);var ou={};va(ou,{AI_AGENT_TOOL_NAMES:()=>qo,AbortError:()=>Ke,AgentCore:()=>Yo,ApproveTokenTool:()=>Pn,BaseNftAiTool:()=>Oe,BaseSwapService:()=>Ze,BaseTool:()=>v,BaseWalletActionTool:()=>Pe,BuyTokenTool:()=>xn,ChatHistory:()=>En,DEFAULT_CHAIN:()=>ve,DEFAULT_PROVIDER:()=>Yn,DEFAULT_RPC_BY_CHAIN:()=>Te,DebridgeAdapter:()=>en,EstimatePoolYieldTool:()=>dn,GeminiProvider:()=>z,GeminiSearchAiTool:()=>Xt,HEX_TO_PANTOGRAPH:()=>ws,KnowledgeBase:()=>Nn,ManageLiquidityRedirectTool:()=>mn,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>Fo,NFC_AMAZON_DEFAULT_DOMAIN:()=>wr,NFC_AMAZON_DOMAINS:()=>br,NFTContractInfoTool:()=>Gt,NFTMetadataTool:()=>Yt,NFT_AGENT_TOOL_NAMES:()=>Mo,NfcBuyTool:()=>zt,NfcInfoTool:()=>Kt,NoFormTool:()=>zn,OpenAddLiquidityFormTool:()=>cn,POOL_AGENT_TOOL_NAMES:()=>Bo,PantographService:()=>le,PoolByAddressTool:()=>ln,PoolDetailTool:()=>sn,PoolFallbackAiTool:()=>Qt,PoolPriceRangesTool:()=>pn,PoolSearchTool:()=>an,PoolService:()=>ce,PreviewAddLiquidityTool:()=>un,RelayAdapter:()=>tn,Router:()=>Un,SUPPORTED_CHAINS:()=>Tt,SUPPORTED_CHAINS_LABEL:()=>At,SWAP_PROVIDER_CONFIG:()=>Co,SendNativeTool:()=>An,SendNftTool:()=>_n,SendTokenTool:()=>Sn,Subagent:()=>X,SubgraphAddPoolTool:()=>kn,SubgraphCoinPoolPairsTool:()=>wn,SubgraphPoolByAddressTool:()=>fn,SubgraphPoolByPositionIdTool:()=>yn,SubgraphPoolSearchTool:()=>hn,SubgraphPositionDetailTool:()=>bn,SubgraphTrendingPoolsTool:()=>gn,Summarizer:()=>Rn,SwapServiceFactory:()=>dt,SwapTokenTool:()=>Cn,Synthesizer:()=>In,TOKEN_AGENT_TOOL_NAMES:()=>Oo,TRANSFER_TOPIC:()=>Xs,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>ks,TokenAnalyticsTool:()=>_t,TokenHoldersTool:()=>Ct,TokenInfoTool:()=>xt,TokenScoreTool:()=>Et,ToolRegistry:()=>kt,TopGainersTool:()=>Nt,TopPoolsTool:()=>rn,TransactionByHashTool:()=>Vt,TrendingTokensTool:()=>Rt,UNISWAP_CHAIN_SLUG:()=>Kn,UpstashKnowledgeBase:()=>nt,WALLET_ACTION_AGENT_TOOL_NAMES:()=>$o,WALLET_AGENT_TOOL_NAMES:()=>Do,WalletApprovalsTool:()=>Ft,WalletDefiPositionsTool:()=>Bt,WalletDefiProtocolPositionsTool:()=>$t,WalletDefiSummaryTool:()=>qt,WalletHistoryTool:()=>It,WalletNFTsTool:()=>Ht,WalletNftTransfersTool:()=>Dt,WalletPnlSummaryTool:()=>Ot,WalletPnlTool:()=>Mt,WalletTokenBalancesTool:()=>Ut,WalletTokenTransfersTool:()=>Lt,WebsiteTrustKeyringAgent:()=>jo,ZERO_ADDRESS:()=>B,amazonDomainForLanguage:()=>kr,apiClient:()=>x,buildChallenge:()=>lr,buildRangePresets:()=>Sr,buildUniswapPoolUrl:()=>ke,clampTick:()=>De,completeX402:()=>cr,configureSupportedChains:()=>fo,createAiAgent:()=>to,createDefaultSubagents:()=>Vo,createNfcAgent:()=>eo,createNftAgent:()=>Zn,createPoolAgent:()=>no,createTokenAgent:()=>Jn,createWalletActionAgent:()=>oo,createWalletAgent:()=>Qn,createX402SignatureProvider:()=>dr,displayFromChallenge:()=>us,encodeSignedHeader:()=>ur,ethCallAt:()=>$n,ethCallByChain:()=>sr,fetchTopMarketplaces:()=>Tr,getAffiliateFee:()=>Zt,getChainMeta:()=>oe,getDefaultRpcUrl:()=>Ba,getGatewayAddress:()=>Eo,getGatewayChains:()=>Ro,getNativeTokenInfo:()=>nn,getPositionManagerAddress:()=>No,getProviderByChain:()=>xo,ingestKnowledgeBase:()=>fa,isAbortError:()=>ut,isPaymentRequired:()=>pi,nfcAmazonSearchUrl:()=>To,normaliseCountry:()=>vo,normalizePriceRangeToPool:()=>ft,priceToTick:()=>ct,readPaymentError:()=>ls,readPaymentRequired:()=>mo,readReceipt:()=>cs,registerMaybeNoForm:()=>Lo,requestWithX402:()=>di,resolveNfcShopLinks:()=>jt,resolveRpcUrl:()=>$e,roundTickToSpacing:()=>Le,rpcCall:()=>Ve,setRpcOverrides:()=>rr,swapServiceFactory:()=>Me,tickToPrice:()=>Ce,toPantographChain:()=>Ri});module.exports=Sa(ou);var Mr=Aa(require("axios"));var Or="0.2.46";var xa=`keyring-agent-core/${Or} (Keyring Chatbot Agent; +https://keyring.app)`,zo=null;function Fr(a){zo=a}var Ca=["payment-signature","x-payment"];function _a(a){return a?Object.keys(a).some(e=>Ca.includes(e.toLowerCase())):!1}var qr;function Mn(a){qr=a}var Ea=3e4,Ra=typeof process<"u"&&process.versions?.node!=null,Xo=class{instance;constructor(e={}){this.instance=Mr.default.create({baseURL:e.baseURL,timeout:e.timeout??Ea,validateStatus:()=>!0,headers:{Accept:"application/json",...Ra?{"User-Agent":e.userAgent??xa}:{},...e.headers}})}async request(e,t,n,r={}){let o=r.signal??qr,s=await this.instance.request({...r,signal:o,method:e,url:t,data:n}),i={};for(let[c,u]of Object.entries(s.headers??{}))u!=null&&(i[c.toLowerCase()]=String(u));let l={ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,data:s.data,headers:i};if(l.status===402&&zo&&!_a(r.headers)){let c=await zo(l,{url:t,method:String(e),body:n,headers:r.headers});if(c)return this.request(e,t,n,{...r,headers:{...r.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Xo;function I(a){let{data:e,status:t,statusText:n}=a,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=l=>l&&typeof l=="object"?l.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}var Br=require("js-sha3");function q(a){return typeof a=="string"&&/^0x[0-9a-fA-F]{40}$/.test(a)}function Na(a){return new Uint8Array(Br.keccak256.arrayBuffer(a))}function Fn(a){let e=a.startsWith("0x")?a.slice(2):a,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function $r(a){return"0x"+Array.from(a).map(e=>e.toString(16).padStart(2,"0")).join("")}function Vr(a){return new TextEncoder().encode(a)}function lt(...a){let e=a.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;return t}function Ua(a,e=32){let t=new Uint8Array(e);return t.set(a,e-a.length),t}function Ia(a,e=32){let t=new Uint8Array(e);return t.set(a),t}function Wr(a){let e=((a%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Fn(e)}function qn(a){return Wr(BigInt(a))}function Hr(a){return a==="uint"?"uint256":a==="int"?"int256":a.match(/^uint$/)?"uint256":a.match(/^int$/)?"int256":a.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function Gr(a){let e=Hr(a.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(a.components??[]).map(Gr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function La(a){let e=(a.inputs??[]).map(Gr).join(",");return`${a.name??""}(${e})`}function Qo(a,e){let t=Ma(a.type);if(t){let[r,o]=t;return Da({...a,type:o},e,r)}if(a.type==="tuple")return Oa(a,e);if(a.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:Ua(Fn(o.toLowerCase()))}}if(a.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Hr(a.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:qn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:Wr(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Fn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ia(o)}}if(n==="bytes"){let r=typeof e=="string"?Fn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:lt(qn(r.length),s)}}if(n==="string"){let r=typeof e=="string"?Vr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:lt(qn(r.length),s)}}throw new Error(`Unsupported ABI type: ${a.type}`)}function Jo(a){let e=0;for(let{dynamic:o,encoded:s}of a)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of a)o?(t.push(qn(e+r)),n.push(s),r+=s.length):t.push(s);return lt(...t,...n)}function Da(a,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let i=Qo(a,s);i.dynamic&&(r=!0),o.push(i)}if(n||r){let s=Jo(o);if(n){let i=qn(o.length);return{dynamic:!0,encoded:o.length>0?lt(i,s):i}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:lt(...o.map(s=>s.encoded))}}function Oa(a,e){let t=a.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],i=Array.isArray(e)?e[o]:e[s.name??""],l=Qo(s,i);l.dynamic&&(n=!0),r.push(l)}return{dynamic:n,encoded:n?Jo(r):lt(...r.map(o=>o.encoded))}}function Ma(a){let e=a.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Zo(a,e){if(a.length!==e.length)throw new Error(`Expected ${a.length} values, got ${e.length}`);if(a.length===0)return"0x";let t=a.map((r,o)=>Qo(r,e[o])),n=Jo(t);return $r(n)}function ht({abi:a,functionName:e,args:t=[]}){let n=a.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=La(n),o=Na(Vr(r)).slice(0,4),s=n.inputs??[],i=s.length===0||t.length===0?new Uint8Array(0):Fn(Zo(s,t).slice(2));return $r(lt(o,i))}var er=require("js-sha3"),Yr=2n**96n;function Z(a,e=8){return!Number.isFinite(a)||a===0?a:Number(a.toPrecision(e))}function jr(a,e,t){let n=a*a,r=Yr*Yr,o=n*10n**18n/r;return Number(o)/1e18*Math.pow(10,e-t)}function Ce(a,e,t){return Math.pow(1.0001,a)*Math.pow(10,e-t)}function ct(a,e,t){if(a<=0)throw new Error("priceToTick: price must be > 0");let n=a/Math.pow(10,e-t),r=Math.log(n)/Math.log(1.0001),o=Math.round(r);return Math.abs(r-o)<.001?o:Math.floor(r)}function ft(a,e,t){let n={minPrice:a,maxPrice:e,inverted:!1};if(!Number.isFinite(a)||!Number.isFinite(e)||!Number.isFinite(t)||a<=0||e<=0||t<=0||a>=e)return n;let r={minPrice:1/e,maxPrice:1/a,inverted:!0},o=c=>t>=c.minPrice&&t<=c.maxPrice,s=o(n),i=o(r);if(s&&!i)return n;if(i&&!s)return r;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(r)<l(n)?r:n}function Le(a,e,t="nearest"){let n=Math.abs(a-Math.round(a))<1e-6?Math.round(a):a,r=(n%e+e)%e;if(r===0)return n;let o=n-r,s=o+e;return t==="down"?o:t==="up"?s:n-o<s-n?o:s}var je=-887272,gt=887272;function De(a){return a<je?je:a>gt?gt:a}var Fa=/^0x[0-9a-f]+$/i;function ee(a){return a.startsWith("0x")||a.startsWith("0X")?a.slice(2):a}function io(a){let e=ee(a).toLowerCase();if(e.length>64)throw new Error(`pad32: input too long (${e.length})`);return e.padStart(64,"0")}function lo(a){if(!Fa.test(a)||ee(a).length!==40)throw new Error(`encodeAddress: invalid address ${a}`);return io(a.toLowerCase())}function fe(a,e=256){let t=typeof a=="bigint"?a:BigInt(a);if(t<0n)throw new Error("encodeUint: negative");let n=t.toString(16);if(n.length>e/4)throw new Error(`encodeUint: overflow ${e}`);return io(n)}function tr(a){let e=typeof a=="bigint"?a:BigInt(a);if(e>=0n)return io(e.toString(16));let t=1n<<256n;return io((t+e).toString(16))}function Kr(a){return"0x"+(0,er.keccak_256)(qa(a))}function qa(a){let e=ee(a),t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substring(n*2,n*2+2),16);return t}function ue(a){return"0x"+(0,er.keccak_256)(new TextEncoder().encode(a)).slice(0,8)}function Bn(a,e){let t=a.substring(e,e+64);return t?BigInt("0x"+t):0n}function nr(a,e){let t=a.substring(e,e+64),n=BigInt("0x"+t),r=1n<<256n,o=1n<<23n;return n>=1n<<255n?Number(n-r):(n<o,Number(n))}function or(a,e){return"0x"+a.substring(e+24,e+64).toLowerCase()}var Te={"0x1":"https://ethereum-rpc.publicnode.com","0xa":"https://mainnet.optimism.io","0x38":"https://bsc-dataseed.binance.org","0x89":"https://polygon-bor-rpc.publicnode.com","0x2105":"https://mainnet.base.org","0xa4b1":"https://arb1.arbitrum.io/rpc","0xa86a":"https://avalanche-c-chain-rpc.publicnode.com","0xe708":"https://rpc.linea.build","0x64":"https://gnosis-rpc.publicnode.com","0x3e7":"https://rpc.hyperliquid.xyz/evm","0x1388":"https://rpc.mantle.xyz","0x8f":"https://rpc.monad.xyz"};function Ba(a){return Te[a.toLowerCase()]}var zr={};function rr(a){let e={};if(a)for(let[t,n]of Object.entries(a))typeof n=="string"&&n.trim()&&(e[t.toLowerCase()]=n.trim());zr=e}function $e(a){let e=a.toLowerCase();return zr[e]??Te[e]}async function Ve(a,e,t){for(let r=0;r<=5;r++){let o=await x.post(a,{jsonrpc:"2.0",id:Date.now(),method:e,params:t},{headers:{"Content-Type":"application/json"}});if(o.status===429&&r<5){await new Promise(i=>setTimeout(i,2**r*500));continue}if(!o.ok)throw new Error(`RPC ${e}: ${I(o)}`);let s=o.data;if(s.error)throw new Error(`RPC ${e}: ${s.error.message}`);if(s.result===void 0)throw new Error(`RPC ${e}: empty result`);return s.result}throw new Error(`RPC ${e}: exceeded max retries (429)`)}function $n(a,e,t){return Ve(a,"eth_call",[{to:e,data:t},"latest"])}async function sr(a,e,t){let n=$e(a);if(!n)return null;try{return await $n(n,e,t)}catch{return null}}var $a="0xcA11bde05977b3631167028862bE2a173976CA11",Va={};function Xr(a){return Va[a.toLowerCase()]??$a}var Wa=ue("aggregate3((address,bool,bytes)[])"),Ha=[{type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],Ga=ue("tokenURI(uint256)"),Ya=ue("symbol()"),ja=ue("decimals()"),co=50,Qr=/^0x[0-9a-fA-F]{40}$/;function We(a,e){return a.slice(e*2,e*2+64)}function He(a){return a?Number(BigInt("0x"+a)):0}function Ka(a){try{return Ga+fe(BigInt(a))}catch{return null}}function Jr(a){let e=Zo(Ha,[a]);return Wa+ee(e)}function Zr(a,e){let t=ee(a);if(t.length<64)return[];let n=He(We(t,0)),r=He(We(t,n)),o=Math.min(r,e),s=n+32,i=[];for(let l=0;l<o;l++){let c=s+He(We(t,s+l*32)),u=He(We(t,c))===1,d=c+He(We(t,c+32)),p=He(We(t,d)),m=t.slice((d+32)*2,(d+32)*2+p*2);i.push({success:u,returnData:"0x"+m})}return i}function es(a){let e=ee(a);if(e.length<128)return null;let t=He(We(e,0)),n=He(We(e,t));if(n<=0)return null;let r=e.slice((t+32)*2,(t+32)*2+n*2);if(r.length<n*2)return null;let o=new Uint8Array(n);for(let i=0;i<n;i++)o[i]=parseInt(r.slice(i*2,i*2+2),16);return new TextDecoder().decode(o).replace(/\0+$/,"").trim()||null}function za(a){let e=es(a);if(e)return e;let t=ee(a);if(t.length!==64)return null;let n=[];for(let o=0;o<32;o++){let s=parseInt(t.slice(o*2,o*2+2),16);if(s===0)break;n.push(s)}return new TextDecoder().decode(new Uint8Array(n)).trim()||null}function Xa(a){let e=ee(a);if(e.length<64)return null;let t=He(We(e,0));return Number.isFinite(t)&&t>=0&&t<=36?t:null}async function ts(a,e,t){let n=e.map(()=>({symbol:null,decimals:null})),r=t?.trim()||$e(a);if(!r||e.length===0)return n;let o=Xr(a),s=[];e.forEach((l,c)=>{Qr.test(l)&&(s.push({index:c,field:"symbol",call:{target:l,allowFailure:!0,callData:Ya}}),s.push({index:c,field:"decimals",call:{target:l,allowFailure:!0,callData:ja}}))});let i=[];for(let l=0;l<s.length;l+=co)i.push(s.slice(l,l+co));return await Promise.all(i.map(async l=>{try{let c=await $n(r,o,Jr(l.map(d=>d.call)));Zr(c,l.length).forEach((d,p)=>{if(!d.success)return;let m=l[p];m.field==="symbol"?n[m.index].symbol=za(d.returnData):n[m.index].decimals=Xa(d.returnData)})}catch{}})),n}async function ns(a,e,t){let n=new Array(e.length).fill(null),r=t?.trim()||$e(a);if(!r||e.length===0)return n;let o=Xr(a),s=[];e.forEach((l,c)=>{if(!Qr.test(l.contract))return;let u=Ka(l.tokenId);u!==null&&s.push({index:c,call:{target:l.contract,allowFailure:!0,callData:u}})});let i=[];for(let l=0;l<s.length;l+=co)i.push(s.slice(l,l+co));return await Promise.all(i.map(async l=>{try{let c=await $n(r,o,Jr(l.map(d=>d.call)));Zr(c,l.length).forEach((d,p)=>{d.success&&(n[l[p].index]=es(d.returnData))})}catch{}})),n}function Qa(a){return uo(String(a))??"0"}function uo(a){let e=a.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",n=e[2]??"",r=e[3]??"";if(n===""&&r==="")return null;let o=e[4]?parseInt(e[4],10):0,s=n+r,i=n.length+o,l;return i<=0?l=`0.${"0".repeat(-i)}${s}`:i>=s.length?l=s+"0".repeat(i-s.length):l=`${s.slice(0,i)}.${s.slice(i)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":t+l}function ar(a){let e=uo(a);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function ir(a,e){let t=a<0n,n=(t?-a:a).toString(),r;if(e===0)r=n;else{let o=n.padStart(e+1,"0"),s=o.length-e;r=`${o.slice(0,s)}.${o.slice(s)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${r}`:r}function yt(a){if(typeof a=="number")return Number.isFinite(a)&&a>0?Qa(a):null;if(typeof a!="string")return null;let e=a.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=uo(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function bt(a,e){let t=uo(a);if(t===null||e<0)return a;let n=t.startsWith("-"),[r,o=""]=(n?t.slice(1):t).split(".");if(o.length<=e)return t;let s=e===0?r:`${r}.${o.slice(0,e)}`,i=s.includes(".")?s.replace(/0+$/,"").replace(/\.$/,""):s;return n?`-${i}`:i}function wt(a,e,t,n){let r=ar(a);if(!r||t<=0n||n<0)return a;let o=r.mant*e*10n**BigInt(n)/(t*10n**BigInt(r.frac));return ir(o,n)}function po(a,e){let t=ar(a),n=ar(e);if(!t||!n){let i=Number(a),l=Number(e);return i<l?-1:i>l?1:0}let r=Math.max(t.frac,n.frac),o=t.mant*10n**BigInt(r-t.frac),s=n.mant*10n**BigInt(r-n.frac);return o<s?-1:o>s?1:0}var Ja={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},Za="payment-required",ei="PAYMENT-SIGNATURE",ti="X-PAYMENT",ni="payment-response",oi="x-payment-response",ri=600,si=300,ai={ethereum:1,sepolia:11155111,abstract:2741,"abstract-testnet":11124,base:8453,"base-sepolia":84532,avalanche:43114,"avalanche-fuji":43113,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338,story:1514,educhain:41923,"skale-base-sepolia":324705682,megaeth:4326,monad:143,stable:988,"stable-testnet":2201};function os(a){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(a),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(a,"utf8").toString("base64")}function ss(a){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(a,"base64").toString("utf8")}function ii(){let a=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(a);else for(let t=0;t<32;t++)a[t]=Math.floor(Math.random()*256);return"0x"+Array.from(a,t=>t.toString(16).padStart(2,"0")).join("")}function as(a){let e=String(a);if(e.includes(":")){let[n,r]=e.split(":"),o=parseInt(r,10);if(n!=="eip155"||Number.isNaN(o))throw new Error(`Unsupported x402 network: ${a} (only EVM "eip155:*" is supported)`);return o}let t=ai[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${a}`);return t}function is(a){if(!a.query||Object.keys(a.query).length===0)return a.url;let e=Object.entries(a.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return a.url.includes("?")?`${a.url}&${e}`:`${a.url}?${e}`}function mo(a){let e=a.headers[Za];if(e){let r=rs(li(e));return r&&Array.isArray(r.accepts)?{version:2,payload:r}:null}let t=a.data,n=t&&typeof t=="object"?t:rs(t);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function rs(a){if(typeof a!="string")return null;try{let e=JSON.parse(a);return e&&typeof e=="object"?e:null}catch{return null}}function li(a){try{return ss(a)}catch{return null}}function ci(a){let e=a.amount??a.maxAmountRequired;return typeof a.scheme!="string"||typeof a.network!="string"||e==null||typeof a.asset!="string"||typeof a.payTo!="string"?null:{scheme:a.scheme,network:a.network,amount:String(e),asset:a.asset,payTo:a.payTo,...typeof a.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:a.maxTimeoutSeconds}:{},...a.extra&&typeof a.extra=="object"?{extra:a.extra}:{},...typeof a.resource=="string"?{resource:a.resource}:{},...typeof a.description=="string"?{description:a.description}:{},...typeof a.mimeType=="string"?{mimeType:a.mimeType}:{},...a.outputSchema!=null?{outputSchema:a.outputSchema}:{}}}function ui(a){let e=null;for(let t of a){let n=ci(t);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return as(n.network),n}catch(r){e=r instanceof Error?r.message:String(r)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function lr(a,e,t,n){let r=mo(a);if(!r)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:s}=r,i=ui(s.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=as(i.network),c=Math.floor(Date.now()/1e3),u={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-ri)),validBefore:String(c+(i.maxTimeoutSeconds??si)),nonce:ii()},d={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:Ja,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:is(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:o,requirements:i,authorization:u,typedData:d,chainId:l,...s.resource!=null?{resource:s.resource}:{},...s.extensions!=null?{extensions:s.extensions}:{},...n?{userQuery:n}:{}}}async function di(a,e,t,n){let r=is(e),o=await a.request(e.method??"GET",r,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:lr(o,e,t,n)};if(!o.ok)throw new Error(I(o));return{status:"ok",data:o.data}}async function cr(a,e,t){let{url:n,method:r,body:o,headers:s}=e.request,i=await a.request(r,n,o,{headers:{...s??{},...ur(e,t)}});if(i.ok)return i.data;throw new Error(mi(i)??I(i))}function pi(a){return mo(a)!==null}function ls(a){let e=cs(a);return e?.errorReason?e.errorReason:mo(a)?.payload.error??null}function mi(a){let e=ls(a);return e?`x402 payment rejected: ${e}`:null}var hi={1:"Ethereum",10:"Optimism",137:"Polygon",143:"Monad",988:"Stable",1328:"Sei Testnet",1329:"Sei",1514:"Story",2201:"Stable Testnet",2741:"Abstract",3338:"Peaq",4326:"MegaETH",4689:"IoTeX",8453:"Base",11124:"Abstract Testnet",41923:"EDU Chain",42161:"Arbitrum",43113:"Avalanche Fuji",43114:"Avalanche",80002:"Polygon Amoy",84532:"Base Sepolia",324705682:"SKALE Base Sepolia",11155111:"Sepolia"};function ur(a,e){let{requirements:t,authorization:n}=a,r={signature:e,authorization:n};if(a.x402Version===1){let s={x402Version:1,scheme:t.scheme,network:t.network,payload:r};return{[ti]:os(JSON.stringify(s))}}let o={x402Version:2,...a.resource!=null?{resource:a.resource}:{},accepted:gi(t),payload:r,...a.extensions!=null?{extensions:a.extensions}:{}};return{[ei]:os(JSON.stringify(o))}}function gi(a){let{resource:e,description:t,mimeType:n,outputSchema:r,...o}=a;return o}function cs(a){let e=a.headers[ni]??a.headers[oi];if(!e)return null;try{return JSON.parse(ss(e))}catch{return null}}function fi(a,e){return a==null?e:hi[a]??`Chain ${a}`}async function us(a){let e=a.requirements,n=a.resource?.description||e.description,r=a.chainId??null,o=null,s=null;if(r!=null){let[l]=await ts("0x"+r.toString(16),[e.asset]);o=l?.symbol??null,s=l?.decimals??null}let i=String(e.amount);if(s!==null)try{i=ir(BigInt(e.amount),s)}catch{}return{amount:i,asset:o||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:s,assetAddress:e.asset,network:r!=null?`eip155:${r}`:e.network,networkRaw:e.network,chainId:r,networkLabel:fi(r,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:a.request.url}}function dr(a){return async(e,t)=>{let n=a.getPayer(),r=a.getSigner();if(!n||!r)return null;let o;try{o=lr(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let s;try{s=await r({typedData:o.typedData,display:await us(o)})}catch{s=null}return s?ur(o,s):null}}var Ke=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function ut(a){if(!a||typeof a!="object")return!1;let e=a;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Vn(a){if(a?.aborted)throw new Ke}function pr(a,e){if(!e)return{signal:a.signal,cleanup:()=>{}};if(e.aborted)return a.abort(),{signal:a.signal,cleanup:()=>{}};let t=()=>a.abort();return e.addEventListener("abort",t),{signal:a.signal,cleanup:()=>e.removeEventListener("abort",t)}}var ds={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},yi="https://nft.keyring.app/api/gemini-stable",bi="https://generativelanguage.googleapis.com",wi=new Set([408,429,500,502,503,504]),ps=3e4,ho=a=>new Promise(e=>setTimeout(e,a));function go(a,e,t){if(t!=null&&t>0)return Math.min(t,ps);let n=Math.min(e*2**(a-1),ps);return n/2+Math.random()*(n/2)}function ki(a){if(!a)return null;let e=Number(a);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(a);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var z=class{model;maxTokens;temperature;baseUrl;apiKey;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?bi:yi)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;Vn(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let h of c){let g=h.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${h.role}: [${g}]`)}}let u=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),d={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let p={contents:c,generationConfig:d};r&&(p.systemInstruction=r),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let h=1;h<=s;h++){Vn(l);let g;try{g=await x.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(A){if(ut(A))throw A;if(f=A instanceof Error?A.message:String(A),h>=s)break;await ho(go(h,i));continue}if(!g.ok){let A=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${g.status}: ${A}`,!wi.has(g.status))throw new Error(f);if(h>=s)break;let _=ki(g.headers["retry-after"]??null);await ho(go(h,i,_));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=s)break;await ho(go(h,i));continue}let y=g.data,b=y.candidates?.[0];if(!b)return{text:"",toolCalls:[]};let w="",k=[],T=b.content?.parts;if(!Array.isArray(T)||T.length===0){let A=b.finishReason;if(!(A==="SAFETY"||A==="RECITATION")&&h<s){f=`Gemini returned an empty turn (finishReason=${A??"none"})`,await ho(go(h,i));continue}return{text:"",toolCalls:[]}}for(let A of T)A.text&&(w+=A.text),A.functionCall&&k.push({toolName:A.functionCall.name,args:A.functionCall.args??{},callId:A.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let S=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:S}}throw new Error(f)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===i.role&&!c&&!u?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let l=r[i],c=o[o.length-1];l.role==="function"&&!c?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(r[i+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
2
- `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:ds[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:ds[o.items?.type??"string"]??"STRING"}),n[o.name]=s,o.required&&r.push(o.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:n,required:r}}})}};var kt=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(t=>t.category===e)}async execute(e,t,n){let r=this.tools.get(e);if(!r)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await r.execute(t,n),duration:Date.now()-o}}catch(s){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var Tt=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Ti=new Set(Tt),ze=[...Tt],mr=new Set(ze),ve="0x1",At="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function vi(a){return a.map(e=>vt[e]??e).join(", ")}function fo(a){let e=new Set;if(a)for(let n of a){let r=yo(n);r&&e.add(r)}let t=Tt.filter(n=>!e.has(n));ze=t.length>0?[...t]:[...Tt],mr=new Set(ze),ve=ze.includes("0x1")?"0x1":ze[0],At=vi(ze)}var Ai={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function $(a){let e=yo(a);return e&&mr.has(e)?e:null}function yo(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Ai[e];if(t)return t;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&Ti.has(n)?n:null}function _e(a){return $(a)!==null}function de(){return[...ze]}var Qe=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${At}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Xe=a=>typeof a=="string"&&a.trim()!=="";function re(a,e){if(Xe(a)){let t=$(a);if(t)return t;throw new Qe(a.trim())}if(Xe(e?.chain)){let t=$(e.chain);if(t)return t;throw new Qe(e.chain.trim())}return null}function bo(a,e){return $(a)??$(e?.chain)??void 0}var vt={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function P(a){let e=yo(a);return e&&vt[e]?vt[e]:typeof a=="string"&&a.trim()?a.trim():"the requested chain"}var Si={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function ms(a,e){let t=yo(a),n=t?Si[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Pi={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function hs(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase();return e?Pi[e]??null:null}var xi={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function gs(a){let e=$(a);return e?xi[e]??null:null}function St(a,e){if(!Xe(a))return null;let t=$(a),n=$(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:vt[t]??t,connectedLabel:vt[n]??n}}function fs(a,e){let t=typeof a=="string"?a.trim():"",n=e&&e.length?e.filter(o=>mr.has(o)):[];return(n.length?n:ze).map(o=>{let s=vt[o]??o;return{label:s,prompt:t?`${t} (${s})`:s}})}function Pt(a,e){return{actionButtons:fs(e),_instructions:`The user wants to ${a} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var K=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=fs(e,t)}},Wn=class extends Error{code="no_wallet_connected";constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one."),this.name="NoWalletConnectedError"}};function Y(a,e){if(Xe(a))return a.trim();if(Xe(e?.walletAddress))return e.walletAddress.trim();throw new Wn}function te(a,e,t){if(Xe(a)){let n=$(a);if(n)return n;throw new Qe(a.trim())}if(Xe(e?.chain)){let n=$(e.chain);if(n)return n;throw new Qe(e.chain.trim())}if(Xe(e?.walletAddress))throw new K(typeof e?.query=="string"?e.query:void 0,t);return ve}var v=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s=Ci(o);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-r,...s.actionButtons?{actionButtons:s.actionButtons}:{},...s.ui?{ui:s.ui}:{}}}catch(o){return o instanceof K?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-r,actionButtons:o.buttons}:o instanceof Wn?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-r}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}};function Ci(a){if(!a||typeof a!="object")return{data:a};let e=a,t=e.actionButtons,n=Array.isArray(t)&&t.length>0?t:void 0,r=e.ui,o=r&&typeof r=="object"&&typeof r.component=="string"?r:void 0;if(!n&&!o)return{data:a};let{actionButtons:s,ui:i,...l}=e;return{data:l,...n?{actionButtons:n}:{},...o?{ui:o}:{}}}var _i="https://wallet-api.pantograph.app",Ei="0x0000000000000000000000000000000000000000",ws={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},ks={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function Ri(a){return ws[a.toLowerCase()]||a}function ys(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function hr(a){let e=a,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function gr(a){if(Array.isArray(a))return a;let e=a;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function ie(a){if(a==null)return null;let e=typeof a=="number"?a:parseFloat(String(a));return Number.isFinite(e)?e:null}function bs(a,e){let t=a.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=ie(a.price_change_percentage_24h)??ie(a.priceChange24h)??ie(a.usd_price_24hr_percent_change)??ie(a.price_change_24h)??ie(a.priceChange);return{chainId:e,tokenAddress:a.address??a.token_address??"",name:a.name??null,symbol:a.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:a.logoURI??a.icon_image??a.logo??null,usdPrice:ie(a.price)??ie(a.usd_price),marketCap:ie(a.market_cap)??ie(a.marketCap),totalVolume:{"24h":ie(a.total_volume)??ie(a.volume24h)},pricePercentChange:{"24h":r}}}var le=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??_i).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),r=this.tokensUrl(t,n),o=await x.get(r);if(!o.ok)return;let s=gr(o.data),i=new Map;for(let l of s)l.address&&i.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=i.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),r=await x.get(n);if(!r.ok)return null;let o=gr(r.data),s=e.toLowerCase()===Ei,i=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||s&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||s&&l.token_address==="");return i?hr(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=this.tokensUrl(t,e.join(",")),o=await x.get(r);if(!o.ok)return n;let s=gr(o.data),i=new Set(e.map(l=>l.toLowerCase()));for(let l of s){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&i.has(c)&&(n[c]=hr(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||ve,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=ys({chainId:o,key:t}),i=`${this.baseUrl}/token-list/all?${s}`,l=await x.get(i);if(!l.ok)throw new Error(I(l));let c=l.data,u=c?.result??c?.data??c,d=[];return Array.isArray(u)?d=u:u&&typeof u=="object"&&(d=Object.values(u).flat()),{success:!0,data:d.map(hr)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||ve,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=ks[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],u=l.status==="fulfilled"?o.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>bs(h,t)):[],d=new Set,p=[];for(let h of u){let g=h.tokenAddress?.toLowerCase();!g||d.has(g)||(d.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||d.has(g)||(d.add(g),m.push(h))}let f=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=ie(s.market_cap)??ie(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":ie(s.total_volume)??ie(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=parseInt(e,16),o=ys({chainId:r,duration:n,limit:t}),s=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(s);if(!c.ok)throw new Error(I(c));let u=c.data;if(i=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],i.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return i.map(l=>bs(l,e))}async getTopGainers(e){let t=e?.chain||ve,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,r=e?.duration||"24h";try{let o=await this.fetchTopGainers(t,n,r);return await this.enrichTrendingMarketData(o,t),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var Ni="https://nft.keyring.app",Ui="https://nft.keyring.app",Ii=.01,N=5,V=1e3,Li=25,Di="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Oi="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function j(a){return a||ve}function W(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function H(a){return new Promise(e=>setTimeout(e,a))}function Mi(a){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!a||typeof a!="object")return e;let t=a;if("active_protocols"in t||"total_usd_value"in t){let r=t;return{...e,...r,protocols:r.protocols||[]}}let n=t.result;return!n||typeof n!="object"?e:{active_protocols:n.activeProtocols??0,total_positions:n.totalPositions??0,total_usd_value:n.totalUsd??0,total_unclaimed_usd_value:n.totalUnclaimedUsd??0,protocols:(n.protocols||[]).map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",positions:r.positionCount??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,account_health_factor:r.accountHealthFactor??null}))}}function Fi(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function fr(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ni).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Ui).replace(/\/+$/,""),this.pantograph=new le({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=j(n),l="Unknown error";for(let c=1;c<=N;c++)try{let u={chain:i,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(u.token_addresses=r);let d=[],p=null;do{p&&(u.cursor=p);let f=W(u),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${f}`,g=await x.get(h);if(!g.ok)throw new U(g.status,I(g));let y=g.data,b=y?.data??y;b?.result?.length>0&&d.push(...b.result),p=b?.cursor??null}while(p);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(f=>parseFloat(f.balance||"0")>0),m.result=m.result.map(f=>({...f,token_address:f.token_address.toLowerCase()===Di?Oi:f.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(f=>f.usd_value==null||f.usd_value>=Ii)),{success:!0,data:m}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof U&&u.status===400)break;c<N&&await H(V)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=j(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${W({chain:r,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${W({chain:r,include:"percent_change"})}`)]),u=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){o="Token metadata not found",i<N&&await H(V);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=100,excludeSpam:o=!1,cursor:s,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=j(n),d=[],p=s,m,f;for(let h=0;h<Li;h++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:u,limit:r,excludeSpam:o,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!g.success){if(d.length===0)return g;break}let y=g.data;if(!y)break;let{result:b,cursor:w,page:k,page_size:T}=y;if(Array.isArray(b)&&d.push(...b),m=k,f=T,p=typeof w=="string"&&w.trim()?w:void 0,!p)break}return{success:!0,data:{result:d,cursor:p,page:m,page_size:f}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:n,limit:r,excludeSpam:o,cursor:s,tokenAddresses:i,includePrices:l,format:c}=e,u="Unknown error";for(let d=1;d<=N;d++)try{let p={chain:n,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(p.cursor=s),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let m=W(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await x.get(f);if(!h.ok)throw new U(h.status,I(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;d<N&&await H(V)}return{success:!1,error:u}}async getWalletNftCollections(e){let{address:t,chain:n,limit:r=100,excludeSpam:o=!0,cursor:s}=e;if(!t)return{success:!1,error:"Address is required"};let i=j(n),l="Unknown error";for(let c=1;c<=N;c++)try{let u={chain:i,limit:r,exclude_spam:o};s&&(u.cursor=s);let d=W(u),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${d}`,m=await x.get(p);if(!m.ok)throw new U(m.status,I(m));let f=m.data;return{success:!0,data:f?.data??f}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof U&&u.status===400)break;c<N&&await H(V)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!q(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=j(r),u="Unknown error";for(let d=1;d<=N;d++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:i};l&&(p.include=l);let m=W(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await x.get(f);if(!h.ok)throw new U(h.status,I(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;d<N&&await H(V)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:i,toBlock:l,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=j(n),f=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let g=1;g<=N;g++)try{let y={chain:m,limit:f,order:u};o&&(y.from_date=o),s&&(y.to_date=s),i!=null&&(y.from_block=i),l!=null&&(y.to_block=l),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=W(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,k=await x.get(w);if(!k.ok)throw new U(k.status,I(k));let T=k.data;return{success:!0,data:T?.data??T}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;g<N&&await H(V)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=j(n),m=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let h=1;h<=N;h++)try{let g={chain:p,limit:m,order:d};s&&(g.from_date=s),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),u&&(g.cursor=u),r?.length&&(g.contract_addresses=r);let y=W(g),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await x.get(b);if(!w.ok)throw new U(w.status,I(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(g){if(f=g instanceof Error?g.message:"Unknown error",g instanceof U&&g.status===400)break;h<N&&await H(V)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=j(n),h=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=N;y++)try{let b={chain:f,limit:h,order:d,format:m};s&&(b.from_date=s),i&&(b.to_date=i),l!=null&&(b.from_block=l),c!=null&&(b.to_block=c),u&&(b.cursor=u),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=W(b),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,T=await x.get(k);if(!T.ok)throw new U(T.status,I(T));let S=T.data;return{success:!0,data:S?.data??S}}catch(b){if(g=b instanceof Error?b.message:"Unknown error",b instanceof U&&b.status===400)break;y<N&&await H(V)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!q(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=j(n),s="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:o};r&&(l.days=r);let c=W(l),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await x.get(u);if(!d.ok)throw new U(d.status,I(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:s}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=W(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await x.get(d);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await H(V)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let u=W(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await x.get(d);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await H(V)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let u=c.data,d=u?.data??u;return{success:!0,data:Mi(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let u=c.data,d=u?.data??u;return{success:!0,data:Fi(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!q(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=j(r),s="Unknown error";for(let i=1;i<=N;i++)try{let l=W({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,u=await x.get(c);if(!u.ok)throw new U(u.status,I(u));let m=u.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(g=>({token_type:g.tokenType,address:g.address,contract_address:g.address,name:g.name??"",symbol:g.symbol??"",decimals:g.decimals??18,logo:g.logo,balance:g.balance??"0",balance_formatted:g.balanceFormatted??"0",usd_price:g.usdPrice,usd_value:g.usdValue}))}))}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:s}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!q(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!q(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=N;o++)try{let s={};t&&(s.chain=j(t)),n!=null&&(s.limit=n);let i=W(s),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let u=c.data,d=u?.data??u;return{success:!0,data:fr(d)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof U&&s.status===400)break;o<N&&await H(V)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=W(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new U(d.status,I(d));let p=d.data,m=p?.data??p;return{success:!0,data:fr(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=W(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new U(d.status,I(d));let p=d.data,m=p?.data??p;return{success:!0,data:fr(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var xt=class extends v{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new z(e?.llm??{})}async run(e,t){let n=e.keyword||"",r=e.prompt||"",o=t?.walletAddress||void 0;if(!n)return{error:"Missing required parameter: keyword"};let s;try{s=te(e.chain,t)}catch(i){if(i instanceof Qe)return await this.researchTokenChainAgnostic(n,r,o);throw i}return await this.searchToken(n,s,r,o)}async researchTokenChainAgnostic(e,t,n){let r=[n?`User's connected wallet address: ${n}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
1
+ "use strict";var ya=Object.create;var ao=Object.defineProperty;var ba=Object.getOwnPropertyDescriptor;var wa=Object.getOwnPropertyNames;var ka=Object.getPrototypeOf,Ta=Object.prototype.hasOwnProperty;var va=(a,e)=>{for(var t in e)ao(a,t,{get:e[t],enumerable:!0})},Dr=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wa(e))!Ta.call(a,r)&&r!==t&&ao(a,r,{get:()=>e[r],enumerable:!(n=ba(e,r))||n.enumerable});return a};var Aa=(a,e,t)=>(t=a!=null?ya(ka(a)):{},Dr(e||!a||!a.__esModule?ao(t,"default",{value:a,enumerable:!0}):t,a)),Sa=a=>Dr(ao({},"__esModule",{value:!0}),a);var ou={};va(ou,{AI_AGENT_TOOL_NAMES:()=>qo,AbortError:()=>Ke,AgentCore:()=>Yo,ApproveTokenTool:()=>Pn,BaseNftAiTool:()=>Oe,BaseSwapService:()=>Ze,BaseTool:()=>v,BaseWalletActionTool:()=>Pe,BuyTokenTool:()=>xn,ChatHistory:()=>En,DEFAULT_CHAIN:()=>ve,DEFAULT_PROVIDER:()=>Yn,DEFAULT_RPC_BY_CHAIN:()=>Te,DebridgeAdapter:()=>en,EstimatePoolYieldTool:()=>dn,GeminiProvider:()=>z,GeminiSearchAiTool:()=>Xt,HEX_TO_PANTOGRAPH:()=>ws,KnowledgeBase:()=>Nn,ManageLiquidityRedirectTool:()=>mn,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>Fo,NFC_AMAZON_DEFAULT_DOMAIN:()=>wr,NFC_AMAZON_DOMAINS:()=>br,NFTContractInfoTool:()=>Gt,NFTMetadataTool:()=>Yt,NFT_AGENT_TOOL_NAMES:()=>Mo,NfcBuyTool:()=>zt,NfcInfoTool:()=>Kt,NoFormTool:()=>zn,OpenAddLiquidityFormTool:()=>cn,POOL_AGENT_TOOL_NAMES:()=>Bo,PantographService:()=>le,PoolByAddressTool:()=>ln,PoolDetailTool:()=>sn,PoolFallbackAiTool:()=>Qt,PoolPriceRangesTool:()=>pn,PoolSearchTool:()=>an,PoolService:()=>ce,PreviewAddLiquidityTool:()=>un,RelayAdapter:()=>tn,Router:()=>Un,SUPPORTED_CHAINS:()=>Tt,SUPPORTED_CHAINS_LABEL:()=>At,SWAP_PROVIDER_CONFIG:()=>Co,SendNativeTool:()=>An,SendNftTool:()=>_n,SendTokenTool:()=>Sn,Subagent:()=>X,SubgraphAddPoolTool:()=>kn,SubgraphCoinPoolPairsTool:()=>wn,SubgraphPoolByAddressTool:()=>fn,SubgraphPoolByPositionIdTool:()=>yn,SubgraphPoolSearchTool:()=>hn,SubgraphPositionDetailTool:()=>bn,SubgraphTrendingPoolsTool:()=>gn,Summarizer:()=>Rn,SwapServiceFactory:()=>dt,SwapTokenTool:()=>Cn,Synthesizer:()=>In,TOKEN_AGENT_TOOL_NAMES:()=>Oo,TRANSFER_TOPIC:()=>Xs,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>ks,TokenAnalyticsTool:()=>_t,TokenHoldersTool:()=>Ct,TokenInfoTool:()=>xt,TokenScoreTool:()=>Et,ToolRegistry:()=>kt,TopGainersTool:()=>Nt,TopPoolsTool:()=>rn,TransactionByHashTool:()=>Vt,TrendingTokensTool:()=>Rt,UNISWAP_CHAIN_SLUG:()=>Kn,UpstashKnowledgeBase:()=>nt,WALLET_ACTION_AGENT_TOOL_NAMES:()=>$o,WALLET_AGENT_TOOL_NAMES:()=>Do,WalletApprovalsTool:()=>Ft,WalletDefiPositionsTool:()=>Bt,WalletDefiProtocolPositionsTool:()=>$t,WalletDefiSummaryTool:()=>qt,WalletHistoryTool:()=>It,WalletNFTsTool:()=>Ht,WalletNftTransfersTool:()=>Dt,WalletPnlSummaryTool:()=>Ot,WalletPnlTool:()=>Mt,WalletTokenBalancesTool:()=>Ut,WalletTokenTransfersTool:()=>Lt,WebsiteTrustKeyringAgent:()=>jo,ZERO_ADDRESS:()=>B,amazonDomainForLanguage:()=>kr,apiClient:()=>x,buildChallenge:()=>lr,buildRangePresets:()=>Sr,buildUniswapPoolUrl:()=>ke,clampTick:()=>De,completeX402:()=>cr,configureSupportedChains:()=>fo,createAiAgent:()=>to,createDefaultSubagents:()=>Vo,createNfcAgent:()=>eo,createNftAgent:()=>Zn,createPoolAgent:()=>no,createTokenAgent:()=>Jn,createWalletActionAgent:()=>oo,createWalletAgent:()=>Qn,createX402SignatureProvider:()=>dr,displayFromChallenge:()=>us,encodeSignedHeader:()=>ur,ethCallAt:()=>$n,ethCallByChain:()=>sr,fetchTopMarketplaces:()=>Tr,getAffiliateFee:()=>Zt,getChainMeta:()=>oe,getDefaultRpcUrl:()=>Ba,getGatewayAddress:()=>Eo,getGatewayChains:()=>Ro,getNativeTokenInfo:()=>nn,getPositionManagerAddress:()=>No,getProviderByChain:()=>xo,ingestKnowledgeBase:()=>fa,isAbortError:()=>ut,isPaymentRequired:()=>pi,nfcAmazonSearchUrl:()=>To,normaliseCountry:()=>vo,normalizePriceRangeToPool:()=>ft,priceToTick:()=>ct,readPaymentError:()=>ls,readPaymentRequired:()=>mo,readReceipt:()=>cs,registerMaybeNoForm:()=>Lo,requestWithX402:()=>di,resolveNfcShopLinks:()=>jt,resolveRpcUrl:()=>$e,roundTickToSpacing:()=>Le,rpcCall:()=>Ve,setRpcOverrides:()=>rr,swapServiceFactory:()=>Me,tickToPrice:()=>Ce,toPantographChain:()=>Ri});module.exports=Sa(ou);var Mr=Aa(require("axios"));var Or="0.2.47";var xa=`keyring-agent-core/${Or} (Keyring Chatbot Agent; +https://keyring.app)`,zo=null;function Fr(a){zo=a}var Ca=["payment-signature","x-payment"];function _a(a){return a?Object.keys(a).some(e=>Ca.includes(e.toLowerCase())):!1}var qr;function Mn(a){qr=a}var Ea=3e4,Ra=typeof process<"u"&&process.versions?.node!=null,Xo=class{instance;constructor(e={}){this.instance=Mr.default.create({baseURL:e.baseURL,timeout:e.timeout??Ea,validateStatus:()=>!0,headers:{Accept:"application/json",...Ra?{"User-Agent":e.userAgent??xa}:{},...e.headers}})}async request(e,t,n,r={}){let o=r.signal??qr,s=await this.instance.request({...r,signal:o,method:e,url:t,data:n}),i={};for(let[c,d]of Object.entries(s.headers??{}))d!=null&&(i[c.toLowerCase()]=String(d));let l={ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,data:s.data,headers:i};if(l.status===402&&zo&&!_a(r.headers)){let c=await zo(l,{url:t,method:String(e),body:n,headers:r.headers});if(c)return this.request(e,t,n,{...r,headers:{...r.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Xo;function I(a){let{data:e,status:t,statusText:n}=a,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=l=>l&&typeof l=="object"?l.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}var Br=require("js-sha3");function q(a){return typeof a=="string"&&/^0x[0-9a-fA-F]{40}$/.test(a)}function Na(a){return new Uint8Array(Br.keccak256.arrayBuffer(a))}function Fn(a){let e=a.startsWith("0x")?a.slice(2):a,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function $r(a){return"0x"+Array.from(a).map(e=>e.toString(16).padStart(2,"0")).join("")}function Vr(a){return new TextEncoder().encode(a)}function lt(...a){let e=a.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;return t}function Ua(a,e=32){let t=new Uint8Array(e);return t.set(a,e-a.length),t}function Ia(a,e=32){let t=new Uint8Array(e);return t.set(a),t}function Wr(a){let e=((a%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Fn(e)}function qn(a){return Wr(BigInt(a))}function Hr(a){return a==="uint"?"uint256":a==="int"?"int256":a.match(/^uint$/)?"uint256":a.match(/^int$/)?"int256":a.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function Gr(a){let e=Hr(a.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(a.components??[]).map(Gr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function La(a){let e=(a.inputs??[]).map(Gr).join(",");return`${a.name??""}(${e})`}function Qo(a,e){let t=Ma(a.type);if(t){let[r,o]=t;return Da({...a,type:o},e,r)}if(a.type==="tuple")return Oa(a,e);if(a.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:Ua(Fn(o.toLowerCase()))}}if(a.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Hr(a.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:qn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:Wr(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Fn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ia(o)}}if(n==="bytes"){let r=typeof e=="string"?Fn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:lt(qn(r.length),s)}}if(n==="string"){let r=typeof e=="string"?Vr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:lt(qn(r.length),s)}}throw new Error(`Unsupported ABI type: ${a.type}`)}function Jo(a){let e=0;for(let{dynamic:o,encoded:s}of a)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of a)o?(t.push(qn(e+r)),n.push(s),r+=s.length):t.push(s);return lt(...t,...n)}function Da(a,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let i=Qo(a,s);i.dynamic&&(r=!0),o.push(i)}if(n||r){let s=Jo(o);if(n){let i=qn(o.length);return{dynamic:!0,encoded:o.length>0?lt(i,s):i}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:lt(...o.map(s=>s.encoded))}}function Oa(a,e){let t=a.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],i=Array.isArray(e)?e[o]:e[s.name??""],l=Qo(s,i);l.dynamic&&(n=!0),r.push(l)}return{dynamic:n,encoded:n?Jo(r):lt(...r.map(o=>o.encoded))}}function Ma(a){let e=a.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Zo(a,e){if(a.length!==e.length)throw new Error(`Expected ${a.length} values, got ${e.length}`);if(a.length===0)return"0x";let t=a.map((r,o)=>Qo(r,e[o])),n=Jo(t);return $r(n)}function ht({abi:a,functionName:e,args:t=[]}){let n=a.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=La(n),o=Na(Vr(r)).slice(0,4),s=n.inputs??[],i=s.length===0||t.length===0?new Uint8Array(0):Fn(Zo(s,t).slice(2));return $r(lt(o,i))}var er=require("js-sha3"),Yr=2n**96n;function Z(a,e=8){return!Number.isFinite(a)||a===0?a:Number(a.toPrecision(e))}function jr(a,e,t){let n=a*a,r=Yr*Yr,o=n*10n**18n/r;return Number(o)/1e18*Math.pow(10,e-t)}function Ce(a,e,t){return Math.pow(1.0001,a)*Math.pow(10,e-t)}function ct(a,e,t){if(a<=0)throw new Error("priceToTick: price must be > 0");let n=a/Math.pow(10,e-t),r=Math.log(n)/Math.log(1.0001),o=Math.round(r);return Math.abs(r-o)<.001?o:Math.floor(r)}function ft(a,e,t){let n={minPrice:a,maxPrice:e,inverted:!1};if(!Number.isFinite(a)||!Number.isFinite(e)||!Number.isFinite(t)||a<=0||e<=0||t<=0||a>=e)return n;let r={minPrice:1/e,maxPrice:1/a,inverted:!0},o=c=>t>=c.minPrice&&t<=c.maxPrice,s=o(n),i=o(r);if(s&&!i)return n;if(i&&!s)return r;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(r)<l(n)?r:n}function Le(a,e,t="nearest"){let n=Math.abs(a-Math.round(a))<1e-6?Math.round(a):a,r=(n%e+e)%e;if(r===0)return n;let o=n-r,s=o+e;return t==="down"?o:t==="up"?s:n-o<s-n?o:s}var je=-887272,gt=887272;function De(a){return a<je?je:a>gt?gt:a}var Fa=/^0x[0-9a-f]+$/i;function ee(a){return a.startsWith("0x")||a.startsWith("0X")?a.slice(2):a}function io(a){let e=ee(a).toLowerCase();if(e.length>64)throw new Error(`pad32: input too long (${e.length})`);return e.padStart(64,"0")}function lo(a){if(!Fa.test(a)||ee(a).length!==40)throw new Error(`encodeAddress: invalid address ${a}`);return io(a.toLowerCase())}function fe(a,e=256){let t=typeof a=="bigint"?a:BigInt(a);if(t<0n)throw new Error("encodeUint: negative");let n=t.toString(16);if(n.length>e/4)throw new Error(`encodeUint: overflow ${e}`);return io(n)}function tr(a){let e=typeof a=="bigint"?a:BigInt(a);if(e>=0n)return io(e.toString(16));let t=1n<<256n;return io((t+e).toString(16))}function Kr(a){return"0x"+(0,er.keccak_256)(qa(a))}function qa(a){let e=ee(a),t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substring(n*2,n*2+2),16);return t}function ue(a){return"0x"+(0,er.keccak_256)(new TextEncoder().encode(a)).slice(0,8)}function Bn(a,e){let t=a.substring(e,e+64);return t?BigInt("0x"+t):0n}function nr(a,e){let t=a.substring(e,e+64),n=BigInt("0x"+t),r=1n<<256n,o=1n<<23n;return n>=1n<<255n?Number(n-r):(n<o,Number(n))}function or(a,e){return"0x"+a.substring(e+24,e+64).toLowerCase()}var Te={"0x1":"https://ethereum-rpc.publicnode.com","0xa":"https://mainnet.optimism.io","0x38":"https://bsc-dataseed.binance.org","0x89":"https://polygon-bor-rpc.publicnode.com","0x2105":"https://mainnet.base.org","0xa4b1":"https://arb1.arbitrum.io/rpc","0xa86a":"https://avalanche-c-chain-rpc.publicnode.com","0xe708":"https://rpc.linea.build","0x64":"https://gnosis-rpc.publicnode.com","0x3e7":"https://rpc.hyperliquid.xyz/evm","0x1388":"https://rpc.mantle.xyz","0x8f":"https://rpc.monad.xyz"};function Ba(a){return Te[a.toLowerCase()]}var zr={};function rr(a){let e={};if(a)for(let[t,n]of Object.entries(a))typeof n=="string"&&n.trim()&&(e[t.toLowerCase()]=n.trim());zr=e}function $e(a){let e=a.toLowerCase();return zr[e]??Te[e]}async function Ve(a,e,t){for(let r=0;r<=5;r++){let o=await x.post(a,{jsonrpc:"2.0",id:Date.now(),method:e,params:t},{headers:{"Content-Type":"application/json"}});if(o.status===429&&r<5){await new Promise(i=>setTimeout(i,2**r*500));continue}if(!o.ok)throw new Error(`RPC ${e}: ${I(o)}`);let s=o.data;if(s.error)throw new Error(`RPC ${e}: ${s.error.message}`);if(s.result===void 0)throw new Error(`RPC ${e}: empty result`);return s.result}throw new Error(`RPC ${e}: exceeded max retries (429)`)}function $n(a,e,t){return Ve(a,"eth_call",[{to:e,data:t},"latest"])}async function sr(a,e,t){let n=$e(a);if(!n)return null;try{return await $n(n,e,t)}catch{return null}}var $a="0xcA11bde05977b3631167028862bE2a173976CA11",Va={};function Xr(a){return Va[a.toLowerCase()]??$a}var Wa=ue("aggregate3((address,bool,bytes)[])"),Ha=[{type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],Ga=ue("tokenURI(uint256)"),Ya=ue("symbol()"),ja=ue("decimals()"),co=50,Qr=/^0x[0-9a-fA-F]{40}$/;function We(a,e){return a.slice(e*2,e*2+64)}function He(a){return a?Number(BigInt("0x"+a)):0}function Ka(a){try{return Ga+fe(BigInt(a))}catch{return null}}function Jr(a){let e=Zo(Ha,[a]);return Wa+ee(e)}function Zr(a,e){let t=ee(a);if(t.length<64)return[];let n=He(We(t,0)),r=He(We(t,n)),o=Math.min(r,e),s=n+32,i=[];for(let l=0;l<o;l++){let c=s+He(We(t,s+l*32)),d=He(We(t,c))===1,u=c+He(We(t,c+32)),p=He(We(t,u)),m=t.slice((u+32)*2,(u+32)*2+p*2);i.push({success:d,returnData:"0x"+m})}return i}function es(a){let e=ee(a);if(e.length<128)return null;let t=He(We(e,0)),n=He(We(e,t));if(n<=0)return null;let r=e.slice((t+32)*2,(t+32)*2+n*2);if(r.length<n*2)return null;let o=new Uint8Array(n);for(let i=0;i<n;i++)o[i]=parseInt(r.slice(i*2,i*2+2),16);return new TextDecoder().decode(o).replace(/\0+$/,"").trim()||null}function za(a){let e=es(a);if(e)return e;let t=ee(a);if(t.length!==64)return null;let n=[];for(let o=0;o<32;o++){let s=parseInt(t.slice(o*2,o*2+2),16);if(s===0)break;n.push(s)}return new TextDecoder().decode(new Uint8Array(n)).trim()||null}function Xa(a){let e=ee(a);if(e.length<64)return null;let t=He(We(e,0));return Number.isFinite(t)&&t>=0&&t<=36?t:null}async function ts(a,e,t){let n=e.map(()=>({symbol:null,decimals:null})),r=t?.trim()||$e(a);if(!r||e.length===0)return n;let o=Xr(a),s=[];e.forEach((l,c)=>{Qr.test(l)&&(s.push({index:c,field:"symbol",call:{target:l,allowFailure:!0,callData:Ya}}),s.push({index:c,field:"decimals",call:{target:l,allowFailure:!0,callData:ja}}))});let i=[];for(let l=0;l<s.length;l+=co)i.push(s.slice(l,l+co));return await Promise.all(i.map(async l=>{try{let c=await $n(r,o,Jr(l.map(u=>u.call)));Zr(c,l.length).forEach((u,p)=>{if(!u.success)return;let m=l[p];m.field==="symbol"?n[m.index].symbol=za(u.returnData):n[m.index].decimals=Xa(u.returnData)})}catch{}})),n}async function ns(a,e,t){let n=new Array(e.length).fill(null),r=t?.trim()||$e(a);if(!r||e.length===0)return n;let o=Xr(a),s=[];e.forEach((l,c)=>{if(!Qr.test(l.contract))return;let d=Ka(l.tokenId);d!==null&&s.push({index:c,call:{target:l.contract,allowFailure:!0,callData:d}})});let i=[];for(let l=0;l<s.length;l+=co)i.push(s.slice(l,l+co));return await Promise.all(i.map(async l=>{try{let c=await $n(r,o,Jr(l.map(u=>u.call)));Zr(c,l.length).forEach((u,p)=>{u.success&&(n[l[p].index]=es(u.returnData))})}catch{}})),n}function Qa(a){return uo(String(a))??"0"}function uo(a){let e=a.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",n=e[2]??"",r=e[3]??"";if(n===""&&r==="")return null;let o=e[4]?parseInt(e[4],10):0,s=n+r,i=n.length+o,l;return i<=0?l=`0.${"0".repeat(-i)}${s}`:i>=s.length?l=s+"0".repeat(i-s.length):l=`${s.slice(0,i)}.${s.slice(i)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":t+l}function ar(a){let e=uo(a);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function ir(a,e){let t=a<0n,n=(t?-a:a).toString(),r;if(e===0)r=n;else{let o=n.padStart(e+1,"0"),s=o.length-e;r=`${o.slice(0,s)}.${o.slice(s)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${r}`:r}function yt(a){if(typeof a=="number")return Number.isFinite(a)&&a>0?Qa(a):null;if(typeof a!="string")return null;let e=a.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=uo(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function bt(a,e){let t=uo(a);if(t===null||e<0)return a;let n=t.startsWith("-"),[r,o=""]=(n?t.slice(1):t).split(".");if(o.length<=e)return t;let s=e===0?r:`${r}.${o.slice(0,e)}`,i=s.includes(".")?s.replace(/0+$/,"").replace(/\.$/,""):s;return n?`-${i}`:i}function wt(a,e,t,n){let r=ar(a);if(!r||t<=0n||n<0)return a;let o=r.mant*e*10n**BigInt(n)/(t*10n**BigInt(r.frac));return ir(o,n)}function po(a,e){let t=ar(a),n=ar(e);if(!t||!n){let i=Number(a),l=Number(e);return i<l?-1:i>l?1:0}let r=Math.max(t.frac,n.frac),o=t.mant*10n**BigInt(r-t.frac),s=n.mant*10n**BigInt(r-n.frac);return o<s?-1:o>s?1:0}var Ja={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},Za="payment-required",ei="PAYMENT-SIGNATURE",ti="X-PAYMENT",ni="payment-response",oi="x-payment-response",ri=600,si=300,ai={ethereum:1,sepolia:11155111,abstract:2741,"abstract-testnet":11124,base:8453,"base-sepolia":84532,avalanche:43114,"avalanche-fuji":43113,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338,story:1514,educhain:41923,"skale-base-sepolia":324705682,megaeth:4326,monad:143,stable:988,"stable-testnet":2201};function os(a){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(a),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(a,"utf8").toString("base64")}function ss(a){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(a,"base64").toString("utf8")}function ii(){let a=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(a);else for(let t=0;t<32;t++)a[t]=Math.floor(Math.random()*256);return"0x"+Array.from(a,t=>t.toString(16).padStart(2,"0")).join("")}function as(a){let e=String(a);if(e.includes(":")){let[n,r]=e.split(":"),o=parseInt(r,10);if(n!=="eip155"||Number.isNaN(o))throw new Error(`Unsupported x402 network: ${a} (only EVM "eip155:*" is supported)`);return o}let t=ai[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${a}`);return t}function is(a){if(!a.query||Object.keys(a.query).length===0)return a.url;let e=Object.entries(a.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return a.url.includes("?")?`${a.url}&${e}`:`${a.url}?${e}`}function mo(a){let e=a.headers[Za];if(e){let r=rs(li(e));return r&&Array.isArray(r.accepts)?{version:2,payload:r}:null}let t=a.data,n=t&&typeof t=="object"?t:rs(t);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function rs(a){if(typeof a!="string")return null;try{let e=JSON.parse(a);return e&&typeof e=="object"?e:null}catch{return null}}function li(a){try{return ss(a)}catch{return null}}function ci(a){let e=a.amount??a.maxAmountRequired;return typeof a.scheme!="string"||typeof a.network!="string"||e==null||typeof a.asset!="string"||typeof a.payTo!="string"?null:{scheme:a.scheme,network:a.network,amount:String(e),asset:a.asset,payTo:a.payTo,...typeof a.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:a.maxTimeoutSeconds}:{},...a.extra&&typeof a.extra=="object"?{extra:a.extra}:{},...typeof a.resource=="string"?{resource:a.resource}:{},...typeof a.description=="string"?{description:a.description}:{},...typeof a.mimeType=="string"?{mimeType:a.mimeType}:{},...a.outputSchema!=null?{outputSchema:a.outputSchema}:{}}}function ui(a){let e=null;for(let t of a){let n=ci(t);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return as(n.network),n}catch(r){e=r instanceof Error?r.message:String(r)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function lr(a,e,t,n){let r=mo(a);if(!r)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:s}=r,i=ui(s.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=as(i.network),c=Math.floor(Date.now()/1e3),d={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-ri)),validBefore:String(c+(i.maxTimeoutSeconds??si)),nonce:ii()},u={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:Ja,primaryType:"TransferWithAuthorization",message:{...d}};return{request:{url:is(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:o,requirements:i,authorization:d,typedData:u,chainId:l,...s.resource!=null?{resource:s.resource}:{},...s.extensions!=null?{extensions:s.extensions}:{},...n?{userQuery:n}:{}}}async function di(a,e,t,n){let r=is(e),o=await a.request(e.method??"GET",r,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:lr(o,e,t,n)};if(!o.ok)throw new Error(I(o));return{status:"ok",data:o.data}}async function cr(a,e,t){let{url:n,method:r,body:o,headers:s}=e.request,i=await a.request(r,n,o,{headers:{...s??{},...ur(e,t)}});if(i.ok)return i.data;throw new Error(mi(i)??I(i))}function pi(a){return mo(a)!==null}function ls(a){let e=cs(a);return e?.errorReason?e.errorReason:mo(a)?.payload.error??null}function mi(a){let e=ls(a);return e?`x402 payment rejected: ${e}`:null}var hi={1:"Ethereum",10:"Optimism",137:"Polygon",143:"Monad",988:"Stable",1328:"Sei Testnet",1329:"Sei",1514:"Story",2201:"Stable Testnet",2741:"Abstract",3338:"Peaq",4326:"MegaETH",4689:"IoTeX",8453:"Base",11124:"Abstract Testnet",41923:"EDU Chain",42161:"Arbitrum",43113:"Avalanche Fuji",43114:"Avalanche",80002:"Polygon Amoy",84532:"Base Sepolia",324705682:"SKALE Base Sepolia",11155111:"Sepolia"};function ur(a,e){let{requirements:t,authorization:n}=a,r={signature:e,authorization:n};if(a.x402Version===1){let s={x402Version:1,scheme:t.scheme,network:t.network,payload:r};return{[ti]:os(JSON.stringify(s))}}let o={x402Version:2,...a.resource!=null?{resource:a.resource}:{},accepted:gi(t),payload:r,...a.extensions!=null?{extensions:a.extensions}:{}};return{[ei]:os(JSON.stringify(o))}}function gi(a){let{resource:e,description:t,mimeType:n,outputSchema:r,...o}=a;return o}function cs(a){let e=a.headers[ni]??a.headers[oi];if(!e)return null;try{return JSON.parse(ss(e))}catch{return null}}function fi(a,e){return a==null?e:hi[a]??`Chain ${a}`}async function us(a){let e=a.requirements,n=a.resource?.description||e.description,r=a.chainId??null,o=null,s=null;if(r!=null){let[l]=await ts("0x"+r.toString(16),[e.asset]);o=l?.symbol??null,s=l?.decimals??null}let i=String(e.amount);if(s!==null)try{i=ir(BigInt(e.amount),s)}catch{}return{amount:i,asset:o||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:s,assetAddress:e.asset,network:r!=null?`eip155:${r}`:e.network,networkRaw:e.network,chainId:r,networkLabel:fi(r,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:a.request.url}}function dr(a){return async(e,t)=>{let n=a.getPayer(),r=a.getSigner();if(!n||!r)return null;let o;try{o=lr(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let s;try{s=await r({typedData:o.typedData,display:await us(o)})}catch{s=null}return s?ur(o,s):null}}var Ke=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function ut(a){if(!a||typeof a!="object")return!1;let e=a;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Vn(a){if(a?.aborted)throw new Ke}function pr(a,e){if(!e)return{signal:a.signal,cleanup:()=>{}};if(e.aborted)return a.abort(),{signal:a.signal,cleanup:()=>{}};let t=()=>a.abort();return e.addEventListener("abort",t),{signal:a.signal,cleanup:()=>e.removeEventListener("abort",t)}}var ds={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},yi="https://nft.keyring.app/api/gemini-stable",bi="https://generativelanguage.googleapis.com",wi=new Set([408,429,500,502,503,504]),ps=3e4,ho=a=>new Promise(e=>setTimeout(e,a));function go(a,e,t){if(t!=null&&t>0)return Math.min(t,ps);let n=Math.min(e*2**(a-1),ps);return n/2+Math.random()*(n/2)}function ki(a){if(!a)return null;let e=Number(a);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(a);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var z=class{model;maxTokens;temperature;baseUrl;apiKey;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?bi:yi)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;Vn(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let h of c){let g=h.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${h.role}: [${g}]`)}}let d=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),u={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};d!=null&&(u.thinkingConfig={thinkingBudget:d});let p={contents:c,generationConfig:u};r&&(p.systemInstruction=r),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let h=1;h<=s;h++){Vn(l);let g;try{g=await x.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(A){if(ut(A))throw A;if(f=A instanceof Error?A.message:String(A),h>=s)break;await ho(go(h,i));continue}if(!g.ok){let A=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${g.status}: ${A}`,!wi.has(g.status))throw new Error(f);if(h>=s)break;let _=ki(g.headers["retry-after"]??null);await ho(go(h,i,_));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=s)break;await ho(go(h,i));continue}let y=g.data,b=y.candidates?.[0];if(!b)return{text:"",toolCalls:[]};let w="",k=[],T=b.content?.parts;if(!Array.isArray(T)||T.length===0){let A=b.finishReason;if(!(A==="SAFETY"||A==="RECITATION")&&h<s){f=`Gemini returned an empty turn (finishReason=${A??"none"})`,await ho(go(h,i));continue}return{text:"",toolCalls:[]}}for(let A of T)A.text&&(w+=A.text),A.functionCall&&k.push({toolName:A.functionCall.name,args:A.functionCall.args??{},callId:A.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let S=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:S}}throw new Error(f)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(u=>u.functionCall),d=l?.parts.some(u=>u.functionCall);l&&l.role===i.role&&!c&&!d?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let l=r[i],c=o[o.length-1];l.role==="function"&&!c?.parts.some(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.functionCall)&&!(r[i+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
2
+ `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:ds[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:ds[o.items?.type??"string"]??"STRING"}),n[o.name]=s,o.required&&r.push(o.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:n,required:r}}})}};var kt=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(t=>t.category===e)}async execute(e,t,n){let r=this.tools.get(e);if(!r)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await r.execute(t,n),duration:Date.now()-o}}catch(s){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var Tt=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Ti=new Set(Tt),ze=[...Tt],mr=new Set(ze),ve="0x1",At="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function vi(a){return a.map(e=>vt[e]??e).join(", ")}function fo(a){let e=new Set;if(a)for(let n of a){let r=yo(n);r&&e.add(r)}let t=Tt.filter(n=>!e.has(n));ze=t.length>0?[...t]:[...Tt],mr=new Set(ze),ve=ze.includes("0x1")?"0x1":ze[0],At=vi(ze)}var Ai={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function $(a){let e=yo(a);return e&&mr.has(e)?e:null}function yo(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Ai[e];if(t)return t;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&Ti.has(n)?n:null}function _e(a){return $(a)!==null}function de(){return[...ze]}var Qe=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${At}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Xe=a=>typeof a=="string"&&a.trim()!=="";function re(a,e){if(Xe(a)){let t=$(a);if(t)return t;throw new Qe(a.trim())}if(Xe(e?.chain)){let t=$(e.chain);if(t)return t;throw new Qe(e.chain.trim())}return null}function bo(a,e){return $(a)??$(e?.chain)??void 0}var vt={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function P(a){let e=yo(a);return e&&vt[e]?vt[e]:typeof a=="string"&&a.trim()?a.trim():"the requested chain"}var Si={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function ms(a,e){let t=yo(a),n=t?Si[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Pi={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function hs(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase();return e?Pi[e]??null:null}var xi={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function gs(a){let e=$(a);return e?xi[e]??null:null}function St(a,e){if(!Xe(a))return null;let t=$(a),n=$(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:vt[t]??t,connectedLabel:vt[n]??n}}function fs(a,e){let t=typeof a=="string"?a.trim():"",n=e&&e.length?e.filter(o=>mr.has(o)):[];return(n.length?n:ze).map(o=>{let s=vt[o]??o;return{label:s,prompt:t?`${t} (${s})`:s}})}function Pt(a,e){return{actionButtons:fs(e),_instructions:`The user wants to ${a} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var K=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=fs(e,t)}},Wn=class extends Error{code="no_wallet_connected";constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one."),this.name="NoWalletConnectedError"}};function Y(a,e){if(Xe(a))return a.trim();if(Xe(e?.walletAddress))return e.walletAddress.trim();throw new Wn}function te(a,e,t){if(Xe(a)){let n=$(a);if(n)return n;throw new Qe(a.trim())}if(Xe(e?.chain)){let n=$(e.chain);if(n)return n;throw new Qe(e.chain.trim())}if(Xe(e?.walletAddress))throw new K(typeof e?.query=="string"?e.query:void 0,t);return ve}var v=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s=Ci(o);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-r,...s.actionButtons?{actionButtons:s.actionButtons}:{},...s.ui?{ui:s.ui}:{}}}catch(o){return o instanceof K?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-r,actionButtons:o.buttons}:o instanceof Wn?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-r}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}};function Ci(a){if(!a||typeof a!="object")return{data:a};let e=a,t=e.actionButtons,n=Array.isArray(t)&&t.length>0?t:void 0,r=e.ui,o=r&&typeof r=="object"&&typeof r.component=="string"?r:void 0;if(!n&&!o)return{data:a};let{actionButtons:s,ui:i,...l}=e;return{data:l,...n?{actionButtons:n}:{},...o?{ui:o}:{}}}var _i="https://wallet-api.pantograph.app",Ei="0x0000000000000000000000000000000000000000",ws={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},ks={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function Ri(a){return ws[a.toLowerCase()]||a}function ys(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function hr(a){let e=a,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function gr(a){if(Array.isArray(a))return a;let e=a;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function ie(a){if(a==null)return null;let e=typeof a=="number"?a:parseFloat(String(a));return Number.isFinite(e)?e:null}function bs(a,e){let t=a.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=ie(a.price_change_percentage_24h)??ie(a.priceChange24h)??ie(a.usd_price_24hr_percent_change)??ie(a.price_change_24h)??ie(a.priceChange);return{chainId:e,tokenAddress:a.address??a.token_address??"",name:a.name??null,symbol:a.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:a.logoURI??a.icon_image??a.logo??null,usdPrice:ie(a.price)??ie(a.usd_price),marketCap:ie(a.market_cap)??ie(a.marketCap),totalVolume:{"24h":ie(a.total_volume)??ie(a.volume24h)},pricePercentChange:{"24h":r}}}var le=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??_i).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),r=this.tokensUrl(t,n),o=await x.get(r);if(!o.ok)return;let s=gr(o.data),i=new Map;for(let l of s)l.address&&i.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=i.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),r=await x.get(n);if(!r.ok)return null;let o=gr(r.data),s=e.toLowerCase()===Ei,i=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||s&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||s&&l.token_address==="");return i?hr(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=this.tokensUrl(t,e.join(",")),o=await x.get(r);if(!o.ok)return n;let s=gr(o.data),i=new Set(e.map(l=>l.toLowerCase()));for(let l of s){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&i.has(c)&&(n[c]=hr(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||ve,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=ys({chainId:o,key:t}),i=`${this.baseUrl}/token-list/all?${s}`,l=await x.get(i);if(!l.ok)throw new Error(I(l));let c=l.data,d=c?.result??c?.data??c,u=[];return Array.isArray(d)?u=d:d&&typeof d=="object"&&(u=Object.values(d).flat()),{success:!0,data:u.map(hr)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||ve,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=ks[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],d=l.status==="fulfilled"?o.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>bs(h,t)):[],u=new Set,p=[];for(let h of d){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),m.push(h))}let f=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=ie(s.market_cap)??ie(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":ie(s.total_volume)??ie(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=parseInt(e,16),o=ys({chainId:r,duration:n,limit:t}),s=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(s);if(!c.ok)throw new Error(I(c));let d=c.data;if(i=Array.isArray(d)?d:Array.isArray(d.data)?d.data:[],i.length>0)break;l<4&&await new Promise(u=>setTimeout(u,2e3))}return i.map(l=>bs(l,e))}async getTopGainers(e){let t=e?.chain||ve,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,r=e?.duration||"24h";try{let o=await this.fetchTopGainers(t,n,r);return await this.enrichTrendingMarketData(o,t),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var Ni="https://nft.keyring.app",Ui="https://nft.keyring.app",Ii=.01,N=5,V=1e3,Li=25,Di="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Oi="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function j(a){return a||ve}function W(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function H(a){return new Promise(e=>setTimeout(e,a))}function Mi(a){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!a||typeof a!="object")return e;let t=a;if("active_protocols"in t||"total_usd_value"in t){let r=t;return{...e,...r,protocols:r.protocols||[]}}let n=t.result;return!n||typeof n!="object"?e:{active_protocols:n.activeProtocols??0,total_positions:n.totalPositions??0,total_usd_value:n.totalUsd??0,total_unclaimed_usd_value:n.totalUnclaimedUsd??0,protocols:(n.protocols||[]).map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",positions:r.positionCount??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,account_health_factor:r.accountHealthFactor??null}))}}function Fi(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function fr(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ni).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Ui).replace(/\/+$/,""),this.pantograph=new le({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=j(n),l="Unknown error";for(let c=1;c<=N;c++)try{let d={chain:i,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(d.token_addresses=r);let u=[],p=null;do{p&&(d.cursor=p);let f=W(d),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${f}`,g=await x.get(h);if(!g.ok)throw new U(g.status,I(g));let y=g.data,b=y?.data??y;b?.result?.length>0&&u.push(...b.result),p=b?.cursor??null}while(p);let m={result:u};return m?.result?.length>0&&(m.result=m.result.filter(f=>parseFloat(f.balance||"0")>0),m.result=m.result.map(f=>({...f,token_address:f.token_address.toLowerCase()===Di?Oi:f.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(f=>f.usd_value==null||f.usd_value>=Ii)),{success:!0,data:m}}catch(d){if(l=d instanceof Error?d.message:"Unknown error",d instanceof U&&d.status===400)break;c<N&&await H(V)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=j(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${W({chain:r,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${W({chain:r,include:"percent_change"})}`)]),d=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;d=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!d){o="Token metadata not found",i<N&&await H(V);continue}let u=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;u=p?.data??p}return{success:!0,data:{...d,...u?.usd_price?{usd_price:u.usd_price}:{},...u?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:u.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=100,excludeSpam:o=!1,cursor:s,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let d=j(n),u=[],p=s,m,f;for(let h=0;h<Li;h++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:d,limit:r,excludeSpam:o,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!g.success){if(u.length===0)return g;break}let y=g.data;if(!y)break;let{result:b,cursor:w,page:k,page_size:T}=y;if(Array.isArray(b)&&u.push(...b),m=k,f=T,p=typeof w=="string"&&w.trim()?w:void 0,!p)break}return{success:!0,data:{result:u,cursor:p,page:m,page_size:f}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:n,limit:r,excludeSpam:o,cursor:s,tokenAddresses:i,includePrices:l,format:c}=e,d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:n,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(p.cursor=s),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let m=W(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await x.get(f);if(!h.ok)throw new U(h.status,I(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;u<N&&await H(V)}return{success:!1,error:d}}async getWalletNftCollections(e){let{address:t,chain:n,limit:r=100,excludeSpam:o=!0,cursor:s}=e;if(!t)return{success:!1,error:"Address is required"};let i=j(n),l="Unknown error";for(let c=1;c<=N;c++)try{let d={chain:i,limit:r,exclude_spam:o};s&&(d.cursor=s);let u=W(d),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${u}`,m=await x.get(p);if(!m.ok)throw new U(m.status,I(m));let f=m.data;return{success:!0,data:f?.data??f}}catch(d){if(l=d instanceof Error?d.message:"Unknown error",d instanceof U&&d.status===400)break;c<N&&await H(V)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!q(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=j(r),d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:i};l&&(p.include=l);let m=W(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await x.get(f);if(!h.ok)throw new U(h.status,I(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;u<N&&await H(V)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:i,toBlock:l,cursor:c,order:d="DESC",includeInternalTransactions:u,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=j(n),f=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let g=1;g<=N;g++)try{let y={chain:m,limit:f,order:d};o&&(y.from_date=o),s&&(y.to_date=s),i!=null&&(y.from_block=i),l!=null&&(y.to_block=l),c&&(y.cursor=c),u!=null&&(y.include_internal_transactions=u),p!=null&&(y.nft_metadata=p);let b=W(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,k=await x.get(w);if(!k.ok)throw new U(k.status,I(k));let T=k.data;return{success:!0,data:T?.data??T}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;g<N&&await H(V)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=j(n),m=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let h=1;h<=N;h++)try{let g={chain:p,limit:m,order:u};s&&(g.from_date=s),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),d&&(g.cursor=d),r?.length&&(g.contract_addresses=r);let y=W(g),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await x.get(b);if(!w.ok)throw new U(w.status,I(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(g){if(f=g instanceof Error?g.message:"Unknown error",g instanceof U&&g.status===400)break;h<N&&await H(V)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=j(n),h=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=N;y++)try{let b={chain:f,limit:h,order:u,format:m};s&&(b.from_date=s),i&&(b.to_date=i),l!=null&&(b.from_block=l),c!=null&&(b.to_block=c),d&&(b.cursor=d),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=W(b),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,T=await x.get(k);if(!T.ok)throw new U(T.status,I(T));let S=T.data;return{success:!0,data:S?.data??S}}catch(b){if(g=b instanceof Error?b.message:"Unknown error",b instanceof U&&b.status===400)break;y<N&&await H(V)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!q(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=j(n),s="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:o};r&&(l.days=r);let c=W(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data;return{success:!0,data:p?.data??p}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:s}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let d=W(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await x.get(u);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await H(V)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let d=W(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await x.get(u);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await H(V)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:Mi(u)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!q(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:Fi(u)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!q(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=j(r),s="Unknown error";for(let i=1;i<=N;i++)try{let l=W({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,d=await x.get(c);if(!d.ok)throw new U(d.status,I(d));let m=d.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(g=>({token_type:g.tokenType,address:g.address,contract_address:g.address,name:g.name??"",symbol:g.symbol??"",decimals:g.decimals??18,logo:g.logo,balance:g.balance??"0",balance_formatted:g.balanceFormatted??"0",usd_price:g.usdPrice,usd_value:g.usdValue}))}))}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:s}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!q(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!q(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=W({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await H(V)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=N;o++)try{let s={};t&&(s.chain=j(t)),n!=null&&(s.limit=n);let i=W(s),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:fr(u)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof U&&s.status===400)break;o<N&&await H(V)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=W(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data,m=p?.data??p;return{success:!0,data:fr(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=W(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data,m=p?.data??p;return{success:!0,data:fr(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await H(V)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var xt=class extends v{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new z(e?.llm??{})}async run(e,t){let n=e.keyword||"",r=e.prompt||"",o=t?.walletAddress||void 0;if(!n)return{error:"Missing required parameter: keyword"};let s;try{s=te(e.chain,t)}catch(i){if(i instanceof Qe)return await this.researchTokenChainAgnostic(n,r,o);throw i}return await this.searchToken(n,s,r,o)}async researchTokenChainAgnostic(e,t,n){let r=[n?`User's connected wallet address: ${n}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
3
3
  `),o=t?await this.askGeminiWithSearch(t,r):null;return{_instructions:'The token info comes from web research only (the user is on a chain this app does not support on-chain). Present a clear summary of the token using the research: what it is, current USD price and 24h change, market data, recent news and the catalyst behind any price move, and a brief, clearly-hedged sense of market direction (no financial advice). Do NOT add a labelled "AI Analysis" heading and do NOT mention that the analysis came from AI \u2014 write it as a normal token summary. If a field is unknown, omit it. Do NOT mention chains, tools, or that anything is unsupported; just answer the question.',keyword:e,token:null,userHoldsToken:!1,research:o}}async searchToken(e,t,n,r){let o=[r?`User's connected wallet address: ${r}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
4
- `),[s,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),r?this.findTokenInWallet(r,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,o):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],u=e.toLowerCase(),d=g=>g.symbol?.toLowerCase()===u||g.token_address?.toLowerCase()===u,p=[...c].sort((g,y)=>(d(g)?0:1)-(d(y)?0:1)),m=null,f=p[0];if(f?.token_address){let g=await this.service.getTokenMetadata({address:f.token_address,chain:t});g.success&&g.data&&(m=g.data)}return!m&&f&&(m={...f}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:t,userHoldsToken:!!i,walletBalance:i,token:m,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),s=r.data.result.find(i=>i.token_address.toLowerCase()===o||i.symbol?.toLowerCase()===o||i.name?.toLowerCase().includes(o));return s||null}};var Ct=class extends v{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=te(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,i=d.symbol,l=d.name}let c=await this.service.getTokenHolders({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let u=c.data;return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},totalHolders:u.totalHolders,holdersByAcquisition:u.holdersByAcquisition,holderChange:u.holderChange,holderSupply:u.holderSupply,holderDistribution:u.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var _t=class extends v{name="get-token-analytics";description=`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=te(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,i=d.symbol,l=d.name}let c=await this.service.getTokenAnalytics({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let u=c.data??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},usdPrice:u.usdPrice??null,totalLiquidity:u.totalLiquidity??null,totalFullyDilutedValuation:u.totalFullyDilutedValuation??null,totalBuyVolume:u.totalBuyVolume??null,totalSellVolume:u.totalSellVolume??null,totalBuyers:u.totalBuyers??null,totalSellers:u.totalSellers??null,totalBuys:u.totalBuys??null,totalSells:u.totalSells??null,uniqueWallets:u.uniqueWallets??null,pricePercentChange:u.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Et=class extends v{name="get-token-score";description=`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=te(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let u=c.data??{},d=u.metrics??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},score:u.score??null,updatedAt:u.updatedAt??null,metrics:{usdPrice:d.usdPrice??null,liquidityUsd:d.liquidityUsd??null,volumeUsd:d.volumeUsd??null,transactions:d.transactions??null,supply:d.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Rt=class extends v{name="get-trending-tokens";description='List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad, and more.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1}];service;constructor(e){super(),this.service=new le({baseUrl:e?.pantographUrl})}async run(e,t){let n=bo(e.chain,t),r=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,o=await this.service.getTrendingTokens({chain:n,limit:r});if(!o.success)return{error:o.error||"Failed to fetch trending tokens"};let s=o.data??[];return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
4
+ `),[s,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),r?this.findTokenInWallet(r,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,o):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],d=e.toLowerCase(),u=g=>g.symbol?.toLowerCase()===d||g.token_address?.toLowerCase()===d,p=[...c].sort((g,y)=>(u(g)?0:1)-(u(y)?0:1)),m=null,f=p[0];if(f?.token_address){let g=await this.service.getTokenMetadata({address:f.token_address,chain:t});g.success&&g.data&&(m=g.data)}return!m&&f&&(m={...f}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:t,userHoldsToken:!!i,walletBalance:i,token:m,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),s=r.data.result.find(i=>i.token_address.toLowerCase()===o||i.symbol?.toLowerCase()===o||i.name?.toLowerCase().includes(o));return s||null}};var Ct=class extends v{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=te(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(o){let u=await this.resolveContractAddress(o,n,r);if(!u)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenHolders({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var _t=class extends v{name="get-token-analytics";description=`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=te(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let u=await this.resolveContractAddress(o,n,r);if(!u)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenAnalytics({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Et=class extends v{name="get-token-score";description=`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=te(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},u=d.metrics??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:u.usdPrice??null,liquidityUsd:u.liquidityUsd??null,volumeUsd:u.volumeUsd??null,transactions:u.transactions??null,supply:u.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Rt=class extends v{name="get-trending-tokens";description='List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad, and more.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1}];service;constructor(e){super(),this.service=new le({baseUrl:e?.pantographUrl})}async run(e,t){let n=bo(e.chain,t),r=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,o=await this.service.getTrendingTokens({chain:n,limit:r});if(!o.success)return{error:o.error||"Failed to fetch trending tokens"};let s=o.data??[];return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
5
5
  <rank>. <name> (<symbol>)
6
6
  - Price: <usdPrice>
7
7
  - Market Cap: <marketCap>
@@ -13,7 +13,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
13
13
  - Market Cap: <marketCap>
14
14
  - Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
15
15
  - 24h Volume: <totalVolume.24h>
16
- Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?P(n):"all",timeFrame:o??null,count:c.length,tokens:c}}};var Ut=class extends v{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,r=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(r+"00").slice(0,2)}`}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t);if(r){let i=await this.service.getWalletTokenBalances({address:n,chain:r,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(n,r,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let o=de(),s=await Promise.all(o.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,s)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",r=e.symbol||"",o=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${r} (${o})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let r=n.reduce((o,s)=>o+(s.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(r)}`,tokens:n.map(o=>this.toTokenLine(o))}}renderBalancesByChain(e,t){let n=t.map(o=>{let s=o.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=o.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:P(o.chain),total:s,tokens:i}}).filter(o=>o.tokens.length>0).sort((o,s)=>s.total-o.total),r=n.reduce((o,s)=>o+s.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(r)}`,chains:n.map(o=>({chain:o.chain,totalUsdValue:`$${this.truncateUsd(o.total)}`,tokens:o.tokens.map(s=>this.toTokenLine(s))}))}}};var It=class extends v{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=te(e.chain,t),o=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,s=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,u=Number.isFinite(l)?l:void 0,d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,y=Number.isFinite(g)&&g>0?g:10,b=await this.service.getWalletHistory({address:n,chain:r,limit:y,fromDate:o,toDate:s,fromBlock:c,toBlock:u,cursor:d,order:m,includeInternalTransactions:f,nftMetadata:h});if(!b.success)return{error:b.error||"Failed to fetch wallet history"};let k=(b.data?.result||[]).map(T=>{let S=ms(r,T.hash);return S?{...T,explorerUrl:S}:T});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:r||"default",pagination:{cursor:b.data?.cursor??null,hasMore:!!b.data?.cursor},transactionCount:k.length,transactions:k}}};function qi(a){if(a.value_decimal)return a.value_decimal;let e=parseInt(a.token_decimals??"18",10);if(isNaN(e)||e===0)return a.value;try{let t=BigInt(a.value),n=BigInt(10)**BigInt(e),r=t/n,s=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return s?`${r}.${s}`:`${r}`}catch{return a.value}}var Lt=class extends v{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=te(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,b,w;if(g){let C=await this.resolveContractAddressBySymbol(g,n,r);C&&(y=[C.address],b=C.symbol,w=C.name)}let k=await this.service.getWalletTokenTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let T=n.toLowerCase(),A=(k.data?.result||[]).map(C=>{let M=C.from_address.toLowerCase()===T,E=M?"send":"receive",Q=M?C.to_address:C.from_address,O=M?C.to_address_label??void 0:C.from_address_label??void 0,Ie=M?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:E,amount_formatted:qi(C),counterparty:Q,counterparty_label:O,counterparty_entity:Ie}}),_=h==="all"?A:A.filter(C=>C.direction===h);if(g&&!y){let C=g.toLowerCase();_=_.filter(M=>(M.token_symbol??"").toLowerCase()===C)}let R=this.buildCounterparties(_);return{walletAddress:n,chain:r||"default",resolvedToken:b?{symbol:b,name:w,contractAddress:y?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:y||null,direction:h,limit:s,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??s,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:_.length,transfers:_,counterparties:R}}async resolveContractAddressBySymbol(e,t,n){let r=e.toLowerCase(),o=await this.service.getWalletTokenBalances({address:t,chain:n});if(o.success&&o.data?.result?.length){let i=o.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let s=await this.service.searchTokensByKey({key:e,chain:n});if(s.success&&s.data?.length){let l=s.data.find(c=>(c.symbol??"").toLowerCase()===r)??s.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let s=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=parseFloat(o.amount_formatted)||0,c=s.get(i);c?(c.total+=l,c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):s.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,total:l,count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((s,i)=>i[1].count-s[1].count).map(([s,i])=>({address:s,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Dt=class extends v{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=te(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(_=>typeof _=="string"&&!!_).map(_=>_.trim()):void 0,b=await this.service.getWalletNftTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m,includePrices:f});if(!b.success)return{error:b.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),T=(b.data?.result||[]).map(_=>{let R=_.from_address.toLowerCase()===w,C=R?"send":"receive",M=R?_.to_address:_.from_address,E=R?_.to_address_label??void 0:_.from_address_label??void 0,Q=R?_.to_address_entity??void 0:_.from_address_entity??void 0;return{..._,direction:C,counterparty:M,counterparty_label:E,counterparty_entity:Q}}),S=g==="all"?T:T.filter(_=>_.direction===g),A=this.buildCounterparties(S);return{walletAddress:n,chain:r||"default",filters:{contractAddresses:y||null,direction:g,limit:s,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null,includePrices:f??null},pagination:{cursor:b.data?.cursor??null,pageSize:b.data?.page_size??s,page:b.data?.page??null,hasMore:!!b.data?.cursor},transferCount:S.length,transfers:S,counterparties:A}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let s=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=o.token_name??o.token_address,c=s.get(i);c?(c.tokenIds.add(o.token_id),c.collections.add(l),c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):s.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,tokenIds:new Set([o.token_id]),collections:new Set([l]),count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((s,i)=>i[1].count-s[1].count).map(([s,i])=>({address:s,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Bi=["all","7","30","60","90"],Ot=class extends v{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=Bi.includes(o)?o:void 0;if(r){let h=await this.service.getWalletPnlSummary({address:n,chain:r,days:s});return h.success?{walletAddress:n,chain:r,days:s??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(de().map(async h=>{let g=await this.service.getWalletPnlSummary({address:n,chain:h,days:s});return{chain:h,data:g.success?g.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:P(h.chain),summary:this.mapSummary(h.data)})),u=l.reduce((h,g)=>h+Number(g.data.total_realized_profit_usd||0),0),d=l.reduce((h,g)=>h+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((h,g)=>h+Number(g.data.total_sold_volume_usd||0),0),m=l.reduce((h,g)=>h+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((h,g)=>h+g.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:l.reduce((h,g)=>h+g.data.total_buys,0),totalSells:l.reduce((h,g)=>h+g.data.total_sells,0),totalBoughtVolumeUsd:d,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:s??"all",summary:f,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var $i=["all","7","30","60","90"],wo=25,Mt=class extends v{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${wo}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${wo}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${wo}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=$i.includes(o)?o:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[];if(r){let d=await this.fetchChainPnl(n,r,s,i,l);return d.ok?{walletAddress:n,chain:r,days:s??"all",filters:{tokenAddresses:d.tokenAddresses??null,resolvedSymbols:d.resolvedFromSymbols.length>0?d.resolvedFromSymbols:null,unresolvedSymbols:d.unresolvedSymbols.length>0?d.unresolvedSymbols:null},tokenCount:d.tokens.length,tokens:d.tokens}:{error:d.error||"Failed to fetch wallet PnL"}}let u=(await Promise.all(de().map(async d=>({chain:d,res:await this.fetchChainPnl(n,d,s,i,l)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:P(d.chain),tokenCount:d.res.tokens.length,tokens:d.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:s??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:u.reduce((d,p)=>d+p.tokenCount,0),chains:u}}async fetchChainPnl(e,t,n,r,o){let s=[],i=[];r.length>0&&(await Promise.all(r.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?s.push({symbol:r[m],address:p.address}):i.push(r[m])});let l=Vi([...s.map(d=>d.address),...o]).slice(0,wo),c=l.length>0?l:void 0,u=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:u.success,error:u.error,tokens:u.data?.result??[],tokenAddresses:c,resolvedFromSymbols:s,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Vi(a){let e=new Set,t=[];for(let n of a){let r=n.toLowerCase();e.has(r)||(e.add(r),t.push(n))}return t}var Wi=BigInt(2)**BigInt(255),Ft=class extends v{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=te(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:r,limit:s,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,d=(c.result||[]).map(h=>Hi(h)),p=0,m=0,f=[];for(let h of d){h.isUnlimited&&(m+=1);let g=parseFloat(h.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let y=h.token.possibleSpam||h.token.verifiedContract===!1,b=!h.spender.label&&!h.spender.entity;(y||h.isUnlimited&&b)&&f.push(h)}return{walletAddress:n,chain:r||"default",filters:{limit:s,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??s,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:d,riskyApprovals:f}}};function Hi(a){let e=Gi(a.value);return{blockNumber:a.block_number,blockTimestamp:a.block_timestamp??null,transactionHash:a.transaction_hash??null,value:a.value,valueFormatted:a.value_formatted??null,isUnlimited:e,token:{address:a.token.address,addressLabel:a.token.address_label??null,name:a.token.name??null,symbol:a.token.symbol??null,logo:a.token.logo??null,possibleSpam:!!a.token.possible_spam,verifiedContract:a.token.verified_contract??null,currentBalance:a.token.current_balance??null,currentBalanceFormatted:a.token.current_balance_formatted??null,usdPrice:a.token.usd_price??null,usdAtRisk:a.token.usd_at_risk??null},spender:{address:a.spender.address,label:a.spender.address_label??null,entity:a.spender.entity??null,entityLogo:a.spender.entity_logo??null}}}function Gi(a){if(!a)return!1;try{return BigInt(a)>=Wi}catch{return!1}}var qt=class extends v{name="get-wallet-defi-summary";description=`Get a wallet's DeFi protocols summary: which protocols the wallet is using, total USD value locked across all protocols, total unclaimed rewards/fees, number of active protocols, and total number of positions. Returns a per-protocol breakdown (protocol name, logo, url, positions count, usd value, unclaimed). Use for questions like: "Which DeFi protocols am I using?", "What's my total DeFi value?", "How much do I have in DeFi?", "Show my DeFi portfolio overview", "Unclaimed rewards across protocols". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Do NOT use for: detailed per-position data \u2192 get-wallet-defi-positions; positions inside a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t);if(r){let i=await this.service.getWalletDefiSummary({address:n,chain:r});return i.success?{walletAddress:n,chain:r,...this.summaryFields(i.data)}:{error:i.error||"Failed to fetch wallet DeFi summary"}}let s=(await Promise.all(de().map(async i=>{let l=await this.service.getWalletDefiSummary({address:n,chain:i});return{chain:i,data:l.success?l.data:void 0}}))).flatMap(i=>i.data&&i.data.active_protocols>0?[{chain:P(i.chain),data:i.data}]:[]).map(i=>({chain:i.chain,...this.summaryFields(i.data)})).sort((i,l)=>l.totalUsdValue-i.totalUsdValue);return{_instructions:"These DeFi summaries cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains with DeFi activity, highest total value first). Present one section per chain, in order: the chain name then its protocols. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",totalUsdValue:s.reduce((i,l)=>i+(l.totalUsdValue||0),0),totalUnclaimedUsdValue:s.reduce((i,l)=>i+(l.totalUnclaimedUsdValue||0),0),chains:s}}summaryFields(e){return{activeProtocols:e.active_protocols,totalPositions:e.total_positions,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,protocols:(e.protocols||[]).map(t=>({protocolName:t.protocol_name,protocolId:t.protocol_id,protocolUrl:t.protocol_url,protocolLogo:t.protocol_logo,positions:t.positions,totalUsdValue:t.total_usd_value,totalUnclaimedUsdValue:t.total_unclaimed_usd_value,accountHealthFactor:t.account_health_factor??null}))}}};var Bt=class extends v{name="get-wallet-defi-positions";description='Get every DeFi position a wallet holds across all supported protocols, with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Do NOT use for: aggregate totals \u2192 get-wallet-defi-summary; positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t);if(r){let i=await this.service.getWalletDefiPositions({address:n,chain:r});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:r,positionCount:l.length,positions:l.map(As)}}let s=(await Promise.all(de().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:P(i.chain),positionCount:i.rows.length,positions:i.rows.map(As)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:s.reduce((i,l)=>i+l.positionCount,0),chains:s}}};function As(a){return{protocolName:a.protocol_name,protocolId:a.protocol_id,protocolUrl:a.protocol_url,protocolLogo:a.protocol_logo,accountHealthFactor:a.account_data?.health_factor??null,position:Yi(a.position)}}function Yi(a){return{label:a.label,address:a.address,balanceUsd:a.balance_usd,totalUnclaimedUsdValue:a.total_unclaimed_usd_value,tokens:(a.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:a.position_details??null}}var $t=class extends v{name="get-wallet-defi-protocol-positions";description='Get every position a wallet holds inside a specific DeFi protocol, with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "what do I have on Aave v3", "show my Lido staking", "my Curve pools", "Pendle positions". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions; totals only \u2192 get-wallet-defi-summary.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-summary to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let r=Y(e.address,t),o=re(e.chain,t);if(o){let l=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:o});return l.success?l.data?{walletAddress:r,chain:o,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(de().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:P(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:r,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(ji)}}};function ji(a){return{label:a.label,address:a.address,balanceUsd:a.balance_usd,totalUnclaimedUsdValue:a.total_unclaimed_usd_value,tokens:(a.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:a.position_details??null}}function Ki(a){try{return(Number(BigInt(a))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return a}}var Vt=class extends v{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let r=te(e.chain,t),o=await this.service.getTransactionByHash({transactionHash:n,chain:r});if(!o.success||!o.data)return{error:o.error||"Failed to fetch transaction"};let s=o.data,i=(s.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=s.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:s.hash,status:s.receipt_status==="1"?"success":s.receipt_status==="0"?"failed":"unknown",timestamp:s.block_timestamp,blockNumber:s.block_number,from:{address:s.from_address,label:s.from_address_label||null,entity:s.from_address_entity||null},to:s.to_address?{address:s.to_address,label:s.to_address_label||null,entity:s.to_address_entity||null}:null,valueEth:Ki(s.value||"0"),fee:s.transaction_fee,gasUsed:s.receipt_gas_used,gasPriceGwei:s.gas_price?(Number(s.gas_price)/1e9).toFixed(4):null,decodedCall:s.decoded_call?{signature:s.decoded_call.signature,label:s.decoded_call.label,params:s.decoded_call.params}:null,decodedEvents:i,contractCreated:s.receipt_contract_address||null,logs:l}}};var ko="https://ipfs.pantograph.app/ipfs/",Ss=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Hn(a){let e=a?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ko}${t[1]}`:Ss.test(e)?`${ko}${e}`:null}function Ps(a){let e=a?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ko}${t[1]}`:Ss.test(e)?`${ko}${e}`:null}function xs(a){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(a)}function yr(a){if(!a||typeof a!="object")return;let e=a,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function zi(a){if(typeof atob=="function"){let e=atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(a,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Xi(a){let e=a.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",n=e[2]??"";try{let r=/;base64/i.test(t)?zi(n):decodeURIComponent(n);return JSON.parse(r)}catch{try{return JSON.parse(n)}catch{return null}}}function Cs(a){let e=a?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Xi(e);return t?Hn(yr(t)):null}var Qi=12,Ji=6e3;async function Zi(a,e,t){let n=new Array(a.length),r=0,o=new Array(Math.max(1,Math.min(e,a.length))).fill(0).map(async()=>{for(;r<a.length;){let s=r++;n[s]=await t(a[s],s)}});return await Promise.all(o),n}async function el(a,e){try{let t=await x.get(a,{timeout:e});if(!t.ok)return null;let n=t.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function tl(a,e){let t=a?.trim();if(!t)return null;if(/^data:/i.test(t))return Cs(t);let n=Ps(t);if(!n)return null;if(xs(n))return n;let r=await el(n,e);if(r){let o=Hn(yr(r));if(o)return o}return null}async function _s(a,e,t){if(e.length===0)return[];let n=t?.concurrency??Qi,r=t?.timeoutMs??Ji,o=await ns(a,e,t?.rpcUrl);return Zi(o,n,s=>tl(s,r))}var Es=100,nl=100,Wt="{name}",Rs="{chain}",Ht=class extends v{name="get-wallet-nfts";description=`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`;category="nft";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t),o=r?[r]:de(),s=ll(e.contract_address),i=Is(e.collection_name);return s||i?this.listNfts({address:n,chains:o,singleChain:!!r,contract:s,collectionName:i}):this.listCollections({address:n,chains:o,singleChain:!!r,args:e})}async listCollections(e){let{address:t,chains:n,singleChain:r,args:o}=e,s=await Promise.all(n.map(async c=>{let u=await this.service.getWalletNftCollections({address:t,chain:c,limit:Es});return{chain:c,rows:u.success?Ns(u.data?.result??[]):[],ok:u.success}}));if(r&&!s[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=s.flatMap(c=>c.rows.map(u=>({name:rl(u),contractAddress:u.token_address,chain:P(c.chain),nftCount:u.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(r?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=al(i,o);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:n,singleChain:r,contract:o,collectionName:s}=e,i=await Promise.all(n.map(async m=>{let f=await this.service.getWalletNFTs({address:t,chain:m,limit:Es,...o?{tokenAddresses:[o]}:{}});return{chain:m,rows:f.success?Ns(f.data?.result??[]):[],ok:f.success}}));if(r&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>ol(f,{contract:o,collectionName:s})).map(f=>({chain:m.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${s??o??""}"`+(r?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||s||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:m,row:f},h)=>{let g=sl(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:u[h]??g.image,chain:P(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:d}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),n=new Map;e.forEach((r,o)=>{let s=n.get(r.chain)??[];s.push(o),n.set(r.chain,s)});try{await Promise.all([...n.entries()].map(async([r,o])=>{let s=o.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await _s(r,s);o.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Ns(a){return a.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function ol(a,e){if(e.contract)return a.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(a.name??"").toLowerCase().includes(t)}return!1}function rl(a){let e=a.name?.trim();if(e)return e;let t=a.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function sl(a){return{name:a.normalized_metadata?.name||a.name||`#${a.token_id}`,tokenId:a.token_id,contractAddress:a.token_address,image:Hn(a.normalized_metadata?.image||a.media?.original_media_url)}}function al(a,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",r=[];for(let o of a){if(r.length>=nl)break;if(!o.contractAddress)continue;let s=typeof o.chain=="string"?o.chain.trim():"",i=s?`show my ${Wt} NFTs on ${Rs}`:`show my ${Wt} NFTs`,l=Us(n,{[Wt]:o.name,[Rs]:s},i);s&&!l.includes(s)&&(l=`${l} (${s})`),r.push({label:il(t,o.name,Wt),prompt:`${l} (${o.contractAddress})`})}return r}function Us(a,e,t){let n=a&&a.includes(Wt)?a:t;for(let[r,o]of Object.entries(e))n=n.split(r).join(o);return n.replace(/\s+/g," ").trim()}function il(a,e,t){return Us(a,{[Wt]:e},t)}function Is(a){if(typeof a!="string")return;let e=a.trim();return e||void 0}function ll(a){let e=Is(a);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var cl="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",Oe=class extends v{kind="data";category="nft";llm;constructor(e){super(),this.llm=new z(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:cl,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Gt=class extends Oe{name="get-nft-contract-info";description='Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.';parameters=Oe.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`);presentInstructions="Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks."};var Yt=class extends Oe{name="get-nft-metadata";description='Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.';parameters=Oe.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`);presentInstructions="Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points."};var br={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},wr="amazon.com";function ul(a){return a?a.trim().toLowerCase().split(/[-_]/)[0]:""}function kr(a){let e=ul(a);return br[e]??wr}function To(a){return`https://${kr(a)}/s?k=NFC%20Tag`}function vo(a){if(!a)return"";let e=a.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var dl=720*60*1e3,Ls=new Map,Ds=3;function pl(a){return[`A user in country "${a}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Ds} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function ml(a){if(!a)return[];let e=a.indexOf("["),t=a.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(a.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let r=[],o=new Set;for(let s of n){if(!s||typeof s!="object")continue;let i=s.label,l=s.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!o.has(c)&&(o.add(c),r.push({label:i.trim(),url:l.trim()}),r.length>=Ds))break}return r}async function Tr(a,e){let t=vo(a);if(!t||!e)return null;let n=Ls.get(t);if(n&&n.expires>Date.now())return n.links;let r=Date.now(),o=[{role:"user",content:pl(t),timestamp:r}];try{let s=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),i=ml(s.text);if(i.length)return Ls.set(t,{links:i,expires:Date.now()+dl}),i}catch{}return null}async function jt(a){let e=await Tr(a.country,a.llm);return e&&e.length?e:[{label:"Amazon",url:To(a.language)}]}function hl(a){return a.length<=1?a.length===1?`[${a[0].label}](${a[0].url})`:"":a.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
16
+ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?P(n):"all",timeFrame:o??null,count:c.length,tokens:c}}};var Ut=class extends v{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,r=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(r+"00").slice(0,2)}`}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t);if(r){let i=await this.service.getWalletTokenBalances({address:n,chain:r,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(n,r,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let o=de(),s=await Promise.all(o.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,s)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",r=e.symbol||"",o=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${r} (${o})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let r=n.reduce((o,s)=>o+(s.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(r)}`,tokens:n.map(o=>this.toTokenLine(o))}}renderBalancesByChain(e,t){let n=t.map(o=>{let s=o.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=o.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:P(o.chain),total:s,tokens:i}}).filter(o=>o.tokens.length>0).sort((o,s)=>s.total-o.total),r=n.reduce((o,s)=>o+s.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(r)}`,chains:n.map(o=>({chain:o.chain,totalUsdValue:`$${this.truncateUsd(o.total)}`,tokens:o.tokens.map(s=>this.toTokenLine(s))}))}}};var It=class extends v{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=te(e.chain,t),o=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,s=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,d=Number.isFinite(l)?l:void 0,u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,y=Number.isFinite(g)&&g>0?g:10,b=await this.service.getWalletHistory({address:n,chain:r,limit:y,fromDate:o,toDate:s,fromBlock:c,toBlock:d,cursor:u,order:m,includeInternalTransactions:f,nftMetadata:h});if(!b.success)return{error:b.error||"Failed to fetch wallet history"};let k=(b.data?.result||[]).map(T=>{let S=ms(r,T.hash);return S?{...T,explorerUrl:S}:T});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:r||"default",pagination:{cursor:b.data?.cursor??null,hasMore:!!b.data?.cursor},transactionCount:k.length,transactions:k}}};function qi(a){if(a.value_decimal)return a.value_decimal;let e=parseInt(a.token_decimals??"18",10);if(isNaN(e)||e===0)return a.value;try{let t=BigInt(a.value),n=BigInt(10)**BigInt(e),r=t/n,s=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return s?`${r}.${s}`:`${r}`}catch{return a.value}}var Lt=class extends v{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=te(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,b,w;if(g){let C=await this.resolveContractAddressBySymbol(g,n,r);C&&(y=[C.address],b=C.symbol,w=C.name)}let k=await this.service.getWalletTokenTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let T=n.toLowerCase(),A=(k.data?.result||[]).map(C=>{let M=C.from_address.toLowerCase()===T,E=M?"send":"receive",Q=M?C.to_address:C.from_address,O=M?C.to_address_label??void 0:C.from_address_label??void 0,Ie=M?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:E,amount_formatted:qi(C),counterparty:Q,counterparty_label:O,counterparty_entity:Ie}}),_=h==="all"?A:A.filter(C=>C.direction===h);if(g&&!y){let C=g.toLowerCase();_=_.filter(M=>(M.token_symbol??"").toLowerCase()===C)}let R=this.buildCounterparties(_);return{walletAddress:n,chain:r||"default",resolvedToken:b?{symbol:b,name:w,contractAddress:y?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:y||null,direction:h,limit:s,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??s,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:_.length,transfers:_,counterparties:R}}async resolveContractAddressBySymbol(e,t,n){let r=e.toLowerCase(),o=await this.service.getWalletTokenBalances({address:t,chain:n});if(o.success&&o.data?.result?.length){let i=o.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let s=await this.service.searchTokensByKey({key:e,chain:n});if(s.success&&s.data?.length){let l=s.data.find(c=>(c.symbol??"").toLowerCase()===r)??s.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let s=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=parseFloat(o.amount_formatted)||0,c=s.get(i);c?(c.total+=l,c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):s.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,total:l,count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((s,i)=>i[1].count-s[1].count).map(([s,i])=>({address:s,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Dt=class extends v{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=te(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(_=>typeof _=="string"&&!!_).map(_=>_.trim()):void 0,b=await this.service.getWalletNftTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m,includePrices:f});if(!b.success)return{error:b.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),T=(b.data?.result||[]).map(_=>{let R=_.from_address.toLowerCase()===w,C=R?"send":"receive",M=R?_.to_address:_.from_address,E=R?_.to_address_label??void 0:_.from_address_label??void 0,Q=R?_.to_address_entity??void 0:_.from_address_entity??void 0;return{..._,direction:C,counterparty:M,counterparty_label:E,counterparty_entity:Q}}),S=g==="all"?T:T.filter(_=>_.direction===g),A=this.buildCounterparties(S);return{walletAddress:n,chain:r||"default",filters:{contractAddresses:y||null,direction:g,limit:s,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null,includePrices:f??null},pagination:{cursor:b.data?.cursor??null,pageSize:b.data?.page_size??s,page:b.data?.page??null,hasMore:!!b.data?.cursor},transferCount:S.length,transfers:S,counterparties:A}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let s=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=o.token_name??o.token_address,c=s.get(i);c?(c.tokenIds.add(o.token_id),c.collections.add(l),c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):s.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,tokenIds:new Set([o.token_id]),collections:new Set([l]),count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((s,i)=>i[1].count-s[1].count).map(([s,i])=>({address:s,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Bi=["all","7","30","60","90"],Ot=class extends v{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=Bi.includes(o)?o:void 0;if(r){let h=await this.service.getWalletPnlSummary({address:n,chain:r,days:s});return h.success?{walletAddress:n,chain:r,days:s??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(de().map(async h=>{let g=await this.service.getWalletPnlSummary({address:n,chain:h,days:s});return{chain:h,data:g.success?g.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:P(h.chain),summary:this.mapSummary(h.data)})),d=l.reduce((h,g)=>h+Number(g.data.total_realized_profit_usd||0),0),u=l.reduce((h,g)=>h+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((h,g)=>h+Number(g.data.total_sold_volume_usd||0),0),m=l.reduce((h,g)=>h+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((h,g)=>h+g.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:u>0?d/u*100:0,totalBuys:l.reduce((h,g)=>h+g.data.total_buys,0),totalSells:l.reduce((h,g)=>h+g.data.total_sells,0),totalBoughtVolumeUsd:u,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:s??"all",summary:f,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var $i=["all","7","30","60","90"],wo=25,Mt=class extends v{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${wo}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${wo}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${wo}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=$i.includes(o)?o:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[];if(r){let u=await this.fetchChainPnl(n,r,s,i,l);return u.ok?{walletAddress:n,chain:r,days:s??"all",filters:{tokenAddresses:u.tokenAddresses??null,resolvedSymbols:u.resolvedFromSymbols.length>0?u.resolvedFromSymbols:null,unresolvedSymbols:u.unresolvedSymbols.length>0?u.unresolvedSymbols:null},tokenCount:u.tokens.length,tokens:u.tokens}:{error:u.error||"Failed to fetch wallet PnL"}}let d=(await Promise.all(de().map(async u=>({chain:u,res:await this.fetchChainPnl(n,u,s,i,l)})))).filter(u=>u.res.ok&&u.res.tokens.length>0).map(u=>({chain:P(u.chain),tokenCount:u.res.tokens.length,tokens:u.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:s??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:d.reduce((u,p)=>u+p.tokenCount,0),chains:d}}async fetchChainPnl(e,t,n,r,o){let s=[],i=[];r.length>0&&(await Promise.all(r.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?s.push({symbol:r[m],address:p.address}):i.push(r[m])});let l=Vi([...s.map(u=>u.address),...o]).slice(0,wo),c=l.length>0?l:void 0,d=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:c,resolvedFromSymbols:s,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Vi(a){let e=new Set,t=[];for(let n of a){let r=n.toLowerCase();e.has(r)||(e.add(r),t.push(n))}return t}var Wi=BigInt(2)**BigInt(255),Ft=class extends v{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=te(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:r,limit:s,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,u=(c.result||[]).map(h=>Hi(h)),p=0,m=0,f=[];for(let h of u){h.isUnlimited&&(m+=1);let g=parseFloat(h.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let y=h.token.possibleSpam||h.token.verifiedContract===!1,b=!h.spender.label&&!h.spender.entity;(y||h.isUnlimited&&b)&&f.push(h)}return{walletAddress:n,chain:r||"default",filters:{limit:s,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??s,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:u.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:u,riskyApprovals:f}}};function Hi(a){let e=Gi(a.value);return{blockNumber:a.block_number,blockTimestamp:a.block_timestamp??null,transactionHash:a.transaction_hash??null,value:a.value,valueFormatted:a.value_formatted??null,isUnlimited:e,token:{address:a.token.address,addressLabel:a.token.address_label??null,name:a.token.name??null,symbol:a.token.symbol??null,logo:a.token.logo??null,possibleSpam:!!a.token.possible_spam,verifiedContract:a.token.verified_contract??null,currentBalance:a.token.current_balance??null,currentBalanceFormatted:a.token.current_balance_formatted??null,usdPrice:a.token.usd_price??null,usdAtRisk:a.token.usd_at_risk??null},spender:{address:a.spender.address,label:a.spender.address_label??null,entity:a.spender.entity??null,entityLogo:a.spender.entity_logo??null}}}function Gi(a){if(!a)return!1;try{return BigInt(a)>=Wi}catch{return!1}}var qt=class extends v{name="get-wallet-defi-summary";description=`Get a wallet's DeFi protocols summary: which protocols the wallet is using, total USD value locked across all protocols, total unclaimed rewards/fees, number of active protocols, and total number of positions. Returns a per-protocol breakdown (protocol name, logo, url, positions count, usd value, unclaimed). Use for questions like: "Which DeFi protocols am I using?", "What's my total DeFi value?", "How much do I have in DeFi?", "Show my DeFi portfolio overview", "Unclaimed rewards across protocols". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Do NOT use for: detailed per-position data \u2192 get-wallet-defi-positions; positions inside a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t);if(r){let i=await this.service.getWalletDefiSummary({address:n,chain:r});return i.success?{walletAddress:n,chain:r,...this.summaryFields(i.data)}:{error:i.error||"Failed to fetch wallet DeFi summary"}}let s=(await Promise.all(de().map(async i=>{let l=await this.service.getWalletDefiSummary({address:n,chain:i});return{chain:i,data:l.success?l.data:void 0}}))).flatMap(i=>i.data&&i.data.active_protocols>0?[{chain:P(i.chain),data:i.data}]:[]).map(i=>({chain:i.chain,...this.summaryFields(i.data)})).sort((i,l)=>l.totalUsdValue-i.totalUsdValue);return{_instructions:"These DeFi summaries cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains with DeFi activity, highest total value first). Present one section per chain, in order: the chain name then its protocols. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",totalUsdValue:s.reduce((i,l)=>i+(l.totalUsdValue||0),0),totalUnclaimedUsdValue:s.reduce((i,l)=>i+(l.totalUnclaimedUsdValue||0),0),chains:s}}summaryFields(e){return{activeProtocols:e.active_protocols,totalPositions:e.total_positions,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,protocols:(e.protocols||[]).map(t=>({protocolName:t.protocol_name,protocolId:t.protocol_id,protocolUrl:t.protocol_url,protocolLogo:t.protocol_logo,positions:t.positions,totalUsdValue:t.total_usd_value,totalUnclaimedUsdValue:t.total_unclaimed_usd_value,accountHealthFactor:t.account_health_factor??null}))}}};var Bt=class extends v{name="get-wallet-defi-positions";description='Get every DeFi position a wallet holds across all supported protocols, with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Do NOT use for: aggregate totals \u2192 get-wallet-defi-summary; positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t);if(r){let i=await this.service.getWalletDefiPositions({address:n,chain:r});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:r,positionCount:l.length,positions:l.map(As)}}let s=(await Promise.all(de().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:P(i.chain),positionCount:i.rows.length,positions:i.rows.map(As)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:s.reduce((i,l)=>i+l.positionCount,0),chains:s}}};function As(a){return{protocolName:a.protocol_name,protocolId:a.protocol_id,protocolUrl:a.protocol_url,protocolLogo:a.protocol_logo,accountHealthFactor:a.account_data?.health_factor??null,position:Yi(a.position)}}function Yi(a){return{label:a.label,address:a.address,balanceUsd:a.balance_usd,totalUnclaimedUsdValue:a.total_unclaimed_usd_value,tokens:(a.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:a.position_details??null}}var $t=class extends v{name="get-wallet-defi-protocol-positions";description='Get every position a wallet holds inside a specific DeFi protocol, with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "what do I have on Aave v3", "show my Lido staking", "my Curve pools", "Pendle positions". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions; totals only \u2192 get-wallet-defi-summary.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-summary to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let r=Y(e.address,t),o=re(e.chain,t);if(o){let l=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:o});return l.success?l.data?{walletAddress:r,chain:o,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(de().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:P(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:r,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(ji)}}};function ji(a){return{label:a.label,address:a.address,balanceUsd:a.balance_usd,totalUnclaimedUsdValue:a.total_unclaimed_usd_value,tokens:(a.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:a.position_details??null}}function Ki(a){try{return(Number(BigInt(a))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return a}}var Vt=class extends v{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let r=te(e.chain,t),o=await this.service.getTransactionByHash({transactionHash:n,chain:r});if(!o.success||!o.data)return{error:o.error||"Failed to fetch transaction"};let s=o.data,i=(s.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=s.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:s.hash,status:s.receipt_status==="1"?"success":s.receipt_status==="0"?"failed":"unknown",timestamp:s.block_timestamp,blockNumber:s.block_number,from:{address:s.from_address,label:s.from_address_label||null,entity:s.from_address_entity||null},to:s.to_address?{address:s.to_address,label:s.to_address_label||null,entity:s.to_address_entity||null}:null,valueEth:Ki(s.value||"0"),fee:s.transaction_fee,gasUsed:s.receipt_gas_used,gasPriceGwei:s.gas_price?(Number(s.gas_price)/1e9).toFixed(4):null,decodedCall:s.decoded_call?{signature:s.decoded_call.signature,label:s.decoded_call.label,params:s.decoded_call.params}:null,decodedEvents:i,contractCreated:s.receipt_contract_address||null,logs:l}}};var ko="https://ipfs.pantograph.app/ipfs/",Ss=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Hn(a){let e=a?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ko}${t[1]}`:Ss.test(e)?`${ko}${e}`:null}function Ps(a){let e=a?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ko}${t[1]}`:Ss.test(e)?`${ko}${e}`:null}function xs(a){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(a)}function yr(a){if(!a||typeof a!="object")return;let e=a,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function zi(a){if(typeof atob=="function"){let e=atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(a,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Xi(a){let e=a.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",n=e[2]??"";try{let r=/;base64/i.test(t)?zi(n):decodeURIComponent(n);return JSON.parse(r)}catch{try{return JSON.parse(n)}catch{return null}}}function Cs(a){let e=a?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Xi(e);return t?Hn(yr(t)):null}var Qi=12,Ji=6e3;async function Zi(a,e,t){let n=new Array(a.length),r=0,o=new Array(Math.max(1,Math.min(e,a.length))).fill(0).map(async()=>{for(;r<a.length;){let s=r++;n[s]=await t(a[s],s)}});return await Promise.all(o),n}async function el(a,e){try{let t=await x.get(a,{timeout:e});if(!t.ok)return null;let n=t.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function tl(a,e){let t=a?.trim();if(!t)return null;if(/^data:/i.test(t))return Cs(t);let n=Ps(t);if(!n)return null;if(xs(n))return n;let r=await el(n,e);if(r){let o=Hn(yr(r));if(o)return o}return null}async function _s(a,e,t){if(e.length===0)return[];let n=t?.concurrency??Qi,r=t?.timeoutMs??Ji,o=await ns(a,e,t?.rpcUrl);return Zi(o,n,s=>tl(s,r))}var Es=100,nl=100,Wt="{name}",Rs="{chain}",Ht=class extends v{name="get-wallet-nfts";description=`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`;category="nft";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Y(e.address,t),r=re(e.chain,t),o=r?[r]:de(),s=ll(e.contract_address),i=Is(e.collection_name);return s||i?this.listNfts({address:n,chains:o,singleChain:!!r,contract:s,collectionName:i}):this.listCollections({address:n,chains:o,singleChain:!!r,args:e})}async listCollections(e){let{address:t,chains:n,singleChain:r,args:o}=e,s=await Promise.all(n.map(async c=>{let d=await this.service.getWalletNftCollections({address:t,chain:c,limit:Es});return{chain:c,rows:d.success?Ns(d.data?.result??[]):[],ok:d.success}}));if(r&&!s[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=s.flatMap(c=>c.rows.map(d=>({name:rl(d),contractAddress:d.token_address,chain:P(c.chain),nftCount:d.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(r?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=al(i,o);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:n,singleChain:r,contract:o,collectionName:s}=e,i=await Promise.all(n.map(async m=>{let f=await this.service.getWalletNFTs({address:t,chain:m,limit:Es,...o?{tokenAddresses:[o]}:{}});return{chain:m,rows:f.success?Ns(f.data?.result??[]):[],ok:f.success}}));if(r&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>ol(f,{contract:o,collectionName:s})).map(f=>({chain:m.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${s??o??""}"`+(r?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||s||l[0].row.token_address,d=await this.resolveOnchainImages(l),u=l.map(({chain:m,row:f},h)=>{let g=sl(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:d[h]??g.image,chain:P(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:u}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),n=new Map;e.forEach((r,o)=>{let s=n.get(r.chain)??[];s.push(o),n.set(r.chain,s)});try{await Promise.all([...n.entries()].map(async([r,o])=>{let s=o.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await _s(r,s);o.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Ns(a){return a.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function ol(a,e){if(e.contract)return a.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(a.name??"").toLowerCase().includes(t)}return!1}function rl(a){let e=a.name?.trim();if(e)return e;let t=a.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function sl(a){return{name:a.normalized_metadata?.name||a.name||`#${a.token_id}`,tokenId:a.token_id,contractAddress:a.token_address,image:Hn(a.normalized_metadata?.image||a.media?.original_media_url)}}function al(a,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",r=[];for(let o of a){if(r.length>=nl)break;if(!o.contractAddress)continue;let s=typeof o.chain=="string"?o.chain.trim():"",i=s?`show my ${Wt} NFTs on ${Rs}`:`show my ${Wt} NFTs`,l=Us(n,{[Wt]:o.name,[Rs]:s},i);s&&!l.includes(s)&&(l=`${l} (${s})`),r.push({label:il(t,o.name,Wt),prompt:`${l} (${o.contractAddress})`})}return r}function Us(a,e,t){let n=a&&a.includes(Wt)?a:t;for(let[r,o]of Object.entries(e))n=n.split(r).join(o);return n.replace(/\s+/g," ").trim()}function il(a,e,t){return Us(a,{[Wt]:e},t)}function Is(a){if(typeof a!="string")return;let e=a.trim();return e||void 0}function ll(a){let e=Is(a);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var cl="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",Oe=class extends v{kind="data";category="nft";llm;constructor(e){super(),this.llm=new z(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:cl,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Gt=class extends Oe{name="get-nft-contract-info";description='Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.';parameters=Oe.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`);presentInstructions="Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks."};var Yt=class extends Oe{name="get-nft-metadata";description='Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.';parameters=Oe.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`);presentInstructions="Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points."};var br={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},wr="amazon.com";function ul(a){return a?a.trim().toLowerCase().split(/[-_]/)[0]:""}function kr(a){let e=ul(a);return br[e]??wr}function To(a){return`https://${kr(a)}/s?k=NFC%20Tag`}function vo(a){if(!a)return"";let e=a.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var dl=720*60*1e3,Ls=new Map,Ds=3;function pl(a){return[`A user in country "${a}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Ds} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function ml(a){if(!a)return[];let e=a.indexOf("["),t=a.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(a.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let r=[],o=new Set;for(let s of n){if(!s||typeof s!="object")continue;let i=s.label,l=s.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!o.has(c)&&(o.add(c),r.push({label:i.trim(),url:l.trim()}),r.length>=Ds))break}return r}async function Tr(a,e){let t=vo(a);if(!t||!e)return null;let n=Ls.get(t);if(n&&n.expires>Date.now())return n.links;let r=Date.now(),o=[{role:"user",content:pl(t),timestamp:r}];try{let s=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),i=ml(s.text);if(i.length)return Ls.set(t,{links:i,expires:Date.now()+dl}),i}catch{}return null}async function jt(a){let e=await Tr(a.country,a.llm);return e&&e.length?e:[{label:"Amazon",url:To(a.language)}]}function hl(a){return a.length<=1?a.length===1?`[${a[0].label}](${a[0].url})`:"":a.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
17
17
  `)}var Os=["WHAT IT IS: NFC (Near-Field Communication) is a short-range wireless standard operating at 13.56 MHz, a",'subset of the older RFID family. An "NFC tag" is a tiny passive chip + antenna (often embedded in a','sticker, card, keyfob, wristband, or ring). "Passive" means it has no battery \u2014 it draws all its power from',"the electromagnetic field of the reader (a smartphone or dedicated reader) when held within ~2\u20134 cm. The","tag does nothing on its own; it simply waits to be tapped, then hands over the small piece of data it holds.","","HOW IT WORKS: When an NFC-enabled phone comes close, the reader emits a 13.56 MHz radio field. Through","inductive (magnetic) coupling that field powers the tag, which then transmits its stored data back to the","reader \u2014 no pairing, no app launch, no internet required for the handshake. The exchange is bidirectional","and near-instant (well under a second). Tags can be READ many times and, unless locked, also re-WRITTEN.","Data is stored in the standardised NDEF format (NFC Data Exchange Format) so any NFC phone can parse it the","same way. NFC works in three modes: reader/writer (phone reads or writes a tag), peer-to-peer (two devices","exchange data), and card-emulation (the phone itself acts like a tag, e.g. for tap-to-pay).","","WHAT'S INSIDE AN NFC TAG: just two parts \u2014 (1) a microchip (the integrated circuit) that holds a small","block of memory plus simple logic, and (2) a thin coiled antenna (usually etched copper or aluminium) that","both harvests power from the reader's field and carries the data signal. There is no battery and no moving","parts, which is why tags are paper-thin, cheap, and last for years (often rated for ~10 years of storage","and 100,000+ rewrites). Common chips differ mainly by memory size: NTAG213 (~144 bytes), NTAG215","(~504 bytes), NTAG216 (~888 bytes); larger/industrial families (e.g. ICODE, MIFARE) add more memory or","security features.","","WHAT IT CAN STORE: capacity is small \u2014 tens to a few hundred bytes of usable memory \u2014 so a tag holds a","compact payload, not files. Typical contents: a website URL, plain text, a contact card (vCard), Wi-Fi","credentials (SSID + password for one-tap join), an app-launch or deep link, a phone number / email,","geo-coordinates, a Bluetooth pairing handoff, or a small identifier/token. It is NOT mass storage \u2014 large","content lives elsewhere and the tag holds a pointer (a link or ID) to it.","","COMMON REAL-WORLD USES: contactless payments (Apple Pay / Google Pay via card emulation); transit and","access cards (metro, office door badges, hotel keys); product tags and anti-counterfeit / authenticity","checks; smart posters and marketing (tap to open a page, menu, or promo); pairing speakers/headphones with",'one tap; digital business cards and "tap to share contact"; smart-home automations (tap a tag by the door',"to run a routine); inventory, asset tracking, and ticketing; and tap-to-act crypto flows (e.g. open a","wallet address or a dapp link).","","HOW TO USE ONE: (1) Get an NFC tag (sticker/card/keyfob). (2) Make sure the phone has NFC enabled","(Settings \u2192 Connections/NFC; most modern Android phones and iPhone XS and later support it). (3) To WRITE,",'install an NFC writer app (e.g. "NFC Tools"), choose the record type (URL, text, Wi-Fi\u2026), enter the data,',"and tap the phone to the tag to program it. (4) To READ, just tap the phone to the tag \u2014 the action fires","automatically. (5) Optionally LOCK the tag to make it read-only so the data cannot be overwritten. Keep the","tag away from metal surfaces, which can detune the antenna and block reads.","","WHY THEY ARE POPULAR: they are extremely cheap (cents each), battery-free and maintenance-free, work with","the phone almost everyone already carries, and need just a tap \u2014 no app pairing, codes, or setup. The very","short range is a feature, not a bug: you must deliberately bring the devices together, which makes NFC","trusted for payments and access where accidental or remote reads would be a security risk.","","CRYPTO / WALLET CONTEXT: because a tag can hold a short identifier or address, NFC is handy for tap-to-act","flows \u2014 e.g. encoding a public wallet address or a deep link. Private keys/seed phrases should never be","written to an open, re-writable tag; treat tags as public, tamper-readable pointers, not secure key vaults.","","PRACTICAL TIPS: re-writable blank tags are inexpensive; pick a chip with enough memory for the payload",'(NTAG215+ for longer URLs or vCards). Use a metal-shielded ("on-metal") tag if you must stick it to a',"metal surface. Range is intentionally tiny (a few cm) for security \u2014 you must deliberately tap."].join(`
18
18
  `),Kt=class extends v{kind="data";name="nfc-info";category="nfc";description='Use when the user asks a conceptual / how-to question about NFC tags \u2014 what an NFC tag is, how NFC works, what data a tag can store, tag types/capacity, or how to read/write/use one ("what is an NFC tag", "how does NFC work", "what can I store on an NFC tag", "how do I use an NFC tag"). Returns an expert reference to answer from, plus a country-appropriate Amazon buy link to close with. Pass the current turn\'s BCP-47 `language` so the right storefront is picked. For a pure "where to buy" question with no explanation needed, prefer nfc-buy-link.';parameters=[{name:"language",type:"string",description:`The BCP-47 language tag of the user's current message (e.g. "en", "vi", "ja", "zh", "de"). Used only to pick the local Amazon storefront for the closing buy link. Optional (defaults to amazon.com).`,required:!1}];llm;constructor(e){super(),e&&(this.llm=new z(e))}async run(e,t){let n=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,r=await jt({country:t?.country,language:n,llm:this.llm}),o=hl(r),s=r.length>1;return{reference:Os,marketplaceLinks:r,_instructions:`Answer the user's NFC question as a knowledgeable, friendly expert, writing in the USER'S language (translate naturally \u2014 never leave it in English when they wrote another language). Draw on the reference below for the facts (do NOT invent anything beyond it), but write a polished, well-organized answer \u2014 not a terse one-liner. FORMAT: Use short Markdown section headings (bold or "##") and bullet points so it is easy to scan, similar to a great encyclopedia entry. For a broad question like "what is an NFC tag", give a thorough multi-section answer: open with a 1\u20132 sentence plain-language definition, then cover sections such as "How it works", "What's inside", "What it can store", "Common uses", "How to use one", and "Why they're popular" \u2014 include concrete specifics (the 13.56 MHz frequency, chip names + byte capacities, example payloads, numbered steps). Aim for genuinely useful depth, several short paragraphs/lists, not a wall of dense text. For a NARROW question (e.g. only "what can it store" or "how do I write one"), answer just that part in focused detail and skip the unrelated sections. Do not mention tools, this reference, or that anything is canned. AT THE END, add a short closing line telling them where they can buy NFC tags, then include EACH of these exact CLICKABLE Markdown links `+(s?"as a NUMBERED Markdown list (1., 2., 3.), ONE store per line, in this exact order and numbering":"inline")+` (keep every URL byte-for-byte; localize only the visible text; keep the form [text](url)):
19
19
  ${o}
@@ -117,7 +117,7 @@ ${$s}`,Sl=`query V4Pool($chain: Chain!, $poolId: String!) {
117
117
  __typename
118
118
  }
119
119
  }
120
- ${$s}`,Jt={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function So(a){return new Promise(e=>setTimeout(e,a))}function vr(a){if(!a)return 1;let e=a.toLowerCase();return Jt[e]??1}function Ar(a){if(!a)return"ETHEREUM";let e=a.toLowerCase();return Tl[e]??"ETHEREUM"}function Fs(a,e){if(!a)return[];switch(e){case"V2":return a.poolStatsV2??[];case"V3":return a.poolStatsV3??[];case"V4":return a.poolStatsV4??[]}}function qs(a,e){switch(e){case"volume1Day":return a.volume1Day?.value??0;case"volume1Week":return a.volume1Week?.value??0;case"volume30Day":return a.volume30Day?.value??0;case"txCount":return a.txCount??0;case"apr":return a.apr??0;default:return a.totalLiquidity?.value??0}}function Bs(a){let e=a.volume1Day?.value,t=a.totalLiquidity?.value;return typeof a.feeTier!="number"||!e||!t?void 0:a.feeTier/1e4*e/t*365}var pe=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??bl).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=$(e)??e.toLowerCase();return Object.prototype.hasOwnProperty.call(Jt,t)}listSupportedChains(){return Object.keys(Jt).filter(e=>_e(e))}async getExploreStats(e){let t=vr(e?.chain),n=e?.multichain===!0,r=encodeURIComponent(JSON.stringify({chainId:String(t),multichain:n})),o=`${this.baseUrl}${wl}?connect=v1&encoding=json&message=${r}`,s="Unknown error";for(let i=1;i<=Je;i++)try{let l=await x.get(o,{headers:{accept:"*/*",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!l.ok)throw new Error(I(l));return{success:!0,data:l.data}}catch(l){s=l instanceof Error?l.message:"Unknown error",i<Je&&await So(Ao)}return{success:!1,error:s}}async getTopPools(e){let t=e?.protocolVersion??"V3",n=e?.limit&&e.limit>0?Math.floor(e.limit):10,r=e?.sortBy??"tvl",o=await this.getExploreStats({chain:e?.chain,multichain:e?.multichain});return!o.success||!o.data?{success:!1,error:o.error||"Failed to fetch ExploreStats"}:{success:!0,data:Fs(o.data.stats,t).map(l=>({...l,apr:Bs(l),fee24hUsd:l.volume1Day?.value&&l.feeTier?l.feeTier/1e4*l.volume1Day.value:void 0})).sort((l,c)=>qs(c,r)-qs(l,r)).slice(0,n)}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:vl,variables:{chain:Ar(e.chain),address:t},pickField:"v3Pool"}):{success:!1,error:"Pool address is required"}}async getV2PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V2Pair",query:Al,variables:{chain:Ar(e.chain),address:t},pickField:"v2Pair"}):{success:!1,error:"Pair address is required"}}async getV4PoolDetail(e){let t=e.poolId?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V4Pool",query:Sl,variables:{chain:Ar(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${kl}`,n=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),r="Unknown error";for(let o=1;o<=Je;o++)try{let s=await x.post(t,n,{headers:{accept:"*/*","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web","_dd-custom-header-graph-ql-operation-name":e.operationName,"_dd-custom-header-graph-ql-operation-type":"query"}});if(!s.ok)throw new Error(I(s));let i=s.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let l=i.data?.[e.pickField]??void 0;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(s){r=s instanceof Error?s.message:"Unknown error",o<Je&&await So(Ao)}return{success:!1,error:r}}async searchTokens(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};if(q(t))return{success:!1,error:"Address is invalid for token search. If you pasted a 0x address, it may be a Uniswap pool \u2014 try the pool search tool instead."};let n=vr(e.chain),r=e.page&&e.page>0?Math.floor(e.page):1,o=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,s=`${this.baseUrl}${Ms}`,i=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"TOKEN",page:r,size:o}),l="Unknown error";for(let c=1;c<=Je;c++)try{let u=await x.post(s,i,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!u.ok)throw new Error(I(u));return{success:!0,data:u.data.tokens??[]}}catch(u){l=u instanceof Error?u.message:"Unknown error",c<Je&&await So(Ao)}return{success:!1,error:l}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let n=vr(e.chain),r=e.page&&e.page>0?Math.floor(e.page):1,o=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,s=e.protocolVersion??"V3",i=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=`${this.baseUrl}${Ms}`,c=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"POOL",page:r,size:o}),[u,d]=await Promise.allSettled([this.fetchSearchPools(l,c),this.getExploreStats({chain:e.chain})]);if(u.status==="rejected"||!u.value.success)return{success:!1,error:u.status==="rejected"?String(u.reason):u.value.error??"Failed to search pools"};let p=t.toLowerCase().split(/\s+/).filter(Boolean),m=u.value.data??[];s!=="ALL"&&(m=m.filter(g=>g.protocolVersion===s)),i!=null&&(m=m.filter(g=>g.feeTier===i));let f=new Map;for(let g of m)g.id&&f.set(g.id.toLowerCase(),g);if(d.status==="fulfilled"&&d.value.success&&d.value.data){let g=d.value.data.stats,y=s==="ALL"?["V2","V3","V4"]:[s];for(let b of y)for(let w of Fs(g,b)){if(!w.id||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),T=(w.token1?.symbol??"").toLowerCase(),S=(w.token0?.name??"").toLowerCase(),A=(w.token1?.name??"").toLowerCase();if(!p.some(E=>k.includes(E)||T.includes(E)||S.includes(E)||A.includes(E)))continue;let R=Bs(w),C=w.id.toLowerCase(),M=f.get(C);M?f.set(C,{...M,...R!=null?{apr:R}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}}):f.set(C,{id:w.id,protocolVersion:w.protocolVersion,feeTier:w.feeTier,token0:w.token0?{address:w.token0.address,symbol:w.token0.symbol,name:w.token0.name,decimals:w.token0.decimals}:void 0,token1:w.token1?{address:w.token1.address,symbol:w.token1.symbol,name:w.token1.name,decimals:w.token1.decimals}:void 0,...R!=null?{apr:R}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}})}}return{success:!0,data:Array.from(f.values()).sort((g,y)=>this.matchScore(y,p)-this.matchScore(g,p))}}async fetchSearchPools(e,t){let n="Unknown error";for(let r=1;r<=Je;r++)try{let o=await x.post(e,t,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!o.ok)throw new Error(I(o));return{success:!0,data:o.data.pools??[]}}catch(o){n=o instanceof Error?o.message:"Unknown error",r<Je&&await So(Ao)}return{success:!1,error:n}}matchScore(e,t){let n=[e.token0?.symbol??"",e.token1?.symbol??""].map(o=>o.toLowerCase()),r=0;for(let o of t){let s=0;for(let i of n)i===o?s=Math.max(s,3):i.startsWith(o)?s=Math.max(s,2):i.includes(o)&&(s=Math.max(s,1));r+=s}return r}};var Pl={"0x1":"https://gateway.thegraph.com/api/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV","0xa4b1":"https://gateway.thegraph.com/api/subgraphs/id/FbCGRftH4a3yZugY7TnbYgPJVEv2LvMT6oF1fxPe9aJM","0x89":"https://gateway.thegraph.com/api/subgraphs/id/3hCPRGf4z88VC5rsBKU5AA9FBBq5nF3jbKJG7VZCbhjm","0x38":"https://gateway.thegraph.com/api/subgraphs/id/GcKPSgHoY42xNYVAkSPDhXSzi6aJDRQSKqBSXezL47gV","0x2105":"https://gateway.thegraph.com/api/subgraphs/id/HMuAwufqZ1YCRmzL2SfHTVkzZovC9VL2UAKhjvRqKiR1","0xa":"https://gateway.thegraph.com/api/subgraphs/id/Cghf4LfVqPiFw6fp6Y5X5Ubc8UpmUhSfJL82zwiBFLaj","0xa86a":"https://gateway.thegraph.com/api/subgraphs/id/GVH9h9KZ9CqheUEL93qMbq7QwgoBu32QXQDPR6bev4Eo"},xl={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},Cl={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},Vs={"0x1":"0x1",1:"0x1",eth:"0x1",ethereum:"0x1",mainnet:"0x1","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","0x38":"0x38",56:"0x38",bnb:"0x38",bsc:"0x38","0x2105":"0x2105",8453:"0x2105",base:"0x2105","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a"},Ws={100:.01,500:.05,3e3:.3,1e4:1},_l={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},El=300*1e3,ne=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...Pl,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([n])=>_e(n))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return Vs[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),n=Vs[t];return!!(n&&this.subgraphUrls[n])}chainName(e){let t=this.resolveChain(e);return xl[t]||t}numericChainId(e){return Cl[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let n=this.resolveChain(e),r=this.subgraphUrls[n];if(!r)throw new Error(`No subgraph available for chain: ${e}`);let o=await x.post(r,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Subgraph query failed: ${I(o)}`);let s=o.data;if(s.errors&&s.errors.length>0)throw new Error(`Subgraph error: ${s.errors[0].message||"Unknown"}`);return s.data}poolFragment(){return`
120
+ ${$s}`,Jt={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function So(a){return new Promise(e=>setTimeout(e,a))}function vr(a){if(!a)return 1;let e=a.toLowerCase();return Jt[e]??1}function Ar(a){if(!a)return"ETHEREUM";let e=a.toLowerCase();return Tl[e]??"ETHEREUM"}function Fs(a,e){if(!a)return[];switch(e){case"V2":return a.poolStatsV2??[];case"V3":return a.poolStatsV3??[];case"V4":return a.poolStatsV4??[]}}function qs(a,e){switch(e){case"volume1Day":return a.volume1Day?.value??0;case"volume1Week":return a.volume1Week?.value??0;case"volume30Day":return a.volume30Day?.value??0;case"txCount":return a.txCount??0;case"apr":return a.apr??0;default:return a.totalLiquidity?.value??0}}function Bs(a){let e=a.volume1Day?.value,t=a.totalLiquidity?.value;return typeof a.feeTier!="number"||!e||!t?void 0:a.feeTier/1e4*e/t*365}var pe=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??bl).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=$(e)??e.toLowerCase();return Object.prototype.hasOwnProperty.call(Jt,t)}listSupportedChains(){return Object.keys(Jt).filter(e=>_e(e))}async getExploreStats(e){let t=vr(e?.chain),n=e?.multichain===!0,r=encodeURIComponent(JSON.stringify({chainId:String(t),multichain:n})),o=`${this.baseUrl}${wl}?connect=v1&encoding=json&message=${r}`,s="Unknown error";for(let i=1;i<=Je;i++)try{let l=await x.get(o,{headers:{accept:"*/*",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!l.ok)throw new Error(I(l));return{success:!0,data:l.data}}catch(l){s=l instanceof Error?l.message:"Unknown error",i<Je&&await So(Ao)}return{success:!1,error:s}}async getTopPools(e){let t=e?.protocolVersion??"V3",n=e?.limit&&e.limit>0?Math.floor(e.limit):10,r=e?.sortBy??"tvl",o=await this.getExploreStats({chain:e?.chain,multichain:e?.multichain});return!o.success||!o.data?{success:!1,error:o.error||"Failed to fetch ExploreStats"}:{success:!0,data:Fs(o.data.stats,t).map(l=>({...l,apr:Bs(l),fee24hUsd:l.volume1Day?.value&&l.feeTier?l.feeTier/1e4*l.volume1Day.value:void 0})).sort((l,c)=>qs(c,r)-qs(l,r)).slice(0,n)}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:vl,variables:{chain:Ar(e.chain),address:t},pickField:"v3Pool"}):{success:!1,error:"Pool address is required"}}async getV2PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V2Pair",query:Al,variables:{chain:Ar(e.chain),address:t},pickField:"v2Pair"}):{success:!1,error:"Pair address is required"}}async getV4PoolDetail(e){let t=e.poolId?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V4Pool",query:Sl,variables:{chain:Ar(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${kl}`,n=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),r="Unknown error";for(let o=1;o<=Je;o++)try{let s=await x.post(t,n,{headers:{accept:"*/*","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web","_dd-custom-header-graph-ql-operation-name":e.operationName,"_dd-custom-header-graph-ql-operation-type":"query"}});if(!s.ok)throw new Error(I(s));let i=s.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let l=i.data?.[e.pickField]??void 0;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(s){r=s instanceof Error?s.message:"Unknown error",o<Je&&await So(Ao)}return{success:!1,error:r}}async searchTokens(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};if(q(t))return{success:!1,error:"Address is invalid for token search. If you pasted a 0x address, it may be a Uniswap pool \u2014 try the pool search tool instead."};let n=vr(e.chain),r=e.page&&e.page>0?Math.floor(e.page):1,o=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,s=`${this.baseUrl}${Ms}`,i=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"TOKEN",page:r,size:o}),l="Unknown error";for(let c=1;c<=Je;c++)try{let d=await x.post(s,i,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!d.ok)throw new Error(I(d));return{success:!0,data:d.data.tokens??[]}}catch(d){l=d instanceof Error?d.message:"Unknown error",c<Je&&await So(Ao)}return{success:!1,error:l}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let n=vr(e.chain),r=e.page&&e.page>0?Math.floor(e.page):1,o=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,s=e.protocolVersion??"V3",i=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=`${this.baseUrl}${Ms}`,c=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"POOL",page:r,size:o}),[d,u]=await Promise.allSettled([this.fetchSearchPools(l,c),this.getExploreStats({chain:e.chain})]);if(d.status==="rejected"||!d.value.success)return{success:!1,error:d.status==="rejected"?String(d.reason):d.value.error??"Failed to search pools"};let p=t.toLowerCase().split(/\s+/).filter(Boolean),m=d.value.data??[];s!=="ALL"&&(m=m.filter(g=>g.protocolVersion===s)),i!=null&&(m=m.filter(g=>g.feeTier===i));let f=new Map;for(let g of m)g.id&&f.set(g.id.toLowerCase(),g);if(u.status==="fulfilled"&&u.value.success&&u.value.data){let g=u.value.data.stats,y=s==="ALL"?["V2","V3","V4"]:[s];for(let b of y)for(let w of Fs(g,b)){if(!w.id||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),T=(w.token1?.symbol??"").toLowerCase(),S=(w.token0?.name??"").toLowerCase(),A=(w.token1?.name??"").toLowerCase();if(!p.some(E=>k.includes(E)||T.includes(E)||S.includes(E)||A.includes(E)))continue;let R=Bs(w),C=w.id.toLowerCase(),M=f.get(C);M?f.set(C,{...M,...R!=null?{apr:R}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}}):f.set(C,{id:w.id,protocolVersion:w.protocolVersion,feeTier:w.feeTier,token0:w.token0?{address:w.token0.address,symbol:w.token0.symbol,name:w.token0.name,decimals:w.token0.decimals}:void 0,token1:w.token1?{address:w.token1.address,symbol:w.token1.symbol,name:w.token1.name,decimals:w.token1.decimals}:void 0,...R!=null?{apr:R}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}})}}return{success:!0,data:Array.from(f.values()).sort((g,y)=>this.matchScore(y,p)-this.matchScore(g,p))}}async fetchSearchPools(e,t){let n="Unknown error";for(let r=1;r<=Je;r++)try{let o=await x.post(e,t,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!o.ok)throw new Error(I(o));return{success:!0,data:o.data.pools??[]}}catch(o){n=o instanceof Error?o.message:"Unknown error",r<Je&&await So(Ao)}return{success:!1,error:n}}matchScore(e,t){let n=[e.token0?.symbol??"",e.token1?.symbol??""].map(o=>o.toLowerCase()),r=0;for(let o of t){let s=0;for(let i of n)i===o?s=Math.max(s,3):i.startsWith(o)?s=Math.max(s,2):i.includes(o)&&(s=Math.max(s,1));r+=s}return r}};var Pl={"0x1":"https://gateway.thegraph.com/api/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV","0xa4b1":"https://gateway.thegraph.com/api/subgraphs/id/FbCGRftH4a3yZugY7TnbYgPJVEv2LvMT6oF1fxPe9aJM","0x89":"https://gateway.thegraph.com/api/subgraphs/id/3hCPRGf4z88VC5rsBKU5AA9FBBq5nF3jbKJG7VZCbhjm","0x38":"https://gateway.thegraph.com/api/subgraphs/id/GcKPSgHoY42xNYVAkSPDhXSzi6aJDRQSKqBSXezL47gV","0x2105":"https://gateway.thegraph.com/api/subgraphs/id/HMuAwufqZ1YCRmzL2SfHTVkzZovC9VL2UAKhjvRqKiR1","0xa":"https://gateway.thegraph.com/api/subgraphs/id/Cghf4LfVqPiFw6fp6Y5X5Ubc8UpmUhSfJL82zwiBFLaj","0xa86a":"https://gateway.thegraph.com/api/subgraphs/id/GVH9h9KZ9CqheUEL93qMbq7QwgoBu32QXQDPR6bev4Eo"},xl={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},Cl={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},Vs={"0x1":"0x1",1:"0x1",eth:"0x1",ethereum:"0x1",mainnet:"0x1","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","0x38":"0x38",56:"0x38",bnb:"0x38",bsc:"0x38","0x2105":"0x2105",8453:"0x2105",base:"0x2105","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a"},Ws={100:.01,500:.05,3e3:.3,1e4:1},_l={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},El=300*1e3,ne=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...Pl,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([n])=>_e(n))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return Vs[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),n=Vs[t];return!!(n&&this.subgraphUrls[n])}chainName(e){let t=this.resolveChain(e);return xl[t]||t}numericChainId(e){return Cl[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let n=this.resolveChain(e),r=this.subgraphUrls[n];if(!r)throw new Error(`No subgraph available for chain: ${e}`);let o=await x.post(r,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Subgraph query failed: ${I(o)}`);let s=o.data;if(s.errors&&s.errors.length>0)throw new Error(`Subgraph error: ${s.errors[0].message||"Unknown"}`);return s.data}poolFragment(){return`
121
121
  id
122
122
  token0 { id symbol name }
123
123
  token1 { id symbol name }
@@ -134,16 +134,16 @@ ${$s}`,Jt={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
134
134
  volumeToken0
135
135
  volumeToken1
136
136
  }
137
- `}hasValidVolume(e){let t=e.poolDayData?.[0];return t?parseFloat(t.volumeToken0||"0")!==0&&parseFloat(t.volumeToken1||"0")!==0&&parseFloat(t.volumeUSD||"0")!==0:!1}sanitize(e){return!isFinite(e)||isNaN(e)||e>1e11?0:e}mapPool(e,t){let n=e,r=Number(n.feeTier||0),o=Ws[r]??r/1e4,s=this.sanitize(parseFloat(n.totalValueLockedUSD||"0")),i=n.poolDayData?.[0],l=parseFloat(i?.volumeUSD||"0"),c=parseFloat(i?.feesUSD||"0"),u=null;return s>0&&c>0&&(u=parseFloat((c*365*100/s).toFixed(2))),{poolAddress:n.id,pair:`${n.token0.symbol}/${n.token1.symbol}`,token0:{symbol:n.token0.symbol,address:n.token0.id,name:n.token0.name},token1:{symbol:n.token1.symbol,address:n.token1.id,name:n.token1.name},tvl:s,volume24hUsd:l,fees24hUsd:c,apr:u,feeTierBps:r,feeTierPercent:o,liquidity:n.liquidity||"0",chain:this.chainName(t)}}async fetchDefiLlamaUniswap(){let e=Date.now();if(this.llamaCache&&e-this.llamaCacheAt<El)return this.llamaCache;try{let t=await x.get("https://yields.llama.fi/pools");if(!t.ok)throw new Error(`DefiLlama: ${I(t)}`);let r=(t.data.data||[]).filter(o=>o.project==="uniswap-v3");return this.llamaCache=r,this.llamaCacheAt=e,r}catch{return this.llamaCache??[]}}parseLlamaFeeTier(e){if(!e)return null;let t=e.match(/^([\d.]+)%/);return t?Math.round(parseFloat(t[1])*1e4):null}enrichWithLlama(e,t){return t.length?e.map(n=>{let r=this.resolveChain(n.chain),o=n.feeTierBps,s=n.token0.address.toLowerCase(),i=n.token1.address.toLowerCase(),l=t.filter(p=>_l[p.chain.toLowerCase()]===r),c=l.find(p=>{if(!p.underlyingTokens||p.underlyingTokens.length<2)return!1;let m=p.underlyingTokens.map(h=>h.toLowerCase());if(!(m.includes(s)&&m.includes(i)))return!1;let f=this.parseLlamaFeeTier(p.poolMeta);return f===null||f===o});if(!c){let p=n.token0.symbol.toUpperCase(),m=n.token1.symbol.toUpperCase(),f=[p,m].sort().join("-");c=l.find(h=>{if([...h.symbol.split("-").map(b=>b.toUpperCase())].sort().join("-")!==f)return!1;let y=this.parseLlamaFeeTier(h.poolMeta);return y===null||y===o})}if(!c)return n;let u=c.apyBase??c.apy??null,d={...n};return u!==null&&(d.apr=parseFloat(u.toFixed(2))),c.tvlUsd!=null&&(d.tvl=this.sanitize(c.tvlUsd)),c.volumeUsd1d!=null&&(d.volume24hUsd=this.sanitize(c.volumeUsd1d)),d}):e}async searchPools(e){let{tokens:t,chain:n,sortBy:r,filters:o}=e,s=this.resolveChain(n),i=t.map(h=>{let g=h.toUpperCase(),y=new Set([g]);return g.startsWith("W")||y.add("W"+g),g.startsWith("W")&&g.length>1&&y.add(g.slice(1)),[...y]}),l=['totalValueLockedUSD_gt: "10000"','liquidity_gt: "0"','volumeUSD_gt: "0"'];o?.feeTier&&l.push(`feeTier: "${o.feeTier}"`);let c="totalValueLockedUSD";r==="volume"?c="volumeUSD":r==="fee"?c="feeTier":r==="liquidity"&&(c="liquidity");let u=r==="fee"?"asc":"desc",d=h=>h.length===1?`symbol: "${h[0]}"`:`symbol_in: [${h.map(g=>`"${g}"`).join(", ")}]`,p=(h,g)=>`{
137
+ `}hasValidVolume(e){let t=e.poolDayData?.[0];return t?parseFloat(t.volumeToken0||"0")!==0&&parseFloat(t.volumeToken1||"0")!==0&&parseFloat(t.volumeUSD||"0")!==0:!1}sanitize(e){return!isFinite(e)||isNaN(e)||e>1e11?0:e}mapPool(e,t){let n=e,r=Number(n.feeTier||0),o=Ws[r]??r/1e4,s=this.sanitize(parseFloat(n.totalValueLockedUSD||"0")),i=n.poolDayData?.[0],l=parseFloat(i?.volumeUSD||"0"),c=parseFloat(i?.feesUSD||"0"),d=null;return s>0&&c>0&&(d=parseFloat((c*365*100/s).toFixed(2))),{poolAddress:n.id,pair:`${n.token0.symbol}/${n.token1.symbol}`,token0:{symbol:n.token0.symbol,address:n.token0.id,name:n.token0.name},token1:{symbol:n.token1.symbol,address:n.token1.id,name:n.token1.name},tvl:s,volume24hUsd:l,fees24hUsd:c,apr:d,feeTierBps:r,feeTierPercent:o,liquidity:n.liquidity||"0",chain:this.chainName(t)}}async fetchDefiLlamaUniswap(){let e=Date.now();if(this.llamaCache&&e-this.llamaCacheAt<El)return this.llamaCache;try{let t=await x.get("https://yields.llama.fi/pools");if(!t.ok)throw new Error(`DefiLlama: ${I(t)}`);let r=(t.data.data||[]).filter(o=>o.project==="uniswap-v3");return this.llamaCache=r,this.llamaCacheAt=e,r}catch{return this.llamaCache??[]}}parseLlamaFeeTier(e){if(!e)return null;let t=e.match(/^([\d.]+)%/);return t?Math.round(parseFloat(t[1])*1e4):null}enrichWithLlama(e,t){return t.length?e.map(n=>{let r=this.resolveChain(n.chain),o=n.feeTierBps,s=n.token0.address.toLowerCase(),i=n.token1.address.toLowerCase(),l=t.filter(p=>_l[p.chain.toLowerCase()]===r),c=l.find(p=>{if(!p.underlyingTokens||p.underlyingTokens.length<2)return!1;let m=p.underlyingTokens.map(h=>h.toLowerCase());if(!(m.includes(s)&&m.includes(i)))return!1;let f=this.parseLlamaFeeTier(p.poolMeta);return f===null||f===o});if(!c){let p=n.token0.symbol.toUpperCase(),m=n.token1.symbol.toUpperCase(),f=[p,m].sort().join("-");c=l.find(h=>{if([...h.symbol.split("-").map(b=>b.toUpperCase())].sort().join("-")!==f)return!1;let y=this.parseLlamaFeeTier(h.poolMeta);return y===null||y===o})}if(!c)return n;let d=c.apyBase??c.apy??null,u={...n};return d!==null&&(u.apr=parseFloat(d.toFixed(2))),c.tvlUsd!=null&&(u.tvl=this.sanitize(c.tvlUsd)),c.volumeUsd1d!=null&&(u.volume24hUsd=this.sanitize(c.volumeUsd1d)),u}):e}async searchPools(e){let{tokens:t,chain:n,sortBy:r,filters:o}=e,s=this.resolveChain(n),i=t.map(h=>{let g=h.toUpperCase(),y=new Set([g]);return g.startsWith("W")||y.add("W"+g),g.startsWith("W")&&g.length>1&&y.add(g.slice(1)),[...y]}),l=['totalValueLockedUSD_gt: "10000"','liquidity_gt: "0"','volumeUSD_gt: "0"'];o?.feeTier&&l.push(`feeTier: "${o.feeTier}"`);let c="totalValueLockedUSD";r==="volume"?c="volumeUSD":r==="fee"?c="feeTier":r==="liquidity"&&(c="liquidity");let d=r==="fee"?"asc":"desc",u=h=>h.length===1?`symbol: "${h[0]}"`:`symbol_in: [${h.map(g=>`"${g}"`).join(", ")}]`,p=(h,g)=>`{
138
138
  pools(
139
139
  first: ${g}
140
140
  orderBy: ${c}
141
- orderDirection: ${u}
141
+ orderDirection: ${d}
142
142
  where: { ${[...l,...h].join(", ")} }
143
143
  ) {
144
144
  ${this.poolFragment()}
145
145
  }
146
- }`,m;if(i.length>0){let g,y;i.length>=2?(g=p([`token0_: { ${d(i[0])} }`,`token1_: { ${d(i[1])} }`],100),y=p([`token0_: { ${d(i[1])} }`,`token1_: { ${d(i[0])} }`],100)):(g=p([`token0_: { ${d(i[0])} }`],100),y=p([`token1_: { ${d(i[0])} }`],100));let[b,w]=await Promise.allSettled([this.querySubgraph(s,g),this.querySubgraph(s,y)]),k=b.status==="fulfilled"?(b.value?.pools||[]).filter(A=>this.hasValidVolume(A)).map(A=>this.mapPool(A,s)):[],T=w.status==="fulfilled"?(w.value?.pools||[]).filter(A=>this.hasValidVolume(A)).map(A=>this.mapPool(A,s)):[],S=new Set(k.map(A=>A.poolAddress));m=[...k,...T.filter(A=>!S.has(A.poolAddress))]}else m=((await this.querySubgraph(s,p([],100)))?.pools||[]).filter(g=>this.hasValidVolume(g)).map(g=>this.mapPool(g,s));let f=await this.fetchDefiLlamaUniswap();return f.length>0&&(m=this.enrichWithLlama(m,f)),o?.minTVL!=null&&(m=m.filter(h=>h.tvl>=o.minTVL)),o?.maxTVL!=null&&(m=m.filter(h=>h.tvl<=o.maxTVL)),o?.minAPR!=null&&(m=m.filter(h=>h.apr!=null&&h.apr>=o.minAPR)),o?.maxAPR!=null&&(m=m.filter(h=>h.apr!=null&&h.apr<=o.maxAPR)),r==="apr"?m.sort((h,g)=>(g.apr??0)-(h.apr??0)):r==="liquidity"&&m.sort((h,g)=>{let y=BigInt(g.liquidity||"0")-BigInt(h.liquidity||"0");return y>0n?1:y<0n?-1:0}),m}async getTrendingPools(e){let t=this.resolveChain(e.chain),n=`{
146
+ }`,m;if(i.length>0){let g,y;i.length>=2?(g=p([`token0_: { ${u(i[0])} }`,`token1_: { ${u(i[1])} }`],100),y=p([`token0_: { ${u(i[1])} }`,`token1_: { ${u(i[0])} }`],100)):(g=p([`token0_: { ${u(i[0])} }`],100),y=p([`token1_: { ${u(i[0])} }`],100));let[b,w]=await Promise.allSettled([this.querySubgraph(s,g),this.querySubgraph(s,y)]),k=b.status==="fulfilled"?(b.value?.pools||[]).filter(A=>this.hasValidVolume(A)).map(A=>this.mapPool(A,s)):[],T=w.status==="fulfilled"?(w.value?.pools||[]).filter(A=>this.hasValidVolume(A)).map(A=>this.mapPool(A,s)):[],S=new Set(k.map(A=>A.poolAddress));m=[...k,...T.filter(A=>!S.has(A.poolAddress))]}else m=((await this.querySubgraph(s,p([],100)))?.pools||[]).filter(g=>this.hasValidVolume(g)).map(g=>this.mapPool(g,s));let f=await this.fetchDefiLlamaUniswap();return f.length>0&&(m=this.enrichWithLlama(m,f)),o?.minTVL!=null&&(m=m.filter(h=>h.tvl>=o.minTVL)),o?.maxTVL!=null&&(m=m.filter(h=>h.tvl<=o.maxTVL)),o?.minAPR!=null&&(m=m.filter(h=>h.apr!=null&&h.apr>=o.minAPR)),o?.maxAPR!=null&&(m=m.filter(h=>h.apr!=null&&h.apr<=o.maxAPR)),r==="apr"?m.sort((h,g)=>(g.apr??0)-(h.apr??0)):r==="liquidity"&&m.sort((h,g)=>{let y=BigInt(g.liquidity||"0")-BigInt(h.liquidity||"0");return y>0n?1:y<0n?-1:0}),m}async getTrendingPools(e){let t=this.resolveChain(e.chain),n=`{
147
147
  pools(
148
148
  first: 100
149
149
  orderBy: volumeUSD
@@ -176,25 +176,25 @@ ${$s}`,Jt={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
176
176
  ${this.poolFragment()}
177
177
  }
178
178
  }
179
- }`,r=await this.querySubgraph(t,n);if(!r?.position?.pool)return null;let o=r.position,s=this.mapPool(o.pool,t),i=await this.fetchDefiLlamaUniswap(),l=i.length>0?this.enrichWithLlama([s],i)[0]:s,c=l.feeTierBps,u=l.feeTierPercent;return{position:{positionId:o.id,poolAddress:l.poolAddress,pair:l.pair,token0:{symbol:l.token0.symbol,address:l.token0.address},token1:{symbol:l.token1.symbol,address:l.token1.address},feeTierBps:c,feeTierPercent:u,chain:l.chain,liquidity:o.liquidity,depositedToken0:o.depositedToken0,depositedToken1:o.depositedToken1,withdrawnToken0:o.withdrawnToken0,withdrawnToken1:o.withdrawnToken1,collectedFeesToken0:o.collectedFeesToken0,collectedFeesToken1:o.collectedFeesToken1},pool:l}}async getCoinPoolPairs(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchCoinPoolV2Items(t)).map(o=>this.mapCoinPoolV2Item(o)).filter(o=>o!==null);if(e.tokens&&e.tokens.length>=2){let o=e.tokens[0].toUpperCase(),s=e.tokens[1].toUpperCase();r=r.filter(i=>{let[l="",c=""]=i.pair.toUpperCase().split("/");return l.includes(o)&&c.includes(s)||l.includes(s)&&c.includes(o)})}return r}async getCoinPoolByAddress(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(o=>o.poolId?.toLowerCase()===n).map(o=>this.mapCoinPoolV2Item(o)).filter(o=>o!==null).sort((o,s)=>(s.apr??-1/0)-(o.apr??-1/0))}async fetchCoinPoolV2Items(e){if(!this.coinPoolBaseUrl)return[];try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(I(n));return n.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=S=>S==null||!Number.isFinite(S)?0:Math.pow(1.0001,S)*Math.pow(10,t-n),o=r(e.minTick),s=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?o:s>0?1/s:0,p=u?s:o>0?1/o:0,m=u?c:c>0?1/c:0,f=u?e.token0.symbol:e.token1.symbol,h=u?e.token1.symbol:e.token0.symbol;if(!m||!d&&!p)return null;let g=Math.min(d,p),y=Math.max(d,p);if(m<g||m>y)return null;let b=Number(e.fee),w=Ws[b]??b/1e4,k=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,T=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:T,token0Price:i,token1Price:l,priceRange:{minPrice:Z(d),maxPrice:Z(p),currentPrice:Z(m),baseToken:f,quoteToken:h}}}};var Ze=class{config;constructor(e){this.config=e}hasIntegratedApproval(){return!1}};var Rl="https://exchange-api.keyring.app/admin/setting?configs=others",Nl="https://api.coinpool.app/config/bridgeProviderByChain",Ul="https://coinpool-api-op.bacoor-test001.xyz/config/bridgeProviderByChain";function Il(a){let e=null,t=null;return async()=>e||t||(t=(async()=>{try{return e=await a(),e}catch{return null}finally{t=null}})(),t)}async function Gs(a){return(await x.get(a,{headers:{Accept:"application/json"}})).data}var Ll=Il(async()=>(await Gs(Rl))?.others??null),Po={prod:null,dev:null},Gn={prod:null,dev:null};async function Dl(a){let e=a?"prod":"dev";if(Po[e])return Po[e];if(Gn[e])return Gn[e];let t=a?Nl:Ul;return Gn[e]=(async()=>{try{let n=await Gs(t);return Po[e]=n?.data??null,Po[e]}catch{return null}finally{Gn[e]=null}})(),Gn[e]}function Ol(a){if(!a)return null;try{let e=JSON.parse(a);return e&&typeof e=="object"?e:null}catch{return null}}function Hs(a){if(a==null)return 0;let e=typeof a=="number"?a:Number(a);return Number.isFinite(e)?e:0}function Ml(a){return a==="debridge"||a==="relay"}async function xo(a,e){let n=(await Dl(e))?.[String(a)];return Ml(n)?n:null}async function Zt(a,e){let t=await Ll();if(!t)return null;let n,r;if(a==="debridge")n=Ol(t.affiliateRecipient)?.[String(e)],r=Hs(t.AFFILIATE_FEE_PERENT);else if(a==="relay")n=t.RELAY_AFFILIATE_FEE_RECIPIENT,r=Hs(t.RELAY_AFFILIATE_FEE_PERCENT);else return null;return!n||r<=0?null:{affiliateFeeRecipient:n,affiliateFeePercent:r}}var Fl="https://dln.debridge.finance/v1.0",ql="0x0000000000000000000000000000000000000000",Bl=new Set([429,500]),$l=5,Vl=1e3,Wl=a=>new Promise(e=>setTimeout(e,a)),en=class extends Ze{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Fl,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:o,dstTokenAddress:s,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:u}=e,d=u??t!==o,p=await Zt(this.getProviderName(),t);try{if(d){let h={srcChainId:String(t),srcChainTokenIn:n,srcChainTokenInAmount:r,dstChainId:String(o),dstChainTokenOut:s,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:l,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent);let g=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,h);return g.error||g.errorMessage?{success:!1,error:g.error??g.errorMessage,errorMessage:g.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:g.tx,estimation:g.estimation,isCrossChain:!0,srcChainId:t,dstChainId:o,raw:g}}let m={chainId:String(t),tokenIn:n,tokenInAmount:r,tokenOut:s,tokenOutRecipient:i,accesstoken:this.accessToken};p&&(m.affiliateFeeRecipient=p.affiliateFeeRecipient,m.affiliateFeePercent=p.affiliateFeePercent),c!==void 0&&(m.slippage=c);let f=await this.get(`${this.apiBaseUrl}/chain/transaction`,m);return f.error||f.errorMessage?{success:!1,error:f.error??f.errorMessage,errorMessage:f.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:f.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:f}}catch(m){return{success:!1,error:m,errorMessage:m instanceof Error?m.message:"Failed to fetch quote"}}}async checkApproval(e){let{chain:t,userAddress:n,tokenAddress:r,amount:o}=e,s=e.quoteData?.tx?.to;if(!s)return{isNeeded:!1,error:"No contract address found in quote"};if(!r||r.toLowerCase()===ql)return{isNeeded:!1,integrated:!1,contractAddress:s,message:"Native coin needs no approval."};let i=await this.readAllowance(t,r,n,s);if(i===null)return{isNeeded:!0,integrated:!1,contractAddress:s,message:"Could not read allowance; approval required before the swap."};let l;try{l=BigInt(o)}catch{l=0n}return i>=l?{isNeeded:!1,integrated:!1,contractAddress:s,message:"Sufficient allowance already granted."}:{isNeeded:!0,integrated:!1,contractAddress:s,message:"Approval required: current allowance is below the swap amount."}}async readAllowance(e,t,n,r){if(!e)return null;let o=l=>l.toLowerCase().replace(/^0x/,"").padStart(64,"0"),s=`0xdd62ed3e${o(n)}${o(r)}`,i=await sr(e,t,s);if(typeof i!="string"||!/^0x[0-9a-fA-F]*$/.test(i)||i==="0x")return null;try{return BigInt(i)}catch{return null}}async executeSwap(e){let{quoteData:t}=e;return{success:!0,provider:"debridge",txData:t.tx??void 0,estimation:t.estimation}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let n=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!n.orderIds?.length)return{success:!1,status:"PENDING"};let r=n.orderIds[0];switch(((await this.get(`${this.apiBaseUrl}/dln/order/${r}/status`,{accesstoken:this.accessToken})).status??"").toUpperCase()){case"FULFILLED":case"SENTUNLOCK":case"CLAIMEDUNLOCK":return{success:!0,status:"COMPLETED"};case"ORDERCANCELLED":case"SENTORDERCANCEL":case"CLAIMEDORDERCANCEL":return{success:!0,status:"FAILED"};default:return{success:!0,status:"PENDING"}}}catch(n){return{success:!1,status:"ERROR",error:n instanceof Error?n.message:String(n)}}}async get(e,t){let n=Object.entries(t).map(([s,i])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(i))}`).join("&"),r=n?`${e}?${n}`:e,o=await x.get(r,{headers:{Accept:"application/json"}});for(let s=0;s<$l&&Bl.has(o.status);s++)await Wl(Vl),o=await x.get(r,{headers:{Accept:"application/json"}});return o.data}};var Hl="https://api.relay.link";function Ys(a){return a===7565164||a==="7565164"?792703809:a}var tn=class extends Ze{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Hl,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:o,dstTokenAddress:s,recipientAddress:i,senderAddress:l,slippage:c}=e,u=await Zt(this.getProviderName(),t),d={user:i||l,originChainId:Ys(t),destinationChainId:Ys(o),originCurrency:n,destinationCurrency:s,amount:r,recipient:i||l,tradeType:"EXACT_INPUT"};u&&(d.appFees=[{recipient:u.affiliateFeeRecipient,fee:Math.floor(u.affiliateFeePercent*100)}]),typeof c=="number"&&Number.isFinite(c)&&(d.slippageTolerance=Math.floor(c*100).toString());try{let p=await this.request("/quote/v2","POST",d);if(!p||p.error)return{success:!1,error:p?.error??"Unknown error",errorMessage:p?.message??"Failed to fetch quote from Relay"};let m=p.steps?.find(b=>b.id==="approve"),f=p.steps?.find(b=>b.id==="swap"||b.id==="deposit"),h=f?.items?.[0]?.data,g=Array.isArray(h?.instructions);return{success:!0,provider:"relay",tx:h?g?{data:{instructions:h.instructions??[],addressLookupTableAddresses:h.addressLookupTableAddresses??[]},chainId:h.chainId}:{from:h.from,to:h.to,data:h.data,value:h.value,chainId:h.chainId,maxFeePerGas:h.maxFeePerGas,maxPriorityFeePerGas:h.maxPriorityFeePerGas}:null,isCrossChain:t!==o,srcChainId:t,dstChainId:o,raw:{steps:p.steps,fees:p.fees,details:p.details,approveStep:m,requestId:f?.requestId}}}catch(p){return{success:!1,error:p,errorMessage:p instanceof Error?p.message:"Failed to fetch quote"}}}async checkApproval(e){let t=e.quoteData?.raw?.approveStep;if(t){let n=t.items?.[0]?.data;return{isNeeded:!0,integrated:!0,approvalData:n,contractAddress:n?.to,message:"Approval step is included in quote and will be executed first."}}return{isNeeded:!1,integrated:!0,message:"No approval needed or already approved"}}async executeSwap(e){let{quoteData:t}=e,n=t.raw;return n?.steps?{success:!0,provider:"relay",steps:n.steps,estimation:t.estimation}:{success:!1,error:"Invalid quote data"}}async trackTransaction(e){try{let n=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return n==="success"||n==="refunded"?{success:!0,status:"COMPLETED"}:n==="failure"||n==="expired"?{success:!0,status:"FAILED"}:{success:!0,status:"PENDING"}}catch(t){return{success:!1,status:"ERROR",error:t instanceof Error?t.message:String(t)}}}async request(e,t,n){let r={"Content-Type":"application/json"};this.apiKey&&(r["x-api-key"]=this.apiKey);let o=`${this.apiBaseUrl}${e}`,s;if(t==="GET"&&n){let l=Object.entries(n).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(u))}`).join("&");o=`${o}?${l}`}else t==="POST"&&n&&(s=n);let i=await x.request(t,o,s,{headers:r});if(!i.ok)throw new Error(I(i));return i.data}};var Co={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},Yn="debridge";function Gl(a){if(a==null)return null;let e=typeof a=="number"?a:Number(a);return Number.isFinite(e)?e:null}var dt=class{providerConfig;isProduction;cache=new Map;constructor(e=Co,t=!0){this.providerConfig=e,this.isProduction=t}async getService(e){let t=await this.getActiveProvider(e),n=this.cache.get(t);if(n)return n;let r=this.createService(t);return this.cache.set(t,r),r}async getServiceByProvider(e){let t=this.cache.get(e);if(t)return t;let n=this.createService(e);return this.cache.set(e,n),n}async getActiveProvider(e){let t=Gl(e);return t===null?Yn:await xo(t,this.isProduction)??Yn}async isProviderActive(e,t){return await this.getActiveProvider(t)===e}getAvailableProviders(){return Object.keys(this.providerConfig)}clearCache(){this.cache.clear()}createService(e){let t=this.providerConfig[e]??{};switch(e){case"debridge":return new en(t);case"relay":return new tn(t);default:{let n=e;throw new Error(`Unknown swap provider: ${String(n)}`)}}}},Me=new dt;var Yl="https://api.coinpool.app/config/addresses",jl="https://coinpool-api-op.bacoor-test001.xyz/config/addresses",_o={prod:null,dev:null},jn={prod:null,dev:null};async function js(a){let e=a?"prod":"dev";if(_o[e])return _o[e];if(jn[e])return jn[e];let t=a?Yl:jl;return jn[e]=(async()=>{try{let r=(await x.get(t,{headers:{Accept:"application/json"}})).data;return _o[e]=r?.data??null,_o[e]}catch{return null}finally{jn[e]=null}})(),jn[e]}function Kl(a){let e=a.trim();if(/^0x[0-9a-fA-F]+$/.test(e)){let t=Number.parseInt(e,16);return Number.isFinite(t)?String(t):null}return/^\d+$/.test(e)?e:null}async function Ks(a,e,t){let n=await js(t);if(!n)return;let r=Kl(e);if(!r)return;let o=n[a]?.[r];return Array.isArray(o)?o[0]:typeof o=="string"?o:void 0}async function Eo(a,e){return Ks("createPoolProxyV3",a,e)}var zl=/^0x[0-9a-fA-F]{40}$/;async function Xl(a,e){let n=(await js(e))?.[a];if(!n||typeof n!="object")return[];let r=[];for(let[o,s]of Object.entries(n)){let i=Array.isArray(s)?s[0]:s;typeof i=="string"&&zl.test(i.trim())&&r.push(o)}return r}async function Ro(a){return Xl("createPoolProxyV3",a)}async function No(a,e){return Ks("nftPositionUniswap",a,e)}var B="0x0000000000000000000000000000000000000000",zs={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:Te["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:Te["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:Te["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:Te["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:Te["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:Te["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:Te["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:Te["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function oe(a){return zs[a.toLowerCase()]}function nn(a){return oe(a)?.native}var Xs="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function Sr(a){let e=a.stableTicks??3,t=a.widePercent??{down:50,up:100},n=Ce(a.currentTick,a.token0Decimals,a.token1Decimals),r=De(Le(a.currentTick-e*a.tickSpacing,a.tickSpacing,"down")),o=De(Le(a.currentTick+e*a.tickSpacing,a.tickSpacing,"up")),s=n*(1-t.down/100),i=n*(1+t.up/100),l=ct(s,a.token0Decimals,a.token1Decimals),c=ct(i,a.token0Decimals,a.token1Decimals),u=De(Le(l,a.tickSpacing,"down")),d=De(Le(c,a.tickSpacing,"up")),p=(m,f,h,g,y)=>{let b=Ce(g,a.token0Decimals,a.token1Decimals),w=Ce(y,a.token0Decimals,a.token1Decimals);return{id:m,label:f,description:h,tickLower:g,tickUpper:y,minPrice:b,maxPrice:w,minPercentChange:(b-n)/n*100,maxPercentChange:(w-n)/n*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",r,o),p("wide","Wide","Good for volatile pairs",u,d)]}var Ql=ue("slot0()"),Jl=ue("liquidity()"),Zl=ue("tickSpacing()"),ec=ue("fee()"),tc=ue("token0()"),nc=ue("token1()"),oc=ue("decimals()"),ce=class{swapFactory;isProduction;constructor(e){this.isProduction=e?.isProduction??!0,this.swapFactory=e?.swapFactory??(this.isProduction?Me:new dt(void 0,!1))}isSupported(e){if(!e)return!1;let t=$(e)??e.toLowerCase();return!!oe(t)}listSupportedChains(){return Object.keys(zs).filter(e=>_e(e))}getRpcUrl(e){let t=$e(e);if(t)return t;let n=oe(e);if(!n)throw new Error(`Unsupported chain: ${e}`);return n.defaultRpc}async getGatewayAddress(e){return Eo(e,this.isProduction)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await Ro(this.isProduction),t=[];for(let n of e){let r=$(n);r&&oe(r)&&!t.includes(r)&&t.push(r)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return No(e,this.isProduction)}async ethCall(e,t,n){return Ve(this.getRpcUrl(e),"eth_call",[{to:t,data:n},"latest"])}async getNativeBalance(e,t){let n=await Ve(this.getRpcUrl(e),"eth_getBalance",[t,"latest"]);return BigInt(n)}async getGasPrice(e){let t=await Ve(this.getRpcUrl(e),"eth_gasPrice",[]);return BigInt(t)}async getTransactionReceipt(e,t){return await Ve(this.getRpcUrl(e),"eth_getTransactionReceipt",[t])}async extractMintedNftId(e,t){let n=await this.getPositionManagerAddress(e);if(!n)return null;let r=n.toLowerCase();for(let o of t.logs??[]){if((o.address??"").toLowerCase()!==r)continue;let s=o.topics??[];if(!(s.length<4||s[0]?.toLowerCase()!==Xs||"0x"+s[1].slice(-40).toLowerCase()!==B))try{return BigInt(s[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=oe(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let n=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*n*18n/10n}async readPoolOnchain(e,t){let[n,r,o,s,i,l]=await Promise.all([this.ethCall(e,t,Ql),this.ethCall(e,t,Jl),this.ethCall(e,t,Zl),this.ethCall(e,t,ec),this.ethCall(e,t,tc),this.ethCall(e,t,nc)]),c=ee(n),u=Bn(c,0),d=nr(c,64),p=Bn(ee(r),0),m=Number(nr(ee(o),0)),f=Number(Bn(ee(s),0)),h=or(ee(i),0),g=or(ee(l),0),[y,b]=await Promise.all([this.readErc20Decimals(e,h),this.readErc20Decimals(e,g)]),w=jr(u,y,b);return{poolAddress:t,chainId:e,fee:f,tickSpacing:m,liquidity:p,sqrtPriceX96:u,currentTick:d,token0:h,token1:g,currentPrice:w}}async readErc20Decimals(e,t){if(t.toLowerCase()===B)return 18;let n=await this.ethCall(e,t,oc);return Number(Bn(ee(n),0))}async getNativePriceUsd(e){let t=oe(e);if(!t)return null;try{let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,r=await x.get(n);if(!r.ok)return null;let s=r.data[t.native.coingeckoId]?.usd;return typeof s=="number"?s:null}catch{return null}}splitNativeAmountForRange(e){let{nativeAmountWei:t,pool:n,tickLower:r,tickUpper:o,token0Decimals:s,token1Decimals:i}=e,l=2**96,c=Number(n.sqrtPriceX96)/l,u=Math.pow(1.0001,r/2),d=Math.pow(1.0001,o/2);if(c<=u)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(c>=d)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let p=1/c-1/d,m=c-u,f=c*c,h=p*f,y=h+m;if(!Number.isFinite(y)||y<=0)throw new Error("splitNativeAmountForRange: invalid total value");let b=h/y,w=1-b,k=1000000000000000n,T=BigInt(Math.floor(b*Number(k))),S=t*T/k,A=t-S;return{ratio0:b,ratio1:w,amountInFor0Wei:S,amountInFor1Wei:A}}async fetchSwapLeg(e){let t=Number.parseInt(e.chainId,16);if(!Number.isFinite(t))throw new Error(`Invalid hex chain id: ${e.chainId}`);let r=await(await this.swapFactory.getService(t)).getQuote({srcChainId:t,srcTokenAddress:e.tokenIn,srcTokenAmount:e.tokenInAmount,dstChainId:t,dstTokenAddress:e.tokenOut,recipientAddress:e.tokenOutRecipient,senderAddress:e.senderAddress??e.tokenOutRecipient,slippage:e.slippage,isCrossChain:!1});if(!r.success||!r.tx)throw new Error(r.errorMessage??"Swap quote failed");let o=r.tx;if(!o.to||typeof o.data!="string")throw new Error("Swap quote returned an unsupported tx shape (non-EVM payload?)");let s=r.raw??{},i=s.tokenOut?.minAmount??s.details?.currencyOut?.minimumAmount??"0";return{to:o.to,data:o.data,value:o.value??"0",minAmountOut:i}}encodeMintCalldata(e){if(e.paymentInfo.length!==2||e.exchanges.length!==2)throw new Error("encodeMintCalldata: paymentInfo and exchanges must each have length 2");let t=ue("mint((address,uint256,address,uint256)[2],(address,bytes,uint256)[2],(uint24,uint256,uint256,int24,int24))"),n=e.paymentInfo.map(f=>lo(f.tokenIn)+fe(f.tokenInAmount)+lo(f.tokenOut)+fe(f.tokenOutAmount)).join(""),o=e.exchanges.map(f=>{let h=ee(f.data||"0x"),g=h.length/2,y=fe(g),b=(64-h.length%64)%64,w=h+"0".repeat(b);return{head:lo(f.to)+fe(96)+fe(f.value),body:y+w}}).map(f=>f.head+f.body),s=o.length*32,i=[];for(let f of o)i.push(fe(s)),s+=f.length/2;let l=i.join("")+o.join(""),c=fe(e.fee,24)+fe(e.amount0Min)+fe(e.amount1Min)+tr(e.tickLower)+tr(e.tickUpper),p=256+32+160,m=n+fe(p)+c+l;return t+m}_keccak(e){return Kr(e)}};var rc={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},sc=/^0x[a-fA-F0-9]{40}$/;function ac(a,e){if(typeof a!="string"||typeof e!="string")return null;let t=rc[a.toLowerCase()];return!t||!sc.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function Ee(a,e){let t=ac(a,e);return t?{uniswapUrl:t}:{}}var Qs=Object.keys(Jt),Ae="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a, Linea=0xe708, Gnosis=0x64, HyperEVM=0x3e7, Mantle=0x1388, Monad=0x8f. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";function me(){return Qs.filter(a=>_e(a)).map(a=>P(a)).join(", ")}function Se(){return{kind:"info",async listSupported(){return Qs.filter(a=>_e(a))},async isSupported(a){if(!a)return!1;let e=$(a)??a.toLowerCase();return Object.prototype.hasOwnProperty.call(Jt,e)}}}function on(a){return{kind:"add-liquidity",listSupported:()=>a.listAddLiquiditySupportedChains(),isSupported:e=>a.isAddLiquiditySupported(e)}}function Pr(a,e,t){let n=r=>typeof r=="string"&&r.trim()!=="";if(n(a))return $(a)??a.trim();if(n(e?.chain))return $(e.chain)??e.chain.trim();if(n(e?.walletAddress))throw new K(typeof e?.query=="string"?e.query:void 0,t);return ve}async function he(a,e,t){let n=await a.listSupported(),r=Pr(e,t,n);return await a.isSupported(r)?{ok:!0,chain:r}:{ok:!1,result:xr(r,n,a.kind)}}function xr(a,e,t="info"){return{_instructions:`${t==="add-liquidity"?"Adding liquidity is NOT available on this network. Tell the user, in their language, that they cannot add liquidity / provide LP on this chain yet (note: viewing pool info may still work on other chains). Then name the chains where adding liquidity IS available":"Liquidity-pool data is NOT available on this network. Tell the user, in their language, that pools are not supported on this chain. Then name the chains where pools ARE available"} using EXACTLY and ONLY the entries in the \`supportedChains\` field below \u2014 copy them verbatim, add nothing. CRITICAL: this list is the complete, authoritative set. Do NOT add, infer, or invent ANY other chain \u2014 NOT EVEN a chain this app supports for wallet/token/DeFi features (for example Gnosis, HyperEVM, Mantle, and Monad are NOT pool chains; never list them unless they literally appear in \`supportedChains\`). Keep it short and friendly. Do NOT mention tools, services, APIs, forms, or any internals.`,unsupportedChain:P(a),supportedChains:e.map(r=>P(r))}}var Uo="{pair}";var et=[{name:"add_button_label",type:"string",description:`Label template for the per-pool "Add liquidity" buttons that render under EVERY pool you show, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each pool automatically. Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:`A short "add liquidity" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a pool's button is clicked. ALWAYS provide it. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain these pools are on is appended automatically.`,required:!1}],Re=' A clickable "Add liquidity" button is shown below your reply for each pool automatically \u2014 do NOT list, number, or repeat those buttons in your text; just deliver your analysis.';function Ne(a,e,t){return Cr(a,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function Cr(a,e,t,n){let r=typeof n=="string"&&n.trim()?` (${n.trim()})`:"",o=[];for(let s of a){if(o.length>=5)break;let i=s.token0?.symbol?.trim(),l=s.token1?.symbol?.trim();if(!i||!l)continue;let c=ic(i,l,s.feeTierPercent);o.push({label:Js(e,c,`Add liquidity to ${Uo}`),prompt:Js(t,c,`add liquidity to ${Uo}`)+r})}return o}function ic(a,e,t){let n=`${a}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${n} ${lc(t)}%`:n}function lc(a){return Number(a.toFixed(4)).toString()}function Js(a,e,t){return(a&&a.includes(Uo)?a:t).split(Uo).join(e).replace(/\s+/g," ").trim()}var ye="You are a seasoned DEX liquidity-pool analyst with deep, credible expertise. Deliver a genuinely insightful, professional read \u2014 the kind a sophisticated LP would pay for \u2014 in natural, flowing prose rather than a rigid template, never sacrificing depth or authority for a conversational tone. ",be="Ground every judgement rigorously in the data, never guesses \u2014 and only use a signal when its data is present: \u2022 capital efficiency = `volumeToTvlRatio` (volume \xF7 TVL) \u2014 higher means each $ of liquidity earns more fees; >1 is very active, <0.1 is sluggish. \u2022 APR quality \u2014 a very high APR sitting on a TINY TVL is usually volatile/unsustainable (treat with caution); a solid APR on deep TVL is the sweet spot. \u2022 TVL trend \u2014 when a 24h TVL % change is present, note whether liquidity is growing or shrinking. \u2022 TVL depth \u2014 deeper pools = lower slippage and a steadier position; thin pools carry higher risk. \u2022 fee tier vs pair type \u2014 stable/correlated pairs suit low tiers (0.01\u20130.05%), volatile pairs suit higher tiers (0.3\u20131%). \u2022 token safety \u2014 when a token exposes isSpam=true or a non-VERIFIED safetyLevel, FLAG it prominently as a risk. ",we="Give a clear one-line worthiness verdict for LPs (e.g. a \u2B50 rating or High / Medium / Low attractiveness), woven naturally into the prose rather than tacked on as a fixed label. ",se="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",Ue=`LINKS \u2014 write every pool pair as PLAIN TEXT only (e.g. "USDC/WETH"). Do NOT create markdown links, do NOT output any URLs, and do NOT print raw pool or token contract addresses anywhere in your answer. The system automatically turns each pool's pair into the correct clickable link after you reply, so you must NEVER add a link, a "Link to pool" line, a "View on Uniswap" line, or a bare URL yourself \u2014 doing so produces wrong/duplicate links. Just name each pair in text. Format numbers human-readably (e.g. $12.5M, +1.23%, 0.05%). Omit null fields. Answer in the user's language. Do NOT mention tool or API names.`;var cc=["tvl","volume1Day","volume1Week","volume30Day","txCount","apr"],uc=["V2","V3","V4"],rn=class extends v{name="get-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens (symbol, name, address, decimals), TVL, transaction count, and rolling volume buckets (1d / 1w / 30d). Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap V3 pools on Base", "which pool has the most liquidity for USDC", "show pools with highest 24h volume on Arbitrum". Source: https://app.uniswap.org/explore (ExploreStats gateway). Supports: `+me();category="blockchain-data";parameters=[{name:"chain",type:"string",description:Ae,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", or "V4". Default is "V3" (the dataset with the richest stats). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume1Week", "volume30Day", "txCount", or "apr" (estimated annualized fee yield). Pools are returned in descending order by this metric.',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"multichain",type:"boolean",description:"When true, request Uniswap's multichain aggregated view instead of a single chain. Defaults to false. Most queries should leave this off.",required:!1,default:!1},{name:"forAddLiquidity",type:"boolean",description:'Set TRUE only when this ranking is the ENTRY POINT of the ADD-LIQUIDITY flow \u2014 the user wants to add / provide liquidity ("add pool", "i want to add liquidity", "th\xEAm thanh kho\u1EA3n") but named NO specific pool, so you show top pools (use sortBy="apr") for them to pick one. In that mode the tool gates on ADD-LIQUIDITY chain support (only chains with a gateway) and, when the connected chain has no gateway, returns the "adding liquidity is not available on this chain" message with the correct supported list \u2014 so the user is told up front, not after picking a pool. OMIT (false) for ordinary informational rankings ("top pools on Base", "biggest pools").',required:!1,default:!1},...et];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new pe(e),this.subgraphFallback=new ne(t),this.pool=new ce({isProduction:e?.isProduction})}async run(e,t){let n=e.forAddLiquidity===!0,r=n?on(this.pool):Se(),o=await r.listSupported(),s=Pr(e.chain,t,o),i=this.parseProtocolVersion(e.protocolVersion),l=this.parseSortKey(e.sortBy),c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,u=!n&&e.multichain===!0;if(!u&&!await r.isSupported(s))return xr(s,o,r.kind);let d=await this.service.getTopPools({chain:s,protocolVersion:i,sortBy:l,limit:c,multichain:u});if(!d.success)return{error:d.error||"Failed to fetch top pools"};let p=(d.data??[]).map(w=>this.formatPool(w)),m="uniswap";if(p.length===0&&i==="V3"){let w=await this.fetchV3Fallback(s,l,c);w.length>0&&(p=w,m="subgraph")}let f=p.map(w=>this.withExpertSignals(w)),h=await this.pool.isAddLiquiditySupported(s)?Ne(f,e,P(s)):[],g=m==="subgraph",y=g?`"Volume past day" (translate naturally into the user's language; NEVER call it "24h volume", "daily volume", or "24h")`:"24h volume";return{_instructions:(g?`BEGIN your answer with "According to the latest data from Subgraph Uniswap V3," (translate the sentence naturally into the user's language but keep the word "Subgraph" as-is). `:"")+ye+`You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, ${y}, 24h fee revenue, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. `+be+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+we+se+"Mention the chain and the sort metric in the intro line. "+Ue+(h.length>0?Re:""),chain:s,protocolVersion:i,sortBy:l,source:m,count:f.length,pools:f.map(w=>({...w,...Ee(s,w.address)})),...h.length>0?{actionButtons:h}:{}}}withExpertSignals(e){let t=e.tvlUsd,n=e.volume1DayUsd,r=typeof t=="number"&&t>0&&typeof n=="number"?Math.round(n/t*1e3)/1e3:void 0;return{...e,volumeToTvlRatio:r}}async fetchV3Fallback(e,t,n){try{return(await this.subgraphFallback.getTrendingPools({chain:e})).map(i=>this.formatSubgraphPool(i,e)).sort((i,l)=>this.fallbackSortValue(l,t)-this.fallbackSortValue(i,t)).slice(0,n)}catch{return[]}}fallbackSortValue(e,t){switch(t){case"apr":return e.apr??0;case"volume1Day":case"volume1Week":case"volume30Day":return e.volume1DayUsd??0;default:return e.tvlUsd??0}}formatSubgraphPool(e,t){return{apr:e.apr??void 0,address:e.poolAddress,chain:t,protocolVersion:"V3",feeTierBps:e.feeTierBps,feeTierPercent:typeof e.feeTierBps=="number"?e.feeTierBps/1e4:void 0,tvlUsd:e.tvl,fee24hUsd:e.fees24hUsd,volume1DayUsd:e.volume24hUsd,volume1WeekUsd:void 0,volume30DayUsd:void 0,txCount:void 0,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0}}parseProtocolVersion(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(uc.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(cc.includes(t))return t}return"tvl"}formatPool(e){return{apr:e.apr,address:e.id,chain:e.chain,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,tvlUsd:e.totalLiquidity?.value,fee24hUsd:e.fee24hUsd,volume1DayUsd:e.volume1Day?.value,volume1WeekUsd:e.volume1Week?.value,volume30DayUsd:e.volume30Day?.value,txCount:e.txCount,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.price?.value,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.price?.value,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}};var _r={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},dc={100:.01,500:.05,3e3:.3,1e4:1},tt=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=$(e);return!!(t&&_r[t])}listSupportedChains(){return Object.keys(_r).filter(e=>$(e)===e)}numericChainId(e){let t=$(e);return t?_r[t]:void 0}async getPairs(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchV2Items(t)).map(o=>this.mapV2Item(o)).filter(o=>o!==null);if(e.tokens&&e.tokens.length>=2){let o=e.tokens[0].toUpperCase(),s=e.tokens[1].toUpperCase(),i=(l,c)=>l.includes(c)||c.includes(l);r=r.filter(l=>{let[c="",u=""]=l.pair.toUpperCase().split("/");return i(c,o)&&i(u,s)||i(c,s)&&i(u,o)})}return r}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(o=>o.poolId?.toLowerCase()===n).map(o=>this.mapV2Item(o)).filter(o=>o!==null).sort((o,s)=>(s.apr??-1/0)-(o.apr??-1/0))}async fetchV2Items(e){try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(I(n));return n.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=S=>S==null||!Number.isFinite(S)?0:Math.pow(1.0001,S)*Math.pow(10,t-n),o=r(e.minTick),s=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?o:s>0?1/s:0,p=u?s:o>0?1/o:0,m=u?c:c>0?1/c:0,f=u?e.token0.symbol:e.token1.symbol,h=u?e.token1.symbol:e.token0.symbol;if(!m||!d&&!p)return null;let g=Math.min(d,p),y=Math.max(d,p);if(m<g||m>y)return null;let b=Number(e.fee),w=dc[b]??b/1e4,k=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,T=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:T,token0Price:i,token1Price:l,priceRange:{minPrice:Z(d),maxPrice:Z(p),currentPrice:Z(m),baseToken:f,quoteToken:h}}}};var pc=365,Zs=/^0x[a-fA-F0-9]{40}$/,mc=6,sn=class extends v{name="get-pool-detail";description="Get detailed stats for a Uniswap V3 pool by token pair (and optional fee tier). Always runs a search first and filters by the provided symbols + fee tier. When the filter resolves to exactly one pool, returns its full detail. When the pair is fully named but NO fee tier is given, returns detail plus a comparative analysis of ALL the pair's fee-tier variants (no need to ask the user to pick). When only one token is given (so the matches are different pairs), returns a `candidates` list \u2014 show it and ask which pair they want, then re-call this tool with the missing info. Detail response includes: pool address, fee tier (bps and %), both tokens (symbol, name, address, decimals, USD price), token0/token1 reserves, total TVL with 24h % change, 24h volume, weekly historical volume series, total tx count, and a derived APR estimate (fees \xF7 TVL \xD7 365). NEVER pass a pool address \u2014 the tool resolves the address itself by searching. Token contract addresses are NOT pool addresses. Source: https://app.uniswap.org. Supports: "+me();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter \u2014 USDC/WETH and WETH/USDC resolve to the same pool. When both token0Symbol and token1Symbol are provided the search is filtered to that exact pair.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 when omitted the tool returns all pools containing token0Symbol so the user can pick.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "USDC/WETH 0.05%" \u2192 feeTier=500). NEVER guess or infer one. When the user has not mentioned a fee tier, OMIT it \u2014 the tool then returns detail plus a comparative analysis of ALL fee-tier variants of the pair (no need to ask the user to pick one).',required:!1},{name:"chain",type:"string",description:Ae,required:!1},...et];service;coinPool;pool;constructor(e,t){super(),this.service=new pe(e),this.coinPool=new tt(t),this.pool=new ce({isProduction:e?.isProduction})}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",s=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0;if(!o)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let l=s?`${o} ${s}`:o,c=await this.service.searchPools({query:l,chain:r,page:1,size:100,protocolVersion:"V3"});if(!c.success)return{error:c.error||"Pool search failed"};let u=c.data??[],p=u.filter(g=>this.matchesFilter(g,o,s,i,"ordered")),m=!1;if(p.length===0&&s){let g=u.filter(y=>this.matchesFilter(y,o,s,i,"reversed"));g.length>0&&(p=g,m=!0)}if(p.length===0)return{error:`No V3 pool matched ${this.describeQuery(o,s,i)} on ${P(r)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!Zs.test(g.id))return{error:"Resolved pool has no valid address"};let[y,b]=await Promise.all([this.service.getV3PoolDetail({address:g.id,chain:r}),this.fetchPriceRanges(r,g.id,g.token0?.symbol,g.token1?.symbol)]);if(!y.success||!y.data)return{error:y.error||"Failed to fetch pool detail"};let w={...this.formatPool(y.data),...Ee(r,g.id)},k=await this.pool.isAddLiquiditySupported(r)?Ne([w],e,P(r)):[];return{priceRanges:b,_instructions:ye+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, token1 reserve + USD price, and total tx count. Optionally include the weekly historical volume as a sparkline-style bullet list. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+be+we+'PRICE RANGES: when `priceRanges` is a non-empty array, add a "Suggested price ranges" section listing each candidate \u2014 fee tier (`fee`), the min\u2013max range (`priceRange.minPrice`\u2013`priceRange.maxPrice` in baseToken/quoteToken units), the current price (`priceRange.currentPrice`), and its `apr`. CRITICAL: that `apr` is the yield for THAT specific range only \u2014 NEVER present it as the overall pool APR. Sort by apr desc; note the top entry is the most concentrated/highest-yield range but narrower = higher risk of going out of range. When `priceRanges` is empty or absent, simply omit this section. '+se+Ue+(k.length>0?Re:""),pairOrderMatched:m?"reversed":"ordered",pool:w,...k.length>0?{actionButtons:k}:{}}}if(s){let g=this.rankCandidates(p).slice(0,mc),b=(await Promise.all(g.map(async w=>{if(!w.id||!Zs.test(w.id))return;let k=await this.service.getV3PoolDetail({address:w.id,chain:r});if(!(!k.success||!k.data))return{...this.formatPool(k.data),...Ee(r,w.id)}}))).filter(w=>w!=null);if(b.length>0){let w=await this.pool.isAddLiquiditySupported(r)?Ne(b,e,P(r)):[];return{_instructions:ye+"The user named a pair WITHOUT a fee tier, so here is EVERY fee-tier variant of that pair \u2014 do NOT ask them to pick a tier. Present them as a ranked list (rank them by capital efficiency / fee yield, not just TVL). For each variant show the fee tier (%), TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), and tx count. Analyze every variant \u2014 give each its own genuine read, never skip one, and never repeat the same sentence structure. "+be+"Focus on which fee tier is the right home for THIS pair: lower tiers (0.01\u20130.05%) win on stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 and the tier that actually captures most of the real volume with deep TVL is usually the one to LP in. Close with an overall section naming the single best fee tier to provide liquidity in right now and why. "+we+se+Ue+(w.length>0?Re:""),chain:r,pairOrderMatched:m?"reversed":"ordered",multiFeeTier:!0,count:b.length,pools:b,...w.length>0?{actionButtons:w}:{}}}}let f=this.rankCandidates(p).slice(0,10).map(g=>{let y=this.formatCandidate(g);return{...y,...Ee(r,y.address)}}),h=await this.pool.isAddLiquiditySupported(r)?Ne(f,e,P(r)):[];return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume) and ask the user which one they want to see. Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. When they answer, re-call this tool with their selection \u2014 pass token0Symbol + token1Symbol + feeTier (use the exact feeTier in bps from the chosen candidate). Format numbers human-readably (e.g. $12.5M, 0.05%). Do NOT mention tool/API names."+(h.length>0?Re:""),chain:r,pairOrderMatched:m?"reversed":"ordered",reason:this.candidateReason(o,s,i),missing:this.missingFields(s,i),candidates:f,...h.length>0?{actionButtons:h}:{}}}matchesFilter(e,t,n,r,o){if(r!=null&&e.feeTier!==r)return!1;let s=(e.token0?.symbol??"").toLowerCase(),i=(e.token1?.symbol??"").toLowerCase(),l=t.toLowerCase();if(n){let c=n.toLowerCase();return o==="reversed"?this.symbolIncludes(s,c)&&this.symbolIncludes(i,l):this.symbolIncludes(s,l)&&this.symbolIncludes(i,c)}return this.symbolIncludes(s,l)||this.symbolIncludes(i,l)}symbolIncludes(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at fee tier ${n} bps`:r}candidateReason(e,t,n){return t?n==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${n} bps. Ask the user which one they meant.`:`Multiple pools contain ${e}. Ask the user for the other token (and fee tier).`}missingFields(e,t){let n=[];return e||n.push("token1Symbol"),t==null&&n.push("feeTier"),n}rankCandidates(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}formatCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let o=await this.coinPool.getByAddress({chain:e,poolAddress:t});return o.length===0&&n&&r&&(o=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),o.sort((s,i)=>(i.apr??-1/0)-(s.apr??-1/0)).slice(0,10)}catch{return[]}}formatPool(e){let t=e.totalLiquidity?.value,n=e.volume24h?.value,r=e.feeTier,o=typeof r=="number"?r/1e4:void 0,s=typeof n=="number"&&typeof o=="number"?n*o/100:void 0,i=typeof s=="number"&&typeof t=="number"&&t>0?s/t*pc*100:void 0,l=typeof n=="number"&&typeof t=="number"&&t>0?Math.round(n/t*1e3)/1e3:void 0;return{address:e.address,protocolVersion:e.protocolVersion,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:s,aprPercent:i,volumeToTvlRatio:l,txCount:e.txCount,historicalVolumeWeek:this.formatHistorical(e.historicalVolume),token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.market?.price?.value??e.token0.price?.value,reserve:e.token0Supply,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.market?.price?.value??e.token1.price?.value,reserve:e.token1Supply,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var hc=["V2","V3","V4","ALL"],an=class extends v{name="search-pools";description='Search Uniswap liquidity pools on a given chain by free-text query \u2014 a SINGLE token symbol or token name. Returns matching pools with: pool address, fee tier (bps + %), protocol version, both tokens (symbol, name, address, decimals, logo), and short-window USD volume buckets (6h / 12h / 24h). Use this tool when the user names ONE token and wants pools related to it: "find WBTC pools on Optimism", "pools containing PEPE on Ethereum", "show USDC pools". Do NOT use for: (a) two-symbol pair lookups like "USDC/WETH 0.05%" \u2014 use get-pool-detail; (b) raw 0x addresses (token or pool) \u2014 use lookup-pool-by-address; (c) chain-wide rankings with no token mentioned \u2014 use get-top-pools. Source: https://app.uniswap.org search. Supports: '+me();category="blockchain-data";parameters=[{name:"query",type:"string",description:'Single token symbol or name to search pools by (e.g. "WBTC", "USDC", "pepe"). Do NOT pass a 0x address (use lookup-pool-by-address) or a two-symbol pair (use get-pool-detail).',required:!0},{name:"chain",type:"string",description:Ae,required:!1},{name:"protocolVersion",type:"string",description:'Filter results by Uniswap protocol version: "V2", "V3", "V4", or "ALL" to include every version. Default is "V3" \u2014 only switch when the user explicitly asks for V2, V4, or all versions.',required:!1,default:"V3"},{name:"page",type:"number",description:"1-based page index. Defaults to 1.",required:!1,default:1},{name:"size",type:"number",description:'Page size (max 50). Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"feeTier",type:"number",description:'Optional fee tier filter in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. When provided, only pools with this exact fee tier are returned. Pass it whenever the user mentions a fee tier in the current message OR earlier in the conversation (e.g. "USDC/WETH 0.05% pool on Base" \u2192 feeTier=500). Omit otherwise.',required:!1},...et];service;pool;constructor(e){super(),this.service=new pe(e),this.pool=new ce({isProduction:e?.isProduction})}async run(e,t){let n=typeof e.query=="string"?e.query.trim():"";if(!n)return{error:"Search query is required"};let r=await he(Se(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,i=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):5,l=this.parseProtocolFilter(e.protocolVersion),c=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,u=await this.service.searchPools({query:n,chain:o,page:s,size:i,protocolVersion:l,feeTier:c});if(!u.success)return{error:u.error||"Failed to search pools"};let d=(u.data??[]).map(m=>this.formatPool(m)),p=await this.pool.isAddLiquiditySupported(o)?Ne(d,e,P(o)):[];return{_instructions:ye+"Present the pools that match the search AND give an expert read on each. Render each pool as its own block: a bold header with the pair (token0/token1 symbols) + fee tier (%), then beneath it the metrics that have data \u2014 TVL (USD), 24h volume (USD), APR (%), tx count, protocol version. Skip any field that is null/undefined \u2014 never show zeros or dashes for missing data. Then add an expert read on each pool \u2014 is it worth providing liquidity in, and why. "+be+we+"When several pools share the searched token, finish with a clear TOP PICK among them. "+se+"Mention the search query and chain in the intro. "+Ue+(p.length>0?Re:""),query:n,chain:o,protocolVersion:l,feeTierBps:c,feeTierPercent:c!=null?c/1e4:void 0,page:s,size:i,count:d.length,pools:d.map(m=>({...m,...Ee(o,m.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(hc.includes(t))return t}return"V3"}formatPool(e){let t={address:e.id,chainId:e.chainId,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0};e.apr!=null&&(t.apr=e.apr),e.tvlUsd!=null&&(t.tvlUsd=e.tvlUsd);let n=e.volume1DayUsd??e.volumeUsd24hr;n!=null&&(t.volume24hUsd=n),e.volumeUsd6hr!=null&&(t.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(t.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(t.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&n!=null&&(t.volumeToTvlRatio=Math.round(n/e.tvlUsd*1e3)/1e3);let r=e.token0,o=e.token1;return r&&(t.token0={address:r.address,symbol:r.symbol,name:r.name,decimals:r.decimals}),o&&(t.token1={address:o.address,symbol:o.symbol,name:o.name,decimals:o.decimals}),t}};var gc=365,ea=/^0x[a-fA-F0-9]{40}$/,ln=class extends v{name="lookup-pool-by-address";description='Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use this tool when the user pastes a single address and asks about "the pool" without saying which kind. For pool detail (when the address is a pool): pair, fee tier, TVL with 24h % change, 24h volume, 24h fees, estimated APR, token reserves with USD prices, and weekly volume series. For token resolution (when the address is a token): the resolved token (symbol, name, decimals) plus a ranked list of pools that include it (pair, fee tier, 24h volume, pool address). Source: https://app.uniswap.org. Supports: '+me();category="blockchain-data";parameters=[{name:"address",type:"string",description:"A 0x-prefixed EVM address. May be a Uniswap pool contract OR a token contract \u2014 the tool figures out which.",required:!0},{name:"chain",type:"string",description:Ae,required:!1},...et];service;pool;constructor(e){super(),this.service=new pe(e),this.pool=new ce({isProduction:e?.isProduction})}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.address=="string"?e.address.trim():"",[s,i]=await Promise.all([this.service.searchPools({query:o,chain:r,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:o,chain:r,page:1,size:5})]),l=s.success?this.findPoolByAddress(s.data??[],o):void 0;if(l)return this.handlePoolHit(l,r,e);let c=i.success?this.findTokenByAddress(i.data??[],o):void 0;return c?this.handleTokenHit(c,r,e):!s.success&&!i.success?{error:s.error||i.error||"Failed to resolve address"}:{error:`Address ${o} did not match any pool or token Uniswap knows on ${P(r)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t,n){if(!e.id)return{error:"Resolved pool has no identifier"};let r=e.protocolVersion??"V3",o=r==="V4"?await this.service.getV4PoolDetail({poolId:e.id,chain:t}):r==="V2"?ea.test(e.id)?await this.service.getV2PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V2 pair has no valid address"}:ea.test(e.id)?await this.service.getV3PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V3 pool has no valid address"};if(!o.success||!o.data)return{error:o.error||"Failed to fetch pool detail"};let s={...this.formatPoolDetail(o.data),...Ee(t,e.id)},i=await this.pool.isAddLiquiditySupported(t)?Ne([s],n,P(t)):[];return{_instructions:`The address is a Uniswap ${r} pool. `+ye+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), protocol version, and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, token1 reserve + USD price, and total tx count. For V4 pools also mention tickSpacing, isDynamicFee, and the hook address if present. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+be+we+se+Ue+(i.length>0?Re:""),resolvedAs:"pool",chain:t,protocolVersion:r,pool:s,...i.length>0?{actionButtons:i}:{}}}async handleTokenHit(e,t,n){let r=e.symbol?.trim();if(!r)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let o=await this.service.searchPools({query:r,chain:t,page:1,size:100,protocolVersion:"V3"});if(!o.success)return{error:o.error||"Failed to fetch pools for resolved token"};let s=(e.address??"").toLowerCase(),l=[...(o.data??[]).filter(d=>{let p=(d.token0?.address??"").toLowerCase(),m=(d.token1?.address??"").toLowerCase();return p===s||m===s})].sort((d,p)=>(p.volumeUsd24hr??0)-(d.volumeUsd24hr??0)).slice(0,10),c=l.map(d=>({...this.formatPoolCandidate(d),...Ee(t,d.id)})),u=await this.pool.isAddLiquiditySupported(t)?Ne(c,n,P(t)):[];return{_instructions:"The address is a token, not a pool. Tell the user which token it is (symbol + name), then render the matching pools as a numbered list: pair (token0/token1 symbols), fee tier (%), protocol version, 24h volume (USD). Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. Ask which pool they want detail on; when they answer, re-call this tool with that pool address to fetch the detail. Format numbers human-readably. Omit null fields. Do NOT mention tool/API names."+(u.length>0?Re:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...u.length>0?{actionButtons:u}:{}}}findPoolByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.id??"").toLowerCase()===n)}findTokenByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.address??"").toLowerCase()===n)}formatToken(e){return{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,isSpam:e.isSpam,safetyLevel:e.safetyLevel}}formatPoolCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}formatPoolDetail(e){let t=e.totalLiquidity?.value,n=e.volume24h?.value,r=e.feeTier,o=typeof r=="number"?r/1e4:void 0,s=typeof n=="number"&&typeof o=="number"?n*o/100:void 0,i=typeof s=="number"&&typeof t=="number"&&t>0?s/t*gc*100:void 0,l=typeof n=="number"&&typeof t=="number"&&t>0?Math.round(n/t*1e3)/1e3:void 0;return{address:e.address??e.poolId,protocolVersion:e.protocolVersion,poolId:e.poolId,tickSpacing:e.tickSpacing,isDynamicFee:e.isDynamicFee,hookAddress:e.hook?.address,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:s,aprPercent:i,volumeToTvlRatio:l,txCount:e.txCount,historicalVolumeWeek:this.formatHistorical(e.historicalVolume),token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.market?.price?.value??e.token0.price?.value,reserve:e.token0Supply,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.market?.price?.value??e.token1.price?.value,reserve:e.token1Supply,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var fc=/^0x[a-fA-F0-9]{40}$/,cn=class extends v{name="open-add-liquidity-form";kind="ui";category="pool-action";description='Open the Add-Liquidity form for a specific Uniswap V3 pool. Use this when the user wants to provide liquidity / add LP / farm / stake / deposit into a pool \u2014 natural-language verbs in any language all map here. Resolves the pool by token symbols (and optional fee tier), reads on-chain state, checks the connected wallet\'s NATIVE balance, then returns a UI payload that the FE renders as the form (with two preset ranges: Stable \xB13 ticks and Wide -50%/+100%). CONSTRAINT: the gateway only accepts the chain\'s NATIVE coin as input (ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche). The native amount is auto-split via deBridge into both pool tokens \u2014 the user never selects a different input. If the user asks to add liquidity using a NON-NATIVE token amount (e.g. "add pool with 5 USDT", "th\xEAm 100 USDC"), pass that symbol via `requestedNonNativeToken` so the tool can return error="unsupported_input_token" \u2014 never silently convert their non-native amount into native or USD. PRECONDITION: a connected wallet (userContext.walletAddress). If absent, the tool returns error="wallet_not_connected" and the agent must ask the user to connect.';parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Required to uniquely identify the pool.',required:!0},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. Omit when unknown \u2014 the tool will resolve the best match automatically.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prefillNativeAmount",type:"number",description:"Optional NATIVE-COIN amount (human-readable) to pre-fill the form's input field. ONLY pass this when the user named an amount in the chain's native coin itself \u2014 ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche. Example: \"add 0.1 ETH to USDC/WETH on Base\". Pass the plain decimal number (e.g. 0.1 for 0.1 ETH). DO NOT convert a non-native amount (USDC, USDT, DAI, WBTC, \u2026) into native here \u2014 pass `requestedNonNativeToken` instead so the tool can reject. Mutually exclusive with prefillUsdAmount \u2014 pass one or neither.",required:!1},{name:"prefillUsdAmount",type:"number",description:'Optional USD amount to pre-fill the form\'s input field. Use this ONLY when the user explicitly speaks in USD/dollars \u2014 e.g. "add $10 to this pool", "10 dollars", "10 \u0111\xF4". The tool converts the USD value to native amount automatically using the current native-token price. DO NOT use this as a workaround for non-native token amounts (e.g. "5 USDT" is NOT $5 \u2014 USDT may de-peg, and even if 1:1 the user asked for a token, not USD). For non-native token amounts pass `requestedNonNativeToken` instead. Mutually exclusive with prefillNativeAmount \u2014 pass one or neither.',required:!1},{name:"requestedNonNativeToken",type:"string",description:`Set this ONLY when the user named an AMOUNT in a non-native token \u2014 e.g. "add pool with 5 USDT", "add 100 USDC to USDC/WETH", "th\xEAm 5 USDT v\xE0o pool". The trigger is "<number> <non-native-symbol>" in the user's message, NOT the mere appearance of the symbol. Pass the symbol the user attached the amount to (e.g. "USDT", "USDC", "DAI"). CRITICAL: If the user also names a NATIVE amount in the same message (e.g. "add USDC/WETH with 0.1 ETH", "th\xEAm pool USDC/WETH 0.3% v\u1EDBi 0.000005 ETH"), the native amount is the input \u2014 leave this EMPTY and use prefillNativeAmount. The pool pair symbols (the two tokens after "pool" / "to") are NEVER the input token by themselves \u2014 they only identify which pool. The tool will return error="unsupported_input_token" so the agent can tell the user that only the chain's native coin is accepted as input. DO NOT silently convert the user's non-native amount into a native amount or USD amount \u2014 the user explicitly named a different asset and must be informed, not auto-corrected. Leave empty when the user did name a native amount, a USD amount, or no amount at all.`,required:!1},{name:"rangeStrategy",type:"string",description:'Optional preset that pre-fills the min/max price inputs (FE keeps them editable). One of: "stable" \u2014 \xB13 tickSpacing around the current price (narrow, higher yield, higher out-of-range risk; pick for stablecoin / low-volatility pairs and when the user says "safe", "tight", "high yield", "t\u1EADp trung"); "wide" \u2014 currentPrice \xD7 [0.5, 2.0] (broad, lower yield, less rebalancing; pick when the user says "wide", "set and forget", "r\u1ED9ng"); "full" \u2014 full V3 tick range (V2-style, lowest yield, never goes out of range; pick when the user says "full range", "v2-style", "kh\xF4ng lo out of range"). Omit when the user did not signal a preference AND did not provide explicit minPrice/maxPrice. Mutually exclusive with minPrice/maxPrice \u2014 if both are passed, explicit prices win.',required:!1},{name:"minPrice",type:"number",description:'Optional explicit lower bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 minPrice=1800. Must be paired with maxPrice. When set, overrides rangeStrategy.',required:!1},{name:"maxPrice",type:"number",description:'Optional explicit upper bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 maxPrice=2200. Must be paired with minPrice. When set, overrides rangeStrategy.',required:!1},{name:"add_button_label",type:"string",description:`Label template for the per-fee-tier "Add liquidity" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. ALWAYS pass this when you call the tool with a pair but NO feeTier (the tool may return several fee-tier variants for the pair, and each gets a one-tap button). Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:'A short "add liquidity" command template IN THE USER\'S CURRENT LANGUAGE, submitted as the next user turn when a fee-tier button is clicked \u2014 it carries the chosen fee tier so the tool resolves that exact pool. ALWAYS pass this alongside `add_button_label` when calling with a pair but no feeTier. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain this pair is on is appended to the prompt automatically.',required:!1}];uniswap;pool;coinPool;minProvideUsd;constructor(e){super(),this.uniswap=new pe(e),this.pool=new ce(e?.pool),this.coinPool=new tt(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),o&&typeof o=="object"&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(s.actionButtons=o.actionButtons),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=await he(on(this.pool),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",s=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,c=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,u=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,d=u&&l!=null&&(u.toLowerCase()===o.toLowerCase()||u.toLowerCase()===s.toLowerCase())?null:u,p=this.parseRangeStrategy(e.rangeStrategy),m=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,f=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!o||!s)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let h=oe(r);if(!h)return{error:"unsupported_chain",chain:r,_instructions:`Chain ${r} is not supported by the add-liquidity flow.`};let g=nn(r);if(d&&g&&d.toLowerCase()!==g.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:d,nativeSymbol:g.symbol,chainName:h.name,_instructions:`The user asked to add liquidity using ${d}, but this app only supports the chain's native coin (${g.symbol} on ${h.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${g.symbol} or in USD. DO NOT silently convert their ${d} amount, do NOT pre-fill the form, and do NOT call this tool again until the user provides a native or USD amount.`};let y=await this.pool.getGatewayAddress(r);if(!y)return{error:"no_gateway_configured",chain:r,_instructions:`No gateway contract is configured for chain ${r} (${h.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let b=t?.walletAddress;if(!b)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before adding liquidity. Do NOT render the form."};let w=await this.uniswap.searchPools({query:`${o} ${s}`,chain:r,page:1,size:100,protocolVersion:"V3",feeTier:i});if(!w.success)return{error:w.error||"pool_search_failed"};let k=w.data??[],T=k.find(L=>this.matchesPairExact(L,o,s,i)),S=T?[]:k.filter(L=>this.matchesPair(L,o,s,i));if(!T&&S.length===0)return{error:"pool_not_found",_instructions:`No V3 pool found for ${o}/${s}${i!=null?` at ${i}bps`:""} on ${h.name}. Verify the inputs with the user.`};if(!T&&S.length>1){let L=S.map(J=>{let mt=J.volume1DayUsd??J.volumeUsd24hr,so=J.tvlUsd,Lr=typeof mt=="number"&&typeof so=="number"&&so>0?mt/so:void 0;return{address:J.id,token0Symbol:J.token0?.symbol,token1Symbol:J.token1?.symbol,feeTier:J.feeTier,feeTierPercent:J.feeTier!=null?J.feeTier/1e4:void 0,volume24hUsd:mt,tvlUsd:so,...Lr!=null?{volumeToTvlRatio:Lr}:void 0,...J.apr?{apr:J.apr}:void 0}}).sort((J,mt)=>(mt.volumeToTvlRatio??mt.apr??-1/0)-(J.volumeToTvlRatio??J.apr??-1/0)).slice(0,5),Ko=Cr(L.map(J=>({token0:{symbol:J.token0Symbol},token1:{symbol:J.token1Symbol},feeTierPercent:J.feeTierPercent})),typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",P(r));return{relatedPools:L,count:L.length,...Ko.length>0?{actionButtons:Ko}:{},_instructions:ye+"The user wants to ADD LIQUIDITY to this pair but named NO fee tier \u2014 `relatedPools` holds the related pools (the pair's fee-tier variants and closely-matching pools). Do NOT just ask them to pick blindly: give a genuine comparative read. Present them as a ranked list (rank by capital efficiency / fee yield, not just TVL); for each show the fee tier (%), TVL (USD), 24h volume (USD), and estimated APR (%) when present. Analyze each with its own real read \u2014 never skip one or repeat the same sentence structure. "+be+"Focus on which fee tier is the best home for THIS pair to LP in: lower tiers (0.01\u20130.05%) suit stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 the tier that captures most of the real volume on deep TVL is usually the one to provide liquidity in. Close by naming the single best fee tier to add liquidity in right now and why, then invite the user to confirm a tier to continue. When they choose, re-run the add-liquidity step with token0Symbol + token1Symbol + the chosen feeTier (in bps). "+we+se+Ue+(Ko.length>0?' A clickable "Add liquidity" button is shown below your reply for each fee-tier candidate automatically \u2014 do NOT list, number, or repeat those buttons.':"")}}let A=T??S[0];if(!A.id||!fc.test(A.id))return{error:"invalid_pool_address"};let _=this.fetchPriceRanges(r,A.id,A.token0?.symbol,A.token1?.symbol),R=await this.pool.readPoolOnchain(r,A.id),[C,M,E]=await Promise.all([this.pool.getNativeBalance(r,b),this.pool.estimateGasReserveWei(r),this.pool.getNativePriceUsd(r)]),Q=C>M?C-M:0n,O=nn(r),Ie=Number(Q)/10**O.decimals,ge=Number(C)/10**O.decimals,G=E!=null?Ie*E:null,[Be,ae]=await Promise.all([this.pool.readErc20Decimals(r,R.token0),this.pool.readErc20Decimals(r,R.token1)]),ot={min:Ce(je,Be,ae),max:Ce(gt,Be,ae)},Ye=null;C===0n?Ye="no_balance":G!=null&&G<this.minProvideUsd&&(Ye="insufficient_balance");let rt=A.token0,st=A.token1,Dn=[25,50,75,100].map(L=>({percent:L,amountWei:(Q*BigInt(L)/100n).toString(),amount:Ie*(L/100)})),On=null,at=null;if(l!=null){at=l;let L=BigInt(Math.floor(at*10**O.decimals));L>0n&&(On=L.toString())}else if(c!=null&&E!=null&&E>0){at=c/E;let L=BigInt(Math.floor(at*10**O.decimals));L>0n&&(On=L.toString())}let ro={address:B,isNative:!0,symbol:O.symbol,name:O.name,decimals:O.decimals,priceUsd:E,balanceWei:C.toString(),balance:ge,gasReserveWei:M.toString(),spendableWei:Q.toString(),spendable:Ie,spendableUsd:G,quickRates:Dn,minProvideUsd:this.minProvideUsd,warning:Ye,warningMessage:Ye==="no_balance"?`You have no ${O.symbol} on ${h.name}. Top up to add liquidity.`:Ye==="insufficient_balance"?`Spendable ${O.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:at,prefillAmountWei:On},it=this.computePrefillRange({explicitMinPrice:m,explicitMaxPrice:f,rangeStrategy:p,currentPrice:R.currentPrice,currentTick:R.currentTick,tickSpacing:R.tickSpacing,token0Decimals:Be,token1Decimals:ae,priceBounds:ot}),Ur={component:"AddLiquidityForm",props:{chain:{hexId:r,name:h.name},pool:{address:R.poolAddress,fee:R.fee,feePercent:R.fee/1e4,tickSpacing:R.tickSpacing,currentTick:R.currentTick,currentPrice:Z(R.currentPrice),sqrtPriceX96:R.sqrtPriceX96.toString(),token0:{address:R.token0,symbol:rt?.symbol,name:rt?.name,logo:rt?.logo},token1:{address:R.token1,symbol:st?.symbol,name:st?.name,logo:st?.logo}},inputToken:ro,priceBounds:ot,prefillRange:it,gatewayAddress:y}},Ir=this.orientRangesToForm(await _,R.currentPrice,rt?.symbol,st?.symbol);return{ui:Ur,suggestedRanges:Ir,summary:this.buildSummary({chainName:h.name,pair:`${rt?.symbol??o}/${st?.symbol??s}`,feePercent:R.fee/1e4,warning:Ye,minProvideUsd:this.minProvideUsd,nativeSymbol:O.symbol}),_instructions:'The add-liquidity action is ready. In the user\'s language, invite them to enter the amount and price range to add liquidity, naming the pool + chain (e.g. "Enter the amount and price range to add liquidity to <pool> on <chain>"). Speak ONLY of the user\'s action (adding liquidity). NEVER say you "opened a form", "opened" anything, or describe any screen/form/window/UI being shown \u2014 phrase it as the next step the user takes, not as something you did. If warning="no_balance" tell them they need to top up. If warning="insufficient_balance" tell them the balance is below the minimum. REFERENCE RANGES: when `suggestedRanges` is a non-empty array, briefly offer 1\u20133 of them (highest `apr` first) as price ranges the user can REFERENCE when filling in their range \u2014 for each give the min\u2013max (`minPrice`\u2013`maxPrice`) and its `apr`. These prices are ALREADY in the SAME unit the form shows (`quoteSymbol` per `baseSymbol`), so quote them as-is \u2014 do NOT invert them. CRITICAL: that `apr` is the yield for THAT specific range ONLY \u2014 NEVER present it as the overall pool APR; narrower = higher out-of-range risk. These are only in-range suggestions to reference \u2014 the user still chooses their own range. When `suggestedRanges` is empty or absent, omit this entirely. '+se+"Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, data sources, or internal tool names. Wait for the user to fill in amount + price range before proceeding."}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let o=await this.coinPool.getByAddress({chain:e,poolAddress:t});return o.length===0&&n&&r&&(o=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),o.sort((s,i)=>(i.apr??-1/0)-(s.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,n,r){let o=s=>Number.isFinite(s)&&s>0;return o(t)?e.map(s=>{let{minPrice:i,maxPrice:l,currentPrice:c}=s.priceRange,u=i,d=l,p=c;if(o(c)){let m=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<m&&(u=o(l)?1/l:0,d=o(i)?1/i:0,p=1/c)}return{fee:s.fee,apr:s.apr,minPrice:Z(u),maxPrice:Z(d),currentPrice:Z(p),baseSymbol:n,quoteSymbol:r}}).filter(s=>o(s.minPrice)&&o(s.maxPrice)):[]}matchesPairExact(e,t,n,r){if(!r||r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),s=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase();return o===i&&s===l||o===l&&s===i}matchesPair(e,t,n,r){if(r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),s=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase(),c=this.symMatch(o,i)&&this.symMatch(s,l),u=this.symMatch(o,l)&&this.symMatch(s,i);return c||u}symMatch(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}parseRangeStrategy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="stable"||t==="wide"||t==="full"?t:null}computePrefillRange(e){let{explicitMinPrice:t,explicitMaxPrice:n,rangeStrategy:r,currentPrice:o,priceBounds:s}=e;if(t!=null&&n!=null&&n>t){let{minPrice:i,maxPrice:l}=ft(t,n,o);return{strategy:"user",minPrice:Math.max(i,s.min),maxPrice:Math.min(l,s.max)}}if(r==="full")return{strategy:"full",minPrice:s.min,maxPrice:s.max};if(r==="stable"||r==="wide"){let l=Sr({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===r);if(l)return{strategy:r,minPrice:l.minPrice,maxPrice:l.maxPrice}}return null}buildSummary(e){let t=[`Ready to add liquidity to the ${e.pair} ${e.feePercent}% pool on ${e.chainName}. Enter an amount and a price range to continue.`];return e.warning==="no_balance"?t.push(`You'll need some ${e.nativeSymbol} on ${e.chainName} first \u2014 top up to continue.`):e.warning==="insufficient_balance"&&t.push(`Your spendable ${e.nativeSymbol} is below the $${e.minProvideUsd} minimum \u2014 top up before continuing.`),t.join(" ")}};var ta=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}],Io=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]}];var yc=/^0x[a-fA-F0-9]{40}$/,un=class extends v{name="preview-add-liquidity";kind="action";category="pool-action";description='Preview the add-liquidity transaction. Call this whenever a concrete pool ADDRESS, a native amount, and BOTH min and max price (in token1 per token0) are known \u2014 whether the user filled the AddLiquidityForm OR stated all of them directly in chat (e.g. "add to USDC/WETH with 0.01 ETH, range 0.0005-0.0007, pool=0x\u2026"). Do NOT require the form to have been opened first. The tool converts prices \u2192 ticks (rounded to tickSpacing), fetches deBridge swap quotes for both legs, encodes the gateway.mint call, and returns an unsigned tx the FE will sign. REQUIRES the exact poolAddress (from open-add-liquidity-form props.pool.address or given by the user) \u2014 if only token symbols / a fee tier are known, resolve the pool via open-add-liquidity-form first.';parameters=[{name:"poolAddress",type:"string",description:"V3 pool contract address (returned by open-add-liquidity-form in props.pool.address).",required:!0},{name:"chain",type:"string",description:`Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea .Must match the pool's chain. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.`,required:!1},{name:"minPrice",type:"number",description:`Lower bound of the position price range, in token1-per-token0 units (decimal-adjusted \u2014 the SAME unit as pool.currentPrice from open-add-liquidity-form). Example: if currentPrice is 1800 (USDC per WETH), minPrice 900 means "the position is in-range while WETH \u2265 900 USDC". Must be >= 0 and < maxPrice. Pass 0 for a "full-range lower" position (the range extends down to price 0, i.e. Uniswap's MIN_TICK). CRITICAL: copy the number the user gave VERBATIM \u2014 every digit and every leading zero. Do NOT add or drop a zero, round, or rescale it. Tiny decimals like 0.000533 are easy to mis-transcribe (0.000533 must stay 0.000533, NEVER 0.0000533). If unsure, prefer the user's exact characters over your own reformatting.`,required:!0},{name:"maxPrice",type:"number",description:`Upper bound of the position price range, in the same units as minPrice. Must be > minPrice. Pass a very large number (or props.priceBounds.max) for a "full range upper" position. CRITICAL: copy the user's number VERBATIM \u2014 every digit and leading zero; never add/drop a zero, round, or rescale.`,required:!0},{name:"nativeAmount",type:"number",description:"Native amount the user wants to spend, as a human-readable decimal number (e.g. 0.1 for 0.1 ETH). The tool converts to wei internally.",required:!0},{name:"slippageBps",type:"number",description:"Slippage tolerance in basis points (100 = 1%). Optional \u2014 defaults to 100.",required:!1}];pool;defaultSlippageBps;mintMinPercent;pantograph;constructor(e){super(),this.pool=new ce(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new le}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=await he(on(this.pool),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=Number(e.minPrice),i=Number(e.maxPrice),l=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,c=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!n||!o||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!yc.test(n))return{error:"invalid_pool_address",_instructions:"poolAddress is not a valid EVM address. Re-open the add-liquidity form to get the correct pool address."};if(s<0||i<=0||s>=i)return{error:"invalid_price_range",_instructions:"minPrice must be >= 0 (0 = full-range lower), maxPrice must be > 0, and minPrice must be strictly less than maxPrice."};if(l<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let u=oe(o);if(!u)return{error:"unsupported_chain",chain:o};let d=await this.pool.getGatewayAddress(o);if(!d)return{error:"no_gateway_configured",chain:o};let p=t?.walletAddress;if(!p)return{error:"wallet_not_connected"};let m=nn(o),f=BigInt(Math.floor(l*10**m.decimals));if(f<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let h=await this.pool.readPoolOnchain(o,n),[g,y]=await Promise.all([this.pool.readErc20Decimals(o,h.token0),this.pool.readErc20Decimals(o,h.token1)]),{minPrice:b,maxPrice:w}=ft(s,i,h.currentPrice),k=b===0?je:ct(b,g,y),T=ct(w,g,y),S=b===0?De(Le(je,h.tickSpacing,"up")):De(Le(k,h.tickSpacing,"down")),A=De(Le(T,h.tickSpacing,"up"));if(S>=A||S<je||A>gt)return{error:"invalid_range_after_alignment",_instructions:"After aligning to tickSpacing the range collapsed. Ask the user for a wider price range.",rawTickLower:k,rawTickUpper:T,tickLower:S,tickUpper:A};let _={tickLower:S,tickUpper:A,minPrice:Z(Ce(S,g,y)),maxPrice:Z(Ce(A,g,y))},R=h.currentTick;if(R<S||R>=A){let L=R<S?"below":"above";return{error:"out_of_range",_instructions:`The chosen price range does NOT include the pool's current price, so this would be an OUT-OF-RANGE position (it would sit entirely in one token and earn no fees until the price moves back into the range). The current price is ${L==="below"?"BELOW":"ABOVE"} the chosen range. Tell the user (in their language) that their range is out of range, show the current price and their chosen min/max, and ask them to pick a range that brackets the current price. Do NOT proceed with the transaction. Do NOT mention tool names.`,currentPrice:Z(h.currentPrice),requestedRange:{minPrice:_.minPrice,maxPrice:_.maxPrice},side:L}}let[C,M,E]=await Promise.all([this.pool.getNativeBalance(o,p),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),Q=f+M;if(C<Q)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:C.toString(),requiredWei:Q.toString(),gasReserveWei:M.toString()};let O=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:h,tickLower:S,tickUpper:A,token0Decimals:g,token1Decimals:y}),Ie=h.token0.toLowerCase()===B,ge=h.token1.toLowerCase()===B,G=[];if(Ie||O.amountInFor0Wei===0n)G.push({tokenIn:B,tokenOut:h.token0,amountIn:O.amountInFor0Wei,tx:{to:B,data:"0x",value:"0"},minAmountOut:Ie?O.amountInFor0Wei:0n});else{let L=await this.pool.fetchSwapLeg({senderAddress:p,chainId:o,tokenIn:B,tokenInAmount:O.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:d,slippage:typeof c=="number"?c:"auto"});G.push({tokenIn:B,tokenOut:h.token0,amountIn:O.amountInFor0Wei,tx:{to:L.to,data:L.data,value:L.value},minAmountOut:BigInt(L.minAmountOut||"0")})}if(ge||O.amountInFor1Wei===0n)G.push({tokenIn:B,tokenOut:h.token1,amountIn:O.amountInFor1Wei,tx:{to:B,data:"0x",value:"0"},minAmountOut:ge?O.amountInFor1Wei:0n});else{let L=await this.pool.fetchSwapLeg({senderAddress:p,chainId:o,tokenIn:B,tokenInAmount:O.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:d,slippage:typeof c=="number"?c:"auto"});G.push({tokenIn:B,tokenOut:h.token1,amountIn:O.amountInFor1Wei,tx:{to:L.to,data:L.data,value:L.value},minAmountOut:BigInt(L.minAmountOut||"0")})}let Be=L=>L*BigInt(this.mintMinPercent)/100n,ae=Be(G[0].minAmountOut),ot=Be(G[1].minAmountOut),Ye=G.map(L=>({tokenIn:L.tokenIn,tokenInAmount:BigInt(L.amountIn),tokenOut:L.tokenOut,tokenOutAmount:BigInt(L.minAmountOut)})),rt=G.map(L=>({to:L.tx.to,data:L.tx.data,value:BigInt(L.tx.value||"0")})),st=ht({abi:ta,functionName:"mint",args:[Ye,rt,{fee:Number(h.fee),amount0Min:BigInt(ae),amount1Min:BigInt(ot),tickLower:S,tickUpper:A}]}),Dn=l,On={chainId:o,to:d,data:st,value:f.toString(),from:p},at={nativeIn:Dn,nativeSymbol:m.symbol,nativeInUsd:E!=null?Dn*E:null,ratio:{token0Percent:O.ratio0,token1Percent:O.ratio1},expectedToken0:Number(G[0].minAmountOut)/10**g,expectedToken1:Number(G[1].minAmountOut)/10**y,amount0Min:ae.toString(),amount1Min:ot.toString(),slippageBps:c},ro=await this.pantograph.getTokensMetadata([h.token0,h.token1],o),it=ro[h.token0],pt=ro[h.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:o,name:u.name},unsignedTx:On,summary:at,pool:{...h,feePercent:h.fee/1e4,currentPrice:Z(h.currentPrice),token0:{address:h.token0,symbol:it?.auditGoplus?.token_symbol||it.symbol,name:it.name,decimals:it.decimals,logo:it.icon_image},token1:{address:h.token1,symbol:pt?.auditGoplus?.token_symbol||pt.symbol,name:pt.name,decimals:pt.decimals,logo:pt.icon_image}},range:_,gatewayAddress:d}},summary:`Ready to add ${Dn} ${m.symbol} to pool ${h.token0}/${h.token1} ${h.fee/1e4}% on ${u.name}, range [${_.minPrice}, ${_.maxPrice}].`,_instructions:"A confirmation panel has been opened on the FE; the user will sign and broadcast the unsigned tx with their wallet. Briefly tell them (in their language) what is about to happen \u2014 the native amount, the auto-split ratio between the two pool tokens, and the chosen price range. Do NOT mention internal tool/component names."}}};var na=365,bc=1e3,wc=/^0x[a-fA-F0-9]{40}$/;function kc(a,e){return{depositUsd:a,aprPercent:e*100,dailyUsd:a*e/na,weeklyUsd:a*e/52,monthlyUsd:a*e/12,yearlyUsd:a*e}}var dn=class extends v{name="estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap V3 pool. Answers questions like: "If I put $1000 into the USDC/WETH 0.05% pool, how much per day?", "b\u1ECF 500$ v\xE0o pool ETH/USDC 0.3% m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "APR of WBTC/ETH 0.3% on Arbitrum". BEHAVIOR (designed to minimize back-and-forth with the user):
179
+ }`,r=await this.querySubgraph(t,n);if(!r?.position?.pool)return null;let o=r.position,s=this.mapPool(o.pool,t),i=await this.fetchDefiLlamaUniswap(),l=i.length>0?this.enrichWithLlama([s],i)[0]:s,c=l.feeTierBps,d=l.feeTierPercent;return{position:{positionId:o.id,poolAddress:l.poolAddress,pair:l.pair,token0:{symbol:l.token0.symbol,address:l.token0.address},token1:{symbol:l.token1.symbol,address:l.token1.address},feeTierBps:c,feeTierPercent:d,chain:l.chain,liquidity:o.liquidity,depositedToken0:o.depositedToken0,depositedToken1:o.depositedToken1,withdrawnToken0:o.withdrawnToken0,withdrawnToken1:o.withdrawnToken1,collectedFeesToken0:o.collectedFeesToken0,collectedFeesToken1:o.collectedFeesToken1},pool:l}}async getCoinPoolPairs(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchCoinPoolV2Items(t)).map(o=>this.mapCoinPoolV2Item(o)).filter(o=>o!==null);if(e.tokens&&e.tokens.length>=2){let o=e.tokens[0].toUpperCase(),s=e.tokens[1].toUpperCase();r=r.filter(i=>{let[l="",c=""]=i.pair.toUpperCase().split("/");return l.includes(o)&&c.includes(s)||l.includes(s)&&c.includes(o)})}return r}async getCoinPoolByAddress(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(o=>o.poolId?.toLowerCase()===n).map(o=>this.mapCoinPoolV2Item(o)).filter(o=>o!==null).sort((o,s)=>(s.apr??-1/0)-(o.apr??-1/0))}async fetchCoinPoolV2Items(e){if(!this.coinPoolBaseUrl)return[];try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(I(n));return n.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=S=>S==null||!Number.isFinite(S)?0:Math.pow(1.0001,S)*Math.pow(10,t-n),o=r(e.minTick),s=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,d=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),u=d?o:s>0?1/s:0,p=d?s:o>0?1/o:0,m=d?c:c>0?1/c:0,f=d?e.token0.symbol:e.token1.symbol,h=d?e.token1.symbol:e.token0.symbol;if(!m||!u&&!p)return null;let g=Math.min(u,p),y=Math.max(u,p);if(m<g||m>y)return null;let b=Number(e.fee),w=Ws[b]??b/1e4,k=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,T=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:T,token0Price:i,token1Price:l,priceRange:{minPrice:Z(u),maxPrice:Z(p),currentPrice:Z(m),baseToken:f,quoteToken:h}}}};var Ze=class{config;constructor(e){this.config=e}hasIntegratedApproval(){return!1}};var Rl="https://exchange-api.keyring.app/admin/setting?configs=others",Nl="https://api.coinpool.app/config/bridgeProviderByChain",Ul="https://coinpool-api-op.bacoor-test001.xyz/config/bridgeProviderByChain";function Il(a){let e=null,t=null;return async()=>e||t||(t=(async()=>{try{return e=await a(),e}catch{return null}finally{t=null}})(),t)}async function Gs(a){return(await x.get(a,{headers:{Accept:"application/json"}})).data}var Ll=Il(async()=>(await Gs(Rl))?.others??null),Po={prod:null,dev:null},Gn={prod:null,dev:null};async function Dl(a){let e=a?"prod":"dev";if(Po[e])return Po[e];if(Gn[e])return Gn[e];let t=a?Nl:Ul;return Gn[e]=(async()=>{try{let n=await Gs(t);return Po[e]=n?.data??null,Po[e]}catch{return null}finally{Gn[e]=null}})(),Gn[e]}function Ol(a){if(!a)return null;try{let e=JSON.parse(a);return e&&typeof e=="object"?e:null}catch{return null}}function Hs(a){if(a==null)return 0;let e=typeof a=="number"?a:Number(a);return Number.isFinite(e)?e:0}function Ml(a){return a==="debridge"||a==="relay"}async function xo(a,e){let n=(await Dl(e))?.[String(a)];return Ml(n)?n:null}async function Zt(a,e){let t=await Ll();if(!t)return null;let n,r;if(a==="debridge")n=Ol(t.affiliateRecipient)?.[String(e)],r=Hs(t.AFFILIATE_FEE_PERENT);else if(a==="relay")n=t.RELAY_AFFILIATE_FEE_RECIPIENT,r=Hs(t.RELAY_AFFILIATE_FEE_PERCENT);else return null;return!n||r<=0?null:{affiliateFeeRecipient:n,affiliateFeePercent:r}}var Fl="https://dln.debridge.finance/v1.0",ql="0x0000000000000000000000000000000000000000",Bl=new Set([429,500]),$l=5,Vl=1e3,Wl=a=>new Promise(e=>setTimeout(e,a)),en=class extends Ze{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Fl,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:o,dstTokenAddress:s,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:d}=e,u=d??t!==o,p=await Zt(this.getProviderName(),t);try{if(u){let h={srcChainId:String(t),srcChainTokenIn:n,srcChainTokenInAmount:r,dstChainId:String(o),dstChainTokenOut:s,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:l,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent);let g=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,h);return g.error||g.errorMessage?{success:!1,error:g.error??g.errorMessage,errorMessage:g.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:g.tx,estimation:g.estimation,isCrossChain:!0,srcChainId:t,dstChainId:o,raw:g}}let m={chainId:String(t),tokenIn:n,tokenInAmount:r,tokenOut:s,tokenOutRecipient:i,accesstoken:this.accessToken};p&&(m.affiliateFeeRecipient=p.affiliateFeeRecipient,m.affiliateFeePercent=p.affiliateFeePercent),c!==void 0&&(m.slippage=c);let f=await this.get(`${this.apiBaseUrl}/chain/transaction`,m);return f.error||f.errorMessage?{success:!1,error:f.error??f.errorMessage,errorMessage:f.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:f.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:f}}catch(m){return{success:!1,error:m,errorMessage:m instanceof Error?m.message:"Failed to fetch quote"}}}async checkApproval(e){let{chain:t,userAddress:n,tokenAddress:r,amount:o}=e,s=e.quoteData?.tx?.to;if(!s)return{isNeeded:!1,error:"No contract address found in quote"};if(!r||r.toLowerCase()===ql)return{isNeeded:!1,integrated:!1,contractAddress:s,message:"Native coin needs no approval."};let i=await this.readAllowance(t,r,n,s);if(i===null)return{isNeeded:!0,integrated:!1,contractAddress:s,message:"Could not read allowance; approval required before the swap."};let l;try{l=BigInt(o)}catch{l=0n}return i>=l?{isNeeded:!1,integrated:!1,contractAddress:s,message:"Sufficient allowance already granted."}:{isNeeded:!0,integrated:!1,contractAddress:s,message:"Approval required: current allowance is below the swap amount."}}async readAllowance(e,t,n,r){if(!e)return null;let o=l=>l.toLowerCase().replace(/^0x/,"").padStart(64,"0"),s=`0xdd62ed3e${o(n)}${o(r)}`,i=await sr(e,t,s);if(typeof i!="string"||!/^0x[0-9a-fA-F]*$/.test(i)||i==="0x")return null;try{return BigInt(i)}catch{return null}}async executeSwap(e){let{quoteData:t}=e;return{success:!0,provider:"debridge",txData:t.tx??void 0,estimation:t.estimation}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let n=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!n.orderIds?.length)return{success:!1,status:"PENDING"};let r=n.orderIds[0];switch(((await this.get(`${this.apiBaseUrl}/dln/order/${r}/status`,{accesstoken:this.accessToken})).status??"").toUpperCase()){case"FULFILLED":case"SENTUNLOCK":case"CLAIMEDUNLOCK":return{success:!0,status:"COMPLETED"};case"ORDERCANCELLED":case"SENTORDERCANCEL":case"CLAIMEDORDERCANCEL":return{success:!0,status:"FAILED"};default:return{success:!0,status:"PENDING"}}}catch(n){return{success:!1,status:"ERROR",error:n instanceof Error?n.message:String(n)}}}async get(e,t){let n=Object.entries(t).map(([s,i])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(i))}`).join("&"),r=n?`${e}?${n}`:e,o=await x.get(r,{headers:{Accept:"application/json"}});for(let s=0;s<$l&&Bl.has(o.status);s++)await Wl(Vl),o=await x.get(r,{headers:{Accept:"application/json"}});return o.data}};var Hl="https://api.relay.link";function Ys(a){return a===7565164||a==="7565164"?792703809:a}var tn=class extends Ze{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Hl,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:o,dstTokenAddress:s,recipientAddress:i,senderAddress:l,slippage:c}=e,d=await Zt(this.getProviderName(),t),u={user:i||l,originChainId:Ys(t),destinationChainId:Ys(o),originCurrency:n,destinationCurrency:s,amount:r,recipient:i||l,tradeType:"EXACT_INPUT"};d&&(u.appFees=[{recipient:d.affiliateFeeRecipient,fee:Math.floor(d.affiliateFeePercent*100)}]),typeof c=="number"&&Number.isFinite(c)&&(u.slippageTolerance=Math.floor(c*100).toString());try{let p=await this.request("/quote/v2","POST",u);if(!p||p.error)return{success:!1,error:p?.error??"Unknown error",errorMessage:p?.message??"Failed to fetch quote from Relay"};let m=p.steps?.find(b=>b.id==="approve"),f=p.steps?.find(b=>b.id==="swap"||b.id==="deposit"),h=f?.items?.[0]?.data,g=Array.isArray(h?.instructions);return{success:!0,provider:"relay",tx:h?g?{data:{instructions:h.instructions??[],addressLookupTableAddresses:h.addressLookupTableAddresses??[]},chainId:h.chainId}:{from:h.from,to:h.to,data:h.data,value:h.value,chainId:h.chainId,maxFeePerGas:h.maxFeePerGas,maxPriorityFeePerGas:h.maxPriorityFeePerGas}:null,isCrossChain:t!==o,srcChainId:t,dstChainId:o,raw:{steps:p.steps,fees:p.fees,details:p.details,approveStep:m,requestId:f?.requestId}}}catch(p){return{success:!1,error:p,errorMessage:p instanceof Error?p.message:"Failed to fetch quote"}}}async checkApproval(e){let t=e.quoteData?.raw?.approveStep;if(t){let n=t.items?.[0]?.data;return{isNeeded:!0,integrated:!0,approvalData:n,contractAddress:n?.to,message:"Approval step is included in quote and will be executed first."}}return{isNeeded:!1,integrated:!0,message:"No approval needed or already approved"}}async executeSwap(e){let{quoteData:t}=e,n=t.raw;return n?.steps?{success:!0,provider:"relay",steps:n.steps,estimation:t.estimation}:{success:!1,error:"Invalid quote data"}}async trackTransaction(e){try{let n=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return n==="success"||n==="refunded"?{success:!0,status:"COMPLETED"}:n==="failure"||n==="expired"?{success:!0,status:"FAILED"}:{success:!0,status:"PENDING"}}catch(t){return{success:!1,status:"ERROR",error:t instanceof Error?t.message:String(t)}}}async request(e,t,n){let r={"Content-Type":"application/json"};this.apiKey&&(r["x-api-key"]=this.apiKey);let o=`${this.apiBaseUrl}${e}`,s;if(t==="GET"&&n){let l=Object.entries(n).map(([c,d])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`).join("&");o=`${o}?${l}`}else t==="POST"&&n&&(s=n);let i=await x.request(t,o,s,{headers:r});if(!i.ok)throw new Error(I(i));return i.data}};var Co={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},Yn="debridge";function Gl(a){if(a==null)return null;let e=typeof a=="number"?a:Number(a);return Number.isFinite(e)?e:null}var dt=class{providerConfig;isProduction;cache=new Map;constructor(e=Co,t=!0){this.providerConfig=e,this.isProduction=t}async getService(e){let t=await this.getActiveProvider(e),n=this.cache.get(t);if(n)return n;let r=this.createService(t);return this.cache.set(t,r),r}async getServiceByProvider(e){let t=this.cache.get(e);if(t)return t;let n=this.createService(e);return this.cache.set(e,n),n}async getActiveProvider(e){let t=Gl(e);return t===null?Yn:await xo(t,this.isProduction)??Yn}async isProviderActive(e,t){return await this.getActiveProvider(t)===e}getAvailableProviders(){return Object.keys(this.providerConfig)}clearCache(){this.cache.clear()}createService(e){let t=this.providerConfig[e]??{};switch(e){case"debridge":return new en(t);case"relay":return new tn(t);default:{let n=e;throw new Error(`Unknown swap provider: ${String(n)}`)}}}},Me=new dt;var Yl="https://api.coinpool.app/config/addresses",jl="https://coinpool-api-op.bacoor-test001.xyz/config/addresses",_o={prod:null,dev:null},jn={prod:null,dev:null};async function js(a){let e=a?"prod":"dev";if(_o[e])return _o[e];if(jn[e])return jn[e];let t=a?Yl:jl;return jn[e]=(async()=>{try{let r=(await x.get(t,{headers:{Accept:"application/json"}})).data;return _o[e]=r?.data??null,_o[e]}catch{return null}finally{jn[e]=null}})(),jn[e]}function Kl(a){let e=a.trim();if(/^0x[0-9a-fA-F]+$/.test(e)){let t=Number.parseInt(e,16);return Number.isFinite(t)?String(t):null}return/^\d+$/.test(e)?e:null}async function Ks(a,e,t){let n=await js(t);if(!n)return;let r=Kl(e);if(!r)return;let o=n[a]?.[r];return Array.isArray(o)?o[0]:typeof o=="string"?o:void 0}async function Eo(a,e){return Ks("createPoolProxyV3",a,e)}var zl=/^0x[0-9a-fA-F]{40}$/;async function Xl(a,e){let n=(await js(e))?.[a];if(!n||typeof n!="object")return[];let r=[];for(let[o,s]of Object.entries(n)){let i=Array.isArray(s)?s[0]:s;typeof i=="string"&&zl.test(i.trim())&&r.push(o)}return r}async function Ro(a){return Xl("createPoolProxyV3",a)}async function No(a,e){return Ks("nftPositionUniswap",a,e)}var B="0x0000000000000000000000000000000000000000",zs={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:Te["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:Te["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:Te["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:Te["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:Te["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:Te["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:Te["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:Te["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function oe(a){return zs[a.toLowerCase()]}function nn(a){return oe(a)?.native}var Xs="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function Sr(a){let e=a.stableTicks??3,t=a.widePercent??{down:50,up:100},n=Ce(a.currentTick,a.token0Decimals,a.token1Decimals),r=De(Le(a.currentTick-e*a.tickSpacing,a.tickSpacing,"down")),o=De(Le(a.currentTick+e*a.tickSpacing,a.tickSpacing,"up")),s=n*(1-t.down/100),i=n*(1+t.up/100),l=ct(s,a.token0Decimals,a.token1Decimals),c=ct(i,a.token0Decimals,a.token1Decimals),d=De(Le(l,a.tickSpacing,"down")),u=De(Le(c,a.tickSpacing,"up")),p=(m,f,h,g,y)=>{let b=Ce(g,a.token0Decimals,a.token1Decimals),w=Ce(y,a.token0Decimals,a.token1Decimals);return{id:m,label:f,description:h,tickLower:g,tickUpper:y,minPrice:b,maxPrice:w,minPercentChange:(b-n)/n*100,maxPercentChange:(w-n)/n*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",r,o),p("wide","Wide","Good for volatile pairs",d,u)]}var Ql=ue("slot0()"),Jl=ue("liquidity()"),Zl=ue("tickSpacing()"),ec=ue("fee()"),tc=ue("token0()"),nc=ue("token1()"),oc=ue("decimals()"),ce=class{swapFactory;isProduction;constructor(e){this.isProduction=e?.isProduction??!0,this.swapFactory=e?.swapFactory??(this.isProduction?Me:new dt(void 0,!1))}isSupported(e){if(!e)return!1;let t=$(e)??e.toLowerCase();return!!oe(t)}listSupportedChains(){return Object.keys(zs).filter(e=>_e(e))}getRpcUrl(e){let t=$e(e);if(t)return t;let n=oe(e);if(!n)throw new Error(`Unsupported chain: ${e}`);return n.defaultRpc}async getGatewayAddress(e){return Eo(e,this.isProduction)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await Ro(this.isProduction),t=[];for(let n of e){let r=$(n);r&&oe(r)&&!t.includes(r)&&t.push(r)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return No(e,this.isProduction)}async ethCall(e,t,n){return Ve(this.getRpcUrl(e),"eth_call",[{to:t,data:n},"latest"])}async getNativeBalance(e,t){let n=await Ve(this.getRpcUrl(e),"eth_getBalance",[t,"latest"]);return BigInt(n)}async getGasPrice(e){let t=await Ve(this.getRpcUrl(e),"eth_gasPrice",[]);return BigInt(t)}async getTransactionReceipt(e,t){return await Ve(this.getRpcUrl(e),"eth_getTransactionReceipt",[t])}async extractMintedNftId(e,t){let n=await this.getPositionManagerAddress(e);if(!n)return null;let r=n.toLowerCase();for(let o of t.logs??[]){if((o.address??"").toLowerCase()!==r)continue;let s=o.topics??[];if(!(s.length<4||s[0]?.toLowerCase()!==Xs||"0x"+s[1].slice(-40).toLowerCase()!==B))try{return BigInt(s[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=oe(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let n=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*n*18n/10n}async readPoolOnchain(e,t){let[n,r,o,s,i,l]=await Promise.all([this.ethCall(e,t,Ql),this.ethCall(e,t,Jl),this.ethCall(e,t,Zl),this.ethCall(e,t,ec),this.ethCall(e,t,tc),this.ethCall(e,t,nc)]),c=ee(n),d=Bn(c,0),u=nr(c,64),p=Bn(ee(r),0),m=Number(nr(ee(o),0)),f=Number(Bn(ee(s),0)),h=or(ee(i),0),g=or(ee(l),0),[y,b]=await Promise.all([this.readErc20Decimals(e,h),this.readErc20Decimals(e,g)]),w=jr(d,y,b);return{poolAddress:t,chainId:e,fee:f,tickSpacing:m,liquidity:p,sqrtPriceX96:d,currentTick:u,token0:h,token1:g,currentPrice:w}}async readErc20Decimals(e,t){if(t.toLowerCase()===B)return 18;let n=await this.ethCall(e,t,oc);return Number(Bn(ee(n),0))}async getNativePriceUsd(e){let t=oe(e);if(!t)return null;try{let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,r=await x.get(n);if(!r.ok)return null;let s=r.data[t.native.coingeckoId]?.usd;return typeof s=="number"?s:null}catch{return null}}splitNativeAmountForRange(e){let{nativeAmountWei:t,pool:n,tickLower:r,tickUpper:o,token0Decimals:s,token1Decimals:i}=e,l=2**96,c=Number(n.sqrtPriceX96)/l,d=Math.pow(1.0001,r/2),u=Math.pow(1.0001,o/2);if(c<=d)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(c>=u)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let p=1/c-1/u,m=c-d,f=c*c,h=p*f,y=h+m;if(!Number.isFinite(y)||y<=0)throw new Error("splitNativeAmountForRange: invalid total value");let b=h/y,w=1-b,k=1000000000000000n,T=BigInt(Math.floor(b*Number(k))),S=t*T/k,A=t-S;return{ratio0:b,ratio1:w,amountInFor0Wei:S,amountInFor1Wei:A}}async fetchSwapLeg(e){let t=Number.parseInt(e.chainId,16);if(!Number.isFinite(t))throw new Error(`Invalid hex chain id: ${e.chainId}`);let r=await(await this.swapFactory.getService(t)).getQuote({srcChainId:t,srcTokenAddress:e.tokenIn,srcTokenAmount:e.tokenInAmount,dstChainId:t,dstTokenAddress:e.tokenOut,recipientAddress:e.tokenOutRecipient,senderAddress:e.senderAddress??e.tokenOutRecipient,slippage:e.slippage,isCrossChain:!1});if(!r.success||!r.tx)throw new Error(r.errorMessage??"Swap quote failed");let o=r.tx;if(!o.to||typeof o.data!="string")throw new Error("Swap quote returned an unsupported tx shape (non-EVM payload?)");let s=r.raw??{},i=s.tokenOut?.minAmount??s.details?.currencyOut?.minimumAmount??"0";return{to:o.to,data:o.data,value:o.value??"0",minAmountOut:i}}encodeMintCalldata(e){if(e.paymentInfo.length!==2||e.exchanges.length!==2)throw new Error("encodeMintCalldata: paymentInfo and exchanges must each have length 2");let t=ue("mint((address,uint256,address,uint256)[2],(address,bytes,uint256)[2],(uint24,uint256,uint256,int24,int24))"),n=e.paymentInfo.map(f=>lo(f.tokenIn)+fe(f.tokenInAmount)+lo(f.tokenOut)+fe(f.tokenOutAmount)).join(""),o=e.exchanges.map(f=>{let h=ee(f.data||"0x"),g=h.length/2,y=fe(g),b=(64-h.length%64)%64,w=h+"0".repeat(b);return{head:lo(f.to)+fe(96)+fe(f.value),body:y+w}}).map(f=>f.head+f.body),s=o.length*32,i=[];for(let f of o)i.push(fe(s)),s+=f.length/2;let l=i.join("")+o.join(""),c=fe(e.fee,24)+fe(e.amount0Min)+fe(e.amount1Min)+tr(e.tickLower)+tr(e.tickUpper),p=256+32+160,m=n+fe(p)+c+l;return t+m}_keccak(e){return Kr(e)}};var rc={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},sc=/^0x[a-fA-F0-9]{40}$/;function ac(a,e){if(typeof a!="string"||typeof e!="string")return null;let t=rc[a.toLowerCase()];return!t||!sc.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function Ee(a,e){let t=ac(a,e);return t?{uniswapUrl:t}:{}}var Qs=Object.keys(Jt),Ae="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a, Linea=0xe708, Gnosis=0x64, HyperEVM=0x3e7, Mantle=0x1388, Monad=0x8f. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";function me(){return Qs.filter(a=>_e(a)).map(a=>P(a)).join(", ")}function Se(){return{kind:"info",async listSupported(){return Qs.filter(a=>_e(a))},async isSupported(a){if(!a)return!1;let e=$(a)??a.toLowerCase();return Object.prototype.hasOwnProperty.call(Jt,e)}}}function on(a){return{kind:"add-liquidity",listSupported:()=>a.listAddLiquiditySupportedChains(),isSupported:e=>a.isAddLiquiditySupported(e)}}function Pr(a,e,t){let n=r=>typeof r=="string"&&r.trim()!=="";if(n(a))return $(a)??a.trim();if(n(e?.chain))return $(e.chain)??e.chain.trim();if(n(e?.walletAddress))throw new K(typeof e?.query=="string"?e.query:void 0,t);return ve}async function he(a,e,t){let n=await a.listSupported(),r=Pr(e,t,n);return await a.isSupported(r)?{ok:!0,chain:r}:{ok:!1,result:xr(r,n,a.kind)}}function xr(a,e,t="info"){return{_instructions:`${t==="add-liquidity"?"Adding liquidity is NOT available on this network. Tell the user, in their language, that they cannot add liquidity / provide LP on this chain yet (note: viewing pool info may still work on other chains). Then name the chains where adding liquidity IS available":"Liquidity-pool data is NOT available on this network. Tell the user, in their language, that pools are not supported on this chain. Then name the chains where pools ARE available"} using EXACTLY and ONLY the entries in the \`supportedChains\` field below \u2014 copy them verbatim, add nothing. CRITICAL: this list is the complete, authoritative set. Do NOT add, infer, or invent ANY other chain \u2014 NOT EVEN a chain this app supports for wallet/token/DeFi features (for example Gnosis, HyperEVM, Mantle, and Monad are NOT pool chains; never list them unless they literally appear in \`supportedChains\`). Keep it short and friendly. Do NOT mention tools, services, APIs, forms, or any internals.`,unsupportedChain:P(a),supportedChains:e.map(r=>P(r))}}var Uo="{pair}";var et=[{name:"add_button_label",type:"string",description:`Label template for the per-pool "Add liquidity" buttons that render under EVERY pool you show, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each pool automatically. Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:`A short "add liquidity" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a pool's button is clicked. ALWAYS provide it. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain these pools are on is appended automatically.`,required:!1}],Re=' A clickable "Add liquidity" button is shown below your reply for each pool automatically \u2014 do NOT list, number, or repeat those buttons in your text; just deliver your analysis.';function Ne(a,e,t){return Cr(a,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function Cr(a,e,t,n){let r=typeof n=="string"&&n.trim()?` (${n.trim()})`:"",o=[];for(let s of a){if(o.length>=5)break;let i=s.token0?.symbol?.trim(),l=s.token1?.symbol?.trim();if(!i||!l)continue;let c=ic(i,l,s.feeTierPercent);o.push({label:Js(e,c,`Add liquidity to ${Uo}`),prompt:Js(t,c,`add liquidity to ${Uo}`)+r})}return o}function ic(a,e,t){let n=`${a}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${n} ${lc(t)}%`:n}function lc(a){return Number(a.toFixed(4)).toString()}function Js(a,e,t){return(a&&a.includes(Uo)?a:t).split(Uo).join(e).replace(/\s+/g," ").trim()}var ye="You are a seasoned DEX liquidity-pool analyst with deep, credible expertise. Deliver a genuinely insightful, professional read \u2014 the kind a sophisticated LP would pay for \u2014 in natural, flowing prose rather than a rigid template, never sacrificing depth or authority for a conversational tone. ",be="Ground every judgement rigorously in the data, never guesses \u2014 and only use a signal when its data is present: \u2022 capital efficiency = `volumeToTvlRatio` (volume \xF7 TVL) \u2014 higher means each $ of liquidity earns more fees; >1 is very active, <0.1 is sluggish. \u2022 APR quality \u2014 a very high APR sitting on a TINY TVL is usually volatile/unsustainable (treat with caution); a solid APR on deep TVL is the sweet spot. \u2022 TVL trend \u2014 when a 24h TVL % change is present, note whether liquidity is growing or shrinking. \u2022 TVL depth \u2014 deeper pools = lower slippage and a steadier position; thin pools carry higher risk. \u2022 fee tier vs pair type \u2014 stable/correlated pairs suit low tiers (0.01\u20130.05%), volatile pairs suit higher tiers (0.3\u20131%). \u2022 token safety \u2014 when a token exposes isSpam=true or a non-VERIFIED safetyLevel, FLAG it prominently as a risk. ",we="Give a clear one-line worthiness verdict for LPs (e.g. a \u2B50 rating or High / Medium / Low attractiveness), woven naturally into the prose rather than tacked on as a fixed label. ",se="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",Ue=`LINKS \u2014 write every pool pair as PLAIN TEXT only (e.g. "USDC/WETH"). Do NOT create markdown links, do NOT output any URLs, and do NOT print raw pool or token contract addresses anywhere in your answer. The system automatically turns each pool's pair into the correct clickable link after you reply, so you must NEVER add a link, a "Link to pool" line, a "View on Uniswap" line, or a bare URL yourself \u2014 doing so produces wrong/duplicate links. Just name each pair in text. Format numbers human-readably (e.g. $12.5M, +1.23%, 0.05%). Omit null fields. Answer in the user's language. Do NOT mention tool or API names.`;var cc=["tvl","volume1Day","volume1Week","volume30Day","txCount","apr"],uc=["V2","V3","V4"],rn=class extends v{name="get-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens (symbol, name, address, decimals), TVL, transaction count, and rolling volume buckets (1d / 1w / 30d). Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap V3 pools on Base", "which pool has the most liquidity for USDC", "show pools with highest 24h volume on Arbitrum". Source: https://app.uniswap.org/explore (ExploreStats gateway). Supports: `+me();category="blockchain-data";parameters=[{name:"chain",type:"string",description:Ae,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", or "V4". Default is "V3" (the dataset with the richest stats). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume1Week", "volume30Day", "txCount", or "apr" (estimated annualized fee yield). Pools are returned in descending order by this metric.',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"multichain",type:"boolean",description:"When true, request Uniswap's multichain aggregated view instead of a single chain. Defaults to false. Most queries should leave this off.",required:!1,default:!1},{name:"forAddLiquidity",type:"boolean",description:'Set TRUE only when this ranking is the ENTRY POINT of the ADD-LIQUIDITY flow \u2014 the user wants to add / provide liquidity ("add pool", "i want to add liquidity", "th\xEAm thanh kho\u1EA3n") but named NO specific pool, so you show top pools (use sortBy="apr") for them to pick one. In that mode the tool gates on ADD-LIQUIDITY chain support (only chains with a gateway) and, when the connected chain has no gateway, returns the "adding liquidity is not available on this chain" message with the correct supported list \u2014 so the user is told up front, not after picking a pool. OMIT (false) for ordinary informational rankings ("top pools on Base", "biggest pools").',required:!1,default:!1},...et];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new pe(e),this.subgraphFallback=new ne(t),this.pool=new ce({isProduction:e?.isProduction})}async run(e,t){let n=e.forAddLiquidity===!0,r=n?on(this.pool):Se(),o=await r.listSupported(),s=Pr(e.chain,t,o),i=this.parseProtocolVersion(e.protocolVersion),l=this.parseSortKey(e.sortBy),c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=!n&&e.multichain===!0;if(!d&&!await r.isSupported(s))return xr(s,o,r.kind);let u=await this.service.getTopPools({chain:s,protocolVersion:i,sortBy:l,limit:c,multichain:d});if(!u.success)return{error:u.error||"Failed to fetch top pools"};let p=(u.data??[]).map(w=>this.formatPool(w)),m="uniswap";if(p.length===0&&i==="V3"){let w=await this.fetchV3Fallback(s,l,c);w.length>0&&(p=w,m="subgraph")}let f=p.map(w=>this.withExpertSignals(w)),h=await this.pool.isAddLiquiditySupported(s)?Ne(f,e,P(s)):[],g=m==="subgraph",y=g?`"Volume past day" (translate naturally into the user's language; NEVER call it "24h volume", "daily volume", or "24h")`:"24h volume";return{_instructions:(g?`BEGIN your answer with "According to the latest data from Subgraph Uniswap V3," (translate the sentence naturally into the user's language but keep the word "Subgraph" as-is). `:"")+ye+`You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, ${y}, 24h fee revenue, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. `+be+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+we+se+"Mention the chain and the sort metric in the intro line. "+Ue+(h.length>0?Re:""),chain:s,protocolVersion:i,sortBy:l,source:m,count:f.length,pools:f.map(w=>({...w,...Ee(s,w.address)})),...h.length>0?{actionButtons:h}:{}}}withExpertSignals(e){let t=e.tvlUsd,n=e.volume1DayUsd,r=typeof t=="number"&&t>0&&typeof n=="number"?Math.round(n/t*1e3)/1e3:void 0;return{...e,volumeToTvlRatio:r}}async fetchV3Fallback(e,t,n){try{return(await this.subgraphFallback.getTrendingPools({chain:e})).map(i=>this.formatSubgraphPool(i,e)).sort((i,l)=>this.fallbackSortValue(l,t)-this.fallbackSortValue(i,t)).slice(0,n)}catch{return[]}}fallbackSortValue(e,t){switch(t){case"apr":return e.apr??0;case"volume1Day":case"volume1Week":case"volume30Day":return e.volume1DayUsd??0;default:return e.tvlUsd??0}}formatSubgraphPool(e,t){return{apr:e.apr??void 0,address:e.poolAddress,chain:t,protocolVersion:"V3",feeTierBps:e.feeTierBps,feeTierPercent:typeof e.feeTierBps=="number"?e.feeTierBps/1e4:void 0,tvlUsd:e.tvl,fee24hUsd:e.fees24hUsd,volume1DayUsd:e.volume24hUsd,volume1WeekUsd:void 0,volume30DayUsd:void 0,txCount:void 0,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0}}parseProtocolVersion(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(uc.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(cc.includes(t))return t}return"tvl"}formatPool(e){return{apr:e.apr,address:e.id,chain:e.chain,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,tvlUsd:e.totalLiquidity?.value,fee24hUsd:e.fee24hUsd,volume1DayUsd:e.volume1Day?.value,volume1WeekUsd:e.volume1Week?.value,volume30DayUsd:e.volume30Day?.value,txCount:e.txCount,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.price?.value,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.price?.value,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}};var _r={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},dc={100:.01,500:.05,3e3:.3,1e4:1},tt=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=$(e);return!!(t&&_r[t])}listSupportedChains(){return Object.keys(_r).filter(e=>$(e)===e)}numericChainId(e){let t=$(e);return t?_r[t]:void 0}async getPairs(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchV2Items(t)).map(o=>this.mapV2Item(o)).filter(o=>o!==null);if(e.tokens&&e.tokens.length>=2){let o=e.tokens[0].toUpperCase(),s=e.tokens[1].toUpperCase(),i=(l,c)=>l.includes(c)||c.includes(l);r=r.filter(l=>{let[c="",d=""]=l.pair.toUpperCase().split("/");return i(c,o)&&i(d,s)||i(c,s)&&i(d,o)})}return r}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(o=>o.poolId?.toLowerCase()===n).map(o=>this.mapV2Item(o)).filter(o=>o!==null).sort((o,s)=>(s.apr??-1/0)-(o.apr??-1/0))}async fetchV2Items(e){try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(I(n));return n.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=S=>S==null||!Number.isFinite(S)?0:Math.pow(1.0001,S)*Math.pow(10,t-n),o=r(e.minTick),s=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,d=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),u=d?o:s>0?1/s:0,p=d?s:o>0?1/o:0,m=d?c:c>0?1/c:0,f=d?e.token0.symbol:e.token1.symbol,h=d?e.token1.symbol:e.token0.symbol;if(!m||!u&&!p)return null;let g=Math.min(u,p),y=Math.max(u,p);if(m<g||m>y)return null;let b=Number(e.fee),w=dc[b]??b/1e4,k=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,T=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:T,token0Price:i,token1Price:l,priceRange:{minPrice:Z(u),maxPrice:Z(p),currentPrice:Z(m),baseToken:f,quoteToken:h}}}};var pc=365,Zs=/^0x[a-fA-F0-9]{40}$/,mc=6,sn=class extends v{name="get-pool-detail";description="Get detailed stats for a Uniswap V3 pool by token pair (and optional fee tier). Always runs a search first and filters by the provided symbols + fee tier. When the filter resolves to exactly one pool, returns its full detail. When the pair is fully named but NO fee tier is given, returns detail plus a comparative analysis of ALL the pair's fee-tier variants (no need to ask the user to pick). When only one token is given (so the matches are different pairs), returns a `candidates` list \u2014 show it and ask which pair they want, then re-call this tool with the missing info. Detail response includes: pool address, fee tier (bps and %), both tokens (symbol, name, address, decimals, USD price), token0/token1 reserves, total TVL with 24h % change, 24h volume, weekly historical volume series, total tx count, and a derived APR estimate (fees \xF7 TVL \xD7 365). NEVER pass a pool address \u2014 the tool resolves the address itself by searching. Token contract addresses are NOT pool addresses. Source: https://app.uniswap.org. Supports: "+me();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter \u2014 USDC/WETH and WETH/USDC resolve to the same pool. When both token0Symbol and token1Symbol are provided the search is filtered to that exact pair.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 when omitted the tool returns all pools containing token0Symbol so the user can pick.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "USDC/WETH 0.05%" \u2192 feeTier=500). NEVER guess or infer one. When the user has not mentioned a fee tier, OMIT it \u2014 the tool then returns detail plus a comparative analysis of ALL fee-tier variants of the pair (no need to ask the user to pick one).',required:!1},{name:"chain",type:"string",description:Ae,required:!1},...et];service;coinPool;pool;constructor(e,t){super(),this.service=new pe(e),this.coinPool=new tt(t),this.pool=new ce({isProduction:e?.isProduction})}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",s=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0;if(!o)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let l=s?`${o} ${s}`:o,c=await this.service.searchPools({query:l,chain:r,page:1,size:100,protocolVersion:"V3"});if(!c.success)return{error:c.error||"Pool search failed"};let d=c.data??[],p=d.filter(g=>this.matchesFilter(g,o,s,i,"ordered")),m=!1;if(p.length===0&&s){let g=d.filter(y=>this.matchesFilter(y,o,s,i,"reversed"));g.length>0&&(p=g,m=!0)}if(p.length===0)return{error:`No V3 pool matched ${this.describeQuery(o,s,i)} on ${P(r)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!Zs.test(g.id))return{error:"Resolved pool has no valid address"};let[y,b]=await Promise.all([this.service.getV3PoolDetail({address:g.id,chain:r}),this.fetchPriceRanges(r,g.id,g.token0?.symbol,g.token1?.symbol)]);if(!y.success||!y.data)return{error:y.error||"Failed to fetch pool detail"};let w={...this.formatPool(y.data),...Ee(r,g.id)},k=await this.pool.isAddLiquiditySupported(r)?Ne([w],e,P(r)):[];return{priceRanges:b,_instructions:ye+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, token1 reserve + USD price, and total tx count. Optionally include the weekly historical volume as a sparkline-style bullet list. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+be+we+'PRICE RANGES: when `priceRanges` is a non-empty array, add a "Suggested price ranges" section listing each candidate \u2014 fee tier (`fee`), the min\u2013max range (`priceRange.minPrice`\u2013`priceRange.maxPrice` in baseToken/quoteToken units), the current price (`priceRange.currentPrice`), and its `apr`. CRITICAL: that `apr` is the yield for THAT specific range only \u2014 NEVER present it as the overall pool APR. Sort by apr desc; note the top entry is the most concentrated/highest-yield range but narrower = higher risk of going out of range. When `priceRanges` is empty or absent, simply omit this section. '+se+Ue+(k.length>0?Re:""),pairOrderMatched:m?"reversed":"ordered",pool:w,...k.length>0?{actionButtons:k}:{}}}if(s){let g=this.rankCandidates(p).slice(0,mc),b=(await Promise.all(g.map(async w=>{if(!w.id||!Zs.test(w.id))return;let k=await this.service.getV3PoolDetail({address:w.id,chain:r});if(!(!k.success||!k.data))return{...this.formatPool(k.data),...Ee(r,w.id)}}))).filter(w=>w!=null);if(b.length>0){let w=await this.pool.isAddLiquiditySupported(r)?Ne(b,e,P(r)):[];return{_instructions:ye+"The user named a pair WITHOUT a fee tier, so here is EVERY fee-tier variant of that pair \u2014 do NOT ask them to pick a tier. Present them as a ranked list (rank them by capital efficiency / fee yield, not just TVL). For each variant show the fee tier (%), TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), and tx count. Analyze every variant \u2014 give each its own genuine read, never skip one, and never repeat the same sentence structure. "+be+"Focus on which fee tier is the right home for THIS pair: lower tiers (0.01\u20130.05%) win on stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 and the tier that actually captures most of the real volume with deep TVL is usually the one to LP in. Close with an overall section naming the single best fee tier to provide liquidity in right now and why. "+we+se+Ue+(w.length>0?Re:""),chain:r,pairOrderMatched:m?"reversed":"ordered",multiFeeTier:!0,count:b.length,pools:b,...w.length>0?{actionButtons:w}:{}}}}let f=this.rankCandidates(p).slice(0,10).map(g=>{let y=this.formatCandidate(g);return{...y,...Ee(r,y.address)}}),h=await this.pool.isAddLiquiditySupported(r)?Ne(f,e,P(r)):[];return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume) and ask the user which one they want to see. Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. When they answer, re-call this tool with their selection \u2014 pass token0Symbol + token1Symbol + feeTier (use the exact feeTier in bps from the chosen candidate). Format numbers human-readably (e.g. $12.5M, 0.05%). Do NOT mention tool/API names."+(h.length>0?Re:""),chain:r,pairOrderMatched:m?"reversed":"ordered",reason:this.candidateReason(o,s,i),missing:this.missingFields(s,i),candidates:f,...h.length>0?{actionButtons:h}:{}}}matchesFilter(e,t,n,r,o){if(r!=null&&e.feeTier!==r)return!1;let s=(e.token0?.symbol??"").toLowerCase(),i=(e.token1?.symbol??"").toLowerCase(),l=t.toLowerCase();if(n){let c=n.toLowerCase();return o==="reversed"?this.symbolIncludes(s,c)&&this.symbolIncludes(i,l):this.symbolIncludes(s,l)&&this.symbolIncludes(i,c)}return this.symbolIncludes(s,l)||this.symbolIncludes(i,l)}symbolIncludes(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at fee tier ${n} bps`:r}candidateReason(e,t,n){return t?n==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${n} bps. Ask the user which one they meant.`:`Multiple pools contain ${e}. Ask the user for the other token (and fee tier).`}missingFields(e,t){let n=[];return e||n.push("token1Symbol"),t==null&&n.push("feeTier"),n}rankCandidates(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}formatCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let o=await this.coinPool.getByAddress({chain:e,poolAddress:t});return o.length===0&&n&&r&&(o=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),o.sort((s,i)=>(i.apr??-1/0)-(s.apr??-1/0)).slice(0,10)}catch{return[]}}formatPool(e){let t=e.totalLiquidity?.value,n=e.volume24h?.value,r=e.feeTier,o=typeof r=="number"?r/1e4:void 0,s=typeof n=="number"&&typeof o=="number"?n*o/100:void 0,i=typeof s=="number"&&typeof t=="number"&&t>0?s/t*pc*100:void 0,l=typeof n=="number"&&typeof t=="number"&&t>0?Math.round(n/t*1e3)/1e3:void 0;return{address:e.address,protocolVersion:e.protocolVersion,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:s,aprPercent:i,volumeToTvlRatio:l,txCount:e.txCount,historicalVolumeWeek:this.formatHistorical(e.historicalVolume),token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.market?.price?.value??e.token0.price?.value,reserve:e.token0Supply,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.market?.price?.value??e.token1.price?.value,reserve:e.token1Supply,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var hc=["V2","V3","V4","ALL"],an=class extends v{name="search-pools";description='Search Uniswap liquidity pools on a given chain by free-text query \u2014 a SINGLE token symbol or token name. Returns matching pools with: pool address, fee tier (bps + %), protocol version, both tokens (symbol, name, address, decimals, logo), and short-window USD volume buckets (6h / 12h / 24h). Use this tool when the user names ONE token and wants pools related to it: "find WBTC pools on Optimism", "pools containing PEPE on Ethereum", "show USDC pools". Do NOT use for: (a) two-symbol pair lookups like "USDC/WETH 0.05%" \u2014 use get-pool-detail; (b) raw 0x addresses (token or pool) \u2014 use lookup-pool-by-address; (c) chain-wide rankings with no token mentioned \u2014 use get-top-pools. Source: https://app.uniswap.org search. Supports: '+me();category="blockchain-data";parameters=[{name:"query",type:"string",description:'Single token symbol or name to search pools by (e.g. "WBTC", "USDC", "pepe"). Do NOT pass a 0x address (use lookup-pool-by-address) or a two-symbol pair (use get-pool-detail).',required:!0},{name:"chain",type:"string",description:Ae,required:!1},{name:"protocolVersion",type:"string",description:'Filter results by Uniswap protocol version: "V2", "V3", "V4", or "ALL" to include every version. Default is "V3" \u2014 only switch when the user explicitly asks for V2, V4, or all versions.',required:!1,default:"V3"},{name:"page",type:"number",description:"1-based page index. Defaults to 1.",required:!1,default:1},{name:"size",type:"number",description:'Page size (max 50). Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"feeTier",type:"number",description:'Optional fee tier filter in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. When provided, only pools with this exact fee tier are returned. Pass it whenever the user mentions a fee tier in the current message OR earlier in the conversation (e.g. "USDC/WETH 0.05% pool on Base" \u2192 feeTier=500). Omit otherwise.',required:!1},...et];service;pool;constructor(e){super(),this.service=new pe(e),this.pool=new ce({isProduction:e?.isProduction})}async run(e,t){let n=typeof e.query=="string"?e.query.trim():"";if(!n)return{error:"Search query is required"};let r=await he(Se(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,i=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):5,l=this.parseProtocolFilter(e.protocolVersion),c=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,d=await this.service.searchPools({query:n,chain:o,page:s,size:i,protocolVersion:l,feeTier:c});if(!d.success)return{error:d.error||"Failed to search pools"};let u=(d.data??[]).map(m=>this.formatPool(m)),p=await this.pool.isAddLiquiditySupported(o)?Ne(u,e,P(o)):[];return{_instructions:ye+"Present the pools that match the search AND give an expert read on each. Render each pool as its own block: a bold header with the pair (token0/token1 symbols) + fee tier (%), then beneath it the metrics that have data \u2014 TVL (USD), 24h volume (USD), APR (%), tx count, protocol version. Skip any field that is null/undefined \u2014 never show zeros or dashes for missing data. Then add an expert read on each pool \u2014 is it worth providing liquidity in, and why. "+be+we+"When several pools share the searched token, finish with a clear TOP PICK among them. "+se+"Mention the search query and chain in the intro. "+Ue+(p.length>0?Re:""),query:n,chain:o,protocolVersion:l,feeTierBps:c,feeTierPercent:c!=null?c/1e4:void 0,page:s,size:i,count:u.length,pools:u.map(m=>({...m,...Ee(o,m.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(hc.includes(t))return t}return"V3"}formatPool(e){let t={address:e.id,chainId:e.chainId,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0};e.apr!=null&&(t.apr=e.apr),e.tvlUsd!=null&&(t.tvlUsd=e.tvlUsd);let n=e.volume1DayUsd??e.volumeUsd24hr;n!=null&&(t.volume24hUsd=n),e.volumeUsd6hr!=null&&(t.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(t.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(t.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&n!=null&&(t.volumeToTvlRatio=Math.round(n/e.tvlUsd*1e3)/1e3);let r=e.token0,o=e.token1;return r&&(t.token0={address:r.address,symbol:r.symbol,name:r.name,decimals:r.decimals}),o&&(t.token1={address:o.address,symbol:o.symbol,name:o.name,decimals:o.decimals}),t}};var gc=365,ea=/^0x[a-fA-F0-9]{40}$/,ln=class extends v{name="lookup-pool-by-address";description='Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use this tool when the user pastes a single address and asks about "the pool" without saying which kind. For pool detail (when the address is a pool): pair, fee tier, TVL with 24h % change, 24h volume, 24h fees, estimated APR, token reserves with USD prices, and weekly volume series. For token resolution (when the address is a token): the resolved token (symbol, name, decimals) plus a ranked list of pools that include it (pair, fee tier, 24h volume, pool address). Source: https://app.uniswap.org. Supports: '+me();category="blockchain-data";parameters=[{name:"address",type:"string",description:"A 0x-prefixed EVM address. May be a Uniswap pool contract OR a token contract \u2014 the tool figures out which.",required:!0},{name:"chain",type:"string",description:Ae,required:!1},...et];service;pool;constructor(e){super(),this.service=new pe(e),this.pool=new ce({isProduction:e?.isProduction})}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.address=="string"?e.address.trim():"",[s,i]=await Promise.all([this.service.searchPools({query:o,chain:r,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:o,chain:r,page:1,size:5})]),l=s.success?this.findPoolByAddress(s.data??[],o):void 0;if(l)return this.handlePoolHit(l,r,e);let c=i.success?this.findTokenByAddress(i.data??[],o):void 0;return c?this.handleTokenHit(c,r,e):!s.success&&!i.success?{error:s.error||i.error||"Failed to resolve address"}:{error:`Address ${o} did not match any pool or token Uniswap knows on ${P(r)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t,n){if(!e.id)return{error:"Resolved pool has no identifier"};let r=e.protocolVersion??"V3",o=r==="V4"?await this.service.getV4PoolDetail({poolId:e.id,chain:t}):r==="V2"?ea.test(e.id)?await this.service.getV2PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V2 pair has no valid address"}:ea.test(e.id)?await this.service.getV3PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V3 pool has no valid address"};if(!o.success||!o.data)return{error:o.error||"Failed to fetch pool detail"};let s={...this.formatPoolDetail(o.data),...Ee(t,e.id)},i=await this.pool.isAddLiquiditySupported(t)?Ne([s],n,P(t)):[];return{_instructions:`The address is a Uniswap ${r} pool. `+ye+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), protocol version, and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, token1 reserve + USD price, and total tx count. For V4 pools also mention tickSpacing, isDynamicFee, and the hook address if present. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+be+we+se+Ue+(i.length>0?Re:""),resolvedAs:"pool",chain:t,protocolVersion:r,pool:s,...i.length>0?{actionButtons:i}:{}}}async handleTokenHit(e,t,n){let r=e.symbol?.trim();if(!r)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let o=await this.service.searchPools({query:r,chain:t,page:1,size:100,protocolVersion:"V3"});if(!o.success)return{error:o.error||"Failed to fetch pools for resolved token"};let s=(e.address??"").toLowerCase(),l=[...(o.data??[]).filter(u=>{let p=(u.token0?.address??"").toLowerCase(),m=(u.token1?.address??"").toLowerCase();return p===s||m===s})].sort((u,p)=>(p.volumeUsd24hr??0)-(u.volumeUsd24hr??0)).slice(0,10),c=l.map(u=>({...this.formatPoolCandidate(u),...Ee(t,u.id)})),d=await this.pool.isAddLiquiditySupported(t)?Ne(c,n,P(t)):[];return{_instructions:"The address is a token, not a pool. Tell the user which token it is (symbol + name), then render the matching pools as a numbered list: pair (token0/token1 symbols), fee tier (%), protocol version, 24h volume (USD). Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. Ask which pool they want detail on; when they answer, re-call this tool with that pool address to fetch the detail. Format numbers human-readably. Omit null fields. Do NOT mention tool/API names."+(d.length>0?Re:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...d.length>0?{actionButtons:d}:{}}}findPoolByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.id??"").toLowerCase()===n)}findTokenByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.address??"").toLowerCase()===n)}formatToken(e){return{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,isSpam:e.isSpam,safetyLevel:e.safetyLevel}}formatPoolCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}formatPoolDetail(e){let t=e.totalLiquidity?.value,n=e.volume24h?.value,r=e.feeTier,o=typeof r=="number"?r/1e4:void 0,s=typeof n=="number"&&typeof o=="number"?n*o/100:void 0,i=typeof s=="number"&&typeof t=="number"&&t>0?s/t*gc*100:void 0,l=typeof n=="number"&&typeof t=="number"&&t>0?Math.round(n/t*1e3)/1e3:void 0;return{address:e.address??e.poolId,protocolVersion:e.protocolVersion,poolId:e.poolId,tickSpacing:e.tickSpacing,isDynamicFee:e.isDynamicFee,hookAddress:e.hook?.address,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:s,aprPercent:i,volumeToTvlRatio:l,txCount:e.txCount,historicalVolumeWeek:this.formatHistorical(e.historicalVolume),token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.market?.price?.value??e.token0.price?.value,reserve:e.token0Supply,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.market?.price?.value??e.token1.price?.value,reserve:e.token1Supply,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var fc=/^0x[a-fA-F0-9]{40}$/,cn=class extends v{name="open-add-liquidity-form";kind="ui";category="pool-action";description='Open the Add-Liquidity form for a specific Uniswap V3 pool. Use this when the user wants to provide liquidity / add LP / farm / stake / deposit into a pool \u2014 natural-language verbs in any language all map here. Resolves the pool by token symbols (and optional fee tier), reads on-chain state, checks the connected wallet\'s NATIVE balance, then returns a UI payload that the FE renders as the form (with two preset ranges: Stable \xB13 ticks and Wide -50%/+100%). CONSTRAINT: the gateway only accepts the chain\'s NATIVE coin as input (ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche). The native amount is auto-split via deBridge into both pool tokens \u2014 the user never selects a different input. If the user asks to add liquidity using a NON-NATIVE token amount (e.g. "add pool with 5 USDT", "th\xEAm 100 USDC"), pass that symbol via `requestedNonNativeToken` so the tool can return error="unsupported_input_token" \u2014 never silently convert their non-native amount into native or USD. PRECONDITION: a connected wallet (userContext.walletAddress). If absent, the tool returns error="wallet_not_connected" and the agent must ask the user to connect.';parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Required to uniquely identify the pool.',required:!0},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. Omit when unknown \u2014 the tool will resolve the best match automatically.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prefillNativeAmount",type:"number",description:"Optional NATIVE-COIN amount (human-readable) to pre-fill the form's input field. ONLY pass this when the user named an amount in the chain's native coin itself \u2014 ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche. Example: \"add 0.1 ETH to USDC/WETH on Base\". Pass the plain decimal number (e.g. 0.1 for 0.1 ETH). DO NOT convert a non-native amount (USDC, USDT, DAI, WBTC, \u2026) into native here \u2014 pass `requestedNonNativeToken` instead so the tool can reject. Mutually exclusive with prefillUsdAmount \u2014 pass one or neither.",required:!1},{name:"prefillUsdAmount",type:"number",description:'Optional USD amount to pre-fill the form\'s input field. Use this ONLY when the user explicitly speaks in USD/dollars \u2014 e.g. "add $10 to this pool", "10 dollars", "10 \u0111\xF4". The tool converts the USD value to native amount automatically using the current native-token price. DO NOT use this as a workaround for non-native token amounts (e.g. "5 USDT" is NOT $5 \u2014 USDT may de-peg, and even if 1:1 the user asked for a token, not USD). For non-native token amounts pass `requestedNonNativeToken` instead. Mutually exclusive with prefillNativeAmount \u2014 pass one or neither.',required:!1},{name:"requestedNonNativeToken",type:"string",description:`Set this ONLY when the user named an AMOUNT in a non-native token \u2014 e.g. "add pool with 5 USDT", "add 100 USDC to USDC/WETH", "th\xEAm 5 USDT v\xE0o pool". The trigger is "<number> <non-native-symbol>" in the user's message, NOT the mere appearance of the symbol. Pass the symbol the user attached the amount to (e.g. "USDT", "USDC", "DAI"). CRITICAL: If the user also names a NATIVE amount in the same message (e.g. "add USDC/WETH with 0.1 ETH", "th\xEAm pool USDC/WETH 0.3% v\u1EDBi 0.000005 ETH"), the native amount is the input \u2014 leave this EMPTY and use prefillNativeAmount. The pool pair symbols (the two tokens after "pool" / "to") are NEVER the input token by themselves \u2014 they only identify which pool. The tool will return error="unsupported_input_token" so the agent can tell the user that only the chain's native coin is accepted as input. DO NOT silently convert the user's non-native amount into a native amount or USD amount \u2014 the user explicitly named a different asset and must be informed, not auto-corrected. Leave empty when the user did name a native amount, a USD amount, or no amount at all.`,required:!1},{name:"rangeStrategy",type:"string",description:'Optional preset that pre-fills the min/max price inputs (FE keeps them editable). One of: "stable" \u2014 \xB13 tickSpacing around the current price (narrow, higher yield, higher out-of-range risk; pick for stablecoin / low-volatility pairs and when the user says "safe", "tight", "high yield", "t\u1EADp trung"); "wide" \u2014 currentPrice \xD7 [0.5, 2.0] (broad, lower yield, less rebalancing; pick when the user says "wide", "set and forget", "r\u1ED9ng"); "full" \u2014 full V3 tick range (V2-style, lowest yield, never goes out of range; pick when the user says "full range", "v2-style", "kh\xF4ng lo out of range"). Omit when the user did not signal a preference AND did not provide explicit minPrice/maxPrice. Mutually exclusive with minPrice/maxPrice \u2014 if both are passed, explicit prices win.',required:!1},{name:"minPrice",type:"number",description:'Optional explicit lower bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 minPrice=1800. Must be paired with maxPrice. When set, overrides rangeStrategy.',required:!1},{name:"maxPrice",type:"number",description:'Optional explicit upper bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 maxPrice=2200. Must be paired with minPrice. When set, overrides rangeStrategy.',required:!1},{name:"add_button_label",type:"string",description:`Label template for the per-fee-tier "Add liquidity" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. ALWAYS pass this when you call the tool with a pair but NO feeTier (the tool may return several fee-tier variants for the pair, and each gets a one-tap button). Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:'A short "add liquidity" command template IN THE USER\'S CURRENT LANGUAGE, submitted as the next user turn when a fee-tier button is clicked \u2014 it carries the chosen fee tier so the tool resolves that exact pool. ALWAYS pass this alongside `add_button_label` when calling with a pair but no feeTier. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain this pair is on is appended to the prompt automatically.',required:!1}];uniswap;pool;coinPool;minProvideUsd;constructor(e){super(),this.uniswap=new pe(e),this.pool=new ce(e?.pool),this.coinPool=new tt(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),o&&typeof o=="object"&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(s.actionButtons=o.actionButtons),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=await he(on(this.pool),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",s=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,c=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,d=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,u=d&&l!=null&&(d.toLowerCase()===o.toLowerCase()||d.toLowerCase()===s.toLowerCase())?null:d,p=this.parseRangeStrategy(e.rangeStrategy),m=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,f=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!o||!s)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let h=oe(r);if(!h)return{error:"unsupported_chain",chain:r,_instructions:`Chain ${r} is not supported by the add-liquidity flow.`};let g=nn(r);if(u&&g&&u.toLowerCase()!==g.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:u,nativeSymbol:g.symbol,chainName:h.name,_instructions:`The user asked to add liquidity using ${u}, but this app only supports the chain's native coin (${g.symbol} on ${h.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${g.symbol} or in USD. DO NOT silently convert their ${u} amount, do NOT pre-fill the form, and do NOT call this tool again until the user provides a native or USD amount.`};let y=await this.pool.getGatewayAddress(r);if(!y)return{error:"no_gateway_configured",chain:r,_instructions:`No gateway contract is configured for chain ${r} (${h.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let b=t?.walletAddress;if(!b)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before adding liquidity. Do NOT render the form."};let w=await this.uniswap.searchPools({query:`${o} ${s}`,chain:r,page:1,size:100,protocolVersion:"V3",feeTier:i});if(!w.success)return{error:w.error||"pool_search_failed"};let k=w.data??[],T=k.find(L=>this.matchesPairExact(L,o,s,i)),S=T?[]:k.filter(L=>this.matchesPair(L,o,s,i));if(!T&&S.length===0)return{error:"pool_not_found",_instructions:`No V3 pool found for ${o}/${s}${i!=null?` at ${i}bps`:""} on ${h.name}. Verify the inputs with the user.`};if(!T&&S.length>1){let L=S.map(J=>{let mt=J.volume1DayUsd??J.volumeUsd24hr,so=J.tvlUsd,Lr=typeof mt=="number"&&typeof so=="number"&&so>0?mt/so:void 0;return{address:J.id,token0Symbol:J.token0?.symbol,token1Symbol:J.token1?.symbol,feeTier:J.feeTier,feeTierPercent:J.feeTier!=null?J.feeTier/1e4:void 0,volume24hUsd:mt,tvlUsd:so,...Lr!=null?{volumeToTvlRatio:Lr}:void 0,...J.apr?{apr:J.apr}:void 0}}).sort((J,mt)=>(mt.volumeToTvlRatio??mt.apr??-1/0)-(J.volumeToTvlRatio??J.apr??-1/0)).slice(0,5),Ko=Cr(L.map(J=>({token0:{symbol:J.token0Symbol},token1:{symbol:J.token1Symbol},feeTierPercent:J.feeTierPercent})),typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",P(r));return{relatedPools:L,count:L.length,...Ko.length>0?{actionButtons:Ko}:{},_instructions:ye+"The user wants to ADD LIQUIDITY to this pair but named NO fee tier \u2014 `relatedPools` holds the related pools (the pair's fee-tier variants and closely-matching pools). Do NOT just ask them to pick blindly: give a genuine comparative read. Present them as a ranked list (rank by capital efficiency / fee yield, not just TVL); for each show the fee tier (%), TVL (USD), 24h volume (USD), and estimated APR (%) when present. Analyze each with its own real read \u2014 never skip one or repeat the same sentence structure. "+be+"Focus on which fee tier is the best home for THIS pair to LP in: lower tiers (0.01\u20130.05%) suit stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 the tier that captures most of the real volume on deep TVL is usually the one to provide liquidity in. Close by naming the single best fee tier to add liquidity in right now and why, then invite the user to confirm a tier to continue. When they choose, re-run the add-liquidity step with token0Symbol + token1Symbol + the chosen feeTier (in bps). "+we+se+Ue+(Ko.length>0?' A clickable "Add liquidity" button is shown below your reply for each fee-tier candidate automatically \u2014 do NOT list, number, or repeat those buttons.':"")}}let A=T??S[0];if(!A.id||!fc.test(A.id))return{error:"invalid_pool_address"};let _=this.fetchPriceRanges(r,A.id,A.token0?.symbol,A.token1?.symbol),R=await this.pool.readPoolOnchain(r,A.id),[C,M,E]=await Promise.all([this.pool.getNativeBalance(r,b),this.pool.estimateGasReserveWei(r),this.pool.getNativePriceUsd(r)]),Q=C>M?C-M:0n,O=nn(r),Ie=Number(Q)/10**O.decimals,ge=Number(C)/10**O.decimals,G=E!=null?Ie*E:null,[Be,ae]=await Promise.all([this.pool.readErc20Decimals(r,R.token0),this.pool.readErc20Decimals(r,R.token1)]),ot={min:Ce(je,Be,ae),max:Ce(gt,Be,ae)},Ye=null;C===0n?Ye="no_balance":G!=null&&G<this.minProvideUsd&&(Ye="insufficient_balance");let rt=A.token0,st=A.token1,Dn=[25,50,75,100].map(L=>({percent:L,amountWei:(Q*BigInt(L)/100n).toString(),amount:Ie*(L/100)})),On=null,at=null;if(l!=null){at=l;let L=BigInt(Math.floor(at*10**O.decimals));L>0n&&(On=L.toString())}else if(c!=null&&E!=null&&E>0){at=c/E;let L=BigInt(Math.floor(at*10**O.decimals));L>0n&&(On=L.toString())}let ro={address:B,isNative:!0,symbol:O.symbol,name:O.name,decimals:O.decimals,priceUsd:E,balanceWei:C.toString(),balance:ge,gasReserveWei:M.toString(),spendableWei:Q.toString(),spendable:Ie,spendableUsd:G,quickRates:Dn,minProvideUsd:this.minProvideUsd,warning:Ye,warningMessage:Ye==="no_balance"?`You have no ${O.symbol} on ${h.name}. Top up to add liquidity.`:Ye==="insufficient_balance"?`Spendable ${O.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:at,prefillAmountWei:On},it=this.computePrefillRange({explicitMinPrice:m,explicitMaxPrice:f,rangeStrategy:p,currentPrice:R.currentPrice,currentTick:R.currentTick,tickSpacing:R.tickSpacing,token0Decimals:Be,token1Decimals:ae,priceBounds:ot}),Ur={component:"AddLiquidityForm",props:{chain:{hexId:r,name:h.name},pool:{address:R.poolAddress,fee:R.fee,feePercent:R.fee/1e4,tickSpacing:R.tickSpacing,currentTick:R.currentTick,currentPrice:Z(R.currentPrice),sqrtPriceX96:R.sqrtPriceX96.toString(),token0:{address:R.token0,symbol:rt?.symbol,name:rt?.name,logo:rt?.logo},token1:{address:R.token1,symbol:st?.symbol,name:st?.name,logo:st?.logo}},inputToken:ro,priceBounds:ot,prefillRange:it,gatewayAddress:y}},Ir=this.orientRangesToForm(await _,R.currentPrice,rt?.symbol,st?.symbol);return{ui:Ur,suggestedRanges:Ir,summary:this.buildSummary({chainName:h.name,pair:`${rt?.symbol??o}/${st?.symbol??s}`,feePercent:R.fee/1e4,warning:Ye,minProvideUsd:this.minProvideUsd,nativeSymbol:O.symbol}),_instructions:'The add-liquidity action is ready. In the user\'s language, invite them to enter the amount and price range to add liquidity, naming the pool + chain (e.g. "Enter the amount and price range to add liquidity to <pool> on <chain>"). Speak ONLY of the user\'s action (adding liquidity). NEVER say you "opened a form", "opened" anything, or describe any screen/form/window/UI being shown \u2014 phrase it as the next step the user takes, not as something you did. If warning="no_balance" tell them they need to top up. If warning="insufficient_balance" tell them the balance is below the minimum. REFERENCE RANGES: when `suggestedRanges` is a non-empty array, briefly offer 1\u20133 of them (highest `apr` first) as price ranges the user can REFERENCE when filling in their range \u2014 for each give the min\u2013max (`minPrice`\u2013`maxPrice`) and its `apr`. These prices are ALREADY in the SAME unit the form shows (`quoteSymbol` per `baseSymbol`), so quote them as-is \u2014 do NOT invert them. CRITICAL: that `apr` is the yield for THAT specific range ONLY \u2014 NEVER present it as the overall pool APR; narrower = higher out-of-range risk. These are only in-range suggestions to reference \u2014 the user still chooses their own range. When `suggestedRanges` is empty or absent, omit this entirely. '+se+"Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, data sources, or internal tool names. Wait for the user to fill in amount + price range before proceeding."}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let o=await this.coinPool.getByAddress({chain:e,poolAddress:t});return o.length===0&&n&&r&&(o=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),o.sort((s,i)=>(i.apr??-1/0)-(s.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,n,r){let o=s=>Number.isFinite(s)&&s>0;return o(t)?e.map(s=>{let{minPrice:i,maxPrice:l,currentPrice:c}=s.priceRange,d=i,u=l,p=c;if(o(c)){let m=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<m&&(d=o(l)?1/l:0,u=o(i)?1/i:0,p=1/c)}return{fee:s.fee,apr:s.apr,minPrice:Z(d),maxPrice:Z(u),currentPrice:Z(p),baseSymbol:n,quoteSymbol:r}}).filter(s=>o(s.minPrice)&&o(s.maxPrice)):[]}matchesPairExact(e,t,n,r){if(!r||r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),s=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase();return o===i&&s===l||o===l&&s===i}matchesPair(e,t,n,r){if(r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),s=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase(),c=this.symMatch(o,i)&&this.symMatch(s,l),d=this.symMatch(o,l)&&this.symMatch(s,i);return c||d}symMatch(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}parseRangeStrategy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="stable"||t==="wide"||t==="full"?t:null}computePrefillRange(e){let{explicitMinPrice:t,explicitMaxPrice:n,rangeStrategy:r,currentPrice:o,priceBounds:s}=e;if(t!=null&&n!=null&&n>t){let{minPrice:i,maxPrice:l}=ft(t,n,o);return{strategy:"user",minPrice:Math.max(i,s.min),maxPrice:Math.min(l,s.max)}}if(r==="full")return{strategy:"full",minPrice:s.min,maxPrice:s.max};if(r==="stable"||r==="wide"){let l=Sr({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===r);if(l)return{strategy:r,minPrice:l.minPrice,maxPrice:l.maxPrice}}return null}buildSummary(e){let t=[`Ready to add liquidity to the ${e.pair} ${e.feePercent}% pool on ${e.chainName}. Enter an amount and a price range to continue.`];return e.warning==="no_balance"?t.push(`You'll need some ${e.nativeSymbol} on ${e.chainName} first \u2014 top up to continue.`):e.warning==="insufficient_balance"&&t.push(`Your spendable ${e.nativeSymbol} is below the $${e.minProvideUsd} minimum \u2014 top up before continuing.`),t.join(" ")}};var ta=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}],Io=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]}];var yc=/^0x[a-fA-F0-9]{40}$/,un=class extends v{name="preview-add-liquidity";kind="action";category="pool-action";description='Preview the add-liquidity transaction. Call this whenever a concrete pool ADDRESS, a native amount, and BOTH min and max price (in token1 per token0) are known \u2014 whether the user filled the AddLiquidityForm OR stated all of them directly in chat (e.g. "add to USDC/WETH with 0.01 ETH, range 0.0005-0.0007, pool=0x\u2026"). Do NOT require the form to have been opened first. The tool converts prices \u2192 ticks (rounded to tickSpacing), fetches deBridge swap quotes for both legs, encodes the gateway.mint call, and returns an unsigned tx the FE will sign. REQUIRES the exact poolAddress (from open-add-liquidity-form props.pool.address or given by the user) \u2014 if only token symbols / a fee tier are known, resolve the pool via open-add-liquidity-form first.';parameters=[{name:"poolAddress",type:"string",description:"V3 pool contract address (returned by open-add-liquidity-form in props.pool.address).",required:!0},{name:"chain",type:"string",description:`Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea .Must match the pool's chain. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.`,required:!1},{name:"minPrice",type:"number",description:`Lower bound of the position price range, in token1-per-token0 units (decimal-adjusted \u2014 the SAME unit as pool.currentPrice from open-add-liquidity-form). Example: if currentPrice is 1800 (USDC per WETH), minPrice 900 means "the position is in-range while WETH \u2265 900 USDC". Must be >= 0 and < maxPrice. Pass 0 for a "full-range lower" position (the range extends down to price 0, i.e. Uniswap's MIN_TICK). CRITICAL: copy the number the user gave VERBATIM \u2014 every digit and every leading zero. Do NOT add or drop a zero, round, or rescale it. Tiny decimals like 0.000533 are easy to mis-transcribe (0.000533 must stay 0.000533, NEVER 0.0000533). If unsure, prefer the user's exact characters over your own reformatting.`,required:!0},{name:"maxPrice",type:"number",description:`Upper bound of the position price range, in the same units as minPrice. Must be > minPrice. Pass a very large number (or props.priceBounds.max) for a "full range upper" position. CRITICAL: copy the user's number VERBATIM \u2014 every digit and leading zero; never add/drop a zero, round, or rescale.`,required:!0},{name:"nativeAmount",type:"number",description:"Native amount the user wants to spend, as a human-readable decimal number (e.g. 0.1 for 0.1 ETH). The tool converts to wei internally.",required:!0},{name:"slippageBps",type:"number",description:"Slippage tolerance in basis points (100 = 1%). Optional \u2014 defaults to 100.",required:!1}];pool;defaultSlippageBps;mintMinPercent;pantograph;constructor(e){super(),this.pool=new ce(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new le}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=await he(on(this.pool),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=Number(e.minPrice),i=Number(e.maxPrice),l=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,c=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!n||!o||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!yc.test(n))return{error:"invalid_pool_address",_instructions:"poolAddress is not a valid EVM address. Re-open the add-liquidity form to get the correct pool address."};if(s<0||i<=0||s>=i)return{error:"invalid_price_range",_instructions:"minPrice must be >= 0 (0 = full-range lower), maxPrice must be > 0, and minPrice must be strictly less than maxPrice."};if(l<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let d=oe(o);if(!d)return{error:"unsupported_chain",chain:o};let u=await this.pool.getGatewayAddress(o);if(!u)return{error:"no_gateway_configured",chain:o};let p=t?.walletAddress;if(!p)return{error:"wallet_not_connected"};let m=nn(o),f=BigInt(Math.floor(l*10**m.decimals));if(f<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let h=await this.pool.readPoolOnchain(o,n),[g,y]=await Promise.all([this.pool.readErc20Decimals(o,h.token0),this.pool.readErc20Decimals(o,h.token1)]),{minPrice:b,maxPrice:w}=ft(s,i,h.currentPrice),k=b===0?je:ct(b,g,y),T=ct(w,g,y),S=b===0?De(Le(je,h.tickSpacing,"up")):De(Le(k,h.tickSpacing,"down")),A=De(Le(T,h.tickSpacing,"up"));if(S>=A||S<je||A>gt)return{error:"invalid_range_after_alignment",_instructions:"After aligning to tickSpacing the range collapsed. Ask the user for a wider price range.",rawTickLower:k,rawTickUpper:T,tickLower:S,tickUpper:A};let _={tickLower:S,tickUpper:A,minPrice:Z(Ce(S,g,y)),maxPrice:Z(Ce(A,g,y))},R=h.currentTick;if(R<S||R>=A){let L=R<S?"below":"above";return{error:"out_of_range",_instructions:`The chosen price range does NOT include the pool's current price, so this would be an OUT-OF-RANGE position (it would sit entirely in one token and earn no fees until the price moves back into the range). The current price is ${L==="below"?"BELOW":"ABOVE"} the chosen range. Tell the user (in their language) that their range is out of range, show the current price and their chosen min/max, and ask them to pick a range that brackets the current price. Do NOT proceed with the transaction. Do NOT mention tool names.`,currentPrice:Z(h.currentPrice),requestedRange:{minPrice:_.minPrice,maxPrice:_.maxPrice},side:L}}let[C,M,E]=await Promise.all([this.pool.getNativeBalance(o,p),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),Q=f+M;if(C<Q)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:C.toString(),requiredWei:Q.toString(),gasReserveWei:M.toString()};let O=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:h,tickLower:S,tickUpper:A,token0Decimals:g,token1Decimals:y}),Ie=h.token0.toLowerCase()===B,ge=h.token1.toLowerCase()===B,G=[];if(Ie||O.amountInFor0Wei===0n)G.push({tokenIn:B,tokenOut:h.token0,amountIn:O.amountInFor0Wei,tx:{to:B,data:"0x",value:"0"},minAmountOut:Ie?O.amountInFor0Wei:0n});else{let L=await this.pool.fetchSwapLeg({senderAddress:p,chainId:o,tokenIn:B,tokenInAmount:O.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});G.push({tokenIn:B,tokenOut:h.token0,amountIn:O.amountInFor0Wei,tx:{to:L.to,data:L.data,value:L.value},minAmountOut:BigInt(L.minAmountOut||"0")})}if(ge||O.amountInFor1Wei===0n)G.push({tokenIn:B,tokenOut:h.token1,amountIn:O.amountInFor1Wei,tx:{to:B,data:"0x",value:"0"},minAmountOut:ge?O.amountInFor1Wei:0n});else{let L=await this.pool.fetchSwapLeg({senderAddress:p,chainId:o,tokenIn:B,tokenInAmount:O.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});G.push({tokenIn:B,tokenOut:h.token1,amountIn:O.amountInFor1Wei,tx:{to:L.to,data:L.data,value:L.value},minAmountOut:BigInt(L.minAmountOut||"0")})}let Be=L=>L*BigInt(this.mintMinPercent)/100n,ae=Be(G[0].minAmountOut),ot=Be(G[1].minAmountOut),Ye=G.map(L=>({tokenIn:L.tokenIn,tokenInAmount:BigInt(L.amountIn),tokenOut:L.tokenOut,tokenOutAmount:BigInt(L.minAmountOut)})),rt=G.map(L=>({to:L.tx.to,data:L.tx.data,value:BigInt(L.tx.value||"0")})),st=ht({abi:ta,functionName:"mint",args:[Ye,rt,{fee:Number(h.fee),amount0Min:BigInt(ae),amount1Min:BigInt(ot),tickLower:S,tickUpper:A}]}),Dn=l,On={chainId:o,to:u,data:st,value:f.toString(),from:p},at={nativeIn:Dn,nativeSymbol:m.symbol,nativeInUsd:E!=null?Dn*E:null,ratio:{token0Percent:O.ratio0,token1Percent:O.ratio1},expectedToken0:Number(G[0].minAmountOut)/10**g,expectedToken1:Number(G[1].minAmountOut)/10**y,amount0Min:ae.toString(),amount1Min:ot.toString(),slippageBps:c},ro=await this.pantograph.getTokensMetadata([h.token0,h.token1],o),it=ro[h.token0],pt=ro[h.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:o,name:d.name},unsignedTx:On,summary:at,pool:{...h,feePercent:h.fee/1e4,currentPrice:Z(h.currentPrice),token0:{address:h.token0,symbol:it?.auditGoplus?.token_symbol||it.symbol,name:it.name,decimals:it.decimals,logo:it.icon_image},token1:{address:h.token1,symbol:pt?.auditGoplus?.token_symbol||pt.symbol,name:pt.name,decimals:pt.decimals,logo:pt.icon_image}},range:_,gatewayAddress:u}},summary:`Ready to add ${Dn} ${m.symbol} to pool ${h.token0}/${h.token1} ${h.fee/1e4}% on ${d.name}, range [${_.minPrice}, ${_.maxPrice}].`,_instructions:"A confirmation panel has been opened on the FE; the user will sign and broadcast the unsigned tx with their wallet. Briefly tell them (in their language) what is about to happen \u2014 the native amount, the auto-split ratio between the two pool tokens, and the chosen price range. Do NOT mention internal tool/component names."}}};var na=365,bc=1e3,wc=/^0x[a-fA-F0-9]{40}$/;function kc(a,e){return{depositUsd:a,aprPercent:e*100,dailyUsd:a*e/na,weeklyUsd:a*e/52,monthlyUsd:a*e/12,yearlyUsd:a*e}}var dn=class extends v{name="estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap V3 pool. Answers questions like: "If I put $1000 into the USDC/WETH 0.05% pool, how much per day?", "b\u1ECF 500$ v\xE0o pool ETH/USDC 0.3% m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "APR of WBTC/ETH 0.3% on Arbitrum". BEHAVIOR (designed to minimize back-and-forth with the user):
180
180
  \u2022 If only ONE token symbol is given \u2192 auto-pick the highest-volume V3 pool containing that token and compute yield. Do NOT ask the user for the other token.
181
181
  \u2022 If BOTH tokens are given but fee tier is missing AND multiple fee tiers exist \u2192 return candidates (one per fee tier) so the agent can ask the user to pick.
182
182
  \u2022 If depositUsd is missing \u2192 default to $1000 and clearly mark the result as a per-$1000 example. Do NOT ask the user for the deposit amount.
183
183
  \u2022 If chain is missing \u2192 default to userContext.chain or "0x1" (Ethereum).
184
- Source: Uniswap ExploreStats (live 24h data). Supports: `+me();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of one of the pool tokens (e.g. "USDC"). Pair order does not matter.',required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 if omitted, the tool auto-picks the highest-volume pool containing token0Symbol.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "ETH/USDC 0.3%" \u2192 feeTier=3000). NEVER guess or infer one. When the user has not mentioned a fee tier and the pair has multiple fee tiers, OMIT it \u2014 the tool then returns candidates.',required:!1},{name:"depositUsd",type:"number",description:"USD amount to deposit. Optional \u2014 defaults to 1000 and the response is marked as a per-$1000 example.",required:!1},{name:"chain",type:"string",description:Ae,required:!1}];service;constructor(e){super(),this.service=new pe(e)}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",s=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:bc;if(!o)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let u=s?`${o} ${s}`:o,d=await this.service.searchPools({query:u,chain:r,page:1,size:50,protocolVersion:"V3"});if(!d.success)return{error:d.error||"Pool search failed"};let p=d.data??[],m=this.filterPools(p,o,s,i);if(m.length===0)return{error:`No V3 pool found for ${this.describeQuery(o,s,i)} on ${P(r)}. Verify the token symbols with the user.`};let f=this.rankByVolume(m);if(s&&i==null&&new Set(f.map(Q=>Q.feeTier).filter(Q=>typeof Q=="number")).size>1){let Q=this.dedupeByFeeTier(f).slice(0,5);return{_instructions:"The pair has multiple fee tiers. Present them as a short numbered list (fee tier %, 24h volume). Ask which fee tier the user wants, then re-call with the same token symbols + chosen feeTier. If the user already mentioned a deposit amount, pass it along as depositUsd. Do NOT mention tool names. Format numbers human-readably (e.g. $12.5M, 0.05%).",reason:`${o}/${s} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:Q.map(O=>({pair:O.token0?.symbol&&O.token1?.symbol?`${O.token0.symbol}/${O.token1.symbol}`:void 0,feeTierBps:O.feeTier,feeTierPercent:typeof O.feeTier=="number"?O.feeTier/1e4:void 0,volume24hUsd:O.volumeUsd24hr,address:O.id}))}}let h=f[0];if(!h.id||!wc.test(h.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getV3PoolDetail({address:h.id,chain:r});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let y=g.data,b=y.totalLiquidity?.value,w=y.volume24h?.value,k=y.feeTier,T=typeof k=="number"?k/1e4:void 0,S=typeof w=="number"&&typeof T=="number"?w*T/100:void 0,A=typeof S=="number"&&typeof b=="number"&&b>0?S/b*na:void 0,_=typeof w=="number"&&typeof b=="number"&&b>0?w/b:void 0,R={address:y.address,pair:y.token0?.symbol&&y.token1?.symbol?`${y.token0.symbol}/${y.token1.symbol}`:void 0,feeTierBps:k,feeTierPercent:T,tvlUsd:b,volume24hUsd:w,fees24hUsd:S,volumeToTvlRatio:_,aprPercent:typeof A=="number"?A*100:void 0,chain:r,token0:y.token0?{symbol:y.token0.symbol}:void 0,token1:y.token1?{symbol:y.token1.symbol}:void 0},C=s?void 0:`User only provided ${o}; auto-picked the highest-volume V3 pool containing it.`;if(A==null)return{_instructions:"Pool APR could not be computed (TVL or volume data unavailable). Inform the user briefly and show TVL/volume if present. Do NOT mention tool names.",pool:R,autoPickedReason:C,aprUnavailableReason:b?"Volume data unavailable":"TVL is zero or unavailable"};let M=kc(c,A);return{_instructions:ye+"Present the yield estimate naturally in the user's language. "+(l?"Lead with: pool (pair + fee %), chain, APR %. Then show projected earnings for the user's deposit \u2014 daily, weekly, monthly, yearly. ":'IMPORTANT: depositUsd was NOT specified by the user \u2014 the result is a per-$1000 EXAMPLE. Lead with: pool (pair + fee %), chain, APR %. Then say "for every $1000 deposited you would earn approximately:" and list daily / weekly / monthly / yearly. End with a short note that the user can multiply these numbers by (their deposit / 1000) for a custom amount. ')+(C?'Mention briefly that you picked the highest-volume pool for this token (do NOT say "auto-picked"). ':"")+"After the numbers, add a SHORT expert read of whether this pool is actually worth the deposit. "+be+we+se+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:R,estimate:M,depositMode:l?"user-specified":"default-1000-example",autoPickedReason:C,disclaimer:"Fee yield is based on the pool's 24h volume snapshot and assumes full-range liquidity. Actual returns vary with price movement, volume changes, and impermanent loss."}}filterPools(e,t,n,r){let o=t.toLowerCase(),s=n?n.toLowerCase():"";return e.filter(i=>{if(r!=null&&i.feeTier!==r)return!1;let l=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return s?this.sym(l,o)&&this.sym(c,s)||this.sym(l,s)&&this.sym(c,o):this.sym(l,o)||this.sym(c,o)})}sym(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}rankByVolume(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,n=[];for(let r of e)typeof r.feeTier=="number"&&(t.has(r.feeTier)||(t.add(r.feeTier),n.push(r)));return n}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at ${n} bps`:r}};var pn=class extends v{name="get-pool-price-ranges";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a given EVM chain. Each entry shows: pair, fee tier, min/max price range, current price, and the APR earned WITHIN that range (strictly per-range \u2014 NOT the overall pool APR). Use ONLY for questions about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use get-pool-detail or search-pools for that. Source: CoinPool. Supports: '+me()+".";category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:Ae,required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new tt(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=await he(Se(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getPairs({chain:o,tokens:n});if(i.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and offer the pool's overall stats instead (via get-pool-detail).",tokens:n,chain:o,pairs:[],count:0};let l=[...i].sort((c,u)=>(u.apr??-1/0)-(c.apr??-1/0)).slice(0,s);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+se+"Do NOT mention tool or API names.",tokens:n,chain:o,count:l.length,pairs:l}}};var oa="https://coinpool.app/my-liquidity",mn=class extends v{name="manage-liquidity-redirect";description='Use when the user wants to MANAGE an EXISTING liquidity position rather than open a new one \u2014 specifically: collecting / claiming earned fees or rewards ("collect earnings", "claim my fees", "thu ph\xED", "r\xFAt l\xE3i"), or closing / removing / withdrawing a position ("close the pair", "close my position", "remove liquidity", "withdraw liquidity", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "\u0111\xF3ng c\u1EB7p"). This tool does NOT perform the action \u2014 it returns a link to the CoinPool management page where the user does it themselves. Do NOT use this for ADDING liquidity (use the add-liquidity form) or for pool data/analysis questions.';category="pool-action";parameters=[{name:"action",type:"string",description:'What the user wants to do \u2014 one of: "collect" (collect/claim earned fees) or "close" (close/remove the position). Optional \u2014 used only to tailor the wording. Omit if unclear.',required:!1}];async run(e){let t=e.action==="collect"||e.action==="close"?e.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${t==="collect"?"collect their earned fees":t==="close"?"close / remove their position":"manage their existing position (collect earnings or close the pair)"}, they need to visit the CoinPool management page and do it there. Give them the link as plain text: ${oa} \u2014 write the URL exactly, do NOT shorten it or wrap it in markdown. Keep it short and friendly. Do NOT mention tool names.`,url:oa,action:t}}};var Tc=["tvl","volume","apr","fee","liquidity"],hn=class extends v{name="subgraph-search-pools";description='Search Uniswap V3 liquidity pools via The Graph subgraphs by token symbol(s) on one or more chains. Use for: "find ETH/USDC pools on Base", "show OP pools", "stablecoin pools on Arbitrum", "best USDC pool". Returns pools with pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched), and liquidity rank. When exactly two tokens are given, also returns CoinPool concentrated-liquidity price-range candidates (per-range APR) for that pair. Supports TVL/APR/fee filters and sort by tvl, volume, apr, fee, or liquidity. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).';category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols to match. 0 tokens = top pools by chosen sort. 1 token = pools containing it. 2 tokens = pools with that exact pair (both orderings tried). Wrapped variants (WETH\u2194ETH, WBTC\u2194BTC) auto-handled.",required:!1,default:[]},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"sortBy",type:"string",description:'Sort key: "tvl" (default), "volume", "apr", "fee" (low-to-high), or "liquidity".',required:!1,default:"tvl"},{name:"minTVL",type:"number",description:"Minimum TVL in USD.",required:!1},{name:"maxTVL",type:"number",description:"Maximum TVL in USD.",required:!1},{name:"minAPR",type:"number",description:"Minimum APR percentage (e.g. 5 for 5%).",required:!1},{name:"maxAPR",type:"number",description:"Maximum APR percentage.",required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100, 500, 3000, or 10000.",required:!1},{name:"limit",type:"number",description:"Max pools to return after sort/filter. Default 5, max 20.",required:!1,default:5}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),r=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),o=r.filter(f=>!this.service.isSupported(f)),s=r.filter(f=>this.service.isSupported(f)).map(f=>this.service.resolveChain(f));if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let i=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&Tc.includes(e.sortBy)?e.sortBy:"tvl",c={minTVL:typeof e.minTVL=="number"?e.minTVL:void 0,maxTVL:typeof e.maxTVL=="number"?e.maxTVL:void 0,minAPR:typeof e.minAPR=="number"?e.minAPR:void 0,maxAPR:typeof e.maxAPR=="number"?e.maxAPR:void 0,feeTier:typeof e.feeTier=="number"?e.feeTier:void 0},u=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5;if(r.length>0&&s.length===0)return{_instructions:"The user requested chains we do not support via The Graph subgraph. Politely list the unsupported chains and the supported chains. Do not show any pool data.",unsupportedChains:o.map(P),supportedChains:this.service.listSupportedChains().map(P),pools:[],count:0};let p=(await Promise.allSettled(i.map(f=>this.service.searchPools({tokens:n,chain:f,sortBy:l,filters:c})))).flatMap(f=>f.status==="fulfilled"?f.value:[]);l==="apr"?p.sort((f,h)=>(h.apr??0)-(f.apr??0)):l==="tvl"?p.sort((f,h)=>h.tvl-f.tvl):l==="volume"?p.sort((f,h)=>h.volume24hUsd-f.volume24hUsd):l==="fee"&&p.sort((f,h)=>f.feeTierBps-h.feeTierBps),p=p.slice(0,u);let m=[];return n.length===2&&(m=(await Promise.allSettled(i.map(h=>this.service.getCoinPoolPairs({chain:h,tokens:n})))).flatMap((h,g)=>h.status==="fulfilled"?h.value.map(y=>({...y,chain:P(i[g])})):[]),m.sort((h,g)=>(g.apr??-1/0)-(h.apr??-1/0)),m=m.slice(0,u)),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). Then list the pools with: pair (e.g. USDC/WETH), fee tier (%), TVL (USD), volume past day (USD), APR (%). Format USD human-readably ($12.5M, $450K). Mention chain and sort metric briefly. If a pool has no APR (null), skip the APR field rather than showing zero. For EACH pool, render the provided uniswapUrl as a clickable markdown link \u2014 e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)". Never omit this link. Do not invent URLs. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: the APR in coinPoolPairs is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the list, add a brief, natural read on the pools \u2014 conversational, like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4CA} Evaluation"); vary your wording each time and only mention what actually stands out in THIS data. Reason ONLY from the numbers shown \u2014 never invent figures. Touch on, as it fits: which pool looks strongest and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; a high volume-to-TVL ratio signals an active, fee-generating pool); whether the fee tier fits the pair (0.05% for stable/correlated, 0.30% for typical volatile, 1% for exotic/low-liquidity); any pool to be cautious about (thin TVL/volume, or an eye-catching APR that is likely volatile/unsustainable rather than a sure thing); and the key risks in a line (APR is variable, high APR usually means higher risk, impermanent loss for LPs on volatile pairs). Keep it short and human \u2014 a sentence or two or a couple of light bullets. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, no stock disclaimer). If unsupportedChains is non-empty, mention them once at the end.',tokens:n,chains:i.map(P),unsupportedChains:o.map(P),sortBy:l,filters:c,count:p.length,pools:p.map(f=>this.formatPool(f)),coinPoolPairs:m}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:ke(e)}}};function ke(a){return`https://app.uniswap.org/explore/pools/${Kn[a.chain]||a.chain}/${a.poolAddress}`}var Kn={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var gn=class extends v{name="subgraph-trending-pools";description='List Uniswap V3 pools with the highest volume past day on one or more chains via The Graph subgraphs. Use for: "what are trending pools?", "most active pools", "hot pools right now", "pools with biggest volume today". Returns pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched) for each. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).';category="blockchain-data";parameters=[{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"limit",type:"number",description:"Max pools to return. Default 5, max 20.",required:!1,default:5}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),r=n.filter(u=>!this.service.isSupported(u)),o=n.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(n.length>0&&o.length===0)return{_instructions:"User requested unsupported chains. Politely list them and the supported chains; do not show pool data.",unsupportedChains:r,supportedChains:this.service.listSupportedChains(),pools:[],count:0};if(o.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let s=o.length>0?o:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,c=(await Promise.allSettled(s.map(u=>this.service.getTrendingPools({chain:u})))).flatMap(u=>u.status==="fulfilled"?u.value:[]);return c.sort((u,d)=>d.volume24hUsd-u.volume24hUsd),c=c.slice(0,i),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). List pools ranked by volume past day. For each: pair, fee %, volume past day, TVL, APR (skip if null). For EACH pool render the provided uniswapUrl as a clickable markdown link (e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)"). Never omit it. Do not invent URLs.',chains:s,unsupportedChains:r,count:c.length,pools:c.map(u=>({pair:u.pair,poolAddress:u.poolAddress,chain:u.chain,feeTierBps:u.feeTierBps,feeTierPercent:u.feeTierPercent,tvlUsd:u.tvl,volumePastDayUsd:u.volume24hUsd,fees24hUsd:u.fees24hUsd,apr:u.apr,token0:u.token0,token1:u.token1,uniswapUrl:ke(u)}))}}};var fn=class extends v{name="subgraph-pool-by-address";description='Fetch full pool detail AND an evaluation for a specific Uniswap V3 pool by its on-chain address via The Graph subgraphs. Returns Uniswap fundamentals (pair, fee tier, TVL, volume past day + fees, APR, token addresses) enriched with CoinPool concentrated-liquidity price-range candidates (per-range APR + min/max/current price), then a genuine assessment of the pool. Use whenever the user pastes a 0x pool address \u2014 both for plain detail ("tell me about pool 0xabc\u2026", "details of this pool 0x\u2026") and for an opinion ("\u0111\xE1nh gi\xE1 pool 0x\u2026", "rate/evaluate this pool 0x\u2026", "is pool 0x\u2026 good?", "pool n\xE0y c\xF3 t\u1ED1t kh\xF4ng").';category="blockchain-data";parameters=[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"This only supports Uniswap V3 pools. Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address)."};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let o=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(o))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[o],supportedChains:this.service.listSupportedChains()};let s=this.service.resolveChain(o),[i,l]=await Promise.all([this.service.getPoolByAddress({poolAddress:n,chain:s}),this.service.getCoinPoolByAddress({chain:s,poolAddress:n}).catch(()=>[])]);return i?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(l.length>0?" enriched with CoinPool range data,":"")+'" (translate naturally; keep "Subgraph" and "CoinPool" as-is). First show the pool snapshot: pair, fee tier (%), TVL, volume past day, 24h fees, APR (skip if null), and the pool address. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: a range APR is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Then give a genuine evaluation of THIS pool \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading; vary the wording each time and only cover what is actually relevant to this pool and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: liquidity depth & activity (higher TVL + volume past day = deeper liquidity, more fees, less slippage; thin TVL/volume is a red flag); fee-tier fit (0.05% suits stable/correlated pairs, 0.30% typical volatile pairs, 1% exotic/low-liquidity ones \u2014 flag a mismatch); whether the APR looks attractive vs. how sustainable it is (fee-driven and steady vs. thin-TVL spikes that can vanish); if coinPoolPairs is present, which price range makes sense \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Close with a short, natural overall take (e.g. solid / decent-with-caveats / risky) and a brief nudge that it is informational, not financial advice \u2014 phrase it differently each time, do not paste a stock disclaimer. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs. Do NOT mention tool names, UI, or forms.',chain:s,coinPoolPairs:l,pool:{pair:i.pair,poolAddress:i.poolAddress,chain:i.chain,feeTierBps:i.feeTierBps,feeTierPercent:i.feeTierPercent,tvlUsd:i.tvl,volumePastDayUsd:i.volume24hUsd,fees24hUsd:i.fees24hUsd,apr:i.apr,token0:i.token0,token1:i.token1,uniswapUrl:ke(i)}}:{error:`No pool found at ${n} on ${P(s)}.`}}};var yn=class extends v{name="subgraph-pool-by-position-id";description='Return the pool underlying a Uniswap V3 NFT position id. Use when the user wants the pool stats for a numeric id WITHOUT the deposit/withdraw/fee history (e.g. "which pool is position 962961 in?", "show the pool of id 12345"). For full position history use subgraph-position-detail instead.';category="blockchain-data";parameters=[{name:"positionId",type:"string",description:"Numeric Uniswap V3 NFT position id as a string.",required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),o=r.filter(u=>!this.service.isSupported(u)),s=r.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(r.length>0&&s.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:o,supportedChains:this.service.listSupportedChains()};if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let i=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(u=>this.service.getPoolByPositionId({positionId:n,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);return c?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pool of that position: pair, fee %, TVL, volume past day, APR. Mention the position id. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs.',positionId:n,pool:{pair:c.pair,poolAddress:c.poolAddress,chain:c.chain,feeTierBps:c.feeTierBps,feeTierPercent:c.feeTierPercent,tvlUsd:c.tvl,volumePastDayUsd:c.volume24hUsd,fees24hUsd:c.fees24hUsd,apr:c.apr,token0:c.token0,token1:c.token1,uniswapUrl:ke(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:n,chains:i,found:!1}}};var bn=class extends v{name="subgraph-position-detail";description=`Look up a Uniswap V3 liquidity position by its numeric NFT id (e.g. 962961) on one or more chains via The Graph subgraphs. Returns the position (deposited/withdrawn token amounts, collected fees, liquidity) AND its underlying pool (pair, fee tier, TVL, volume past day, APR). Use when the user names a numeric id with phrases like: "position 12345", "pool id 962961", "tell me about position 962961". Does NOT support the user's wallet-wide LP list \u2014 only a specific id.`;category="blockchain-data";parameters=[{name:"positionId",type:"string",description:'Numeric Uniswap V3 NFT position id as a string (e.g. "962961").',required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=r.filter(d=>!this.service.isSupported(d)),s=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.length>0&&s.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:o,supportedChains:this.service.listSupportedChains()};if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let i=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(d=>this.service.getPositionDetail({positionId:n,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);if(!c)return{_instructions:"No position with this id was found on the chosen chains. Suggest the user double-check the id or specify another chain.",positionId:n,chains:i,found:!1};let u=Kn[c.position.chain]||c.position.chain;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pair, chain, fee tier (%), deposited/withdrawn/collected fees for each token, plus pool stats (TVL, volume past day, APR). End the response with TWO clickable markdown links from the data: position.uniswapPositionUrl as "[View position on Uniswap](uniswapPositionUrl)" and pool.uniswapUrl as "[View pool on Uniswap](uniswapUrl)". Never omit them. Do not invent URLs.',positionId:n,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${u}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:ke(c.pool)}}}};var wn=class extends v{name="subgraph-coinpool-pairs";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a chain. Each entry shows: pair, fee tier, min/max price range, current price, and APR within that range (NOT the overall pool APR \u2014 strictly per-range). Use ONLY for queries about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use subgraph-search-pools for that.';category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let o=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(o))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[o],supportedChains:this.service.listSupportedChains()};let s=this.service.resolveChain(o),i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,l=await this.service.getCoinPoolPairs({chain:s,tokens:n});if(l.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and suggest using general pool data instead (via subgraph-search-pools).",tokens:n,chain:s,pairs:[],count:0};let c=[...l].sort((u,d)=>(d.apr??-1/0)-(u.apr??-1/0)).slice(0,i);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:n,chain:s,count:c.length,pairs:c}}};var kn=class extends v{name="subgraph-add-pool";description='Open the ADD-LIQUIDITY / ADD-POOL flow for Uniswap V3 via The Graph subgraphs. Use for ANY "provide / add liquidity", "add LP", "add pool", "create pool", "create pair", "farm/deposit into a pool" intent (natural-language verbs in any language map here: "th\xEAm thanh kho\u1EA3n", "th\xEAm pool", "t\u1EA1o pool"). It RESOLVES the pool the user means \u2014 by 0x pool address, or by one/two token symbols (with optional fee tier) \u2014 like the detail/search tools, then points the user to the add-liquidity website. When two token symbols are given, it also surfaces CoinPool concentrated-liquidity price-range candidates (per-range APR) to help pick a range. Pass `poolAddress` when the user gives a 0x pool address; otherwise pass `tokens` (1 or 2 symbols) and optional `feeTier`. Leave both blank when the user named no pool/token \u2014 the tool returns the chain\'s top pools to choose from. It does NOT build a transaction; it surfaces the add-liquidity link.';category="blockchain-data";parameters=[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars). Pass when the user gives a concrete pool address; otherwise leave blank and pass `tokens`.",required:!1},{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols of the pair to add liquidity to. 1 token = pools containing it; 2 tokens = that exact pair (both orderings tried). Leave EMPTY when the user named no token \u2014 the tool returns top pools to choose from.",required:!1,default:[]},{name:"feeTier",type:"number",description:"Optional fee tier in basis points (100, 500, 3000, or 10000) to disambiguate the pool.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"howTo",type:"boolean",description:'Set TRUE when the user asks HOW to add liquidity / how to create a pool or pair / how it works ("how to add pool", "how to add pair", "how do I add liquidity", "c\xE1ch th\xEAm thanh kho\u1EA3n", "l\xE0m sao \u0111\u1EC3 add pool/pair") rather than naming a specific pool to add to ("pool" and "pair" are equivalent here). Returns the general steps + the add-liquidity website link, without needing a pool, token, or connected chain. Leave false/omit for a concrete add-liquidity request.',required:!1}];service;linkAddLiquidity;constructor(e){super(),this.service=new ne(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let d=this.linkAddLiquidity??null,p=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",m="",f=[];if(this.service.isSupported(p)){m=this.service.resolveChain(p);try{f=(await this.service.searchPools({tokens:[],chain:m,sortBy:"tvl"})).slice(0,5)}catch{f=[]}}return{_instructions:`The user is asking HOW to add liquidity / create a pool \u2014 a how-to question, not a request about a specific pool. Reply in the user's language, in THIS exact order:
184
+ Source: Uniswap ExploreStats (live 24h data). Supports: `+me();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of one of the pool tokens (e.g. "USDC"). Pair order does not matter.',required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 if omitted, the tool auto-picks the highest-volume pool containing token0Symbol.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "ETH/USDC 0.3%" \u2192 feeTier=3000). NEVER guess or infer one. When the user has not mentioned a fee tier and the pair has multiple fee tiers, OMIT it \u2014 the tool then returns candidates.',required:!1},{name:"depositUsd",type:"number",description:"USD amount to deposit. Optional \u2014 defaults to 1000 and the response is marked as a per-$1000 example.",required:!1},{name:"chain",type:"string",description:Ae,required:!1}];service;constructor(e){super(),this.service=new pe(e)}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",s=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:bc;if(!o)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let d=s?`${o} ${s}`:o,u=await this.service.searchPools({query:d,chain:r,page:1,size:50,protocolVersion:"V3"});if(!u.success)return{error:u.error||"Pool search failed"};let p=u.data??[],m=this.filterPools(p,o,s,i);if(m.length===0)return{error:`No V3 pool found for ${this.describeQuery(o,s,i)} on ${P(r)}. Verify the token symbols with the user.`};let f=this.rankByVolume(m);if(s&&i==null&&new Set(f.map(Q=>Q.feeTier).filter(Q=>typeof Q=="number")).size>1){let Q=this.dedupeByFeeTier(f).slice(0,5);return{_instructions:"The pair has multiple fee tiers. Present them as a short numbered list (fee tier %, 24h volume). Ask which fee tier the user wants, then re-call with the same token symbols + chosen feeTier. If the user already mentioned a deposit amount, pass it along as depositUsd. Do NOT mention tool names. Format numbers human-readably (e.g. $12.5M, 0.05%).",reason:`${o}/${s} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:Q.map(O=>({pair:O.token0?.symbol&&O.token1?.symbol?`${O.token0.symbol}/${O.token1.symbol}`:void 0,feeTierBps:O.feeTier,feeTierPercent:typeof O.feeTier=="number"?O.feeTier/1e4:void 0,volume24hUsd:O.volumeUsd24hr,address:O.id}))}}let h=f[0];if(!h.id||!wc.test(h.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getV3PoolDetail({address:h.id,chain:r});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let y=g.data,b=y.totalLiquidity?.value,w=y.volume24h?.value,k=y.feeTier,T=typeof k=="number"?k/1e4:void 0,S=typeof w=="number"&&typeof T=="number"?w*T/100:void 0,A=typeof S=="number"&&typeof b=="number"&&b>0?S/b*na:void 0,_=typeof w=="number"&&typeof b=="number"&&b>0?w/b:void 0,R={address:y.address,pair:y.token0?.symbol&&y.token1?.symbol?`${y.token0.symbol}/${y.token1.symbol}`:void 0,feeTierBps:k,feeTierPercent:T,tvlUsd:b,volume24hUsd:w,fees24hUsd:S,volumeToTvlRatio:_,aprPercent:typeof A=="number"?A*100:void 0,chain:r,token0:y.token0?{symbol:y.token0.symbol}:void 0,token1:y.token1?{symbol:y.token1.symbol}:void 0},C=s?void 0:`User only provided ${o}; auto-picked the highest-volume V3 pool containing it.`;if(A==null)return{_instructions:"Pool APR could not be computed (TVL or volume data unavailable). Inform the user briefly and show TVL/volume if present. Do NOT mention tool names.",pool:R,autoPickedReason:C,aprUnavailableReason:b?"Volume data unavailable":"TVL is zero or unavailable"};let M=kc(c,A);return{_instructions:ye+"Present the yield estimate naturally in the user's language. "+(l?"Lead with: pool (pair + fee %), chain, APR %. Then show projected earnings for the user's deposit \u2014 daily, weekly, monthly, yearly. ":'IMPORTANT: depositUsd was NOT specified by the user \u2014 the result is a per-$1000 EXAMPLE. Lead with: pool (pair + fee %), chain, APR %. Then say "for every $1000 deposited you would earn approximately:" and list daily / weekly / monthly / yearly. End with a short note that the user can multiply these numbers by (their deposit / 1000) for a custom amount. ')+(C?'Mention briefly that you picked the highest-volume pool for this token (do NOT say "auto-picked"). ':"")+"After the numbers, add a SHORT expert read of whether this pool is actually worth the deposit. "+be+we+se+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:R,estimate:M,depositMode:l?"user-specified":"default-1000-example",autoPickedReason:C,disclaimer:"Fee yield is based on the pool's 24h volume snapshot and assumes full-range liquidity. Actual returns vary with price movement, volume changes, and impermanent loss."}}filterPools(e,t,n,r){let o=t.toLowerCase(),s=n?n.toLowerCase():"";return e.filter(i=>{if(r!=null&&i.feeTier!==r)return!1;let l=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return s?this.sym(l,o)&&this.sym(c,s)||this.sym(l,s)&&this.sym(c,o):this.sym(l,o)||this.sym(c,o)})}sym(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}rankByVolume(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,n=[];for(let r of e)typeof r.feeTier=="number"&&(t.has(r.feeTier)||(t.add(r.feeTier),n.push(r)));return n}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at ${n} bps`:r}};var pn=class extends v{name="get-pool-price-ranges";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a given EVM chain. Each entry shows: pair, fee tier, min/max price range, current price, and the APR earned WITHIN that range (strictly per-range \u2014 NOT the overall pool APR). Use ONLY for questions about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use get-pool-detail or search-pools for that. Source: CoinPool. Supports: '+me()+".";category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:Ae,required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new tt(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=await he(Se(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getPairs({chain:o,tokens:n});if(i.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and offer the pool's overall stats instead (via get-pool-detail).",tokens:n,chain:o,pairs:[],count:0};let l=[...i].sort((c,d)=>(d.apr??-1/0)-(c.apr??-1/0)).slice(0,s);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+se+"Do NOT mention tool or API names.",tokens:n,chain:o,count:l.length,pairs:l}}};var oa="https://coinpool.app/my-liquidity",mn=class extends v{name="manage-liquidity-redirect";description='Use when the user wants to MANAGE an EXISTING liquidity position rather than open a new one \u2014 specifically: collecting / claiming earned fees or rewards ("collect earnings", "claim my fees", "thu ph\xED", "r\xFAt l\xE3i"), or closing / removing / withdrawing a position ("close the pair", "close my position", "remove liquidity", "withdraw liquidity", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "\u0111\xF3ng c\u1EB7p"). This tool does NOT perform the action \u2014 it returns a link to the CoinPool management page where the user does it themselves. Do NOT use this for ADDING liquidity (use the add-liquidity form) or for pool data/analysis questions.';category="pool-action";parameters=[{name:"action",type:"string",description:'What the user wants to do \u2014 one of: "collect" (collect/claim earned fees) or "close" (close/remove the position). Optional \u2014 used only to tailor the wording. Omit if unclear.',required:!1}];async run(e){let t=e.action==="collect"||e.action==="close"?e.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${t==="collect"?"collect their earned fees":t==="close"?"close / remove their position":"manage their existing position (collect earnings or close the pair)"}, they need to visit the CoinPool management page and do it there. Give them the link as plain text: ${oa} \u2014 write the URL exactly, do NOT shorten it or wrap it in markdown. Keep it short and friendly. Do NOT mention tool names.`,url:oa,action:t}}};var Tc=["tvl","volume","apr","fee","liquidity"],hn=class extends v{name="subgraph-search-pools";description='Search Uniswap V3 liquidity pools via The Graph subgraphs by token symbol(s) on one or more chains. Use for: "find ETH/USDC pools on Base", "show OP pools", "stablecoin pools on Arbitrum", "best USDC pool". Returns pools with pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched), and liquidity rank. When exactly two tokens are given, also returns CoinPool concentrated-liquidity price-range candidates (per-range APR) for that pair. Supports TVL/APR/fee filters and sort by tvl, volume, apr, fee, or liquidity. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).';category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols to match. 0 tokens = top pools by chosen sort. 1 token = pools containing it. 2 tokens = pools with that exact pair (both orderings tried). Wrapped variants (WETH\u2194ETH, WBTC\u2194BTC) auto-handled.",required:!1,default:[]},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"sortBy",type:"string",description:'Sort key: "tvl" (default), "volume", "apr", "fee" (low-to-high), or "liquidity".',required:!1,default:"tvl"},{name:"minTVL",type:"number",description:"Minimum TVL in USD.",required:!1},{name:"maxTVL",type:"number",description:"Maximum TVL in USD.",required:!1},{name:"minAPR",type:"number",description:"Minimum APR percentage (e.g. 5 for 5%).",required:!1},{name:"maxAPR",type:"number",description:"Maximum APR percentage.",required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100, 500, 3000, or 10000.",required:!1},{name:"limit",type:"number",description:"Max pools to return after sort/filter. Default 5, max 20.",required:!1,default:5}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),r=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),o=r.filter(f=>!this.service.isSupported(f)),s=r.filter(f=>this.service.isSupported(f)).map(f=>this.service.resolveChain(f));if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let i=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&Tc.includes(e.sortBy)?e.sortBy:"tvl",c={minTVL:typeof e.minTVL=="number"?e.minTVL:void 0,maxTVL:typeof e.maxTVL=="number"?e.maxTVL:void 0,minAPR:typeof e.minAPR=="number"?e.minAPR:void 0,maxAPR:typeof e.maxAPR=="number"?e.maxAPR:void 0,feeTier:typeof e.feeTier=="number"?e.feeTier:void 0},d=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5;if(r.length>0&&s.length===0)return{_instructions:"The user requested chains we do not support via The Graph subgraph. Politely list the unsupported chains and the supported chains. Do not show any pool data.",unsupportedChains:o.map(P),supportedChains:this.service.listSupportedChains().map(P),pools:[],count:0};let p=(await Promise.allSettled(i.map(f=>this.service.searchPools({tokens:n,chain:f,sortBy:l,filters:c})))).flatMap(f=>f.status==="fulfilled"?f.value:[]);l==="apr"?p.sort((f,h)=>(h.apr??0)-(f.apr??0)):l==="tvl"?p.sort((f,h)=>h.tvl-f.tvl):l==="volume"?p.sort((f,h)=>h.volume24hUsd-f.volume24hUsd):l==="fee"&&p.sort((f,h)=>f.feeTierBps-h.feeTierBps),p=p.slice(0,d);let m=[];return n.length===2&&(m=(await Promise.allSettled(i.map(h=>this.service.getCoinPoolPairs({chain:h,tokens:n})))).flatMap((h,g)=>h.status==="fulfilled"?h.value.map(y=>({...y,chain:P(i[g])})):[]),m.sort((h,g)=>(g.apr??-1/0)-(h.apr??-1/0)),m=m.slice(0,d)),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). Then list the pools with: pair (e.g. USDC/WETH), fee tier (%), TVL (USD), volume past day (USD), APR (%). Format USD human-readably ($12.5M, $450K). Mention chain and sort metric briefly. If a pool has no APR (null), skip the APR field rather than showing zero. For EACH pool, render the provided uniswapUrl as a clickable markdown link \u2014 e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)". Never omit this link. Do not invent URLs. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: the APR in coinPoolPairs is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the list, add a brief, natural read on the pools \u2014 conversational, like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4CA} Evaluation"); vary your wording each time and only mention what actually stands out in THIS data. Reason ONLY from the numbers shown \u2014 never invent figures. Touch on, as it fits: which pool looks strongest and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; a high volume-to-TVL ratio signals an active, fee-generating pool); whether the fee tier fits the pair (0.05% for stable/correlated, 0.30% for typical volatile, 1% for exotic/low-liquidity); any pool to be cautious about (thin TVL/volume, or an eye-catching APR that is likely volatile/unsustainable rather than a sure thing); and the key risks in a line (APR is variable, high APR usually means higher risk, impermanent loss for LPs on volatile pairs). Keep it short and human \u2014 a sentence or two or a couple of light bullets. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, no stock disclaimer). If unsupportedChains is non-empty, mention them once at the end.',tokens:n,chains:i.map(P),unsupportedChains:o.map(P),sortBy:l,filters:c,count:p.length,pools:p.map(f=>this.formatPool(f)),coinPoolPairs:m}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:ke(e)}}};function ke(a){return`https://app.uniswap.org/explore/pools/${Kn[a.chain]||a.chain}/${a.poolAddress}`}var Kn={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var gn=class extends v{name="subgraph-trending-pools";description='List Uniswap V3 pools with the highest volume past day on one or more chains via The Graph subgraphs. Use for: "what are trending pools?", "most active pools", "hot pools right now", "pools with biggest volume today". Returns pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched) for each. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).';category="blockchain-data";parameters=[{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"limit",type:"number",description:"Max pools to return. Default 5, max 20.",required:!1,default:5}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),r=n.filter(d=>!this.service.isSupported(d)),o=n.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(n.length>0&&o.length===0)return{_instructions:"User requested unsupported chains. Politely list them and the supported chains; do not show pool data.",unsupportedChains:r,supportedChains:this.service.listSupportedChains(),pools:[],count:0};if(o.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let s=o.length>0?o:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,c=(await Promise.allSettled(s.map(d=>this.service.getTrendingPools({chain:d})))).flatMap(d=>d.status==="fulfilled"?d.value:[]);return c.sort((d,u)=>u.volume24hUsd-d.volume24hUsd),c=c.slice(0,i),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). List pools ranked by volume past day. For each: pair, fee %, volume past day, TVL, APR (skip if null). For EACH pool render the provided uniswapUrl as a clickable markdown link (e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)"). Never omit it. Do not invent URLs.',chains:s,unsupportedChains:r,count:c.length,pools:c.map(d=>({pair:d.pair,poolAddress:d.poolAddress,chain:d.chain,feeTierBps:d.feeTierBps,feeTierPercent:d.feeTierPercent,tvlUsd:d.tvl,volumePastDayUsd:d.volume24hUsd,fees24hUsd:d.fees24hUsd,apr:d.apr,token0:d.token0,token1:d.token1,uniswapUrl:ke(d)}))}}};var fn=class extends v{name="subgraph-pool-by-address";description='Fetch full pool detail AND an evaluation for a specific Uniswap V3 pool by its on-chain address via The Graph subgraphs. Returns Uniswap fundamentals (pair, fee tier, TVL, volume past day + fees, APR, token addresses) enriched with CoinPool concentrated-liquidity price-range candidates (per-range APR + min/max/current price), then a genuine assessment of the pool. Use whenever the user pastes a 0x pool address \u2014 both for plain detail ("tell me about pool 0xabc\u2026", "details of this pool 0x\u2026") and for an opinion ("\u0111\xE1nh gi\xE1 pool 0x\u2026", "rate/evaluate this pool 0x\u2026", "is pool 0x\u2026 good?", "pool n\xE0y c\xF3 t\u1ED1t kh\xF4ng").';category="blockchain-data";parameters=[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"This only supports Uniswap V3 pools. Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address)."};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let o=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(o))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[o],supportedChains:this.service.listSupportedChains()};let s=this.service.resolveChain(o),[i,l]=await Promise.all([this.service.getPoolByAddress({poolAddress:n,chain:s}),this.service.getCoinPoolByAddress({chain:s,poolAddress:n}).catch(()=>[])]);return i?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(l.length>0?" enriched with CoinPool range data,":"")+'" (translate naturally; keep "Subgraph" and "CoinPool" as-is). First show the pool snapshot: pair, fee tier (%), TVL, volume past day, 24h fees, APR (skip if null), and the pool address. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: a range APR is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Then give a genuine evaluation of THIS pool \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading; vary the wording each time and only cover what is actually relevant to this pool and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: liquidity depth & activity (higher TVL + volume past day = deeper liquidity, more fees, less slippage; thin TVL/volume is a red flag); fee-tier fit (0.05% suits stable/correlated pairs, 0.30% typical volatile pairs, 1% exotic/low-liquidity ones \u2014 flag a mismatch); whether the APR looks attractive vs. how sustainable it is (fee-driven and steady vs. thin-TVL spikes that can vanish); if coinPoolPairs is present, which price range makes sense \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Close with a short, natural overall take (e.g. solid / decent-with-caveats / risky) and a brief nudge that it is informational, not financial advice \u2014 phrase it differently each time, do not paste a stock disclaimer. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs. Do NOT mention tool names, UI, or forms.',chain:s,coinPoolPairs:l,pool:{pair:i.pair,poolAddress:i.poolAddress,chain:i.chain,feeTierBps:i.feeTierBps,feeTierPercent:i.feeTierPercent,tvlUsd:i.tvl,volumePastDayUsd:i.volume24hUsd,fees24hUsd:i.fees24hUsd,apr:i.apr,token0:i.token0,token1:i.token1,uniswapUrl:ke(i)}}:{error:`No pool found at ${n} on ${P(s)}.`}}};var yn=class extends v{name="subgraph-pool-by-position-id";description='Return the pool underlying a Uniswap V3 NFT position id. Use when the user wants the pool stats for a numeric id WITHOUT the deposit/withdraw/fee history (e.g. "which pool is position 962961 in?", "show the pool of id 12345"). For full position history use subgraph-position-detail instead.';category="blockchain-data";parameters=[{name:"positionId",type:"string",description:"Numeric Uniswap V3 NFT position id as a string.",required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=r.filter(d=>!this.service.isSupported(d)),s=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.length>0&&s.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:o,supportedChains:this.service.listSupportedChains()};if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let i=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(d=>this.service.getPoolByPositionId({positionId:n,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);return c?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pool of that position: pair, fee %, TVL, volume past day, APR. Mention the position id. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs.',positionId:n,pool:{pair:c.pair,poolAddress:c.poolAddress,chain:c.chain,feeTierBps:c.feeTierBps,feeTierPercent:c.feeTierPercent,tvlUsd:c.tvl,volumePastDayUsd:c.volume24hUsd,fees24hUsd:c.fees24hUsd,apr:c.apr,token0:c.token0,token1:c.token1,uniswapUrl:ke(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:n,chains:i,found:!1}}};var bn=class extends v{name="subgraph-position-detail";description=`Look up a Uniswap V3 liquidity position by its numeric NFT id (e.g. 962961) on one or more chains via The Graph subgraphs. Returns the position (deposited/withdrawn token amounts, collected fees, liquidity) AND its underlying pool (pair, fee tier, TVL, volume past day, APR). Use when the user names a numeric id with phrases like: "position 12345", "pool id 962961", "tell me about position 962961". Does NOT support the user's wallet-wide LP list \u2014 only a specific id.`;category="blockchain-data";parameters=[{name:"positionId",type:"string",description:'Numeric Uniswap V3 NFT position id as a string (e.g. "962961").',required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),o=r.filter(u=>!this.service.isSupported(u)),s=r.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(r.length>0&&s.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:o,supportedChains:this.service.listSupportedChains()};if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let i=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(u=>this.service.getPositionDetail({positionId:n,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);if(!c)return{_instructions:"No position with this id was found on the chosen chains. Suggest the user double-check the id or specify another chain.",positionId:n,chains:i,found:!1};let d=Kn[c.position.chain]||c.position.chain;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pair, chain, fee tier (%), deposited/withdrawn/collected fees for each token, plus pool stats (TVL, volume past day, APR). End the response with TWO clickable markdown links from the data: position.uniswapPositionUrl as "[View position on Uniswap](uniswapPositionUrl)" and pool.uniswapUrl as "[View pool on Uniswap](uniswapUrl)". Never omit them. Do not invent URLs.',positionId:n,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${d}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:ke(c.pool)}}}};var wn=class extends v{name="subgraph-coinpool-pairs";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a chain. Each entry shows: pair, fee tier, min/max price range, current price, and APR within that range (NOT the overall pool APR \u2014 strictly per-range). Use ONLY for queries about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use subgraph-search-pools for that.';category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new ne(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let o=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(o))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[o],supportedChains:this.service.listSupportedChains()};let s=this.service.resolveChain(o),i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,l=await this.service.getCoinPoolPairs({chain:s,tokens:n});if(l.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and suggest using general pool data instead (via subgraph-search-pools).",tokens:n,chain:s,pairs:[],count:0};let c=[...l].sort((d,u)=>(u.apr??-1/0)-(d.apr??-1/0)).slice(0,i);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:n,chain:s,count:c.length,pairs:c}}};var kn=class extends v{name="subgraph-add-pool";description='Open the ADD-LIQUIDITY / ADD-POOL flow for Uniswap V3 via The Graph subgraphs. Use for ANY "provide / add liquidity", "add LP", "add pool", "create pool", "create pair", "farm/deposit into a pool" intent (natural-language verbs in any language map here: "th\xEAm thanh kho\u1EA3n", "th\xEAm pool", "t\u1EA1o pool"). It RESOLVES the pool the user means \u2014 by 0x pool address, or by one/two token symbols (with optional fee tier) \u2014 like the detail/search tools, then points the user to the add-liquidity website. When two token symbols are given, it also surfaces CoinPool concentrated-liquidity price-range candidates (per-range APR) to help pick a range. Pass `poolAddress` when the user gives a 0x pool address; otherwise pass `tokens` (1 or 2 symbols) and optional `feeTier`. Leave both blank when the user named no pool/token \u2014 the tool returns the chain\'s top pools to choose from. It does NOT build a transaction; it surfaces the add-liquidity link.';category="blockchain-data";parameters=[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars). Pass when the user gives a concrete pool address; otherwise leave blank and pass `tokens`.",required:!1},{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols of the pair to add liquidity to. 1 token = pools containing it; 2 tokens = that exact pair (both orderings tried). Leave EMPTY when the user named no token \u2014 the tool returns top pools to choose from.",required:!1,default:[]},{name:"feeTier",type:"number",description:"Optional fee tier in basis points (100, 500, 3000, or 10000) to disambiguate the pool.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"howTo",type:"boolean",description:'Set TRUE when the user asks HOW to add liquidity / how to create a pool or pair / how it works ("how to add pool", "how to add pair", "how do I add liquidity", "c\xE1ch th\xEAm thanh kho\u1EA3n", "l\xE0m sao \u0111\u1EC3 add pool/pair") rather than naming a specific pool to add to ("pool" and "pair" are equivalent here). Returns the general steps + the add-liquidity website link, without needing a pool, token, or connected chain. Leave false/omit for a concrete add-liquidity request.',required:!1}];service;linkAddLiquidity;constructor(e){super(),this.service=new ne(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let u=this.linkAddLiquidity??null,p=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",m="",f=[];if(this.service.isSupported(p)){m=this.service.resolveChain(p);try{f=(await this.service.searchPools({tokens:[],chain:m,sortBy:"tvl"})).slice(0,5)}catch{f=[]}}return{_instructions:`The user is asking HOW to add liquidity / create a pool \u2014 a how-to question, not a request about a specific pool. Reply in the user's language, in THIS exact order:
185
185
  1) A clear, easy-to-follow step-by-step guide (numbered steps) on how adding liquidity works. Generate the steps yourself from how Uniswap V3 add-liquidity actually works \u2014 keep each step short; do not pad with filler.
186
- `+(f.length>0?'2) A few popular pools (from the provided list) as examples to add liquidity to \u2014 show fee tier %, TVL, APR (skip APR if null). For EACH pool, make it a clickable Uniswap link using its `uniswapUrl`: wrap the pair as a markdown link, e.g. "[USDC/WETH](uniswapUrl)", or append "[View on Uniswap](uniswapUrl)". Use the uniswapUrl verbatim; never invent one. Make clear these are just examples for reference, not recommendations.\n':"")+(f.length>0?"3) ":"2) ")+this.linkInstruction(d)+`
187
- Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:m||void 0,addLiquidityLink:d,count:f.length,pools:f.map(h=>this.formatPool(h))}}let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase()),o=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,s=typeof e.chain=="string"&&e.chain.trim();if(!s&&!t?.chain&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let i=s?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(i))return{_instructions:"The requested chain is not supported by the Subgraph pool service. Tell the user, in their language, that add-liquidity is not available on that network and list the supported chains briefly. Do NOT mention tool names.",unsupportedChains:[P(i)],supportedChains:this.service.listSupportedChains().map(P)};let l=this.service.resolveChain(i);if(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let d=await this.service.getPoolByAddress({poolAddress:n,chain:l});return d?this.poolsResult([d],l,!0):{error:`No pool found at ${n} on ${P(l)}.`}}if(r.length>0){let d=await this.service.searchPools({tokens:r,chain:l,sortBy:"tvl",filters:{feeTier:o}});if(d.length===0)return{error:`No Uniswap V3 pool found for ${r.join("/")}${o!=null?` at ${o}bps`:""} on ${P(l)}. Ask the user to check the token symbols, or try a different pair.`};let p=r.length===2?await this.fetchCoinPoolPairs(l,r):[];return this.poolsResult(d.slice(0,8),l,!0,p)}let c=await this.service.searchPools({tokens:[],chain:l,sortBy:"tvl"}),u=this.linkAddLiquidity??null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity but has not named a pool yet. Briefly list these top pools (pair, fee tier %, TVL, APR \u2014 skip APR if null) as suggestions, render each `uniswapUrl` as a clickable markdown link, then ask the user which token pair (or pool) they want to add liquidity to. '+this.linkInstruction(u)+"Do NOT mention tool names, UI, or forms.",chain:l,needsSelection:!0,addLiquidityLink:u,count:c.length,pools:c.slice(0,6).map(d=>this.formatPool(d))}}async fetchCoinPoolPairs(e,t){try{return[...await this.service.getCoinPoolPairs({chain:e,tokens:t})].sort((r,o)=>(o.apr??-1/0)-(r.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(e){return e?`ALWAYS finish by inviting the user to add liquidity on the website, as ONE short sentence that shows the FULL link in plain view \u2014 display the entire URL verbatim (${e}) as the visible link text, do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${e}](${e}). For example: "You can add liquidity here: [${e}](${e})". Use the URL verbatim; never invent one, and never use a pool's uniswapUrl here. `:"No add-liquidity website is configured, so do not show or invent any link. "}poolsResult(e,t,n,r=[]){let o=n?this.linkAddLiquidity??null:null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity. Show the resolved pool(s): pair (e.g. USDC/WETH), fee tier (%), TVL, volume past day, APR (skip if null), and the pool address. For EACH pool, render the provided `uniswapUrl` as a clickable markdown link. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)", to help the user choose a range when adding liquidity. CRITICAL: that APR is for the SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the data, give a genuine, conversational recommendation \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4A1} Recommendation"); vary your wording naturally each time and only cover what is actually relevant to THIS pair and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: which pool/fee tier looks best and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; fee-tier fit: 0.05% for stable/correlated pairs, 0.30% for typical volatile pairs, 1% for exotic/low-liquidity ones); which price range makes sense (from coinPoolPairs if present) \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; anything worth avoiding (thin TVL/volume, ranges far from current price, chasing the top APR blindly); and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Keep it short and human \u2014 a sentence or two or a couple of light bullets, tailored to whether the pair is stable or volatile. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, do not paste a stock disclaimer). '+(o?`Then, at the VERY END, write ONE short, friendly sentence in the user's language inviting them to add liquidity, showing the FULL add-liquidity link in plain view: display the entire URL verbatim as the visible link text \u2014 do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${o}](${o}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${o}](${o})." Use the addLiquidityLink verbatim; never invent a URL, and never use a pool's uniswapUrl here.`:"Do NOT invent or show any add-liquidity link (none is configured). Just present the pool(s).")+" Do NOT mention tool names, UI, forms, or that a transaction is built elsewhere.",chain:t,addLiquidityLink:o,count:e.length,pools:e.map(i=>this.formatPool(i)),coinPoolPairs:r}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:ke(e)}}};function Fe(a){if(typeof a=="number")return Number.isFinite(a)&&a>0?{kind:"token",value:a,raw:String(a)}:null;if(typeof a!="string")return null;let e=a.trim();if(!e)return null;if(/^(?:max(?:imum)?|all|everything|tất\s*cả|toàn\s*bộ)$/i.test(e))return{kind:"percent",percent:100,raw:e};let t=e.match(/^%?\s*([0-9]*\.?[0-9]+)\s*%$|^%\s*([0-9]*\.?[0-9]+)$/);if(t){let o=parseFloat(t[1]??t[2]);return Number.isFinite(o)&&o>0?{kind:"percent",percent:o,raw:e}:null}let n=e.match(/^\$\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*\$$|^(?:usd)\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*usd$/i);if(n){let o=parseFloat(n[1]??n[2]??n[3]??n[4]);return Number.isFinite(o)&&o>0?{kind:"usd",usd:o,raw:e}:null}let r=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(r){let o=parseFloat(r[1]);return Number.isFinite(o)&&o>0?{kind:"token",value:o,raw:e}:null}return null}function ra(a,e){switch(a.kind){case"token":return{ok:!0,amount:a.value};case"percent":return e.balance===void 0||!Number.isFinite(e.balance)||e.balance<=0?{ok:!1,reason:"no_balance"}:{ok:!0,amount:e.balance*a.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:a.usd/e.usdPrice}}}var vc={send:30000n,swap:1000000n},Ac={"0x1":["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"],"0xa":["https://optimism-rpc.publicnode.com","https://optimism.drpc.org"],"0x38":["https://bsc-rpc.publicnode.com","https://bsc.drpc.org"],"0x89":["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"],"0x2105":["https://base-rpc.publicnode.com","https://base.drpc.org"],"0xa4b1":["https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"],"0xa86a":["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"],"0xe708":["https://linea-rpc.publicnode.com","https://linea.drpc.org"],"0x64":["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"],"0x3e7":["https://rpc.hyperliquid.xyz/evm"],"0x1388":["https://mantle-rpc.publicnode.com","https://rpc.mantle.xyz"],"0x8f":["https://rpc.monad.xyz"]};async function Sc(a){let e=a.toLowerCase(),n=[$e(a),...Ac[e]??[]].filter(r=>!!r);for(let r of n)try{let o=await Ve(r,"eth_gasPrice",[]),s=BigInt(o);if(s>0n)return s}catch{}return 0n}async function Tn(a,e){let t=await Sc(a);return t<=0n?0n:vc[e]*t}function vn(a,e,t){if(e<=0n)return a;let n=oe(t)?.native.decimals;if(n===void 0)return a;let r=Number(e)/10**n;return!Number.isFinite(r)||r<=0?a:Math.max(0,a-r)}var Pe=class extends v{kind="ui";category="wallet-action";buildUI(e){let t={action:this.actionType,chainId:e.chainId,chainName:P(e.chainId),walletAddress:e.walletAddress,parameters:e.parameters};return{component:this.component,props:t}}userInputFields=[];moralis;constructor(e){super(),e!==void 0&&(this.moralis=new D(e))}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=q(e.trim()),s=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(s);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(s)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}parseDecimals(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isInteger(t)&&t>=0)return t}}async resolveTokenRef(e){let{contractArg:t,symbolArg:n,decimalsArg:r,chain:o,walletAddress:s}=e,i=this.parseDecimals(r),l=typeof n=="string"&&n.trim()?n.trim():void 0,c=this.normaliseAddress(t),u=typeof t=="string"&&t.trim()?t.trim():void 0,d=c??l??u;if(!d)return{token:void 0};let p=await this.resolveContractAddress(d,o,s);return p?{token:{address:p.address,symbol:l??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:l,decimals:i}}:{error:"token_not_found",key:d}}requireWallet(e){let t=e?.walletAddress;return t?{ok:!0,address:t}:{ok:!1,payload:{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before submitting the action. Do NOT render the form."}}}requireChain(e,t){return re(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return q(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:n,chain:r,walletAddress:o,gasKind:s}=e,i=Fe(t);if(!i)return null;let l=e.symbol??"the token",c=n.toLowerCase()==="native",u=!!s&&c&&!!r;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let d=await this.readTokenBalanceAndPrice(n,r,o),p=d?.balance;u&&d?.balance!==void 0&&(p=await this.computeNativeSpendable(r,s,d.balance));let m=ra(i,{balance:p,usdPrice:d?.usdPrice});return m.ok?{amount:this.toPlainDecimal(m.amount)}:m.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${l} balance to work out ${i.raw} right now. Tell them, in their language, that the balance couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a balance or amount. Do NOT mention tool names, UI, or forms.`}:{error:"amount_price_unavailable",_instructions:`Could not get a USD price for ${l} to work out ${i.raw} right now. Tell them, in their language, that the price couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(e,t,n){let r=await Tn(e,t);return vn(n,r,e)}async resolveNativeSpendableFormatted(e,t,n){if(!(!e||!t))try{let r=await this.readTokenBalanceAndPrice("native",e,t);if(r?.balance===void 0)return;let o=await this.computeNativeSpendable(e,n,r.balance);return this.toPlainDecimal(o)}catch{return}}async readTokenBalanceAndPrice(e,t,n){if(!this.moralis||!n)return;let r=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[],s=e.toLowerCase()==="native",i=e.toLowerCase(),l=o.find(u=>s?u.native_token===!0:(u.token_address??"").toLowerCase()===i);if(!l)return;let c=l.balance_formatted!=null?Number(l.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof l.usd_price=="number"&&l.usd_price>0?l.usd_price:void 0,balanceFormatted:l.balance_formatted,symbol:l.symbol}}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),s=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(s>=0){let d=i.length+s;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-s-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(s.actionButtons=o.actionButtons),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=this.requireWallet(t);if(!n.ok)return n.payload;let r=St(e.chain,t);if(r){let g=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${g} on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to ${g} on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can ${g} on ${r.connectedLabel} (their current network) instead. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}let o=this.requireChain(e,t);if(!o){let g=typeof t?.query=="string"?t.query:void 0;return Pt(this.actionType.replace(/_/g," "),g)}let s=await this.buildParameters(e,t);if(s&&typeof s=="object"&&"error"in s&&typeof s.error=="string"||s&&typeof s=="object"&&"actionButtons"in s&&Array.isArray(s.actionButtons)||s&&typeof s=="object"&&"ui"in s&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string")return s;let i=s,l=this.buildUI({parameters:i,chainId:o,walletAddress:n.address}),c=g=>{let y=i[g];return y!=null&&y!==""},u=this.userInputFields.filter(g=>!(Array.isArray(g.key)?g.key:[g.key]).some(c)).map(g=>g.label),d=this.userInputFields.map(g=>{let b=(Array.isArray(g.key)?g.key:[g.key]).find(c);return b?`${g.label}: ${i[b]}`:null}).filter(g=>g!=null),p=this.actionType.replace(/_/g," "),m='NEVER invent, guess, or insert a placeholder (e.g. "[recipient address]") for any detail the user has not actually provided \u2014 only state values listed as already provided. Do NOT mention tool names, UI, or forms.',f="The user completes this themselves and it is submitted right away \u2014 do NOT ask them to reply to confirm, do NOT say you will send it for them, and do NOT announce the result. This turn ends after your message.",h=u.length>0?`The ${p} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${u.join(", ")}. `+(d.length>0?`Already provided: ${d.join("; ")}. `:"")+`${f} ${m}`:`The ${p} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${p}. `+(d.length>0?`Details provided: ${d.join("; ")}. `:"")+`${f} ${m}`;return{ui:l,action:this.actionType,chainId:o,parameters:i,_instructions:h}}};var An=class extends Pe{name="open-send-native-form";actionType="send_native";component="SendNativeForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}async run(e,t){if(e.chain==null||e.chain===""){let n=hs(e.native_symbol);if(n)return super.run({...e,chain:n},t)}return super.run(e,t)}description=`Open the SEND NATIVE form for the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026). Use for ANY native-send intent: "send eth", "send 0.1 ETH", "transfer 1 BNB to vitalik.eth", "g\u1EEDi ETH". Call EVEN IF the user did not name an amount or recipient \u2014 the form prompts for them. Do NOT use for ERC-20 tokens \u2014 use open-send-token-form instead.`;parameters=[{name:"chain",type:"string",description:'Hex chain id: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Defaults to connected chain.',required:!1},{name:"native_symbol",type:"string",description:'The native coin the user named to send, VERBATIM (e.g. "ETH", "BNB", "MATIC", "AVAX"). ALWAYS set this when the user names the coin ("send bnb" \u2192 native_symbol="BNB"); leave blank only when they say just "send" with no coin. A coin that belongs to one specific chain (BNB\u2192BSC, MATIC/POL\u2192Polygon, AVAX\u2192Avalanche, XDAI\u2192Gnosis, HYPE\u2192HyperEVM, MNT\u2192Mantle, MON\u2192Monad) selects that chain, so the tool can detect when the wallet is connected elsewhere.',required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Amount of native coin to send. Accepted forms: a plain amount ("0.1"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become the literal "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself (and for the native coin always leaves enough to cover the network fee). Omit when unknown.',required:!1}];async buildParameters(e,t){let n={},r=this.requireChain(e,t)??void 0,o=t?.walletAddress??void 0,s=await this.readTokenBalanceAndPrice("native",r,o);if(!s||s.balance==null||s.balance<=0){let u=s?.symbol||"the native coin";return{error:"no_native_balance",_instructions:`The user wants to send ${u} but their wallet holds 0 ${u} on this chain. Tell them, in their language, that they do not have any ${u} to send and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}let i=s.symbol||(typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0);if(i&&(n.native_symbol=i),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?n.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(n.to_address=e.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:r,walletAddress:o,gasKind:"send"});if(l&&"error"in l)return l;l&&(n.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(r,o,"send");return c!==void 0&&(n.spendable=c),n}};var Sn=class extends Pe{name="open-send-token-form";actionType="send_token";component="SendTokenForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}description=`Open the SEND TOKEN (ERC-20) form. Use for ANY ERC-20 send/transfer intent: "send token", "send USDC", "transfer 50 DAI to 0x\u2026", "g\u1EEDi 10 USDT". Call this tool EVEN IF the user did not name a token, amount, or recipient \u2014 the tool handles missing token via a picker, the form prompts for the rest. Do NOT use for the chain's native coin (ETH/BNB/MATIC/AVAX) \u2014 use open-send-native-form instead.`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol \u2014 the tool will look up the address.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). ALWAYS set this whenever the user names a token to send ("send usdc" \u2192 token_symbol="USDC"); only leave it blank when the user names NO token at all ("send token"), so the tool can show a wallet picker. Used to auto-resolve the contract address and to display the symbol in the form. (Pass either this or contract_address.)',required:!1},{name:"decimals",type:"number",description:"Token decimals (e.g. 6 for USDC, 18 for most ERC-20s). Optional.",required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown.",required:!1},{name:"amount",type:"string",description:'Amount of the token to send. Accepted forms: a plain amount ("100"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself. Omit when unknown.',required:!1},{name:"send_prompt_template",type:"string",description:`A short imperative "send" command IN THE USER'S LANGUAGE, used as the label/command when the user has not yet picked which token to send (token-picker buttons). Write it in the SAME language the user is using right now. Use these exact placeholders (do not translate the braces): "{symbol}" for the token, "{amount}" for the amount, "{to}" for the recipient address, "{chain}" for the chain name. Put the localized verb, the "to" preposition, and the "on <chain>" preposition directly in the text. English example: "send {amount} {symbol} to {to} on {chain}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to} tr\xEAn {chain}". Japanese example: "{chain} \u3067 {to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to}/{chain} too \u2014 the tool removes any whose value is unknown.`,required:!0}];async buildParameters(e,t){let n=this.normaliseAddress(e.contract_address)!=null,r=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!n&&!r&&this.moralis){let u=this.requireChain(e,t)??void 0,d=t?.walletAddress;if(d){let p=await this.moralis.getWalletTokenBalances({address:d,chain:u,excludeSpam:!1,excludeUnverifiedContracts:!1}),f=(p.success?p.data?.result??[]:[]).filter(k=>k.symbol&&(k.native_token||k.token_address)).sort((k,T)=>(T.usd_value??0)-(k.usd_value??0)).slice(0,8);if(f.length===0)return{error:"no_token_holdings",_instructions:"The wallet does not hold any sendable tokens on this chain. Tell the user they have nothing to send and suggest they top up first. Do NOT open the form."};let h=e.to_address!=null?this.normaliseAddress(e.to_address):null,g=this.normaliseAmount(e.amount),y=typeof e.send_prompt_template=="string"?e.send_prompt_template:"",b=u?P(u):null;return{actionButtons:f.map(k=>{let T=k.symbol,S=k.balance_formatted?this.cleanAmountString(k.balance_formatted):"",A=k.name?k.name:"",_=k.usd_value?`($${k.usd_value.toFixed(2)})`:"";return{label:`${A}:${S} ${T} ${_}`.trim(),prompt:this.buildSendPrompt(y,T,g,h,b)}}),_instructions:"Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n g\u1EEDi token.' / 'You want to send a token.'), then ask them to choose which token from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n g\u1EEDi.' / 'Please choose the token you want to send.'). Do NOT list the tokens in text \u2014 the options already show them. Do NOT mention tool names, UI, or forms."}}}let o=this.requireChain(e,t)??void 0,s=t?.walletAddress??void 0,i=await this.findOwnedTokenForSend(e,o,s);if(i&&"error"in i)return i;let l=i?.token,c={};if(l?.address&&(c.contract_address=l.address),l?.symbol&&(c.token_symbol=l.symbol),l?.decimals!==void 0&&(c.decimals=String(l.decimals)),i?.spendable!==void 0&&(c.spendable=i.spendable),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?c.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(c.to_address=e.to_address.trim())}if(l?.address){let u=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:l.address,symbol:l.symbol,chain:o,walletAddress:s});if(u&&"error"in u)return u;u&&(c.amount=u.amount)}else{let u=this.normaliseAmount(e.amount);u&&(c.amount=u)}return c}async findOwnedTokenForSend(e,t,n){let r=this.normaliseAddress(e.contract_address),o=typeof e.token_symbol=="string"&&e.token_symbol.trim()?e.token_symbol.trim():void 0,s=r??o;if(!this.moralis||!n||!s){let m=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:n});return"error"in m?{error:"token_not_found",symbol:m.key,_instructions:`Could not resolve token "${m.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:m.token}}let i=s.toLowerCase(),l=r!=null,c=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=(c.success?c.data?.result??[]:[]).find(m=>l?(m.token_address??"").toLowerCase()===i:(m.symbol??"").toLowerCase()===i);if(d&&d.balance&&!/^0*$/.test(d.balance.trim())){let m=this.parseDecimals(e.decimals);return{token:{address:d.token_address,symbol:d.symbol??o,name:d.name,decimals:m??(typeof d.decimals=="number"?d.decimals:void 0)},spendable:d.balance_formatted?this.cleanAmountString(d.balance_formatted):void 0}}let p=d?.symbol??o??s;return{error:"no_balance",symbol:p,_instructions:`The user does not hold any ${p} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${p} to send, and suggest they top up or pick another token. Do NOT open a form. Do NOT mention tool names, UI, or forms.`}}buildSendPrompt(e,t,n,r,o){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,n??"");return i=this.fillOrDropPhrase(i,"{to}",r),i=this.fillOrDropPhrase(i,"{chain}",o),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,n){if(n)return e.split(t).join(n);let r=t.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${r}`,"g"),"").replace(new RegExp(`${r}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(r,"g"),"")}};var Pn=class extends Pe{name="open-approve-token-form";actionType="approve_token";component="ApproveTokenForm";userInputFields=[{key:"spender_address",label:"the spender address to approve"}];constructor(e){super(e)}description='Open the APPROVE TOKEN form so the user can grant a spender allowance on an ERC-20 token. Use when the user says "approve USDC for Uniswap", "c\u1EA5p quy\u1EC1n 100 USDT cho 0x\u2026", "revoke approval". Pass `contract_address` when you have it; otherwise pass `token_symbol` (e.g. "USDC") and the tool auto-resolves the contract. Always pass `spender_address` (the contract being approved). Pass `amount` for a specific allowance; omit for unlimited (max uint256). For approving 0 to revoke, pass amount="0".';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). Required when contract_address is not given. Used to auto-resolve the contract.',required:!1},{name:"decimals",type:"number",description:"Token decimals.",required:!1},{name:"spender_address",type:"string",description:"EVM address of the spender contract being approved (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Human-readable allowance amount. Omit for UNLIMITED (max uint256). Pass "0" to revoke.',required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:n,walletAddress:t?.walletAddress??void 0});if("error"in r)return{error:"token_not_found",symbol:r.key,_instructions:`Could not resolve token "${r.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let o=r.token,s=this.normaliseAddress(e.spender_address),i={};if(o?.address&&(i.contract_address=o.address),s&&(i.spender_address=s),o?.symbol&&(i.token_symbol=o.symbol),o?.decimals!==void 0&&(i.decimals=String(o.decimals)),typeof e.amount=="string"&&e.amount.trim()){let l=e.amount.trim(),c=parseFloat(l);Number.isFinite(c)&&c>=0&&(i.amount=l)}else typeof e.amount=="number"&&Number.isFinite(e.amount)&&e.amount>=0&&(i.amount=String(e.amount));return i}};var xn=class extends v{name="open-buy-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new D(e),this.pantograph=new le({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[BuyTokenTool] ${e}`):console.log(`[BuyTokenTool] ${e}`,JSON.stringify(t)))}description='Open the BUY TOKEN flow for ANY buy/purchase intent. Handles both cases: (a) the user NAMED a token \u2014 "buy PEPE", "mua DOGE", "buy 100 USDC with ETH": pass `token_symbol` (the destination); if you also know the pay token, fill `pay_with_symbol` (or `pay_with_address`), else leave pay_with_* blank and the tool returns a wallet picker. (b) the user did NOT name a token \u2014 "buy a trending token", "mua token trending", "buy something pumping", "buy hot tokens", "mua token t\u0103ng m\u1EA1nh": leave `token_symbol` blank and the tool returns buttons of the chain\'s current trending tokens so the user picks one. Amount: `buy_amount` = destination to RECEIVE; `pay_with_amount` = payment to SPEND. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"token_symbol",type:"string",description:'Symbol of the token the user wants to BUY (e.g. "PEPE"). Leave EMPTY when the user did not name a token (e.g. "buy a trending token") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"contract_address",type:"string",description:`Destination token address (0x\u2026), or "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from token_symbol.`,required:!1},{name:"buy_amount",type:"string",description:`Quantity of the DESTINATION token (the one being bought) the user wants to RECEIVE. Set this when the amount sits next to the token being bought: "buy 5 PEPE", "mua 5 PEPE", "buy 0.02 PCM with USDC" \u2192 buy_amount = the number next to PEPE/PCM. May also be a USD value when the user sizes the buy in dollars ("buy $5 of PEPE" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$" to a token quantity). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with pay_with_amount \u2014 set at most ONE of the two.`,required:!1},{name:"pay_with_symbol",type:"string",description:'Symbol of the payment token (e.g. "USDC", "ETH"). Set ONLY when the user actually named a token to pay with. Leave EMPTY when they did not \u2014 do NOT default to the native coin / ETH; the tool then returns a picker of the tokens the wallet holds.',required:!1},{name:"pay_with_address",type:"string",description:`Address of the payment token (0x\u2026), OR "native" for the chain's native coin. Set ONLY when the user named the payment token. Leave EMPTY when they did not \u2014 do NOT invent an address or default to native.`,required:!1},{name:"pay_with_amount",type:"string",description:'Quantity of the PAYMENT token (the one being spent) the user wants to SPEND. Set this when the amount sits next to the payment token: "buy PEPE with 10 USDC", "mua PEPE b\u1EB1ng 10 USDC", "spend 0.5 ETH on DOGE" \u2192 pay_with_amount = the number next to USDC/ETH. May also be a PERCENT of the pay-token balance ("buy USDC with 50% USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("buy USDC with 5$ USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set pay_with_symbol to the payment token ("ETH" in "buy USDC with max ETH"). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with buy_amount \u2014 set at most ONE of the two.',required:!1},{name:"limit",type:"number",description:"Only used when no token is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the trending-token picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_with_prompt_template",type:"string",description:`A short "buy X with Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the pay-token picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{token}" = token being bought, "{pay}" = payment token, "{buy_amount}" = quantity of the BOUGHT token (place it next to {token}), "{pay_amount}" = quantity of the PAYMENT token (place it next to {pay}). Put the localized verb and the "with" preposition directly in the text. English example: "buy {buy_amount} {token} with {pay_amount} {pay}". Vietnamese example: "mua {buy_amount} {token} b\u1EB1ng {pay_amount} {pay}". Japanese example: "{pay_amount} {pay} \u3067 {buy_amount} {token} \u8CFC\u5165". Always include {token} and {pay}. Include both {buy_amount} and {pay_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount).`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(s.actionButtons=o.actionButtons),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let r=St(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to buy on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to buy on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can buy on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let s=typeof t?.query=="string"?t.query:void 0;return Pt("buy",s)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let n=typeof e.token_symbol=="string"?e.token_symbol.trim():"",r=typeof e.contract_address=="string"?e.contract_address.trim():"",o=this.requireChain(e,t)??void 0,s=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:o,walletAddress:s,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(e,t);let i=await this.resolveSide(e.contract_address,n,o,s,"dest"),l=i.address,c=i.symbol??n,u=i.decimals,d=await this.resolveSide(e.pay_with_address,e.pay_with_symbol,o,s,"pay"),p=d.address,m=d.symbol,f=d.decimals,h=await this.resolveBuyAmountSpec(e.buy_amount,l,o,c),g=p?await this.resolvePayAmountSpec(e.pay_with_amount,p,o,s,m,f??(p==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),y=Fe(e.pay_with_amount),b=!!y&&y.kind!=="token",w=null;if(this.dbg("resolved sides",{dest:{destContract:l,destSymbol:c,destDecimals:u},pay:{payAddr:p,paySymbol:m,payDecimals:f},buyAmount:h,payAmount:g}),!l)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${c||r}" to buy on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!p&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:c,destContract:l,buyAmount:h,payAmount:g});if(!p)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${c}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(h&&!g){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:h,destSymbol:c,paySymbol:m});let k=await this.derivePayAmountFromBuy({chain:o,buyAmount:h,destContract:l,destSymbol:c,payAddr:p,paySymbol:m});if(!k)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${m??"of the payment token"} equals ${h} ${c} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${m??"of the payment token"} they want to spend instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};g=k,w=h,b=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:g,derivedFromBuy:w})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:p,paySymbol:m,payAmount:g});let k=await this.checkPayBalance({args:e,userContext:t,chain:o,destSymbol:c,destContract:l,payAddr:p,paySymbol:m,payAmount:g,buyAmount:h,derivedFromBuy:w,amountSizedToBalance:b});if(k)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:k.error,hasButtons:Array.isArray(k.actionButtons)}),k;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!h&&!g&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let k=await this.buildAmountPicker({userContext:t,chain:o,destSymbol:c,payAddr:p,paySymbol:m,buyWithTemplate:typeof e.buy_with_prompt_template=="string"?e.buy_with_prompt_template:""});if(k)return this.dbg("\u2192 Branch 1.5: amount picker returned"),k;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(g&&(f!==void 0||p==="native")){this.dbg("Branch 1.75: building confirm tx");let k=await this.buildConfirmTx({userContext:t,chain:o,destContract:l,destSymbol:c,destDecimals:u,payAddr:p,paySymbol:m,payDecimals:f,payAmount:g});return k&&"ui"in k?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),k):k&&"quoteError"in k?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:k.quoteError}),{error:"quote_failed",quoteError:k.quoteError,_instructions:`Could not quote buying ${c} with ${m??"the selected token"}. The swap provider reported: "${k.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to buy ${c} with ${m??"the selected token"} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs pay amount"),{error:"needs_pay_amount",_instructions:`Ask the user, in their language, how much ${m??"of the payment token"} they want to spend to buy ${c}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return q(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!n)return null;let r=parseFloat(n[1]);return Number.isFinite(r)&&r>0?n[1]:null}correctAmountSide(e,t){let n=typeof t?.query=="string"?t.query:"",r=typeof e.token_symbol=="string"?e.token_symbol.trim():"",o=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"";if(!n||!r||!o)return;let s=typeof e.buy_amount=="string"?e.buy_amount.trim():"",i=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",l=s.length>0,c=i.length>0;if(l===c)return;let u=l?s:i,d=u.match(/[0-9]*\.?[0-9]+/)?.[0];if(!d)return;let p=this.nearestSymbolSide(n,d,r,o);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:u,buySym:r,paySym:o}),e.pay_with_amount=u,e.buy_amount=""):p==="buy"&&c&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:u,buySym:r,paySym:o}),e.buy_amount=u,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=typeof e.token_symbol=="string"?e.token_symbol.trim():"";if(!r)return;let o=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"",s=typeof e.pay_with_address=="string"?e.pay_with_address.trim():"";if(!o&&!s)return;let i=n.toLowerCase(),l=o.toLowerCase(),c=s.toLowerCase(),u=l==="native"||c==="native",d=[];if(o&&l!=="native"&&d.push(l),c&&c!=="native"&&d.push(c),u){d.push("native");let m=this.requireChain(e,t)??void 0,f=m?oe(m)?.native.symbol:void 0;f&&d.push(f.toLowerCase())}d.some(m=>q(m)?i.includes(m):this.indexOfToken(i,m)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:o,payAddr:s,buySym:r}),e.pay_with_symbol="",e.pay_with_address="")}dropInventedAmounts(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=(n.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),o=s=>{let i=typeof e[s]=="string"?e[s].trim():"";if(!i)return;let l=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(l===void 0)return;let c=parseFloat(l);Number.isFinite(c)&&(r.some(u=>u===c)||(this.dbg(`dropInventedAmounts: clearing invented ${s}`,{val:i}),e[s]=""))};o("buy_amount"),o("pay_with_amount")}nearestSymbolSide(e,t,n,r){let o=e.toLowerCase(),s=o.indexOf(t.toLowerCase()),i=this.indexOfToken(o,n.toLowerCase()),l=this.indexOfToken(o,r.toLowerCase());if(s<0||i<0||l<0)return null;let c=(p,m)=>Math.max(0,p-(s+t.length),s-(p+m)),u=c(i,n.length),d=c(l,r.length);return d===u?null:d<u?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|[^a-z0-9])(${n})(?:[^a-z0-9]|$)`));return r&&r.index!==void 0?r.index+r[0].indexOf(r[1]):-1}requireChain(e,t){let n=typeof e.chain=="string"&&e.chain.trim()?e.chain.trim():null;return n||(typeof t?.chain=="string"&&t.chain.trim()?t.chain.trim():null)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=q(e.trim()),s=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(s);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(s)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let s=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(s.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,u=m=>m.toLowerCase()===B?"native":m,d=l??c??(s||void 0);if(!d)return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(d,n,r);return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:i,chain:n,key:d,lookup:p}),p?{address:u(p.address),symbol:c??p.symbol,decimals:p.decimals}:l?{address:u(l),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,destContract:r,destSymbol:o,destDecimals:s,payAddr:i,paySymbol:l,payDecimals:c,payAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let p=oe(n),m=Number.parseInt(n,16);if(!p||!Number.isFinite(m))return null;let f=i==="native",h=f?p.native.decimals??18:c;if(h===void 0)return null;let g=this.toRawAmount(u,h);if(!g)return null;let y=f?B:i,b=r==="native"?B:r,w;try{w=await(await Me.getServiceByProvider("debridge")).getQuote({srcChainId:m,srcTokenAddress:y,srcTokenAmount:g,dstChainId:m,dstTokenAddress:b,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(E){return{quoteError:E instanceof Error?E.message:String(E)}}if(!w.success)return this.dbg("buildConfirmTx: quote failed",{error:w.error,errorMessage:w.errorMessage}),{quoteError:this.extractQuoteError(w)};if(!w.tx)return{quoteError:"No route available for this swap."};let k=w.tx;if(!k.to||typeof k.data!="string")return null;let T={chainId:n,to:k.to,data:k.data,value:k.value??"0",from:d},S=this.extractOutRaw(w),A=S&&s!==void 0?this.trimAmount(Number(S)/10**s):void 0,_;f||(_=await this.buildApproveTx({chain:n,walletAddress:d,payAddr:i,payDec:h,rawAmount:g,quote:w}));let C={component:"BuyTokenConfirmTx",props:{chain:{hexId:n,name:p.name},payToken:{address:f?"native":i,symbol:l,decimals:h,amount:u,rawAmount:g},buyToken:{address:r,symbol:o,decimals:s,amount:A,rawAmount:S},estimatedOut:A,estimatedOutRaw:S,provider:w.provider,swapTx:T,approveTx:_}},M=A?` They will receive about ${A} ${o}.`:"";return{ui:C,_instructions:`The purchase of ${o} with ${u} ${l??"the selected token"} is ready for the user to confirm.${M} Briefly tell the user, in their language, the amount they are spending and the estimated amount they will receive, and ask them to review and confirm to complete the purchase. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (buying) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async derivePayAmountFromBuy(e){let{chain:t,buyAmount:n,destContract:r,payAddr:o}=e,[s,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:s,payPrice:i}),!s||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,u=l*s/i;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?B:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),o=r.success?r.data?.usd_price:void 0;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}async resolvePayAmountSpec(e,t,n,r,o,s){let i=Fe(e);if(!i)return null;let l=u=>s===void 0?u:bt(u,s);if(i.kind==="token")return l(yt(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let u=await this.readPayBalance(r,t,n);if(this.dbg("resolvePayAmountSpec: percent",{percent:i.percent,paySymbol:o,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??s??18;return i.percent>=100?this.cleanAmountString(u.balanceFormatted):wt(u.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,d)}let c=await this.getUsdPrice(t,n);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:o,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,n,r){let o=Fe(e);if(!o)return null;if(o.kind==="token")return yt(e)??this.toPlainDecimal(o.value);if(o.kind==="percent"||!t)return null;let s=await this.getUsdPrice(t,n);return this.dbg("resolveBuyAmountSpec: usd",{usd:o.usd,destSymbol:r,price:s}),s?this.trimAmount(o.usd/s):null}async buildApproveTx(e){let{chain:t,walletAddress:n,payAddr:r,payDec:o,rawAmount:s,quote:i}=e;try{let c=await(await Me.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:s,tokenDecimals:o,quoteData:i});if(!c.isNeeded)return;let u=c.approvalData??{};if(u.to&&typeof u.data=="string")return{chainId:t,to:u.to,data:u.data,value:u.value??"0",from:n};let d=c.contractAddress;if(!d)return;let p=ht({abi:Io,functionName:"approve",args:[d,BigInt(s)]});return{chainId:t,to:r,data:p,value:"0",from:n}}catch{return}}toRawAmount(e,t){let n=e.trim();if(!/^\d*\.?\d+$/.test(n))return null;let[r,o=""]=n.split("."),s=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(s||"0");return i<=0n?null:i.toString()}catch{return null}}extractQuoteError(e){if(e.errorMessage&&e.errorMessage.trim())return e.errorMessage.trim();let t=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},n=e.raw??{};return t(e.error)??t(n.errorMessage)??t(n.error)??"The swap could not be quoted right now."}extractOutRaw(e){let t=e.raw??{},n=t.tokenOut?.amount??t.tokenOut?.minAmount??t.details?.currencyOut?.amount??t.details?.currencyOut?.minimumAmount??t.estimation?.dstChainTokenOut?.recommendedAmount??t.estimation?.dstChainTokenOut?.amount;return n&&/^\d+$/.test(n)?n:void 0}async buildPayWithPicker(e){let{args:t,userContext:n,destSymbol:r,destContract:o}=e,s=this.requireChain(t,n)??void 0,i=this.moralis,l=n.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:s,excludeSpam:!1,excludeUnverifiedContracts:!1}),u=c.success?c.data?.result??[]:[],d=o?.toLowerCase(),p=r.trim().toLowerCase(),m=u.filter(b=>!b.symbol||p&&b.symbol.toLowerCase()===p?!1:b.native_token?d!=="native":!(!b.token_address||d&&b.token_address.toLowerCase()===d)).sort((b,w)=>(w.usd_value??0)-(b.usd_value??0)).slice(0,8);if(m.length===0)return{error:"no_pay_token_holdings",_instructions:"The wallet has no tokens that can pay for this purchase on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let f=e.buyAmount??this.normaliseAmount(t.buy_amount),h=e.payAmount??this.normaliseAmount(t.pay_with_amount),g=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:m.map(b=>{let w=b.symbol,k=b.name?.trim()||w,T=b.balance_formatted?`${this.cleanAmountString(b.balance_formatted)} `:"",S=typeof b.usd_value=="number"&&b.usd_value>0?` ($${b.usd_value.toFixed(2)})`:"",A=`${k}: ${T}${w}${S}`,_=f?this.buildBuyWithPrompt(g,r,w,f,null):this.buildBuyWithPrompt(g,r,w,null,h);return{label:A,prompt:_}}),_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n mua ${r}.' / 'You want to buy ${r}.'), then ask them to choose which token they want to spend to buy ${r} from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua.' / 'Please choose the token to spend.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async checkPayBalance(e){let{args:t,userContext:n,chain:r,destSymbol:o,destContract:s,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:u}=e,d=n.walletAddress,p=await this.readPayBalance(d,i,r),m=e.paySymbol??p?.symbol??"the selected token";if(!p){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:m});let b=await this.buildPayWithPicker({args:t,userContext:n,destSymbol:o,destContract:s,buyAmount:c,payAmount:l});return"actionButtons"in b?{error:"no_pay_balance",actionButtons:b.actionButtons,_instructions:`The user wanted to spend ${m} to buy ${o}, but their wallet holds no ${m} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${m} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${m} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to pay with (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua ${o} t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to pay with from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:b}if(!l||e.amountSizedToBalance)return null;let f=p.decimals!==void 0?bt(l,p.decimals):l;if(po(f,p.balanceFormatted)<=0)return null;let h=this.cleanAmountString(p.balanceFormatted),g=this.percentSpendButtons({balanceFormatted:p.balanceFormatted,balanceNum:p.balanceNum,decimals:p.decimals,paySymbol:m,destSymbol:o,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:""}),y=u?`Buying ${u} ${o} needs about ${l} ${m}, but they only have ${h} ${m} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them that buying ${u} ${o} would cost about ${l} ${m}, which is more than their balance of ${h} ${m}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${l} ${m} to buy ${o}, but they only have ${h} ${m} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${l} ${m} exceeds their balance of ${h} ${m}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:g,_instructions:y+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readPayBalance(e,t,n){if(!this.moralis)return null;let r=await this.moralis.getWalletTokenBalances({address:e,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[];this.dbg("readPayBalance",{payAddr:t,chain:n,ok:r.success,count:o.length,held:o.map(c=>({sym:c.symbol,addr:c.token_address,bal:c.balance_formatted}))});let s=t.toLowerCase(),i=o.find(c=>s==="native"?c.native_token===!0:c.token_address?.toLowerCase()===s);if(!i?.balance_formatted)return this.dbg("readPayBalance: pay token NOT held \u2192 null",{payAddr:t}),null;let l=Number(i.balance_formatted);if(!Number.isFinite(l)||l<=0)return this.dbg("readPayBalance: zero/invalid balance \u2192 null",{payAddr:t,balance:i.balance_formatted}),null;if(s==="native"&&n){let c=await Tn(n,"swap"),u=vn(l,c,n);if(this.dbg("readPayBalance: native spendable",{balanceNum:l,spendable:u}),u<=0)return this.dbg("readPayBalance: native spendable \u2264 0 \u2192 null",{balanceNum:l}),null;let d=this.trimAmount(u),p=typeof i.decimals=="number"?i.decimals:18;return{balanceFormatted:d,balanceNum:u,symbol:i.symbol,decimals:p}}return this.dbg("readPayBalance: held",{payAddr:t,balance:i.balance_formatted,symbol:i.symbol}),{balanceFormatted:i.balance_formatted,balanceNum:l,symbol:i.symbol,decimals:typeof i.decimals=="number"?i.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,paySymbol:r,destSymbol:o,buyWithTemplate:s}=e,i=n??18;return[25,50,75,100].map(c=>{let u=wt(this.cleanAmountString(t),BigInt(c),100n,i);return{label:`${c}%`,prompt:this.buildBuyWithPrompt(s,o,r,null,u)}})}async buildAmountPicker(e){let{userContext:t,chain:n,destSymbol:r,payAddr:o,buyWithTemplate:s}=e,i=t.walletAddress,l=await this.readPayBalance(i,o,n),c=e.paySymbol??l?.symbol;if(!l||!c)return null;let u=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,paySymbol:c,destSymbol:r,buyWithTemplate:s}),d=this.cleanAmountString(l.balanceFormatted);return{actionButtons:u,_instructions:`The user's spendable balance is ${d} ${c}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${c} balance (e.g., 'B\u1EA1n mu\u1ED1n mua ${r} b\u1EB1ng ${c}, hi\u1EC7n c\xF3 ${d} ${c} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to buy ${r} with ${c}; you have ${d} ${c} available.'), then ask how much they want to spend and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),s=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(s>=0){let d=i.length+s;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-s-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildBuyPrompt(e,t){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}buildBuyWithPrompt(e,t,n,r,o){return(e&&e.includes("{token}")&&e.includes("{pay}")?e:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,t).replace(/\{pay\}/g,n).replace(/\{buy_amount\}/g,r??"").replace(/\{pay_amount\}/g,o??"").replace(/\s+/g," ").trim()}async buildTrendingPicker(e,t){if(!this.pantograph)return{error:"trending_unavailable",_instructions:"Trending tokens are unavailable in this build (service not configured). Tell the user briefly and ask them to name a token to buy."};let n=this.requireChain(e,t)??void 0,r=typeof e.limit=="number"&&Number.isFinite(e.limit)?Math.floor(e.limit):6,o=Math.max(1,Math.min(10,r)),s=await this.pantograph.getTrendingTokens({chain:n,limit:o}),i=s.success?s.data??[]:[];if(i.length===0)return{error:"no_trending_tokens",_instructions:"No trending tokens are available for this chain right now. Tell the user briefly and suggest they name a token directly."};let l=i.filter(m=>m.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",u=l.map(m=>{let f=m.symbol;return{label:f,prompt:this.buildBuyPrompt(c,f)}}),p=l.map((m,f)=>{let h=m.name?.trim()||m.symbol,g=m.symbol,y=typeof m.usdPrice=="number"&&m.usdPrice>0?`$${this.formatPrice(m.usdPrice)}`:"N/A",b=m.pricePercentChange?.["24h"],w=typeof b=="number"&&Number.isFinite(b)?` (${b>0?"+":b<0?"-":""}${this.formatPercent(Math.abs(b))}%)`:"";return`${f+1}. ${h} (${g}) \u2014 ${y}${w}`}).join(`
186
+ `+(f.length>0?'2) A few popular pools (from the provided list) as examples to add liquidity to \u2014 show fee tier %, TVL, APR (skip APR if null). For EACH pool, make it a clickable Uniswap link using its `uniswapUrl`: wrap the pair as a markdown link, e.g. "[USDC/WETH](uniswapUrl)", or append "[View on Uniswap](uniswapUrl)". Use the uniswapUrl verbatim; never invent one. Make clear these are just examples for reference, not recommendations.\n':"")+(f.length>0?"3) ":"2) ")+this.linkInstruction(u)+`
187
+ Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:m||void 0,addLiquidityLink:u,count:f.length,pools:f.map(h=>this.formatPool(h))}}let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=(Array.isArray(e.tokens)?e.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase()),o=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,s=typeof e.chain=="string"&&e.chain.trim();if(!s&&!t?.chain&&t?.walletAddress)throw new K(typeof t?.query=="string"?t.query:void 0);let i=s?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(i))return{_instructions:"The requested chain is not supported by the Subgraph pool service. Tell the user, in their language, that add-liquidity is not available on that network and list the supported chains briefly. Do NOT mention tool names.",unsupportedChains:[P(i)],supportedChains:this.service.listSupportedChains().map(P)};let l=this.service.resolveChain(i);if(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let u=await this.service.getPoolByAddress({poolAddress:n,chain:l});return u?this.poolsResult([u],l,!0):{error:`No pool found at ${n} on ${P(l)}.`}}if(r.length>0){let u=await this.service.searchPools({tokens:r,chain:l,sortBy:"tvl",filters:{feeTier:o}});if(u.length===0)return{error:`No Uniswap V3 pool found for ${r.join("/")}${o!=null?` at ${o}bps`:""} on ${P(l)}. Ask the user to check the token symbols, or try a different pair.`};let p=r.length===2?await this.fetchCoinPoolPairs(l,r):[];return this.poolsResult(u.slice(0,8),l,!0,p)}let c=await this.service.searchPools({tokens:[],chain:l,sortBy:"tvl"}),d=this.linkAddLiquidity??null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity but has not named a pool yet. Briefly list these top pools (pair, fee tier %, TVL, APR \u2014 skip APR if null) as suggestions, render each `uniswapUrl` as a clickable markdown link, then ask the user which token pair (or pool) they want to add liquidity to. '+this.linkInstruction(d)+"Do NOT mention tool names, UI, or forms.",chain:l,needsSelection:!0,addLiquidityLink:d,count:c.length,pools:c.slice(0,6).map(u=>this.formatPool(u))}}async fetchCoinPoolPairs(e,t){try{return[...await this.service.getCoinPoolPairs({chain:e,tokens:t})].sort((r,o)=>(o.apr??-1/0)-(r.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(e){return e?`ALWAYS finish by inviting the user to add liquidity on the website, as ONE short sentence that shows the FULL link in plain view \u2014 display the entire URL verbatim (${e}) as the visible link text, do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${e}](${e}). For example: "You can add liquidity here: [${e}](${e})". Use the URL verbatim; never invent one, and never use a pool's uniswapUrl here. `:"No add-liquidity website is configured, so do not show or invent any link. "}poolsResult(e,t,n,r=[]){let o=n?this.linkAddLiquidity??null:null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity. Show the resolved pool(s): pair (e.g. USDC/WETH), fee tier (%), TVL, volume past day, APR (skip if null), and the pool address. For EACH pool, render the provided `uniswapUrl` as a clickable markdown link. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)", to help the user choose a range when adding liquidity. CRITICAL: that APR is for the SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the data, give a genuine, conversational recommendation \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4A1} Recommendation"); vary your wording naturally each time and only cover what is actually relevant to THIS pair and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: which pool/fee tier looks best and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; fee-tier fit: 0.05% for stable/correlated pairs, 0.30% for typical volatile pairs, 1% for exotic/low-liquidity ones); which price range makes sense (from coinPoolPairs if present) \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; anything worth avoiding (thin TVL/volume, ranges far from current price, chasing the top APR blindly); and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Keep it short and human \u2014 a sentence or two or a couple of light bullets, tailored to whether the pair is stable or volatile. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, do not paste a stock disclaimer). '+(o?`Then, at the VERY END, write ONE short, friendly sentence in the user's language inviting them to add liquidity, showing the FULL add-liquidity link in plain view: display the entire URL verbatim as the visible link text \u2014 do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${o}](${o}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${o}](${o})." Use the addLiquidityLink verbatim; never invent a URL, and never use a pool's uniswapUrl here.`:"Do NOT invent or show any add-liquidity link (none is configured). Just present the pool(s).")+" Do NOT mention tool names, UI, forms, or that a transaction is built elsewhere.",chain:t,addLiquidityLink:o,count:e.length,pools:e.map(i=>this.formatPool(i)),coinPoolPairs:r}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:ke(e)}}};function Fe(a){if(typeof a=="number")return Number.isFinite(a)&&a>0?{kind:"token",value:a,raw:String(a)}:null;if(typeof a!="string")return null;let e=a.trim();if(!e)return null;if(/^(?:max(?:imum)?|all|everything|tất\s*cả|toàn\s*bộ)$/i.test(e))return{kind:"percent",percent:100,raw:e};let t=e.match(/^%?\s*([0-9]*\.?[0-9]+)\s*%$|^%\s*([0-9]*\.?[0-9]+)$/);if(t){let o=parseFloat(t[1]??t[2]);return Number.isFinite(o)&&o>0?{kind:"percent",percent:o,raw:e}:null}let n=e.match(/^\$\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*\$$|^(?:usd)\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*usd$/i);if(n){let o=parseFloat(n[1]??n[2]??n[3]??n[4]);return Number.isFinite(o)&&o>0?{kind:"usd",usd:o,raw:e}:null}let r=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(r){let o=parseFloat(r[1]);return Number.isFinite(o)&&o>0?{kind:"token",value:o,raw:e}:null}return null}function ra(a,e){switch(a.kind){case"token":return{ok:!0,amount:a.value};case"percent":return e.balance===void 0||!Number.isFinite(e.balance)||e.balance<=0?{ok:!1,reason:"no_balance"}:{ok:!0,amount:e.balance*a.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:a.usd/e.usdPrice}}}var vc={send:30000n,swap:1000000n},Ac={"0x1":["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"],"0xa":["https://optimism-rpc.publicnode.com","https://optimism.drpc.org"],"0x38":["https://bsc-rpc.publicnode.com","https://bsc.drpc.org"],"0x89":["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"],"0x2105":["https://base-rpc.publicnode.com","https://base.drpc.org"],"0xa4b1":["https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"],"0xa86a":["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"],"0xe708":["https://linea-rpc.publicnode.com","https://linea.drpc.org"],"0x64":["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"],"0x3e7":["https://rpc.hyperliquid.xyz/evm"],"0x1388":["https://mantle-rpc.publicnode.com","https://rpc.mantle.xyz"],"0x8f":["https://rpc.monad.xyz"]};async function Sc(a){let e=a.toLowerCase(),n=[$e(a),...Ac[e]??[]].filter(r=>!!r);for(let r of n)try{let o=await Ve(r,"eth_gasPrice",[]),s=BigInt(o);if(s>0n)return s}catch{}return 0n}async function Tn(a,e){let t=await Sc(a);return t<=0n?0n:vc[e]*t}function vn(a,e,t){if(e<=0n)return a;let n=oe(t)?.native.decimals;if(n===void 0)return a;let r=Number(e)/10**n;return!Number.isFinite(r)||r<=0?a:Math.max(0,a-r)}var Pe=class extends v{kind="ui";category="wallet-action";buildUI(e){let t={action:this.actionType,chainId:e.chainId,chainName:P(e.chainId),walletAddress:e.walletAddress,parameters:e.parameters};return{component:this.component,props:t}}userInputFields=[];moralis;constructor(e){super(),e!==void 0&&(this.moralis=new D(e))}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=q(e.trim()),s=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(s);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(s)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}parseDecimals(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isInteger(t)&&t>=0)return t}}async resolveTokenRef(e){let{contractArg:t,symbolArg:n,decimalsArg:r,chain:o,walletAddress:s}=e,i=this.parseDecimals(r),l=typeof n=="string"&&n.trim()?n.trim():void 0,c=this.normaliseAddress(t),d=typeof t=="string"&&t.trim()?t.trim():void 0,u=c??l??d;if(!u)return{token:void 0};let p=await this.resolveContractAddress(u,o,s);return p?{token:{address:p.address,symbol:l??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:l,decimals:i}}:{error:"token_not_found",key:u}}requireWallet(e){let t=e?.walletAddress;return t?{ok:!0,address:t}:{ok:!1,payload:{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before submitting the action. Do NOT render the form."}}}requireChain(e,t){return re(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return q(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:n,chain:r,walletAddress:o,gasKind:s}=e,i=Fe(t);if(!i)return null;let l=e.symbol??"the token",c=n.toLowerCase()==="native",d=!!s&&c&&!!r;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let u=await this.readTokenBalanceAndPrice(n,r,o),p=u?.balance;d&&u?.balance!==void 0&&(p=await this.computeNativeSpendable(r,s,u.balance));let m=ra(i,{balance:p,usdPrice:u?.usdPrice});return m.ok?{amount:this.toPlainDecimal(m.amount)}:m.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${l} balance to work out ${i.raw} right now. Tell them, in their language, that the balance couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a balance or amount. Do NOT mention tool names, UI, or forms.`}:{error:"amount_price_unavailable",_instructions:`Could not get a USD price for ${l} to work out ${i.raw} right now. Tell them, in their language, that the price couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(e,t,n){let r=await Tn(e,t);return vn(n,r,e)}async resolveNativeSpendableFormatted(e,t,n){if(!(!e||!t))try{let r=await this.readTokenBalanceAndPrice("native",e,t);if(r?.balance===void 0)return;let o=await this.computeNativeSpendable(e,n,r.balance);return this.toPlainDecimal(o)}catch{return}}async readTokenBalanceAndPrice(e,t,n){if(!this.moralis||!n)return;let r=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[],s=e.toLowerCase()==="native",i=e.toLowerCase(),l=o.find(d=>s?d.native_token===!0:(d.token_address??"").toLowerCase()===i);if(!l)return;let c=l.balance_formatted!=null?Number(l.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof l.usd_price=="number"&&l.usd_price>0?l.usd_price:void 0,balanceFormatted:l.balance_formatted,symbol:l.symbol}}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),s=Number(o),[i,l=""]=r.split("."),c=i+l,d;if(s>=0){let u=i.length+s;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-s-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),n?`-${d}`:d}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isFinite(t)||t<=0)return;let r=n*t;if(!(!Number.isFinite(r)||r<=0))return this.toPlainDecimal(r)}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(s.actionButtons=o.actionButtons),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=this.requireWallet(t);if(!n.ok)return n.payload;let r=St(e.chain,t);if(r){let g=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${g} on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to ${g} on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can ${g} on ${r.connectedLabel} (their current network) instead. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}let o=this.requireChain(e,t);if(!o){let g=typeof t?.query=="string"?t.query:void 0;return Pt(this.actionType.replace(/_/g," "),g)}let s=await this.buildParameters(e,t);if(s&&typeof s=="object"&&"error"in s&&typeof s.error=="string"||s&&typeof s=="object"&&"actionButtons"in s&&Array.isArray(s.actionButtons)||s&&typeof s=="object"&&"ui"in s&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string")return s;let i=s,l=this.buildUI({parameters:i,chainId:o,walletAddress:n.address}),c=g=>{let y=i[g];return y!=null&&y!==""},d=this.userInputFields.filter(g=>!(Array.isArray(g.key)?g.key:[g.key]).some(c)).map(g=>g.label),u=this.userInputFields.map(g=>{let b=(Array.isArray(g.key)?g.key:[g.key]).find(c);return b?`${g.label}: ${i[b]}`:null}).filter(g=>g!=null),p=this.actionType.replace(/_/g," "),m='NEVER invent, guess, or insert a placeholder (e.g. "[recipient address]") for any detail the user has not actually provided \u2014 only state values listed as already provided. Do NOT mention tool names, UI, or forms.',f="The user completes this themselves and it is submitted right away \u2014 do NOT ask them to reply to confirm, do NOT say you will send it for them, and do NOT announce the result. This turn ends after your message.",h=d.length>0?`The ${p} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${d.join(", ")}. `+(u.length>0?`Already provided: ${u.join("; ")}. `:"")+`${f} ${m}`:`The ${p} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${p}. `+(u.length>0?`Details provided: ${u.join("; ")}. `:"")+`${f} ${m}`;return{ui:l,action:this.actionType,chainId:o,parameters:i,_instructions:h}}};var An=class extends Pe{name="open-send-native-form";actionType="send_native";component="SendNativeForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}async run(e,t){if(e.chain==null||e.chain===""){let n=hs(e.native_symbol);if(n)return super.run({...e,chain:n},t)}return super.run(e,t)}description=`Open the SEND NATIVE form for the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026). Use for ANY native-send intent: "send eth", "send 0.1 ETH", "transfer 1 BNB to vitalik.eth", "g\u1EEDi ETH". Call EVEN IF the user did not name an amount or recipient \u2014 the form prompts for them. Do NOT use for ERC-20 tokens \u2014 use open-send-token-form instead.`;parameters=[{name:"chain",type:"string",description:'Hex chain id: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Defaults to connected chain.',required:!1},{name:"native_symbol",type:"string",description:'The native coin the user named to send, VERBATIM (e.g. "ETH", "BNB", "MATIC", "AVAX"). ALWAYS set this when the user names the coin ("send bnb" \u2192 native_symbol="BNB"); leave blank only when they say just "send" with no coin. A coin that belongs to one specific chain (BNB\u2192BSC, MATIC/POL\u2192Polygon, AVAX\u2192Avalanche, XDAI\u2192Gnosis, HYPE\u2192HyperEVM, MNT\u2192Mantle, MON\u2192Monad) selects that chain, so the tool can detect when the wallet is connected elsewhere.',required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Amount of native coin to send. Accepted forms: a plain amount ("0.1"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become the literal "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself (and for the native coin always leaves enough to cover the network fee). Omit when unknown.',required:!1}];async buildParameters(e,t){let n={},r=this.requireChain(e,t)??void 0,o=t?.walletAddress??void 0,s=await this.readTokenBalanceAndPrice("native",r,o);if(!s||s.balance==null||s.balance<=0){let u=s?.symbol||"the native coin";return{error:"no_native_balance",_instructions:`The user wants to send ${u} but their wallet holds 0 ${u} on this chain. Tell them, in their language, that they do not have any ${u} to send and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}let i=s.symbol||(typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0);if(i&&(n.native_symbol=i),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?n.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(n.to_address=e.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:r,walletAddress:o,gasKind:"send"});if(l&&"error"in l)return l;l&&(n.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(r,o,"send");c!==void 0&&(n.spendable=c);let d=this.formatSpendableUsd(c,s.usdPrice);return d!==void 0&&(n.spendableUsd=d),n}};var Sn=class extends Pe{name="open-send-token-form";actionType="send_token";component="SendTokenForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}description=`Open the SEND TOKEN (ERC-20) form. Use for ANY ERC-20 send/transfer intent: "send token", "send USDC", "transfer 50 DAI to 0x\u2026", "g\u1EEDi 10 USDT". Call this tool EVEN IF the user did not name a token, amount, or recipient \u2014 the tool handles missing token via a picker, the form prompts for the rest. Do NOT use for the chain's native coin (ETH/BNB/MATIC/AVAX) \u2014 use open-send-native-form instead.`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol \u2014 the tool will look up the address.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). ALWAYS set this whenever the user names a token to send ("send usdc" \u2192 token_symbol="USDC"); only leave it blank when the user names NO token at all ("send token"), so the tool can show a wallet picker. Used to auto-resolve the contract address and to display the symbol in the form. (Pass either this or contract_address.)',required:!1},{name:"decimals",type:"number",description:"Token decimals (e.g. 6 for USDC, 18 for most ERC-20s). Optional.",required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown.",required:!1},{name:"amount",type:"string",description:'Amount of the token to send. Accepted forms: a plain amount ("100"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself. Omit when unknown.',required:!1},{name:"send_prompt_template",type:"string",description:`A short imperative "send" command IN THE USER'S LANGUAGE, used as the label/command when the user has not yet picked which token to send (token-picker buttons). Write it in the SAME language the user is using right now. Use these exact placeholders (do not translate the braces): "{symbol}" for the token, "{amount}" for the amount, "{to}" for the recipient address, "{chain}" for the chain name. Put the localized verb, the "to" preposition, and the "on <chain>" preposition directly in the text. English example: "send {amount} {symbol} to {to} on {chain}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to} tr\xEAn {chain}". Japanese example: "{chain} \u3067 {to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to}/{chain} too \u2014 the tool removes any whose value is unknown.`,required:!0}];async buildParameters(e,t){let n=this.normaliseAddress(e.contract_address)!=null,r=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!n&&!r&&this.moralis){let u=this.requireChain(e,t)??void 0,p=t?.walletAddress;if(p){let m=await this.moralis.getWalletTokenBalances({address:p,chain:u,excludeSpam:!1,excludeUnverifiedContracts:!1}),h=(m.success?m.data?.result??[]:[]).filter(T=>T.symbol&&(T.native_token||T.token_address)).sort((T,S)=>(S.usd_value??0)-(T.usd_value??0)).slice(0,8);if(h.length===0)return{error:"no_token_holdings",_instructions:"The wallet does not hold any sendable tokens on this chain. Tell the user they have nothing to send and suggest they top up first. Do NOT open the form."};let g=e.to_address!=null?this.normaliseAddress(e.to_address):null,y=this.normaliseAmount(e.amount),b=typeof e.send_prompt_template=="string"?e.send_prompt_template:"",w=u?P(u):null;return{actionButtons:h.map(T=>{let S=T.symbol,A=T.balance_formatted?this.cleanAmountString(T.balance_formatted):"",_=T.name?T.name:"",R=T.usd_value?`($${T.usd_value.toFixed(2)})`:"";return{label:`${_}:${A} ${S} ${R}`.trim(),prompt:this.buildSendPrompt(b,S,y,g,w)}}),_instructions:"Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n g\u1EEDi token.' / 'You want to send a token.'), then ask them to choose which token from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n g\u1EEDi.' / 'Please choose the token you want to send.'). Do NOT list the tokens in text \u2014 the options already show them. Do NOT mention tool names, UI, or forms."}}}let o=this.requireChain(e,t)??void 0,s=t?.walletAddress??void 0,i=await this.findOwnedTokenForSend(e,o,s);if(i&&"error"in i)return i;let l=i?.token,c={};l?.address&&(c.contract_address=l.address),l?.symbol&&(c.token_symbol=l.symbol),l?.decimals!==void 0&&(c.decimals=String(l.decimals)),i?.spendable!==void 0&&(c.spendable=i.spendable);let d=this.formatSpendableUsd(i?.spendable,i?.usdPrice);if(d!==void 0&&(c.spendableUsd=d),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?c.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(c.to_address=e.to_address.trim())}if(l?.address){let u=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:l.address,symbol:l.symbol,chain:o,walletAddress:s});if(u&&"error"in u)return u;u&&(c.amount=u.amount)}else{let u=this.normaliseAmount(e.amount);u&&(c.amount=u)}return c}async findOwnedTokenForSend(e,t,n){let r=this.normaliseAddress(e.contract_address),o=typeof e.token_symbol=="string"&&e.token_symbol.trim()?e.token_symbol.trim():void 0,s=r??o;if(!this.moralis||!n||!s){let m=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:n});return"error"in m?{error:"token_not_found",symbol:m.key,_instructions:`Could not resolve token "${m.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:m.token}}let i=s.toLowerCase(),l=r!=null,c=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),u=(c.success?c.data?.result??[]:[]).find(m=>l?(m.token_address??"").toLowerCase()===i:(m.symbol??"").toLowerCase()===i);if(u&&u.balance&&!/^0*$/.test(u.balance.trim())){let m=this.parseDecimals(e.decimals);return{token:{address:u.token_address,symbol:u.symbol??o,name:u.name,decimals:m??(typeof u.decimals=="number"?u.decimals:void 0)},spendable:u.balance_formatted?this.cleanAmountString(u.balance_formatted):void 0,usdPrice:typeof u.usd_price=="number"&&u.usd_price>0?u.usd_price:void 0}}let p=u?.symbol??o??s;return{error:"no_balance",symbol:p,_instructions:`The user does not hold any ${p} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${p} to send, and suggest they top up or pick another token. Do NOT open a form. Do NOT mention tool names, UI, or forms.`}}buildSendPrompt(e,t,n,r,o){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,n??"");return i=this.fillOrDropPhrase(i,"{to}",r),i=this.fillOrDropPhrase(i,"{chain}",o),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,n){if(n)return e.split(t).join(n);let r=t.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${r}`,"g"),"").replace(new RegExp(`${r}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(r,"g"),"")}};var Pn=class extends Pe{name="open-approve-token-form";actionType="approve_token";component="ApproveTokenForm";userInputFields=[{key:"spender_address",label:"the spender address to approve"}];constructor(e){super(e)}description='Open the APPROVE TOKEN form so the user can grant a spender allowance on an ERC-20 token. Use when the user says "approve USDC for Uniswap", "c\u1EA5p quy\u1EC1n 100 USDT cho 0x\u2026", "revoke approval". Pass `contract_address` when you have it; otherwise pass `token_symbol` (e.g. "USDC") and the tool auto-resolves the contract. Always pass `spender_address` (the contract being approved). Pass `amount` for a specific allowance; omit for unlimited (max uint256). For approving 0 to revoke, pass amount="0".';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). Required when contract_address is not given. Used to auto-resolve the contract.',required:!1},{name:"decimals",type:"number",description:"Token decimals.",required:!1},{name:"spender_address",type:"string",description:"EVM address of the spender contract being approved (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Human-readable allowance amount. Omit for UNLIMITED (max uint256). Pass "0" to revoke.',required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:n,walletAddress:t?.walletAddress??void 0});if("error"in r)return{error:"token_not_found",symbol:r.key,_instructions:`Could not resolve token "${r.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let o=r.token,s=this.normaliseAddress(e.spender_address),i={};if(o?.address&&(i.contract_address=o.address),s&&(i.spender_address=s),o?.symbol&&(i.token_symbol=o.symbol),o?.decimals!==void 0&&(i.decimals=String(o.decimals)),typeof e.amount=="string"&&e.amount.trim()){let l=e.amount.trim(),c=parseFloat(l);Number.isFinite(c)&&c>=0&&(i.amount=l)}else typeof e.amount=="number"&&Number.isFinite(e.amount)&&e.amount>=0&&(i.amount=String(e.amount));return i}};var xn=class extends v{name="open-buy-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new D(e),this.pantograph=new le({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[BuyTokenTool] ${e}`):console.log(`[BuyTokenTool] ${e}`,JSON.stringify(t)))}description='Open the BUY TOKEN flow for ANY buy/purchase intent. Handles both cases: (a) the user NAMED a token \u2014 "buy PEPE", "mua DOGE", "buy 100 USDC with ETH": pass `token_symbol` (the destination); if you also know the pay token, fill `pay_with_symbol` (or `pay_with_address`), else leave pay_with_* blank and the tool returns a wallet picker. (b) the user did NOT name a token \u2014 "buy a trending token", "mua token trending", "buy something pumping", "buy hot tokens", "mua token t\u0103ng m\u1EA1nh": leave `token_symbol` blank and the tool returns buttons of the chain\'s current trending tokens so the user picks one. Amount: `buy_amount` = destination to RECEIVE; `pay_with_amount` = payment to SPEND. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"token_symbol",type:"string",description:'Symbol of the token the user wants to BUY (e.g. "PEPE"). Leave EMPTY when the user did not name a token (e.g. "buy a trending token") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"contract_address",type:"string",description:`Destination token address (0x\u2026), or "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from token_symbol.`,required:!1},{name:"buy_amount",type:"string",description:`Quantity of the DESTINATION token (the one being bought) the user wants to RECEIVE. Set this when the amount sits next to the token being bought: "buy 5 PEPE", "mua 5 PEPE", "buy 0.02 PCM with USDC" \u2192 buy_amount = the number next to PEPE/PCM. May also be a USD value when the user sizes the buy in dollars ("buy $5 of PEPE" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$" to a token quantity). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with pay_with_amount \u2014 set at most ONE of the two.`,required:!1},{name:"pay_with_symbol",type:"string",description:'Symbol of the payment token (e.g. "USDC", "ETH"). Set ONLY when the user actually named a token to pay with. Leave EMPTY when they did not \u2014 do NOT default to the native coin / ETH; the tool then returns a picker of the tokens the wallet holds.',required:!1},{name:"pay_with_address",type:"string",description:`Address of the payment token (0x\u2026), OR "native" for the chain's native coin. Set ONLY when the user named the payment token. Leave EMPTY when they did not \u2014 do NOT invent an address or default to native.`,required:!1},{name:"pay_with_amount",type:"string",description:'Quantity of the PAYMENT token (the one being spent) the user wants to SPEND. Set this when the amount sits next to the payment token: "buy PEPE with 10 USDC", "mua PEPE b\u1EB1ng 10 USDC", "spend 0.5 ETH on DOGE" \u2192 pay_with_amount = the number next to USDC/ETH. May also be a PERCENT of the pay-token balance ("buy USDC with 50% USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("buy USDC with 5$ USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set pay_with_symbol to the payment token ("ETH" in "buy USDC with max ETH"). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with buy_amount \u2014 set at most ONE of the two.',required:!1},{name:"limit",type:"number",description:"Only used when no token is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the trending-token picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_with_prompt_template",type:"string",description:`A short "buy X with Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the pay-token picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{token}" = token being bought, "{pay}" = payment token, "{buy_amount}" = quantity of the BOUGHT token (place it next to {token}), "{pay_amount}" = quantity of the PAYMENT token (place it next to {pay}). Put the localized verb and the "with" preposition directly in the text. English example: "buy {buy_amount} {token} with {pay_amount} {pay}". Vietnamese example: "mua {buy_amount} {token} b\u1EB1ng {pay_amount} {pay}". Japanese example: "{pay_amount} {pay} \u3067 {buy_amount} {token} \u8CFC\u5165". Always include {token} and {pay}. Include both {buy_amount} and {pay_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount).`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(s.actionButtons=o.actionButtons),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let r=St(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to buy on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to buy on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can buy on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let s=typeof t?.query=="string"?t.query:void 0;return Pt("buy",s)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let n=typeof e.token_symbol=="string"?e.token_symbol.trim():"",r=typeof e.contract_address=="string"?e.contract_address.trim():"",o=this.requireChain(e,t)??void 0,s=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:o,walletAddress:s,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(e,t);let i=await this.resolveSide(e.contract_address,n,o,s,"dest"),l=i.address,c=i.symbol??n,d=i.decimals,u=await this.resolveSide(e.pay_with_address,e.pay_with_symbol,o,s,"pay"),p=u.address,m=u.symbol,f=u.decimals,h=await this.resolveBuyAmountSpec(e.buy_amount,l,o,c),g=p?await this.resolvePayAmountSpec(e.pay_with_amount,p,o,s,m,f??(p==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),y=Fe(e.pay_with_amount),b=!!y&&y.kind!=="token",w=null;if(this.dbg("resolved sides",{dest:{destContract:l,destSymbol:c,destDecimals:d},pay:{payAddr:p,paySymbol:m,payDecimals:f},buyAmount:h,payAmount:g}),!l)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${c||r}" to buy on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!p&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:c,destContract:l,buyAmount:h,payAmount:g});if(!p)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${c}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(h&&!g){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:h,destSymbol:c,paySymbol:m});let k=await this.derivePayAmountFromBuy({chain:o,buyAmount:h,destContract:l,destSymbol:c,payAddr:p,paySymbol:m});if(!k)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${m??"of the payment token"} equals ${h} ${c} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${m??"of the payment token"} they want to spend instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};g=k,w=h,b=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:g,derivedFromBuy:w})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:p,paySymbol:m,payAmount:g});let k=await this.checkPayBalance({args:e,userContext:t,chain:o,destSymbol:c,destContract:l,payAddr:p,paySymbol:m,payAmount:g,buyAmount:h,derivedFromBuy:w,amountSizedToBalance:b});if(k)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:k.error,hasButtons:Array.isArray(k.actionButtons)}),k;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!h&&!g&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let k=await this.buildAmountPicker({userContext:t,chain:o,destSymbol:c,payAddr:p,paySymbol:m,buyWithTemplate:typeof e.buy_with_prompt_template=="string"?e.buy_with_prompt_template:""});if(k)return this.dbg("\u2192 Branch 1.5: amount picker returned"),k;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(g&&(f!==void 0||p==="native")){this.dbg("Branch 1.75: building confirm tx");let k=await this.buildConfirmTx({userContext:t,chain:o,destContract:l,destSymbol:c,destDecimals:d,payAddr:p,paySymbol:m,payDecimals:f,payAmount:g});return k&&"ui"in k?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),k):k&&"quoteError"in k?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:k.quoteError}),{error:"quote_failed",quoteError:k.quoteError,_instructions:`Could not quote buying ${c} with ${m??"the selected token"}. The swap provider reported: "${k.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to buy ${c} with ${m??"the selected token"} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs pay amount"),{error:"needs_pay_amount",_instructions:`Ask the user, in their language, how much ${m??"of the payment token"} they want to spend to buy ${c}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return q(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!n)return null;let r=parseFloat(n[1]);return Number.isFinite(r)&&r>0?n[1]:null}correctAmountSide(e,t){let n=typeof t?.query=="string"?t.query:"",r=typeof e.token_symbol=="string"?e.token_symbol.trim():"",o=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"";if(!n||!r||!o)return;let s=typeof e.buy_amount=="string"?e.buy_amount.trim():"",i=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",l=s.length>0,c=i.length>0;if(l===c)return;let d=l?s:i,u=d.match(/[0-9]*\.?[0-9]+/)?.[0];if(!u)return;let p=this.nearestSymbolSide(n,u,r,o);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:d,buySym:r,paySym:o}),e.pay_with_amount=d,e.buy_amount=""):p==="buy"&&c&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:d,buySym:r,paySym:o}),e.buy_amount=d,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=typeof e.token_symbol=="string"?e.token_symbol.trim():"";if(!r)return;let o=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"",s=typeof e.pay_with_address=="string"?e.pay_with_address.trim():"";if(!o&&!s)return;let i=n.toLowerCase(),l=o.toLowerCase(),c=s.toLowerCase(),d=l==="native"||c==="native",u=[];if(o&&l!=="native"&&u.push(l),c&&c!=="native"&&u.push(c),d){u.push("native");let m=this.requireChain(e,t)??void 0,f=m?oe(m)?.native.symbol:void 0;f&&u.push(f.toLowerCase())}u.some(m=>q(m)?i.includes(m):this.indexOfToken(i,m)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:o,payAddr:s,buySym:r}),e.pay_with_symbol="",e.pay_with_address="")}dropInventedAmounts(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=(n.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),o=s=>{let i=typeof e[s]=="string"?e[s].trim():"";if(!i)return;let l=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(l===void 0)return;let c=parseFloat(l);Number.isFinite(c)&&(r.some(d=>d===c)||(this.dbg(`dropInventedAmounts: clearing invented ${s}`,{val:i}),e[s]=""))};o("buy_amount"),o("pay_with_amount")}nearestSymbolSide(e,t,n,r){let o=e.toLowerCase(),s=o.indexOf(t.toLowerCase()),i=this.indexOfToken(o,n.toLowerCase()),l=this.indexOfToken(o,r.toLowerCase());if(s<0||i<0||l<0)return null;let c=(p,m)=>Math.max(0,p-(s+t.length),s-(p+m)),d=c(i,n.length),u=c(l,r.length);return u===d?null:u<d?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|[^a-z0-9])(${n})(?:[^a-z0-9]|$)`));return r&&r.index!==void 0?r.index+r[0].indexOf(r[1]):-1}requireChain(e,t){let n=typeof e.chain=="string"&&e.chain.trim()?e.chain.trim():null;return n||(typeof t?.chain=="string"&&t.chain.trim()?t.chain.trim():null)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=q(e.trim()),s=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(s);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(s)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let s=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(s.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,d=m=>m.toLowerCase()===B?"native":m,u=l??c??(s||void 0);if(!u)return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,n,r);return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:i,chain:n,key:u,lookup:p}),p?{address:d(p.address),symbol:c??p.symbol,decimals:p.decimals}:l?{address:d(l),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,destContract:r,destSymbol:o,destDecimals:s,payAddr:i,paySymbol:l,payDecimals:c,payAmount:d}=e,u=t?.walletAddress;if(!u||!n||!r)return null;let p=oe(n),m=Number.parseInt(n,16);if(!p||!Number.isFinite(m))return null;let f=i==="native",h=f?p.native.decimals??18:c;if(h===void 0)return null;let g=this.toRawAmount(d,h);if(!g)return null;let y=f?B:i,b=r==="native"?B:r,w;try{w=await(await Me.getServiceByProvider("debridge")).getQuote({srcChainId:m,srcTokenAddress:y,srcTokenAmount:g,dstChainId:m,dstTokenAddress:b,recipientAddress:u,senderAddress:u,slippage:"auto",isCrossChain:!1})}catch(E){return{quoteError:E instanceof Error?E.message:String(E)}}if(!w.success)return this.dbg("buildConfirmTx: quote failed",{error:w.error,errorMessage:w.errorMessage}),{quoteError:this.extractQuoteError(w)};if(!w.tx)return{quoteError:"No route available for this swap."};let k=w.tx;if(!k.to||typeof k.data!="string")return null;let T={chainId:n,to:k.to,data:k.data,value:k.value??"0",from:u},S=this.extractOutRaw(w),A=S&&s!==void 0?this.trimAmount(Number(S)/10**s):void 0,_;f||(_=await this.buildApproveTx({chain:n,walletAddress:u,payAddr:i,payDec:h,rawAmount:g,quote:w}));let C={component:"BuyTokenConfirmTx",props:{chain:{hexId:n,name:p.name},payToken:{address:f?"native":i,symbol:l,decimals:h,amount:d,rawAmount:g},buyToken:{address:r,symbol:o,decimals:s,amount:A,rawAmount:S},estimatedOut:A,estimatedOutRaw:S,provider:w.provider,swapTx:T,approveTx:_}},M=A?` They will receive about ${A} ${o}.`:"";return{ui:C,_instructions:`The purchase of ${o} with ${d} ${l??"the selected token"} is ready for the user to confirm.${M} Briefly tell the user, in their language, the amount they are spending and the estimated amount they will receive, and ask them to review and confirm to complete the purchase. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (buying) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async derivePayAmountFromBuy(e){let{chain:t,buyAmount:n,destContract:r,payAddr:o}=e,[s,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:s,payPrice:i}),!s||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,d=l*s/i;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?B:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),o=r.success?r.data?.usd_price:void 0;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}async resolvePayAmountSpec(e,t,n,r,o,s){let i=Fe(e);if(!i)return null;let l=d=>s===void 0?d:bt(d,s);if(i.kind==="token")return l(yt(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let d=await this.readPayBalance(r,t,n);if(this.dbg("resolvePayAmountSpec: percent",{percent:i.percent,paySymbol:o,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let u=d.decimals??s??18;return i.percent>=100?this.cleanAmountString(d.balanceFormatted):wt(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,n);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:o,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,n,r){let o=Fe(e);if(!o)return null;if(o.kind==="token")return yt(e)??this.toPlainDecimal(o.value);if(o.kind==="percent"||!t)return null;let s=await this.getUsdPrice(t,n);return this.dbg("resolveBuyAmountSpec: usd",{usd:o.usd,destSymbol:r,price:s}),s?this.trimAmount(o.usd/s):null}async buildApproveTx(e){let{chain:t,walletAddress:n,payAddr:r,payDec:o,rawAmount:s,quote:i}=e;try{let c=await(await Me.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:s,tokenDecimals:o,quoteData:i});if(!c.isNeeded)return;let d=c.approvalData??{};if(d.to&&typeof d.data=="string")return{chainId:t,to:d.to,data:d.data,value:d.value??"0",from:n};let u=c.contractAddress;if(!u)return;let p=ht({abi:Io,functionName:"approve",args:[u,BigInt(s)]});return{chainId:t,to:r,data:p,value:"0",from:n}}catch{return}}toRawAmount(e,t){let n=e.trim();if(!/^\d*\.?\d+$/.test(n))return null;let[r,o=""]=n.split("."),s=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(s||"0");return i<=0n?null:i.toString()}catch{return null}}extractQuoteError(e){if(e.errorMessage&&e.errorMessage.trim())return e.errorMessage.trim();let t=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},n=e.raw??{};return t(e.error)??t(n.errorMessage)??t(n.error)??"The swap could not be quoted right now."}extractOutRaw(e){let t=e.raw??{},n=t.tokenOut?.amount??t.tokenOut?.minAmount??t.details?.currencyOut?.amount??t.details?.currencyOut?.minimumAmount??t.estimation?.dstChainTokenOut?.recommendedAmount??t.estimation?.dstChainTokenOut?.amount;return n&&/^\d+$/.test(n)?n:void 0}async buildPayWithPicker(e){let{args:t,userContext:n,destSymbol:r,destContract:o}=e,s=this.requireChain(t,n)??void 0,i=this.moralis,l=n.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:s,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=c.success?c.data?.result??[]:[],u=o?.toLowerCase(),p=r.trim().toLowerCase(),m=d.filter(b=>!b.symbol||p&&b.symbol.toLowerCase()===p?!1:b.native_token?u!=="native":!(!b.token_address||u&&b.token_address.toLowerCase()===u)).sort((b,w)=>(w.usd_value??0)-(b.usd_value??0)).slice(0,8);if(m.length===0)return{error:"no_pay_token_holdings",_instructions:"The wallet has no tokens that can pay for this purchase on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let f=e.buyAmount??this.normaliseAmount(t.buy_amount),h=e.payAmount??this.normaliseAmount(t.pay_with_amount),g=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:m.map(b=>{let w=b.symbol,k=b.name?.trim()||w,T=b.balance_formatted?`${this.cleanAmountString(b.balance_formatted)} `:"",S=typeof b.usd_value=="number"&&b.usd_value>0?` ($${b.usd_value.toFixed(2)})`:"",A=`${k}: ${T}${w}${S}`,_=f?this.buildBuyWithPrompt(g,r,w,f,null):this.buildBuyWithPrompt(g,r,w,null,h);return{label:A,prompt:_}}),_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n mua ${r}.' / 'You want to buy ${r}.'), then ask them to choose which token they want to spend to buy ${r} from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua.' / 'Please choose the token to spend.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async checkPayBalance(e){let{args:t,userContext:n,chain:r,destSymbol:o,destContract:s,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:d}=e,u=n.walletAddress,p=await this.readPayBalance(u,i,r),m=e.paySymbol??p?.symbol??"the selected token";if(!p){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:m});let b=await this.buildPayWithPicker({args:t,userContext:n,destSymbol:o,destContract:s,buyAmount:c,payAmount:l});return"actionButtons"in b?{error:"no_pay_balance",actionButtons:b.actionButtons,_instructions:`The user wanted to spend ${m} to buy ${o}, but their wallet holds no ${m} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${m} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${m} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to pay with (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua ${o} t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to pay with from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:b}if(!l||e.amountSizedToBalance)return null;let f=p.decimals!==void 0?bt(l,p.decimals):l;if(po(f,p.balanceFormatted)<=0)return null;let h=this.cleanAmountString(p.balanceFormatted),g=this.percentSpendButtons({balanceFormatted:p.balanceFormatted,balanceNum:p.balanceNum,decimals:p.decimals,paySymbol:m,destSymbol:o,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:""}),y=d?`Buying ${d} ${o} needs about ${l} ${m}, but they only have ${h} ${m} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them that buying ${d} ${o} would cost about ${l} ${m}, which is more than their balance of ${h} ${m}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${l} ${m} to buy ${o}, but they only have ${h} ${m} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${l} ${m} exceeds their balance of ${h} ${m}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:g,_instructions:y+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readPayBalance(e,t,n){if(!this.moralis)return null;let r=await this.moralis.getWalletTokenBalances({address:e,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[];this.dbg("readPayBalance",{payAddr:t,chain:n,ok:r.success,count:o.length,held:o.map(c=>({sym:c.symbol,addr:c.token_address,bal:c.balance_formatted}))});let s=t.toLowerCase(),i=o.find(c=>s==="native"?c.native_token===!0:c.token_address?.toLowerCase()===s);if(!i?.balance_formatted)return this.dbg("readPayBalance: pay token NOT held \u2192 null",{payAddr:t}),null;let l=Number(i.balance_formatted);if(!Number.isFinite(l)||l<=0)return this.dbg("readPayBalance: zero/invalid balance \u2192 null",{payAddr:t,balance:i.balance_formatted}),null;if(s==="native"&&n){let c=await Tn(n,"swap"),d=vn(l,c,n);if(this.dbg("readPayBalance: native spendable",{balanceNum:l,spendable:d}),d<=0)return this.dbg("readPayBalance: native spendable \u2264 0 \u2192 null",{balanceNum:l}),null;let u=this.trimAmount(d),p=typeof i.decimals=="number"?i.decimals:18;return{balanceFormatted:u,balanceNum:d,symbol:i.symbol,decimals:p}}return this.dbg("readPayBalance: held",{payAddr:t,balance:i.balance_formatted,symbol:i.symbol}),{balanceFormatted:i.balance_formatted,balanceNum:l,symbol:i.symbol,decimals:typeof i.decimals=="number"?i.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,paySymbol:r,destSymbol:o,buyWithTemplate:s}=e,i=n??18;return[25,50,75,100].map(c=>{let d=wt(this.cleanAmountString(t),BigInt(c),100n,i);return{label:`${c}%`,prompt:this.buildBuyWithPrompt(s,o,r,null,d)}})}async buildAmountPicker(e){let{userContext:t,chain:n,destSymbol:r,payAddr:o,buyWithTemplate:s}=e,i=t.walletAddress,l=await this.readPayBalance(i,o,n),c=e.paySymbol??l?.symbol;if(!l||!c)return null;let d=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,paySymbol:c,destSymbol:r,buyWithTemplate:s}),u=this.cleanAmountString(l.balanceFormatted);return{actionButtons:d,_instructions:`The user's spendable balance is ${u} ${c}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${c} balance (e.g., 'B\u1EA1n mu\u1ED1n mua ${r} b\u1EB1ng ${c}, hi\u1EC7n c\xF3 ${u} ${c} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to buy ${r} with ${c}; you have ${u} ${c} available.'), then ask how much they want to spend and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),s=Number(o),[i,l=""]=r.split("."),c=i+l,d;if(s>=0){let u=i.length+s;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-s-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),n?`-${d}`:d}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildBuyPrompt(e,t){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}buildBuyWithPrompt(e,t,n,r,o){return(e&&e.includes("{token}")&&e.includes("{pay}")?e:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,t).replace(/\{pay\}/g,n).replace(/\{buy_amount\}/g,r??"").replace(/\{pay_amount\}/g,o??"").replace(/\s+/g," ").trim()}async buildTrendingPicker(e,t){if(!this.pantograph)return{error:"trending_unavailable",_instructions:"Trending tokens are unavailable in this build (service not configured). Tell the user briefly and ask them to name a token to buy."};let n=this.requireChain(e,t)??void 0,r=typeof e.limit=="number"&&Number.isFinite(e.limit)?Math.floor(e.limit):6,o=Math.max(1,Math.min(10,r)),s=await this.pantograph.getTrendingTokens({chain:n,limit:o}),i=s.success?s.data??[]:[];if(i.length===0)return{error:"no_trending_tokens",_instructions:"No trending tokens are available for this chain right now. Tell the user briefly and suggest they name a token directly."};let l=i.filter(m=>m.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",d=l.map(m=>{let f=m.symbol;return{label:f,prompt:this.buildBuyPrompt(c,f)}}),p=l.map((m,f)=>{let h=m.name?.trim()||m.symbol,g=m.symbol,y=typeof m.usdPrice=="number"&&m.usdPrice>0?`$${this.formatPrice(m.usdPrice)}`:"N/A",b=m.pricePercentChange?.["24h"],w=typeof b=="number"&&Number.isFinite(b)?` (${b>0?"+":b<0?"-":""}${this.formatPercent(Math.abs(b))}%)`:"";return`${f+1}. ${h} (${g}) \u2014 ${y}${w}`}).join(`
188
188
  `)+`
189
189
 
190
- Is there any token you want to buy?`;return{actionButtons:u,_instructions:`The trending tokens are on ${n?P(n):"the connected chain"}. Reply in the user's language using the pattern 'state intent \u2192 ask to choose'. Start with a one-line header that states the user's intent (e.g., 'B\u1EA1n mu\u1ED1n mua token \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to buy a token \u2014 here are the tokens currently trending upwards on <chain name>:'), then output EXACTLY the following list, preserving the line breaks, ordering, prices, and percentages verbatim (translate only the wording, never the numbers). The list already ends with a 'choose' prompt. Do NOT add or remove tokens, and do NOT mention tool names, UI, or forms:
190
+ Is there any token you want to buy?`;return{actionButtons:d,_instructions:`The trending tokens are on ${n?P(n):"the connected chain"}. Reply in the user's language using the pattern 'state intent \u2192 ask to choose'. Start with a one-line header that states the user's intent (e.g., 'B\u1EA1n mu\u1ED1n mua token \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to buy a token \u2014 here are the tokens currently trending upwards on <chain name>:'), then output EXACTLY the following list, preserving the line breaks, ordering, prices, and percentages verbatim (translate only the wording, never the numbers). The list already ends with a 'choose' prompt. Do NOT add or remove tokens, and do NOT mention tool names, UI, or forms:
191
191
 
192
- ${p}`}}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var Cn=class extends v{name="open-swap-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new D(e),this.pantograph=new le({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[SwapTokenTool] ${e}`):console.log(`[SwapTokenTool] ${e}`,JSON.stringify(t)))}description='Open the SWAP TOKEN flow for ANY swap/exchange/convert intent where the user swaps a token they ALREADY HOLD into another token \u2014 "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang ETH", "convert DAI to USDC", "exchange 10 USDC for PEPE". The FROM token is the user\'s own holding (the source). Handles both cases: (a) the user named the destination \u2014 "swap USDC to USDT": pass `from_symbol` (the source, e.g. "USDC") and `to_symbol` (the destination, e.g. "USDT"). (b) the user named only the source \u2014 "swap USDC": pass `from_symbol` and leave `to_symbol` blank; the tool returns buttons of the chain\'s current trending tokens so the user picks what to receive. If the user named NO token at all \u2014 "swap" / "\u0111\u1ED5i token": leave both blank and the tool returns the wallet\'s holdings so the user picks what to swap FROM. Amount: `from_amount` = source to SPEND; `to_amount` = destination to RECEIVE. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"from_symbol",type:"string",description:`Symbol of the SOURCE token the user wants to swap FROM \u2014 a token they already hold (e.g. "USDC"). Leave EMPTY only when the user named no token at all (e.g. "swap") \u2014 the tool then returns the wallet's holdings to pick the source from.`,required:!1},{name:"from_address",type:"string",description:`Source token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from from_symbol.`,required:!1},{name:"from_amount",type:"string",description:'Quantity of the SOURCE token (the one being swapped FROM / spent) the user wants to SPEND. Set this when the amount sits next to the source token: "swap 10 USDC to USDT", "\u0111\u1ED5i 10 USDC sang ETH" \u2192 from_amount = the number next to USDC. May also be a PERCENT of the source balance ("swap 50% USDC to USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("swap $5 USDC to USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set from_symbol to the source token ("ETH" in "swap max ETH to USDC"). Mutually exclusive with to_amount \u2014 set at most ONE of the two.',required:!1},{name:"to_symbol",type:"string",description:'Symbol of the DESTINATION token the user wants to RECEIVE (e.g. "USDT"). Leave EMPTY when the user did not name a destination (e.g. "swap USDC") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"to_address",type:"string",description:`Destination token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from to_symbol.`,required:!1},{name:"to_amount",type:"string",description:`Quantity of the DESTINATION token (the one being received) the user wants to RECEIVE. Set this when the amount sits next to the destination token: "swap USDC to 5 USDT" \u2192 to_amount = the number next to USDT. May also be a USD value ("swap USDC to $5 USDT" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$"). Mutually exclusive with from_amount \u2014 set at most ONE.`,required:!1},{name:"limit",type:"number",description:"Only used when no destination is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"swap_from_prompt_template",type:"string",description:`A short "swap {token}" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the source picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the source symbol; put the localized verb directly in the text. English example: "swap {token}". Vietnamese example: "\u0111\u1ED5i {token}". Japanese example: "{token} \u3092\u30B9\u30EF\u30C3\u30D7". Always include {token}.`,required:!0},{name:"swap_to_prompt_template",type:"string",description:`A short "swap X to Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the destination (trending) picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{from}" = source token, "{to}" = destination token, "{from_amount}" = quantity of the SOURCE token (place it next to {from}), "{to_amount}" = quantity of the DESTINATION token (place it next to {to}). Put the localized verb and the "to" preposition directly in the text. English example: "swap {from_amount} {from} to {to_amount} {to}". Vietnamese example: "\u0111\u1ED5i {from_amount} {from} sang {to_amount} {to}". Japanese example: "{from_amount} {from} \u3092 {to_amount} {to} \u306B\u30B9\u30EF\u30C3\u30D7". Always include {from} and {to}. Include both {from_amount} and {to_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount).`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(s.actionButtons=o.actionButtons),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before swapping. Do NOT proceed."};let r=St(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to swap on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to swap on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can swap on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let s=typeof t?.query=="string"?t.query:void 0;return Pt("swap",s)}return this.buildResult(e,t)}async buildResult(e,t){let n=typeof e.from_symbol=="string"?e.from_symbol.trim():"",r=typeof e.from_address=="string"?e.from_address.trim():"",o=typeof e.to_symbol=="string"?e.to_symbol.trim():"",s=this.requireChain(e,t)??void 0,i=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:s,walletAddress:i,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: source picker (no source token named)"),await this.buildSourcePicker(e,t);let l=await this.resolveSide(e.from_address,n,s,i,"from"),c=l.address,u=l.symbol??n,d=l.decimals,p=await this.resolveSide(e.to_address,o,s,i,"to"),m=p.address,f=p.symbol??o,h=p.decimals,g=await this.resolveToAmountSpec(e.to_amount,m,s,f),y=c?await this.resolveFromAmountSpec(e.from_amount,c,s,i,u,d??(c==="native"?18:void 0)):this.normaliseAmount(e.from_amount),b=Fe(e.from_amount),w=!!b&&b.kind!=="token",k=null;if(this.dbg("resolved sides",{from:{fromContract:c,fromSym:u,fromDecimals:d},to:{toContract:m,toSym:f,toDecimals:h},fromAmount:y,toAmount:g}),!c)return this.dbg("\u2192 source token not resolved"),{error:"from_token_not_found",_instructions:`Could not find the token "${u||r}" to swap from on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!m&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: destination picker (dest token missing)"),await this.buildToTrendingPicker({args:e,userContext:t,fromSym:u,fromContract:c,fromAmount:y,toAmount:g});if(!m)return{error:"to_token_missing",_instructions:`Ask the user, in their language, which token they want to receive when swapping ${u}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(g&&!y){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:g,fromSym:u,toSym:f});let T=await this.deriveFromAmountFromTo({chain:s,toAmount:g,toContract:m,toSym:f,fromContract:c,fromSym:u});if(!T)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs from amount"),{error:"needs_from_amount",_instructions:`Could not work out how much ${u??"of the source token"} equals ${g} ${f} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${u??"of the source token"} they want to swap instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};y=T,k=g,w=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:y,derivedFromTo:k})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:c,fromSym:u,fromAmount:y});let T=await this.checkFromBalance({args:e,userContext:t,chain:s,fromContract:c,fromSym:u,fromAmount:y,toAmount:g,derivedFromTo:k,amountSizedToBalance:w});if(T)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:T.error,hasButtons:Array.isArray(T.actionButtons)}),T;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!y&&!g&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let T=await this.buildAmountPicker({userContext:t,chain:s,fromContract:c,fromSym:u,toSym:f,swapToTemplate:typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:""});if(T)return this.dbg("\u2192 Branch 1.5: amount picker returned"),T;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(y&&(d!==void 0||c==="native")){this.dbg("Branch 1.75: building confirm tx");let T=await this.buildConfirmTx({userContext:t,chain:s,toContract:m,toSym:f,toDecimals:h,fromContract:c,fromSym:u,fromDecimals:d,fromAmount:y});return T&&"ui"in T?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),T):T&&"quoteError"in T?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:T.quoteError}),{error:"quote_failed",quoteError:T.quoteError,_instructions:`Could not quote swapping ${u??"the source token"} to ${f}. The swap provider reported: "${T.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to swap ${u??"the source token"} to ${f} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs from amount"),{error:"needs_from_amount",_instructions:`Ask the user, in their language, how much ${u??"of the source token"} they want to swap to ${f}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return q(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}requireChain(e,t){let n=typeof e.chain=="string"&&e.chain.trim()?e.chain.trim():null;return n||(typeof t?.chain=="string"&&t.chain.trim()?t.chain.trim():null)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=q(e.trim()),s=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(s);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(s)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let s=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(s.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,u=m=>m.toLowerCase()===B?"native":m,d=l??c??(s||void 0);if(!d)return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(d,n,r);return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:i,chain:n,key:d,lookup:p}),p?{address:u(p.address),symbol:c??p.symbol,decimals:p.decimals}:l?{address:u(l),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,toContract:r,toSym:o,toDecimals:s,fromContract:i,fromSym:l,fromDecimals:c,fromAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let p=oe(n),m=Number.parseInt(n,16);if(!p||!Number.isFinite(m))return null;let f=i==="native",h=f?p.native.decimals??18:c;if(h===void 0)return null;let g=this.toRawAmount(u,h);if(!g)return null;let y=f?B:i,b=r==="native"?B:r,w;try{w=await(await Me.getServiceByProvider("debridge")).getQuote({srcChainId:m,srcTokenAddress:y,srcTokenAmount:g,dstChainId:m,dstTokenAddress:b,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(E){return{quoteError:E instanceof Error?E.message:String(E)}}if(!w.success)return this.dbg("buildConfirmTx: quote failed",{error:w.error,errorMessage:w.errorMessage}),{quoteError:this.extractQuoteError(w)};if(!w.tx)return{quoteError:"No route available for this swap."};let k=w.tx;if(!k.to||typeof k.data!="string")return null;let T={chainId:n,to:k.to,data:k.data,value:k.value??"0",from:d},S=this.extractOutRaw(w),A=S&&s!==void 0?this.trimAmount(Number(S)/10**s):void 0,_;f||(_=await this.buildApproveTx({chain:n,walletAddress:d,fromAddr:i,fromDec:h,rawAmount:g,quote:w}));let C={component:"SwapTokenConfirmTx",props:{chain:{hexId:n,name:p.name},fromToken:{address:f?"native":i,symbol:l,decimals:h,amount:u,rawAmount:g},toToken:{address:r,symbol:o,decimals:s,amount:A,rawAmount:S},estimatedOut:A,estimatedOutRaw:S,provider:w.provider,swapTx:T,approveTx:_}},M=A?` They will receive about ${A} ${o}.`:"";return{ui:C,_instructions:`The swap of ${u} ${l??"the source token"} to ${o} is ready for the user to confirm.${M} Briefly tell the user, in their language, the amount they are swapping and the estimated amount they will receive, and ask them to review and confirm to complete the swap. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (swapping) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async deriveFromAmountFromTo(e){let{chain:t,toAmount:n,toContract:r,fromContract:o}=e,[s,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:s,fromPrice:i}),!s||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,u=l*s/i;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?B:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),o=r.success?r.data?.usd_price:void 0;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}async resolveFromAmountSpec(e,t,n,r,o,s){let i=Fe(e);if(!i)return null;let l=u=>s===void 0?u:bt(u,s);if(i.kind==="token")return l(yt(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let u=await this.readFromBalance(r,t,n);if(this.dbg("resolveFromAmountSpec: percent",{percent:i.percent,fromSym:o,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??s??18;return i.percent>=100?this.cleanAmountString(u.balanceFormatted):wt(u.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,d)}let c=await this.getUsdPrice(t,n);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:o,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,n,r){let o=Fe(e);if(!o)return null;if(o.kind==="token")return yt(e)??this.toPlainDecimal(o.value);if(o.kind==="percent"||!t)return null;let s=await this.getUsdPrice(t,n);return this.dbg("resolveToAmountSpec: usd",{usd:o.usd,toSym:r,price:s}),s?this.trimAmount(o.usd/s):null}async buildApproveTx(e){let{chain:t,walletAddress:n,fromAddr:r,fromDec:o,rawAmount:s,quote:i}=e;try{let c=await(await Me.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:s,tokenDecimals:o,quoteData:i});if(!c.isNeeded)return;let u=c.approvalData??{};if(u.to&&typeof u.data=="string")return{chainId:t,to:u.to,data:u.data,value:u.value??"0",from:n};let d=c.contractAddress;if(!d)return;let p=ht({abi:Io,functionName:"approve",args:[d,BigInt(s)]});return{chainId:t,to:r,data:p,value:"0",from:n}}catch{return}}toRawAmount(e,t){let n=e.trim();if(!/^\d*\.?\d+$/.test(n))return null;let[r,o=""]=n.split("."),s=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(s||"0");return i<=0n?null:i.toString()}catch{return null}}extractQuoteError(e){if(e.errorMessage&&e.errorMessage.trim())return e.errorMessage.trim();let t=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},n=e.raw??{};return t(e.error)??t(n.errorMessage)??t(n.error)??"The swap could not be quoted right now."}extractOutRaw(e){let t=e.raw??{},n=t.tokenOut?.amount??t.tokenOut?.minAmount??t.details?.currencyOut?.amount??t.details?.currencyOut?.minimumAmount??t.estimation?.dstChainTokenOut?.recommendedAmount??t.estimation?.dstChainTokenOut?.amount;return n&&/^\d+$/.test(n)?n:void 0}async buildSourcePicker(e,t){if(!this.moralis||!t?.walletAddress)return{error:"source_unavailable",_instructions:"Cannot list the wallet holdings in this build. Tell the user briefly and ask them to name the token they want to swap from."};let n=this.requireChain(e,t)??void 0,r=t.walletAddress,o=await this.moralis.getWalletTokenBalances({address:r,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),i=(o.success?o.data?.result??[]:[]).filter(u=>u.symbol?u.native_token?!0:!!u.token_address:!1).sort((u,d)=>(d.usd_value??0)-(u.usd_value??0)).slice(0,8);if(i.length===0)return{error:"no_swap_holdings",_instructions:"The wallet holds no tokens to swap on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let l=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"";return{actionButtons:i.map(u=>{let d=u.symbol,p=u.name?.trim()||d,m=u.balance_formatted?`${this.cleanAmountString(u.balance_formatted)} `:"",f=typeof u.usd_value=="number"&&u.usd_value>0?` ($${u.usd_value.toFixed(2)})`:"";return{label:`${p}: ${m}${d}${f}`,prompt:this.buildSwapFromPrompt(l,d)}}),_instructions:"Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n swap token.' / 'You want to swap a token.'), then ask them to choose which token to swap from in the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap.' / 'Please choose the token to swap from.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms."}}async buildToTrendingPicker(e){let{args:t,userContext:n,fromSym:r,fromContract:o}=e,s=this.requireChain(t,n)??void 0,i=this.pantograph,l=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,l)),u=await i.getTrendingTokens({chain:s,limit:c+2}),d=u.success?u.data??[]:[],p=o?.toLowerCase(),m=r.toLowerCase(),f=d.filter(T=>!(!T.symbol||p&&p!=="native"&&T.tokenAddress&&T.tokenAddress.toLowerCase()===p||T.symbol.toLowerCase()===m)).slice(0,c);if(f.length===0)return{error:"no_trending_tokens",_instructions:`No trending tokens are available to swap ${r} into on this chain right now. Tell the user briefly and suggest they name the token they want to receive directly. Do NOT mention tool names, UI, or forms.`};let h=e.fromAmount??this.normaliseAmount(t.from_amount),g=e.toAmount??this.normaliseAmount(t.to_amount),y=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",b=f.map(T=>{let S=T.symbol,A=h?this.buildSwapToPrompt(y,r,S,h,null):this.buildSwapToPrompt(y,r,S,null,g);return{label:S,prompt:A}}),k=f.map((T,S)=>{let A=T.name?.trim()||T.symbol,_=T.symbol,R=typeof T.usdPrice=="number"&&T.usdPrice>0?`$${this.formatPrice(T.usdPrice)}`:"N/A",C=T.pricePercentChange?.["24h"],M=typeof C=="number"&&Number.isFinite(C)?` (${C>0?"+":C<0?"-":""}${this.formatPercent(Math.abs(C))}%)`:"";return`${S+1}. ${A} (${_}) \u2014 ${R}${M}`}).join(`
192
+ ${p}`}}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var Cn=class extends v{name="open-swap-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new D(e),this.pantograph=new le({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[SwapTokenTool] ${e}`):console.log(`[SwapTokenTool] ${e}`,JSON.stringify(t)))}description='Open the SWAP TOKEN flow for ANY swap/exchange/convert intent where the user swaps a token they ALREADY HOLD into another token \u2014 "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang ETH", "convert DAI to USDC", "exchange 10 USDC for PEPE". The FROM token is the user\'s own holding (the source). Handles both cases: (a) the user named the destination \u2014 "swap USDC to USDT": pass `from_symbol` (the source, e.g. "USDC") and `to_symbol` (the destination, e.g. "USDT"). (b) the user named only the source \u2014 "swap USDC": pass `from_symbol` and leave `to_symbol` blank; the tool returns buttons of the chain\'s current trending tokens so the user picks what to receive. If the user named NO token at all \u2014 "swap" / "\u0111\u1ED5i token": leave both blank and the tool returns the wallet\'s holdings so the user picks what to swap FROM. Amount: `from_amount` = source to SPEND; `to_amount` = destination to RECEIVE. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"from_symbol",type:"string",description:`Symbol of the SOURCE token the user wants to swap FROM \u2014 a token they already hold (e.g. "USDC"). Leave EMPTY only when the user named no token at all (e.g. "swap") \u2014 the tool then returns the wallet's holdings to pick the source from.`,required:!1},{name:"from_address",type:"string",description:`Source token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from from_symbol.`,required:!1},{name:"from_amount",type:"string",description:'Quantity of the SOURCE token (the one being swapped FROM / spent) the user wants to SPEND. Set this when the amount sits next to the source token: "swap 10 USDC to USDT", "\u0111\u1ED5i 10 USDC sang ETH" \u2192 from_amount = the number next to USDC. May also be a PERCENT of the source balance ("swap 50% USDC to USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("swap $5 USDC to USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set from_symbol to the source token ("ETH" in "swap max ETH to USDC"). Mutually exclusive with to_amount \u2014 set at most ONE of the two.',required:!1},{name:"to_symbol",type:"string",description:'Symbol of the DESTINATION token the user wants to RECEIVE (e.g. "USDT"). Leave EMPTY when the user did not name a destination (e.g. "swap USDC") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"to_address",type:"string",description:`Destination token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from to_symbol.`,required:!1},{name:"to_amount",type:"string",description:`Quantity of the DESTINATION token (the one being received) the user wants to RECEIVE. Set this when the amount sits next to the destination token: "swap USDC to 5 USDT" \u2192 to_amount = the number next to USDT. May also be a USD value ("swap USDC to $5 USDT" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$"). Mutually exclusive with from_amount \u2014 set at most ONE.`,required:!1},{name:"limit",type:"number",description:"Only used when no destination is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"swap_from_prompt_template",type:"string",description:`A short "swap {token}" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the source picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the source symbol; put the localized verb directly in the text. English example: "swap {token}". Vietnamese example: "\u0111\u1ED5i {token}". Japanese example: "{token} \u3092\u30B9\u30EF\u30C3\u30D7". Always include {token}.`,required:!0},{name:"swap_to_prompt_template",type:"string",description:`A short "swap X to Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the destination (trending) picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{from}" = source token, "{to}" = destination token, "{from_amount}" = quantity of the SOURCE token (place it next to {from}), "{to_amount}" = quantity of the DESTINATION token (place it next to {to}). Put the localized verb and the "to" preposition directly in the text. English example: "swap {from_amount} {from} to {to_amount} {to}". Vietnamese example: "\u0111\u1ED5i {from_amount} {from} sang {to_amount} {to}". Japanese example: "{from_amount} {from} \u3092 {to_amount} {to} \u306B\u30B9\u30EF\u30C3\u30D7". Always include {from} and {to}. Include both {from_amount} and {to_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount).`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(s.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(s.actionButtons=o.actionButtons),s}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before swapping. Do NOT proceed."};let r=St(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to swap on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to swap on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can swap on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let s=typeof t?.query=="string"?t.query:void 0;return Pt("swap",s)}return this.buildResult(e,t)}async buildResult(e,t){let n=typeof e.from_symbol=="string"?e.from_symbol.trim():"",r=typeof e.from_address=="string"?e.from_address.trim():"",o=typeof e.to_symbol=="string"?e.to_symbol.trim():"",s=this.requireChain(e,t)??void 0,i=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:s,walletAddress:i,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: source picker (no source token named)"),await this.buildSourcePicker(e,t);let l=await this.resolveSide(e.from_address,n,s,i,"from"),c=l.address,d=l.symbol??n,u=l.decimals,p=await this.resolveSide(e.to_address,o,s,i,"to"),m=p.address,f=p.symbol??o,h=p.decimals,g=await this.resolveToAmountSpec(e.to_amount,m,s,f),y=c?await this.resolveFromAmountSpec(e.from_amount,c,s,i,d,u??(c==="native"?18:void 0)):this.normaliseAmount(e.from_amount),b=Fe(e.from_amount),w=!!b&&b.kind!=="token",k=null;if(this.dbg("resolved sides",{from:{fromContract:c,fromSym:d,fromDecimals:u},to:{toContract:m,toSym:f,toDecimals:h},fromAmount:y,toAmount:g}),!c)return this.dbg("\u2192 source token not resolved"),{error:"from_token_not_found",_instructions:`Could not find the token "${d||r}" to swap from on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!m&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: destination picker (dest token missing)"),await this.buildToTrendingPicker({args:e,userContext:t,fromSym:d,fromContract:c,fromAmount:y,toAmount:g});if(!m)return{error:"to_token_missing",_instructions:`Ask the user, in their language, which token they want to receive when swapping ${d}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(g&&!y){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:g,fromSym:d,toSym:f});let T=await this.deriveFromAmountFromTo({chain:s,toAmount:g,toContract:m,toSym:f,fromContract:c,fromSym:d});if(!T)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs from amount"),{error:"needs_from_amount",_instructions:`Could not work out how much ${d??"of the source token"} equals ${g} ${f} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${d??"of the source token"} they want to swap instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};y=T,k=g,w=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:y,derivedFromTo:k})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:c,fromSym:d,fromAmount:y});let T=await this.checkFromBalance({args:e,userContext:t,chain:s,fromContract:c,fromSym:d,fromAmount:y,toAmount:g,derivedFromTo:k,amountSizedToBalance:w});if(T)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:T.error,hasButtons:Array.isArray(T.actionButtons)}),T;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!y&&!g&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let T=await this.buildAmountPicker({userContext:t,chain:s,fromContract:c,fromSym:d,toSym:f,swapToTemplate:typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:""});if(T)return this.dbg("\u2192 Branch 1.5: amount picker returned"),T;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(y&&(u!==void 0||c==="native")){this.dbg("Branch 1.75: building confirm tx");let T=await this.buildConfirmTx({userContext:t,chain:s,toContract:m,toSym:f,toDecimals:h,fromContract:c,fromSym:d,fromDecimals:u,fromAmount:y});return T&&"ui"in T?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),T):T&&"quoteError"in T?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:T.quoteError}),{error:"quote_failed",quoteError:T.quoteError,_instructions:`Could not quote swapping ${d??"the source token"} to ${f}. The swap provider reported: "${T.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to swap ${d??"the source token"} to ${f} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs from amount"),{error:"needs_from_amount",_instructions:`Ask the user, in their language, how much ${d??"of the source token"} they want to swap to ${f}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return q(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}requireChain(e,t){let n=typeof e.chain=="string"&&e.chain.trim()?e.chain.trim():null;return n||(typeof t?.chain=="string"&&t.chain.trim()?t.chain.trim():null)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=q(e.trim()),s=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(s);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(s)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let s=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(s.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,d=m=>m.toLowerCase()===B?"native":m,u=l??c??(s||void 0);if(!u)return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,n,r);return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:i,chain:n,key:u,lookup:p}),p?{address:d(p.address),symbol:c??p.symbol,decimals:p.decimals}:l?{address:d(l),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,toContract:r,toSym:o,toDecimals:s,fromContract:i,fromSym:l,fromDecimals:c,fromAmount:d}=e,u=t?.walletAddress;if(!u||!n||!r)return null;let p=oe(n),m=Number.parseInt(n,16);if(!p||!Number.isFinite(m))return null;let f=i==="native",h=f?p.native.decimals??18:c;if(h===void 0)return null;let g=this.toRawAmount(d,h);if(!g)return null;let y=f?B:i,b=r==="native"?B:r,w;try{w=await(await Me.getServiceByProvider("debridge")).getQuote({srcChainId:m,srcTokenAddress:y,srcTokenAmount:g,dstChainId:m,dstTokenAddress:b,recipientAddress:u,senderAddress:u,slippage:"auto",isCrossChain:!1})}catch(E){return{quoteError:E instanceof Error?E.message:String(E)}}if(!w.success)return this.dbg("buildConfirmTx: quote failed",{error:w.error,errorMessage:w.errorMessage}),{quoteError:this.extractQuoteError(w)};if(!w.tx)return{quoteError:"No route available for this swap."};let k=w.tx;if(!k.to||typeof k.data!="string")return null;let T={chainId:n,to:k.to,data:k.data,value:k.value??"0",from:u},S=this.extractOutRaw(w),A=S&&s!==void 0?this.trimAmount(Number(S)/10**s):void 0,_;f||(_=await this.buildApproveTx({chain:n,walletAddress:u,fromAddr:i,fromDec:h,rawAmount:g,quote:w}));let C={component:"SwapTokenConfirmTx",props:{chain:{hexId:n,name:p.name},fromToken:{address:f?"native":i,symbol:l,decimals:h,amount:d,rawAmount:g},toToken:{address:r,symbol:o,decimals:s,amount:A,rawAmount:S},estimatedOut:A,estimatedOutRaw:S,provider:w.provider,swapTx:T,approveTx:_}},M=A?` They will receive about ${A} ${o}.`:"";return{ui:C,_instructions:`The swap of ${d} ${l??"the source token"} to ${o} is ready for the user to confirm.${M} Briefly tell the user, in their language, the amount they are swapping and the estimated amount they will receive, and ask them to review and confirm to complete the swap. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (swapping) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async deriveFromAmountFromTo(e){let{chain:t,toAmount:n,toContract:r,fromContract:o}=e,[s,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:s,fromPrice:i}),!s||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,d=l*s/i;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?B:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),o=r.success?r.data?.usd_price:void 0;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}async resolveFromAmountSpec(e,t,n,r,o,s){let i=Fe(e);if(!i)return null;let l=d=>s===void 0?d:bt(d,s);if(i.kind==="token")return l(yt(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let d=await this.readFromBalance(r,t,n);if(this.dbg("resolveFromAmountSpec: percent",{percent:i.percent,fromSym:o,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let u=d.decimals??s??18;return i.percent>=100?this.cleanAmountString(d.balanceFormatted):wt(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,n);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:o,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,n,r){let o=Fe(e);if(!o)return null;if(o.kind==="token")return yt(e)??this.toPlainDecimal(o.value);if(o.kind==="percent"||!t)return null;let s=await this.getUsdPrice(t,n);return this.dbg("resolveToAmountSpec: usd",{usd:o.usd,toSym:r,price:s}),s?this.trimAmount(o.usd/s):null}async buildApproveTx(e){let{chain:t,walletAddress:n,fromAddr:r,fromDec:o,rawAmount:s,quote:i}=e;try{let c=await(await Me.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:s,tokenDecimals:o,quoteData:i});if(!c.isNeeded)return;let d=c.approvalData??{};if(d.to&&typeof d.data=="string")return{chainId:t,to:d.to,data:d.data,value:d.value??"0",from:n};let u=c.contractAddress;if(!u)return;let p=ht({abi:Io,functionName:"approve",args:[u,BigInt(s)]});return{chainId:t,to:r,data:p,value:"0",from:n}}catch{return}}toRawAmount(e,t){let n=e.trim();if(!/^\d*\.?\d+$/.test(n))return null;let[r,o=""]=n.split("."),s=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(s||"0");return i<=0n?null:i.toString()}catch{return null}}extractQuoteError(e){if(e.errorMessage&&e.errorMessage.trim())return e.errorMessage.trim();let t=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},n=e.raw??{};return t(e.error)??t(n.errorMessage)??t(n.error)??"The swap could not be quoted right now."}extractOutRaw(e){let t=e.raw??{},n=t.tokenOut?.amount??t.tokenOut?.minAmount??t.details?.currencyOut?.amount??t.details?.currencyOut?.minimumAmount??t.estimation?.dstChainTokenOut?.recommendedAmount??t.estimation?.dstChainTokenOut?.amount;return n&&/^\d+$/.test(n)?n:void 0}async buildSourcePicker(e,t){if(!this.moralis||!t?.walletAddress)return{error:"source_unavailable",_instructions:"Cannot list the wallet holdings in this build. Tell the user briefly and ask them to name the token they want to swap from."};let n=this.requireChain(e,t)??void 0,r=t.walletAddress,o=await this.moralis.getWalletTokenBalances({address:r,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),i=(o.success?o.data?.result??[]:[]).filter(d=>d.symbol?d.native_token?!0:!!d.token_address:!1).sort((d,u)=>(u.usd_value??0)-(d.usd_value??0)).slice(0,8);if(i.length===0)return{error:"no_swap_holdings",_instructions:"The wallet holds no tokens to swap on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let l=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"";return{actionButtons:i.map(d=>{let u=d.symbol,p=d.name?.trim()||u,m=d.balance_formatted?`${this.cleanAmountString(d.balance_formatted)} `:"",f=typeof d.usd_value=="number"&&d.usd_value>0?` ($${d.usd_value.toFixed(2)})`:"";return{label:`${p}: ${m}${u}${f}`,prompt:this.buildSwapFromPrompt(l,u)}}),_instructions:"Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n swap token.' / 'You want to swap a token.'), then ask them to choose which token to swap from in the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap.' / 'Please choose the token to swap from.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms."}}async buildToTrendingPicker(e){let{args:t,userContext:n,fromSym:r,fromContract:o}=e,s=this.requireChain(t,n)??void 0,i=this.pantograph,l=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,l)),d=await i.getTrendingTokens({chain:s,limit:c+2}),u=d.success?d.data??[]:[],p=o?.toLowerCase(),m=r.toLowerCase(),f=u.filter(T=>!(!T.symbol||p&&p!=="native"&&T.tokenAddress&&T.tokenAddress.toLowerCase()===p||T.symbol.toLowerCase()===m)).slice(0,c);if(f.length===0)return{error:"no_trending_tokens",_instructions:`No trending tokens are available to swap ${r} into on this chain right now. Tell the user briefly and suggest they name the token they want to receive directly. Do NOT mention tool names, UI, or forms.`};let h=e.fromAmount??this.normaliseAmount(t.from_amount),g=e.toAmount??this.normaliseAmount(t.to_amount),y=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",b=f.map(T=>{let S=T.symbol,A=h?this.buildSwapToPrompt(y,r,S,h,null):this.buildSwapToPrompt(y,r,S,null,g);return{label:S,prompt:A}}),k=f.map((T,S)=>{let A=T.name?.trim()||T.symbol,_=T.symbol,R=typeof T.usdPrice=="number"&&T.usdPrice>0?`$${this.formatPrice(T.usdPrice)}`:"N/A",C=T.pricePercentChange?.["24h"],M=typeof C=="number"&&Number.isFinite(C)?` (${C>0?"+":C<0?"-":""}${this.formatPercent(Math.abs(C))}%)`:"";return`${S+1}. ${A} (${_}) \u2014 ${R}${M}`}).join(`
193
193
  `)+`
194
194
 
195
195
  Which token do you want to receive?`;return{actionButtons:b,_instructions:`The user wants to swap ${r} into another token. The trending tokens are on ${s?P(s):"the connected chain"}. Reply in the user's language using the pattern 'state intent \u2192 ask to choose'. Start with a one-line header that states the user's intent (e.g., 'B\u1EA1n mu\u1ED1n swap ${r} sang token kh\xE1c \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to swap ${r} \u2014 here are the tokens currently trending on <chain name>:'), then output EXACTLY the following list, preserving the line breaks, ordering, prices, and percentages verbatim (translate only the wording, never the numbers). The list already ends with a 'choose' prompt. Do NOT add or remove tokens, and do NOT mention tool names, UI, or forms:
196
196
 
197
- ${k}`}}async checkFromBalance(e){let{args:t,userContext:n,chain:r,fromContract:o,fromAmount:s,derivedFromTo:i}=e,l=n.walletAddress,c=await this.readFromBalance(l,o,r),u=e.fromSym??c?.symbol??"the selected token";if(!c){this.dbg("checkFromBalance: NOT held \u2192 source picker fallback",{fromSym:u});let h=await this.buildSourcePicker(t,n);return"actionButtons"in h?{error:"no_from_balance",actionButtons:h.actionButtons,_instructions:`The user wanted to swap ${u}, but their wallet holds no ${u} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${u} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${u} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to swap from (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to swap from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:h}if(!s||e.amountSizedToBalance)return null;let d=c.decimals!==void 0?bt(s,c.decimals):s;if(po(d,c.balanceFormatted)<=0)return null;let p=this.cleanAmountString(c.balanceFormatted),m=this.percentSpendButtons({balanceFormatted:c.balanceFormatted,balanceNum:c.balanceNum,decimals:c.decimals,fromSym:u,toSym:typeof t.to_symbol=="string"?t.to_symbol.trim():c.symbol??"the destination token",swapToTemplate:typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:""}),f=i?`Receiving ${i} of the destination token needs about ${s} ${u}, but they only have ${p} ${u} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them this would cost about ${s} ${u}, which is more than their balance of ${p} ${u}, then ask them to choose a smaller amount \u2014 `:`The user wants to swap ${s} ${u}, but they only have ${p} ${u} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${s} ${u} exceeds their balance of ${p} ${u}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_from_balance",actionButtons:m,_instructions:f+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readFromBalance(e,t,n){if(!this.moralis)return null;let r=await this.moralis.getWalletTokenBalances({address:e,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[];this.dbg("readFromBalance",{fromAddr:t,chain:n,ok:r.success,count:o.length});let s=t.toLowerCase(),i=o.find(c=>s==="native"?c.native_token===!0:c.token_address?.toLowerCase()===s);if(!i?.balance_formatted)return this.dbg("readFromBalance: source token NOT held \u2192 null",{fromAddr:t}),null;let l=Number(i.balance_formatted);if(!Number.isFinite(l)||l<=0)return this.dbg("readFromBalance: zero/invalid balance \u2192 null",{fromAddr:t,balance:i.balance_formatted}),null;if(s==="native"&&n){let c=await Tn(n,"swap"),u=vn(l,c,n);if(this.dbg("readFromBalance: native spendable",{balanceNum:l,spendable:u}),u<=0)return this.dbg("readFromBalance: native spendable \u2264 0 \u2192 null",{balanceNum:l}),null;let d=this.trimAmount(u),p=typeof i.decimals=="number"?i.decimals:18;return{balanceFormatted:d,balanceNum:u,symbol:i.symbol,decimals:p}}return this.dbg("readFromBalance: held",{fromAddr:t,balance:i.balance_formatted,symbol:i.symbol}),{balanceFormatted:i.balance_formatted,balanceNum:l,symbol:i.symbol,decimals:typeof i.decimals=="number"?i.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,fromSym:r,toSym:o,swapToTemplate:s}=e,i=n??18;return[25,50,75,100].map(c=>{let u=wt(this.cleanAmountString(t),BigInt(c),100n,i);return{label:`${c}%`,prompt:this.buildSwapToPrompt(s,r,o,u,null)}})}async buildAmountPicker(e){let{userContext:t,chain:n,fromContract:r,toSym:o,swapToTemplate:s}=e,i=t.walletAddress,l=await this.readFromBalance(i,r,n),c=e.fromSym??l?.symbol;if(!l||!c)return null;let u=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,fromSym:c,toSym:o,swapToTemplate:s}),d=this.cleanAmountString(l.balanceFormatted);return{actionButtons:u,_instructions:`The user's spendable balance is ${d} ${c}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${c} balance (e.g., 'B\u1EA1n mu\u1ED1n swap ${c} sang ${o}, hi\u1EC7n c\xF3 ${d} ${c} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to swap ${c} to ${o}; you have ${d} ${c} available.'), then ask how much they want to swap and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),s=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(s>=0){let d=i.length+s;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-s-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildSwapFromPrompt(e,t){return(e&&e.includes("{token}")?e:"swap {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}buildSwapToPrompt(e,t,n,r,o){return(e&&e.includes("{from}")&&e.includes("{to}")?e:"swap {from_amount} {from} to {to_amount} {to}").replace(/\{from\}/g,t).replace(/\{to\}/g,n).replace(/\{from_amount\}/g,r??"").replace(/\{to_amount\}/g,o??"").replace(/\s+/g," ").trim()}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var _n=class extends Pe{name="open-send-nft-form";actionType="send_nft";component="SendNftForm";userInputFields=[{key:"to_address",label:"the recipient address"}];description=`Open the SEND NFT form. Use for ANY NFT send/transfer intent: "send NFT", "transfer my Bored Ape", "send token id 1234 to 0x\u2026", "g\u1EEDi NFT". Call this tool EVEN IF the user did not name a contract, token id, NFT name, or recipient \u2014 the tool resolves missing identifiers from the wallet's NFT holdings and emits picker buttons when more than one match exists. Do NOT use this for ERC-20s (use open-send-token-form) or the native coin (open-send-native-form).`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) \u2014 identifies WHICH NFT collection to send from. Only set this when the user explicitly named the collection/contract (e.g. "contract 0x\u2026", "collection 0x\u2026", "from 0x\u2026"). NEVER put the recipient address here. Omit when unknown.',required:!1},{name:"token_id",type:"string",description:'NFT token id as a decimal string (e.g. "1234"). Omit when unknown.',required:!1},{name:"nft_name",type:"string",description:'Free-form NFT or collection name as the user said it (e.g. "Bored Ape"). Used to look up the NFT in the wallet when no contract_address / token_id is provided. Omit when unknown.',required:!1},{name:"token_standard",type:"string",description:'NFT contract type ("ERC721" or "ERC1155"). Optional; the tool re-derives it from the wallet row.',required:!1},{name:"to_address",type:"string",description:'RECIPIENT EVM address (0x\u2026) \u2014 the wallet that will RECEIVE the NFT. Only set this when the user explicitly named a destination (e.g. "send to 0x\u2026", "to 0x\u2026", "g\u1EEDi \u0111\u1EBFn 0x\u2026", "cho 0x\u2026"). NEVER put the NFT collection / contract address here. Omit when unknown.',required:!1},{name:"amount",type:"string",description:"Number of editions to send. Only meaningful for ERC-1155; for ERC-721 the tool forces 1. Pass as a positive integer string. Omit when unknown \u2014 defaults to 1.",required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=t?.walletAddress,o=this.normaliseAddress(e.contract_address),s=this.normaliseTokenId(e.token_id),i=this.normaliseString(e.nft_name),l=this.normaliseAddress(e.to_address),c=this.normaliseString(e.token_standard),u=this.normaliseAmountInt(e.amount);if(!o&&!s&&!i)return{error:"nft_not_specified",_instructions:"The user wants to send an NFT but did not say which one. Ask them, in their language, to provide the NFT collection contract address, the token id, and the recipient address so the transfer can be prepared. Keep it to one short sentence. Do NOT open the form. Do NOT mention tool names, UI, or forms."};if(!this.moralis||!r)return this.paramsFromInputs({contract:o,tokenId:s,toAddress:l,standardArg:c,nftName:i,amountInt:u});let d=await this.moralis.getWalletNFTs({address:r,chain:n,limit:100,excludeSpam:!1}),p=d.success?d.data?.result??[]:[],m=this.matchNfts(p,{contract:o,tokenId:s,nftName:i});if(m.length===0){let f=i??(o&&s?`#${s}`:o??`#${s??""}`),h=P(n);return{error:"nft_not_owned",_instructions:`The user asked to send "${f}" but the wallet does not hold a matching NFT on ${h}. Tell them, in their language, that they do not own that NFT on ${h} and ask them to pick another one (by name, contract, or token id). Refer to the chain by this name \u2014 never as a hex id. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}return m.length===1?this.paramsFromNft(m[0],{toAddress:l,amountInt:u}):this.paramsFromInputs({contract:o,tokenId:s,toAddress:l,standardArg:c,nftName:i,amountInt:u})}normaliseString(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}normaliseTokenId(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?String(Math.trunc(e)):this.normaliseString(e)}normaliseAmountInt(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.trunc(e);if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}}nftDisplayName(e){return(e.normalized_metadata?.name||e.name||`#${e.token_id}`).toString()}matchNfts(e,t){let n=t.contract?t.contract.toLowerCase():void 0,r=t.nftName?t.nftName.toLowerCase():void 0;return e.filter(o=>{if(n&&o.token_address.toLowerCase()!==n||t.tokenId&&o.token_id!==t.tokenId)return!1;if(r&&!n&&!t.tokenId){let s=(o.normalized_metadata?.name??"").toLowerCase(),i=(o.name??"").toLowerCase();if(!s.includes(r)&&!i.includes(r))return!1}return!0})}paramsFromInputs(e){let t={};return e.contract&&(t.contract_address=e.contract),e.tokenId&&(t.token_id=e.tokenId),e.toAddress&&(t.to_address=e.toAddress),e.standardArg&&(t.token_standard=e.standardArg.toUpperCase()),e.nftName&&(t.nft_name=e.nftName),e.amountInt&&(t.amount=String(e.amountInt)),t}paramsFromNft(e,t){let n=(e.contract_type||"").toUpperCase(),r=e.amount&&e.amount.trim()?e.amount.trim():"1",o=n==="ERC1155"?String(Math.min(t.amountInt??1,parseInt(r,10)||1)):"1",s={contract_address:e.token_address,token_id:e.token_id,token_standard:n||"ERC721",amount:o,maxAmount:r,nft_name:this.nftDisplayName(e)};t.toAddress&&(s.to_address=t.toAddress);let i=e.normalized_metadata?.image||e.media?.original_media_url||"";return i&&(s.nft_image=i),s}};var zn=class{name;description;category;parameters=[];message;constructor(e,t){this.name=e.name,this.description=e.description,this.category=e.category,this.message=t}async execute(){return{toolName:this.name,callId:`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,success:!0,data:{message:this.message,_instructions:`Reply with a SINGLE short sentence in the USER'S language that conveys the message below \u2014 translate it naturally rather than leaving it in its original language. Reproduce any URL in it byte-for-byte, and NEVER invent one that is not there. Output ONLY that sentence: no preamble, no second copy, no extra detail. Do NOT ask the user for any details (token, amount, recipient, \u2026) and do NOT mention tool names, forms, or UI. The message to convey:
197
+ ${k}`}}async checkFromBalance(e){let{args:t,userContext:n,chain:r,fromContract:o,fromAmount:s,derivedFromTo:i}=e,l=n.walletAddress,c=await this.readFromBalance(l,o,r),d=e.fromSym??c?.symbol??"the selected token";if(!c){this.dbg("checkFromBalance: NOT held \u2192 source picker fallback",{fromSym:d});let h=await this.buildSourcePicker(t,n);return"actionButtons"in h?{error:"no_from_balance",actionButtons:h.actionButtons,_instructions:`The user wanted to swap ${d}, but their wallet holds no ${d} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${d} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${d} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to swap from (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to swap from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:h}if(!s||e.amountSizedToBalance)return null;let u=c.decimals!==void 0?bt(s,c.decimals):s;if(po(u,c.balanceFormatted)<=0)return null;let p=this.cleanAmountString(c.balanceFormatted),m=this.percentSpendButtons({balanceFormatted:c.balanceFormatted,balanceNum:c.balanceNum,decimals:c.decimals,fromSym:d,toSym:typeof t.to_symbol=="string"?t.to_symbol.trim():c.symbol??"the destination token",swapToTemplate:typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:""}),f=i?`Receiving ${i} of the destination token needs about ${s} ${d}, but they only have ${p} ${d} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them this would cost about ${s} ${d}, which is more than their balance of ${p} ${d}, then ask them to choose a smaller amount \u2014 `:`The user wants to swap ${s} ${d}, but they only have ${p} ${d} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${s} ${d} exceeds their balance of ${p} ${d}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_from_balance",actionButtons:m,_instructions:f+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readFromBalance(e,t,n){if(!this.moralis)return null;let r=await this.moralis.getWalletTokenBalances({address:e,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[];this.dbg("readFromBalance",{fromAddr:t,chain:n,ok:r.success,count:o.length});let s=t.toLowerCase(),i=o.find(c=>s==="native"?c.native_token===!0:c.token_address?.toLowerCase()===s);if(!i?.balance_formatted)return this.dbg("readFromBalance: source token NOT held \u2192 null",{fromAddr:t}),null;let l=Number(i.balance_formatted);if(!Number.isFinite(l)||l<=0)return this.dbg("readFromBalance: zero/invalid balance \u2192 null",{fromAddr:t,balance:i.balance_formatted}),null;if(s==="native"&&n){let c=await Tn(n,"swap"),d=vn(l,c,n);if(this.dbg("readFromBalance: native spendable",{balanceNum:l,spendable:d}),d<=0)return this.dbg("readFromBalance: native spendable \u2264 0 \u2192 null",{balanceNum:l}),null;let u=this.trimAmount(d),p=typeof i.decimals=="number"?i.decimals:18;return{balanceFormatted:u,balanceNum:d,symbol:i.symbol,decimals:p}}return this.dbg("readFromBalance: held",{fromAddr:t,balance:i.balance_formatted,symbol:i.symbol}),{balanceFormatted:i.balance_formatted,balanceNum:l,symbol:i.symbol,decimals:typeof i.decimals=="number"?i.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,fromSym:r,toSym:o,swapToTemplate:s}=e,i=n??18;return[25,50,75,100].map(c=>{let d=wt(this.cleanAmountString(t),BigInt(c),100n,i);return{label:`${c}%`,prompt:this.buildSwapToPrompt(s,r,o,d,null)}})}async buildAmountPicker(e){let{userContext:t,chain:n,fromContract:r,toSym:o,swapToTemplate:s}=e,i=t.walletAddress,l=await this.readFromBalance(i,r,n),c=e.fromSym??l?.symbol;if(!l||!c)return null;let d=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,fromSym:c,toSym:o,swapToTemplate:s}),u=this.cleanAmountString(l.balanceFormatted);return{actionButtons:d,_instructions:`The user's spendable balance is ${u} ${c}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${c} balance (e.g., 'B\u1EA1n mu\u1ED1n swap ${c} sang ${o}, hi\u1EC7n c\xF3 ${u} ${c} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to swap ${c} to ${o}; you have ${u} ${c} available.'), then ask how much they want to swap and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),s=Number(o),[i,l=""]=r.split("."),c=i+l,d;if(s>=0){let u=i.length+s;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-s-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),n?`-${d}`:d}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildSwapFromPrompt(e,t){return(e&&e.includes("{token}")?e:"swap {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}buildSwapToPrompt(e,t,n,r,o){return(e&&e.includes("{from}")&&e.includes("{to}")?e:"swap {from_amount} {from} to {to_amount} {to}").replace(/\{from\}/g,t).replace(/\{to\}/g,n).replace(/\{from_amount\}/g,r??"").replace(/\{to_amount\}/g,o??"").replace(/\s+/g," ").trim()}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var _n=class extends Pe{name="open-send-nft-form";actionType="send_nft";component="SendNftForm";userInputFields=[{key:"to_address",label:"the recipient address"}];description=`Open the SEND NFT form. Use for ANY NFT send/transfer intent: "send NFT", "transfer my Bored Ape", "send token id 1234 to 0x\u2026", "g\u1EEDi NFT". Call this tool EVEN IF the user did not name a contract, token id, NFT name, or recipient \u2014 the tool resolves missing identifiers from the wallet's NFT holdings and emits picker buttons when more than one match exists. Do NOT use this for ERC-20s (use open-send-token-form) or the native coin (open-send-native-form).`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) \u2014 identifies WHICH NFT collection to send from. Only set this when the user explicitly named the collection/contract (e.g. "contract 0x\u2026", "collection 0x\u2026", "from 0x\u2026"). NEVER put the recipient address here. Omit when unknown.',required:!1},{name:"token_id",type:"string",description:'NFT token id as a decimal string (e.g. "1234"). Omit when unknown.',required:!1},{name:"nft_name",type:"string",description:'Free-form NFT or collection name as the user said it (e.g. "Bored Ape"). Used to look up the NFT in the wallet when no contract_address / token_id is provided. Omit when unknown.',required:!1},{name:"token_standard",type:"string",description:'NFT contract type ("ERC721" or "ERC1155"). Optional; the tool re-derives it from the wallet row.',required:!1},{name:"to_address",type:"string",description:'RECIPIENT EVM address (0x\u2026) \u2014 the wallet that will RECEIVE the NFT. Only set this when the user explicitly named a destination (e.g. "send to 0x\u2026", "to 0x\u2026", "g\u1EEDi \u0111\u1EBFn 0x\u2026", "cho 0x\u2026"). NEVER put the NFT collection / contract address here. Omit when unknown.',required:!1},{name:"amount",type:"string",description:"Number of editions to send. Only meaningful for ERC-1155; for ERC-721 the tool forces 1. Pass as a positive integer string. Omit when unknown \u2014 defaults to 1.",required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=t?.walletAddress,o=this.normaliseAddress(e.contract_address),s=this.normaliseTokenId(e.token_id),i=this.normaliseString(e.nft_name),l=this.normaliseAddress(e.to_address),c=this.normaliseString(e.token_standard),d=this.normaliseAmountInt(e.amount);if(!o&&!s&&!i)return{error:"nft_not_specified",_instructions:"The user wants to send an NFT but did not say which one. Ask them, in their language, to provide the NFT collection contract address, the token id, and the recipient address so the transfer can be prepared. Keep it to one short sentence. Do NOT open the form. Do NOT mention tool names, UI, or forms."};if(!this.moralis||!r)return this.paramsFromInputs({contract:o,tokenId:s,toAddress:l,standardArg:c,nftName:i,amountInt:d});let u=await this.moralis.getWalletNFTs({address:r,chain:n,limit:100,excludeSpam:!1}),p=u.success?u.data?.result??[]:[],m=this.matchNfts(p,{contract:o,tokenId:s,nftName:i});if(m.length===0){let f=i??(o&&s?`#${s}`:o??`#${s??""}`),h=P(n);return{error:"nft_not_owned",_instructions:`The user asked to send "${f}" but the wallet does not hold a matching NFT on ${h}. Tell them, in their language, that they do not own that NFT on ${h} and ask them to pick another one (by name, contract, or token id). Refer to the chain by this name \u2014 never as a hex id. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}return m.length===1?this.paramsFromNft(m[0],{toAddress:l,amountInt:d}):this.paramsFromInputs({contract:o,tokenId:s,toAddress:l,standardArg:c,nftName:i,amountInt:d})}normaliseString(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}normaliseTokenId(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?String(Math.trunc(e)):this.normaliseString(e)}normaliseAmountInt(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.trunc(e);if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}}nftDisplayName(e){return(e.normalized_metadata?.name||e.name||`#${e.token_id}`).toString()}matchNfts(e,t){let n=t.contract?t.contract.toLowerCase():void 0,r=t.nftName?t.nftName.toLowerCase():void 0;return e.filter(o=>{if(n&&o.token_address.toLowerCase()!==n||t.tokenId&&o.token_id!==t.tokenId)return!1;if(r&&!n&&!t.tokenId){let s=(o.normalized_metadata?.name??"").toLowerCase(),i=(o.name??"").toLowerCase();if(!s.includes(r)&&!i.includes(r))return!1}return!0})}paramsFromInputs(e){let t={};return e.contract&&(t.contract_address=e.contract),e.tokenId&&(t.token_id=e.tokenId),e.toAddress&&(t.to_address=e.toAddress),e.standardArg&&(t.token_standard=e.standardArg.toUpperCase()),e.nftName&&(t.nft_name=e.nftName),e.amountInt&&(t.amount=String(e.amountInt)),t}paramsFromNft(e,t){let n=(e.contract_type||"").toUpperCase(),r=e.amount&&e.amount.trim()?e.amount.trim():"1",o=n==="ERC1155"?String(Math.min(t.amountInt??1,parseInt(r,10)||1)):"1",s={contract_address:e.token_address,token_id:e.token_id,token_standard:n||"ERC721",amount:o,maxAmount:r,nft_name:this.nftDisplayName(e)};t.toAddress&&(s.to_address=t.toAddress);let i=e.normalized_metadata?.image||e.media?.original_media_url||"";return i&&(s.nft_image=i),s}};var zn=class{name;description;category;parameters=[];message;constructor(e,t){this.name=e.name,this.description=e.description,this.category=e.category,this.message=t}async execute(){return{toolName:this.name,callId:`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,success:!0,data:{message:this.message,_instructions:`Reply with a SINGLE short sentence in the USER'S language that conveys the message below \u2014 translate it naturally rather than leaving it in its original language. Reproduce any URL in it byte-for-byte, and NEVER invent one that is not there. Output ONLY that sentence: no preamble, no second copy, no extra detail. Do NOT ask the user for any details (token, amount, recipient, \u2026) and do NOT mention tool names, forms, or UI. The message to convey:
198
198
 
199
199
  `+this.message},duration:0}}};function Lo(a,e,t){let n=t?.[e.name];a.register(n?new zn(e,n):e)}var En=class{messages=[];fullMessages=[];summary=null;maxMessages;constructor(e=50){this.maxMessages=e}add(e){this.messages.push(e),this.fullMessages.push(e)}addMany(e){this.messages.push(...e),this.fullMessages.push(...e)}addUIOnly(e){this.fullMessages.push(e)}rollbackLastWorkingMessage(){this.messages.pop()}getAll(){return[...this.messages]}getAllFull(){return[...this.fullMessages]}getRecent(e){return this.messages.slice(-e)}getConversation(){let e=[];return this.summary&&e.push({role:"system",content:`[Previous conversation summary]: ${this.summary}`,timestamp:0}),e.push(...this.messages),e}get length(){return this.messages.length}needsSummary(){return this.messages.filter(t=>t.role==="user").length>this.maxMessages}getSummary(){return this.summary}compact(e,t=10){this.summary=e,this.messages=this.messages.slice(-t)}compactWith(e,t){this.summary=e,this.messages=[...t]}clear(){this.messages=[],this.fullMessages=[],this.summary=null}serialise(){return{messages:[...this.messages],summary:this.summary,fullMessages:[...this.fullMessages]}}restore(e){Array.isArray(e)?(this.messages=[...e],this.fullMessages=[...e],this.summary=null):(this.messages=[...e.messages],this.summary=e.summary??null,this.fullMessages=e.fullMessages?[...e.fullMessages]:[...e.messages])}};var Rn=class{llm;constructor(e){this.llm=e}async summarize(e){let t=e.filter(s=>s.role==="user"||s.role==="assistant");if(t.length===0)return"";let n=t.map(s=>`${s.role==="user"?"User":"Assistant"}: ${s.content}`).join(`
200
200
  `),r=[{role:"system",content:"You are a conversation summarizer. Produce a concise summary of the conversation below. Keep key facts, decisions, and context that would be needed to continue the conversation. Reply with only the summary, no extra commentary. Respond in the same language as the conversation.",timestamp:0},{role:"user",content:`Summarise this conversation:
@@ -217,9 +217,9 @@ FAQ ENTRIES:
217
217
  `,Nn=class{entries=[];llm=null;constructor(e){e&&(this.entries=e)}setLLM(e){this.llm=e}setEntries(e){this.entries=e}addEntries(e){this.entries.push(...e)}getEntries(){return this.entries.slice()}get size(){return this.entries.length}async search(e,t=3){return this.entries.length===0?[]:this.llm?this.llmSearch(e,t):this.tokenSearch(e,t,.25)}async llmSearch(e,t){let n=this.entries.map((o,s)=>`[${s}] ${o.question}`).join(`
218
218
  `),r=[{role:"user",content:Pc+n+`
219
219
 
220
- USER QUERY: ${e}`,timestamp:0}];try{let i=(await this.llm.chat(r)).text.trim().match(/\[[\s\S]*\]/);if(!i)return[];let l=JSON.parse(i[0]),c=[];for(let u of l)u.index>=0&&u.index<this.entries.length&&u.score>=.6&&c.push({entry:this.entries[u.index],score:u.score});return c.sort((u,d)=>d.score-u.score),c.slice(0,t)}catch{return this.tokenSearch(e,t,.25)}}tokenSearch(e,t,n){let r=this.tokenize(e);if(r.size===0)return[];let o=[];for(let s of this.entries){let i=this.tokenize(s.question),l=this.jaccardSimilarity(r,i);l>=n&&o.push({entry:s,score:l})}return o.sort((s,i)=>i.score-s.score),o.slice(0,t)}tokenize(e){let t=e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(n=>n.length>1);return new Set(t)}jaccardSimilarity(e,t){if(e.size===0||t.size===0)return 0;let n=0;for(let o of e)t.has(o)&&n++;let r=e.size+t.size-n;return r===0?0:n/r}};var Xn=require("@upstash/vector"),xc="https://perfect-octopus-59684-us1-vector.upstash.io",Cc="ABkFMHBlcmZlY3Qtb2N0b3B1cy01OTY4NC11czFhZG1pbk56WXdOV0k0T0RndFpUaGtOeTAwWWpjMkxXRmtNRFV0WW1WaU9UaGtOMlV5T0ROaQ==",nt=class{index;namespace;minScore;defaultTopK;embedStrategy;fusionAlgorithm;debug;constructor(e={}){let t=e.url??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_URL:void 0)??xc,n=e.token??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_TOKEN:void 0)??Cc;this.index=new Xn.Index({url:t,token:n}),this.namespace=e.namespace,this.minScore=e.minScore??1.3,this.defaultTopK=e.defaultTopK??3,this.embedStrategy=e.embedStrategy??"question",this.fusionAlgorithm=e.fusionAlgorithm==="RRF"?Xn.FusionAlgorithm.RRF:Xn.FusionAlgorithm.DBSF,this.debug=e.debug??!1}async search(e,t,n){let r=n?.applyMinScore??!0,o=t??this.defaultTopK;if(!e.trim())return[];let s=this.namespace?this.index.namespace(this.namespace):this.index,i;try{i=await s.query({data:e,topK:o,includeMetadata:!0,fusionAlgorithm:this.fusionAlgorithm})}catch(c){return this.debug&&console.warn("[UpstashKnowledgeBase] query failed:",c),[]}let l=[];for(let c of i){if(r&&c.score<this.minScore)continue;let u=c.metadata;!u?.question||!u?.answer||l.push({entry:{question:u.question,answer:u.answer},score:c.score})}return this.debug&&console.log(`[UpstashKnowledgeBase] query="${e}" \u2192 ${l.length}/${i.length} hit(s) `+(r?`above ${this.minScore}`:"(minScore bypassed)")+(l[0]?` (top: ${l[0].score.toFixed(3)})`:"")),l}async upsert(e){if(e.length===0)return{count:0};let t=this.namespace?this.index.namespace(this.namespace):this.index,n=await Promise.all(e.map(async r=>({id:r.id??await this.deriveId(r.question),data:this.buildEmbedText(r),metadata:{question:r.question,answer:r.answer,...r.metadata??{}}})));return await t.upsert(n),this.debug&&console.log(`[UpstashKnowledgeBase] upserted ${n.length} entr${n.length===1?"y":"ies"} (strategy=${this.embedStrategy})`),{count:n.length}}buildEmbedText(e){return this.embedStrategy==="question-and-answer"?`${e.question}
220
+ USER QUERY: ${e}`,timestamp:0}];try{let i=(await this.llm.chat(r)).text.trim().match(/\[[\s\S]*\]/);if(!i)return[];let l=JSON.parse(i[0]),c=[];for(let d of l)d.index>=0&&d.index<this.entries.length&&d.score>=.6&&c.push({entry:this.entries[d.index],score:d.score});return c.sort((d,u)=>u.score-d.score),c.slice(0,t)}catch{return this.tokenSearch(e,t,.25)}}tokenSearch(e,t,n){let r=this.tokenize(e);if(r.size===0)return[];let o=[];for(let s of this.entries){let i=this.tokenize(s.question),l=this.jaccardSimilarity(r,i);l>=n&&o.push({entry:s,score:l})}return o.sort((s,i)=>i.score-s.score),o.slice(0,t)}tokenize(e){let t=e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(n=>n.length>1);return new Set(t)}jaccardSimilarity(e,t){if(e.size===0||t.size===0)return 0;let n=0;for(let o of e)t.has(o)&&n++;let r=e.size+t.size-n;return r===0?0:n/r}};var Xn=require("@upstash/vector"),xc="https://perfect-octopus-59684-us1-vector.upstash.io",Cc="ABkFMHBlcmZlY3Qtb2N0b3B1cy01OTY4NC11czFhZG1pbk56WXdOV0k0T0RndFpUaGtOeTAwWWpjMkxXRmtNRFV0WW1WaU9UaGtOMlV5T0ROaQ==",nt=class{index;namespace;minScore;defaultTopK;embedStrategy;fusionAlgorithm;debug;constructor(e={}){let t=e.url??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_URL:void 0)??xc,n=e.token??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_TOKEN:void 0)??Cc;this.index=new Xn.Index({url:t,token:n}),this.namespace=e.namespace,this.minScore=e.minScore??1.3,this.defaultTopK=e.defaultTopK??3,this.embedStrategy=e.embedStrategy??"question",this.fusionAlgorithm=e.fusionAlgorithm==="RRF"?Xn.FusionAlgorithm.RRF:Xn.FusionAlgorithm.DBSF,this.debug=e.debug??!1}async search(e,t,n){let r=n?.applyMinScore??!0,o=t??this.defaultTopK;if(!e.trim())return[];let s=this.namespace?this.index.namespace(this.namespace):this.index,i;try{i=await s.query({data:e,topK:o,includeMetadata:!0,fusionAlgorithm:this.fusionAlgorithm})}catch(c){return this.debug&&console.warn("[UpstashKnowledgeBase] query failed:",c),[]}let l=[];for(let c of i){if(r&&c.score<this.minScore)continue;let d=c.metadata;!d?.question||!d?.answer||l.push({entry:{question:d.question,answer:d.answer},score:c.score})}return this.debug&&console.log(`[UpstashKnowledgeBase] query="${e}" \u2192 ${l.length}/${i.length} hit(s) `+(r?`above ${this.minScore}`:"(minScore bypassed)")+(l[0]?` (top: ${l[0].score.toFixed(3)})`:"")),l}async upsert(e){if(e.length===0)return{count:0};let t=this.namespace?this.index.namespace(this.namespace):this.index,n=await Promise.all(e.map(async r=>({id:r.id??await this.deriveId(r.question),data:this.buildEmbedText(r),metadata:{question:r.question,answer:r.answer,...r.metadata??{}}})));return await t.upsert(n),this.debug&&console.log(`[UpstashKnowledgeBase] upserted ${n.length} entr${n.length===1?"y":"ies"} (strategy=${this.embedStrategy})`),{count:n.length}}buildEmbedText(e){return this.embedStrategy==="question-and-answer"?`${e.question}
221
221
 
222
- ${e.answer}`:e.question}async delete(e){return e.length===0?{deleted:0}:{deleted:(await(this.namespace?this.index.namespace(this.namespace):this.index).delete(e)).deleted}}async reset(){this.namespace?await this.index.reset({namespace:this.namespace}):await this.index.reset()}async size(){let e=await this.index.info();return this.namespace?e.namespaces?.[this.namespace]?.vectorCount??0:e.vectorCount??0}async deriveId(e){let t=new TextEncoder().encode(e.trim().toLowerCase()),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("").slice(0,32)}};function qe(a){return a.filter(e=>e.role!=="tool"&&!(e.role==="assistant"&&e.toolCalls&&e.toolCalls.length>0)&&!e._intermediate)}function sa(a,e){let t=[];for(let n=0;n<a.length;n++){let r=a[n];if(r.role==="assistant"&&r.toolCalls&&r.toolCalls.length>0){if(r.toolCalls.every(l=>e.has(l.toolName))){t.push(r);continue}let s=r.toolCalls.map(l=>l.toolName).join(", ");t.push({role:"assistant",content:`(Previously called external tools: ${s} \u2014 results not visible here.)`,timestamp:r.timestamp});let i=new Set(r.toolCalls.map(l=>l.callId));for(;n+1<a.length;){let l=a[n+1];if(l.role==="tool"&&l.toolCallId&&i.has(l.toolCallId))n++;else break}continue}if(r.role==="tool"){r.toolName&&e.has(r.toolName)&&t.push(r);continue}t.push(r)}return t}function Ge(a,e){if(a.length<=e)return[...a];let t=a.length-e;for(;t>0;){if(a[t].role==="tool"){t--;continue}break}let n=a.slice(t),r=0;for(;r<n.length&&n[r].role==="tool";)r++;return n.slice(r)}function aa(a,e){return Ge(a,e)}function ia(a){for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.role==="assistant"&&!(t.toolCalls&&t.toolCalls.length>0))return t.subagents&&t.subagents.length>0?[...t.subagents]:[]}return[]}function la(a,e=5){let t=a.filter(s=>s.role==="tool").slice(-e);if(t.length===0)return"";let n=[],r=[];for(let s of t){let i;try{i=JSON.parse(s.content)}catch{continue}if(typeof i!="object"||i===null)continue;let l=i,c=l.pagination;c&&typeof c.cursor=="string"&&c.cursor&&r.push({toolName:s.toolName??"tool",cursor:c.cursor});let u=l.transactions??l.result??l.transfers;if(Array.isArray(u))for(let d of u)typeof d.hash=="string"&&d.hash.startsWith("0x")?n.push(d.hash):typeof d.transaction_hash=="string"&&d.transaction_hash.startsWith("0x")&&n.push(d.transaction_hash)}if(n.length===0&&r.length===0)return"";let o=["[Tool data available from previous calls:]"];if(n.length>0&&o.push(`Transaction hashes (use EXACT values): ${n.slice(0,10).join(", ")}`),r.length>0){let s=r[r.length-1];o.push(`Pagination cursor from ${s.toolName}: ${s.cursor}`)}return o.join(`
222
+ ${e.answer}`:e.question}async delete(e){return e.length===0?{deleted:0}:{deleted:(await(this.namespace?this.index.namespace(this.namespace):this.index).delete(e)).deleted}}async reset(){this.namespace?await this.index.reset({namespace:this.namespace}):await this.index.reset()}async size(){let e=await this.index.info();return this.namespace?e.namespaces?.[this.namespace]?.vectorCount??0:e.vectorCount??0}async deriveId(e){let t=new TextEncoder().encode(e.trim().toLowerCase()),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("").slice(0,32)}};function qe(a){return a.filter(e=>e.role!=="tool"&&!(e.role==="assistant"&&e.toolCalls&&e.toolCalls.length>0)&&!e._intermediate)}function sa(a,e){let t=[];for(let n=0;n<a.length;n++){let r=a[n];if(r.role==="assistant"&&r.toolCalls&&r.toolCalls.length>0){if(r.toolCalls.every(l=>e.has(l.toolName))){t.push(r);continue}let s=r.toolCalls.map(l=>l.toolName).join(", ");t.push({role:"assistant",content:`(Previously called external tools: ${s} \u2014 results not visible here.)`,timestamp:r.timestamp});let i=new Set(r.toolCalls.map(l=>l.callId));for(;n+1<a.length;){let l=a[n+1];if(l.role==="tool"&&l.toolCallId&&i.has(l.toolCallId))n++;else break}continue}if(r.role==="tool"){r.toolName&&e.has(r.toolName)&&t.push(r);continue}t.push(r)}return t}function Ge(a,e){if(a.length<=e)return[...a];let t=a.length-e;for(;t>0;){if(a[t].role==="tool"){t--;continue}break}let n=a.slice(t),r=0;for(;r<n.length&&n[r].role==="tool";)r++;return n.slice(r)}function aa(a,e){return Ge(a,e)}function ia(a){for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.role==="assistant"&&!(t.toolCalls&&t.toolCalls.length>0))return t.subagents&&t.subagents.length>0?[...t.subagents]:[]}return[]}function la(a,e=5){let t=a.filter(s=>s.role==="tool").slice(-e);if(t.length===0)return"";let n=[],r=[];for(let s of t){let i;try{i=JSON.parse(s.content)}catch{continue}if(typeof i!="object"||i===null)continue;let l=i,c=l.pagination;c&&typeof c.cursor=="string"&&c.cursor&&r.push({toolName:s.toolName??"tool",cursor:c.cursor});let d=l.transactions??l.result??l.transfers;if(Array.isArray(d))for(let u of d)typeof u.hash=="string"&&u.hash.startsWith("0x")?n.push(u.hash):typeof u.transaction_hash=="string"&&u.transaction_hash.startsWith("0x")&&n.push(u.transaction_hash)}if(n.length===0&&r.length===0)return"";let o=["[Tool data available from previous calls:]"];if(n.length>0&&o.push(`Transaction hashes (use EXACT values): ${n.slice(0,10).join(", ")}`),r.length>0){let s=r[r.length-1];o.push(`Pagination cursor from ${s.toolName}: ${s.cursor}`)}return o.join(`
223
223
  `)}var _c=`You are a ROUTER for a multi-agent crypto/DeFi assistant. You do NOT talk to the user. You read ONE standalone user query (already contextualized upstream) plus a list of available subagents, and you emit ONE JSON object assigning the query to the right subagent(s).
224
224
 
225
225
  OUTPUT CONTRACT \u2014 overrides everything below:
@@ -266,24 +266,24 @@ User context:
266
266
  ${i.join(`
267
267
  `)}`:"",c=o.length>0?`
268
268
 
269
- Previous turn handled by: ${o.join(", ")}. If this query is a natural continuation (same topic), prefer the same subagent(s). Override only if the query clearly belongs to a different domain.`:"",u=qe(t),d=Ge(u,this.historyMessages);this.debug&&(console.log(`
270
- [Router] history window (${d.length} msg${d.length===1?"":"s"}):`),console.log(`[Router] user query: "${e}"`));let p=[{role:"system",content:_c,timestamp:0},...d,{role:"user",content:`Available subagents:
269
+ Previous turn handled by: ${o.join(", ")}. If this query is a natural continuation (same topic), prefer the same subagent(s). Override only if the query clearly belongs to a different domain.`:"",d=qe(t),u=Ge(d,this.historyMessages);this.debug&&(console.log(`
270
+ [Router] history window (${u.length} msg${u.length===1?"":"s"}):`),console.log(`[Router] user query: "${e}"`));let p=[{role:"system",content:_c,timestamp:0},...u,{role:"user",content:`Available subagents:
271
271
  ${s}${l}${c}
272
272
 
273
273
  User query: ${e}`,timestamp:Date.now()}],m=Date.now(),f=null,h="",g=null;for(let k=1;k<=2;k++){let T=await this.llm.chat(p,void 0,{maxOutputTokens:1024});h=T.text;try{f=this.parseJSON(T.text);break}catch(S){g=S,k<2&&(this.debug&&console.log(`[Router] JSON parse failed (attempt ${k}) \u2014 re-prompting for JSON`),p.push({role:"assistant",content:T.text||"",timestamp:Date.now()}),p.push({role:"user",content:'That response was not valid JSON. Do NOT answer the user and do NOT ask any questions. Reply with ONLY the routing JSON object ({"analysis": "...", "assignments": [...]}) and nothing else.',timestamp:Date.now()}))}}let y=Date.now()-m;if(!f)return this.debug&&(console.log(`[Router] JSON parse failed after retry: ${g}`),console.log(`[Router] raw response: ${h.slice(0,300)}`)),{analysis:"Router could not parse response.",assignments:[]};let b=new Set(n.map(k=>k.name)),w=Array.isArray(f.assignments)?f.assignments.filter(k=>!!k&&typeof k.subagent=="string").filter(k=>b.has(k.subagent)).map(k=>({subagent:k.subagent,query:typeof k.query=="string"&&k.query?k.query:e,reasoning:typeof k.reasoning=="string"?k.reasoning:""})):[];if(this.debug){let k=w.length>0?w.map(T=>T.subagent).join(", "):"(none \u2014 direct answer)";if(console.log(`
274
274
  [Router] (${y}ms)`),console.log(` analysis : ${f.analysis??""}`),console.log(` dispatch : ${k}`),w.length>0)for(let T of w)console.log(` \u2192 ${T.subagent}: "${T.query}"`),console.log(` reason: ${T.reasoning}`)}return{analysis:typeof f.analysis=="string"?f.analysis:"",assignments:w}}async dispatch(e,t,n,r){if(e.assignments.length===0)return[];this.debug&&console.log(`
275
- [Router] dispatching ${e.assignments.length} subagent(s) in parallel\u2026`);let o=Date.now(),s=e.assignments.map(async l=>{let c=t.get(l.subagent);if(!c)return this.debug&&console.log(`[Router] WARN: subagent "${l.subagent}" not registered`),{subagentName:l.subagent,steps:[],finalAnswer:`Subagent "${l.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let u=Date.now(),d=await c.run({query:l.query,reasoning:l.reasoning},n,r);if(this.debug){let p=d.toolResults.map(m=>m.toolName).join(", ")||"\u2014";console.log(`[Router] ${l.subagent} done in ${Date.now()-u}ms | tools: ${p}`)}return d}),i=await Promise.all(s);return this.debug&&console.log(`[Router] all subagents done in ${Date.now()-o}ms total`),i}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,"").trim());try{return JSON.parse(t)}catch(n){let r=t.match(/\{[\s\S]*\}/);if(r)return JSON.parse(r[0]);throw n}}};var Ec=`
275
+ [Router] dispatching ${e.assignments.length} subagent(s) in parallel\u2026`);let o=Date.now(),s=e.assignments.map(async l=>{let c=t.get(l.subagent);if(!c)return this.debug&&console.log(`[Router] WARN: subagent "${l.subagent}" not registered`),{subagentName:l.subagent,steps:[],finalAnswer:`Subagent "${l.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let d=Date.now(),u=await c.run({query:l.query,reasoning:l.reasoning},n,r);if(this.debug){let p=u.toolResults.map(m=>m.toolName).join(", ")||"\u2014";console.log(`[Router] ${l.subagent} done in ${Date.now()-d}ms | tools: ${p}`)}return u}),i=await Promise.all(s);return this.debug&&console.log(`[Router] all subagents done in ${Date.now()-o}ms total`),i}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,"").trim());try{return JSON.parse(t)}catch(n){let r=t.match(/\{[\s\S]*\}/);if(r)return JSON.parse(r[0]);throw n}}};var Ec=`
276
276
 
277
277
  LANGUAGE-AGNOSTIC TOOL SELECTION: The user query may arrive in ANY language (English, Vietnamese, Japanese, Korean, Chinese, Thai, Spanish, Arabic, \u2026). Every intent\u2192tool mapping, verb, and example phrase in this prompt is ILLUSTRATIVE ONLY \u2014 written mostly in English for brevity, NOT a list of accepted words. Always pick the tool by the MEANING of the request, treating translated, transliterated, or mixed-language equivalents exactly like the English example (buy / send / swap / approve / show / search / trending / balance, etc. are the same intent in every language). Token symbols, contract addresses, and numbers are language-neutral \u2014 extract them verbatim. Never refuse, misroute, or fall back to plain text merely because the wording is not in English.`,Rc=`
278
278
 
279
279
  OUTPUT FORMAT: Reply in plain text. NEVER draw tables or any column/pipe layout. When presenting multiple items, use a simple bullet or numbered list; otherwise just write short sentences.`,Nc=`
280
280
 
281
281
  DATA INTEGRITY: NEVER invent, guess, round, or estimate on-chain or market values \u2014 prices, balances, amounts, holder counts, APRs, floor prices, contract or wallet addresses, transaction hashes, or token ids. Every such value MUST come verbatim from an actual tool result in this conversation. If the tools did not return it, say so plainly instead of filling it in.`,X=class{name;description;domain;capability;toolNames;systemPrompt;cortexFallbackTool;mustCallTool;llm;registry;maxToolCalls;historyMessages;debug;constructor(e){if(this.name=e.name,this.description=e.description,this.domain=e.domain,this.capability=e.capability,this.toolNames=new Set(e.toolNames),this.systemPrompt=e.systemPrompt+Ec+Rc+Nc,this.cortexFallbackTool=e.cortexFallbackTool,this.mustCallTool=e.mustCallTool??!1,this.cortexFallbackTool&&!this.toolNames.has(this.cortexFallbackTool))throw new Error(`Subagent "${e.name}": cortexFallbackTool "${this.cortexFallbackTool}" must be in toolNames.`);this.llm=e.llm,this.registry=e.registry,this.maxToolCalls=e.options?.maxToolCalls??5,this.historyMessages=e.options?.historyMessages??10,this.debug=e.options?.debug??!1}getCard(){return{name:this.name,description:this.description,domain:this.domain}}ownsTool(e){return this.toolNames.has(e)}getTools(){return this.registry.getDefinitions().filter(e=>this.toolNames.has(e.name))}async run(e,t,n){let r=this.getTools();if(this.debug&&(console.log(`
282
- [${this.name}] query: "${e.query}"`),console.log(` [${this.name}] tools available: ${r.map(T=>T.name).join(", ")}`)),r.length===0)return{subagentName:this.name,steps:[],finalAnswer:`Subagent "${this.name}" has no registered tools available.`,toolResults:[],toolMessages:[]};let o=[],s=[],i=[],l=new Set,c=0,u=!1,d=[];if(n?.walletAddress&&d.push(`Connected wallet: ${n.walletAddress}`),n?.chain){let T=P(n.chain),S=gs(n.chain),A=S?`; native coin: ${S}`:"";d.push(`Current chain: ${T} (${n.chain})${A}`)}let p=d.length>0?`User context:
283
- ${d.join(`
282
+ [${this.name}] query: "${e.query}"`),console.log(` [${this.name}] tools available: ${r.map(T=>T.name).join(", ")}`)),r.length===0)return{subagentName:this.name,steps:[],finalAnswer:`Subagent "${this.name}" has no registered tools available.`,toolResults:[],toolMessages:[]};let o=[],s=[],i=[],l=new Set,c=0,d=!1,u=[];if(n?.walletAddress&&u.push(`Connected wallet: ${n.walletAddress}`),n?.chain){let T=P(n.chain),S=gs(n.chain),A=S?`; native coin: ${S}`:"";u.push(`Current chain: ${T} (${n.chain})${A}`)}let p=u.length>0?`User context:
283
+ ${u.join(`
284
284
  `)}`:"",m=e.language?`The user's current language is "${e.language}" (BCP-47). Write every user-facing string you produce \u2014 replies AND any localized tool arguments \u2014 in this language.`:"",f=[p,m,`Routed query: ${e.query}`,e.reasoning?`Router reasoning: ${e.reasoning}`:"","Use only the tools you own. If you already have enough information, respond directly in the user's language."].filter(Boolean).join(`
285
285
 
286
- `),h=sa(t,this.toolNames),g=Ge(h,this.historyMessages),y=[{role:"system",content:this.systemPrompt,timestamp:0},...g,{role:"user",content:f,timestamp:Date.now()}],b=6e3,w=this.maxToolCalls+2;for(let T=0;T<w;T++){let S=c<this.maxToolCalls,A=S?r:void 0,_=S&&this.mustCallTool&&c===0,R=await this.llm.chat(y,A,_?{forceToolUse:!0}:void 0);if(R.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&S){this.debug&&console.log(` [${this.name}] no tool called \u2014 re-prompting to act via a tool (AI fallback: ${this.cortexFallbackTool})`),y.push({role:"user",content:`You answered without calling any tool. This is not allowed for on-chain queries \u2014 you must act via a tool, not plain text. FIRST, if any of your structured tools matches the user's intent, call that ONE tool now \u2014 resolve any missing field with a sensible default (per the defaults in your instructions; chain = the connected chain, else Ethereum) instead of asking the user. ONLY if no structured tool fits \u2014 a broad, conceptual, or open-ended question \u2014 call "${this.cortexFallbackTool}" with a clear, self-contained English prompt that captures the user's intent. Do NOT answer in text \u2014 call a tool.`,timestamp:Date.now()});continue}if(c===0&&this.mustCallTool&&S&&!u){u=!0,this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing the LLM to pick a tool`),y.push({role:"user",content:"You answered in text without calling any tool. That is not allowed here: this request needs you to open a form. Call exactly ONE of your tools that matches the user's intent now. Pass only the fields the user actually gave; leave everything else blank \u2014 the tool/form collects the rest (including a token/amount picker when needed). Do NOT ask the user for missing fields. Do NOT answer in text \u2014 call the tool.",timestamp:Date.now()});continue}return this.debug&&console.log(` [${this.name}] done \u2014 ${c} tool call(s), answer: "${R.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:o,finalAnswer:R.text,toolResults:s,toolMessages:i}}let C={role:"assistant",content:R.text||"",toolCalls:R.toolCalls,timestamp:Date.now()};y.push(C);let M=[];for(let E of R.toolCalls){if(!this.toolNames.has(E.toolName)){let ae=`Tool "${E.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${ae}`),o.push({phase:"observe",content:ae,timestamp:Date.now()}),y.push({role:"tool",content:ae,toolName:E.toolName,toolCallId:E.callId,timestamp:Date.now()});continue}let Q=`${E.toolName}::${JSON.stringify(E.args)}`;if(l.has(Q)){let ae=`Skipped duplicate call: ${E.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${E.toolName}`),o.push({phase:"observe",content:ae,timestamp:Date.now()}),y.push({role:"tool",content:ae,toolName:E.toolName,toolCallId:E.callId,timestamp:Date.now()});continue}l.add(Q),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${E.toolName} ${JSON.stringify(E.args)}`),o.push({phase:"think",content:R.text||`Calling ${E.toolName}`,timestamp:Date.now()}),o.push({phase:"act",content:`Calling tool: ${E.toolName}`,toolCall:{toolName:E.toolName,args:E.args},timestamp:Date.now()});let O=Date.now(),Ie={...n,query:e.query},ge=await this.registry.execute(E.toolName,E.args,Ie);s.push(ge);let G=ge.success?JSON.stringify(ge.data):`Error: ${ge.error}`;if(this.debug){let ae=ge.success?"OK":"ERR",ot=ge.success?`${G.slice(0,120)}${G.length>120?"\u2026":""}`:ge.error;console.log(` [${this.name}] ${ae} (${Date.now()-O}ms): ${ot}`)}o.push({phase:"observe",content:G,toolResult:ge,timestamp:Date.now()});let Be={role:"tool",content:G,toolName:E.toolName,toolCallId:E.callId,timestamp:Date.now()};y.push(Be),M.push({...Be,content:G.length>b?G.slice(0,b)+"\u2026[truncated]":G})}M.length>0&&(i.push(C),i.push(...M))}this.debug&&console.log(` [${this.name}] budget exhausted after ${c} calls, forcing final answer`),y.push({role:"user",content:"Tool budget reached. Give your best answer now based on the data gathered.",timestamp:Date.now()});let k=await this.llm.chat(y);return{subagentName:this.name,steps:o,finalAnswer:k.text,toolResults:s,toolMessages:i}}};var Uc=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
286
+ `),h=sa(t,this.toolNames),g=Ge(h,this.historyMessages),y=[{role:"system",content:this.systemPrompt,timestamp:0},...g,{role:"user",content:f,timestamp:Date.now()}],b=6e3,w=this.maxToolCalls+2;for(let T=0;T<w;T++){let S=c<this.maxToolCalls,A=S?r:void 0,_=S&&this.mustCallTool&&c===0,R=await this.llm.chat(y,A,_?{forceToolUse:!0}:void 0);if(R.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&S){this.debug&&console.log(` [${this.name}] no tool called \u2014 re-prompting to act via a tool (AI fallback: ${this.cortexFallbackTool})`),y.push({role:"user",content:`You answered without calling any tool. This is not allowed for on-chain queries \u2014 you must act via a tool, not plain text. FIRST, if any of your structured tools matches the user's intent, call that ONE tool now \u2014 resolve any missing field with a sensible default (per the defaults in your instructions; chain = the connected chain, else Ethereum) instead of asking the user. ONLY if no structured tool fits \u2014 a broad, conceptual, or open-ended question \u2014 call "${this.cortexFallbackTool}" with a clear, self-contained English prompt that captures the user's intent. Do NOT answer in text \u2014 call a tool.`,timestamp:Date.now()});continue}if(c===0&&this.mustCallTool&&S&&!d){d=!0,this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing the LLM to pick a tool`),y.push({role:"user",content:"You answered in text without calling any tool. That is not allowed here: this request needs you to open a form. Call exactly ONE of your tools that matches the user's intent now. Pass only the fields the user actually gave; leave everything else blank \u2014 the tool/form collects the rest (including a token/amount picker when needed). Do NOT ask the user for missing fields. Do NOT answer in text \u2014 call the tool.",timestamp:Date.now()});continue}return this.debug&&console.log(` [${this.name}] done \u2014 ${c} tool call(s), answer: "${R.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:o,finalAnswer:R.text,toolResults:s,toolMessages:i}}let C={role:"assistant",content:R.text||"",toolCalls:R.toolCalls,timestamp:Date.now()};y.push(C);let M=[];for(let E of R.toolCalls){if(!this.toolNames.has(E.toolName)){let ae=`Tool "${E.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${ae}`),o.push({phase:"observe",content:ae,timestamp:Date.now()}),y.push({role:"tool",content:ae,toolName:E.toolName,toolCallId:E.callId,timestamp:Date.now()});continue}let Q=`${E.toolName}::${JSON.stringify(E.args)}`;if(l.has(Q)){let ae=`Skipped duplicate call: ${E.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${E.toolName}`),o.push({phase:"observe",content:ae,timestamp:Date.now()}),y.push({role:"tool",content:ae,toolName:E.toolName,toolCallId:E.callId,timestamp:Date.now()});continue}l.add(Q),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${E.toolName} ${JSON.stringify(E.args)}`),o.push({phase:"think",content:R.text||`Calling ${E.toolName}`,timestamp:Date.now()}),o.push({phase:"act",content:`Calling tool: ${E.toolName}`,toolCall:{toolName:E.toolName,args:E.args},timestamp:Date.now()});let O=Date.now(),Ie={...n,query:e.query},ge=await this.registry.execute(E.toolName,E.args,Ie);s.push(ge);let G=ge.success?JSON.stringify(ge.data):`Error: ${ge.error}`;if(this.debug){let ae=ge.success?"OK":"ERR",ot=ge.success?`${G.slice(0,120)}${G.length>120?"\u2026":""}`:ge.error;console.log(` [${this.name}] ${ae} (${Date.now()-O}ms): ${ot}`)}o.push({phase:"observe",content:G,toolResult:ge,timestamp:Date.now()});let Be={role:"tool",content:G,toolName:E.toolName,toolCallId:E.callId,timestamp:Date.now()};y.push(Be),M.push({...Be,content:G.length>b?G.slice(0,b)+"\u2026[truncated]":G})}M.length>0&&(i.push(C),i.push(...M))}this.debug&&console.log(` [${this.name}] budget exhausted after ${c} calls, forcing final answer`),y.push({role:"user",content:"Tool budget reached. Give your best answer now based on the data gathered.",timestamp:Date.now()});let k=await this.llm.chat(y);return{subagentName:this.name,steps:o,finalAnswer:k.text,toolResults:s,toolMessages:i}}};var Uc=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
287
287
 
288
288
  SPECIALISED TOOLS (prefer these when intent matches):
289
289
  - get-wallet-token-balances: token + native coin balances
@@ -760,7 +760,7 @@ SEND NFT (open-send-nft-form) specifics:
760
760
 
761
761
  Skip the tool ONLY if: walletAddress missing (ask to connect) \xB7 user explicitly names a chain different from userContext.chain (ask to switch).
762
762
 
763
- After the tool returns: 1 short sentence in the user's language. Don't list missing fields. Don't mention tool names.`,$o=["open-send-native-form","open-send-token-form","open-send-nft-form","open-buy-token-form","open-swap-token-form","open-approve-token-form"];function oo(a,e,t){return new X({name:"wallet-action-agent",domain:"wallet-action",capability:"help with wallet actions such as sending tokens or NFTs, buying or swapping tokens",description:["User wants to PERFORM an on-chain action (send a token or NFT, buy, swap, approve).","This agent picks the matching open-*-form tool which emits a pre-filled form (or, for buy/swap, a confirm panel) for the FE to render.",'Includes sending / transferring an NFT ("send nft", "g\u1EEDi nft", "transfer nft") via the NFT send form.',"The FE \u2014 not this agent \u2014 builds and submits the tx after the user confirms.","NOT in scope: read-only wallet/token/NFT queries, past NFT transfer history / events (\u2192 wallet-agent), liquidity provisioning."].join(" "),toolNames:[...$o],systemPrompt:qc,mustCallTool:!0,llm:a,registry:e,options:t})}function Vo(a,e,t,n){let r=(c,u)=>{let d=n?.[c];return d===void 0?u:d},o=r("pool-subgraph",!1),s=n?.pool===!0,i=o?s:r("pool",!0),l=[];return r("wallet",!0)&&l.push(Qn(a,e,t)),r("wallet-action",!0)&&l.push(oo(a,e,t)),r("token",!0)&&l.push(Jn(a,e,t)),r("nft",!0)&&l.push(Zn(a,e,t)),r("nfc",!1)&&l.push(eo(a,e,t)),i&&l.push(no(a,e,t)),o&&l.push(Er(a,e,t)),r("ai",!0)&&l.push(to(a,e,t)),l}var Bc=`You are the response SYNTHESIZER for a crypto/DeFi assistant. You receive the user's question, the agent's reasoning, and raw tool results, and you turn them into ONE clear final answer for the user.
763
+ After the tool returns: 1 short sentence in the user's language. Don't list missing fields. Don't mention tool names.`,$o=["open-send-native-form","open-send-token-form","open-send-nft-form","open-buy-token-form","open-swap-token-form","open-approve-token-form"];function oo(a,e,t){return new X({name:"wallet-action-agent",domain:"wallet-action",capability:"help with wallet actions such as sending tokens or NFTs, buying or swapping tokens",description:["User wants to PERFORM an on-chain action (send a token or NFT, buy, swap, approve).","This agent picks the matching open-*-form tool which emits a pre-filled form (or, for buy/swap, a confirm panel) for the FE to render.",'Includes sending / transferring an NFT ("send nft", "g\u1EEDi nft", "transfer nft") via the NFT send form.',"The FE \u2014 not this agent \u2014 builds and submits the tx after the user confirms.","NOT in scope: read-only wallet/token/NFT queries, past NFT transfer history / events (\u2192 wallet-agent), liquidity provisioning."].join(" "),toolNames:[...$o],systemPrompt:qc,mustCallTool:!0,llm:a,registry:e,options:t})}function Vo(a,e,t,n){let r=(c,d)=>{let u=n?.[c];return u===void 0?d:u},o=r("pool-subgraph",!1),s=n?.pool===!0,i=o?s:r("pool",!0),l=[];return r("wallet",!0)&&l.push(Qn(a,e,t)),r("wallet-action",!0)&&l.push(oo(a,e,t)),r("token",!0)&&l.push(Jn(a,e,t)),r("nft",!0)&&l.push(Zn(a,e,t)),r("nfc",!1)&&l.push(eo(a,e,t)),i&&l.push(no(a,e,t)),o&&l.push(Er(a,e,t)),r("ai",!0)&&l.push(to(a,e,t)),l}var Bc=`You are the response SYNTHESIZER for a crypto/DeFi assistant. You receive the user's question, the agent's reasoning, and raw tool results, and you turn them into ONE clear final answer for the user.
764
764
 
765
765
  GROUNDING \u2014 most important:
766
766
  - Use ONLY facts, numbers, prices, balances, addresses and links that appear in the agent reasoning or tool results. NEVER invent, round, estimate, or "fill in" a value that is not present.
@@ -778,9 +778,9 @@ NEVER:
778
778
 
779
779
  Reply in the same language as the user's question (a separate directive below specifies the exact language).
780
780
  `,In=class{llm;constructor(e){this.llm=e}async synthesise(e,t,n,r){if(!t.steps.some(m=>m.phase==="act")&&t.finalAnswer)return ua(t.finalAnswer);let s=t.steps.filter(m=>m.phase==="observe").map((m,f)=>`[Result ${f+1}]: ${m.content}`).join(`
781
- `),i=qe(n),l=Ge(i,8),c=(r||"").trim().toLowerCase(),u=c?`IMPORTANT: Reply in BCP-47 language "${c}" (the language the user actually typed). Tool results may contain text in other languages \u2014 ignore that and reply ONLY in "${c}".`:`IMPORTANT: The user wrote in the language of this message: "${e}". Reply in that exact language, ignoring any other languages that appear inside tool results.`,d=[{role:"system",content:Bc,timestamp:0},...l,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",s?`Tool results:
782
- ${s}`:"","",u].filter(Boolean).join(`
783
- `),timestamp:Date.now()}],p=await this.llm.chat(d);return ua(p.text)}};function ua(a){return a&&a.replace(/^\[[a-z0-9-]+-agent\]\s*/i,"").replace(/\n\n\[[a-z0-9-]+-agent\]\s*/gi,`
781
+ `),i=qe(n),l=Ge(i,8),c=(r||"").trim().toLowerCase(),d=c?`IMPORTANT: Reply in BCP-47 language "${c}" (the language the user actually typed). Tool results may contain text in other languages \u2014 ignore that and reply ONLY in "${c}".`:`IMPORTANT: The user wrote in the language of this message: "${e}". Reply in that exact language, ignoring any other languages that appear inside tool results.`,u=[{role:"system",content:Bc,timestamp:0},...l,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",s?`Tool results:
782
+ ${s}`:"","",d].filter(Boolean).join(`
783
+ `),timestamp:Date.now()}],p=await this.llm.chat(u);return ua(p.text)}};function ua(a){return a&&a.replace(/^\[[a-z0-9-]+-agent\]\s*/i,"").replace(/\n\n\[[a-z0-9-]+-agent\]\s*/gi,`
784
784
 
785
785
  `)}var $c=`You are a CONTEXTUALIZER.
786
786
 
@@ -1018,22 +1018,22 @@ Examples:
1018
1018
 
1019
1019
  ${l.join(`
1020
1020
 
1021
- `)}`:"",u=Date.now(),d=[{role:"system",content:$c,timestamp:0},...i,{role:"user",content:`Latest user message to contextualize:
1021
+ `)}`:"",d=Date.now(),u=[{role:"system",content:$c,timestamp:0},...i,{role:"user",content:`Latest user message to contextualize:
1022
1022
  ${e}${c}
1023
1023
 
1024
- Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:Vc,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[m,f]=await Promise.allSettled([this.llm.chat(d,void 0,{maxOutputTokens:512}),this.llm.chat(p,void 0,{maxOutputTokens:32})]),h={};if(m.status==="fulfilled")try{h=this.parseJSON(m.value.text)}catch(b){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${m.reason}`);let g="";if(f.status==="fulfilled")try{let b=this.parseJSON(f.value.text);typeof b.language=="string"&&(g=b.language.trim().toLowerCase())}catch(b){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${f.reason}`);let y={isFollowUp:r&&typeof h.isFollowUp=="boolean"?h.isFollowUp:!1,rewrittenQuery:typeof h.rewrittenQuery=="string"&&h.rewrittenQuery.trim()?h.rewrittenQuery.trim():e,topicChanged:r&&typeof h.topicChanged=="boolean"?h.topicChanged:!1,reasoning:typeof h.reasoning=="string"?h.reasoning:"",language:g,mentionedChain:typeof h.mentionedChain=="string"?h.mentionedChain.trim():"",needsWebSearch:h.needsWebSearch===!0,aboutAssistant:h.aboutAssistant===!0};if(this.debug){let b=Date.now()-u,w=y.rewrittenQuery!==e;console.log(`
1025
- [QueryRewriter] (${b}ms)`),console.log(` original : "${e}"`),console.log(` rewritten : "${y.rewrittenQuery}"${w?"":" (unchanged)"}`),console.log(` followUp : ${y.isFollowUp} topicChanged: ${y.topicChanged}`),y.reasoning&&console.log(` reasoning : ${y.reasoning}`),console.log(` language : ${y.language}`),console.log(` webSearch : ${y.needsWebSearch}`),console.log(` aboutSelf : ${y.aboutAssistant}`)}return y}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let n=t.match(/\{[\s\S]*\}/);return n&&(t=n[0]),JSON.parse(t)}};var F=require("@langchain/langgraph");function Ho(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var da="\\s*/\\s*";function Rr(a){return[a.symA.toLowerCase(),a.symB.toLowerCase()].sort().join("|")}function pa(a){return`(${a.symA}${da}${a.symB}|${a.symB}${da}${a.symA})`}function Wc(a){let e=Ho(String(a));return`(?<![\\d.])${Number.isInteger(a)?`${e}(?:\\.0+)?`:`${e}0*`}`}function Nr(a,e,t,n){return`${a.slice(0,e)}[${t}](${n})${a.slice(e+t.length)}`}function Hc(a,e){let n=new RegExp(`(?<!\\[)\\b${pa(e)}\\b`,"i").exec(a);return n?Nr(a,n.index,n[1]??n[0],e.url):null}function Gc(a,e){if(e.feePercent==null)return null;let n=new RegExp(`(?<!\\[)\\b${pa(e)}\\b[^\\n\\]]{0,16}?${Wc(e.feePercent)}\\s*%`,"i").exec(a);return n?Nr(a,n.index,n[1]??"",e.url):null}var Yc=a=>{let e=[],t=n=>{if(!n||typeof n!="object")return;let r=n,o=typeof r.uniswapUrl=="string"?r.uniswapUrl:void 0,s=r.token0?.symbol,i=r.token1?.symbol;if(o&&typeof s=="string"&&s&&typeof i=="string"&&i){let l=r.feeTierPercent;e.push({url:o,symA:Ho(s),symB:Ho(i),feePercent:typeof l=="number"&&Number.isFinite(l)?l:void 0})}};t(a),t(a.pool);for(let n of["pools","candidates"]){let r=a[n];Array.isArray(r)&&r.forEach(t)}return e},jc=[Yc],Kc=a=>{let e=[],t=a.marketplaceLinks;if(Array.isArray(t))for(let r of t){if(!r||typeof r!="object")continue;let{label:o,url:s}=r;typeof o=="string"&&o&&typeof s=="string"&&s&&e.push({url:s,label:o})}let n=typeof a.amazonBuyUrl=="string"?a.amazonBuyUrl:void 0;return n&&e.push({url:n,label:"Amazon"}),e},zc=[Kc];function Xc(a,e){let n=new RegExp(`(?<!\\[)\\b${Ho(e.label)}\\b`,"i").exec(a);return n?Nr(a,n.index,n[0],e.url):null}function Go(a,e){if(!a)return a;let t=[],n=[];for(let i of e)for(let l of i.toolResults){if(!l.success||!l.data||typeof l.data!="object")continue;let c=l.data;for(let u of jc)t.push(...u(c));for(let u of zc)n.push(...u(c))}if(t.length===0&&n.length===0)return a;let r=new Map;for(let i of t)r.set(Rr(i),(r.get(Rr(i))??0)+1);let o=a,s=new Set;for(let i of t){if(s.has(i.url))continue;if(o.includes(i.url)){s.add(i.url);continue}let c=(r.get(Rr(i))??0)>1?Gc(o,i):Hc(o,i);c&&(o=c,s.add(i.url))}for(let i of n){if(s.has(i.url))continue;if(o.includes(i.url)){s.add(i.url);continue}let l=Xc(o,i);l&&(o=l,s.add(i.url))}return o}var xe=a=>({reducer:(e,t)=>t,default:a}),Qc=F.Annotation.Root({userMessage:(0,F.Annotation)(),overrideLang:(0,F.Annotation)(xe(()=>"")),conversationMessages:(0,F.Annotation)(xe(()=>[])),lastSubagents:(0,F.Annotation)(xe(()=>[])),messageId:(0,F.Annotation)(xe(()=>"")),rewrite:(0,F.Annotation)(xe(()=>null)),effectiveQuery:(0,F.Annotation)(xe(()=>"")),turnLanguage:(0,F.Annotation)(xe(()=>"")),kbContext:(0,F.Annotation)(xe(()=>"")),decision:(0,F.Annotation)(xe(()=>null)),assignment:(0,F.Annotation)(xe(()=>null)),assignmentIndex:(0,F.Annotation)(xe(()=>0)),subResults:(0,F.Annotation)({reducer:(a,e)=>a.concat(e),default:()=>[]}),response:(0,F.Annotation)(xe(()=>null))});function ma(a){let e=async d=>{a.addUserMessage(d.userMessage),a.needsSummary()&&await a.compactHistory();let p=a.conversationForTurn(),m=a.lastAssistantSubagents(p);return a.debug&&m.length>0&&console.log(`[AgentCore] previous turn handled by: ${m.join(", ")}`),{conversationMessages:p,lastSubagents:m,messageId:a.generateMessageId()}},t=async d=>{let p=await a.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),m=d.overrideLang||p.language||"";return{rewrite:p,effectiveQuery:p.rewrittenQuery,turnLanguage:m}},n=async d=>{let p=d.rewrite,m=p.isFollowUp?d.effectiveQuery:d.userMessage,f=await a.searchKB(m),h=a.formatKBContext(f),g=await a.tryAnswerFromKB(d.userMessage,f,h,d.messageId);return g?{kbContext:h,response:{...g,messageId:d.messageId,rewrite:p}}:{kbContext:h}},r=async d=>({decision:await a.route(d.effectiveQuery,d.conversationMessages,a.subagentCards(),d.lastSubagents)}),o=async d=>{let p=await a.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.messageId,d.rewrite?.needsWebSearch??!1),m=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...p,messageId:d.messageId,routerDecision:m,rewrite:d.rewrite}}},s=async d=>{let p=await a.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:p}]}},i=async d=>{let p=d.subResults.slice().sort((k,T)=>k.i-T.i).map(k=>k.result);a.persistToolMessages(p);let m=a.mergeTrace(p),f=await a.synthesise(d.userMessage,m,a.synthesiserHistory(),d.turnLanguage||void 0),h=Go(f,p),g=p.map(k=>k.subagentName),y=a.collectUiActions(p,d.turnLanguage||null),b=a.collectActionButtons(p,d.turnLanguage||null);return{response:{...await a.finaliseAnswer({userMessage:d.userMessage,answer:h,subagents:g,uiActions:y,actionButtons:b,messageId:d.messageId}),messageId:d.messageId,trace:m,routerDecision:d.decision,subagentResults:p,rewrite:d.rewrite,...y.length>0?{uiActions:y}:{},...b.length>0?{actionButtons:b}:{}}}},l=async d=>{let p=(d.rewrite?.mentionedChain||String(a.connectedChain()??"")).trim(),m=new Map(a.subagentCards().map(b=>[b.name,b.domain])),f=(d.decision?.assignments??[]).filter(b=>b.subagent!=="ai-agent"),g=f.length>0&&f.every(b=>m.get(b.subagent)==="pool")?me():void 0;return{response:{...await a.answerUnsupportedChain(p,d.turnLanguage,d.messageId,g),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},c=d=>d.response?F.END:d.rewrite?.aboutAssistant?"direct":"route",u=d=>{let p=d.decision?.assignments??[];if(p.length===0)return"direct";let m=p.some(h=>h.subagent!=="ai-agent"),f=(d.rewrite?.mentionedChain||a.connectedChain()||"").trim();return m&&f!==""&&!_e(f)?"unsupportedChain":p.map((h,g)=>new F.Send("subagent",{...d,assignment:h,assignmentIndex:g}))};return new F.StateGraph(Qc).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",s).addNode("synthesize",i).addNode("unsupportedChain",l).addEdge(F.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",F.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",F.END).addEdge("direct",F.END).addEdge("subagent","synthesize").addEdge("synthesize",F.END).compile()}var ha=require("js-sha3");function Ln(){let a=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(a+e).slice(-8)}var Jc="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",Zc=`
1024
+ Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:Vc,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[m,f]=await Promise.allSettled([this.llm.chat(u,void 0,{maxOutputTokens:512}),this.llm.chat(p,void 0,{maxOutputTokens:32})]),h={};if(m.status==="fulfilled")try{h=this.parseJSON(m.value.text)}catch(b){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${m.reason}`);let g="";if(f.status==="fulfilled")try{let b=this.parseJSON(f.value.text);typeof b.language=="string"&&(g=b.language.trim().toLowerCase())}catch(b){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${f.reason}`);let y={isFollowUp:r&&typeof h.isFollowUp=="boolean"?h.isFollowUp:!1,rewrittenQuery:typeof h.rewrittenQuery=="string"&&h.rewrittenQuery.trim()?h.rewrittenQuery.trim():e,topicChanged:r&&typeof h.topicChanged=="boolean"?h.topicChanged:!1,reasoning:typeof h.reasoning=="string"?h.reasoning:"",language:g,mentionedChain:typeof h.mentionedChain=="string"?h.mentionedChain.trim():"",needsWebSearch:h.needsWebSearch===!0,aboutAssistant:h.aboutAssistant===!0};if(this.debug){let b=Date.now()-d,w=y.rewrittenQuery!==e;console.log(`
1025
+ [QueryRewriter] (${b}ms)`),console.log(` original : "${e}"`),console.log(` rewritten : "${y.rewrittenQuery}"${w?"":" (unchanged)"}`),console.log(` followUp : ${y.isFollowUp} topicChanged: ${y.topicChanged}`),y.reasoning&&console.log(` reasoning : ${y.reasoning}`),console.log(` language : ${y.language}`),console.log(` webSearch : ${y.needsWebSearch}`),console.log(` aboutSelf : ${y.aboutAssistant}`)}return y}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let n=t.match(/\{[\s\S]*\}/);return n&&(t=n[0]),JSON.parse(t)}};var F=require("@langchain/langgraph");function Ho(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var da="\\s*/\\s*";function Rr(a){return[a.symA.toLowerCase(),a.symB.toLowerCase()].sort().join("|")}function pa(a){return`(${a.symA}${da}${a.symB}|${a.symB}${da}${a.symA})`}function Wc(a){let e=Ho(String(a));return`(?<![\\d.])${Number.isInteger(a)?`${e}(?:\\.0+)?`:`${e}0*`}`}function Nr(a,e,t,n){return`${a.slice(0,e)}[${t}](${n})${a.slice(e+t.length)}`}function Hc(a,e){let n=new RegExp(`(?<!\\[)\\b${pa(e)}\\b`,"i").exec(a);return n?Nr(a,n.index,n[1]??n[0],e.url):null}function Gc(a,e){if(e.feePercent==null)return null;let n=new RegExp(`(?<!\\[)\\b${pa(e)}\\b[^\\n\\]]{0,16}?${Wc(e.feePercent)}\\s*%`,"i").exec(a);return n?Nr(a,n.index,n[1]??"",e.url):null}var Yc=a=>{let e=[],t=n=>{if(!n||typeof n!="object")return;let r=n,o=typeof r.uniswapUrl=="string"?r.uniswapUrl:void 0,s=r.token0?.symbol,i=r.token1?.symbol;if(o&&typeof s=="string"&&s&&typeof i=="string"&&i){let l=r.feeTierPercent;e.push({url:o,symA:Ho(s),symB:Ho(i),feePercent:typeof l=="number"&&Number.isFinite(l)?l:void 0})}};t(a),t(a.pool);for(let n of["pools","candidates"]){let r=a[n];Array.isArray(r)&&r.forEach(t)}return e},jc=[Yc],Kc=a=>{let e=[],t=a.marketplaceLinks;if(Array.isArray(t))for(let r of t){if(!r||typeof r!="object")continue;let{label:o,url:s}=r;typeof o=="string"&&o&&typeof s=="string"&&s&&e.push({url:s,label:o})}let n=typeof a.amazonBuyUrl=="string"?a.amazonBuyUrl:void 0;return n&&e.push({url:n,label:"Amazon"}),e},zc=[Kc];function Xc(a,e){let n=new RegExp(`(?<!\\[)\\b${Ho(e.label)}\\b`,"i").exec(a);return n?Nr(a,n.index,n[0],e.url):null}function Go(a,e){if(!a)return a;let t=[],n=[];for(let i of e)for(let l of i.toolResults){if(!l.success||!l.data||typeof l.data!="object")continue;let c=l.data;for(let d of jc)t.push(...d(c));for(let d of zc)n.push(...d(c))}if(t.length===0&&n.length===0)return a;let r=new Map;for(let i of t)r.set(Rr(i),(r.get(Rr(i))??0)+1);let o=a,s=new Set;for(let i of t){if(s.has(i.url))continue;if(o.includes(i.url)){s.add(i.url);continue}let c=(r.get(Rr(i))??0)>1?Gc(o,i):Hc(o,i);c&&(o=c,s.add(i.url))}for(let i of n){if(s.has(i.url))continue;if(o.includes(i.url)){s.add(i.url);continue}let l=Xc(o,i);l&&(o=l,s.add(i.url))}return o}var xe=a=>({reducer:(e,t)=>t,default:a}),Qc=F.Annotation.Root({userMessage:(0,F.Annotation)(),overrideLang:(0,F.Annotation)(xe(()=>"")),conversationMessages:(0,F.Annotation)(xe(()=>[])),lastSubagents:(0,F.Annotation)(xe(()=>[])),messageId:(0,F.Annotation)(xe(()=>"")),rewrite:(0,F.Annotation)(xe(()=>null)),effectiveQuery:(0,F.Annotation)(xe(()=>"")),turnLanguage:(0,F.Annotation)(xe(()=>"")),kbContext:(0,F.Annotation)(xe(()=>"")),decision:(0,F.Annotation)(xe(()=>null)),assignment:(0,F.Annotation)(xe(()=>null)),assignmentIndex:(0,F.Annotation)(xe(()=>0)),subResults:(0,F.Annotation)({reducer:(a,e)=>a.concat(e),default:()=>[]}),response:(0,F.Annotation)(xe(()=>null))});function ma(a){let e=async u=>{a.addUserMessage(u.userMessage),a.needsSummary()&&await a.compactHistory();let p=a.conversationForTurn(),m=a.lastAssistantSubagents(p);return a.debug&&m.length>0&&console.log(`[AgentCore] previous turn handled by: ${m.join(", ")}`),{conversationMessages:p,lastSubagents:m,messageId:a.generateMessageId()}},t=async u=>{let p=await a.rewrite(u.userMessage,u.conversationMessages,u.lastSubagents),m=u.overrideLang||p.language||"";return{rewrite:p,effectiveQuery:p.rewrittenQuery,turnLanguage:m}},n=async u=>{let p=u.rewrite,m=p.isFollowUp?u.effectiveQuery:u.userMessage,f=await a.searchKB(m),h=a.formatKBContext(f),g=await a.tryAnswerFromKB(u.userMessage,f,h,u.messageId);return g?{kbContext:h,response:{...g,messageId:u.messageId,rewrite:p}}:{kbContext:h}},r=async u=>({decision:await a.route(u.effectiveQuery,u.conversationMessages,a.subagentCards(),u.lastSubagents)}),o=async u=>{let p=await a.answerDirectly(u.effectiveQuery,u.conversationMessages,u.kbContext,u.messageId,u.rewrite?.needsWebSearch??!1),m=u.decision??{analysis:u.rewrite?.reasoning??"",assignments:[]};return{response:{...p,messageId:u.messageId,routerDecision:m,rewrite:u.rewrite}}},s=async u=>{let p=await a.runSubagent(u.assignment,u.conversationMessages,u.turnLanguage);return{subResults:[{i:u.assignmentIndex,result:p}]}},i=async u=>{let p=u.subResults.slice().sort((k,T)=>k.i-T.i).map(k=>k.result);a.persistToolMessages(p);let m=a.mergeTrace(p),f=await a.synthesise(u.userMessage,m,a.synthesiserHistory(),u.turnLanguage||void 0),h=Go(f,p),g=p.map(k=>k.subagentName),y=a.collectUiActions(p,u.turnLanguage||null),b=a.collectActionButtons(p,u.turnLanguage||null);return{response:{...await a.finaliseAnswer({userMessage:u.userMessage,answer:h,subagents:g,uiActions:y,actionButtons:b,messageId:u.messageId}),messageId:u.messageId,trace:m,routerDecision:u.decision,subagentResults:p,rewrite:u.rewrite,...y.length>0?{uiActions:y}:{},...b.length>0?{actionButtons:b}:{}}}},l=async u=>{let p=(u.rewrite?.mentionedChain||String(a.connectedChain()??"")).trim(),m=new Map(a.subagentCards().map(b=>[b.name,b.domain])),f=(u.decision?.assignments??[]).filter(b=>b.subagent!=="ai-agent"),g=f.length>0&&f.every(b=>m.get(b.subagent)==="pool")?me():void 0;return{response:{...await a.answerUnsupportedChain(p,u.turnLanguage,u.messageId,g),messageId:u.messageId,routerDecision:u.decision,rewrite:u.rewrite}}},c=u=>u.response?F.END:u.rewrite?.aboutAssistant?"direct":"route",d=u=>{let p=u.decision?.assignments??[];if(p.length===0)return"direct";let m=p.some(h=>h.subagent!=="ai-agent"),f=(u.rewrite?.mentionedChain||a.connectedChain()||"").trim();return m&&f!==""&&!_e(f)?"unsupportedChain":p.map((h,g)=>new F.Send("subagent",{...u,assignment:h,assignmentIndex:g}))};return new F.StateGraph(Qc).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",s).addNode("synthesize",i).addNode("unsupportedChain",l).addEdge(F.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",F.END]).addConditionalEdges("route",d,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",F.END).addEdge("direct",F.END).addEdge("subagent","synthesize").addEdge("synthesize",F.END).compile()}var ha=require("js-sha3");function Ln(){let a=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(a+e).slice(-8)}var Jc="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",Zc=`
1026
1026
 
1027
1027
  IDENTITY: This applies ONLY when the user asks who or what you are. In that case, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline. This identity rule does NOT change how you handle restricted topics below \u2014 for those, follow the RESTRICTED TOPICS rule exactly.`,eu=`
1028
1028
 
1029
- RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,Yo=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;ownGeminiKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;x402Signer=null;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;currentAbortController=null;historyReady;constructor(e){this.secretKey=e.secretKey??"",this.ownGeminiKey=!!e.llm?.apiKey?.trim(),rr(e.rpcUrls),fo(e.excludeChains),this.llm=new z(e.llm),this.registry=new kt,this.history=new En(e.maxHistoryMessages??50),this.summarizer=new Rn(this.llm),this.synthesizer=new In(this.llm),this.systemPrompt=(e.systemPrompt??Jc)+Zc+eu,this.debug=e.debug??!1,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new Nn(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new nt({url:t.url,token:t.token,namespace:t.namespace,minScore:t.minScore,defaultTopK:t.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=t.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${t.provider?"custom provider":"Upstash"}`+(t.namespace?`, ns=${t.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:t?.enabled&&!t.provider?this.kbAnswerThreshold=t.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let c=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Ut(c)),this.registry.register(new xt({...c,llm:e.llm})),this.registry.register(new It(c)),this.registry.register(new Lt(c)),this.registry.register(new Dt(c)),this.registry.register(new Ct(c)),this.registry.register(new Ot(c)),this.registry.register(new Mt(c)),this.registry.register(new Vt(c)),this.registry.register(new qt(c)),this.registry.register(new Bt(c)),this.registry.register(new $t(c)),this.registry.register(new Ft(c)),this.registry.register(new Rt(c)),this.registry.register(new Nt(c)),this.registry.register(new _t(c)),this.registry.register(new Et(c)),this.registry.register(new Ht(c))}this.registry.register(new Gt(e.llm)),this.registry.register(new Yt(e.llm)),e.subagents?.nfc===!0&&(this.registry.register(new Kt(e.llm)),this.registry.register(new zt(e.llm))),this.registry.register(new Xt(e.llm));let r=e.subagents?.["pool-subgraph"]===!0,o=r?e.subagents?.pool===!0:e.subagents?.pool!==!1;if(o&&e.uniswap!==!1){let c=typeof e.uniswap=="object"?e.uniswap:void 0,u=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new rn(c,u)),this.registry.register(new sn(c)),this.registry.register(new an(c)),this.registry.register(new ln(c)),this.registry.register(new dn(c));let d=c?{isProduction:c.isProduction}:void 0;this.registry.register(new cn({baseUrl:c?.baseUrl,pool:d,minProvideUsd:c?.minProvideUsd})),this.registry.register(new un({pool:d})),this.registry.register(new pn),this.registry.register(new mn)}if((o||r)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new Qt(e.llm)),r&&e.subgraph!==!1){let c=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new hn(c)),this.registry.register(new gn(c)),this.registry.register(new fn(c)),this.registry.register(new yn(c)),this.registry.register(new bn(c)),this.registry.register(new wn(c)),this.registry.register(new kn(c))}if(e.subagents?.["wallet-action"]!==!1){let c=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{},u=e.noFormTools,d=p=>Lo(this.registry,p,u);d(new An(c)),d(new Sn(c)),d(new _n(c)),d(new Pn(c)),d(new xn(c,{debug:this.debug})),d(new Cn(c,{debug:this.debug}))}this.router=new Un(this.llm,{debug:this.debug}),this.rewriter=new Wo(this.llm,{debug:this.debug});let i=typeof e.subgraph=="object"?e.subgraph:void 0,l=Vo(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:i?.linkAddLiquidity},e.subagents);this.subagents=new Map(l.map(c=>[c.name,c])),this.chatGraph=ma(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let t of e)this.registry.register(t)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,t,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:Ln()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,timestamp:Date.now()});let s=await this.registry.execute(e,t,this.userContext),i=s.data,l=s.success?i?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,c=Ln(),u=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:l,messageId:c,...u.length>0?{uiActions:u}:{}}}async runTool(e,t,n){this.assertLicense(),await this.loadHistory();let r=Ln();if(!this.registry.has(e))return{answer:`Unknown tool: "${e}".`,messageId:r};this.debug&&console.log(`[AgentCore] runTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage?.trim()||`[run ${e}]`,s=typeof n?.language=="string"&&n.language.trim()?n.language.trim():null,i=Array.from(this.subagents.values()).filter(m=>m.ownsTool(e)).map(m=>m.name),l=i.length>0?i:["direct"],c=new AbortController;this.currentAbortController=c;let{signal:u,cleanup:d}=pr(c,n?.signal);this.llm.setRequestSignal?.(u),Mn(u);let p=this.history.serialise();try{this.history.add({role:"user",content:o,timestamp:Date.now()});let m=await this.registry.execute(e,t,{...this.userContext,query:o});Vn(u);let f=m.success?JSON.stringify(m.data):`Error: ${m.error}`,h=Date.now(),g=[{subagentName:l[0],steps:[{phase:"act",content:`Calling tool: ${e}`,toolCall:{toolName:e,args:t},timestamp:h},{phase:"observe",content:f,toolResult:m,timestamp:h}],finalAnswer:"",toolResults:[m],toolMessages:[]}],y=this.mergeTrace(g),b=await this.synthesizer.synthesise(o,y,this.synthesiserHistory(),s??void 0),w=Go(b,g),k=this.collectUiActions(g,s),T=this.collectActionButtons(g,s);return{...await this.finaliseAnswer({userMessage:o,answer:w,subagents:l,uiActions:k,actionButtons:T,messageId:r}),messageId:r,trace:y,subagentResults:g,...k.length>0?{uiActions:k}:{},...T.length>0?{actionButtons:T}:{}}}catch(m){throw ut(m)||u.aborted?(this.history.restore(p),new Ke):(this.history.restore(p),m)}finally{d(),this.llm.setRequestSignal?.(void 0),Mn(void 0),this.currentAbortController===c&&(this.currentAbortController=null)}}setX402Signer(e){this.x402Signer=e,Fr(e?dr({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,t,n){this.assertLicense(),await this.loadHistory();let r=Ln(),o=e,s=n?.userQuery||o?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let i;try{i=await cr(x,o,t)}catch(c){let d=`The payment couldn't be completed: ${c instanceof Error?c.message:String(c)}. Please try again.`;return this.history.add({role:"assistant",content:d,timestamp:Date.now(),messageId:r}),await this.persistHistory(),{answer:d,messageId:r}}return{...await this.synthesizeFromPaidData(s,i,r),messageId:r}}async synthesizeFromPaidData(e,t,n){let r=typeof t=="string"?t:JSON.stringify(t),o=this.systemPrompt+this.capabilitiesSummary(),s=`The user's question was: "${e}".
1029
+ RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,Yo=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;ownGeminiKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;x402Signer=null;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;currentAbortController=null;historyReady;constructor(e){this.secretKey=e.secretKey??"",this.ownGeminiKey=!!e.llm?.apiKey?.trim(),rr(e.rpcUrls),fo(e.excludeChains),this.llm=new z(e.llm),this.registry=new kt,this.history=new En(e.maxHistoryMessages??50),this.summarizer=new Rn(this.llm),this.synthesizer=new In(this.llm),this.systemPrompt=(e.systemPrompt??Jc)+Zc+eu,this.debug=e.debug??!1,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new Nn(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new nt({url:t.url,token:t.token,namespace:t.namespace,minScore:t.minScore,defaultTopK:t.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=t.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${t.provider?"custom provider":"Upstash"}`+(t.namespace?`, ns=${t.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:t?.enabled&&!t.provider?this.kbAnswerThreshold=t.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let c=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Ut(c)),this.registry.register(new xt({...c,llm:e.llm})),this.registry.register(new It(c)),this.registry.register(new Lt(c)),this.registry.register(new Dt(c)),this.registry.register(new Ct(c)),this.registry.register(new Ot(c)),this.registry.register(new Mt(c)),this.registry.register(new Vt(c)),this.registry.register(new qt(c)),this.registry.register(new Bt(c)),this.registry.register(new $t(c)),this.registry.register(new Ft(c)),this.registry.register(new Rt(c)),this.registry.register(new Nt(c)),this.registry.register(new _t(c)),this.registry.register(new Et(c)),this.registry.register(new Ht(c))}this.registry.register(new Gt(e.llm)),this.registry.register(new Yt(e.llm)),e.subagents?.nfc===!0&&(this.registry.register(new Kt(e.llm)),this.registry.register(new zt(e.llm))),this.registry.register(new Xt(e.llm));let r=e.subagents?.["pool-subgraph"]===!0,o=r?e.subagents?.pool===!0:e.subagents?.pool!==!1;if(o&&e.uniswap!==!1){let c=typeof e.uniswap=="object"?e.uniswap:void 0,d=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new rn(c,d)),this.registry.register(new sn(c)),this.registry.register(new an(c)),this.registry.register(new ln(c)),this.registry.register(new dn(c));let u=c?{isProduction:c.isProduction}:void 0;this.registry.register(new cn({baseUrl:c?.baseUrl,pool:u,minProvideUsd:c?.minProvideUsd})),this.registry.register(new un({pool:u})),this.registry.register(new pn),this.registry.register(new mn)}if((o||r)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new Qt(e.llm)),r&&e.subgraph!==!1){let c=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new hn(c)),this.registry.register(new gn(c)),this.registry.register(new fn(c)),this.registry.register(new yn(c)),this.registry.register(new bn(c)),this.registry.register(new wn(c)),this.registry.register(new kn(c))}if(e.subagents?.["wallet-action"]!==!1){let c=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{},d=e.noFormTools,u=p=>Lo(this.registry,p,d);u(new An(c)),u(new Sn(c)),u(new _n(c)),u(new Pn(c)),u(new xn(c,{debug:this.debug})),u(new Cn(c,{debug:this.debug}))}this.router=new Un(this.llm,{debug:this.debug}),this.rewriter=new Wo(this.llm,{debug:this.debug});let i=typeof e.subgraph=="object"?e.subgraph:void 0,l=Vo(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:i?.linkAddLiquidity},e.subagents);this.subagents=new Map(l.map(c=>[c.name,c])),this.chatGraph=ma(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let t of e)this.registry.register(t)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,t,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:Ln()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,timestamp:Date.now()});let s=await this.registry.execute(e,t,this.userContext),i=s.data,l=s.success?i?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,c=Ln(),d=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],u={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return d.length>0&&(u.uiActions=d),this.history.add(u),await this.persistHistory(),{answer:l,messageId:c,...d.length>0?{uiActions:d}:{}}}async runTool(e,t,n){this.assertLicense(),await this.loadHistory();let r=Ln();if(!this.registry.has(e))return{answer:`Unknown tool: "${e}".`,messageId:r};this.debug&&console.log(`[AgentCore] runTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage?.trim()||`[run ${e}]`,s=typeof n?.language=="string"&&n.language.trim()?n.language.trim():null,i=Array.from(this.subagents.values()).filter(m=>m.ownsTool(e)).map(m=>m.name),l=i.length>0?i:["direct"],c=new AbortController;this.currentAbortController=c;let{signal:d,cleanup:u}=pr(c,n?.signal);this.llm.setRequestSignal?.(d),Mn(d);let p=this.history.serialise();try{this.history.add({role:"user",content:o,timestamp:Date.now()});let m=await this.registry.execute(e,t,{...this.userContext,query:o});Vn(d);let f=m.success?JSON.stringify(m.data):`Error: ${m.error}`,h=Date.now(),g=[{subagentName:l[0],steps:[{phase:"act",content:`Calling tool: ${e}`,toolCall:{toolName:e,args:t},timestamp:h},{phase:"observe",content:f,toolResult:m,timestamp:h}],finalAnswer:"",toolResults:[m],toolMessages:[]}],y=this.mergeTrace(g),b=await this.synthesizer.synthesise(o,y,this.synthesiserHistory(),s??void 0),w=Go(b,g),k=this.collectUiActions(g,s),T=this.collectActionButtons(g,s);return{...await this.finaliseAnswer({userMessage:o,answer:w,subagents:l,uiActions:k,actionButtons:T,messageId:r}),messageId:r,trace:y,subagentResults:g,...k.length>0?{uiActions:k}:{},...T.length>0?{actionButtons:T}:{}}}catch(m){throw ut(m)||d.aborted?(this.history.restore(p),new Ke):(this.history.restore(p),m)}finally{u(),this.llm.setRequestSignal?.(void 0),Mn(void 0),this.currentAbortController===c&&(this.currentAbortController=null)}}setX402Signer(e){this.x402Signer=e,Fr(e?dr({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,t,n){this.assertLicense(),await this.loadHistory();let r=Ln(),o=e,s=n?.userQuery||o?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let i;try{i=await cr(x,o,t)}catch(c){let u=`The payment couldn't be completed: ${c instanceof Error?c.message:String(c)}. Please try again.`;return this.history.add({role:"assistant",content:u,timestamp:Date.now(),messageId:r}),await this.persistHistory(),{answer:u,messageId:r}}return{...await this.synthesizeFromPaidData(s,i,r),messageId:r}}async synthesizeFromPaidData(e,t,n){let r=typeof t=="string"?t:JSON.stringify(t),o=this.systemPrompt+this.capabilitiesSummary(),s=`The user's question was: "${e}".
1030
1030
 
1031
1031
  A paid API returned this data:
1032
1032
  ${r}
1033
1033
 
1034
1034
  Answer the user's question using ONLY this data, in the user's language. Be concise. Do NOT mention APIs, payments, tools, or that the data came from anywhere.`,i=await this.llm.chat([{role:"system",content:o,timestamp:0},{role:"user",content:s,timestamp:Date.now()}],void 0,{});return await this.finaliseAnswer({userMessage:e,answer:i.text,messageId:n})}registerSubagent(e){this.subagents.set(e.name,e)}unregisterSubagent(e){return this.subagents.delete(e)}listSubagents(){return Array.from(this.subagents.keys())}setKnowledgeBase(e){this.kbEntries.setEntries(e),this.vectorKBAutoIngested=!1}addKnowledgeBase(e){this.kbEntries.addEntries(e),this.vectorKBAutoIngested=!1}async ingestKnowledgeBase(){if(!this.vectorKB)return{count:0};let e=this.kbEntries.getEntries();if(e.length===0)return{count:0};let t=await this.vectorKB.upsert(e);return this.vectorKBAutoIngested=!0,t}async maybeAutoIngest(e){if(!(!e||!this.vectorKB||this.vectorKBAutoIngested)){if(this.vectorKBAutoIngestPromise)return this.vectorKBAutoIngestPromise;this.vectorKBAutoIngestPromise=(async()=>{try{let{count:t}=await this.ingestKnowledgeBase();this.debug&&t>0&&console.log(`[AgentCore] auto-ingested ${t} KB entr${t===1?"y":"ies"} to vector store`)}catch(t){this.debug&&console.warn("[AgentCore] auto-ingest failed:",t)}finally{this.vectorKBAutoIngestPromise=null}})(),await this.vectorKBAutoIngestPromise}}setUserContext(e){this.userContext={...e}}getUserContext(){return{...this.userContext}}async loadHistory(){if(!this.historyLoaded){if(this.historyLoadingPromise)return this.historyLoadingPromise;this.historyLoadingPromise=this._doLoadHistory(),await this.historyLoadingPromise}}async _doLoadHistory(){if(!this.storage){this.debug&&console.log("[AgentCore] loadHistory: no storage configured"),this.historyLoaded=!0;return}if(!this.persistHistoryEnabled){this.debug&&console.log("[AgentCore] loadHistory: persistHistory disabled \u2014 starting fresh session");try{await this.storage.removeItem(this.storageKey)}catch(e){this.debug&&console.warn("[AgentCore] failed to clear stale history:",e)}this.historyLoaded=!0;return}try{let e=await this.storage.getItem(this.storageKey);if(this.debug&&console.log(`[AgentCore] loadHistory: storage key "${this.storageKey}" ${e?`has ${e.length} chars`:"is empty"}`),e){let t=JSON.parse(e);this.history.restore(t),this.debug&&console.log(`[AgentCore] Restored ${this.history.length} messages from storage`)}}catch(e){this.debug&&console.warn("[AgentCore] Failed to load history from storage:",e)}finally{this.historyLoaded=!0}}async persistHistory(){if(this.storage&&this.persistHistoryEnabled)try{let e=JSON.stringify(this.history.serialise());await this.storage.setItem(this.storageKey,e)}catch(e){this.debug&&console.warn("[AgentCore] Failed to persist history to storage:",e)}}assertLicense(){if(this.licenseChecked)return;if(this.ownGeminiKey){this.licenseChecked=!0;return}let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,ha.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey. Pass a valid secretKey to use the Keyring Gemini proxy, or supply your own Gemini key via llm.apiKey to call the Gemini API directly.");this.licenseChecked=!0}async chat(e,t){this.assertLicense();let n=typeof t?.language=="string"&&t.language.trim()?t.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let r=Date.now();this.debug&&(console.log(`
1035
- ${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let o=new AbortController;this.currentAbortController=o;let{signal:s,cleanup:i}=pr(o,t?.signal);this.llm.setRequestSignal?.(s),Mn(s);let l=this.history.serialise(),c=this.chatGraph.invoke({userMessage:e,overrideLang:n},{signal:s});this.inFlightTurn=c;let u;try{u=await c}catch(d){throw ut(d)||s.aborted?(this.history.restore(l),new Ke):d}finally{i(),this.llm.setRequestSignal?.(void 0),Mn(void 0),this.currentAbortController===o&&(this.currentAbortController=null),this.inFlightTurn===c&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-r}ms total`),console.log(`${"\u2500".repeat(60)}
1036
- `)),u.response??{answer:"",messageId:Ln()}}stop(){this.currentAbortController?.abort()}isBusy(){return this.inFlightTurn!==null}createGraphHost(){return{debug:this.debug,addUserMessage:e=>this.addUserMessage(e),needsSummary:()=>this.history.needsSummary(),compactHistory:()=>this.compactHistory(),conversationForTurn:()=>{let e=this.history.getConversation();return e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e},lastAssistantSubagents:e=>ia(e),generateMessageId:()=>Ln(),rewrite:(e,t,n)=>this.rewriter.rewrite(e,t,n),searchKB:e=>this.searchKB(e),formatKBContext:e=>this.formatKBContext(e),tryAnswerFromKB:(e,t,n,r)=>this.tryAnswerFromKB(e,t,n,r),subagentCards:()=>Array.from(this.subagents.values()).map(e=>e.getCard()),route:(e,t,n,r)=>this.router.route(e,t,n,this.userContext,r),connectedChain:()=>this.userContext.chain,answerUnsupportedChain:(e,t,n,r)=>this.answerUnsupportedChain(e,t,n,r),answerDirectly:(e,t,n,r,o)=>this.answerDirectly(e,t,n,r,o),runSubagent:async(e,t,n)=>{let r=this.subagents.get(e.subagent);if(!r)return this.debug&&console.log(`[AgentCore] WARN: subagent "${e.subagent}" not registered`),{subagentName:e.subagent,steps:[],finalAnswer:`Subagent "${e.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let o=Date.now(),s=await r.run({query:e.query,reasoning:e.reasoning,language:n},t,this.userContext);if(this.debug){let i=s.toolResults.map(l=>l.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-o}ms | tools: ${i}`)}return s},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>this.synthesiserHistory(),mergeTrace:e=>this.mergeTrace(e),synthesise:(e,t,n,r)=>this.synthesizer.synthesise(e,t,n,r),collectUiActions:(e,t)=>this.collectUiActions(e,t),collectActionButtons:(e,t)=>this.collectActionButtons(e,t),finaliseAnswer:e=>this.finaliseAnswer(e)}}capitalizeFirst(e){if(!e)return e;let t=Array.from(e);return t[0]=t[0].toLocaleUpperCase(),t.join("")}collectActionButtons(e,t){let n=new Map,r=[];for(let o of e)for(let s of o.toolResults)if(!(!s.success||!Array.isArray(s.actionButtons)))for(let i of s.actionButtons){if(!i||typeof i!="object"||typeof i.label!="string"||!i.label.trim()||typeof i.prompt!="string"||!i.prompt.trim())continue;let l=this.capitalizeFirst(i.prompt),c={label:i.label,prompt:l,...t?{language:t}:{}},u=n.get(l);u?c.label.length>u.label.length&&n.set(l,c):(n.set(l,c),r.push(l))}return r.map(o=>n.get(o))}collectUiActions(e,t){let n=[];for(let r of e)for(let o of r.toolResults)o.success&&o.ui&&typeof o.ui=="object"&&typeof o.ui.component=="string"&&n.push(this.stampLanguage(o.ui,t));if(this.debug&&n.length>0){let r=n.map(o=>`${o.component}=${o.language}`).join(", ");console.log(`[AgentCore] uiActions stamped (rewrite.language="${t??""}"): ${r}`)}return n}stampLanguage(e,t){return!t||e.language?e:{...e,language:t}}addUserMessage(e){this.history.add({role:"user",content:e,timestamp:Date.now()})}async searchKB(e){let t=this.vectorKB?await this.vectorKB.search(e,void 0,{applyMinScore:!1}):await this.kb.search(e);if(this.debug)if(t.length===0)console.log(`[AgentCore] KB no hits for "${e}"`);else{let n=t.slice(0,3).map(r=>`${r.score.toFixed(3)} ${this.snippet(r.entry.question,60)}`).join(" | ");console.log(`[AgentCore] KB hits (${t.length}): ${n}`)}return t}snippet(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}formatKBContext(e){let t=e.filter(n=>n.score>=this.kbAnswerThreshold);return t.length===0?"":t.map((n,r)=>`[Reference ${r+1}]
1035
+ ${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let o=new AbortController;this.currentAbortController=o;let{signal:s,cleanup:i}=pr(o,t?.signal);this.llm.setRequestSignal?.(s),Mn(s);let l=this.history.serialise(),c=this.chatGraph.invoke({userMessage:e,overrideLang:n},{signal:s});this.inFlightTurn=c;let d;try{d=await c}catch(u){throw ut(u)||s.aborted?(this.history.restore(l),new Ke):u}finally{i(),this.llm.setRequestSignal?.(void 0),Mn(void 0),this.currentAbortController===o&&(this.currentAbortController=null),this.inFlightTurn===c&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-r}ms total`),console.log(`${"\u2500".repeat(60)}
1036
+ `)),d.response??{answer:"",messageId:Ln()}}stop(){this.currentAbortController?.abort()}isBusy(){return this.inFlightTurn!==null}createGraphHost(){return{debug:this.debug,addUserMessage:e=>this.addUserMessage(e),needsSummary:()=>this.history.needsSummary(),compactHistory:()=>this.compactHistory(),conversationForTurn:()=>{let e=this.history.getConversation();return e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e},lastAssistantSubagents:e=>ia(e),generateMessageId:()=>Ln(),rewrite:(e,t,n)=>this.rewriter.rewrite(e,t,n),searchKB:e=>this.searchKB(e),formatKBContext:e=>this.formatKBContext(e),tryAnswerFromKB:(e,t,n,r)=>this.tryAnswerFromKB(e,t,n,r),subagentCards:()=>Array.from(this.subagents.values()).map(e=>e.getCard()),route:(e,t,n,r)=>this.router.route(e,t,n,this.userContext,r),connectedChain:()=>this.userContext.chain,answerUnsupportedChain:(e,t,n,r)=>this.answerUnsupportedChain(e,t,n,r),answerDirectly:(e,t,n,r,o)=>this.answerDirectly(e,t,n,r,o),runSubagent:async(e,t,n)=>{let r=this.subagents.get(e.subagent);if(!r)return this.debug&&console.log(`[AgentCore] WARN: subagent "${e.subagent}" not registered`),{subagentName:e.subagent,steps:[],finalAnswer:`Subagent "${e.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let o=Date.now(),s=await r.run({query:e.query,reasoning:e.reasoning,language:n},t,this.userContext);if(this.debug){let i=s.toolResults.map(l=>l.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-o}ms | tools: ${i}`)}return s},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>this.synthesiserHistory(),mergeTrace:e=>this.mergeTrace(e),synthesise:(e,t,n,r)=>this.synthesizer.synthesise(e,t,n,r),collectUiActions:(e,t)=>this.collectUiActions(e,t),collectActionButtons:(e,t)=>this.collectActionButtons(e,t),finaliseAnswer:e=>this.finaliseAnswer(e)}}capitalizeFirst(e){if(!e)return e;let t=Array.from(e);return t[0]=t[0].toLocaleUpperCase(),t.join("")}collectActionButtons(e,t){let n=new Map,r=[];for(let o of e)for(let s of o.toolResults)if(!(!s.success||!Array.isArray(s.actionButtons)))for(let i of s.actionButtons){if(!i||typeof i!="object"||typeof i.label!="string"||!i.label.trim()||typeof i.prompt!="string"||!i.prompt.trim())continue;let l=this.capitalizeFirst(i.prompt),c={label:i.label,prompt:l,...t?{language:t}:{}},d=n.get(l);d?c.label.length>d.label.length&&n.set(l,c):(n.set(l,c),r.push(l))}return r.map(o=>n.get(o))}collectUiActions(e,t){let n=[];for(let r of e)for(let o of r.toolResults)o.success&&o.ui&&typeof o.ui=="object"&&typeof o.ui.component=="string"&&n.push(this.stampLanguage(o.ui,t));if(this.debug&&n.length>0){let r=n.map(o=>`${o.component}=${o.language}`).join(", ");console.log(`[AgentCore] uiActions stamped (rewrite.language="${t??""}"): ${r}`)}return n}stampLanguage(e,t){return!t||e.language?e:{...e,language:t}}addUserMessage(e){this.history.add({role:"user",content:e,timestamp:Date.now()})}async searchKB(e){let t=this.vectorKB?await this.vectorKB.search(e,void 0,{applyMinScore:!1}):await this.kb.search(e);if(this.debug)if(t.length===0)console.log(`[AgentCore] KB no hits for "${e}"`);else{let n=t.slice(0,3).map(r=>`${r.score.toFixed(3)} ${this.snippet(r.entry.question,60)}`).join(" | ");console.log(`[AgentCore] KB hits (${t.length}): ${n}`)}return t}snippet(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}formatKBContext(e){let t=e.filter(n=>n.score>=this.kbAnswerThreshold);return t.length===0?"":t.map((n,r)=>`[Reference ${r+1}]
1037
1037
  Q: ${n.entry.question}
1038
1038
  A: ${n.entry.answer}`).join(`
1039
1039
 
@@ -1055,7 +1055,7 @@ Answer "no" if, for EVERY FAQ question, ANY of these hold:
1055
1055
  ${i}
1056
1056
  User message: "${e}"
1057
1057
 
1058
- Is the user message EQUIVALENT to AT LEAST ONE of the FAQ questions \u2014 asking the same thing such that that FAQ's answer fully answers the user message? Answer "yes" only if equivalent to one of them, otherwise "no".`,timestamp:Date.now()}],u=(await this.llm.chat(l,void 0,{maxOutputTokens:16})).text.trim().toLowerCase();if(!u.startsWith("yes"))return this.debug&&console.log(`[AgentCore] KB intent guard: verdict="${u}" \u2192 skipping KB, routing to subagent pipeline`),null;this.debug&&console.log('[AgentCore] KB intent guard: verdict="yes" \u2192 answering from KB');let d=[{role:"system",content:this.systemPrompt+`
1058
+ Is the user message EQUIVALENT to AT LEAST ONE of the FAQ questions \u2014 asking the same thing such that that FAQ's answer fully answers the user message? Answer "yes" only if equivalent to one of them, otherwise "no".`,timestamp:Date.now()}],d=(await this.llm.chat(l,void 0,{maxOutputTokens:16})).text.trim().toLowerCase();if(!d.startsWith("yes"))return this.debug&&console.log(`[AgentCore] KB intent guard: verdict="${d}" \u2192 skipping KB, routing to subagent pipeline`),null;this.debug&&console.log('[AgentCore] KB intent guard: verdict="yes" \u2192 answering from KB');let u=[{role:"system",content:this.systemPrompt+`
1059
1059
 
1060
1060
  You have reference material below. Use it ONLY if it directly addresses the user's question. Rephrase and adapt the content naturally \u2014 do NOT copy it verbatim. Do NOT supplement with general knowledge or speculate beyond what the reference provides. If the reference does not fully answer the question, say so honestly.
1061
1061
 
@@ -1064,7 +1064,7 @@ REFERENCE MATERIAL:
1064
1064
  `+n+`
1065
1065
  ---`,timestamp:0},{role:"user",content:`${e}
1066
1066
 
1067
- (You MUST reply in the same language as the question above, regardless of the reference material language.)`,timestamp:Date.now()}],m=(await this.llm.chat(d)).text,f={role:"assistant",content:m,timestamp:Date.now()};return r&&(f.messageId=r),this.history.add(f),await this.persistHistory(),{answer:m}}capabilitiesSummary(){let e=new Set,t=[];for(let n of this.subagents.values()){let r=n.capability;!r||e.has(r)||(e.add(r),t.push(`- ${r}`))}return t.length===0?"":`
1067
+ (You MUST reply in the same language as the question above, regardless of the reference material language.)`,timestamp:Date.now()}],m=(await this.llm.chat(u)).text,f={role:"assistant",content:m,timestamp:Date.now()};return r&&(f.messageId=r),this.history.add(f),await this.persistHistory(),{answer:m}}capabilitiesSummary(){let e=new Set,t=[];for(let n of this.subagents.values()){let r=n.capability;!r||e.has(r)||(e.add(r),t.push(`- ${r}`))}return t.length===0?"":`
1068
1068
 
1069
1069
  CAPABILITIES: When the user asks what you can do or how you can help, describe these concrete abilities (in the user's language) instead of a generic answer:
1070
1070
  `+t.join(`
@@ -1079,9 +1079,9 @@ REFERENCE MATERIAL:
1079
1079
  `+n+`
1080
1080
  ---`:this.systemPrompt)+this.capabilitiesSummary()+s+`
1081
1081
 
1082
- REMINDER: If this query is about a restricted topic (weather, geography, the academic subject of history, entertainment, sports, politics, or physics/chemistry/literature/art), you MUST refuse with one short sentence as instructed \u2014 even if web search returned an answer. NEVER answer a restricted-topic question from search results.`,c=qe(t),u=[{role:"system",content:l,timestamp:0},...c,{role:"user",content:e,timestamp:Date.now()}],d=await this.llm.chat(u,void 0,{googleSearch:o});return await this.finaliseAnswer({userMessage:e,answer:d.text,messageId:r})}async answerUnsupportedChain(e,t,n,r){this.debug&&console.log(`[AgentCore] connected chain "${e}" is not supported \u2192 short-circuit with notice`);let o=(t||"").trim(),s=r&&r.trim()||At,i=[{role:"system",content:`Write ONE short, polite message telling the user that the blockchain network they want to use is NOT supported by this assistant, and inviting them to use one of the supported networks. List the supported networks: ${s}. Use ONLY the network NAMES \u2014 NEVER show any hex chain id (e.g. never write "0x1" or "(0xa)"). Do NOT mention or guess the name or chain id of the unsupported network. `+(o?`Reply in BCP-47 language "${o}".`:"Reply in the same language the user has been using.")+" Do NOT mention tools or internal implementation details.",timestamp:0},{role:"user",content:"Is my currently connected network supported?",timestamp:Date.now()}],c=(await this.llm.chat(i)).text?.trim()||`Your currently connected network is not supported yet. Supported networks: ${s}.`;return await this.finaliseAnswer({userMessage:`[unsupported chain: ${e}]`,answer:c,messageId:n})}synthesiserHistory(){let e=this.history.getConversation(),t=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return qe(t)}mergeTrace(e){let t=[];for(let r of e)t.push({phase:"think",content:`[${r.subagentName}] begin`,timestamp:Date.now()}),t.push(...r.steps),t.push({phase:"observe",content:`[${r.subagentName}] answer: ${r.finalAnswer}`,timestamp:Date.now()});let n=e.map(r=>`[${r.subagentName}] ${r.finalAnswer}`).join(`
1082
+ REMINDER: If this query is about a restricted topic (weather, geography, the academic subject of history, entertainment, sports, politics, or physics/chemistry/literature/art), you MUST refuse with one short sentence as instructed \u2014 even if web search returned an answer. NEVER answer a restricted-topic question from search results.`,c=qe(t),d=[{role:"system",content:l,timestamp:0},...c,{role:"user",content:e,timestamp:Date.now()}],u=await this.llm.chat(d,void 0,{googleSearch:o});return await this.finaliseAnswer({userMessage:e,answer:u.text,messageId:r})}async answerUnsupportedChain(e,t,n,r){this.debug&&console.log(`[AgentCore] connected chain "${e}" is not supported \u2192 short-circuit with notice`);let o=(t||"").trim(),s=r&&r.trim()||At,i=[{role:"system",content:`Write ONE short, polite message telling the user that the blockchain network they want to use is NOT supported by this assistant, and inviting them to use one of the supported networks. List the supported networks: ${s}. Use ONLY the network NAMES \u2014 NEVER show any hex chain id (e.g. never write "0x1" or "(0xa)"). Do NOT mention or guess the name or chain id of the unsupported network. `+(o?`Reply in BCP-47 language "${o}".`:"Reply in the same language the user has been using.")+" Do NOT mention tools or internal implementation details.",timestamp:0},{role:"user",content:"Is my currently connected network supported?",timestamp:Date.now()}],c=(await this.llm.chat(i)).text?.trim()||`Your currently connected network is not supported yet. Supported networks: ${s}.`;return await this.finaliseAnswer({userMessage:`[unsupported chain: ${e}]`,answer:c,messageId:n})}synthesiserHistory(){let e=this.history.getConversation(),t=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return qe(t)}mergeTrace(e){let t=[];for(let r of e)t.push({phase:"think",content:`[${r.subagentName}] begin`,timestamp:Date.now()}),t.push(...r.steps),t.push({phase:"observe",content:`[${r.subagentName}] answer: ${r.finalAnswer}`,timestamp:Date.now()});let n=e.map(r=>`[${r.subagentName}] ${r.finalAnswer}`).join(`
1083
1083
 
1084
- `);return{steps:t,finalAnswer:n}}async finaliseAnswer(e){let{answer:t,subagents:n,uiActions:r,actionButtons:o,messageId:s}=e??{},i={role:"assistant",content:t,timestamp:Date.now()};return n&&n.length>0&&(i.subagents=n),r&&r.length>0&&(i.uiActions=r),o&&o.length>0&&(i.actionButtons=o),s&&(i.messageId=s),this.history.add(i),await this.persistHistory(),{answer:t,...o&&o.length>0?{actionButtons:o}:{}}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),t=6,n=0,r=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(n++,n>=t)){r=p;break}let o=e.slice(r),s=aa(o,o.length),i=e.length-s.length,l=qe(e.slice(0,i)),c=this.history.getSummary(),u=[];c&&u.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),u.push(...l);let d=await this.summarizer.summarize(u);this.history.compactWith(d,s)}persistToolMessages(e){for(let t of e)t.toolMessages.length>0&&(this.history.addMany(t.toolMessages),this.history.add({role:"assistant",content:t.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${t.toolMessages.length} tool message(s) + finalAnswer from ${t.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};var tu="Every domain you analyze is the website of a service that integrates WalletConnect \u2014 i.e. a blockchain / Web3 application (DeFi, DEX, NFT marketplace, bridge, wallet, staking, launchpad, GameFi, etc.). Investigate it WITHIN that crypto/Web3 ecosystem FIRST: assume any brand it resembles is most likely a crypto/blockchain project, look up that brand's official domains within that ecosystem, and prioritize crypto-focused phishing/scam intelligence. This is a strong prior, NOT a guarantee \u2014 if the evidence shows it actually imitates a major NON-crypto brand or is a plain scam, still flag it. NEVER assume a domain is legitimate merely because it sits in the crypto space.",ga='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',jo=class{llm;debug;ecosystem;constructor(e={}){this.llm=e.provider??new z({temperature:.5,...e.llm}),this.debug=e.debug??!1,this.ecosystem=e.ecosystemContext?.trim()||tu}async chat(e){let t=(e?.url??"").trim();if(!t)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(t),r=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let{description:m,keyFeatures:f}=await this.describeOfficial(t,o),{answer:h,keyFeatures:g}=await this.present(n,{isPhishing:!1,description:m,reasons:[],keyFeatures:f},r,o),y={currentSite:t,isPhishing:!1};return g.length>0&&(y.keyFeatures=g),{answer:h,extraData:y}}let s=await this.investigate(t,n,o),i=this.buildVerdict(n,s),l=s.keyFeatures;!i.isPhishing&&l.length===0&&(l=await this.gatherKeyFeatures(t,o)),this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",n),console.log("[WebsiteTrustKeyringAgent] investigation:",s),console.log("[WebsiteTrustKeyringAgent] verdict:",i),console.log("[WebsiteTrustKeyringAgent] keyFeaturesEvidence:",l));let{answer:c,reasons:u,keyFeatures:d}=await this.present(n,{isPhishing:i.isPhishing,description:s.description,copiedSite:i.copiedSite,reasons:i.reasons,keyFeatures:l},r,o),p={currentSite:t,isPhishing:i.isPhishing};return i.copiedSite&&(p.copiedSite=i.copiedSite),i.isPhishing&&u.length>0&&(p.reasons=u),!i.isPhishing&&d.length>0&&(p.keyFeatures=d),{answer:c,extraData:p}}catch(s){throw new Error(`WebsiteTrustKeyringAgent.chat failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}buildVerdict(e,t){let n=t.officialDomain,r=n?t.affiliatedDomains.filter(f=>!this.looksLikeSquatOf(f,n)):t.affiliatedDomains,o=[t.officialDomain,...r].filter(f=>!!f),s=o.length>0?o.some(f=>this.isSameRegistrableDomain(e,f)):t.exactMatchOfficial,l=(t.resemblesBrand||this.carriesBrandName(e,t.officialDomain,t.brand))&&!s&&t.brandIsWellKnown&&(o.length>0||!t.hasOwnLegitPresence),u=!(s||t.hasOwnLegitPresence&&!l)&&t.scamReports.length>0,d=l||u;if(!d)return{isPhishing:!1,reasons:[]};let p=[];if(l){let f=t.officialDomain?this.describeLookAlike(e,t.officialDomain):void 0;f&&p.push(f),t.impersonationEvidence.length>0?p.push(...t.impersonationEvidence):f||p.push(t.officialDomain?`This address (${e}) is not the official ${t.brand??"brand"} domain \u2014 the real one is ${t.officialDomain}; the look-alike is easy to miss at a glance.`:`This domain (${e}) imitates ${t.brand??"a known brand"} but is not its official site and has no legitimate presence of its own.`)}u&&p.push(...t.scamReports);let m=l?t.officialUrl??t.officialDomain??t.brand:void 0;return{isPhishing:d,copiedSite:m,reasons:this.dedupe(p)}}async investigate(e,t,n){let r=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${t}
1084
+ `);return{steps:t,finalAnswer:n}}async finaliseAnswer(e){let{answer:t,subagents:n,uiActions:r,actionButtons:o,messageId:s}=e??{},i={role:"assistant",content:t,timestamp:Date.now()};return n&&n.length>0&&(i.subagents=n),r&&r.length>0&&(i.uiActions=r),o&&o.length>0&&(i.actionButtons=o),s&&(i.messageId=s),this.history.add(i),await this.persistHistory(),{answer:t,...o&&o.length>0?{actionButtons:o}:{}}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),t=6,n=0,r=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(n++,n>=t)){r=p;break}let o=e.slice(r),s=aa(o,o.length),i=e.length-s.length,l=qe(e.slice(0,i)),c=this.history.getSummary(),d=[];c&&d.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),d.push(...l);let u=await this.summarizer.summarize(d);this.history.compactWith(u,s)}persistToolMessages(e){for(let t of e)t.toolMessages.length>0&&(this.history.addMany(t.toolMessages),this.history.add({role:"assistant",content:t.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${t.toolMessages.length} tool message(s) + finalAnswer from ${t.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};var tu="Every domain you analyze is the website of a service that integrates WalletConnect \u2014 i.e. a blockchain / Web3 application (DeFi, DEX, NFT marketplace, bridge, wallet, staking, launchpad, GameFi, etc.). Investigate it WITHIN that crypto/Web3 ecosystem FIRST: assume any brand it resembles is most likely a crypto/blockchain project, look up that brand's official domains within that ecosystem, and prioritize crypto-focused phishing/scam intelligence. This is a strong prior, NOT a guarantee \u2014 if the evidence shows it actually imitates a major NON-crypto brand or is a plain scam, still flag it. NEVER assume a domain is legitimate merely because it sits in the crypto space.",ga='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',jo=class{llm;debug;ecosystem;constructor(e={}){this.llm=e.provider??new z({temperature:.5,...e.llm}),this.debug=e.debug??!1,this.ecosystem=e.ecosystemContext?.trim()||tu}async chat(e){let t=(e?.url??"").trim();if(!t)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(t),r=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let{description:m,keyFeatures:f}=await this.describeOfficial(t,o),{answer:h,keyFeatures:g}=await this.present(n,{isPhishing:!1,description:m,reasons:[],keyFeatures:f},r,o),y={currentSite:t,isPhishing:!1};return g.length>0&&(y.keyFeatures=g),{answer:h,extraData:y}}let s=await this.investigate(t,n,o),i=this.buildVerdict(n,s),l=s.keyFeatures;!i.isPhishing&&l.length===0&&(l=await this.gatherKeyFeatures(t,o)),this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",n),console.log("[WebsiteTrustKeyringAgent] investigation:",s),console.log("[WebsiteTrustKeyringAgent] verdict:",i),console.log("[WebsiteTrustKeyringAgent] keyFeaturesEvidence:",l));let{answer:c,reasons:d,keyFeatures:u}=await this.present(n,{isPhishing:i.isPhishing,description:s.description,copiedSite:i.copiedSite,reasons:i.reasons,keyFeatures:l},r,o),p={currentSite:t,isPhishing:i.isPhishing};return i.copiedSite&&(p.copiedSite=i.copiedSite),i.isPhishing&&d.length>0&&(p.reasons=d),!i.isPhishing&&u.length>0&&(p.keyFeatures=u),{answer:c,extraData:p}}catch(s){throw new Error(`WebsiteTrustKeyringAgent.chat failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}buildVerdict(e,t){let n=t.officialDomain,r=n?t.affiliatedDomains.filter(f=>!this.looksLikeSquatOf(f,n)):t.affiliatedDomains,o=[t.officialDomain,...r].filter(f=>!!f),s=o.length>0?o.some(f=>this.isSameRegistrableDomain(e,f)):t.exactMatchOfficial,l=(t.resemblesBrand||this.carriesBrandName(e,t.officialDomain,t.brand))&&!s&&t.brandIsWellKnown&&(o.length>0||!t.hasOwnLegitPresence),d=!(s||t.hasOwnLegitPresence&&!l)&&t.scamReports.length>0,u=l||d;if(!u)return{isPhishing:!1,reasons:[]};let p=[];if(l){let f=t.officialDomain?this.describeLookAlike(e,t.officialDomain):void 0;f&&p.push(f),t.impersonationEvidence.length>0?p.push(...t.impersonationEvidence):f||p.push(t.officialDomain?`This address (${e}) is not the official ${t.brand??"brand"} domain \u2014 the real one is ${t.officialDomain}; the look-alike is easy to miss at a glance.`:`This domain (${e}) imitates ${t.brand??"a known brand"} but is not its official site and has no legitimate presence of its own.`)}d&&p.push(...t.scamReports);let m=l?t.officialUrl??t.officialDomain??t.brand:void 0;return{isPhishing:u,copiedSite:m,reasons:this.dedupe(p)}}async investigate(e,t,n){let r=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${t}
1085
1085
  URL: ${e}
1086
1086
 
1087
1087
  Investigate, using web search, whether this EXACT domain is a legitimate official site or a phishing / look-alike / scam site. Work through:
@@ -1138,6 +1138,6 @@ Write the user-facing result for a NON-TECHNICAL user:
1138
1138
 
1139
1139
  LANGUAGE (MANDATORY): write "answer", every "reasons" item AND every "keyFeatures" item ENTIRELY in ${o}. The facts above are in English ONLY as source material \u2014 your output prose MUST be in ${o}, not English (unless ${o} itself is English). Only domain names, URLs, markdown links and brand names stay verbatim.
1140
1140
 
1141
- Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:r,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2,maxOutputTokens:1536}),u=this.cleanStr(c?.answer)??(t.description||e),d=this.cleanStrArray(c?.reasons),p=this.cleanStrArray(c?.keyFeatures);return{answer:u,reasons:d.length>0?d.slice(0,5):t.reasons.slice(0,5),keyFeatures:s?(p.length>0?p:t.keyFeatures).slice(0,5):[]}}languageLabel(e){let t={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return t[n]??t[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
1141
+ Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:r,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2,maxOutputTokens:1536}),d=this.cleanStr(c?.answer)??(t.description||e),u=this.cleanStrArray(c?.reasons),p=this.cleanStrArray(c?.keyFeatures);return{answer:d,reasons:u.length>0?u.slice(0,5):t.reasons.slice(0,5),keyFeatures:s?(p.length>0?p:t.keyFeatures).slice(0,5):[]}}languageLabel(e){let t={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return t[n]??t[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
1142
1142
 
1143
- ${ga}`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:o=ga,maxRetries:s=2,maxOutputTokens:i,thinkingBudget:l}=t,c=Date.now(),u=[{role:"system",content:o,timestamp:c},{role:"user",content:e,timestamp:c}],d=await this.llm.chat(u,void 0,{googleSearch:r,maxRetries:s,maxOutputTokens:i,thinkingBudget:l,signal:n}),p=this.parseJson(d.text?.trim()??"");return this.debug&&!p&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(d.text??"").slice(0,200)),p}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(t).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(t=>t.startsWith("xn--")?this.punycodeDecodeLabel(t.slice(4)):t).join("."):e}punycodeDecodeLabel(e){let c=(d,p,m)=>{d=m?Math.floor(d/700):d>>1,d+=Math.floor(d/p);let f=0;for(;d>455;)d=Math.floor(d/35),f+=36;return f+Math.floor(36*d/(d+38))},u=d=>d-48<10?d-22:d-65<26?d-65:d-97<26?d-97:36;try{let d=[],p=e.lastIndexOf("-");for(let y=0;y<Math.max(0,p);y++){let b=e.charCodeAt(y);if(b>=128)return e;d.push(b)}let m=0,f=128,h=72,g=p<0?0:p+1;for(;g<e.length;){let y=m,b=1;for(let k=36;;k+=36){if(g>=e.length)return e;let T=u(e.charCodeAt(g++));if(T>=36)return e;m+=T*b;let S=k<=h?1:k>=h+26?26:k-h;if(T<S)break;b*=36-S}let w=d.length+1;h=c(m-y,w,y===0),f+=Math.floor(m/w),m%=w,d.splice(m,0,f),m++}return String.fromCodePoint(...d)}catch{return e}}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(t=>this.alnum(t)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let o=Array.from({length:r+1},(s,i)=>i);for(let s=1;s<=n;s++){let i=[s];for(let l=1;l<=r;l++){let c=e[s-1]===t[l-1]?0:1;i[l]=Math.min(o[l]+1,i[l-1]+1,o[l-1]+c)}o=i}return o[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let o=this.hostLabels(e);return[t?this.brandCore(t):"",this.alnum(n??"")].filter(i=>i.length>=4).some(i=>r.includes(i)||o.some(l=>this.isNearMiss(l,i)))}looksLikeSquatOf(e,t){if(this.isSameRegistrableDomain(e,t))return!1;let n=this.brandCore(t);if(n.length<4)return!1;let r=this.hostLabels(e);return r.includes(n)?!1:r.some(o=>this.isNearMiss(o,n)||o.length>n.length&&o.includes(n))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),s=r.lastIndexOf(".");if(o>0&&s>0){let c=n.slice(0,o),u=r.slice(0,s),d=n.slice(o+1),p=r.slice(s+1);if(c===u&&d!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${d}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.brandCore(r),l=this.hostLabels(n).find(c=>this.isNearMiss(c,i));if(l){let c=this.editDistance(l,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let o=this.coerceToStr(r);o&&n.push(o)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let t=e,n=this.cleanStr(t.feature)??this.cleanStr(t.name)??this.cleanStr(t.title),r=this.cleanStr(t.description)??this.cleanStr(t.detail)??this.cleanStr(t.text)??this.cleanStr(t.value);return n&&r?n===r?n:`${n} \u2014 ${r}`:n||r?n??r:Object.values(t).map(s=>this.cleanStr(s)).filter(s=>!!s).join(" \u2014 ")||void 0}dedupe(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}};var nu=a=>{let e=JSON.parse(a),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((n,r)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${r} is missing "question" or "answer"`);return n})};async function fa(a,e){let t=a.entries??(a.json?nu(a.json):[]);return t.length===0?{count:0}:new nt(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,ManageLiquidityRedirectTool,MoralisService,NFC_AGENT_TOOL_NAMES,NFC_AMAZON_DEFAULT_DOMAIN,NFC_AMAZON_DOMAINS,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,NfcBuyTool,NfcInfoTool,NoFormTool,OpenAddLiquidityFormTool,POOL_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PreviewAddLiquidityTool,RelayAdapter,Router,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapServiceFactory,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UpstashKnowledgeBase,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletDefiSummaryTool,WalletHistoryTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustKeyringAgent,ZERO_ADDRESS,amazonDomainForLanguage,apiClient,buildChallenge,buildRangePresets,buildUniswapPoolUrl,clampTick,completeX402,configureSupportedChains,createAiAgent,createDefaultSubagents,createNfcAgent,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletAgent,createX402SignatureProvider,displayFromChallenge,encodeSignedHeader,ethCallAt,ethCallByChain,fetchTopMarketplaces,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getGatewayChains,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,isAbortError,isPaymentRequired,nfcAmazonSearchUrl,normaliseCountry,normalizePriceRangeToPool,priceToTick,readPaymentError,readPaymentRequired,readReceipt,registerMaybeNoForm,requestWithX402,resolveNfcShopLinks,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});
1143
+ ${ga}`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:o=ga,maxRetries:s=2,maxOutputTokens:i,thinkingBudget:l}=t,c=Date.now(),d=[{role:"system",content:o,timestamp:c},{role:"user",content:e,timestamp:c}],u=await this.llm.chat(d,void 0,{googleSearch:r,maxRetries:s,maxOutputTokens:i,thinkingBudget:l,signal:n}),p=this.parseJson(u.text?.trim()??"");return this.debug&&!p&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(u.text??"").slice(0,200)),p}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(t).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(t=>t.startsWith("xn--")?this.punycodeDecodeLabel(t.slice(4)):t).join("."):e}punycodeDecodeLabel(e){let c=(u,p,m)=>{u=m?Math.floor(u/700):u>>1,u+=Math.floor(u/p);let f=0;for(;u>455;)u=Math.floor(u/35),f+=36;return f+Math.floor(36*u/(u+38))},d=u=>u-48<10?u-22:u-65<26?u-65:u-97<26?u-97:36;try{let u=[],p=e.lastIndexOf("-");for(let y=0;y<Math.max(0,p);y++){let b=e.charCodeAt(y);if(b>=128)return e;u.push(b)}let m=0,f=128,h=72,g=p<0?0:p+1;for(;g<e.length;){let y=m,b=1;for(let k=36;;k+=36){if(g>=e.length)return e;let T=d(e.charCodeAt(g++));if(T>=36)return e;m+=T*b;let S=k<=h?1:k>=h+26?26:k-h;if(T<S)break;b*=36-S}let w=u.length+1;h=c(m-y,w,y===0),f+=Math.floor(m/w),m%=w,u.splice(m,0,f),m++}return String.fromCodePoint(...u)}catch{return e}}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(t=>this.alnum(t)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let o=Array.from({length:r+1},(s,i)=>i);for(let s=1;s<=n;s++){let i=[s];for(let l=1;l<=r;l++){let c=e[s-1]===t[l-1]?0:1;i[l]=Math.min(o[l]+1,i[l-1]+1,o[l-1]+c)}o=i}return o[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let o=this.hostLabels(e);return[t?this.brandCore(t):"",this.alnum(n??"")].filter(i=>i.length>=4).some(i=>r.includes(i)||o.some(l=>this.isNearMiss(l,i)))}looksLikeSquatOf(e,t){if(this.isSameRegistrableDomain(e,t))return!1;let n=this.brandCore(t);if(n.length<4)return!1;let r=this.hostLabels(e);return r.includes(n)?!1:r.some(o=>this.isNearMiss(o,n)||o.length>n.length&&o.includes(n))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),s=r.lastIndexOf(".");if(o>0&&s>0){let c=n.slice(0,o),d=r.slice(0,s),u=n.slice(o+1),p=r.slice(s+1);if(c===d&&u!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${u}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.brandCore(r),l=this.hostLabels(n).find(c=>this.isNearMiss(c,i));if(l){let c=this.editDistance(l,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let o=this.coerceToStr(r);o&&n.push(o)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let t=e,n=this.cleanStr(t.feature)??this.cleanStr(t.name)??this.cleanStr(t.title),r=this.cleanStr(t.description)??this.cleanStr(t.detail)??this.cleanStr(t.text)??this.cleanStr(t.value);return n&&r?n===r?n:`${n} \u2014 ${r}`:n||r?n??r:Object.values(t).map(s=>this.cleanStr(s)).filter(s=>!!s).join(" \u2014 ")||void 0}dedupe(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}};var nu=a=>{let e=JSON.parse(a),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((n,r)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${r} is missing "question" or "answer"`);return n})};async function fa(a,e){let t=a.entries??(a.json?nu(a.json):[]);return t.length===0?{count:0}:new nt(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,ManageLiquidityRedirectTool,MoralisService,NFC_AGENT_TOOL_NAMES,NFC_AMAZON_DEFAULT_DOMAIN,NFC_AMAZON_DOMAINS,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,NfcBuyTool,NfcInfoTool,NoFormTool,OpenAddLiquidityFormTool,POOL_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PreviewAddLiquidityTool,RelayAdapter,Router,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapServiceFactory,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UpstashKnowledgeBase,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletDefiSummaryTool,WalletHistoryTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustKeyringAgent,ZERO_ADDRESS,amazonDomainForLanguage,apiClient,buildChallenge,buildRangePresets,buildUniswapPoolUrl,clampTick,completeX402,configureSupportedChains,createAiAgent,createDefaultSubagents,createNfcAgent,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletAgent,createX402SignatureProvider,displayFromChallenge,encodeSignedHeader,ethCallAt,ethCallByChain,fetchTopMarketplaces,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getGatewayChains,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,isAbortError,isPaymentRequired,nfcAmazonSearchUrl,normaliseCountry,normalizePriceRangeToPool,priceToTick,readPaymentError,readPaymentRequired,readReceipt,registerMaybeNoForm,requestWithX402,resolveNfcShopLinks,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});