keyring-agent-core 0.2.24 → 0.2.26

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,29 +1,29 @@
1
- "use strict";var dr=Object.create;var gn=Object.defineProperty;var mr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var hr=Object.getPrototypeOf,gr=Object.prototype.hasOwnProperty;var fr=(c,e)=>{for(var t in e)gn(c,t,{get:e[t],enumerable:!0})},po=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pr(e))!gr.call(c,r)&&r!==t&&gn(c,r,{get:()=>e[r],enumerable:!(n=mr(e,r))||n.enumerable});return c};var yr=(c,e,t)=>(t=c!=null?dr(hr(c)):{},po(e||!c||!c.__esModule?gn(t,"default",{value:c,enumerable:!0}):t,c)),br=c=>po(gn({},"__esModule",{value:!0}),c);var Na={};fr(Na,{AI_AGENT_TOOL_NAMES:()=>Fn,AgentCore:()=>Yn,ApproveTokenTool:()=>Ft,BaseNftAiTool:()=>fe,BaseNftMessageTool:()=>ct,BaseSwapService:()=>Ue,BaseTool:()=>T,BaseWalletActionTool:()=>le,BuyTokenTool:()=>Ht,ChatHistory:()=>Kt,DEFAULT_CHAIN:()=>ge,DEFAULT_PROVIDER:()=>rn,DEFAULT_RPC_BY_CHAIN:()=>ie,DebridgeAdapter:()=>St,EstimatePoolYieldTool:()=>Ct,GeminiProvider:()=>ne,GeminiSearchAiTool:()=>pt,HEX_TO_PANTOGRAPH:()=>Uo,KnowledgeBase:()=>zt,MoralisService:()=>R,NFTContractInfoTool:()=>dt,NFTMetadataTool:()=>mt,NFT_AGENT_TOOL_NAMES:()=>qn,OpenAddLiquidityFormTool:()=>Pt,POOL_AGENT_TOOL_NAMES:()=>$n,PantographService:()=>te,PoolByAddressTool:()=>bt,PoolDetailTool:()=>ft,PoolFallbackAiTool:()=>ht,PoolSearchTool:()=>yt,PoolService:()=>Oe,PreviewAddLiquidityTool:()=>_t,RelayAdapter:()=>At,Router:()=>Qt,SUPPORTED_CHAINS:()=>$e,SUPPORTED_CHAINS_LABEL:()=>Ne,SWAP_PROVIDER_CONFIG:()=>Un,SendNativeTool:()=>Mt,SendNftTool:()=>Yt,SendTokenTool:()=>qt,Subagent:()=>j,SubgraphAddPoolTool:()=>Dt,SubgraphCoinPoolPairsTool:()=>Lt,SubgraphPoolByAddressTool:()=>Rt,SubgraphPoolByPositionIdTool:()=>Nt,SubgraphPoolSearchTool:()=>Et,SubgraphPositionDetailTool:()=>It,SubgraphTrendingPoolsTool:()=>Ut,Summarizer:()=>jt,SwapServiceFactory:()=>De,SwapTokenTool:()=>Gt,Synthesizer:()=>Xt,TOKEN_AGENT_TOOL_NAMES:()=>Mn,TRANSFER_TOPIC:()=>zo,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Ro,TokenAnalyticsTool:()=>je,TokenHoldersTool:()=>Ke,TokenInfoTool:()=>Ye,TokenScoreTool:()=>ze,ToolRegistry:()=>Fe,TopGainersTool:()=>Xe,TopPoolsTool:()=>gt,TransactionByHashTool:()=>lt,TrendingTokensTool:()=>Qe,UNISWAP_CHAIN_SLUG:()=>an,UpstashKnowledgeBase:()=>Re,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Wn,WALLET_AGENT_TOOL_NAMES:()=>Bn,WalletApprovalsTool:()=>rt,WalletDefiPositionsTool:()=>at,WalletDefiProtocolPositionsTool:()=>it,WalletDefiSummaryTool:()=>st,WalletHistoryTool:()=>Ze,WalletNFTsTool:()=>ut,WalletNetWorthTool:()=>Tn,WalletNftTransfersTool:()=>tt,WalletPnlSummaryTool:()=>nt,WalletPnlTool:()=>ot,WalletTokenBalancesTool:()=>Je,WalletTokenTransfersTool:()=>et,ZERO_ADDRESS:()=>M,buildRangePresets:()=>lo,buildUniswapPoolUrl:()=>re,clampTick:()=>Te,configureSupportedChains:()=>bn,createAiAgent:()=>mn,createDefaultSubagents:()=>Vn,createNftAgent:()=>dn,createPoolAgent:()=>pn,createTokenAgent:()=>un,createWalletActionAgent:()=>hn,createWalletAgent:()=>cn,ethCallAt:()=>Yo,ethCallByChain:()=>io,getAffiliateFee:()=>vt,getChainMeta:()=>X,getDefaultRpcUrl:()=>Rs,getGatewayAddress:()=>Nn,getNativeTokenInfo:()=>xt,getPositionManagerAddress:()=>In,getProviderByChain:()=>En,ingestKnowledgeBase:()=>cr,priceToTick:()=>Le,resolveRpcUrl:()=>Tt,roundTickToSpacing:()=>ve,rpcCall:()=>Ae,setRpcOverrides:()=>ao,swapServiceFactory:()=>ye,tickToPrice:()=>ue,toPantographChain:()=>tn});module.exports=br(Na);var go=yr(require("axios"));var ho="0.2.24";var kr=`keyring-agent-core/${ho} (Keyring Chatbot Agent; +https://keyring.app)`,vr=3e4,Tr=typeof process<"u"&&process.versions?.node!=null,jn=class{instance;constructor(e={}){this.instance=go.default.create({baseURL:e.baseURL,timeout:e.timeout??vr,validateStatus:()=>!0,headers:{Accept:"application/json",...Tr?{"User-Agent":e.userAgent??kr}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[a,i]of Object.entries(o.headers??{}))i!=null&&(s[a.toLowerCase()]=String(i));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:s}}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)}},_=new jn;function I(c){let{data:e,status:t,statusText:n}=c,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=i=>i&&typeof i=="object"?i.message:void 0,a=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let i of a)if(typeof i=="string"&&i.trim())return i.trim()}return r}var fo={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},Sr="https://nft.keyring.app/api/gemini-stable",Ar=new Set([408,429,500,502,503,504]),yo=3e4,fn=c=>new Promise(e=>setTimeout(e,c));function yn(c,e,t){if(t!=null&&t>0)return Math.min(t,yo);let n=Math.min(e*2**(c-1),yo);return n/2+Math.random()*(n/2)}function xr(c){if(!c)return null;let e=Number(c);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(c);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var ne=class{model;maxTokens;temperature;baseUrl;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??Sr}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:a=1e3}=n??{},i=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of i){let p=m.parts.map(h=>h.functionCall?`fc:${h.functionCall.name}`:h.functionResponse?`fr:${h.functionResponse.name}`:`text:${(h.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${p}]`)}}let l={contents:i,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(l.systemInstruction=r),t?.length?(l.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(l.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(l.tools=[{googleSearch:{}}]);let u=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,d="Unknown error";for(let m=1;m<=s;m++){let p;try{p=await _.post(u,l,{headers:{"Content-Type":"application/json"}})}catch(b){if(d=b instanceof Error?b.message:String(b),m>=s)break;await fn(yn(m,a));continue}if(!p.ok){let b=typeof p.data=="string"?p.data:JSON.stringify(p.data)||p.statusText;if(d=`Gemini proxy error ${p.status}: ${b}`,!Ar.has(p.status))throw new Error(d);if(m>=s)break;let v=xr(p.headers["retry-after"]??null);await fn(yn(m,a,v));continue}if(p.data==null||typeof p.data!="object"){if(d="Gemini proxy returned invalid JSON",m>=s)break;await fn(yn(m,a));continue}let h=p.data,g=h.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let f="",y=[],k=g.content?.parts;if(!Array.isArray(k)||k.length===0){let b=g.finishReason;if(!(b==="SAFETY"||b==="RECITATION")&&m<s){d=`Gemini returned an empty turn (finishReason=${b??"none"})`,await fn(yn(m,a));continue}return{text:"",toolCalls:[]}}for(let b of k)b.text&&(f+=b.text),b.functionCall&&y.push({toolName:b.functionCall.name,args:b.functionCall.args??{},callId:b.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let w=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:f,toolCalls:y,usage:w}}throw new Error(d)}toContents(e){let t=[],n=[];for(let a of e){if(a.role==="system"){t.push(a.content);continue}if(a.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:a.toolName??"unknown",response:{result:a.content},...a.toolCallId?{id:a.toolCallId}:{}}}]});continue}if(a.role==="assistant"&&a.toolCalls?.length){n.push({role:"model",parts:a.toolCalls.map(i=>({functionCall:{name:i.toolName,args:i.args,...i.callId?{id:i.callId}:{}}}))});continue}n.push({role:a.role==="assistant"?"model":"user",parts:[{text:a.content}]})}let r=[];for(let a of n){let i=r[r.length-1],l=a.parts.some(d=>d.functionCall),u=i?.parts.some(d=>d.functionCall);i&&i.role===a.role&&!l&&!u?i.parts.push(...a.parts):r.push({...a,parts:[...a.parts]})}let o=[];for(let a=0;a<r.length;a++){let i=r[a],l=o[o.length-1];i.role==="function"&&!l?.parts.some(d=>d.functionCall)||i.role==="model"&&i.parts.some(d=>d.functionCall)&&!(r[a+1]?.role==="function")||o.push(i)}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:fo[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:fo[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 Fe=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 $e=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],Pr=new Set($e),_e=[...$e],bo=new Set(_e),ge="0x1",Ne="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function _r(c){return c.map(e=>Ve[e]??e).join(", ")}function bn(c){let e=new Set;if(c)for(let n of c){let r=zn(n);r&&e.add(r)}let t=$e.filter(n=>!e.has(n));_e=t.length>0?[...t]:[...$e],bo=new Set(_e),ge=_e.includes("0x1")?"0x1":_e[0],Ne=_r(_e)}var Cr={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","op mainnet":"0xa","optimism mainnet":"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"};function he(c){let e=zn(c);return e&&bo.has(e)?e:null}function zn(c){if(typeof c!="string")return null;let e=c.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Cr[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&&Pr.has(n)?n:null}function wn(c){return he(c)!==null}function wo(){return[..._e]}var We=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Ne}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ce=c=>typeof c=="string"&&c.trim()!=="";function kn(c,e){if(Ce(c)){let t=he(c);if(t)return t;throw new We(c.trim())}if(Ce(e?.chain)){let t=he(e.chain);if(t)return t;throw new We(e.chain.trim())}return null}function vn(c,e){return he(c)??he(e?.chain)??void 0}var Ve={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function N(c){let e=zn(c);return e&&Ve[e]?Ve[e]:typeof c=="string"&&c.trim()?c.trim():"the requested chain"}var Er={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function ko(c){if(typeof c!="string")return null;let e=c.trim().toLowerCase();return e?Er[e]??null:null}var Ur={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function vo(c){let e=he(c);return e?Ur[e]??null:null}function He(c,e){if(!Ce(c))return null;let t=he(c),n=he(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:Ve[t]??t,connectedLabel:Ve[n]??n}}function Rr(){return _e.map(c=>{let e=Ve[c]??c;return{label:e,prompt:e}})}var K=class extends Error{code="needs_chain_selection";buttons;constructor(e){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=e??Rr()}},Jt=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(c,e){if(Ce(c))return c.trim();if(Ce(e?.walletAddress))return e.walletAddress.trim();throw new Jt}function U(c,e){if(Ce(c)){let t=he(c);if(t)return t;throw new We(c.trim())}if(Ce(e?.chain)){let t=he(e.chain);if(t)return t;throw new We(e.chain.trim())}if(Ce(e?.walletAddress))throw new K;return ge}var T=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=Nr(o);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-r,...s.actionButtons?{actionButtons:s.actionButtons}:{}}}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 Jt?{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 Nr(c){if(!c||typeof c!="object")return{data:c};let e=c,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:c};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var To=require("js-sha3");function B(c){return typeof c=="string"&&/^0x[0-9a-fA-F]{40}$/.test(c)}function Ir(c){return new Uint8Array(To.keccak256.arrayBuffer(c))}function Zt(c){let e=c.startsWith("0x")?c.slice(2):c,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 So(c){return"0x"+Array.from(c).map(e=>e.toString(16).padStart(2,"0")).join("")}function Ao(c){return new TextEncoder().encode(c)}function Ie(...c){let e=c.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of c)t.set(r,n),n+=r.length;return t}function Lr(c,e=32){let t=new Uint8Array(e);return t.set(c,e-c.length),t}function Dr(c,e=32){let t=new Uint8Array(e);return t.set(c),t}function xo(c){let e=((c%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Zt(e)}function en(c){return xo(BigInt(c))}function Po(c){return c==="uint"?"uint256":c==="int"?"int256":c.match(/^uint$/)?"uint256":c.match(/^int$/)?"int256":c.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function _o(c){let e=Po(c.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(c.components??[]).map(_o).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function Or(c){let e=(c.inputs??[]).map(_o).join(",");return`${c.name??""}(${e})`}function Qn(c,e){let t=qr(c.type);if(t){let[r,o]=t;return Br({...c,type:o},e,r)}if(c.type==="tuple")return Mr(c,e);if(c.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:Lr(Zt(o.toLowerCase()))}}if(c.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Po(c.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:en(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:xo(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Zt(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Dr(o)}}if(n==="bytes"){let r=typeof e=="string"?Zt(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:Ie(en(r.length),s)}}if(n==="string"){let r=typeof e=="string"?Ao(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:Ie(en(r.length),s)}}throw new Error(`Unsupported ABI type: ${c.type}`)}function Xn(c){let e=0;for(let{dynamic:o,encoded:s}of c)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of c)o?(t.push(en(e+r)),n.push(s),r+=s.length):t.push(s);return Ie(...t,...n)}function Br(c,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 a=Qn(c,s);a.dynamic&&(r=!0),o.push(a)}if(n||r){let s=Xn(o);if(n){let a=en(o.length);return{dynamic:!0,encoded:o.length>0?Ie(a,s):a}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:Ie(...o.map(s=>s.encoded))}}function Mr(c,e){let t=c.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],a=Array.isArray(e)?e[o]:e[s.name??""],i=Qn(s,a);i.dynamic&&(n=!0),r.push(i)}return{dynamic:n,encoded:n?Xn(r):Ie(...r.map(o=>o.encoded))}}function qr(c){let e=c.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Fr(c,e){if(c.length!==e.length)throw new Error(`Expected ${c.length} values, got ${e.length}`);if(c.length===0)return"0x";let t=c.map((r,o)=>Qn(r,e[o])),n=Xn(t);return So(n)}function Ge({abi:c,functionName:e,args:t=[]}){let n=c.find(i=>(i.type==="function"||i.type===void 0)&&i.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=Or(n),o=Ir(Ao(r)).slice(0,4),s=n.inputs??[],a=s.length===0||t.length===0?new Uint8Array(0):Zt(Fr(s,t).slice(2));return So(Ie(o,a))}var $r="https://wallet-api.pantograph.app",Wr="0x0000000000000000000000000000000000000000",Uo={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Ro={"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"]};function tn(c){return Uo[c.toLowerCase()]||c}function Co(c){let e=[];for(let[t,n]of Object.entries(c))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 Jn(c){let e=c,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 ee(c){if(c==null)return null;let e=typeof c=="number"?c:parseFloat(String(c));return Number.isFinite(e)?e:null}function Eo(c,e){let t=c.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=ee(c.price_change_percentage_24h)??ee(c.priceChange24h)??ee(c.usd_price_24hr_percent_change)??ee(c.price_change_24h)??ee(c.priceChange);return{chainId:e,tokenAddress:c.address??c.token_address??"",name:c.name??null,symbol:c.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:c.logoURI??c.icon_image??c.logo??null,usdPrice:ee(c.price)??ee(c.usd_price),marketCap:ee(c.market_cap)??ee(c.marketCap),totalVolume:{"24h":ee(c.total_volume)??ee(c.volume24h)},pricePercentChange:{"24h":r}}}var te=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??$r).replace(/\/+$/,"")}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=tn(t),r=e.map(u=>u.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(r)}`,s=await _.get(o);if(!s.ok)return;let a=s.data,i=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],l=new Map;for(let u of i)u.address&&l.set(u.address.toLowerCase(),{price:u.price!=null?parseFloat(String(u.price)):NaN,icon_image:u.icon_image});for(let u=0;u<e.length;u++){let d=l.get(e[u].token_address.toLowerCase());d&&(d.icon_image&&(e[u].logo=d.icon_image,e[u].thumbnail=d.icon_image),isNaN(d.price)||(e[u].usd_price=d.price,e[u].usd_value=parseFloat(e[u].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,t){try{let n=tn(t),r=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await _.get(r);if(!o.ok)return null;let s=o.data,a=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],i=e.toLowerCase()===Wr,l=a.find(u=>u.address?.toLowerCase()===e.toLowerCase()||i&&u.address===""||u.token_address?.toLowerCase()===e.toLowerCase()||i&&u.token_address==="");return l?Jn(l):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=tn(t),o=`${this.baseUrl}/keyrings/tokens/${r}/v2?addresses=${encodeURIComponent(e.join(","))}`,s=await _.get(o);if(!s.ok)return n;let a=s.data,i=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],l=new Set(e.map(u=>u.toLowerCase()));for(let u of i){let d=u.address?.toLowerCase()||u.token_address?.toLowerCase()||(u.address===""?"":null);d&&l.has(d)&&(n[d]=Jn(u))}}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||ge,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=Co({chainId:o,key:t}),a=`${this.baseUrl}/token-list?${s}`,i=await _.get(a);if(!i.ok)throw new Error(I(i));let l=i.data,u=[];return l?.data?u=Array.isArray(l.data)?l.data:Object.values(l.data).flat():typeof l=="object"&&!Array.isArray(l)&&(u=Object.values(l).flat()),{success:!0,data:u.map(Jn)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||ge,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=Ro[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[a,i]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),l=a.status==="fulfilled"?a.value:[],u=i.status==="fulfilled"?o.map(g=>i.value[g.toLowerCase()]).filter(g=>g!=null).map(g=>Eo(g,t)):[],d=new Set,m=[];for(let g of u){let f=g.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(g))}let p=[];for(let g of l){let f=g.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(g))}let h=r!=null?[...m,...p].slice(0,r):[...m,...p.slice(0,n)];return await this.enrichTrendingMarketData(h,t),{success:!0,data:h}}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=ee(s.market_cap)??ee(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":ee(s.total_volume)??ee(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=tn(e),o=Co({duration:n,limit:t}),s=`${this.baseUrl}/token-list/top-gainers/${r}${o?`?${o}`:""}`,a=[];for(let i=0;i<5;i++){let l=await _.get(s);if(!l.ok)throw new Error(I(l));let u=l.data;if(a=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],a.length>0)break;i<4&&await new Promise(d=>setTimeout(d,2e3))}return a.map(i=>Eo(i,e))}async getTopGainers(e){let t=e?.chain||ge,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 Vr="https://nft.keyring.app",Hr="https://nft.keyring.app",Gr=.01,E=5,F=1e3,Yr="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Kr="0x0000000000000000000000000000000000000000";function V(c){return c||ge}function $(c){let e=[];for(let[t,n]of Object.entries(c))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 W(c){return new Promise(e=>setTimeout(e,c))}function jr(c){if(Array.isArray(c))return c;if(c&&typeof c=="object"){let e=c;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 Zn(c){if(Array.isArray(c))return c;if(c&&typeof c=="object"){let e=c;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 R=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Vr).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Hr).replace(/\/+$/,""),this.pantograph=new te({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 a=V(n),i="Unknown error";for(let l=1;l<=E;l++)try{let u={chain:a,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(u.token_addresses=r);let d=[],m=null;do{m&&(u.cursor=m);let h=$(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,f=await _.get(g);if(!f.ok)throw new Error(I(f));let y=f.data,k=y?.data??y;k?.result?.length>0&&d.push(...k.result),m=k?.cursor??null}while(m);let p={result:d};return p?.result?.length>0&&(p.result=p.result.filter(h=>parseFloat(h.balance||"0")>0),p.result=p.result.map(h=>({...h,token_address:h.token_address.toLowerCase()===Yr?Kr:h.token_address})),await this.enrichTokenPrices(p.result,a),p.result=p.result.filter(h=>h.usd_value==null||h.usd_value>=Gr)),{success:!0,data:p}}catch(u){i=u instanceof Error?u.message:"Unknown error",l<E&&await W(F)}return{success:!1,error:i}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=V(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let a=1;a<=E;a++)try{let[i,l]=await Promise.allSettled([_.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${$({chain:r,addresses:[t]})}`),_.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${$({chain:r,include:"percent_change"})}`)]),u=null;if(i.status==="fulfilled"&&i.value.ok){let m=i.value.data;u=(Array.isArray(m)?m:Array.isArray(m?.data)?m.data:[])[0]??null}if(!u){o="Token metadata not found",a<E&&await W(F);continue}let d=null;if(l.status==="fulfilled"&&l.value.ok){let m=l.value.data;d=m?.data??m}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(i){o=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=10,excludeSpam:o=!0,cursor:s,tokenAddresses:a,includePrices:i,format:l="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=V(n),d="Unknown error";for(let m=1;m<=E;m++)try{let p={chain:u,format:l,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(p.cursor=s),i&&(p.include_prices=!0),a&&a.length>0&&(p.token_addresses=a);let h=$(p),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${h}`,f=await _.get(g);if(!f.ok)throw new Error(I(f));let y=f.data;return{success:!0,data:y?.data??y}}catch(p){d=p instanceof Error?p.message:"Unknown error",m<E&&await W(F)}return{success:!1,error:d}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:a=!0,include:i}=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(!B(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let l=V(r),u="Unknown error";for(let d=1;d<=E;d++)try{let m={chain:l,format:o,normalizeMetadata:s,media_items:a};i&&(m.include=i);let p=$(m),h=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${p}`,g=await _.get(h);if(!g.ok)throw new Error(I(g));let f=g.data;return{success:!0,data:f?.data??f}}catch(m){u=m instanceof Error?m.message:"Unknown error",d<E&&await W(F)}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=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:a,toBlock:i,cursor:l,order:u="DESC",includeInternalTransactions:d,nftMetadata:m}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let p=V(n),h=Math.max(1,Math.min(100,Math.floor(r))),g="Unknown error";for(let f=1;f<=E;f++)try{let y={chain:p,limit:h,order:u};o&&(y.from_date=o),s&&(y.to_date=s),a!=null&&(y.from_block=a),i!=null&&(y.to_block=i),l&&(y.cursor=l),d!=null&&(y.include_internal_transactions=d),m!=null&&(y.nft_metadata=m);let k=$(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${k}`,b=await _.get(w);if(!b.ok)throw new Error(I(b));let v=b.data;return{success:!0,data:v?.data??v}}catch(y){g=y instanceof Error?y.message:"Unknown error",f<E&&await W(F)}return{success:!1,error:g}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let m=V(n),p=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let g=1;g<=E;g++)try{let f={chain:m,limit:p,order:d};s&&(f.from_date=s),a&&(f.to_date=a),i!=null&&(f.from_block=i),l!=null&&(f.to_block=l),u&&(f.cursor=u),r?.length&&(f.contract_addresses=r);let y=$(f),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await _.get(k);if(!w.ok)throw new Error(I(w));let b=w.data;return{success:!0,data:b?.data??b}}catch(f){h=f instanceof Error?f.message:"Unknown error",g<E&&await W(F)}return{success:!1,error:h}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:u,order:d="DESC",includePrices:m,format:p="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let h=V(n),g=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let y=1;y<=E;y++)try{let k={chain:h,limit:g,order:d,format:p};s&&(k.from_date=s),a&&(k.to_date=a),i!=null&&(k.from_block=i),l!=null&&(k.to_block=l),u&&(k.cursor=u),r?.length&&(k.contract_addresses=r),m!=null&&(k.include_prices=m);let w=$(k),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,v=await _.get(b);if(!v.ok)throw new Error(I(v));let A=v.data;return{success:!0,data:A?.data??A}}catch(k){f=k instanceof Error?k.message:"Unknown error",y<E&&await W(F)}return{success:!1,error:f}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!B(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getWalletNetWorth(e){let{address:t,chains:n,excludeSpam:r,excludeUnverifiedContracts:o,maxTokenInactivity:s,minPairSideLiquidityUsd:a}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet net worth is only supported for EVM addresses"};let i="Unknown error";for(let l=1;l<=E;l++)try{let u={};n&&n.length>0&&(u.chains=n.map(y=>V(y))),r!=null&&(u.exclude_spam=r),o!=null&&(u.exclude_unverified_contracts=o),s!=null&&(u.max_token_inactivity=s),a!=null&&(u.min_pair_side_liquidity_usd=a);let d=$(u),m=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/net-worth${d?`?${d}`:""}`,p=await _.get(m);if(!p.ok)throw new Error(I(p));let h=p.data;return{success:!0,data:h?.data??h}}catch(u){i=u instanceof Error?u.message:"Unknown error",l<E&&await W(F)}return{success:!1,error:i}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=V(n),s="Unknown error";for(let a=1;a<=E;a++)try{let i={chain:o};r&&(i.days=r);let l=$(i),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${l}`,d=await _.get(u);if(!d.ok)throw new Error(I(d));let m=d.data;return{success:!0,data:m?.data??m}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}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(!B(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=V(n),a="Unknown error";for(let i=1;i<=E;i++)try{let l={chain:s};r&&(l.days=r),o&&o.length>0&&(l.token_addresses=o.slice(0,25));let u=$(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,m=await _.get(d);if(!m.ok)throw new Error(I(m));let p=m.data;return{success:!0,data:p?.data??p}}catch(l){a=l instanceof Error?l.message:"Unknown error",i<E&&await W(F)}return{success:!1,error:a}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}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(!B(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=V(n),a="Unknown error";for(let i=1;i<=E;i++)try{let l={chain:s};r!=null&&(l.limit=r),o&&(l.cursor=o);let u=$(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,m=await _.get(d);if(!m.ok)throw new Error(I(m));let p=m.data;return{success:!0,data:p?.data??p}}catch(l){a=l instanceof Error?l.message:"Unknown error",i<E&&await W(F)}return{success:!1,error:a}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chains:r}),i=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chains:r}),i=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data,d=u?.data??u;return{success:!0,data:jr(d)}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}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(!B(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=V(r),s="Unknown error";for(let a=1;a<=E;a++)try{let i=$({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${i}`,u=await _.get(l);if(!u.ok)throw new Error(I(u));let p=u.data.result;return{success:!0,data:{protocol_id:p.protocolId,protocol_name:p.protocolName,protocol_url:p.protocolUrl??"",protocol_logo:p.protocolLogo??"",total_usd_value:p.totalUsd??0,total_unclaimed_usd_value:p.totalUnclaimedUsd??null,positions:p.positions.map(g=>({label:g.label,address:g.address,balance_usd:g.balanceUsd??0,total_unclaimed_usd_value:g.unclaimedUsd??0,position_details:g.details,tokens:g.tokens.map(f=>({token_type:f.tokenType,address:f.address,contract_address:f.address,name:f.name??"",symbol:f.symbol??"",decimals:f.decimals??18,logo:f.logo,balance:f.balance??"0",balance_formatted:f.balanceFormatted??"0",usd_price:f.usdPrice,usd_value:f.usdValue}))}))}}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}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(!B(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}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(!B(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=E;o++)try{let s={};t&&(s.chain=V(t)),n!=null&&(s.limit=n);let a=$(s),i=`${this.baseUrl}/api/moralis/proxy/tokens/trending${a?`?${a}`:""}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data,d=u?.data??u;return{success:!0,data:Zn(d)}}catch(s){r=s instanceof Error?s.message:"Unknown error",o<E&&await W(F)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let a=1;a<=E;a++)try{let i={};t&&(i.chain=V(t)),n&&(i.time_frame=n),r!=null&&(i.min_market_cap=r),o!=null&&(i.security_score=o);let l=$(i),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${l?`?${l}`:""}`,d=await _.get(u);if(!d.ok)throw new Error(I(d));let m=d.data,p=m?.data??m;return{success:!0,data:Zn(p)}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let a=1;a<=E;a++)try{let i={};t&&(i.chain=V(t)),n&&(i.time_frame=n),r!=null&&(i.min_market_cap=r),o!=null&&(i.security_score=o);let l=$(i),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${l?`?${l}`:""}`,d=await _.get(u);if(!d.ok)throw new Error(I(d));let m=d.data,p=m?.data??m;return{success:!0,data:Zn(p)}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var Ye=class extends T{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';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. 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, (4) on-chain activity signals (holders, liquidity, unusual flows), (5) team/protocol updates or roadmap items, (6) key risks, red flags, or controversies, (7) sentiment and notable community discussion. When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. Aim for 3-6 sentences. Be specific to the token. Do not use generic filler. 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; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment."`,required:!0},{name:"buy_button_label",type:"string",description:`Label for the "Buy" suggestion button shown under the token info, IN THE USER'S CURRENT LANGUAGE. 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_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the Buy button is clicked. 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}];service;llm;constructor(e){super(),this.service=new R(e),this.llm=new ne({})}async run(e,t){let n=e.keyword||"",r=U(e.chain,t),o=e.prompt||"",s=e.buy_button_label||"",a=e.buy_prompt_template||"",i=t?.walletAddress||void 0;return n?await this.searchToken(n,r,o,s,a,i):{error:"Missing required parameter: keyword"}}async execute(e,t){let n=await super.execute(e,t),r=n.data;return n.success&&r&&Array.isArray(r.actionButtons)&&r.actionButtons.length>0&&(n.actionButtons=r.actionButtons),n}async searchToken(e,t,n,r,o,s){let a=[s?`User's connected wallet address: ${s}`: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(`
3
- `),[i,l,u]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),s?this.findTokenInWallet(s,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,a):Promise.resolve(null)]),d=i.success&&i.data?Array.isArray(i.data)?i.data:[]:[],m=e.toLowerCase(),p=b=>b.symbol?.toLowerCase()===m||b.token_address?.toLowerCase()===m,h=[...d].sort((b,v)=>(p(b)?0:1)-(p(v)?0:1)),g=null,f=h[0];if(f?.token_address){let b=await this.service.getTokenMetadata({address:f.token_address,chain:t});b.success&&b.data&&(g=b.data)}!g&&f&&(g={...f});let y=g?.symbol?.trim(),k=y?[{label:this.fillTemplate(r,y,"Buy {token}"),prompt:this.fillTemplate(o,y,"buy {token}")}]:[];return{_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. 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. A "Buy" button is shown below your reply automatically \u2014 do NOT mention it, list it, or repeat its text.',chain:t,userHoldsToken:!!l,walletBalance:l,token:g,...d.length>1?{searchResults:h.slice(0,10)}:{},research:u,...k.length>0?{actionButtons:k}:{}}}fillTemplate(e,t,n){return(e&&e.includes("{token}")?e:n).replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}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:!0,excludeUnverifiedContracts:!0});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),s=r.data.result.find(a=>a.token_address.toLowerCase()===o||a.symbol?.toLowerCase()===o||a.name?.toLowerCase().includes(o));return s||null}};var Ke=class extends T{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. ';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 . 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 R(e)}async run(e,t){let n=U(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 a,i;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?N(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,a=d.symbol,i=d.name}let l=await this.service.getTokenHolders({address:s,chain:n});if(!l.success)return{error:l.error||"Failed to fetch token holder stats"};let u=l.data;return{token:{symbol:a??o??null,name:i??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 a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var je=class extends T{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.`;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. 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 R(e)}async run(e,t){let n=U(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 a,i;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?N(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,a=d.symbol,i=d.name}let l=await this.service.getTokenAnalytics({address:s,chain:n});if(!l.success)return{error:l.error||"Failed to fetch token analytics"};let u=l.data??{};return{token:{symbol:a??o??null,name:i??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 a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var ze=class extends T{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.`;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. 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 R(e)}async run(e,t){let n=U(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 a,i;if(o){let m=await this.resolveContractAddress(o,n,r);if(!m)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?N(n):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,a=m.symbol,i=m.name}let l=await this.service.getTokenScore({address:s,chain:n});if(!l.success)return{error:l.error||"Failed to fetch token score"};let u=l.data??{},d=u.metrics??{};return{token:{symbol:a??o??null,name:i??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 a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var Qe=class extends T{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, 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. 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},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;constructor(e){super(),this.service=new te({baseUrl:e?.pantographUrl})}async run(e,t){let n=vn(e.chain,t),r=e.buy_button_label||"",o=e.buy_prompt_template||"",s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,a=await this.service.getTrendingTokens({chain:n,limit:s});if(!a.success)return{error:a.error||"Failed to fetch trending tokens"};let i=a.data??[],l=new Set,u=[];for(let d of i){let m=d.symbol?.trim();!m||l.has(m.toLowerCase())||(l.add(m.toLowerCase()),u.push({label:this.fillTemplate(r,m,"Buy {token}"),prompt:this.fillTemplate(o,m,"buy {token}")}))}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):
1
+ "use strict";var jr=Object.create;var Bn=Object.defineProperty;var zr=Object.getOwnPropertyDescriptor;var Qr=Object.getOwnPropertyNames;var Xr=Object.getPrototypeOf,Jr=Object.prototype.hasOwnProperty;var Zr=(l,e)=>{for(var t in e)Bn(l,t,{get:e[t],enumerable:!0})},$o=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qr(e))!Jr.call(l,r)&&r!==t&&Bn(l,r,{get:()=>e[r],enumerable:!(n=zr(e,r))||n.enumerable});return l};var es=(l,e,t)=>(t=l!=null?jr(Xr(l)):{},$o(e||!l||!l.__esModule?Bn(t,"default",{value:l,enumerable:!0}):t,l)),ts=l=>$o(Bn({},"__esModule",{value:!0}),l);var xa={};Zr(xa,{AI_AGENT_TOOL_NAMES:()=>co,AbortError:()=>Ge,AgentCore:()=>fo,ApproveTokenTool:()=>on,BaseNftAiTool:()=>Se,BaseNftMessageTool:()=>St,BaseSwapService:()=>Fe,BaseTool:()=>T,BaseWalletActionTool:()=>fe,BuyTokenTool:()=>ln,ChatHistory:()=>dn,DEFAULT_CHAIN:()=>Ae,DEFAULT_PROVIDER:()=>Pn,DEFAULT_RPC_BY_CHAIN:()=>ge,DebridgeAdapter:()=>Bt,EstimatePoolYieldTool:()=>Wt,GeminiProvider:()=>re,GeminiSearchAiTool:()=>Ct,HEX_TO_PANTOGRAPH:()=>ir,KnowledgeBase:()=>mn,ManageLiquidityRedirectTool:()=>Gt,MoralisService:()=>D,NFTContractInfoTool:()=>xt,NFTMetadataTool:()=>_t,NFT_AGENT_TOOL_NAMES:()=>lo,OpenAddLiquidityFormTool:()=>$t,POOL_AGENT_TOOL_NAMES:()=>uo,PantographService:()=>ee,PoolByAddressTool:()=>It,PoolDetailTool:()=>Ut,PoolFallbackAiTool:()=>Et,PoolPriceRangesTool:()=>Ht,PoolSearchTool:()=>Nt,PoolService:()=>Qe,PreviewAddLiquidityTool:()=>Vt,RelayAdapter:()=>qt,Router:()=>hn,SUPPORTED_CHAINS:()=>tt,SUPPORTED_CHAINS_LABEL:()=>Ye,SWAP_PROVIDER_CONFIG:()=>Jn,SendNativeTool:()=>tn,SendNftTool:()=>un,SendTokenTool:()=>nn,Subagent:()=>j,SubgraphAddPoolTool:()=>Jt,SubgraphCoinPoolPairsTool:()=>Xt,SubgraphPoolByAddressTool:()=>jt,SubgraphPoolByPositionIdTool:()=>zt,SubgraphPoolSearchTool:()=>Yt,SubgraphPositionDetailTool:()=>Qt,SubgraphTrendingPoolsTool:()=>Kt,Summarizer:()=>pn,SwapServiceFactory:()=>ze,SwapTokenTool:()=>cn,Synthesizer:()=>gn,TOKEN_AGENT_TOOL_NAMES:()=>ao,TRANSFER_TOPIC:()=>Er,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>ar,TokenAnalyticsTool:()=>ct,TokenHoldersTool:()=>lt,TokenInfoTool:()=>at,TokenScoreTool:()=>ut,ToolRegistry:()=>et,TopGainersTool:()=>pt,TopPoolsTool:()=>Rt,TransactionByHashTool:()=>At,TrendingTokensTool:()=>dt,UNISWAP_CHAIN_SLUG:()=>_n,UpstashKnowledgeBase:()=>$e,WALLET_ACTION_AGENT_TOOL_NAMES:()=>po,WALLET_AGENT_TOOL_NAMES:()=>io,WalletActionAppTool:()=>Cn,WalletApprovalsTool:()=>wt,WalletDefiPositionsTool:()=>vt,WalletDefiProtocolPositionsTool:()=>Tt,WalletDefiSummaryTool:()=>kt,WalletHistoryTool:()=>ht,WalletNFTsTool:()=>Pt,WalletNftTransfersTool:()=>ft,WalletPnlSummaryTool:()=>yt,WalletPnlTool:()=>bt,WalletTokenBalancesTool:()=>mt,WalletTokenTransfersTool:()=>gt,ZERO_ADDRESS:()=>$,buildRangePresets:()=>No,buildUniswapPoolUrl:()=>de,clampTick:()=>xe,configureSupportedChains:()=>$n,createAiAgent:()=>In,createDefaultSubagents:()=>mo,createNftAgent:()=>Nn,createPoolAgent:()=>Ln,createTokenAgent:()=>Un,createWalletActionAgent:()=>Dn,createWalletActionAppTools:()=>so,createWalletAgent:()=>Rn,ethCallAt:()=>xr,ethCallByChain:()=>Uo,getAffiliateFee:()=>Ot,getChainMeta:()=>J,getDefaultRpcUrl:()=>Ti,getGatewayAddress:()=>eo,getNativeTokenInfo:()=>Ft,getPositionManagerAddress:()=>to,getProviderByChain:()=>Xn,ingestKnowledgeBase:()=>Kr,isAbortError:()=>Ze,normalizePriceRangeToPool:()=>Dt,priceToTick:()=>je,resolveRpcUrl:()=>Mt,roundTickToSpacing:()=>Pe,rpcCall:()=>Ne,setRpcOverrides:()=>Ro,swapServiceFactory:()=>_e,tickToPrice:()=>we,toPantographChain:()=>Tn});module.exports=ts(xa);var Wo=es(require("axios"));var Vo="0.2.26";var os=`keyring-agent-core/${Vo} (Keyring Chatbot Agent; +https://keyring.app)`,rs=3e4,ss=typeof process<"u"&&process.versions?.node!=null,yo=class{instance;constructor(e={}){this.instance=Wo.default.create({baseURL:e.baseURL,timeout:e.timeout??rs,validateStatus:()=>!0,headers:{Accept:"application/json",...ss?{"User-Agent":e.userAgent??os}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[i,a]of Object.entries(o.headers??{}))a!=null&&(s[i.toLowerCase()]=String(a));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:s}}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)}},P=new yo;function L(l){let{data:e,status:t,statusText:n}=l,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=a=>a&&typeof a=="object"?a.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let a of i)if(typeof a=="string"&&a.trim())return a.trim()}return r}var Ge=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Ze(l){if(!l||typeof l!="object")return!1;let e=l;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function bo(l){if(l?.aborted)throw new Ge}function Ho(l,e){if(!e)return{signal:l.signal,cleanup:()=>{}};if(e.aborted)return l.abort(),{signal:l.signal,cleanup:()=>{}};let t=()=>l.abort();return e.addEventListener("abort",t),{signal:l.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Go={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},is="https://nft.keyring.app/api/gemini-stable",as=new Set([408,429,500,502,503,504]),Yo=3e4,qn=l=>new Promise(e=>setTimeout(e,l));function Fn(l,e,t){if(t!=null&&t>0)return Math.min(t,Yo);let n=Math.min(e*2**(l-1),Yo);return n/2+Math.random()*(n/2)}function ls(l){if(!l)return null;let e=Number(l);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(l);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var re=class{model;maxTokens;temperature;baseUrl;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??is}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??{},a=n?.signal??this.requestSignal;bo(a);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of c){let g=m.parts.map(h=>h.functionCall?`fc:${h.functionCall.name}`:h.functionResponse?`fr:${h.functionResponse.name}`:`text:${(h.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let u={contents:c,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(u.systemInstruction=r),t?.length?(u.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(u.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(u.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){bo(a);let g;try{g=await P.post(d,u,{headers:{"Content-Type":"application/json"},signal:a})}catch(k){if(Ze(k))throw k;if(p=k instanceof Error?k.message:String(k),m>=s)break;await qn(Fn(m,i));continue}if(!g.ok){let k=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(p=`Gemini proxy error ${g.status}: ${k}`,!as.has(g.status))throw new Error(p);if(m>=s)break;let A=ls(g.headers["retry-after"]??null);await qn(Fn(m,i,A));continue}if(g.data==null||typeof g.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await qn(Fn(m,i));continue}let h=g.data,f=h.candidates?.[0];if(!f)return{text:"",toolCalls:[]};let y="",b=[],w=f.content?.parts;if(!Array.isArray(w)||w.length===0){let k=f.finishReason;if(!(k==="SAFETY"||k==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${k??"none"})`,await qn(Fn(m,i));continue}return{text:"",toolCalls:[]}}for(let k of w)k.text&&(y+=k.text),k.functionCall&&b.push({toolName:k.functionCall.name,args:k.functionCall.args??{},callId:k.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let v=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:b,usage:v}}throw new Error(p)}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(a=>({functionCall:{name:a.toolName,args:a.args,...a.callId?{id:a.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let a=r[r.length-1],c=i.parts.some(d=>d.functionCall),u=a?.parts.some(d=>d.functionCall);a&&a.role===i.role&&!c&&!u?a.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let a=r[i],c=o[o.length-1];a.role==="function"&&!c?.parts.some(d=>d.functionCall)||a.role==="model"&&a.parts.some(d=>d.functionCall)&&!(r[i+1]?.role==="function")||o.push(a)}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:Go[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:Go[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 et=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"],cs=new Set(tt),De=[...tt],Ko=new Set(De),Ae="0x1",Ye="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function us(l){return l.map(e=>ot[e]??e).join(", ")}function $n(l){let e=new Set;if(l)for(let n of l){let r=Vn(n);r&&e.add(r)}let t=tt.filter(n=>!e.has(n));De=t.length>0?[...t]:[...tt],Ko=new Set(De),Ae=De.includes("0x1")?"0x1":De[0],Ye=us(De)}var ds={"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"};function se(l){let e=Vn(l);return e&&Ko.has(e)?e:null}function Vn(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=ds[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&&cs.has(n)?n:null}function Wn(l){return se(l)!==null}function me(){return[...De]}var nt=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Ye}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Oe=l=>typeof l=="string"&&l.trim()!=="";function ie(l,e){if(Oe(l)){let t=se(l);if(t)return t;throw new nt(l.trim())}if(Oe(e?.chain)){let t=se(e.chain);if(t)return t;throw new nt(e.chain.trim())}return null}function Hn(l,e){return se(l)??se(e?.chain)??void 0}var ot={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function E(l){let e=Vn(l);return e&&ot[e]?ot[e]:typeof l=="string"&&l.trim()?l.trim():"the requested chain"}var ps={"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"};function jo(l,e){let t=Vn(l),n=t?ps[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var ms={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function zo(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase();return e?ms[e]??null:null}var hs={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function Qo(l){let e=se(l);return e?hs[e]??null:null}function rt(l,e){if(!Oe(l))return null;let t=se(l),n=se(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:ot[t]??t,connectedLabel:ot[n]??n}}function Xo(l){let e=typeof l=="string"?l.trim():"";return De.map(t=>{let n=ot[t]??t;return{label:n,prompt:e?`${e} (${n})`:n}})}function st(l,e){return{actionButtons:Xo(e),_instructions:`The user wants to ${l} 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 z=class extends Error{code="needs_chain_selection";buttons;constructor(e){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=Xo(e)}},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 K(l,e){if(Oe(l))return l.trim();if(Oe(e?.walletAddress))return e.walletAddress.trim();throw new wn}function M(l,e){if(Oe(l)){let t=se(l);if(t)return t;throw new nt(l.trim())}if(Oe(e?.chain)){let t=se(e.chain);if(t)return t;throw new nt(e.chain.trim())}if(Oe(e?.walletAddress))throw new z(typeof e?.query=="string"?e.query:void 0);return Ae}var T=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=gs(o);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-r,...s.actionButtons?{actionButtons:s.actionButtons}:{}}}catch(o){return o instanceof z?{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 gs(l){if(!l||typeof l!="object")return{data:l};let e=l,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:l};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var Jo=require("js-sha3");function F(l){return typeof l=="string"&&/^0x[0-9a-fA-F]{40}$/.test(l)}function fs(l){return new Uint8Array(Jo.keccak256.arrayBuffer(l))}function kn(l){let e=l.startsWith("0x")?l.slice(2):l,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 Zo(l){return"0x"+Array.from(l).map(e=>e.toString(16).padStart(2,"0")).join("")}function er(l){return new TextEncoder().encode(l)}function Ke(...l){let e=l.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of l)t.set(r,n),n+=r.length;return t}function ys(l,e=32){let t=new Uint8Array(e);return t.set(l,e-l.length),t}function bs(l,e=32){let t=new Uint8Array(e);return t.set(l),t}function tr(l){let e=((l%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return kn(e)}function vn(l){return tr(BigInt(l))}function nr(l){return l==="uint"?"uint256":l==="int"?"int256":l.match(/^uint$/)?"uint256":l.match(/^int$/)?"int256":l.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function or(l){let e=nr(l.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(l.components??[]).map(or).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function ws(l){let e=(l.inputs??[]).map(or).join(",");return`${l.name??""}(${e})`}function wo(l,e){let t=Ts(l.type);if(t){let[r,o]=t;return ks({...l,type:o},e,r)}if(l.type==="tuple")return vs(l,e);if(l.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:ys(kn(o.toLowerCase()))}}if(l.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=nr(l.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:vn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:tr(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?kn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:bs(o)}}if(n==="bytes"){let r=typeof e=="string"?kn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:Ke(vn(r.length),s)}}if(n==="string"){let r=typeof e=="string"?er(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:Ke(vn(r.length),s)}}throw new Error(`Unsupported ABI type: ${l.type}`)}function ko(l){let e=0;for(let{dynamic:o,encoded:s}of l)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of l)o?(t.push(vn(e+r)),n.push(s),r+=s.length):t.push(s);return Ke(...t,...n)}function ks(l,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=wo(l,s);i.dynamic&&(r=!0),o.push(i)}if(n||r){let s=ko(o);if(n){let i=vn(o.length);return{dynamic:!0,encoded:o.length>0?Ke(i,s):i}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:Ke(...o.map(s=>s.encoded))}}function vs(l,e){let t=l.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??""],a=wo(s,i);a.dynamic&&(n=!0),r.push(a)}return{dynamic:n,encoded:n?ko(r):Ke(...r.map(o=>o.encoded))}}function Ts(l){let e=l.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function As(l,e){if(l.length!==e.length)throw new Error(`Expected ${l.length} values, got ${e.length}`);if(l.length===0)return"0x";let t=l.map((r,o)=>wo(r,e[o])),n=ko(t);return Zo(n)}function it({abi:l,functionName:e,args:t=[]}){let n=l.find(a=>(a.type==="function"||a.type===void 0)&&a.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=ws(n),o=fs(er(r)).slice(0,4),s=n.inputs??[],i=s.length===0||t.length===0?new Uint8Array(0):kn(As(s,t).slice(2));return Zo(Ke(o,i))}var Ss="https://wallet-api.pantograph.app",Ps="0x0000000000000000000000000000000000000000",ir={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},ar={"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"]};function Tn(l){return ir[l.toLowerCase()]||l}function rr(l){let e=[];for(let[t,n]of Object.entries(l))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 vo(l){let e=l,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 Z(l){if(l==null)return null;let e=typeof l=="number"?l:parseFloat(String(l));return Number.isFinite(e)?e:null}function sr(l,e){let t=l.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=Z(l.price_change_percentage_24h)??Z(l.priceChange24h)??Z(l.usd_price_24hr_percent_change)??Z(l.price_change_24h)??Z(l.priceChange);return{chainId:e,tokenAddress:l.address??l.token_address??"",name:l.name??null,symbol:l.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:l.logoURI??l.icon_image??l.logo??null,usdPrice:Z(l.price)??Z(l.usd_price),marketCap:Z(l.market_cap)??Z(l.marketCap),totalVolume:{"24h":Z(l.total_volume)??Z(l.volume24h)},pricePercentChange:{"24h":r}}}var ee=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Ss).replace(/\/+$/,"")}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=Tn(t),r=e.map(u=>u.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(r)}`,s=await P.get(o);if(!s.ok)return;let i=s.data,a=Array.isArray(i)?i:Array.isArray(i.data)?i.data:[],c=new Map;for(let u of a)u.address&&c.set(u.address.toLowerCase(),{price:u.price!=null?parseFloat(String(u.price)):NaN,icon_image:u.icon_image});for(let u=0;u<e.length;u++){let d=c.get(e[u].token_address.toLowerCase());d&&(d.icon_image&&(e[u].logo=d.icon_image,e[u].thumbnail=d.icon_image),isNaN(d.price)||(e[u].usd_price=d.price,e[u].usd_value=parseFloat(e[u].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,t){try{let n=Tn(t),r=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await P.get(r);if(!o.ok)return null;let s=o.data,i=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],a=e.toLowerCase()===Ps,c=i.find(u=>u.address?.toLowerCase()===e.toLowerCase()||a&&u.address===""||u.token_address?.toLowerCase()===e.toLowerCase()||a&&u.token_address==="");return c?vo(c):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=Tn(t),o=`${this.baseUrl}/keyrings/tokens/${r}/v2?addresses=${encodeURIComponent(e.join(","))}`,s=await P.get(o);if(!s.ok)return n;let i=s.data,a=Array.isArray(i)?i:Array.isArray(i.data)?i.data:[],c=new Set(e.map(u=>u.toLowerCase()));for(let u of a){let d=u.address?.toLowerCase()||u.token_address?.toLowerCase()||(u.address===""?"":null);d&&c.has(d)&&(n[d]=vo(u))}}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||Ae,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=rr({chainId:o,key:t}),i=`${this.baseUrl}/token-list?${s}`,a=await P.get(i);if(!a.ok)throw new Error(L(a));let c=a.data,u=[];return c?.data?u=Array.isArray(c.data)?c.data:Object.values(c.data).flat():typeof c=="object"&&!Array.isArray(c)&&(u=Object.values(c).flat()),{success:!0,data:u.map(vo)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Ae,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=ar[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[i,a]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],u=a.status==="fulfilled"?o.map(h=>a.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>sr(h,t)):[],d=new Set,p=[];for(let h of u){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(h))}let m=[];for(let h of c){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(h))}let g=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,t),{success:!0,data:g}}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=Z(s.market_cap)??Z(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":Z(s.total_volume)??Z(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=Tn(e),o=rr({duration:n,limit:t}),s=`${this.baseUrl}/token-list/top-gainers/${r}${o?`?${o}`:""}`,i=[];for(let a=0;a<5;a++){let c=await P.get(s);if(!c.ok)throw new Error(L(c));let u=c.data;if(i=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],i.length>0)break;a<4&&await new Promise(d=>setTimeout(d,2e3))}return i.map(a=>sr(a,e))}async getTopGainers(e){let t=e?.chain||Ae,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 xs="https://nft.keyring.app",_s="https://nft.keyring.app",Cs=.01,R=5,W=1e3,Es="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Rs="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function Y(l){return l||Ae}function H(l){let e=[];for(let[t,n]of Object.entries(l))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 G(l){return new Promise(e=>setTimeout(e,l))}function Us(l){if(Array.isArray(l))return l;if(l&&typeof l=="object"){let e=l;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 To(l){if(Array.isArray(l))return l;if(l&&typeof l=="object"){let e=l;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??xs).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??_s).replace(/\/+$/,""),this.pantograph=new ee({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=Y(n),a="Unknown error";for(let c=1;c<=R;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 g=H(u),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${g}`,f=await P.get(h);if(!f.ok)throw new U(f.status,L(f));let y=f.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(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===Es?Rs:g.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=Cs)),{success:!0,data:m}}catch(u){if(a=u instanceof Error?u.message:"Unknown error",u instanceof U&&u.status===400)break;c<R&&await G(W)}return{success:!1,error:a}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=Y(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let i=1;i<=R;i++)try{let[a,c]=await Promise.allSettled([P.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${H({chain:r,addresses:[t]})}`),P.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${H({chain:r,include:"percent_change"})}`)]),u=null;if(a.status==="fulfilled"&&a.value.ok){let p=a.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){o="Token metadata not found",i<R&&await G(W);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(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof U&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=10,excludeSpam:o=!0,cursor:s,tokenAddresses:i,includePrices:a,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=Y(n),d="Unknown error";for(let p=1;p<=R;p++)try{let m={chain:u,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(m.cursor=s),a&&(m.include_prices=!0),i&&i.length>0&&(m.token_addresses=i);let g=H(m),h=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${g}`,f=await P.get(h);if(!f.ok)throw new U(f.status,L(f));let y=f.data;return{success:!0,data:y?.data??y}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof U&&m.status===400)break;p<R&&await G(W)}return{success:!1,error:d}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:i=!0,include:a}=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(!F(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=Y(r),u="Unknown error";for(let d=1;d<=R;d++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:i};a&&(p.include=a);let m=H(p),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await P.get(g);if(!h.ok)throw new U(h.status,L(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;d<R&&await G(W)}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=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await P.get(a);if(!c.ok)throw new U(c.status,L(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<R&&await G(W)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:i,toBlock:a,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=Y(n),g=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let f=1;f<=R;f++)try{let y={chain:m,limit:g,order:u};o&&(y.from_date=o),s&&(y.to_date=s),i!=null&&(y.from_block=i),a!=null&&(y.to_block=a),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=H(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,v=await P.get(w);if(!v.ok)throw new U(v.status,L(v));let k=v.data;return{success:!0,data:k?.data??k}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;f<R&&await G(W)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:a,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=Y(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let h=1;h<=R;h++)try{let f={chain:p,limit:m,order:d};s&&(f.from_date=s),i&&(f.to_date=i),a!=null&&(f.from_block=a),c!=null&&(f.to_block=c),u&&(f.cursor=u),r?.length&&(f.contract_addresses=r);let y=H(f),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await P.get(b);if(!w.ok)throw new U(w.status,L(w));let v=w.data;return{success:!0,data:v?.data??v}}catch(f){if(g=f instanceof Error?f.message:"Unknown error",f instanceof U&&f.status===400)break;h<R&&await G(W)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:a,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=Y(n),h=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let y=1;y<=R;y++)try{let b={chain:g,limit:h,order:d,format:m};s&&(b.from_date=s),i&&(b.to_date=i),a!=null&&(b.from_block=a),c!=null&&(b.to_block=c),u&&(b.cursor=u),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=H(b),v=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,k=await P.get(v);if(!k.ok)throw new U(k.status,L(k));let A=k.data;return{success:!0,data:A?.data??A}}catch(b){if(f=b instanceof Error?b.message:"Unknown error",b instanceof U&&b.status===400)break;y<R&&await G(W)}return{success:!1,error:f}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!F(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await P.get(a);if(!c.ok)throw new U(c.status,L(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<R&&await G(W)}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(!F(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=Y(n),s="Unknown error";for(let i=1;i<=R;i++)try{let a={chain:o};r&&(a.days=r);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await P.get(u);if(!d.ok)throw new U(d.status,L(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof U&&a.status===400)break;i<R&&await G(W)}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(!F(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=Y(n),i="Unknown error";for(let a=1;a<=R;a++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await P.get(d);if(!p.ok)throw new U(p.status,L(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;a<R&&await G(W)}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=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await P.get(a);if(!c.ok)throw new U(c.status,L(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<R&&await G(W)}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(!F(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=Y(n),i="Unknown error";for(let a=1;a<=R;a++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await P.get(d);if(!p.ok)throw new U(p.status,L(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;a<R&&await G(W)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chains:r}),a=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await P.get(a);if(!c.ok)throw new U(c.status,L(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<R&&await G(W)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chains:r}),a=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await P.get(a);if(!c.ok)throw new U(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:Us(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<R&&await G(W)}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(!F(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=Y(r),s="Unknown error";for(let i=1;i<=R;i++)try{let a=H({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${a}`,u=await P.get(c);if(!u.ok)throw new U(u.status,L(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(f=>({token_type:f.tokenType,address:f.address,contract_address:f.address,name:f.name??"",symbol:f.symbol??"",decimals:f.decimals??18,logo:f.logo,balance:f.balance??"0",balance_formatted:f.balanceFormatted??"0",usd_price:f.usdPrice,usd_value:f.usdValue}))}))}}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof U&&a.status===400)break;i<R&&await G(W)}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(!F(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await P.get(a);if(!c.ok)throw new U(c.status,L(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<R&&await G(W)}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(!F(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await P.get(a);if(!c.ok)throw new U(c.status,L(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<R&&await G(W)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=R;o++)try{let s={};t&&(s.chain=Y(t)),n!=null&&(s.limit=n);let i=H(s),a=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await P.get(a);if(!c.ok)throw new U(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:To(d)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof U&&s.status===400)break;o<R&&await G(W)}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<=R;i++)try{let a={};t&&(a.chain=Y(t)),n&&(a.time_frame=n),r!=null&&(a.min_market_cap=r),o!=null&&(a.security_score=o);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new U(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:To(m)}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof U&&a.status===400)break;i<R&&await G(W)}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<=R;i++)try{let a={};t&&(a.chain=Y(t)),n&&(a.time_frame=n),r!=null&&(a.min_market_cap=r),o!=null&&(a.security_score=o);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new U(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:To(m)}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof U&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var at=class extends T{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';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. 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},{name:"buy_button_label",type:"string",description:`Label for the "Buy" suggestion button shown under the token info, IN THE USER'S CURRENT LANGUAGE. 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_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the Buy button is clicked. 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}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new re({})}async run(e,t){let n=e.keyword||"",r=M(e.chain,t),o=e.prompt||"",s=e.buy_button_label||"",i=e.buy_prompt_template||"",a=t?.walletAddress||void 0;return n?await this.searchToken(n,r,o,s,i,a):{error:"Missing required parameter: keyword"}}async execute(e,t){let n=await super.execute(e,t),r=n.data;return n.success&&r&&Array.isArray(r.actionButtons)&&r.actionButtons.length>0&&(n.actionButtons=r.actionButtons),n}async searchToken(e,t,n,r,o,s){let i=[s?`User's connected wallet address: ${s}`: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(`
3
+ `),[a,c,u]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),s?this.findTokenInWallet(s,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,i):Promise.resolve(null)]),d=a.success&&a.data?Array.isArray(a.data)?a.data:[]:[],p=e.toLowerCase(),m=v=>v.symbol?.toLowerCase()===p||v.token_address?.toLowerCase()===p,g=[...d].sort((v,k)=>(m(v)?0:1)-(m(k)?0:1)),h=null,f=g[0];if(f?.token_address){let v=await this.service.getTokenMetadata({address:f.token_address,chain:t});v.success&&v.data&&(h=v.data)}!h&&f&&(h={...f});let y=h?.symbol?.trim(),b=y?[{label:this.fillTemplate(r,y,"Buy {token}"),prompt:this.fillTemplate(o,y,"buy {token}")}]:[];return{_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. A "Buy" button is shown below your reply automatically \u2014 do NOT mention it, list it, or repeat its text.',chain:t,userHoldsToken:!!c,walletBalance:c,token:h,...d.length>1?{searchResults:g.slice(0,10)}:{},research:u,...b.length>0?{actionButtons:b}:{}}}fillTemplate(e,t,n){return(e&&e.includes("{token}")?e:n).replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}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:!0,excludeUnverifiedContracts:!0});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 lt=class extends T{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. ';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 . 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=M(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,a;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?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,i=d.symbol,a=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:a??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(a=>(a.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(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var ct=class extends T{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.`;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. 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=M(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,a;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?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,i=d.symbol,a=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:a??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(a=>(a.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(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var ut=class extends T{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.`;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. 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=M(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,a;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?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,i=p.symbol,a=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:a??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(a=>(a.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(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var dt=class extends T{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, 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. 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},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;constructor(e){super(),this.service=new ee({baseUrl:e?.pantographUrl})}async run(e,t){let n=Hn(e.chain,t),r=e.buy_button_label||"",o=e.buy_prompt_template||"",s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,i=await this.service.getTrendingTokens({chain:n,limit:s});if(!i.success)return{error:i.error||"Failed to fetch trending tokens"};let a=i.data??[],c=new Set,u=[];for(let d of a){let p=d.symbol?.trim();!p||c.has(p.toLowerCase())||(c.add(p.toLowerCase()),u.push({label:this.fillTemplate(r,p,"Buy {token}"),prompt:this.fillTemplate(o,p,"buy {token}")}))}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
4
  <rank>. <name> (<symbol>)
5
5
  - Price: <usdPrice>
6
6
  - Market Cap: <marketCap>
7
7
  - 24h Price Change: <pricePercentChange.24h>
8
8
  - 24h Volume: <totalVolume.24h>
9
- 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 (+3.56%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms. A "Buy" button is shown below your reply for each token automatically \u2014 do NOT mention, list, or repeat them.`,chain:n?N(n):"all",count:i.length,tokens:i,...u.length>0?{actionButtons:u}:{}}}async execute(e,t){let n=await super.execute(e,t),r=n.data;return n.success&&r&&Array.isArray(r.actionButtons)&&r.actionButtons.length>0&&(n.actionButtons=r.actionButtons),n}fillTemplate(e,t,n){return(e&&e.includes("{token}")?e:n).replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}};var Io={"1h":"1h","1d":"24h","1w":"7d","1M":"30d"},No=Object.keys(Io),Xe=class extends T{name="get-top-gainers";description='List tokens with the highest USD price increase over a chosen timeframe (1h / 1d / 1w / 1M). Returns name & symbol, current USD price, market cap, 24h volume, and the price change % over the selected window. Scoped to a single chain \u2014 pass `chain` to pick the network, otherwise the connected chain (or Ethereum) is used. Use this tool for questions like: "What are today\'s top gainers?", "Biggest pumps this week?", "Which tokens went up most in the last hour?", "Top gainers on Base". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.';category="blockchain-data";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. Defaults to the connected chain, or Ethereum (0x1).',required:!1},{name:"timeFrame",type:"string",description:`Window over which the price change is measured. Allowed values: "1h" (last hour), "1d" (last 24h), "1w" (last 7 days), "1M" (last 30 days). Pick the timeframe that matches the user's question \u2014 e.g. "today" \u2192 "1d", "this week" \u2192 "1w". Defaults to "1d".`,required:!1},{name:"limit",type:"number",description:'Number of top gainers to return. Only set this when the user asks for a specific count (e.g. "show 20 top gainers" \u2192 20). Omit otherwise.',required:!1}];service;constructor(e){super(),this.service=new te({baseUrl:e?.pantographUrl})}async run(e,t){let n=vn(e.chain,t),r=typeof e.timeFrame=="string"?e.timeFrame.trim():void 0;if(r&&!No.includes(r))return{error:`Invalid timeFrame "${r}". Allowed values: ${No.join(", ")}.`};let o=r||void 0,s=o?Io[o]:void 0,a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,i=await this.service.getTopGainers({chain:n,limit:a,duration:s});if(!i.success)return{error:i.error||"Failed to fetch top gainers"};let l=i.data??[];return{_instructions:`Start with a one-line header like "Here are the top gainers 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):
9
+ 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 (+3.56%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms. A "Buy" button is shown below your reply for each token automatically \u2014 do NOT mention, list, or repeat them.`,chain:n?E(n):"all",count:a.length,tokens:a,...u.length>0?{actionButtons:u}:{}}}async execute(e,t){let n=await super.execute(e,t),r=n.data;return n.success&&r&&Array.isArray(r.actionButtons)&&r.actionButtons.length>0&&(n.actionButtons=r.actionButtons),n}fillTemplate(e,t,n){return(e&&e.includes("{token}")?e:n).replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}};var cr={"1h":"1h","1d":"24h","1w":"7d","1M":"30d"},lr=Object.keys(cr),pt=class extends T{name="get-top-gainers";description='List tokens with the highest USD price increase over a chosen timeframe (1h / 1d / 1w / 1M). Returns name & symbol, current USD price, market cap, 24h volume, and the price change % over the selected window. Scoped to a single chain \u2014 pass `chain` to pick the network, otherwise the connected chain (or Ethereum) is used. Use this tool for questions like: "What are today\'s top gainers?", "Biggest pumps this week?", "Which tokens went up most in the last hour?", "Top gainers on Base". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.';category="blockchain-data";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. Defaults to the connected chain, or Ethereum (0x1).',required:!1},{name:"timeFrame",type:"string",description:`Window over which the price change is measured. Allowed values: "1h" (last hour), "1d" (last 24h), "1w" (last 7 days), "1M" (last 30 days). Pick the timeframe that matches the user's question \u2014 e.g. "today" \u2192 "1d", "this week" \u2192 "1w". Defaults to "1d".`,required:!1},{name:"limit",type:"number",description:'Number of top gainers to return. Only set this when the user asks for a specific count (e.g. "show 20 top gainers" \u2192 20). Omit otherwise.',required:!1}];service;constructor(e){super(),this.service=new ee({baseUrl:e?.pantographUrl})}async run(e,t){let n=Hn(e.chain,t),r=typeof e.timeFrame=="string"?e.timeFrame.trim():void 0;if(r&&!lr.includes(r))return{error:`Invalid timeFrame "${r}". Allowed values: ${lr.join(", ")}.`};let o=r||void 0,s=o?cr[o]:void 0,i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,a=await this.service.getTopGainers({chain:n,limit:i,duration:s});if(!a.success)return{error:a.error||"Failed to fetch top gainers"};let c=a.data??[];return{_instructions:`Start with a one-line header like "Here are the top gainers 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):
10
10
  <rank>. <name> (<symbol>)
11
11
  - Price: <usdPrice>
12
12
  - Market Cap: <marketCap>
13
13
  - Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
14
14
  - 24h Volume: <totalVolume.24h>
15
- 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?N(n):"all",timeFrame:o??null,count:l.length,tokens:l}}};var Je=class extends T{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. ';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. 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 R(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=kn(e.chain,t);if(r){let a=await this.service.getWalletTokenBalances({address:n,chain:r,excludeSpam:!1,excludeUnverifiedContracts:!1});return a.success?this.renderBalances(n,r,a.data?.result||[]):{error:a.error||"Failed to fetch token balances"}}let o=wo(),s=await Promise.all(o.map(async a=>{let i=await this.service.getWalletTokenBalances({address:n,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:a,tokens:i.success?i.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((i,l)=>i+(l.usd_value||0),0),a=o.tokens.slice().sort((i,l)=>(l.usd_value||0)-(i.usd_value||0));return{chain:N(o.chain),total:s,tokens:a}}).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 Ze=class extends T{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. 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 . 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 R(e)}async run(e,t){let n=Y(e.address,t),r=U(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,a=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,i=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,l=Number.isFinite(a)?a:void 0,u=Number.isFinite(i)?i:void 0,d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,p=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",h=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,g=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,f=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,y=Number.isFinite(f)&&f>0?f:10,k=await this.service.getWalletHistory({address:n,chain:r,limit:y,fromDate:o,toDate:s,fromBlock:l,toBlock:u,cursor:d,order:p,includeInternalTransactions:h,nftMetadata:g});if(!k.success)return{error:k.error||"Failed to fetch wallet history"};let w=k.data?.result||[];return{walletAddress:n,chain:r||"default",pagination:{cursor:k.data?.cursor??null,hasMore:!!k.data?.cursor},transactionCount:w.length,transactions:w}}};function zr(c){if(c.value_decimal)return c.value_decimal;let e=parseInt(c.token_decimals??"18",10);if(isNaN(e)||e===0)return c.value;try{let t=BigInt(c.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 c.value}}var et=class extends T{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. 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 . 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 R(e)}async run(e,t){let n=Y(e.address,t),r=U(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,a=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,i=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,l=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,p=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",f=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(x=>typeof x=="string"&&!!x).map(x=>x.trim()):void 0,k,w;if(f){let x=await this.resolveContractAddressBySymbol(f,n,r);x&&(y=[x.address],k=x.symbol,w=x.name)}let b=await this.service.getWalletTokenTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:a,toDate:i,fromBlock:l,toBlock:u,cursor:d,order:p});if(!b.success)return{error:b.error||"Failed to fetch token transfers"};let v=n.toLowerCase(),S=(b.data?.result||[]).map(x=>{let L=x.from_address.toLowerCase()===v,P=L?"send":"receive",H=L?x.to_address:x.from_address,Pe=L?x.to_address_label??void 0:x.from_address_label??void 0,ce=L?x.to_address_entity??void 0:x.from_address_entity??void 0;return{...x,direction:P,amount_formatted:zr(x),counterparty:H,counterparty_label:Pe,counterparty_entity:ce}}),C=g==="all"?S:S.filter(x=>x.direction===g);if(f&&!y){let x=f.toLowerCase();C=C.filter(L=>(L.token_symbol??"").toLowerCase()===x)}let D=this.buildCounterparties(C);return{walletAddress:n,chain:r||"default",resolvedToken:k?{symbol:k,name:w,contractAddress:y?.[0]}:null,filters:{tokenSymbol:f||null,contractAddresses:y||null,direction:g,limit:s,order:p,fromDate:a||null,toDate:i||null,fromBlock:l??null,toBlock:u??null},pagination:{cursor:b.data?.cursor??null,pageSize:b.data?.page_size??s,page:b.data?.page??null,hasMore:!!b.data?.cursor},transferCount:C.length,transfers:C,counterparties:D}}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 a=o.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}let s=await this.service.searchTokensByKey({key:e,chain:n});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===r)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let s=o.direction==="send"?t:n,a=o.counterparty.toLowerCase(),i=parseFloat(o.amount_formatted)||0,l=s.get(a);l?(l.total+=i,l.count+=1,!l.label&&o.counterparty_label&&(l.label=o.counterparty_label),!l.entity&&o.counterparty_entity&&(l.entity=o.counterparty_entity),o.block_timestamp<l.first&&(l.first=o.block_timestamp),o.block_timestamp>l.last&&(l.last=o.block_timestamp)):s.set(a,{label:o.counterparty_label,entity:o.counterparty_entity,total:i,count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((s,a)=>a[1].count-s[1].count).map(([s,a])=>({address:s,label:a.label,entity:a.entity,total_amount:a.total.toFixed(6).replace(/\.?0+$/,""),tx_count:a.count,first_seen:a.first,last_seen:a.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 tt=class extends T{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. 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 . 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 R(e)}async run(e,t){let n=Y(e.address,t),r=U(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,a=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,i=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,l=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,p=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",h=typeof e.includePrices=="boolean"?e.includePrices:void 0,g=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",f=g==="send"?"send":g==="receive"?"receive":"all",y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,k=await this.service.getWalletNftTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:a,toDate:i,fromBlock:l,toBlock:u,cursor:d,order:p,includePrices:h});if(!k.success)return{error:k.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),v=(k.data?.result||[]).map(C=>{let D=C.from_address.toLowerCase()===w,x=D?"send":"receive",L=D?C.to_address:C.from_address,P=D?C.to_address_label??void 0:C.from_address_label??void 0,H=D?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:x,counterparty:L,counterparty_label:P,counterparty_entity:H}}),A=f==="all"?v:v.filter(C=>C.direction===f),S=this.buildCounterparties(A);return{walletAddress:n,chain:r||"default",filters:{contractAddresses:y||null,direction:f,limit:s,order:p,fromDate:a||null,toDate:i||null,fromBlock:l??null,toBlock:u??null,includePrices:h??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??s,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:A.length,transfers:A,counterparties:S}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let s=o.direction==="send"?t:n,a=o.counterparty.toLowerCase(),i=o.token_name??o.token_address,l=s.get(a);l?(l.tokenIds.add(o.token_id),l.collections.add(i),l.count+=1,!l.label&&o.counterparty_label&&(l.label=o.counterparty_label),!l.entity&&o.counterparty_entity&&(l.entity=o.counterparty_entity),o.block_timestamp<l.first&&(l.first=o.block_timestamp),o.block_timestamp>l.last&&(l.last=o.block_timestamp)):s.set(a,{label:o.counterparty_label,entity:o.counterparty_entity,tokenIds:new Set([o.token_id]),collections:new Set([i]),count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((s,a)=>a[1].count-s[1].count).map(([s,a])=>({address:s,label:a.label,entity:a.entity,token_ids:Array.from(a.tokenIds),collections:Array.from(a.collections),tx_count:a.count,first_seen:a.first,last_seen:a.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 Tn=class extends T{name="get-wallet-net-worth";description=`Get a wallet's total net worth in USD, with a per-chain breakdown. Returns: total_networth_usd (grand total across all queried chains), chains[] (each with chain, native_balance_formatted, native_balance_usd, token_balance_usd, networth_usd), and optional unsupported_chain_ids / unavailable_chains lists. Use this tool for questions like: "How much is my wallet worth?", "What is my total portfolio value?", "What is my net worth on Ethereum?", "Portfolio value across all chains?". Pass chains=["0x1","0x2105"] to query multiple chains at once; defaults to the connected chain. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. Do NOT use for: individual token balances \u2192 get-wallet-token-balances; realized profit/loss \u2192 get-wallet-pnl-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:"chains",type:"array",description:'One or more hex chain IDs to aggregate. Values: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea If omitted, defaults to the connected chain.',required:!1,items:{type:"string"}},{name:"excludeSpam",type:"boolean",description:"Exclude tokens flagged as spam. Default true for cleaner totals.",required:!1,default:!0},{name:"excludeUnverifiedContracts",type:"boolean",description:"Exclude unverified token contracts. Default false.",required:!1,default:!1},{name:"maxTokenInactivity",type:"number",description:"Exclude tokens that have been inactive for more than N days.",required:!1},{name:"minPairSideLiquidityUsd",type:"number",description:"Exclude tokens with pair-side liquidity below this USD threshold.",required:!1}];service;constructor(e){super(),this.service=new R(e)}async run(e,t){let n=e.address||t?.walletAddress||void 0;if(!n)return{error:'No wallet address available. Please connect a wallet or pass "address".'};let r=Array.isArray(e.chains)?e.chains.filter(p=>typeof p=="string"&&!!p).map(p=>p.trim()):void 0,o=t?.chain,s=r&&r.length>0?r:o?[o]:void 0,a=typeof e.excludeSpam=="boolean"?e.excludeSpam:!0,i=typeof e.excludeUnverifiedContracts=="boolean"?e.excludeUnverifiedContracts:void 0,l=typeof e.maxTokenInactivity=="number"&&Number.isFinite(e.maxTokenInactivity)?e.maxTokenInactivity:void 0,u=typeof e.minPairSideLiquidityUsd=="number"&&Number.isFinite(e.minPairSideLiquidityUsd)?e.minPairSideLiquidityUsd:void 0,d=await this.service.getWalletNetWorth({address:n,chains:s,excludeSpam:a,excludeUnverifiedContracts:i,maxTokenInactivity:l,minPairSideLiquidityUsd:u});if(!d.success)return{error:d.error||"Failed to fetch wallet net worth"};let m=d.data;return{walletAddress:n,chainsQueried:s??["default"],filters:{excludeSpam:a,excludeUnverifiedContracts:i??null,maxTokenInactivity:l??null,minPairSideLiquidityUsd:u??null},totalNetWorthUsd:m.total_networth_usd,chains:m.chains,unsupportedChainIds:m.unsupported_chain_ids??[],unavailableChains:m.unavailable_chains??[]}}};var Qr=["all","7","30","60","90"],nt=class extends T{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 so the connected wallet chain is used.',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 R(e)}async run(e,t){let n=Y(e.address,t),r=U(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=Qr.includes(o)?o:void 0,a=await this.service.getWalletPnlSummary({address:n,chain:r,days:s});if(!a.success)return{error:a.error||"Failed to fetch wallet PnL summary"};let i=a.data;return{walletAddress:n,chain:r||"default",days:s??"all",summary:{totalCountOfTrades:i.total_count_of_trades,totalTradeVolume:i.total_trade_volume,totalRealizedProfitUsd:i.total_realized_profit_usd,totalRealizedProfitPercentage:i.total_realized_profit_percentage,totalBuys:i.total_buys,totalSells:i.total_sells,totalBoughtVolumeUsd:i.total_bought_volume_usd,totalSoldVolumeUsd:i.total_sold_volume_usd}}}};var Xr=["all","7","30","60","90"],Sn=25,ot=class extends T{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 ${Sn}. 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 so the connected wallet chain is used.',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 ${Sn}.`,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 ${Sn}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new R(e)}async run(e,t){let n=Y(e.address,t),r=U(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=Xr.includes(o)?o:void 0,a=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(g=>typeof g=="string"&&!!g.trim()).map(g=>g.trim()):[],i=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(g=>typeof g=="string"&&!!g.trim()).map(g=>g.trim()):[],l=[],u=[];a.length>0&&(await Promise.all(a.map(f=>this.resolveContractAddress(f,r,n)))).forEach((f,y)=>{f?l.push({symbol:a[y],address:f.address}):u.push(a[y])});let d=Jr([...l.map(g=>g.address),...i]).slice(0,Sn),m=d.length>0?d:void 0,p=await this.service.getWalletPnl({address:n,chain:r,days:s,tokenAddresses:m});if(!p.success)return{error:p.error||"Failed to fetch wallet PnL"};let h=p.data?.result??[];return{walletAddress:n,chain:r||"default",days:s??"all",filters:{tokenAddresses:m??null,resolvedSymbols:l.length>0?l:null,unresolvedSymbols:u.length>0?u:null},tokenCount:h.length,tokens:h}}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 a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};function Jr(c){let e=new Set,t=[];for(let n of c){let r=n.toLowerCase();e.has(r)||(e.add(r),t.push(n))}return t}var Zr=BigInt(2)**BigInt(255),rt=class extends T{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 (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. 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 R(e)}async run(e,t){let n=Y(e.address,t),r=U(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,a=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,i=await this.service.getWalletApprovals({address:n,chain:r,limit:s,cursor:a});if(!i.success)return{error:i.error||"Failed to fetch wallet approvals"};let l=i.data,d=(l.result||[]).map(g=>es(g)),m=0,p=0,h=[];for(let g of d){g.isUnlimited&&(p+=1);let f=parseFloat(g.token.usdAtRisk??"");Number.isFinite(f)&&(m+=f);let y=g.token.possibleSpam||g.token.verifiedContract===!1,k=!g.spender.label&&!g.spender.entity;(y||g.isUnlimited&&k)&&h.push(g)}return{walletAddress:n,chain:r||"default",filters:{limit:s,cursor:a??null},pagination:{cursor:l.cursor??null,pageSize:l.page_size??s,page:l.page??null,hasMore:!!l.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:p,totalUsdAtRisk:m,riskyApprovalCount:h.length},approvals:d,riskyApprovals:h}}};function es(c){let e=ts(c.value);return{blockNumber:c.block_number,blockTimestamp:c.block_timestamp??null,transactionHash:c.transaction_hash??null,value:c.value,valueFormatted:c.value_formatted??null,isUnlimited:e,token:{address:c.token.address,addressLabel:c.token.address_label??null,name:c.token.name??null,symbol:c.token.symbol??null,logo:c.token.logo??null,possibleSpam:!!c.token.possible_spam,verifiedContract:c.token.verified_contract??null,currentBalance:c.token.current_balance??null,currentBalanceFormatted:c.token.current_balance_formatted??null,usdPrice:c.token.usd_price??null,usdAtRisk:c.token.usd_at_risk??null},spender:{address:c.spender.address,label:c.spender.address_label??null,entity:c.spender.entity??null,entityLogo:c.spender.entity_logo??null}}}function ts(c){if(!c)return!1;try{return BigInt(c)>=Zr}catch{return!1}}var st=class extends T{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 (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. 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 R(e)}async run(e,t){let n=Y(e.address,t),r=U(e.chain,t),o=await this.service.getWalletDefiSummary({address:n,chain:r});if(!o.success)return{error:o.error||"Failed to fetch wallet DeFi summary"};let s=o.data;return{walletAddress:n,chain:r||"default",activeProtocols:s.active_protocols,totalPositions:s.total_positions,totalUsdValue:s.total_usd_value,totalUnclaimedUsdValue:s.total_unclaimed_usd_value,protocols:(s.protocols||[]).map(a=>({protocolName:a.protocol_name,protocolId:a.protocol_id,protocolUrl:a.protocol_url,protocolLogo:a.protocol_logo,positions:a.positions,totalUsdValue:a.total_usd_value,totalUnclaimedUsdValue:a.total_unclaimed_usd_value,accountHealthFactor:a.account_health_factor??null}))}}};var at=class extends T{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. 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. 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 R(e)}async run(e,t){let n=Y(e.address,t),r=U(e.chain,t),o=await this.service.getWalletDefiPositions({address:n,chain:r});if(!o.success)return{error:o.error||"Failed to fetch wallet DeFi positions"};let s=o.data||[];return{walletAddress:n,chain:r||"default",positionCount:s.length,positions:s.map(a=>ns(a))}}};function ns(c){return{protocolName:c.protocol_name,protocolId:c.protocol_id,protocolUrl:c.protocol_url,protocolLogo:c.protocol_logo,accountHealthFactor:c.account_data?.health_factor??null,position:os(c.position)}}function os(c){return{label:c.label,address:c.address,balanceUsd:c.balance_usd,totalUnclaimedUsdValue:c.total_unclaimed_usd_value,tokens:(c.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:c.position_details??null}}var it=class extends T{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 (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. 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 R(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=U(e.chain,t),s=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:o});if(!s.success)return{error:s.error||"Failed to fetch wallet DeFi protocol positions"};let a=s.data;return a?{walletAddress:r,chain:o||"default",protocolName:a.protocol_name,protocolId:a.protocol_id,protocolUrl:a.protocol_url,protocolLogo:a.protocol_logo,totalUsdValue:a.total_usd_value,totalUnclaimedUsdValue:a.total_unclaimed_usd_value,accountHealthFactor:a.account_data?.health_factor??null,positionCount:(a.positions||[]).length,positions:(a.positions||[]).map(rs)}:{error:"No data returned for this protocol"}}};function rs(c){return{label:c.label,address:c.address,balanceUsd:c.balance_usd,totalUnclaimedUsdValue:c.total_unclaimed_usd_value,tokens:(c.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:c.position_details??null}}function ss(c){try{return(Number(BigInt(c))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return c}}var lt=class extends T{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.';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. 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 R(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let r=U(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,a=(s.logs??[]).filter(l=>!!l.decoded_event).map(l=>({contract:l.address,signature:l.decoded_event.signature,label:l.decoded_event.label,params:l.decoded_event.params})),i=s.logs.map(l=>({address:l.address,decodedEvent:l.decoded_event?{signature:l.decoded_event.signature,label:l.decoded_event.label,params:l.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:ss(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:a,contractCreated:s.receipt_contract_address||null,logs:i}}};var ct=class extends T{kind="data";category="nft";noSuggestions=!0;parameters=[];linkPhrase="this website";url;constructor(e){super();let t=e?.url?.trim();this.url=t||void 0}async run(){let e=this.url?`[${this.linkPhrase}](${this.url})`:this.linkPhrase,t=this.template.replace("{link}",e);return{message:t,_instructions:"This is a fixed notice that ALREADY contains the correct Markdown link. Reply with a SINGLE sentence in the USER'S language that conveys it (translate the wording naturally \u2014 do NOT leave it in English when the user wrote another language). "+(this.url?`You MUST reproduce the Markdown link and keep it CLICKABLE: keep the URL byte-for-byte; you may localize only the visible link text. Keep the form [text](${this.url}). NEVER output the sentence without the link, and NEVER show the raw URL on its own. `:"There is NO website link configured: keep the website phrase as PLAIN TEXT. NEVER add, invent, guess, or fabricate any URL or Markdown link \u2014 there is no link to show. ")+`Output ONLY that one sentence \u2014 do NOT also include the original English, a second copy, or any preamble. Do not mention tools. The exact message to convey (it already includes the link):
15
+ 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?E(n):"all",timeFrame:o??null,count:c.length,tokens:c}}};var mt=class extends T{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. ';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. 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=K(e.address,t),r=ie(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=me(),s=await Promise.all(o.map(async i=>{let a=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:a.success?a.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((a,c)=>a+(c.usd_value||0),0),i=o.tokens.slice().sort((a,c)=>(c.usd_value||0)-(a.usd_value||0));return{chain:E(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 ht=class extends T{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. 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 . 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=K(e.address,t),r=M(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,a=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(a)?a: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",g=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,f=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,y=Number.isFinite(f)&&f>0?f: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:g,nftMetadata:h});if(!b.success)return{error:b.error||"Failed to fetch wallet history"};let v=(b.data?.result||[]).map(k=>{let A=jo(r,k.hash);return A?{...k,explorerUrl:A}:k});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:v.length,transactions:v}}};function Ns(l){if(l.value_decimal)return l.value_decimal;let e=parseInt(l.token_decimals??"18",10);if(isNaN(e)||e===0)return l.value;try{let t=BigInt(l.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 l.value}}var gt=class extends T{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. 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 . 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=K(e.address,t),r=M(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,a=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",g=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=g==="send"?"send":g==="receive"?"receive":"all",f=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(f){let C=await this.resolveContractAddressBySymbol(f,n,r);C&&(y=[C.address],b=C.symbol,w=C.name)}let v=await this.service.getWalletTokenTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:i,toDate:a,fromBlock:c,toBlock:u,cursor:d,order:m});if(!v.success)return{error:v.error||"Failed to fetch token transfers"};let k=n.toLowerCase(),x=(v.data?.result||[]).map(C=>{let B=C.from_address.toLowerCase()===k,_=B?"send":"receive",N=B?C.to_address:C.from_address,ve=B?C.to_address_label??void 0:C.from_address_label??void 0,Le=B?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:_,amount_formatted:Ns(C),counterparty:N,counterparty_label:ve,counterparty_entity:Le}}),S=h==="all"?x:x.filter(C=>C.direction===h);if(f&&!y){let C=f.toLowerCase();S=S.filter(B=>(B.token_symbol??"").toLowerCase()===C)}let O=this.buildCounterparties(S);return{walletAddress:n,chain:r||"default",resolvedToken:b?{symbol:b,name:w,contractAddress:y?.[0]}:null,filters:{tokenSymbol:f||null,contractAddresses:y||null,direction:h,limit:s,order:m,fromDate:i||null,toDate:a||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:v.data?.cursor??null,pageSize:v.data?.page_size??s,page:v.data?.page??null,hasMore:!!v.data?.cursor},transferCount:S.length,transfers:S,counterparties:O}}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(a=>(a.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 a=s.data.find(c=>(c.symbol??"").toLowerCase()===r)??s.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.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(),a=parseFloat(o.amount_formatted)||0,c=s.get(i);c?(c.total+=a,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:a,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 ft=class extends T{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. 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 . 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=K(e.address,t),r=M(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,a=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",g=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",f=h==="send"?"send":h==="receive"?"receive":"all",y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(S=>typeof S=="string"&&!!S).map(S=>S.trim()):void 0,b=await this.service.getWalletNftTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:i,toDate:a,fromBlock:c,toBlock:u,cursor:d,order:m,includePrices:g});if(!b.success)return{error:b.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),k=(b.data?.result||[]).map(S=>{let O=S.from_address.toLowerCase()===w,C=O?"send":"receive",B=O?S.to_address:S.from_address,_=O?S.to_address_label??void 0:S.from_address_label??void 0,N=O?S.to_address_entity??void 0:S.from_address_entity??void 0;return{...S,direction:C,counterparty:B,counterparty_label:_,counterparty_entity:N}}),A=f==="all"?k:k.filter(S=>S.direction===f),x=this.buildCounterparties(A);return{walletAddress:n,chain:r||"default",filters:{contractAddresses:y||null,direction:f,limit:s,order:m,fromDate:i||null,toDate:a||null,fromBlock:c??null,toBlock:u??null,includePrices:g??null},pagination:{cursor:b.data?.cursor??null,pageSize:b.data?.page_size??s,page:b.data?.page??null,hasMore:!!b.data?.cursor},transferCount:A.length,transfers:A,counterparties:x}}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(),a=o.token_name??o.token_address,c=s.get(i);c?(c.tokenIds.add(o.token_id),c.collections.add(a),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([a]),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 Is=["all","7","30","60","90"],yt=class extends T{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=K(e.address,t),r=ie(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=Is.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 a=(await Promise.all(me().map(async h=>{let f=await this.service.getWalletPnlSummary({address:n,chain:h,days:s});return{chain:h,data:f.success?f.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=a.map(h=>({chain:E(h.chain),summary:this.mapSummary(h.data)})),u=a.reduce((h,f)=>h+Number(f.data.total_realized_profit_usd||0),0),d=a.reduce((h,f)=>h+Number(f.data.total_bought_volume_usd||0),0),p=a.reduce((h,f)=>h+Number(f.data.total_sold_volume_usd||0),0),m=a.reduce((h,f)=>h+Number(f.data.total_trade_volume||0),0),g={totalCountOfTrades:a.reduce((h,f)=>h+f.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:a.reduce((h,f)=>h+f.data.total_buys,0),totalSells:a.reduce((h,f)=>h+f.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:g,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 Ls=["all","7","30","60","90"],Gn=25,bt=class extends T{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 ${Gn}. 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 ${Gn}.`,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 ${Gn}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=K(e.address,t),r=ie(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=Ls.includes(o)?o:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],a=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,a);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(me().map(async d=>({chain:d,res:await this.fetchChainPnl(n,d,s,i,a)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:E(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:a.length>0?a: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 a=Ds([...s.map(d=>d.address),...o]).slice(0,Gn),c=a.length>0?a: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(a=>(a.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(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Ds(l){let e=new Set,t=[];for(let n of l){let r=n.toLowerCase();e.has(r)||(e.add(r),t.push(n))}return t}var Os=BigInt(2)**BigInt(255),wt=class extends T{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 (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. 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=K(e.address,t),r=M(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,a=await this.service.getWalletApprovals({address:n,chain:r,limit:s,cursor:i});if(!a.success)return{error:a.error||"Failed to fetch wallet approvals"};let c=a.data,d=(c.result||[]).map(h=>Ms(h)),p=0,m=0,g=[];for(let h of d){h.isUnlimited&&(m+=1);let f=parseFloat(h.token.usdAtRisk??"");Number.isFinite(f)&&(p+=f);let y=h.token.possibleSpam||h.token.verifiedContract===!1,b=!h.spender.label&&!h.spender.entity;(y||h.isUnlimited&&b)&&g.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:g.length},approvals:d,riskyApprovals:g}}};function Ms(l){let e=Bs(l.value);return{blockNumber:l.block_number,blockTimestamp:l.block_timestamp??null,transactionHash:l.transaction_hash??null,value:l.value,valueFormatted:l.value_formatted??null,isUnlimited:e,token:{address:l.token.address,addressLabel:l.token.address_label??null,name:l.token.name??null,symbol:l.token.symbol??null,logo:l.token.logo??null,possibleSpam:!!l.token.possible_spam,verifiedContract:l.token.verified_contract??null,currentBalance:l.token.current_balance??null,currentBalanceFormatted:l.token.current_balance_formatted??null,usdPrice:l.token.usd_price??null,usdAtRisk:l.token.usd_at_risk??null},spender:{address:l.spender.address,label:l.spender.address_label??null,entity:l.spender.entity??null,entityLogo:l.spender.entity_logo??null}}}function Bs(l){if(!l)return!1;try{return BigInt(l)>=Os}catch{return!1}}var kt=class extends T{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 (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. 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=K(e.address,t),r=ie(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(me().map(async i=>{let a=await this.service.getWalletDefiSummary({address:n,chain:i});return{chain:i,data:a.success?a.data:void 0}}))).flatMap(i=>i.data&&i.data.active_protocols>0?[{chain:E(i.chain),data:i.data}]:[]).map(i=>({chain:i.chain,...this.summaryFields(i.data)})).sort((i,a)=>a.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,a)=>i+a.totalUsdValue,0),totalUnclaimedUsdValue:s.reduce((i,a)=>i+a.totalUnclaimedUsdValue,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 vt=class extends T{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. 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. 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=K(e.address,t),r=ie(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 a=i.data||[];return{walletAddress:n,chain:r,positionCount:a.length,positions:a.map(ur)}}let s=(await Promise.all(me().map(async i=>{let a=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:a.success?a.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:E(i.chain),positionCount:i.rows.length,positions:i.rows.map(ur)}));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,a)=>i+a.positionCount,0),chains:s}}};function ur(l){return{protocolName:l.protocol_name,protocolId:l.protocol_id,protocolUrl:l.protocol_url,protocolLogo:l.protocol_logo,accountHealthFactor:l.account_data?.health_factor??null,position:qs(l.position)}}function qs(l){return{label:l.label,address:l.address,balanceUsd:l.balance_usd,totalUnclaimedUsdValue:l.total_unclaimed_usd_value,tokens:(l.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:l.position_details??null}}var Tt=class extends T{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 (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. 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=K(e.address,t),o=ie(e.chain,t);if(o){let a=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:o});return a.success?a.data?{walletAddress:r,chain:o,...this.protocolFields(a.data)}:{error:"No data returned for this protocol"}:{error:a.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(me().map(async a=>{let c=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:a});return{chain:a,data:c.success?c.data:void 0}}))).flatMap(a=>a.data&&(a.data.positions||[]).length>0?[{chain:E(a.chain),data:a.data}]:[]).map(a=>({chain:a.chain,...this.protocolFields(a.data)})).sort((a,c)=>c.totalUsdValue-a.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((a,c)=>a+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(Fs)}}};function Fs(l){return{label:l.label,address:l.address,balanceUsd:l.balance_usd,totalUnclaimedUsdValue:l.total_unclaimed_usd_value,tokens:(l.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:l.position_details??null}}function $s(l){try{return(Number(BigInt(l))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return l}}var At=class extends T{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.';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. 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=M(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})),a=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:$s(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:a}}};var St=class extends T{kind="data";category="nft";noSuggestions=!0;parameters=[];linkPhrase="this website";url;constructor(e){super();let t=e?.url?.trim();this.url=t||void 0}async run(){let e=this.url?`[${this.linkPhrase}](${this.url})`:this.linkPhrase,t=this.template.replace("{link}",e);return{message:t,_instructions:"This is a fixed notice that ALREADY contains the correct Markdown link. Reply with a SINGLE sentence in the USER'S language that conveys it (translate the wording naturally \u2014 do NOT leave it in English when the user wrote another language). "+(this.url?`You MUST reproduce the Markdown link and keep it CLICKABLE: keep the URL byte-for-byte; you may localize only the visible link text. Keep the form [text](${this.url}). NEVER output the sentence without the link, and NEVER show the raw URL on its own. `:"There is NO website link configured: keep the website phrase as PLAIN TEXT. NEVER add, invent, guess, or fabricate any URL or Markdown link \u2014 there is no link to show. ")+`Output ONLY that one sentence \u2014 do NOT also include the original English, a second copy, or any preamble. Do not mention tools. The exact message to convey (it already includes the link):
16
16
 
17
- `+t}}};var ut=class extends ct{name="get-wallet-nfts";description='Use when the user wants to view their NFTs / NFT collection / holdings ("my NFTs", "show my NFTs", "what NFTs do I own", "NFT collection"). Returns a fixed notice directing them to the NFT website. Takes no arguments.';template="Please view your NFT collection on {link} for more details"};var fe=class extends T{kind="data";category="nft";llm;constructor(){super(),this.llm=new ne({})}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:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var dt=class extends fe{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=fe.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 mt=class extends fe{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=fe.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 pt=class extends T{name="gemini-search-ai";description="Ask a search-grounded Gemini model for blockchain / crypto insights that no dedicated tool can answer. Use this as a LAST-RESORT fallback when the specialised data tools are insufficient. Backed by live Google Search grounding \u2014 good for: market analysis, category/theme queries (meme, AI, gaming, L2, RWA), DeFi protocol explanations, cross-chain comparisons, trend / sentiment, recent news or announcements, gas insights, NFT collection lore, and any open-ended crypto reasoning question. Chain-agnostic \u2014 write the chain (Ethereum, BSC, Base, \u2026) and any addresses, time range, or token symbols directly into the prompt. Do NOT use this for: token balances \u2192 get-wallet-token-balances; token prices/metadata \u2192 get-token-info; NFT holdings \u2192 get-wallet-nfts; NFT contract info \u2192 get-nft-contract-info; transaction details \u2192 get-transaction-by-hash; wallet history \u2192 get-wallet-history; token transfers \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; token holders \u2192 get-token-holders; wallet PnL \u2192 get-wallet-pnl or get-wallet-pnl-summary; pool / liquidity data \u2192 pool-agent tools.";category="blockchain-ai";parameters=[{name:"prompt",type:"string",description:'A clear, self-contained English question for the AI. Must include every detail needed to answer without the conversation context: chain (Ethereum / BSC / Base / \u2026), wallet or contract addresses, token symbols, time range, what to compare or rank. Instruct the model to use up-to-date web sources when relevant. Example: "List the top 10 meme-category tokens on Ethereum right now, ranked by 24h trading volume, using up-to-date market data."',required:!0}];llm;constructor(e){super(),this.llm=new ne(e??{})}async run(e,t){let n=typeof e.prompt=="string"?e.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=[];t?.walletAddress&&r.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&r.push(`- Current chain: ${t.chain}`),r.push("Use this context only when relevant to the question. Do not invent on-chain values.");let o=Date.now(),s=[{role:"system",content:`[USER CONTEXT]
17
+ `+t}}};var Pt=class extends St{name="get-wallet-nfts";description='Use when the user wants to view their NFTs / NFT collection / holdings ("my NFTs", "show my NFTs", "what NFTs do I own", "NFT collection"). Returns a fixed notice directing them to the NFT website. Takes no arguments.';template="Please view your NFT collection on {link} for more details"};var Se=class extends T{kind="data";category="nft";llm;constructor(){super(),this.llm=new re({})}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:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var xt=class extends Se{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=Se.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 _t=class extends Se{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=Se.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 Ct=class extends T{name="gemini-search-ai";description="Ask a search-grounded Gemini model for blockchain / crypto insights that no dedicated tool can answer. Use this as a LAST-RESORT fallback when the specialised data tools are insufficient. Backed by live Google Search grounding \u2014 good for: market analysis, category/theme queries (meme, AI, gaming, L2, RWA), DeFi protocol explanations, cross-chain comparisons, trend / sentiment, recent news or announcements, gas insights, NFT collection lore, and any open-ended crypto reasoning question. Chain-agnostic \u2014 write the chain (Ethereum, BSC, Base, \u2026) and any addresses, time range, or token symbols directly into the prompt. Do NOT use this for: token balances \u2192 get-wallet-token-balances; token prices/metadata \u2192 get-token-info; NFT holdings \u2192 get-wallet-nfts; NFT contract info \u2192 get-nft-contract-info; transaction details \u2192 get-transaction-by-hash; wallet history \u2192 get-wallet-history; token transfers \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; token holders \u2192 get-token-holders; wallet PnL \u2192 get-wallet-pnl or get-wallet-pnl-summary; pool / liquidity data \u2192 pool-agent tools.";category="blockchain-ai";parameters=[{name:"prompt",type:"string",description:'A clear, self-contained English question for the AI. Must include every detail needed to answer without the conversation context: chain (Ethereum / BSC / Base / \u2026), wallet or contract addresses, token symbols, time range, what to compare or rank. Instruct the model to use up-to-date web sources when relevant, and to cite approximate dates and the source/outlet for any news it reports. For market-direction or "why is X up/down" questions, explicitly ask the model to identify the concrete CATALYST behind the move (listing, unlock, partnership, hack, macro, narrative rotation, whale flows) rather than just restating the price change, and to end with a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and what to watch) without giving financial advice or price targets. Example: "List the top 10 meme-category tokens on Ethereum right now, ranked by 24h trading volume, using up-to-date market data." Example: "Explain why PEPE on Ethereum has moved over the last 7 days: identify the main catalyst(s) with dated, sourced news, summarize sentiment, and give a brief hedged short-term outlook."',required:!0}];llm;constructor(e){super(),this.llm=new re(e??{})}async run(e,t){let n=typeof e.prompt=="string"?e.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=[];t?.walletAddress&&r.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&r.push(`- Current chain: ${t.chain}`),r.push("Use this context only when relevant to the question. Do not invent on-chain values.");let o=Date.now(),s=[{role:"system",content:`[USER CONTEXT]
18
18
  ${r.join(`
19
- `)}`,timestamp:o},{role:"user",content:n,timestamp:o}];try{return{source:"gemini-search-ai",answer:(await this.llm.chat(s,void 0,{googleSearch:!0,maxRetries:1})).text?.trim()??""}}catch(a){return{error:a instanceof Error?a.message:String(a)}}}};var as=`You are a world-class DEX liquidity-pool master and analyst \u2014 the deepest pool expert there is.
19
+ `)}`,timestamp:o},{role:"user",content:n,timestamp:o}];try{return{source:"gemini-search-ai",answer:(await this.llm.chat(s,void 0,{googleSearch:!0,maxRetries:1})).text?.trim()??""}}catch(i){return{error:i instanceof Error?i.message:String(i)}}}};var Vs=`You are a world-class DEX liquidity-pool master and analyst \u2014 the deepest pool expert there is.
20
20
  You know everything about liquidity pools across protocols and chains: Uniswap V2/V3/V4, PancakeSwap, Curve, Balancer, SushiSwap, Aerodrome, and more.
21
21
  Your expertise covers: concentrated liquidity and tick ranges, fee tiers, TVL / 24h volume / fee APR, impermanent loss, LP position management and rebalancing, range strategy (wide vs narrow), pool health and risk, MEV / slippage, incentives & farming, and how pool mechanics differ between AMM designs.
22
22
  You answer ANY pool-related question \u2014 conceptual, strategic, comparative, or current-events \u2014 clearly and accurately.
23
23
  Use the live Google Search grounding you are given to back claims with up-to-date data (TVL, volumes, APRs, recent protocol changes) whenever relevant; never invent specific on-chain numbers.
24
- Be concise, practical, and honest about uncertainty. End anything that touches returns or strategy with a brief reminder that it is informational, not financial advice. Answer in the user's language. Do NOT mention tools, APIs, or that you are a fallback.`,ht=class extends T{name="pool-fallback-ai";description="Ask a master liquidity-pool analyst (search-grounded AI) any DEX pool question that no structured pool tool can answer. This is the LAST-RESORT pool fallback. Backed by live Google Search \u2014 great for: how Uniswap V3 / V4 pools and concentrated liquidity work, fee-tier and range strategy, impermanent loss, comparing protocols (Uniswap vs Curve vs PancakeSwap \u2026), pool risk / safety, incentives & farming, recent pool-related news or protocol changes, and any open-ended or conceptual pool reasoning. Chain-agnostic \u2014 write the chain (Ethereum, BSC, Base, \u2026) and any pool address or token symbols directly into the prompt. Do NOT use this when a structured subgraph tool fits (pool search, trending pools, pool/position detail by address or id, price-range candidates, add-liquidity) \u2014 only when none of them can serve the question.";category="blockchain-ai";parameters=[{name:"prompt",type:"string",description:'A clear, self-contained English question for the pool master. Must include every detail needed to answer without the conversation context: chain (Ethereum / BSC / Base / \u2026), pool address or token symbols, fee tier, time range, what to compare or explain. Instruct the model to use up-to-date web sources when relevant. Example: "Explain how to choose a price range for an ETH/USDC 0.05% Uniswap V3 pool on Base, and the trade-offs between a narrow and a wide range, using current market context."',required:!0}];llm;constructor(e){super(),this.llm=new ne(e??{})}async run(e,t){let n=typeof e.prompt=="string"?e.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=[];t?.walletAddress&&r.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&r.push(`- Current chain: ${t.chain}`),r.push("Use this context only when relevant to the question. Do not invent on-chain values.");let o=Date.now(),s=[{role:"system",content:as,timestamp:o},{role:"system",content:`[USER CONTEXT]
24
+ Be concise, practical, and honest about uncertainty. End anything that touches returns or strategy with a brief reminder that it is informational, not financial advice. Answer in the user's language. Do NOT mention tools, APIs, or that you are a fallback.`,Et=class extends T{name="pool-fallback-ai";description="Ask a master liquidity-pool analyst (search-grounded AI) any DEX pool question that no structured pool tool can answer. This is the LAST-RESORT pool fallback. Backed by live Google Search \u2014 great for: how Uniswap V3 / V4 pools and concentrated liquidity work, fee-tier and range strategy, impermanent loss, comparing protocols (Uniswap vs Curve vs PancakeSwap \u2026), pool risk / safety, incentives & farming, recent pool-related news or protocol changes, and any open-ended or conceptual pool reasoning. Chain-agnostic \u2014 write the chain (Ethereum, BSC, Base, \u2026) and any pool address or token symbols directly into the prompt. Do NOT use this when a structured subgraph tool fits (pool search, trending pools, pool/position detail by address or id, price-range candidates, add-liquidity) \u2014 only when none of them can serve the question.";category="blockchain-ai";parameters=[{name:"prompt",type:"string",description:'A clear, self-contained English question for the pool master. Must include every detail needed to answer without the conversation context: chain (Ethereum / BSC / Base / \u2026), pool address or token symbols, fee tier, time range, what to compare or explain. Instruct the model to use up-to-date web sources when relevant. Example: "Explain how to choose a price range for an ETH/USDC 0.05% Uniswap V3 pool on Base, and the trade-offs between a narrow and a wide range, using current market context."',required:!0}];llm;constructor(e){super(),this.llm=new re(e??{})}async run(e,t){let n=typeof e.prompt=="string"?e.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=[];t?.walletAddress&&r.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&r.push(`- Current chain: ${t.chain}`),r.push("Use this context only when relevant to the question. Do not invent on-chain values.");let o=Date.now(),s=[{role:"system",content:Vs,timestamp:o},{role:"system",content:`[USER CONTEXT]
25
25
  ${r.join(`
26
- `)}`,timestamp:o},{role:"user",content:n,timestamp:o}];try{return{source:"pool-fallback-ai",answer:(await this.llm.chat(s,void 0,{googleSearch:!0,maxRetries:1})).text?.trim()??""}}catch(a){return{error:a instanceof Error?a.message:String(a)}}}};var is="https://interface.gateway.uniswap.org",ls="/v2/uniswap.explore.v1.ExploreStatsService/ExploreStats",Lo="/v2/Search.v1.SearchService/SearchTokens",cs="/v1/graphql",Ee=3,An=800,us={"0x1":"ETHEREUM","0xa":"OPTIMISM","0x38":"BNB","0x89":"POLYGON","0x2105":"BASE","0xa4b1":"ARBITRUM","0xa86a":"AVALANCHE","0xe708":"LINEA"},ds=`query V3Pool($chain: Chain!, $address: String!) {
26
+ `)}`,timestamp:o},{role:"user",content:n,timestamp:o}];try{return{source:"pool-fallback-ai",answer:(await this.llm.chat(s,void 0,{googleSearch:!0,maxRetries:1})).text?.trim()??""}}catch(i){return{error:i instanceof Error?i.message:String(i)}}}};var Ws="https://interface.gateway.uniswap.org",Hs="/v2/uniswap.explore.v1.ExploreStatsService/ExploreStats",dr="/v2/Search.v1.SearchService/SearchTokens",Gs="/v1/graphql",Me=3,Yn=800,Ys={"0x1":"ETHEREUM","0xa":"OPTIMISM","0x38":"BNB","0x89":"POLYGON","0x2105":"BASE","0xa4b1":"ARBITRUM","0xa86a":"AVALANCHE","0xe708":"LINEA"},Ks=`query V3Pool($chain: Chain!, $address: String!) {
27
27
  v3Pool(chain: $chain, address: $address) {
28
28
  id
29
29
  protocolVersion
@@ -56,7 +56,7 @@ fragment TokenPrice on Token {
56
56
  id
57
57
  market(currency: USD) { id price { id value __typename } __typename }
58
58
  __typename
59
- }`,Mo=`
59
+ }`,gr=`
60
60
  fragment SimpleTokenDetails on Token {
61
61
  ...TokenBasicInfoParts
62
62
  project { id isSpam logoUrl name safetyLevel __typename }
@@ -71,7 +71,7 @@ fragment TokenPrice on Token {
71
71
  id
72
72
  market(currency: USD) { id price { id value __typename } __typename }
73
73
  __typename
74
- }`,ms=`query V2Pair($chain: Chain!, $address: String!) {
74
+ }`,js=`query V2Pair($chain: Chain!, $address: String!) {
75
75
  v2Pair(chain: $chain, address: $address) {
76
76
  id
77
77
  protocolVersion
@@ -88,7 +88,7 @@ fragment TokenPrice on Token {
88
88
  __typename
89
89
  }
90
90
  }
91
- ${Mo}`,ps=`query V4Pool($chain: Chain!, $poolId: String!) {
91
+ ${gr}`,zs=`query V4Pool($chain: Chain!, $poolId: String!) {
92
92
  v4Pool(chain: $chain, poolId: $poolId) {
93
93
  id
94
94
  protocolVersion
@@ -109,12 +109,7 @@ ${Mo}`,ps=`query V4Pool($chain: Chain!, $poolId: String!) {
109
109
  __typename
110
110
  }
111
111
  }
112
- ${Mo}`,hs={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function xn(c){return new Promise(e=>setTimeout(e,c))}function eo(c){if(!c)return 1;let e=c.toLowerCase();return hs[e]??1}function to(c){if(!c)return"ETHEREUM";let e=c.toLowerCase();return us[e]??"ETHEREUM"}function Do(c,e){if(!c)return[];switch(e){case"V2":return c.poolStatsV2??[];case"V3":return c.poolStatsV3??[];case"V4":return c.poolStatsV4??[]}}function Oo(c,e){switch(e){case"volume1Day":return c.volume1Day?.value??0;case"volume1Week":return c.volume1Week?.value??0;case"volume30Day":return c.volume30Day?.value??0;case"txCount":return c.txCount??0;case"apr":return c.apr??0;default:return c.totalLiquidity?.value??0}}function Bo(c){let e=c.volume1Day?.value,t=c.totalLiquidity?.value;return typeof c.feeTier!="number"||!e||!t?void 0:c.feeTier/1e4*e/t*365}var oe=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??is).replace(/\/$/,"")}async getExploreStats(e){let t=eo(e?.chain),n=e?.multichain===!0,r=encodeURIComponent(JSON.stringify({chainId:String(t),multichain:n})),o=`${this.baseUrl}${ls}?connect=v1&encoding=json&message=${r}`,s="Unknown error";for(let a=1;a<=Ee;a++)try{let i=await _.get(o,{headers:{accept:"*/*",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!i.ok)throw new Error(I(i));return{success:!0,data:i.data}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<Ee&&await xn(An)}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:Do(o.data.stats,t).map(i=>({...i,apr:Bo(i),fee24hUsd:i.volume1Day?.value&&i.feeTier?i.feeTier/1e4*i.volume1Day.value:void 0})).sort((i,l)=>Oo(l,r)-Oo(i,r)).slice(0,n)}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:ds,variables:{chain:to(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:ms,variables:{chain:to(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:ps,variables:{chain:to(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${cs}`,n=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),r="Unknown error";for(let o=1;o<=Ee;o++)try{let s=await _.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 a=s.data;if(a.errors)throw new Error(`GraphQL error: ${JSON.stringify(a.errors)}`);let i=a.data?.[e.pickField]??void 0;return i?{success:!0,data:i}:{success:!1,error:"Pool not found"}}catch(s){r=s instanceof Error?s.message:"Unknown error",o<Ee&&await xn(An)}return{success:!1,error:r}}async searchTokens(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};if(B(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=eo(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}${Lo}`,a=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"TOKEN",page:r,size:o}),i="Unknown error";for(let l=1;l<=Ee;l++)try{let u=await _.post(s,a,{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){i=u instanceof Error?u.message:"Unknown error",l<Ee&&await xn(An)}return{success:!1,error:i}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let n=eo(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",a=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,i=`${this.baseUrl}${Lo}`,l=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"POOL",page:r,size:o}),[u,d]=await Promise.allSettled([this.fetchSearchPools(i,l),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 m=t.toLowerCase().split(/\s+/).filter(Boolean),p=u.value.data??[];s!=="ALL"&&(p=p.filter(f=>f.protocolVersion===s)),a!=null&&(p=p.filter(f=>f.feeTier===a));let h=new Map;for(let f of p)f.id&&h.set(f.id.toLowerCase(),f);if(d.status==="fulfilled"&&d.value.success&&d.value.data){let f=d.value.data.stats,y=s==="ALL"?["V2","V3","V4"]:[s];for(let k of y)for(let w of Do(f,k)){if(!w.id||a!=null&&w.feeTier!==a)continue;let b=(w.token0?.symbol??"").toLowerCase(),v=(w.token1?.symbol??"").toLowerCase(),A=(w.token0?.name??"").toLowerCase(),S=(w.token1?.name??"").toLowerCase();if(!m.some(P=>b.includes(P)||v.includes(P)||A.includes(P)||S.includes(P)))continue;let D=Bo(w),x=w.id.toLowerCase(),L=h.get(x);L?h.set(x,{...L,...D!=null?{apr:D}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}}):h.set(x,{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,...D!=null?{apr:D}:{},...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(h.values()).sort((f,y)=>this.matchScore(y,m)-this.matchScore(f,m))}}async fetchSearchPools(e,t){let n="Unknown error";for(let r=1;r<=Ee;r++)try{let o=await _.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<Ee&&await xn(An)}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 a of n)a===o?s=Math.max(s,3):a.startsWith(o)?s=Math.max(s,2):a.includes(o)&&(s=Math.max(s,1));r+=s}return r}};var gs=["tvl","volume1Day","volume1Week","volume30Day","txCount","apr"],fs=["V2","V3","V4"],gt=class extends T{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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea`;category="blockchain-data";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. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',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 10.",required:!1,default:10},{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}];service;constructor(e){super(),this.service=new oe(e)}async run(e,t){let n=U(e.chain,t),r=this.parseProtocolVersion(e.protocolVersion),o=this.parseSortKey(e.sortBy),s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):10,a=e.multichain===!0,i=await this.service.getTopPools({chain:n,protocolVersion:r,sortBy:o,limit:s,multichain:a});if(!i.success)return{error:i.error||"Failed to fetch top pools"};let l=(i.data??[]).map(u=>this.formatPool(u));return{_instructions:"Present the pools as a ranked list. For each pool show: rank, pair (token0/token1 symbols), apr(in %), fee tier (in %), TVL in USD, 24h volume, 24h fee revenue, and protocol version. Format numbers human-readably (e.g. $12.5M, 0.05%). Mention the chain and the sort metric in the intro line. If a value is null, omit it. Do NOT mention tool or API names.",chain:n,protocolVersion:r,sortBy:o,count:l.length,pools:l}}parseProtocolVersion(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(fs.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(gs.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,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}: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}:void 0}}};var ys=365,bs=/^0x[a-fA-F0-9]{40}$/,ft=class extends T{name="get-pool-detail";description="Get detailed stats for a single Uniswap V3 pool, identified by token pair (and optional fee tier). Always runs a search first, filters by the provided symbols + fee tier, and only fetches detail when the filter resolves to exactly one pool. Otherwise returns a `candidates` list \u2014 show that to the user, ask which pool 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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";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%. Optional \u2014 when omitted the tool returns all fee tiers for the pair so the user can pick.",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}];service;constructor(e){super(),this.service=new oe(e)}async run(e,t){let n=U(e.chain,t),r=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",o=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0;if(!r)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let a=o?`${r} ${o}`:r,i=await this.service.searchPools({query:a,chain:n,page:1,size:100,protocolVersion:"V3"});if(!i.success)return{error:i.error||"Pool search failed"};let l=i.data??[],d=l.filter(p=>this.matchesFilter(p,r,o,s,"ordered")),m=!1;if(d.length===0&&o){let p=l.filter(h=>this.matchesFilter(h,r,o,s,"reversed"));p.length>0&&(d=p,m=!0)}if(d.length===0)return{error:`No V3 pool matched ${this.describeQuery(r,o,s)} on ${N(n)}. Verify the symbols and fee tier with the user.`};if(d.length===1){let p=d[0];if(!p.id||!bs.test(p.id))return{error:"Resolved pool has no valid address"};let h=await this.service.getV3PoolDetail({address:p.id,chain:n});return!h.success||!h.data?{error:h.error||"Failed to fetch pool detail"}:{_instructions:"Present pool details in a compact summary. 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. Format numbers human-readably (e.g. $12.5M, +1.23%, 0.05%). Omit null fields. Do NOT mention tool/API names.",pairOrderMatched:m?"reversed":"ordered",pool:this.formatPool(h.data)}}return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume, address) and ask the user which one they want to see. 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.",chain:n,pairOrderMatched:m?"reversed":"ordered",reason:this.candidateReason(r,o,s),missing:this.missingFields(o,s),candidates:this.rankCandidates(d).slice(0,10).map(p=>this.formatCandidate(p))}}matchesFilter(e,t,n,r,o){if(r!=null&&e.feeTier!==r)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase();if(n){let l=n.toLowerCase();return o==="reversed"?this.symbolIncludes(s,l)&&this.symbolIncludes(a,i):this.symbolIncludes(s,i)&&this.symbolIncludes(a,l)}return this.symbolIncludes(s,i)||this.symbolIncludes(a,i)}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}}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,a=typeof s=="number"&&typeof t=="number"&&t>0?s/t*ys*100:void 0;return{address:e.address,protocolVersion:e.protocolVersion,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:s,aprPercent:a,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 ws=["V2","V3","V4","ALL"],yt=class extends T{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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.';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:'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:"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 15.",required:!1,default:15},{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}];service;constructor(e){super(),this.service=new oe(e)}async run(e,t){let n=typeof e.query=="string"?e.query.trim():"";if(!n)return{error:"Search query is required"};let r=U(e.chain,t),o=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,s=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):15,a=this.parseProtocolFilter(e.protocolVersion),i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=await this.service.searchPools({query:n,chain:r,page:o,size:s,protocolVersion:a,feeTier:i});if(!l.success)return{error:l.error||"Failed to search pools"};let u=(l.data??[]).map(d=>this.formatPool(d));return{_instructions:"Present the matching pools as a list. For each pool show: pair (token0/token1 symbols), fee tier (%), protocol version, and only the fields that have actual data \u2014 apr (%), TVL (USD), 24h volume (USD), tx count. Skip any field that is null/undefined \u2014 do not show zeros or dashes. Format numbers human-readably (e.g. $12.5M, 0.30%, 4.2%). Mention the search query and chain in the intro. Do NOT mention tool or API names.",query:n,chain:r,protocolVersion:a,feeTierBps:i,feeTierPercent:i!=null?i/1e4:void 0,page:o,size:s,count:u.length,pools:u}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(ws.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);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 ks=365,qo=/^0x[a-fA-F0-9]{40}$/,bt=class extends T{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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea';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:'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}];service;constructor(e){super(),this.service=new oe(e)}async run(e,t){let n=U(e.chain,t),r=typeof e.address=="string"?e.address.trim():"",[o,s]=await Promise.all([this.service.searchPools({query:r,chain:n,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:r,chain:n,page:1,size:5})]),a=o.success?this.findPoolByAddress(o.data??[],r):void 0;if(a)return this.handlePoolHit(a,n);let i=s.success?this.findTokenByAddress(s.data??[],r):void 0;return i?this.handleTokenHit(i,n):!o.success&&!s.success?{error:o.error||s.error||"Failed to resolve address"}:{error:`Address ${r} did not match any pool or token Uniswap knows on ${N(n)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t){if(!e.id)return{error:"Resolved pool has no identifier"};let n=e.protocolVersion??"V3",r=n==="V4"?await this.service.getV4PoolDetail({poolId:e.id,chain:t}):n==="V2"?qo.test(e.id)?await this.service.getV2PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V2 pair has no valid address"}:qo.test(e.id)?await this.service.getV3PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V3 pool has no valid address"};return!r.success||!r.data?{error:r.error||"Failed to fetch pool detail"}:{_instructions:`The address is a Uniswap ${n} pool. Present pool details in a compact summary. 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. Format numbers human-readably (e.g. $12.5M, +1.23%, 0.05%). Omit null fields. Do NOT mention tool/API names.`,resolvedAs:"pool",chain:t,protocolVersion:n,pool:this.formatPoolDetail(r.data)}}async handleTokenHit(e,t){let n=e.symbol?.trim();if(!n)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let r=await this.service.searchPools({query:n,chain:t,page:1,size:100,protocolVersion:"V3"});if(!r.success)return{error:r.error||"Failed to fetch pools for resolved token"};let o=(e.address??"").toLowerCase(),a=[...(r.data??[]).filter(i=>{let l=(i.token0?.address??"").toLowerCase(),u=(i.token1?.address??"").toLowerCase();return l===o||u===o})].sort((i,l)=>(l.volumeUsd24hr??0)-(i.volumeUsd24hr??0)).slice(0,10);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), and the pool address. 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.",resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:a.length,pools:a.map(i=>this.formatPoolCandidate(i))}}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,a=typeof s=="number"&&typeof t=="number"&&t>0?s/t*ks*100: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:a,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}: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}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var no=require("js-sha3"),Fo=2n**96n;function $o(c,e,t){let n=c*c,r=Fo*Fo,o=n*10n**18n/r;return Number(o)/1e18*Math.pow(10,e-t)}function ue(c,e,t){return Math.pow(1.0001,c)*Math.pow(10,e-t)}function Le(c,e,t){if(c<=0)throw new Error("priceToTick: price must be > 0");let n=c/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 ve(c,e,t="nearest"){let n=Math.abs(c-Math.round(c))<1e-6?Math.round(c):c,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 wt=-887272,kt=887272;function Te(c){return c<wt?wt:c>kt?kt:c}var vs=/^0x[0-9a-f]+$/i;function ae(c){return c.startsWith("0x")||c.startsWith("0X")?c.slice(2):c}function Pn(c){let e=ae(c).toLowerCase();if(e.length>64)throw new Error(`pad32: input too long (${e.length})`);return e.padStart(64,"0")}function _n(c){if(!vs.test(c)||ae(c).length!==40)throw new Error(`encodeAddress: invalid address ${c}`);return Pn(c.toLowerCase())}function de(c,e=256){let t=typeof c=="bigint"?c:BigInt(c);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 Pn(n)}function oo(c){let e=typeof c=="bigint"?c:BigInt(c);if(e>=0n)return Pn(e.toString(16));let t=1n<<256n;return Pn((t+e).toString(16))}function Wo(c){return"0x"+(0,no.keccak_256)(Ts(c))}function Ts(c){let e=ae(c),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 Se(c){return"0x"+(0,no.keccak_256)(new TextEncoder().encode(c)).slice(0,8)}function nn(c,e){let t=c.substring(e,e+64);return t?BigInt("0x"+t):0n}function ro(c,e){let t=c.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 so(c,e){return"0x"+c.substring(e+24,e+64).toLowerCase()}var Ue=class{config;constructor(e){this.config=e}hasIntegratedApproval(){return!1}};var Ss="https://exchange-api.keyring.app/admin/setting?configs=others",As="https://api.coinpool.app/config/bridgeProviderByChain",xs="https://coinpool-api-op.bacoor-test001.xyz/config/bridgeProviderByChain";function Ps(c){let e=null,t=null;return async()=>e||t||(t=(async()=>{try{return e=await c(),e}catch{return null}finally{t=null}})(),t)}async function Ho(c){return(await _.get(c,{headers:{Accept:"application/json"}})).data}var _s=Ps(async()=>(await Ho(Ss))?.others??null),Cn={prod:null,dev:null},on={prod:null,dev:null};async function Cs(c){let e=c?"prod":"dev";if(Cn[e])return Cn[e];if(on[e])return on[e];let t=c?As:xs;return on[e]=(async()=>{try{let n=await Ho(t);return Cn[e]=n?.data??null,Cn[e]}catch{return null}finally{on[e]=null}})(),on[e]}function Es(c){if(!c)return null;try{let e=JSON.parse(c);return e&&typeof e=="object"?e:null}catch{return null}}function Vo(c){if(c==null)return 0;let e=typeof c=="number"?c:Number(c);return Number.isFinite(e)?e:0}function Us(c){return c==="debridge"||c==="relay"}async function En(c,e){let n=(await Cs(e))?.[String(c)];return Us(n)?n:null}async function vt(c,e){let t=await _s();if(!t)return null;let n,r;if(c==="debridge")n=Es(t.affiliateRecipient)?.[String(e)],r=Vo(t.AFFILIATE_FEE_PERENT);else if(c==="relay")n=t.RELAY_AFFILIATE_FEE_RECIPIENT,r=Vo(t.RELAY_AFFILIATE_FEE_PERCENT);else return null;return!n||r<=0?null:{affiliateFeeRecipient:n,affiliateFeePercent:r}}var ie={"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"};function Rs(c){return ie[c.toLowerCase()]}var Go={};function ao(c){let e={};if(c)for(let[t,n]of Object.entries(c))typeof n=="string"&&n.trim()&&(e[t.toLowerCase()]=n.trim());Go=e}function Tt(c){let e=c.toLowerCase();return Go[e]??ie[e]}async function Ae(c,e,t){for(let r=0;r<=5;r++){let o=await _.post(c,{jsonrpc:"2.0",id:Date.now(),method:e,params:t},{headers:{"Content-Type":"application/json"}});if(o.status===429&&r<5){await new Promise(a=>setTimeout(a,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 Yo(c,e,t){return Ae(c,"eth_call",[{to:e,data:t},"latest"])}async function io(c,e,t){let n=Tt(c);if(!n)return null;try{return await Yo(n,e,t)}catch{return null}}var Ns="https://dln.debridge.finance/v1.0",Is="0x0000000000000000000000000000000000000000",Ls=new Set([429,500]),Ds=5,Os=1e3,Bs=c=>new Promise(e=>setTimeout(e,c)),St=class extends Ue{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Ns,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:a,senderAddress:i,slippage:l,isCrossChain:u}=e,d=u??t!==o,m=await vt(this.getProviderName(),t);try{if(d){let g={srcChainId:String(t),srcChainTokenIn:n,srcChainTokenInAmount:r,dstChainId:String(o),dstChainTokenOut:s,dstChainTokenOutRecipient:a,srcChainOrderAuthorityAddress:i,dstChainOrderAuthorityAddress:a,accesstoken:this.accessToken};m&&(g.affiliateFeeRecipient=m.affiliateFeeRecipient,g.affiliateFeePercent=m.affiliateFeePercent);let f=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,g);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,estimation:f.estimation,isCrossChain:!0,srcChainId:t,dstChainId:o,raw:f}}let p={chainId:String(t),tokenIn:n,tokenInAmount:r,tokenOut:s,tokenOutRecipient:a,accesstoken:this.accessToken};m&&(p.affiliateFeeRecipient=m.affiliateFeeRecipient,p.affiliateFeePercent=m.affiliateFeePercent),l!==void 0&&(p.slippage=l);let h=await this.get(`${this.apiBaseUrl}/chain/transaction`,p);return h.error||h.errorMessage?{success:!1,error:h.error??h.errorMessage,errorMessage:h.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:h.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:h}}catch(p){return{success:!1,error:p,errorMessage:p instanceof Error?p.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()===Is)return{isNeeded:!1,integrated:!1,contractAddress:s,message:"Native coin needs no approval."};let a=await this.readAllowance(t,r,n,s);if(a===null)return{isNeeded:!0,integrated:!1,contractAddress:s,message:"Could not read allowance; approval required before the swap."};let i;try{i=BigInt(o)}catch{i=0n}return a>=i?{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=i=>i.toLowerCase().replace(/^0x/,"").padStart(64,"0"),s=`0xdd62ed3e${o(n)}${o(r)}`,a=await io(e,t,s);if(typeof a!="string"||!/^0x[0-9a-fA-F]*$/.test(a)||a==="0x")return null;try{return BigInt(a)}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,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(a))}`).join("&"),r=n?`${e}?${n}`:e,o=await _.get(r,{headers:{Accept:"application/json"}});for(let s=0;s<Ds&&Ls.has(o.status);s++)await Bs(Os),o=await _.get(r,{headers:{Accept:"application/json"}});return o.data}};var Ms="https://api.relay.link";function Ko(c){return c===7565164||c==="7565164"?792703809:c}var At=class extends Ue{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Ms,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:a,senderAddress:i,slippage:l}=e,u=await vt(this.getProviderName(),t),d={user:a||i,originChainId:Ko(t),destinationChainId:Ko(o),originCurrency:n,destinationCurrency:s,amount:r,recipient:a||i,tradeType:"EXACT_INPUT"};u&&(d.appFees=[{recipient:u.affiliateFeeRecipient,fee:Math.floor(u.affiliateFeePercent*100)}]),typeof l=="number"&&Number.isFinite(l)&&(d.slippageTolerance=Math.floor(l*100).toString());try{let m=await this.request("/quote/v2","POST",d);if(!m||m.error)return{success:!1,error:m?.error??"Unknown error",errorMessage:m?.message??"Failed to fetch quote from Relay"};let p=m.steps?.find(k=>k.id==="approve"),h=m.steps?.find(k=>k.id==="swap"||k.id==="deposit"),g=h?.items?.[0]?.data,f=Array.isArray(g?.instructions);return{success:!0,provider:"relay",tx:g?f?{data:{instructions:g.instructions??[],addressLookupTableAddresses:g.addressLookupTableAddresses??[]},chainId:g.chainId}:{from:g.from,to:g.to,data:g.data,value:g.value,chainId:g.chainId,maxFeePerGas:g.maxFeePerGas,maxPriorityFeePerGas:g.maxPriorityFeePerGas}:null,isCrossChain:t!==o,srcChainId:t,dstChainId:o,raw:{steps:m.steps,fees:m.fees,details:m.details,approveStep:p,requestId:h?.requestId}}}catch(m){return{success:!1,error:m,errorMessage:m instanceof Error?m.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 i=Object.entries(n).map(([l,u])=>`${encodeURIComponent(l)}=${encodeURIComponent(String(u))}`).join("&");o=`${o}?${i}`}else t==="POST"&&n&&(s=n);let a=await _.request(t,o,s,{headers:r});if(!a.ok)throw new Error(I(a));return a.data}};var Un={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},rn="debridge";function qs(c){if(c==null)return null;let e=typeof c=="number"?c:Number(c);return Number.isFinite(e)?e:null}var De=class{providerConfig;isProduction;cache=new Map;constructor(e=Un,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=qs(e);return t===null?rn:await En(t,this.isProduction)??rn}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 St(t);case"relay":return new At(t);default:{let n=e;throw new Error(`Unknown swap provider: ${String(n)}`)}}}},ye=new De;var Fs="https://api.coinpool.app/config/addresses",$s="https://coinpool-api-op.bacoor-test001.xyz/config/addresses",Rn={prod:null,dev:null},sn={prod:null,dev:null};async function Ws(c){let e=c?"prod":"dev";if(Rn[e])return Rn[e];if(sn[e])return sn[e];let t=c?Fs:$s;return sn[e]=(async()=>{try{let r=(await _.get(t,{headers:{Accept:"application/json"}})).data;return Rn[e]=r?.data??null,Rn[e]}catch{return null}finally{sn[e]=null}})(),sn[e]}function Vs(c){let e=c.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 jo(c,e,t){let n=await Ws(t);if(!n)return;let r=Vs(e);if(!r)return;let o=n[c]?.[r];return Array.isArray(o)?o[0]:typeof o=="string"?o:void 0}async function Nn(c,e){return jo("createPoolProxyV3",c,e)}async function In(c,e){return jo("nftPositionUniswap",c,e)}var M="0x0000000000000000000000000000000000000000",Hs={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:ie["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:ie["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:ie["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:ie["0x89"],native:{symbol:"MATIC",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:ie["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:ie["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:ie["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:ie["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function X(c){return Hs[c.toLowerCase()]}function xt(c){return X(c)?.native}var zo="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function lo(c){let e=c.stableTicks??3,t=c.widePercent??{down:50,up:100},n=ue(c.currentTick,c.token0Decimals,c.token1Decimals),r=Te(ve(c.currentTick-e*c.tickSpacing,c.tickSpacing,"down")),o=Te(ve(c.currentTick+e*c.tickSpacing,c.tickSpacing,"up")),s=n*(1-t.down/100),a=n*(1+t.up/100),i=Le(s,c.token0Decimals,c.token1Decimals),l=Le(a,c.token0Decimals,c.token1Decimals),u=Te(ve(i,c.tickSpacing,"down")),d=Te(ve(l,c.tickSpacing,"up")),m=(p,h,g,f,y)=>{let k=ue(f,c.token0Decimals,c.token1Decimals),w=ue(y,c.token0Decimals,c.token1Decimals);return{id:p,label:h,description:g,tickLower:f,tickUpper:y,minPrice:k,maxPrice:w,minPercentChange:(k-n)/n*100,maxPercentChange:(w-n)/n*100}};return[m("stable","Stable","Good for stablecoins or low volatility pairs",r,o),m("wide","Wide","Good for volatile pairs",u,d)]}var Gs=Se("slot0()"),Ys=Se("liquidity()"),Ks=Se("tickSpacing()"),js=Se("fee()"),zs=Se("token0()"),Qs=Se("token1()"),Xs=Se("decimals()"),Oe=class{swapFactory;isProduction;constructor(e){this.isProduction=e?.isProduction??!0,this.swapFactory=e?.swapFactory??(this.isProduction?ye:new De(void 0,!1))}getRpcUrl(e){let t=Tt(e);if(t)return t;let n=X(e);if(!n)throw new Error(`Unsupported chain: ${e}`);return n.defaultRpc}async getGatewayAddress(e){return Nn(e,this.isProduction)}async getPositionManagerAddress(e){return In(e,this.isProduction)}async ethCall(e,t,n){return Ae(this.getRpcUrl(e),"eth_call",[{to:t,data:n},"latest"])}async getNativeBalance(e,t){let n=await Ae(this.getRpcUrl(e),"eth_getBalance",[t,"latest"]);return BigInt(n)}async getGasPrice(e){let t=await Ae(this.getRpcUrl(e),"eth_gasPrice",[]);return BigInt(t)}async getTransactionReceipt(e,t){return await Ae(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()!==zo||"0x"+s[1].slice(-40).toLowerCase()!==M))try{return BigInt(s[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=X(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,a,i]=await Promise.all([this.ethCall(e,t,Gs),this.ethCall(e,t,Ys),this.ethCall(e,t,Ks),this.ethCall(e,t,js),this.ethCall(e,t,zs),this.ethCall(e,t,Qs)]),l=ae(n),u=nn(l,0),d=ro(l,64),m=nn(ae(r),0),p=Number(ro(ae(o),0)),h=Number(nn(ae(s),0)),g=so(ae(a),0),f=so(ae(i),0),[y,k]=await Promise.all([this.readErc20Decimals(e,g),this.readErc20Decimals(e,f)]),w=$o(u,y,k);return{poolAddress:t,chainId:e,fee:h,tickSpacing:p,liquidity:m,sqrtPriceX96:u,currentTick:d,token0:g,token1:f,currentPrice:w}}async readErc20Decimals(e,t){if(t.toLowerCase()===M)return 18;let n=await this.ethCall(e,t,Xs);return Number(nn(ae(n),0))}async getNativePriceUsd(e){let t=X(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 _.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:a}=e,i=2**96,l=Number(n.sqrtPriceX96)/i,u=Math.pow(1.0001,r/2),d=Math.pow(1.0001,o/2);if(l<=u)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(l>=d)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let m=1/l-1/d,p=l-u,h=l*l,g=m*h,y=g+p;if(!Number.isFinite(y)||y<=0)throw new Error("splitNativeAmountForRange: invalid total value");let k=g/y,w=1-k,b=1000000000000000n,v=BigInt(Math.floor(k*Number(b))),A=t*v/b,S=t-A;return{ratio0:k,ratio1:w,amountInFor0Wei:A,amountInFor1Wei:S}}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??{},a=s.tokenOut?.minAmount??s.details?.currencyOut?.minimumAmount??"0";return{to:o.to,data:o.data,value:o.value??"0",minAmountOut:a}}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=Se("mint((address,uint256,address,uint256)[2],(address,bytes,uint256)[2],(uint24,uint256,uint256,int24,int24))"),n=e.paymentInfo.map(h=>_n(h.tokenIn)+de(h.tokenInAmount)+_n(h.tokenOut)+de(h.tokenOutAmount)).join(""),o=e.exchanges.map(h=>{let g=ae(h.data||"0x"),f=g.length/2,y=de(f),k=(64-g.length%64)%64,w=g+"0".repeat(k);return{head:_n(h.to)+de(96)+de(h.value),body:y+w}}).map(h=>h.head+h.body),s=o.length*32,a=[];for(let h of o)a.push(de(s)),s+=h.length/2;let i=a.join("")+o.join(""),l=de(e.fee,24)+de(e.amount0Min)+de(e.amount1Min)+oo(e.tickLower)+oo(e.tickUpper),m=256+32+160,p=n+de(m)+l+i;return t+p}_keccak(e){return Wo(e)}};var Js=/^0x[a-fA-F0-9]{40}$/,Pt=class extends T{name="open-add-liquidity-form";kind="ui";category="pool-action";noSuggestions=!0;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}];uniswap;pool;minProvideUsd;constructor(e){super(),this.uniswap=new oe(e),this.pool=new Oe(e?.pool),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),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=U(e.chain,t),r=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",o=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,a=typeof e.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,i=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,l=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,u=l&&a!=null&&(l.toLowerCase()===r.toLowerCase()||l.toLowerCase()===o.toLowerCase())?null:l,d=this.parseRangeStrategy(e.rangeStrategy),m=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,p=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!r||!o)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let h=X(n);if(!h)return{error:"unsupported_chain",chain:n,_instructions:`Chain ${n} is not supported by the add-liquidity flow.`};let g=xt(n);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 f=await this.pool.getGatewayAddress(n);if(!f)return{error:"no_gateway_configured",chain:n,_instructions:`No gateway contract is configured for chain ${n} (${h.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let y=t?.walletAddress;if(!y)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 k=await this.uniswap.searchPools({query:`${r} ${o}`,chain:n,page:1,size:100,protocolVersion:"V3",feeTier:s});if(!k.success)return{error:k.error||"pool_search_failed"};let w=k.data??[],b=w.find(q=>this.matchesPairExact(q,r,o,s)),v=b?[]:w.filter(q=>this.matchesPair(q,r,o,s));if(!b&&v.length===0)return{error:"pool_not_found",_instructions:`No V3 pool found for ${r}/${o}${s!=null?` at ${s}bps`:""} on ${h.name}. Verify the inputs with the user.`};if(!b&&v.length>1)return{candidates:v.map(q=>({address:q.id,token0Symbol:q.token0?.symbol,token1Symbol:q.token1?.symbol,feeTier:q.feeTier,feeTierPercent:q.feeTier!=null?q.feeTier/1e4:void 0,volume24hUsd:q.volume1DayUsd??q.volumeUsd24hr,tvlUsd:q.tvlUsd,...q.apr?{apr:q.apr}:void 0})),_instructions:"Multiple pools matched. Present them as a numbered list (pair, fee %, TVL, 24h volume, address, apr) and ask the user to pick one. Then re-call this tool with the chosen pool's exact token0Symbol, token1Symbol, and feeTier."};let A=b??v[0];if(!A.id||!Js.test(A.id))return{error:"invalid_pool_address"};let S=await this.pool.readPoolOnchain(n,A.id),[C,D,x]=await Promise.all([this.pool.getNativeBalance(n,y),this.pool.estimateGasReserveWei(n),this.pool.getNativePriceUsd(n)]),L=C>D?C-D:0n,P=xt(n),H=Number(L)/10**P.decimals,Pe=Number(C)/10**P.decimals,ce=x!=null?H*x:null,[Q,Z]=await Promise.all([this.pool.readErc20Decimals(n,S.token0),this.pool.readErc20Decimals(n,S.token1)]),ke={min:ue(wt,Q,Z),max:ue(kt,Q,Z)},z=null;C===0n?z="no_balance":ce!=null&&ce<this.minProvideUsd&&(z="insufficient_balance");let me=A.token0,Be=A.token1,Kn=[25,50,75,100].map(q=>({percent:q,amountWei:(L*BigInt(q)/100n).toString(),amount:H*(q/100)})),Me=null,pe=null;if(a!=null){pe=a;let q=BigInt(Math.floor(pe*10**P.decimals));q>0n&&(Me=q.toString())}else if(i!=null&&x!=null&&x>0){pe=i/x;let q=BigInt(Math.floor(pe*10**P.decimals));q>0n&&(Me=q.toString())}let qe={address:M,isNative:!0,symbol:P.symbol,name:P.name,decimals:P.decimals,priceUsd:x,balanceWei:C.toString(),balance:Pe,gasReserveWei:D.toString(),spendableWei:L.toString(),spendable:H,spendableUsd:ce,quickRates:Kn,minProvideUsd:this.minProvideUsd,warning:z,warningMessage:z==="no_balance"?`You have no ${P.symbol} on ${h.name}. Top up to add liquidity.`:z==="insufficient_balance"?`Spendable ${P.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:pe,prefillAmountWei:Me},mo=this.computePrefillRange({explicitMinPrice:m,explicitMaxPrice:p,rangeStrategy:d,currentTick:S.currentTick,tickSpacing:S.tickSpacing,token0Decimals:Q,token1Decimals:Z,priceBounds:ke});return{ui:{component:"AddLiquidityForm",props:{chain:{hexId:n,name:h.name},pool:{address:S.poolAddress,fee:S.fee,feePercent:S.fee/1e4,tickSpacing:S.tickSpacing,currentTick:S.currentTick,currentPrice:S.currentPrice,sqrtPriceX96:S.sqrtPriceX96.toString(),token0:{address:S.token0,symbol:me?.symbol,name:me?.name,logo:me?.logo},token1:{address:S.token1,symbol:Be?.symbol,name:Be?.name,logo:Be?.logo}},inputToken:qe,priceBounds:ke,prefillRange:mo,gatewayAddress:f}},summary:this.buildSummary({chainName:h.name,pair:`${me?.symbol??r}/${Be?.symbol??o}`,feePercent:S.fee/1e4,warning:z,minProvideUsd:this.minProvideUsd,nativeSymbol:P.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>"). If warning="no_balance" tell them they need to top up. If warning="insufficient_balance" tell them the balance is below the minimum. Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, or internal tool names. Wait for the user to fill in amount + price range before proceeding.`}}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(),a=t.toLowerCase(),i=n.toLowerCase();return o===a&&s===i||o===i&&s===a}matchesPair(e,t,n,r){if(r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),s=(e.token1?.symbol??"").toLowerCase(),a=t.toLowerCase(),i=n.toLowerCase(),l=this.symMatch(o,a)&&this.symMatch(s,i),u=this.symMatch(o,i)&&this.symMatch(s,a);return l||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,priceBounds:o}=e;if(t!=null&&n!=null&&n>t)return{strategy:"user",minPrice:Math.max(t,o.min),maxPrice:Math.min(n,o.max)};if(r==="full")return{strategy:"full",minPrice:o.min,maxPrice:o.max};if(r==="stable"||r==="wide"){let a=lo({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(i=>i.id===r);if(a)return{strategy:r,minPrice:a.minPrice,maxPrice:a.maxPrice}}return null}buildSummary(e){let t=[`Add-liquidity form opened for ${e.pair} ${e.feePercent}% on ${e.chainName}.`];return e.warning==="no_balance"?t.push(`No ${e.nativeSymbol} balance \u2014 top up the wallet to add liquidity.`):e.warning==="insufficient_balance"&&t.push(`Balance is below the $${e.minProvideUsd} minimum \u2014 top up before submitting.`),t.join(" ")}};var Qo=[{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"}]}],Ln=[{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 _t=class extends T{name="preview-add-liquidity";kind="action";category="pool-action";noSuggestions=!0;description="Preview the add-liquidity transaction once the user has filled the AddLiquidityForm with a native amount and a price range (min/max price in token1 per token0). 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. Do NOT call this until the user has filled both prices and an amount.";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.',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.',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 Oe(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new te}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=U(e.chain,t),o=Number(e.minPrice),s=Number(e.maxPrice),a=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,i=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!n||!r||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(s))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(o<=0||s<=0||o>=s)return{error:"invalid_price_range",_instructions:"minPrice and maxPrice must both be > 0 and minPrice must be strictly less than maxPrice."};if(a<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let l=X(r);if(!l)return{error:"unsupported_chain",chain:r};let u=await this.pool.getGatewayAddress(r);if(!u)return{error:"no_gateway_configured",chain:r};let d=t?.walletAddress;if(!d)return{error:"wallet_not_connected"};let m=xt(r),p=BigInt(Math.floor(a*10**m.decimals));if(p<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let h=await this.pool.readPoolOnchain(r,n),[g,f]=await Promise.all([this.pool.readErc20Decimals(r,h.token0),this.pool.readErc20Decimals(r,h.token1)]),y=Le(o,g,f),k=Le(s,g,f),w=Te(ve(y,h.tickSpacing,"down")),b=Te(ve(k,h.tickSpacing,"up"));if(w>=b||w<wt||b>kt)return{error:"invalid_range_after_alignment",_instructions:"After aligning to tickSpacing the range collapsed. Ask the user for a wider price range.",rawTickLower:y,rawTickUpper:k,tickLower:w,tickUpper:b};let v={tickLower:w,tickUpper:b,minPrice:ue(w,g,f),maxPrice:ue(b,g,f)},[A,S,C]=await Promise.all([this.pool.getNativeBalance(r,d),this.pool.estimateGasReserveWei(r),this.pool.getNativePriceUsd(r)]),D=p+S;if(A<D)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:A.toString(),requiredWei:D.toString(),gasReserveWei:S.toString()};let x=this.pool.splitNativeAmountForRange({nativeAmountWei:p,pool:h,tickLower:w,tickUpper:b,token0Decimals:g,token1Decimals:f}),L=h.token0.toLowerCase()===M,P=h.token1.toLowerCase()===M,H=[];if(L||x.amountInFor0Wei===0n)H.push({tokenIn:M,tokenOut:h.token0,amountIn:x.amountInFor0Wei,tx:{to:M,data:"0x",value:"0"},minAmountOut:L?x.amountInFor0Wei:0n});else{let G=await this.pool.fetchSwapLeg({senderAddress:d,chainId:r,tokenIn:M,tokenInAmount:x.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:u,slippage:typeof i=="number"?i:"auto"});H.push({tokenIn:M,tokenOut:h.token0,amountIn:x.amountInFor0Wei,tx:{to:G.to,data:G.data,value:G.value},minAmountOut:BigInt(G.minAmountOut||"0")})}if(P||x.amountInFor1Wei===0n)H.push({tokenIn:M,tokenOut:h.token1,amountIn:x.amountInFor1Wei,tx:{to:M,data:"0x",value:"0"},minAmountOut:P?x.amountInFor1Wei:0n});else{let G=await this.pool.fetchSwapLeg({senderAddress:d,chainId:r,tokenIn:M,tokenInAmount:x.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:u,slippage:typeof i=="number"?i:"auto"});H.push({tokenIn:M,tokenOut:h.token1,amountIn:x.amountInFor1Wei,tx:{to:G.to,data:G.data,value:G.value},minAmountOut:BigInt(G.minAmountOut||"0")})}let Pe=G=>G*BigInt(this.mintMinPercent)/100n,ce=Pe(H[0].minAmountOut),Q=Pe(H[1].minAmountOut),Z=H.map(G=>({tokenIn:G.tokenIn,tokenInAmount:BigInt(G.amountIn),tokenOut:G.tokenOut,tokenOutAmount:BigInt(G.minAmountOut)})),ke=H.map(G=>({to:G.tx.to,data:G.tx.data,value:BigInt(G.tx.value||"0")}));console.log("\u{1F680} ~ PreviewAddLiquidityTool ~ run ~ paymentInfo:",Z),console.log("\u{1F680} ~ PreviewAddLiquidityTool ~ run ~ exchangesInfo:",ke),console.log("\u{1F680} ~ PreviewAddLiquidityTool ~ run ~ args:",{args:[Z,ke,{fee:Number(h.fee),amount0Min:BigInt(ce),amount1Min:BigInt(Q),tickLower:w,tickUpper:b}]});let z=Ge({abi:Qo,functionName:"mint",args:[Z,ke,{fee:Number(h.fee),amount0Min:BigInt(ce),amount1Min:BigInt(Q),tickLower:w,tickUpper:b}]}),me=a,Be={chainId:r,to:u,data:z,value:p.toString(),from:d},Kn={nativeIn:me,nativeInUsd:C!=null?me*C:null,ratio:{token0Percent:x.ratio0,token1Percent:x.ratio1},expectedToken0:Number(H[0].minAmountOut)/10**g,expectedToken1:Number(H[1].minAmountOut)/10**f,amount0Min:ce.toString(),amount1Min:Q.toString(),slippageBps:i},Me=await this.pantograph.getTokensMetadata([h.token0,h.token1],r),pe=Me[h.token0],qe=Me[h.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:r,name:l.name},unsignedTx:Be,summary:Kn,pool:{...h,feePercent:h.fee/1e4,token0:{address:h.token0,symbol:pe.symbol,name:pe.name,decimals:pe.decimals,logo:pe.icon_image},token1:{address:h.token1,symbol:qe.symbol,name:qe.name,decimals:qe.decimals,logo:qe.icon_image}},range:v,gatewayAddress:u}},summary:`Ready to add ${me} ${m.symbol} to pool ${h.token0}/${h.token1} ${h.fee/1e4}% on ${l.name}, range [${v.minPrice}, ${v.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 Xo=365,Zs=1e3,ea=/^0x[a-fA-F0-9]{40}$/;function ta(c,e){return{depositUsd:c,aprPercent:e*100,dailyUsd:c*e/Xo,weeklyUsd:c*e/52,monthlyUsd:c*e/12,yearlyUsd:c*e}}var Ct=class extends T{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):
113
- \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.
114
- \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.
115
- \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.
116
- \u2022 If chain is missing \u2192 default to userContext.chain or "0x1" (Ethereum).
117
- Source: Uniswap ExploreStats (live 24h data). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`;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%. Optional \u2014 if omitted and the pair has multiple fee tiers, the tool 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:'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}];service;constructor(e){super(),this.service=new oe(e)}async run(e,t){let n=U(e.chain,t),r=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",o=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,a=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,i=a?e.depositUsd:Zs;if(!r)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let l=o?`${r} ${o}`:r,u=await this.service.searchPools({query:l,chain:n,page:1,size:50,protocolVersion:"V3"});if(!u.success)return{error:u.error||"Pool search failed"};let d=u.data??[],m=this.filterPools(d,r,o,s);if(m.length===0)return{error:`No V3 pool found for ${this.describeQuery(r,o,s)} on ${N(n)}. Verify the token symbols with the user.`};let p=this.rankByVolume(m);if(o&&s==null&&new Set(p.map(L=>L.feeTier).filter(L=>typeof L=="number")).size>1){let L=this.dedupeByFeeTier(p).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:`${r}/${o} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:L.map(P=>({pair:P.token0?.symbol&&P.token1?.symbol?`${P.token0.symbol}/${P.token1.symbol}`:void 0,feeTierBps:P.feeTier,feeTierPercent:typeof P.feeTier=="number"?P.feeTier/1e4:void 0,volume24hUsd:P.volumeUsd24hr,address:P.id}))}}let h=p[0];if(!h.id||!ea.test(h.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getV3PoolDetail({address:h.id,chain:n});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let f=g.data,y=f.totalLiquidity?.value,k=f.volume24h?.value,w=f.feeTier,b=typeof w=="number"?w/1e4:void 0,v=typeof k=="number"&&typeof b=="number"?k*b/100:void 0,A=typeof v=="number"&&typeof y=="number"&&y>0?v/y*Xo:void 0,S={address:f.address,pair:f.token0?.symbol&&f.token1?.symbol?`${f.token0.symbol}/${f.token1.symbol}`:void 0,feeTierBps:w,feeTierPercent:b,tvlUsd:y,volume24hUsd:k,fees24hUsd:v,aprPercent:typeof A=="number"?A*100:void 0,chain:n,token0:f.token0?{symbol:f.token0.symbol}:void 0,token1:f.token1?{symbol:f.token1.symbol}:void 0},C=o?void 0:`User only provided ${r}; 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:S,autoPickedReason:C,aprUnavailableReason:y?"Volume data unavailable":"TVL is zero or unavailable"};let D=ta(i,A);return{_instructions:"Present the yield estimate naturally in the user's language. "+(a?"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"). ':"")+"Add a one-line disclaimer about impermanent loss. Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:S,estimate:D,depositMode:a?"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(a=>{if(r!=null&&a.feeTier!==r)return!1;let i=(a.token0?.symbol??"").toLowerCase(),l=(a.token1?.symbol??"").toLowerCase();return s?this.sym(i,o)&&this.sym(l,s)||this.sym(i,s)&&this.sym(l,o):this.sym(i,o)||this.sym(l,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 na={"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"},oa={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},ra={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},Jo={"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"},Zo={100:.01,500:.05,3e3:.3,1e4:1},sa={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},aa=300*1e3,J=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...na,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([n])=>wn(n))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return Jo[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),n=Jo[t];return!!(n&&this.subgraphUrls[n])}chainName(e){let t=this.resolveChain(e);return oa[t]||t}numericChainId(e){return ra[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 _.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`
112
+ ${gr}`,Qs={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function Kn(l){return new Promise(e=>setTimeout(e,l))}function Ao(l){if(!l)return 1;let e=l.toLowerCase();return Qs[e]??1}function So(l){if(!l)return"ETHEREUM";let e=l.toLowerCase();return Ys[e]??"ETHEREUM"}function pr(l,e){if(!l)return[];switch(e){case"V2":return l.poolStatsV2??[];case"V3":return l.poolStatsV3??[];case"V4":return l.poolStatsV4??[]}}function mr(l,e){switch(e){case"volume1Day":return l.volume1Day?.value??0;case"volume1Week":return l.volume1Week?.value??0;case"volume30Day":return l.volume30Day?.value??0;case"txCount":return l.txCount??0;case"apr":return l.apr??0;default:return l.totalLiquidity?.value??0}}function hr(l){let e=l.volume1Day?.value,t=l.totalLiquidity?.value;return typeof l.feeTier!="number"||!e||!t?void 0:l.feeTier/1e4*e/t*365}var ae=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Ws).replace(/\/$/,"")}async getExploreStats(e){let t=Ao(e?.chain),n=e?.multichain===!0,r=encodeURIComponent(JSON.stringify({chainId:String(t),multichain:n})),o=`${this.baseUrl}${Hs}?connect=v1&encoding=json&message=${r}`,s="Unknown error";for(let i=1;i<=Me;i++)try{let a=await P.get(o,{headers:{accept:"*/*",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!a.ok)throw new Error(L(a));return{success:!0,data:a.data}}catch(a){s=a instanceof Error?a.message:"Unknown error",i<Me&&await Kn(Yn)}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:pr(o.data.stats,t).map(a=>({...a,apr:hr(a),fee24hUsd:a.volume1Day?.value&&a.feeTier?a.feeTier/1e4*a.volume1Day.value:void 0})).sort((a,c)=>mr(c,r)-mr(a,r)).slice(0,n)}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:Ks,variables:{chain:So(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:js,variables:{chain:So(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:zs,variables:{chain:So(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${Gs}`,n=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),r="Unknown error";for(let o=1;o<=Me;o++)try{let s=await P.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(L(s));let i=s.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let a=i.data?.[e.pickField]??void 0;return a?{success:!0,data:a}:{success:!1,error:"Pool not found"}}catch(s){r=s instanceof Error?s.message:"Unknown error",o<Me&&await Kn(Yn)}return{success:!1,error:r}}async searchTokens(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};if(F(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=Ao(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}${dr}`,i=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"TOKEN",page:r,size:o}),a="Unknown error";for(let c=1;c<=Me;c++)try{let u=await P.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(L(u));return{success:!0,data:u.data.tokens??[]}}catch(u){a=u instanceof Error?u.message:"Unknown error",c<Me&&await Kn(Yn)}return{success:!1,error:a}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let n=Ao(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,a=`${this.baseUrl}${dr}`,c=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"POOL",page:r,size:o}),[u,d]=await Promise.allSettled([this.fetchSearchPools(a,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(f=>f.protocolVersion===s)),i!=null&&(m=m.filter(f=>f.feeTier===i));let g=new Map;for(let f of m)f.id&&g.set(f.id.toLowerCase(),f);if(d.status==="fulfilled"&&d.value.success&&d.value.data){let f=d.value.data.stats,y=s==="ALL"?["V2","V3","V4"]:[s];for(let b of y)for(let w of pr(f,b)){if(!w.id||i!=null&&w.feeTier!==i)continue;let v=(w.token0?.symbol??"").toLowerCase(),k=(w.token1?.symbol??"").toLowerCase(),A=(w.token0?.name??"").toLowerCase(),x=(w.token1?.name??"").toLowerCase();if(!p.some(_=>v.includes(_)||k.includes(_)||A.includes(_)||x.includes(_)))continue;let O=hr(w),C=w.id.toLowerCase(),B=g.get(C);B?g.set(C,{...B,...O!=null?{apr:O}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}}):g.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,...O!=null?{apr:O}:{},...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(g.values()).sort((f,y)=>this.matchScore(y,p)-this.matchScore(f,p))}}async fetchSearchPools(e,t){let n="Unknown error";for(let r=1;r<=Me;r++)try{let o=await P.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(L(o));return{success:!0,data:o.data.pools??[]}}catch(o){n=o instanceof Error?o.message:"Unknown error",r<Me&&await Kn(Yn)}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 Xs={"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"},Js={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},Zs={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},fr={"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"},yr={100:.01,500:.05,3e3:.3,1e4:1},ei={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},ti=300*1e3,Q=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...Xs,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([n])=>Wn(n))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return fr[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),n=fr[t];return!!(n&&this.subgraphUrls[n])}chainName(e){let t=this.resolveChain(e);return Js[t]||t}numericChainId(e){return Zs[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 P.post(r,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Subgraph query failed: ${L(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`
118
113
  id
119
114
  token0 { id symbol name }
120
115
  token1 { id symbol name }
@@ -131,16 +126,16 @@ Source: Uniswap ExploreStats (live 24h data). Supports: Ethereum, Optimism, BSC,
131
126
  volumeToken0
132
127
  volumeToken1
133
128
  }
134
- `}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=Zo[r]??r/1e4,s=this.sanitize(parseFloat(n.totalValueLockedUSD||"0")),a=n.poolDayData?.[0],i=parseFloat(a?.volumeUSD||"0"),l=parseFloat(a?.feesUSD||"0"),u=null;return s>0&&l>0&&(u=parseFloat((l*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:i,fees24hUsd:l,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<aa)return this.llamaCache;try{let t=await _.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(),a=n.token1.address.toLowerCase(),i=t.filter(m=>sa[m.chain.toLowerCase()]===r),l=i.find(m=>{if(!m.underlyingTokens||m.underlyingTokens.length<2)return!1;let p=m.underlyingTokens.map(g=>g.toLowerCase());if(!(p.includes(s)&&p.includes(a)))return!1;let h=this.parseLlamaFeeTier(m.poolMeta);return h===null||h===o});if(!l){let m=n.token0.symbol.toUpperCase(),p=n.token1.symbol.toUpperCase(),h=[m,p].sort().join("-");l=i.find(g=>{if([...g.symbol.split("-").map(k=>k.toUpperCase())].sort().join("-")!==h)return!1;let y=this.parseLlamaFeeTier(g.poolMeta);return y===null||y===o})}if(!l)return n;let u=l.apyBase??l.apy??null,d={...n};return u!==null&&(d.apr=parseFloat(u.toFixed(2))),l.tvlUsd!=null&&(d.tvl=this.sanitize(l.tvlUsd)),l.volumeUsd1d!=null&&(d.volume24hUsd=this.sanitize(l.volumeUsd1d)),d}):e}async searchPools(e){let{tokens:t,chain:n,sortBy:r,filters:o}=e,s=this.resolveChain(n),a=t.map(g=>{let f=g.toUpperCase(),y=new Set([f]);return f.startsWith("W")||y.add("W"+f),f.startsWith("W")&&f.length>1&&y.add(f.slice(1)),[...y]}),i=['totalValueLockedUSD_gt: "10000"','liquidity_gt: "0"','volumeUSD_gt: "0"'];o?.feeTier&&i.push(`feeTier: "${o.feeTier}"`);let l="totalValueLockedUSD";r==="volume"?l="volumeUSD":r==="fee"?l="feeTier":r==="liquidity"&&(l="liquidity");let u=r==="fee"?"asc":"desc",d=g=>g.length===1?`symbol: "${g[0]}"`:`symbol_in: [${g.map(f=>`"${f}"`).join(", ")}]`,m=(g,f)=>`{
129
+ `}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=yr[r]??r/1e4,s=this.sanitize(parseFloat(n.totalValueLockedUSD||"0")),i=n.poolDayData?.[0],a=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:a,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<ti)return this.llamaCache;try{let t=await P.get("https://yields.llama.fi/pools");if(!t.ok)throw new Error(`DefiLlama: ${L(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(),a=t.filter(p=>ei[p.chain.toLowerCase()]===r),c=a.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 g=this.parseLlamaFeeTier(p.poolMeta);return g===null||g===o});if(!c){let p=n.token0.symbol.toUpperCase(),m=n.token1.symbol.toUpperCase(),g=[p,m].sort().join("-");c=a.find(h=>{if([...h.symbol.split("-").map(b=>b.toUpperCase())].sort().join("-")!==g)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 f=h.toUpperCase(),y=new Set([f]);return f.startsWith("W")||y.add("W"+f),f.startsWith("W")&&f.length>1&&y.add(f.slice(1)),[...y]}),a=['totalValueLockedUSD_gt: "10000"','liquidity_gt: "0"','volumeUSD_gt: "0"'];o?.feeTier&&a.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(f=>`"${f}"`).join(", ")}]`,p=(h,f)=>`{
135
130
  pools(
136
131
  first: ${f}
137
- orderBy: ${l}
132
+ orderBy: ${c}
138
133
  orderDirection: ${u}
139
- where: { ${[...i,...g].join(", ")} }
134
+ where: { ${[...a,...h].join(", ")} }
140
135
  ) {
141
136
  ${this.poolFragment()}
142
137
  }
143
- }`,p;if(a.length>0){let f,y;a.length>=2?(f=m([`token0_: { ${d(a[0])} }`,`token1_: { ${d(a[1])} }`],100),y=m([`token0_: { ${d(a[1])} }`,`token1_: { ${d(a[0])} }`],100)):(f=m([`token0_: { ${d(a[0])} }`],100),y=m([`token1_: { ${d(a[0])} }`],100));let[k,w]=await Promise.allSettled([this.querySubgraph(s,f),this.querySubgraph(s,y)]),b=k.status==="fulfilled"?(k.value?.pools||[]).filter(S=>this.hasValidVolume(S)).map(S=>this.mapPool(S,s)):[],v=w.status==="fulfilled"?(w.value?.pools||[]).filter(S=>this.hasValidVolume(S)).map(S=>this.mapPool(S,s)):[],A=new Set(b.map(S=>S.poolAddress));p=[...b,...v.filter(S=>!A.has(S.poolAddress))]}else p=((await this.querySubgraph(s,m([],100)))?.pools||[]).filter(f=>this.hasValidVolume(f)).map(f=>this.mapPool(f,s));let h=await this.fetchDefiLlamaUniswap();return h.length>0&&(p=this.enrichWithLlama(p,h)),o?.minTVL!=null&&(p=p.filter(g=>g.tvl>=o.minTVL)),o?.maxTVL!=null&&(p=p.filter(g=>g.tvl<=o.maxTVL)),o?.minAPR!=null&&(p=p.filter(g=>g.apr!=null&&g.apr>=o.minAPR)),o?.maxAPR!=null&&(p=p.filter(g=>g.apr!=null&&g.apr<=o.maxAPR)),r==="apr"?p.sort((g,f)=>(f.apr??0)-(g.apr??0)):r==="liquidity"&&p.sort((g,f)=>{let y=BigInt(f.liquidity||"0")-BigInt(g.liquidity||"0");return y>0n?1:y<0n?-1:0}),p}async getTrendingPools(e){let t=this.resolveChain(e.chain),n=`{
138
+ }`,m;if(i.length>0){let f,y;i.length>=2?(f=p([`token0_: { ${d(i[0])} }`,`token1_: { ${d(i[1])} }`],100),y=p([`token0_: { ${d(i[1])} }`,`token1_: { ${d(i[0])} }`],100)):(f=p([`token0_: { ${d(i[0])} }`],100),y=p([`token1_: { ${d(i[0])} }`],100));let[b,w]=await Promise.allSettled([this.querySubgraph(s,f),this.querySubgraph(s,y)]),v=b.status==="fulfilled"?(b.value?.pools||[]).filter(x=>this.hasValidVolume(x)).map(x=>this.mapPool(x,s)):[],k=w.status==="fulfilled"?(w.value?.pools||[]).filter(x=>this.hasValidVolume(x)).map(x=>this.mapPool(x,s)):[],A=new Set(v.map(x=>x.poolAddress));m=[...v,...k.filter(x=>!A.has(x.poolAddress))]}else m=((await this.querySubgraph(s,p([],100)))?.pools||[]).filter(f=>this.hasValidVolume(f)).map(f=>this.mapPool(f,s));let g=await this.fetchDefiLlamaUniswap();return g.length>0&&(m=this.enrichWithLlama(m,g)),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,f)=>(f.apr??0)-(h.apr??0)):r==="liquidity"&&m.sort((h,f)=>{let y=BigInt(f.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=`{
144
139
  pools(
145
140
  first: 100
146
141
  orderBy: volumeUSD
@@ -149,7 +144,7 @@ Source: Uniswap ExploreStats (live 24h data). Supports: Ethereum, Optimism, BSC,
149
144
  ) {
150
145
  ${this.poolFragment()}
151
146
  }
152
- }`,o=((await this.querySubgraph(t,n))?.pools||[]).filter(a=>this.hasValidVolume(a)).map(a=>this.mapPool(a,t)),s=await this.fetchDefiLlamaUniswap();return s.length>0&&(o=this.enrichWithLlama(o,s)),o}async getPoolByAddress(e){let t=this.resolveChain(e.chain),n=`{
147
+ }`,o=((await this.querySubgraph(t,n))?.pools||[]).filter(i=>this.hasValidVolume(i)).map(i=>this.mapPool(i,t)),s=await this.fetchDefiLlamaUniswap();return s.length>0&&(o=this.enrichWithLlama(o,s)),o}async getPoolByAddress(e){let t=this.resolveChain(e.chain),n=`{
153
148
  pool(id: "${e.poolAddress.toLowerCase()}") {
154
149
  ${this.poolFragment()}
155
150
  }
@@ -173,25 +168,32 @@ Source: Uniswap ExploreStats (live 24h data). Supports: Ethereum, Optimism, BSC,
173
168
  ${this.poolFragment()}
174
169
  }
175
170
  }
176
- }`,r=await this.querySubgraph(t,n);if(!r?.position?.pool)return null;let o=r.position,s=this.mapPool(o.pool,t),a=await this.fetchDefiLlamaUniswap(),i=a.length>0?this.enrichWithLlama([s],a)[0]:s,l=i.feeTierBps,u=i.feeTierPercent;return{position:{positionId:o.id,poolAddress:i.poolAddress,pair:i.pair,token0:{symbol:i.token0.symbol,address:i.token0.address},token1:{symbol:i.token1.symbol,address:i.token1.address},feeTierBps:l,feeTierPercent:u,chain:i.chain,liquidity:o.liquidity,depositedToken0:o.depositedToken0,depositedToken1:o.depositedToken1,withdrawnToken0:o.withdrawnToken0,withdrawnToken1:o.withdrawnToken1,collectedFeesToken0:o.collectedFeesToken0,collectedFeesToken1:o.collectedFeesToken1},pool:i}}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(a=>{let[i="",l=""]=a.pair.toUpperCase().split("/");return i.includes(o)&&l.includes(s)||i.includes(s)&&l.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=45&page=1&sortApr=true`,n=await _.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=A=>A==null||!Number.isFinite(A)?0:Math.pow(1.0001,A)*Math.pow(10,t-n),o=r(e.minTick),s=r(e.maxTick),a=e.token0.price,i=e.token1.price,l=typeof a=="number"&&typeof i=="number"&&i>0?a/i:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?o:s>0?1/s:0,m=u?s:o>0?1/o:0,p=u?l:l>0?1/l:0,h=u?e.token0.symbol:e.token1.symbol,g=u?e.token1.symbol:e.token0.symbol;if(!p||!d&&!m)return null;let f=Math.min(d,m),y=Math.max(d,m);if(p<f||p>y)return null;let k=Number(e.fee),w=Zo[k]??k/1e4,b=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,v=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:b,aprAvg:v,token0Price:a,token1Price:i,priceRange:{minPrice:d,maxPrice:m,currentPrice:p,baseToken:h,quoteToken:g}}}};var ia=["tvl","volume","apr","fee","liquidity"],Et=class extends T{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";noSuggestions=!0;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 J(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(h=>typeof h=="string"&&h.trim().length>0).map(h=>h.trim().toUpperCase()),r=(Array.isArray(e.chains)?e.chains:[]).filter(h=>typeof h=="string"&&h.trim().length>0),o=r.filter(h=>!this.service.isSupported(h)),s=r.filter(h=>this.service.isSupported(h)).map(h=>this.service.resolveChain(h));if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new K;let a=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.sortBy=="string"&&ia.includes(e.sortBy)?e.sortBy:"tvl",l={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(N),supportedChains:this.service.listSupportedChains().map(N),pools:[],count:0};let m=(await Promise.allSettled(a.map(h=>this.service.searchPools({tokens:n,chain:h,sortBy:i,filters:l})))).flatMap(h=>h.status==="fulfilled"?h.value:[]);i==="apr"?m.sort((h,g)=>(g.apr??0)-(h.apr??0)):i==="tvl"?m.sort((h,g)=>g.tvl-h.tvl):i==="volume"?m.sort((h,g)=>g.volume24hUsd-h.volume24hUsd):i==="fee"&&m.sort((h,g)=>h.feeTierBps-g.feeTierBps),m=m.slice(0,u);let p=[];return n.length===2&&(p=(await Promise.allSettled(a.map(g=>this.service.getCoinPoolPairs({chain:g,tokens:n})))).flatMap((g,f)=>g.status==="fulfilled"?g.value.map(y=>({...y,chain:N(a[f])})):[]),p.sort((g,f)=>(f.apr??-1/0)-(g.apr??-1/0)),p=p.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:a.map(N),unsupportedChains:o.map(N),sortBy:i,filters:l,count:m.length,pools:m.map(h=>this.formatPool(h)),coinPoolPairs:p}}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:re(e)}}};function re(c){return`https://app.uniswap.org/explore/pools/${an[c.chain]||c.chain}/${c.poolAddress}`}var an={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var Ut=class extends T{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";noSuggestions=!0;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 J(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;let s=o.length>0?o:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,l=(await Promise.allSettled(s.map(u=>this.service.getTrendingPools({chain:u})))).flatMap(u=>u.status==="fulfilled"?u.value:[]);return l.sort((u,d)=>d.volume24hUsd-u.volume24hUsd),l=l.slice(0,a),{_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:l.length,pools:l.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:re(u)}))}}};var Rt=class extends T{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";noSuggestions=!0;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 J(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;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),[a,i]=await Promise.all([this.service.getPoolByAddress({poolAddress:n,chain:s}),this.service.getCoinPoolByAddress({chain:s,poolAddress:n}).catch(()=>[])]);return a?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(i.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:i,pool:{pair:a.pair,poolAddress:a.poolAddress,chain:a.chain,feeTierBps:a.feeTierBps,feeTierPercent:a.feeTierPercent,tvlUsd:a.tvl,volumePastDayUsd:a.volume24hUsd,fees24hUsd:a.fees24hUsd,apr:a.apr,token0:a.token0,token1:a.token1,uniswapUrl:re(a)}}:{error:`No pool found at ${n} on ${N(s)}.`}}};var Nt=class extends T{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";noSuggestions=!0;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 J(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;let a=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=(await Promise.allSettled(a.map(u=>this.service.getPoolByPositionId({positionId:n,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);return l?{_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:l.pair,poolAddress:l.poolAddress,chain:l.chain,feeTierBps:l.feeTierBps,feeTierPercent:l.feeTierPercent,tvlUsd:l.tvl,volumePastDayUsd:l.volume24hUsd,fees24hUsd:l.fees24hUsd,apr:l.apr,token0:l.token0,token1:l.token1,uniswapUrl:re(l)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:n,chains:a,found:!1}}};var It=class extends T{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";noSuggestions=!0;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 J(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;let a=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=(await Promise.allSettled(a.map(d=>this.service.getPositionDetail({positionId:n,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);if(!l)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:a,found:!1};let u=an[l.position.chain]||l.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:{...l.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${u}/${l.position.positionId}`},pool:{...l.pool,uniswapUrl:re(l.pool)}}}};var Lt=class extends T{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";noSuggestions=!0;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 J(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;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),a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getCoinPoolPairs({chain:s,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 suggest using general pool data instead (via subgraph-search-pools).",tokens:n,chain:s,pairs:[],count:0};let l=[...i].sort((u,d)=>(d.apr??-1/0)-(u.apr??-1/0)).slice(0,a);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:l.length,pairs:l}}};var Dt=class extends T{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";noSuggestions=!0;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 J(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let d=this.linkAddLiquidity??null,m=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",p="",h=[];if(this.service.isSupported(m)){p=this.service.resolveChain(m);try{h=(await this.service.searchPools({tokens:[],chain:p,sortBy:"tvl"})).slice(0,5)}catch{h=[]}}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:
171
+ }`,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(),a=i.length>0?this.enrichWithLlama([s],i)[0]:s,c=a.feeTierBps,u=a.feeTierPercent;return{position:{positionId:o.id,poolAddress:a.poolAddress,pair:a.pair,token0:{symbol:a.token0.symbol,address:a.token0.address},token1:{symbol:a.token1.symbol,address:a.token1.address},feeTierBps:c,feeTierPercent:u,chain:a.chain,liquidity:o.liquidity,depositedToken0:o.depositedToken0,depositedToken1:o.depositedToken1,withdrawnToken0:o.withdrawnToken0,withdrawnToken1:o.withdrawnToken1,collectedFeesToken0:o.collectedFeesToken0,collectedFeesToken1:o.collectedFeesToken1},pool:a}}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[a="",c=""]=i.pair.toUpperCase().split("/");return a.includes(o)&&c.includes(s)||a.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 P.get(t);if(!n.ok)throw new Error(L(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=A=>A==null||!Number.isFinite(A)?0:Math.pow(1.0001,A)*Math.pow(10,t-n),o=r(e.minTick),s=r(e.maxTick),i=e.token0.price,a=e.token1.price,c=typeof i=="number"&&typeof a=="number"&&a>0?i/a: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,g=u?e.token0.symbol:e.token1.symbol,h=u?e.token1.symbol:e.token0.symbol;if(!m||!d&&!p)return null;let f=Math.min(d,p),y=Math.max(d,p);if(m<f||m>y)return null;let b=Number(e.fee),w=yr[b]??b/1e4,v=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,k=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:v,aprAvg:k,token0Price:i,token1Price:a,priceRange:{minPrice:d,maxPrice:p,currentPrice:m,baseToken:g,quoteToken:h}}}};var ni={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},oi=/^0x[a-fA-F0-9]{40}$/;function ri(l,e){if(typeof l!="string"||typeof e!="string")return null;let t=ni[l.toLowerCase()];return!t||!oi.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function ye(l,e){let t=ri(l,e);return t?{uniswapUrl:t}:{}}var le="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. ",ce="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. ",ue="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. ",X="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",be=`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 si=["tvl","volume1Day","volume1Week","volume30Day","txCount","apr"],ii=["V2","V3","V4"],Rt=class extends T{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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea`;category="blockchain-data";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. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',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 10.",required:!1,default:10},{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}];service;subgraphFallback;constructor(e,t){super(),this.service=new ae(e),this.subgraphFallback=new Q(t)}async run(e,t){let n=M(e.chain,t),r=this.parseProtocolVersion(e.protocolVersion),o=this.parseSortKey(e.sortBy),s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):10,i=e.multichain===!0,a=await this.service.getTopPools({chain:n,protocolVersion:r,sortBy:o,limit:s,multichain:i});if(!a.success)return{error:a.error||"Failed to fetch top pools"};let c=(a.data??[]).map(h=>this.formatPool(h)),u="uniswap";if(c.length===0&&r==="V3"){let h=await this.fetchV3Fallback(n,o,s);h.length>0&&(c=h,u="subgraph")}let d=c.map(h=>this.withExpertSignals(h)),p=u==="subgraph",m=p?`"Volume past day" (translate naturally into the user's language; NEVER call it "24h volume", "daily volume", or "24h")`:"24h volume";return{_instructions:(p?`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). `:"")+le+`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, ${m}, 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. `+ce+"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. "+ue+X+"Mention the chain and the sort metric in the intro line. "+be,chain:n,protocolVersion:r,sortBy:o,source:u,count:d.length,pools:d.map(h=>({...h,...ye(n,h.address)}))}}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,a)=>this.fallbackSortValue(a,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(ii.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(si.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 Po={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},ai={100:.01,500:.05,3e3:.3,1e4:1},Be=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=se(e);return!!(t&&Po[t])}listSupportedChains(){return Object.keys(Po).filter(e=>se(e)===e)}numericChainId(e){let t=se(e);return t?Po[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=(a,c)=>a.includes(c)||c.includes(a);r=r.filter(a=>{let[c="",u=""]=a.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 P.get(t);if(!n.ok)throw new Error(L(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=A=>A==null||!Number.isFinite(A)?0:Math.pow(1.0001,A)*Math.pow(10,t-n),o=r(e.minTick),s=r(e.maxTick),i=e.token0.price,a=e.token1.price,c=typeof i=="number"&&typeof a=="number"&&a>0?i/a: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,g=u?e.token0.symbol:e.token1.symbol,h=u?e.token1.symbol:e.token0.symbol;if(!m||!d&&!p)return null;let f=Math.min(d,p),y=Math.max(d,p);if(m<f||m>y)return null;let b=Number(e.fee),w=ai[b]??b/1e4,v=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,k=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:v,aprAvg:k,token0Price:i,token1Price:a,priceRange:{minPrice:d,maxPrice:p,currentPrice:m,baseToken:g,quoteToken:h}}}};var li=365,br=/^0x[a-fA-F0-9]{40}$/,ci=6,Ut=class extends T{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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";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:'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}];service;coinPool;constructor(e,t){super(),this.service=new ae(e),this.coinPool=new Be(t)}async run(e,t){let n=M(e.chain,t),r=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",o=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0;if(!r)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let i=o?`${r} ${o}`:r,a=await this.service.searchPools({query:i,chain:n,page:1,size:100,protocolVersion:"V3"});if(!a.success)return{error:a.error||"Pool search failed"};let c=a.data??[],d=c.filter(m=>this.matchesFilter(m,r,o,s,"ordered")),p=!1;if(d.length===0&&o){let m=c.filter(g=>this.matchesFilter(g,r,o,s,"reversed"));m.length>0&&(d=m,p=!0)}if(d.length===0)return{error:`No V3 pool matched ${this.describeQuery(r,o,s)} on ${E(n)}. Verify the symbols and fee tier with the user.`};if(d.length===1){let m=d[0];if(!m.id||!br.test(m.id))return{error:"Resolved pool has no valid address"};let[g,h]=await Promise.all([this.service.getV3PoolDetail({address:m.id,chain:n}),this.fetchPriceRanges(n,m.id,m.token0?.symbol,m.token1?.symbol)]);return!g.success||!g.data?{error:g.error||"Failed to fetch pool detail"}:{priceRanges:h,_instructions:le+"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. "+ce+ue+'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. '+X+be,pairOrderMatched:p?"reversed":"ordered",pool:{...this.formatPool(g.data),...ye(n,m.id)}}}if(o){let m=this.rankCandidates(d).slice(0,ci),h=(await Promise.all(m.map(async f=>{if(!f.id||!br.test(f.id))return;let y=await this.service.getV3PoolDetail({address:f.id,chain:n});if(!(!y.success||!y.data))return{...this.formatPool(y.data),...ye(n,f.id)}}))).filter(f=>f!=null);if(h.length>0)return{_instructions:le+"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. "+ce+"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. "+ue+X+be,chain:n,pairOrderMatched:p?"reversed":"ordered",multiFeeTier:!0,count:h.length,pools:h}}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.",chain:n,pairOrderMatched:p?"reversed":"ordered",reason:this.candidateReason(r,o,s),missing:this.missingFields(o,s),candidates:this.rankCandidates(d).slice(0,10).map(m=>{let g=this.formatCandidate(m);return{...g,...ye(n,g.address)}})}}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(),a=t.toLowerCase();if(n){let c=n.toLowerCase();return o==="reversed"?this.symbolIncludes(s,c)&&this.symbolIncludes(i,a):this.symbolIncludes(s,a)&&this.symbolIncludes(i,c)}return this.symbolIncludes(s,a)||this.symbolIncludes(i,a)}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*li*100:void 0,a=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:a,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 ui=["V2","V3","V4","ALL"],Nt=class extends T{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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.';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:'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:"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 15.",required:!1,default:15},{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}];service;constructor(e){super(),this.service=new ae(e)}async run(e,t){let n=typeof e.query=="string"?e.query.trim():"";if(!n)return{error:"Search query is required"};let r=M(e.chain,t),o=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,s=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):15,i=this.parseProtocolFilter(e.protocolVersion),a=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,c=await this.service.searchPools({query:n,chain:r,page:o,size:s,protocolVersion:i,feeTier:a});if(!c.success)return{error:c.error||"Failed to search pools"};let u=(c.data??[]).map(d=>this.formatPool(d));return{_instructions:le+"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. "+ce+ue+"When several pools share the searched token, finish with a clear TOP PICK among them. "+X+"Mention the search query and chain in the intro. "+be,query:n,chain:r,protocolVersion:i,feeTierBps:a,feeTierPercent:a!=null?a/1e4:void 0,page:o,size:s,count:u.length,pools:u.map(d=>({...d,...ye(r,d.address)}))}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(ui.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 di=365,wr=/^0x[a-fA-F0-9]{40}$/,It=class extends T{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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea';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:'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}];service;constructor(e){super(),this.service=new ae(e)}async run(e,t){let n=M(e.chain,t),r=typeof e.address=="string"?e.address.trim():"",[o,s]=await Promise.all([this.service.searchPools({query:r,chain:n,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:r,chain:n,page:1,size:5})]),i=o.success?this.findPoolByAddress(o.data??[],r):void 0;if(i)return this.handlePoolHit(i,n);let a=s.success?this.findTokenByAddress(s.data??[],r):void 0;return a?this.handleTokenHit(a,n):!o.success&&!s.success?{error:o.error||s.error||"Failed to resolve address"}:{error:`Address ${r} did not match any pool or token Uniswap knows on ${E(n)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t){if(!e.id)return{error:"Resolved pool has no identifier"};let n=e.protocolVersion??"V3",r=n==="V4"?await this.service.getV4PoolDetail({poolId:e.id,chain:t}):n==="V2"?wr.test(e.id)?await this.service.getV2PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V2 pair has no valid address"}:wr.test(e.id)?await this.service.getV3PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V3 pool has no valid address"};return!r.success||!r.data?{error:r.error||"Failed to fetch pool detail"}:{_instructions:`The address is a Uniswap ${n} pool. `+le+"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. "+ce+ue+X+be,resolvedAs:"pool",chain:t,protocolVersion:n,pool:{...this.formatPoolDetail(r.data),...ye(t,e.id)}}}async handleTokenHit(e,t){let n=e.symbol?.trim();if(!n)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let r=await this.service.searchPools({query:n,chain:t,page:1,size:100,protocolVersion:"V3"});if(!r.success)return{error:r.error||"Failed to fetch pools for resolved token"};let o=(e.address??"").toLowerCase(),i=[...(r.data??[]).filter(a=>{let c=(a.token0?.address??"").toLowerCase(),u=(a.token1?.address??"").toLowerCase();return c===o||u===o})].sort((a,c)=>(c.volumeUsd24hr??0)-(a.volumeUsd24hr??0)).slice(0,10);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.",resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:i.length,pools:i.map(a=>({...this.formatPoolCandidate(a),...ye(t,a.id)}))}}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*di*100:void 0,a=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:a,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 xo=require("js-sha3"),kr=2n**96n;function vr(l,e,t){let n=l*l,r=kr*kr,o=n*10n**18n/r;return Number(o)/1e18*Math.pow(10,e-t)}function we(l,e,t){return Math.pow(1.0001,l)*Math.pow(10,e-t)}function je(l,e,t){if(l<=0)throw new Error("priceToTick: price must be > 0");let n=l/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 Dt(l,e,t){let n={minPrice:l,maxPrice:e,inverted:!1};if(!Number.isFinite(l)||!Number.isFinite(e)||!Number.isFinite(t)||l<=0||e<=0||t<=0||l>=e)return n;let r={minPrice:1/e,maxPrice:1/l,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 a=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return a(r)<a(n)?r:n}function Pe(l,e,t="nearest"){let n=Math.abs(l-Math.round(l))<1e-6?Math.round(l):l,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 qe=-887272,Lt=887272;function xe(l){return l<qe?qe:l>Lt?Lt:l}var pi=/^0x[0-9a-f]+$/i;function he(l){return l.startsWith("0x")||l.startsWith("0X")?l.slice(2):l}function jn(l){let e=he(l).toLowerCase();if(e.length>64)throw new Error(`pad32: input too long (${e.length})`);return e.padStart(64,"0")}function zn(l){if(!pi.test(l)||he(l).length!==40)throw new Error(`encodeAddress: invalid address ${l}`);return jn(l.toLowerCase())}function ke(l,e=256){let t=typeof l=="bigint"?l:BigInt(l);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 jn(n)}function _o(l){let e=typeof l=="bigint"?l:BigInt(l);if(e>=0n)return jn(e.toString(16));let t=1n<<256n;return jn((t+e).toString(16))}function Tr(l){return"0x"+(0,xo.keccak_256)(mi(l))}function mi(l){let e=he(l),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(l){return"0x"+(0,xo.keccak_256)(new TextEncoder().encode(l)).slice(0,8)}function An(l,e){let t=l.substring(e,e+64);return t?BigInt("0x"+t):0n}function Co(l,e){let t=l.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 Eo(l,e){return"0x"+l.substring(e+24,e+64).toLowerCase()}var Fe=class{config;constructor(e){this.config=e}hasIntegratedApproval(){return!1}};var hi="https://exchange-api.keyring.app/admin/setting?configs=others",gi="https://api.coinpool.app/config/bridgeProviderByChain",fi="https://coinpool-api-op.bacoor-test001.xyz/config/bridgeProviderByChain";function yi(l){let e=null,t=null;return async()=>e||t||(t=(async()=>{try{return e=await l(),e}catch{return null}finally{t=null}})(),t)}async function Sr(l){return(await P.get(l,{headers:{Accept:"application/json"}})).data}var bi=yi(async()=>(await Sr(hi))?.others??null),Qn={prod:null,dev:null},Sn={prod:null,dev:null};async function wi(l){let e=l?"prod":"dev";if(Qn[e])return Qn[e];if(Sn[e])return Sn[e];let t=l?gi:fi;return Sn[e]=(async()=>{try{let n=await Sr(t);return Qn[e]=n?.data??null,Qn[e]}catch{return null}finally{Sn[e]=null}})(),Sn[e]}function ki(l){if(!l)return null;try{let e=JSON.parse(l);return e&&typeof e=="object"?e:null}catch{return null}}function Ar(l){if(l==null)return 0;let e=typeof l=="number"?l:Number(l);return Number.isFinite(e)?e:0}function vi(l){return l==="debridge"||l==="relay"}async function Xn(l,e){let n=(await wi(e))?.[String(l)];return vi(n)?n:null}async function Ot(l,e){let t=await bi();if(!t)return null;let n,r;if(l==="debridge")n=ki(t.affiliateRecipient)?.[String(e)],r=Ar(t.AFFILIATE_FEE_PERENT);else if(l==="relay")n=t.RELAY_AFFILIATE_FEE_RECIPIENT,r=Ar(t.RELAY_AFFILIATE_FEE_PERCENT);else return null;return!n||r<=0?null:{affiliateFeeRecipient:n,affiliateFeePercent:r}}var ge={"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"};function Ti(l){return ge[l.toLowerCase()]}var Pr={};function Ro(l){let e={};if(l)for(let[t,n]of Object.entries(l))typeof n=="string"&&n.trim()&&(e[t.toLowerCase()]=n.trim());Pr=e}function Mt(l){let e=l.toLowerCase();return Pr[e]??ge[e]}async function Ne(l,e,t){for(let r=0;r<=5;r++){let o=await P.post(l,{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}: ${L(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 xr(l,e,t){return Ne(l,"eth_call",[{to:e,data:t},"latest"])}async function Uo(l,e,t){let n=Mt(l);if(!n)return null;try{return await xr(n,e,t)}catch{return null}}var Ai="https://dln.debridge.finance/v1.0",Si="0x0000000000000000000000000000000000000000",Pi=new Set([429,500]),xi=5,_i=1e3,Ci=l=>new Promise(e=>setTimeout(e,l)),Bt=class extends Fe{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Ai,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:a,slippage:c,isCrossChain:u}=e,d=u??t!==o,p=await Ot(this.getProviderName(),t);try{if(d){let h={srcChainId:String(t),srcChainTokenIn:n,srcChainTokenInAmount:r,dstChainId:String(o),dstChainTokenOut:s,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:a,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent);let f=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,h);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,estimation:f.estimation,isCrossChain:!0,srcChainId:t,dstChainId:o,raw:f}}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 g=await this.get(`${this.apiBaseUrl}/chain/transaction`,m);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,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:g}}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()===Si)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 a;try{a=BigInt(o)}catch{a=0n}return i>=a?{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=a=>a.toLowerCase().replace(/^0x/,"").padStart(64,"0"),s=`0xdd62ed3e${o(n)}${o(r)}`,i=await Uo(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 P.get(r,{headers:{Accept:"application/json"}});for(let s=0;s<xi&&Pi.has(o.status);s++)await Ci(_i),o=await P.get(r,{headers:{Accept:"application/json"}});return o.data}};var Ei="https://api.relay.link";function _r(l){return l===7565164||l==="7565164"?792703809:l}var qt=class extends Fe{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Ei,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:a,slippage:c}=e,u=await Ot(this.getProviderName(),t),d={user:i||a,originChainId:_r(t),destinationChainId:_r(o),originCurrency:n,destinationCurrency:s,amount:r,recipient:i||a,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"),g=p.steps?.find(b=>b.id==="swap"||b.id==="deposit"),h=g?.items?.[0]?.data,f=Array.isArray(h?.instructions);return{success:!0,provider:"relay",tx:h?f?{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:g?.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 a=Object.entries(n).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(u))}`).join("&");o=`${o}?${a}`}else t==="POST"&&n&&(s=n);let i=await P.request(t,o,s,{headers:r});if(!i.ok)throw new Error(L(i));return i.data}};var Jn={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},Pn="debridge";function Ri(l){if(l==null)return null;let e=typeof l=="number"?l:Number(l);return Number.isFinite(e)?e:null}var ze=class{providerConfig;isProduction;cache=new Map;constructor(e=Jn,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=Ri(e);return t===null?Pn:await Xn(t,this.isProduction)??Pn}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 Bt(t);case"relay":return new qt(t);default:{let n=e;throw new Error(`Unknown swap provider: ${String(n)}`)}}}},_e=new ze;var Ui="https://api.coinpool.app/config/addresses",Ni="https://coinpool-api-op.bacoor-test001.xyz/config/addresses",Zn={prod:null,dev:null},xn={prod:null,dev:null};async function Ii(l){let e=l?"prod":"dev";if(Zn[e])return Zn[e];if(xn[e])return xn[e];let t=l?Ui:Ni;return xn[e]=(async()=>{try{let r=(await P.get(t,{headers:{Accept:"application/json"}})).data;return Zn[e]=r?.data??null,Zn[e]}catch{return null}finally{xn[e]=null}})(),xn[e]}function Li(l){let e=l.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 Cr(l,e,t){let n=await Ii(t);if(!n)return;let r=Li(e);if(!r)return;let o=n[l]?.[r];return Array.isArray(o)?o[0]:typeof o=="string"?o:void 0}async function eo(l,e){return Cr("createPoolProxyV3",l,e)}async function to(l,e){return Cr("nftPositionUniswap",l,e)}var $="0x0000000000000000000000000000000000000000",Di={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:ge["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:ge["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:ge["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:ge["0x89"],native:{symbol:"MATIC",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:ge["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:ge["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:ge["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:ge["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function J(l){return Di[l.toLowerCase()]}function Ft(l){return J(l)?.native}var Er="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function No(l){let e=l.stableTicks??3,t=l.widePercent??{down:50,up:100},n=we(l.currentTick,l.token0Decimals,l.token1Decimals),r=xe(Pe(l.currentTick-e*l.tickSpacing,l.tickSpacing,"down")),o=xe(Pe(l.currentTick+e*l.tickSpacing,l.tickSpacing,"up")),s=n*(1-t.down/100),i=n*(1+t.up/100),a=je(s,l.token0Decimals,l.token1Decimals),c=je(i,l.token0Decimals,l.token1Decimals),u=xe(Pe(a,l.tickSpacing,"down")),d=xe(Pe(c,l.tickSpacing,"up")),p=(m,g,h,f,y)=>{let b=we(f,l.token0Decimals,l.token1Decimals),w=we(y,l.token0Decimals,l.token1Decimals);return{id:m,label:g,description:h,tickLower:f,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 Oi=Ue("slot0()"),Mi=Ue("liquidity()"),Bi=Ue("tickSpacing()"),qi=Ue("fee()"),Fi=Ue("token0()"),$i=Ue("token1()"),Vi=Ue("decimals()"),Qe=class{swapFactory;isProduction;constructor(e){this.isProduction=e?.isProduction??!0,this.swapFactory=e?.swapFactory??(this.isProduction?_e:new ze(void 0,!1))}getRpcUrl(e){let t=Mt(e);if(t)return t;let n=J(e);if(!n)throw new Error(`Unsupported chain: ${e}`);return n.defaultRpc}async getGatewayAddress(e){return eo(e,this.isProduction)}async getPositionManagerAddress(e){return to(e,this.isProduction)}async ethCall(e,t,n){return Ne(this.getRpcUrl(e),"eth_call",[{to:t,data:n},"latest"])}async getNativeBalance(e,t){let n=await Ne(this.getRpcUrl(e),"eth_getBalance",[t,"latest"]);return BigInt(n)}async getGasPrice(e){let t=await Ne(this.getRpcUrl(e),"eth_gasPrice",[]);return BigInt(t)}async getTransactionReceipt(e,t){return await Ne(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()!==Er||"0x"+s[1].slice(-40).toLowerCase()!==$))try{return BigInt(s[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=J(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,a]=await Promise.all([this.ethCall(e,t,Oi),this.ethCall(e,t,Mi),this.ethCall(e,t,Bi),this.ethCall(e,t,qi),this.ethCall(e,t,Fi),this.ethCall(e,t,$i)]),c=he(n),u=An(c,0),d=Co(c,64),p=An(he(r),0),m=Number(Co(he(o),0)),g=Number(An(he(s),0)),h=Eo(he(i),0),f=Eo(he(a),0),[y,b]=await Promise.all([this.readErc20Decimals(e,h),this.readErc20Decimals(e,f)]),w=vr(u,y,b);return{poolAddress:t,chainId:e,fee:g,tickSpacing:m,liquidity:p,sqrtPriceX96:u,currentTick:d,token0:h,token1:f,currentPrice:w}}async readErc20Decimals(e,t){if(t.toLowerCase()===$)return 18;let n=await this.ethCall(e,t,Vi);return Number(An(he(n),0))}async getNativePriceUsd(e){let t=J(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 P.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,a=2**96,c=Number(n.sqrtPriceX96)/a,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,g=c*c,h=p*g,y=h+m;if(!Number.isFinite(y)||y<=0)throw new Error("splitNativeAmountForRange: invalid total value");let b=h/y,w=1-b,v=1000000000000000n,k=BigInt(Math.floor(b*Number(v))),A=t*k/v,x=t-A;return{ratio0:b,ratio1:w,amountInFor0Wei:A,amountInFor1Wei:x}}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(g=>zn(g.tokenIn)+ke(g.tokenInAmount)+zn(g.tokenOut)+ke(g.tokenOutAmount)).join(""),o=e.exchanges.map(g=>{let h=he(g.data||"0x"),f=h.length/2,y=ke(f),b=(64-h.length%64)%64,w=h+"0".repeat(b);return{head:zn(g.to)+ke(96)+ke(g.value),body:y+w}}).map(g=>g.head+g.body),s=o.length*32,i=[];for(let g of o)i.push(ke(s)),s+=g.length/2;let a=i.join("")+o.join(""),c=ke(e.fee,24)+ke(e.amount0Min)+ke(e.amount1Min)+_o(e.tickLower)+_o(e.tickUpper),p=256+32+160,m=n+ke(p)+c+a;return t+m}_keccak(e){return Tr(e)}};var Wi=/^0x[a-fA-F0-9]{40}$/,$t=class extends T{name="open-add-liquidity-form";kind="ui";category="pool-action";noSuggestions=!0;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}];uniswap;pool;coinPool;minProvideUsd;constructor(e){super(),this.uniswap=new ae(e),this.pool=new Qe(e?.pool),this.coinPool=new Be(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),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=M(e.chain,t),r=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",o=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,i=typeof e.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,a=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,c=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,u=c&&i!=null&&(c.toLowerCase()===r.toLowerCase()||c.toLowerCase()===o.toLowerCase())?null:c,d=this.parseRangeStrategy(e.rangeStrategy),p=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,m=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!r||!o)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let g=J(n);if(!g)return{error:"unsupported_chain",chain:n,_instructions:`Chain ${n} is not supported by the add-liquidity flow.`};let h=Ft(n);if(u&&h&&u.toLowerCase()!==h.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:u,nativeSymbol:h.symbol,chainName:g.name,_instructions:`The user asked to add liquidity using ${u}, but this app only supports the chain's native coin (${h.symbol} on ${g.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${h.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 f=await this.pool.getGatewayAddress(n);if(!f)return{error:"no_gateway_configured",chain:n,_instructions:`No gateway contract is configured for chain ${n} (${g.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let y=t?.walletAddress;if(!y)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 b=await this.uniswap.searchPools({query:`${r} ${o}`,chain:n,page:1,size:100,protocolVersion:"V3",feeTier:s});if(!b.success)return{error:b.error||"pool_search_failed"};let w=b.data??[],v=w.find(I=>this.matchesPairExact(I,r,o,s)),k=v?[]:w.filter(I=>this.matchesPair(I,r,o,s));if(!v&&k.length===0)return{error:"pool_not_found",_instructions:`No V3 pool found for ${r}/${o}${s!=null?` at ${s}bps`:""} on ${g.name}. Verify the inputs with the user.`};if(!v&&k.length>1){let I=k.map(oe=>{let Je=oe.volume1DayUsd??oe.volumeUsd24hr,Mn=oe.tvlUsd,Fo=typeof Je=="number"&&typeof Mn=="number"&&Mn>0?Je/Mn:void 0;return{address:oe.id,token0Symbol:oe.token0?.symbol,token1Symbol:oe.token1?.symbol,feeTier:oe.feeTier,feeTierPercent:oe.feeTier!=null?oe.feeTier/1e4:void 0,volume24hUsd:Je,tvlUsd:Mn,...Fo!=null?{volumeToTvlRatio:Fo}:void 0,...oe.apr?{apr:oe.apr}:void 0}}).sort((oe,Je)=>(Je.volumeToTvlRatio??Je.apr??-1/0)-(oe.volumeToTvlRatio??oe.apr??-1/0));return{relatedPools:I,count:I.length,_instructions:le+"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. "+ce+"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). "+ue+X+be}}let A=v??k[0];if(!A.id||!Wi.test(A.id))return{error:"invalid_pool_address"};let x=this.fetchPriceRanges(n,A.id,A.token0?.symbol,A.token1?.symbol),S=await this.pool.readPoolOnchain(n,A.id),[O,C,B]=await Promise.all([this.pool.getNativeBalance(n,y),this.pool.estimateGasReserveWei(n),this.pool.getNativePriceUsd(n)]),_=O>C?O-C:0n,N=Ft(n),ve=Number(_)/10**N.decimals,Le=Number(O)/10**N.decimals,V=B!=null?ve*B:null,[te,Re]=await Promise.all([this.pool.readErc20Decimals(n,S.token0),this.pool.readErc20Decimals(n,S.token1)]),ne={min:we(qe,te,Re),max:we(Lt,te,Re)},Te=null;O===0n?Te="no_balance":V!=null&&V<this.minProvideUsd&&(Te="insufficient_balance");let Ve=A.token0,We=A.token1,fn=[25,50,75,100].map(I=>({percent:I,amountWei:(_*BigInt(I)/100n).toString(),amount:ve*(I/100)})),yn=null,He=null;if(i!=null){He=i;let I=BigInt(Math.floor(He*10**N.decimals));I>0n&&(yn=I.toString())}else if(a!=null&&B!=null&&B>0){He=a/B;let I=BigInt(Math.floor(He*10**N.decimals));I>0n&&(yn=I.toString())}let On={address:$,isNative:!0,symbol:N.symbol,name:N.name,decimals:N.decimals,priceUsd:B,balanceWei:O.toString(),balance:Le,gasReserveWei:C.toString(),spendableWei:_.toString(),spendable:ve,spendableUsd:V,quickRates:fn,minProvideUsd:this.minProvideUsd,warning:Te,warningMessage:Te==="no_balance"?`You have no ${N.symbol} on ${g.name}. Top up to add liquidity.`:Te==="insufficient_balance"?`Spendable ${N.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:He,prefillAmountWei:yn},Xe=this.computePrefillRange({explicitMinPrice:p,explicitMaxPrice:m,rangeStrategy:d,currentPrice:S.currentPrice,currentTick:S.currentTick,tickSpacing:S.tickSpacing,token0Decimals:te,token1Decimals:Re,priceBounds:ne}),Bo={component:"AddLiquidityForm",props:{chain:{hexId:n,name:g.name},pool:{address:S.poolAddress,fee:S.fee,feePercent:S.fee/1e4,tickSpacing:S.tickSpacing,currentTick:S.currentTick,currentPrice:S.currentPrice,sqrtPriceX96:S.sqrtPriceX96.toString(),token0:{address:S.token0,symbol:Ve?.symbol,name:Ve?.name,logo:Ve?.logo},token1:{address:S.token1,symbol:We?.symbol,name:We?.name,logo:We?.logo}},inputToken:On,priceBounds:ne,prefillRange:Xe,gatewayAddress:f}},qo=this.orientRangesToForm(await x,S.currentPrice,Ve?.symbol,We?.symbol);return{ui:Bo,suggestedRanges:qo,summary:this.buildSummary({chainName:g.name,pair:`${Ve?.symbol??r}/${We?.symbol??o}`,feePercent:S.fee/1e4,warning:Te,minProvideUsd:this.minProvideUsd,nativeSymbol:N.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. '+X+"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:a,currentPrice:c}=s.priceRange,u=i,d=a,p=c;if(o(c)){let m=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<m&&(u=o(a)?1/a:0,d=o(i)?1/i:0,p=1/c)}return{fee:s.fee,apr:s.apr,minPrice:u,maxPrice:d,currentPrice: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(),a=n.toLowerCase();return o===i&&s===a||o===a&&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(),a=n.toLowerCase(),c=this.symMatch(o,i)&&this.symMatch(s,a),u=this.symMatch(o,a)&&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:a}=Dt(t,n,o);return{strategy:"user",minPrice:Math.max(i,s.min),maxPrice:Math.min(a,s.max)}}if(r==="full")return{strategy:"full",minPrice:s.min,maxPrice:s.max};if(r==="stable"||r==="wide"){let a=No({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===r);if(a)return{strategy:r,minPrice:a.minPrice,maxPrice:a.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 Rr=[{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"}]}],no=[{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 Hi=/^0x[a-fA-F0-9]{40}$/,Vt=class extends T{name="preview-add-liquidity";kind="action";category="pool-action";noSuggestions=!0;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 Qe(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new ee}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=M(e.chain,t),o=Number(e.minPrice),s=Number(e.maxPrice),i=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,a=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!n||!r||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!Hi.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(o<0||s<=0||o>=s)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(i<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let c=J(r);if(!c)return{error:"unsupported_chain",chain:r};let u=await this.pool.getGatewayAddress(r);if(!u)return{error:"no_gateway_configured",chain:r};let d=t?.walletAddress;if(!d)return{error:"wallet_not_connected"};let p=Ft(r),m=BigInt(Math.floor(i*10**p.decimals));if(m<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let g=await this.pool.readPoolOnchain(r,n),[h,f]=await Promise.all([this.pool.readErc20Decimals(r,g.token0),this.pool.readErc20Decimals(r,g.token1)]),{minPrice:y,maxPrice:b}=Dt(o,s,g.currentPrice),w=y===0?qe:je(y,h,f),v=je(b,h,f),k=y===0?xe(Pe(qe,g.tickSpacing,"up")):xe(Pe(w,g.tickSpacing,"down")),A=xe(Pe(v,g.tickSpacing,"up"));if(k>=A||k<qe||A>Lt)return{error:"invalid_range_after_alignment",_instructions:"After aligning to tickSpacing the range collapsed. Ask the user for a wider price range.",rawTickLower:w,rawTickUpper:v,tickLower:k,tickUpper:A};let x={tickLower:k,tickUpper:A,minPrice:we(k,h,f),maxPrice:we(A,h,f)},S=g.currentTick;if(S<k||S>=A){let I=S<k?"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 ${I==="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:g.currentPrice,requestedRange:{minPrice:x.minPrice,maxPrice:x.maxPrice},side:I}}let[O,C,B]=await Promise.all([this.pool.getNativeBalance(r,d),this.pool.estimateGasReserveWei(r),this.pool.getNativePriceUsd(r)]),_=m+C;if(O<_)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:O.toString(),requiredWei:_.toString(),gasReserveWei:C.toString()};let N=this.pool.splitNativeAmountForRange({nativeAmountWei:m,pool:g,tickLower:k,tickUpper:A,token0Decimals:h,token1Decimals:f}),ve=g.token0.toLowerCase()===$,Le=g.token1.toLowerCase()===$,V=[];if(ve||N.amountInFor0Wei===0n)V.push({tokenIn:$,tokenOut:g.token0,amountIn:N.amountInFor0Wei,tx:{to:$,data:"0x",value:"0"},minAmountOut:ve?N.amountInFor0Wei:0n});else{let I=await this.pool.fetchSwapLeg({senderAddress:d,chainId:r,tokenIn:$,tokenInAmount:N.amountInFor0Wei.toString(),tokenOut:g.token0,tokenOutRecipient:u,slippage:typeof a=="number"?a:"auto"});V.push({tokenIn:$,tokenOut:g.token0,amountIn:N.amountInFor0Wei,tx:{to:I.to,data:I.data,value:I.value},minAmountOut:BigInt(I.minAmountOut||"0")})}if(Le||N.amountInFor1Wei===0n)V.push({tokenIn:$,tokenOut:g.token1,amountIn:N.amountInFor1Wei,tx:{to:$,data:"0x",value:"0"},minAmountOut:Le?N.amountInFor1Wei:0n});else{let I=await this.pool.fetchSwapLeg({senderAddress:d,chainId:r,tokenIn:$,tokenInAmount:N.amountInFor1Wei.toString(),tokenOut:g.token1,tokenOutRecipient:u,slippage:typeof a=="number"?a:"auto"});V.push({tokenIn:$,tokenOut:g.token1,amountIn:N.amountInFor1Wei,tx:{to:I.to,data:I.data,value:I.value},minAmountOut:BigInt(I.minAmountOut||"0")})}let te=I=>I*BigInt(this.mintMinPercent)/100n,Re=te(V[0].minAmountOut),ne=te(V[1].minAmountOut),Te=V.map(I=>({tokenIn:I.tokenIn,tokenInAmount:BigInt(I.amountIn),tokenOut:I.tokenOut,tokenOutAmount:BigInt(I.minAmountOut)})),Ve=V.map(I=>({to:I.tx.to,data:I.tx.data,value:BigInt(I.tx.value||"0")})),We=it({abi:Rr,functionName:"mint",args:[Te,Ve,{fee:Number(g.fee),amount0Min:BigInt(Re),amount1Min:BigInt(ne),tickLower:k,tickUpper:A}]}),fn=i,yn={chainId:r,to:u,data:We,value:m.toString(),from:d},He={nativeIn:fn,nativeSymbol:p.symbol,nativeInUsd:B!=null?fn*B:null,ratio:{token0Percent:N.ratio0,token1Percent:N.ratio1},expectedToken0:Number(V[0].minAmountOut)/10**h,expectedToken1:Number(V[1].minAmountOut)/10**f,amount0Min:Re.toString(),amount1Min:ne.toString(),slippageBps:a},On=await this.pantograph.getTokensMetadata([g.token0,g.token1],r),Xe=On[g.token0],bn=On[g.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:r,name:c.name},unsignedTx:yn,summary:He,pool:{...g,feePercent:g.fee/1e4,token0:{address:g.token0,symbol:Xe.symbol,name:Xe.name,decimals:Xe.decimals,logo:Xe.icon_image},token1:{address:g.token1,symbol:bn.symbol,name:bn.name,decimals:bn.decimals,logo:bn.icon_image}},range:x,gatewayAddress:u}},summary:`Ready to add ${fn} ${p.symbol} to pool ${g.token0}/${g.token1} ${g.fee/1e4}% on ${c.name}, range [${x.minPrice}, ${x.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 Ur=365,Gi=1e3,Yi=/^0x[a-fA-F0-9]{40}$/;function Ki(l,e){return{depositUsd:l,aprPercent:e*100,dailyUsd:l*e/Ur,weeklyUsd:l*e/52,monthlyUsd:l*e/12,yearlyUsd:l*e}}var Wt=class extends T{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):
172
+ \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.
173
+ \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.
174
+ \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.
175
+ \u2022 If chain is missing \u2192 default to userContext.chain or "0x1" (Ethereum).
176
+ Source: Uniswap ExploreStats (live 24h data). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`;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:'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}];service;constructor(e){super(),this.service=new ae(e)}async run(e,t){let n=M(e.chain,t),r=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",o=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,i=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,a=i?e.depositUsd:Gi;if(!r)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let c=o?`${r} ${o}`:r,u=await this.service.searchPools({query:c,chain:n,page:1,size:50,protocolVersion:"V3"});if(!u.success)return{error:u.error||"Pool search failed"};let d=u.data??[],p=this.filterPools(d,r,o,s);if(p.length===0)return{error:`No V3 pool found for ${this.describeQuery(r,o,s)} on ${E(n)}. Verify the token symbols with the user.`};let m=this.rankByVolume(p);if(o&&s==null&&new Set(m.map(_=>_.feeTier).filter(_=>typeof _=="number")).size>1){let _=this.dedupeByFeeTier(m).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:`${r}/${o} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:_.map(N=>({pair:N.token0?.symbol&&N.token1?.symbol?`${N.token0.symbol}/${N.token1.symbol}`:void 0,feeTierBps:N.feeTier,feeTierPercent:typeof N.feeTier=="number"?N.feeTier/1e4:void 0,volume24hUsd:N.volumeUsd24hr,address:N.id}))}}let g=m[0];if(!g.id||!Yi.test(g.id))return{error:"Resolved pool has no valid address."};let h=await this.service.getV3PoolDetail({address:g.id,chain:n});if(!h.success||!h.data)return{error:h.error||"Failed to fetch pool detail."};let f=h.data,y=f.totalLiquidity?.value,b=f.volume24h?.value,w=f.feeTier,v=typeof w=="number"?w/1e4:void 0,k=typeof b=="number"&&typeof v=="number"?b*v/100:void 0,A=typeof k=="number"&&typeof y=="number"&&y>0?k/y*Ur:void 0,x=typeof b=="number"&&typeof y=="number"&&y>0?b/y:void 0,S={address:f.address,pair:f.token0?.symbol&&f.token1?.symbol?`${f.token0.symbol}/${f.token1.symbol}`:void 0,feeTierBps:w,feeTierPercent:v,tvlUsd:y,volume24hUsd:b,fees24hUsd:k,volumeToTvlRatio:x,aprPercent:typeof A=="number"?A*100:void 0,chain:n,token0:f.token0?{symbol:f.token0.symbol}:void 0,token1:f.token1?{symbol:f.token1.symbol}:void 0},O=o?void 0:`User only provided ${r}; 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:S,autoPickedReason:O,aprUnavailableReason:y?"Volume data unavailable":"TVL is zero or unavailable"};let C=Ki(a,A);return{_instructions:le+"Present the yield estimate naturally in the user's language. "+(i?"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. ')+(O?'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. "+ce+ue+X+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:S,estimate:C,depositMode:i?"user-specified":"default-1000-example",autoPickedReason:O,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 a=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return s?this.sym(a,o)&&this.sym(c,s)||this.sym(a,s)&&this.sym(c,o):this.sym(a,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 Ht=class extends T{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: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche.';category="blockchain-data";noSuggestions=!0;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. 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:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new Be(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(a=>typeof a=="string"&&a.trim().length>0).map(a=>a.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=M(e.chain,t);if(!this.service.isSupported(r))return{_instructions:"CoinPool does not serve this chain. Mention the supported chains nicely.",unsupportedChains:[r],supportedChains:this.service.listSupportedChains()};let o=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,s=await this.service.getPairs({chain:r,tokens:n});if(s.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:r,pairs:[],count:0};let i=[...s].sort((a,c)=>(c.apr??-1/0)-(a.apr??-1/0)).slice(0,o);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. '+X+"Do NOT mention tool or API names.",tokens:n,chain:r,count:i.length,pairs:i}}};var Nr="https://coinpool.app/my-liquidity",Gt=class extends T{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";noSuggestions=!0;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: ${Nr} \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:Nr,action:t}}};var ji=["tvl","volume","apr","fee","liquidity"],Yt=class extends T{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";noSuggestions=!0;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 Q(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(g=>typeof g=="string"&&g.trim().length>0).map(g=>g.trim().toUpperCase()),r=(Array.isArray(e.chains)?e.chains:[]).filter(g=>typeof g=="string"&&g.trim().length>0),o=r.filter(g=>!this.service.isSupported(g)),s=r.filter(g=>this.service.isSupported(g)).map(g=>this.service.resolveChain(g));if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new z(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"],a=typeof e.sortBy=="string"&&ji.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(E),supportedChains:this.service.listSupportedChains().map(E),pools:[],count:0};let p=(await Promise.allSettled(i.map(g=>this.service.searchPools({tokens:n,chain:g,sortBy:a,filters:c})))).flatMap(g=>g.status==="fulfilled"?g.value:[]);a==="apr"?p.sort((g,h)=>(h.apr??0)-(g.apr??0)):a==="tvl"?p.sort((g,h)=>h.tvl-g.tvl):a==="volume"?p.sort((g,h)=>h.volume24hUsd-g.volume24hUsd):a==="fee"&&p.sort((g,h)=>g.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,f)=>h.status==="fulfilled"?h.value.map(y=>({...y,chain:E(i[f])})):[]),m.sort((h,f)=>(f.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(E),unsupportedChains:o.map(E),sortBy:a,filters:c,count:p.length,pools:p.map(g=>this.formatPool(g)),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:de(e)}}};function de(l){return`https://app.uniswap.org/explore/pools/${_n[l.chain]||l.chain}/${l.poolAddress}`}var _n={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var Kt=class extends T{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";noSuggestions=!0;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 Q(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 z(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:de(u)}))}}};var jt=class extends T{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";noSuggestions=!0;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 Q(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 z(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,a]=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,'+(a.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:a,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:de(i)}}:{error:`No pool found at ${n} on ${E(s)}.`}}};var zt=class extends T{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";noSuggestions=!0;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 Q(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 z(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:de(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 Qt=class extends T{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";noSuggestions=!0;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 Q(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 z(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=_n[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:de(c.pool)}}}};var Xt=class extends T{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";noSuggestions=!0;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 Q(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 z(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,a=await this.service.getCoinPoolPairs({chain:s,tokens:n});if(a.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=[...a].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 Jt=class extends T{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";noSuggestions=!0;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 Q(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="",g=[];if(this.service.isSupported(p)){m=this.service.resolveChain(p);try{g=(await this.service.searchPools({tokens:[],chain:m,sortBy:"tvl"})).slice(0,5)}catch{g=[]}}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:
177
177
  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.
178
- `+(h.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':"")+(h.length>0?"3) ":"2) ")+this.linkInstruction(d)+`
179
- Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:p||void 0,addLiquidityLink:d,count:h.length,pools:h.map(g=>this.formatPool(g))}}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;let a=s?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(a))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:[N(a)],supportedChains:this.service.listSupportedChains().map(N)};let i=this.service.resolveChain(a);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:i});return d?this.poolsResult([d],i,!0):{error:`No pool found at ${n} on ${N(i)}.`}}if(r.length>0){let d=await this.service.searchPools({tokens:r,chain:i,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 ${N(i)}. Ask the user to check the token symbols, or try a different pair.`};let m=r.length===2?await this.fetchCoinPoolPairs(i,r):[];return this.poolsResult(d.slice(0,8),i,!0,m)}let l=await this.service.searchPools({tokens:[],chain:i,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:i,needsSelection:!0,addLiquidityLink:u,count:l.length,pools:l.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(a=>this.formatPool(a)),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:re(e)}}};function be(c){if(typeof c=="number")return Number.isFinite(c)&&c>0?{kind:"token",value:c,raw:String(c)}:null;if(typeof c!="string")return null;let e=c.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 er(c,e){switch(c.kind){case"token":return{ok:!0,amount:c.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*c.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:c.usd/e.usdPrice}}}var la={send:30000n,swap:1000000n},ca={"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"]};async function ua(c){let e=c.toLowerCase(),n=[Tt(c),...ca[e]??[]].filter(r=>!!r);for(let r of n)try{let o=await Ae(r,"eth_gasPrice",[]),s=BigInt(o);if(s>0n)return s}catch{}return 0n}async function Ot(c,e){let t=await ua(c);return t<=0n?0n:la[e]*t}function Bt(c,e,t){if(e<=0n)return c;let n=X(t)?.native.decimals;if(n===void 0)return c;let r=Number(e)/10**n;return!Number.isFinite(r)||r<=0?c:Math.max(0,c-r)}var le=class extends T{kind="action";category="wallet-action";noSuggestions=!0;userInputFields=[];moralis;constructor(e){super(),e!==void 0&&(this.moralis=new R(e))}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=B(e.trim()),s=i=>o?(i.token_address??"").toLowerCase()===r:(i.symbol??"").toLowerCase()===r;if(n){let i=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(i.success&&i.data?.result?.length){let l=i.data.result.find(s);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name,decimals:typeof l.decimals=="number"?l.decimals:void 0}}}let a=await this.moralis.searchTokensByKey({key:e,chain:t});if(a.success&&a.data?.length){let l=a.data.find(s)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name,decimals:typeof l.decimals=="number"?l.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,a=this.parseDecimals(r),i=typeof n=="string"&&n.trim()?n.trim():void 0,l=this.normaliseAddress(t),u=typeof t=="string"&&t.trim()?t.trim():void 0,d=l??i??u;if(!d)return{token:void 0};let m=await this.resolveContractAddress(d,o,s);return m?{token:{address:m.address,symbol:i??m.symbol,name:m.name,decimals:a??m.decimals}}:l?{token:{address:l,symbol:i,decimals:a}}:{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 kn(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return B(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,a=be(t);if(!a)return null;let i=e.symbol??"the token",l=n.toLowerCase()==="native",u=!!s&&l&&!!r;if(a.kind==="token")return{amount:this.toPlainDecimal(a.value)};let d=await this.readTokenBalanceAndPrice(n,r,o),m=d?.balance;u&&d?.balance!==void 0&&(m=await this.computeNativeSpendable(r,s,d.balance));let p=er(a,{balance:m,usdPrice:d?.usdPrice});return p.ok?{amount:this.toPlainDecimal(p.amount)}:p.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${i} balance to work out ${a.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 ${i} 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 ${i} to work out ${a.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 ${i} 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 Ot(e,t);return Bt(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:!0,excludeUnverifiedContracts:!0}),o=r.success?r.data?.result??[]:[],s=e.toLowerCase()==="native",a=e.toLowerCase(),i=o.find(u=>s?u.native_token===!0:(u.token_address??"").toLowerCase()===a);if(!i)return;let l=i.balance_formatted!=null?Number(i.balance_formatted):void 0;return{balance:Number.isFinite(l)?l:void 0,usdPrice:typeof i.usd_price=="number"&&i.usd_price>0?i.usd_price:void 0,balanceFormatted:i.balance_formatted,symbol:i.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),[a,i=""]=r.split("."),l=a+i,u;if(s>=0){let d=a.length+s;u=d>=l.length?l.padEnd(d,"0"):`${l.slice(0,d)}.${l.slice(d)}`}else u=`0.${"0".repeat(-s-a.length)}${l}`;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=He(e.chain,t);if(r){let f=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${f} on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to ${f} on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can ${f} 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)return{error:"missing_chain",_instructions:'No chain is set. Pass the hex chain id explicitly (e.g. "0x1") or set userContext.chain before calling.'};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 a={action:this.actionType,chainId:o,walletAddress:n.address,parameters:s},i={component:this.component,props:a},l=a.parameters,u=f=>{let y=l[f];return y!=null&&y!==""},d=this.userInputFields.filter(f=>!(Array.isArray(f.key)?f.key:[f.key]).some(u)).map(f=>f.label),m=this.userInputFields.map(f=>{let k=(Array.isArray(f.key)?f.key:[f.key]).find(u);return k?`${f.label}: ${l[k]}`:null}).filter(f=>f!=null),p=this.actionType.replace(/_/g," "),h='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.',g=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(", ")}. `+(m.length>0?`Already provided: ${m.join("; ")}. `:"")+`Do NOT say "review and confirm" yet \u2014 there are still missing details to collect. ${h} Wait for the user to provide the missing details before proceeding.`:`The ${p} has all required details. In the user's language, ask the user to review and confirm to complete the ${p}. `+(m.length>0?`Details provided: ${m.join("; ")}. `:"")+`${h} Wait for the user to confirm or edit before proceeding.`;return{ui:i,action:this.actionType,chainId:o,parameters:a.parameters,_instructions:g}}};var Mt=class extends le{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=ko(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. 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) 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 l=s?.symbol||"the native coin";return{error:"no_native_balance",_instructions:`The user wants to send ${l} but their wallet holds 0 ${l} on this chain. Tell them, in their language, that they do not have any ${l} to send and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}if(e.to_address!=null){let l=this.normaliseAddress(e.to_address);l?n.to_address=l:typeof e.to_address=="string"&&e.to_address.trim()&&(n.to_address=e.to_address.trim())}let a=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:r,walletAddress:o,gasKind:"send"});if(a&&"error"in a)return a;a&&(n.amount=a.amount);let i=await this.resolveNativeSpendableFormatted(r,o,"send");return i!==void 0&&(n.spendable=i),n}};var qt=class extends le{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. Put the localized verb and the "to" preposition directly in the text. English example: "send {amount} {symbol} to {to}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to}". Japanese example: "{to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to} 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 m=await this.moralis.getWalletTokenBalances({address:d,chain:u,excludeSpam:!0,excludeUnverifiedContracts:!0}),h=(m.success?m.data?.result??[]:[]).filter(w=>w.symbol&&(w.native_token||w.token_address)).sort((w,b)=>(b.usd_value??0)-(w.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,f=this.normaliseAmount(e.amount),y=typeof e.send_prompt_template=="string"?e.send_prompt_template:"";return{actionButtons:h.map(w=>{let b=w.symbol,v=w.balance_formatted?this.cleanAmountString(w.balance_formatted):"",A=w.name?w.name:"",S=w.usd_value?`($${w.usd_value.toFixed(2)})`:"";return{label:`${A}:${v} ${b} ${S}`.trim(),prompt:this.buildSendPrompt(y,b,f,g)}}),_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,a=await this.findOwnedTokenForSend(e,o,s);if(a&&"error"in a)return a;let i=a?.token,l={};if(i?.address&&(l.contract_address=i.address),i?.symbol&&(l.token_symbol=i.symbol),i?.decimals!==void 0&&(l.decimals=String(i.decimals)),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?l.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(l.to_address=e.to_address.trim())}if(i?.address){let u=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:i.address,symbol:i.symbol,chain:o,walletAddress:s});if(u&&"error"in u)return u;u&&(l.amount=u.amount)}else{let u=this.normaliseAmount(e.amount);u&&(l.amount=u)}return l}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 p=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:n});return"error"in p?{error:"token_not_found",symbol:p.key,_instructions:`Could not resolve token "${p.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:p.token}}let a=s.toLowerCase(),i=r!=null,l=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!0,excludeUnverifiedContracts:!0}),d=(l.success?l.data?.result??[]:[]).find(p=>i?(p.token_address??"").toLowerCase()===a:(p.symbol??"").toLowerCase()===a);if(d&&d.balance&&!/^0*$/.test(d.balance.trim())){let p=this.parseDecimals(e.decimals);return{token:{address:d.token_address,symbol:d.symbol??o,name:d.name,decimals:p??(typeof d.decimals=="number"?d.decimals:void 0)}}}let m=d?.symbol??o??s;return{error:"no_balance",symbol:m,_instructions:`The user does not hold any ${m} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${m} 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){let s=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,n??"");return r?s=s.replace(/\{to\}/g,r):s=s.replace(/\s*\S+\s*\{to\}/g,"").replace(/\{to\}\s*\S+\s*/g,"").replace(/\{to\}/g,""),s.replace(/\s+/g," ").trim()}};var Ft=class extends le{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),a={};if(o?.address&&(a.contract_address=o.address),s&&(a.spender_address=s),o?.symbol&&(a.token_symbol=o.symbol),o?.decimals!==void 0&&(a.decimals=String(o.decimals)),typeof e.amount=="string"&&e.amount.trim()){let i=e.amount.trim(),l=parseFloat(i);Number.isFinite(l)&&l>=0&&(a.amount=i)}else typeof e.amount=="number"&&Number.isFinite(e.amount)&&e.amount>=0&&(a.amount=String(e.amount));return a}};function da(c){return Dn(String(c))??"0"}function Dn(c){let e=c.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,a=n.length+o,i;return a<=0?i=`0.${"0".repeat(-a)}${s}`:a>=s.length?i=s+"0".repeat(a-s.length):i=`${s.slice(0,a)}.${s.slice(a)}`,i=i.replace(/^0+(?=\d)/,""),i.includes(".")&&(i=i.replace(/0+$/,"").replace(/\.$/,"")),(i===""||i==="-")&&(i="0"),i==="0"?"0":t+i}function co(c){let e=Dn(c);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function ma(c,e){let t=c<0n,n=(t?-c:c).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 $t(c){if(typeof c=="number")return Number.isFinite(c)&&c>0?da(c):null;if(typeof c!="string")return null;let e=c.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Dn(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function Wt(c,e){let t=Dn(c);if(t===null||e<0)return c;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)}`,a=s.includes(".")?s.replace(/0+$/,"").replace(/\.$/,""):s;return n?`-${a}`:a}function Vt(c,e,t,n){let r=co(c);if(!r||t<=0n||n<0)return c;let o=r.mant*e*10n**BigInt(n)/(t*10n**BigInt(r.frac));return ma(o,n)}function On(c,e){let t=co(c),n=co(e);if(!t||!n){let a=Number(c),i=Number(e);return a<i?-1:a>i?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 Ht=class extends T{name="open-buy-token-form";kind="action";category="wallet-action";noSuggestions=!0;moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new R(e),this.pantograph=new te({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=He(e.chain,t);return r?{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.`}:this.requireChain(e,t)?this.buildResult(e,t):{error:"missing_chain",_instructions:'No chain is set. Pass the hex chain id explicitly (e.g. "0x1") or set userContext.chain before calling.'}}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 a=await this.resolveSide(e.contract_address,n,o,s,"dest"),i=a.address,l=a.symbol??n,u=a.decimals,d=await this.resolveSide(e.pay_with_address,e.pay_with_symbol,o,s,"pay"),m=d.address,p=d.symbol,h=d.decimals,g=await this.resolveBuyAmountSpec(e.buy_amount,i,o,l),f=m?await this.resolvePayAmountSpec(e.pay_with_amount,m,o,s,p,h??(m==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),y=be(e.pay_with_amount),k=!!y&&y.kind!=="token",w=null;if(this.dbg("resolved sides",{dest:{destContract:i,destSymbol:l,destDecimals:u},pay:{payAddr:m,paySymbol:p,payDecimals:h},buyAmount:g,payAmount:f}),!i)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${l||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(!m&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:l,destContract:i,buyAmount:g,payAmount:f});if(!m)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${l}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(g&&!f){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:g,destSymbol:l,paySymbol:p});let b=await this.derivePayAmountFromBuy({chain:o,buyAmount:g,destContract:i,destSymbol:l,payAddr:m,paySymbol:p});if(!b)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${p??"of the payment token"} equals ${g} ${l} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${p??"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.`};f=b,w=g,k=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:f,derivedFromBuy:w})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:m,paySymbol:p,payAmount:f});let b=await this.checkPayBalance({args:e,userContext:t,chain:o,destSymbol:l,destContract:i,payAddr:m,paySymbol:p,payAmount:f,buyAmount:g,derivedFromBuy:w,amountSizedToBalance:k});if(b)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:b.error,hasButtons:Array.isArray(b.actionButtons)}),b;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!g&&!f&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let b=await this.buildAmountPicker({userContext:t,chain:o,destSymbol:l,payAddr:m,paySymbol:p,buyWithTemplate:typeof e.buy_with_prompt_template=="string"?e.buy_with_prompt_template:""});if(b)return this.dbg("\u2192 Branch 1.5: amount picker returned"),b;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(f&&(h!==void 0||m==="native")){this.dbg("Branch 1.75: building confirm tx");let b=await this.buildConfirmTx({userContext:t,chain:o,destContract:i,destSymbol:l,destDecimals:u,payAddr:m,paySymbol:p,payDecimals:h,payAmount:f});return b&&"ui"in b?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),b):b&&"quoteError"in b?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:b.quoteError}),{error:"quote_failed",quoteError:b.quoteError,_instructions:`Could not quote buying ${l} with ${p??"the selected token"}. The swap provider reported: "${b.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 ${l} with ${p??"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 ${p??"of the payment token"} they want to spend to buy ${l}. 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 B(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():"",a=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",i=s.length>0,l=a.length>0;if(i===l)return;let u=i?s:a,d=u.match(/[0-9]*\.?[0-9]+/)?.[0];if(!d)return;let m=this.nearestSymbolSide(n,d,r,o);m&&(m==="pay"&&i?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:u,buySym:r,paySym:o}),e.pay_with_amount=u,e.buy_amount=""):m==="buy"&&l&&(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 a=n.toLowerCase(),i=o.toLowerCase(),l=s.toLowerCase(),u=i==="native"||l==="native",d=[];if(o&&i!=="native"&&d.push(i),l&&l!=="native"&&d.push(l),u){d.push("native");let p=this.requireChain(e,t)??void 0,h=p?X(p)?.native.symbol:void 0;h&&d.push(h.toLowerCase())}d.some(p=>B(p)?a.includes(p):this.indexOfToken(a,p)>=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 a=typeof e[s]=="string"?e[s].trim():"";if(!a)return;let i=a.match(/[0-9]*\.?[0-9]+/)?.[0];if(i===void 0)return;let l=parseFloat(i);Number.isFinite(l)&&(r.some(u=>u===l)||(this.dbg(`dropInventedAmounts: clearing invented ${s}`,{val:a}),e[s]=""))};o("buy_amount"),o("pay_with_amount")}nearestSymbolSide(e,t,n,r){let o=e.toLowerCase(),s=o.indexOf(t.toLowerCase()),a=this.indexOfToken(o,n.toLowerCase()),i=this.indexOfToken(o,r.toLowerCase());if(s<0||a<0||i<0)return null;let l=(m,p)=>Math.max(0,m-(s+t.length),s-(m+p)),u=l(a,n.length),d=l(i,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=B(e.trim()),s=i=>o?(i.token_address??"").toLowerCase()===r:(i.symbol??"").toLowerCase()===r;if(n){let i=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(i.success&&i.data?.result?.length){let l=i.data.result.find(s);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name,decimals:typeof l.decimals=="number"?l.decimals:void 0}}}let a=await this.moralis.searchTokensByKey({key:e,chain:t});if(a.success&&a.data?.length){let l=a.data.find(s)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name,decimals:typeof l.decimals=="number"?l.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let s=typeof e=="string"?e.trim():"",a=typeof t=="string"?t.trim():"";if(s.toLowerCase()==="native"||a.toLowerCase()==="native")return{address:"native",symbol:a||void 0};let i=this.normaliseAddress(e),l=a||void 0,u=p=>p.toLowerCase()===M?"native":p,d=i??l??(s||void 0);if(!d)return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:a,chain:n,resolved:"none"}),{address:null,symbol:l};let m=await this.resolveContractAddress(d,n,r);return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:a,chain:n,key:d,lookup:m}),m?{address:u(m.address),symbol:l??m.symbol,decimals:m.decimals}:i?{address:u(i),symbol:l}:{address:null,symbol:l}}async buildConfirmTx(e){let{userContext:t,chain:n,destContract:r,destSymbol:o,destDecimals:s,payAddr:a,paySymbol:i,payDecimals:l,payAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let m=X(n),p=Number.parseInt(n,16);if(!m||!Number.isFinite(p))return null;let h=a==="native",g=h?m.native.decimals??18:l;if(g===void 0)return null;let f=this.toRawAmount(u,g);if(!f)return null;let y=h?M:a,k=r==="native"?M:r,w;try{w=await(await ye.getServiceByProvider("debridge")).getQuote({srcChainId:p,srcTokenAddress:y,srcTokenAmount:f,dstChainId:p,dstTokenAddress:k,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(P){return{quoteError:P instanceof Error?P.message:String(P)}}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 b=w.tx;if(!b.to||typeof b.data!="string")return null;let v={chainId:n,to:b.to,data:b.data,value:b.value??"0",from:d},A=this.extractOutRaw(w),S=A&&s!==void 0?this.trimAmount(Number(A)/10**s):void 0,C;h||(C=await this.buildApproveTx({chain:n,walletAddress:d,payAddr:a,payDec:g,rawAmount:f,quote:w}));let x={component:"BuyTokenConfirmTx",props:{chain:{hexId:n,name:m.name},payToken:{address:h?"native":a,symbol:i,decimals:g,amount:u,rawAmount:f},buyToken:{address:r,symbol:o,decimals:s,amount:S,rawAmount:A},estimatedOut:S,estimatedOutRaw:A,provider:w.provider,swapTx:v,approveTx:C}},L=S?` They will receive about ${S} ${o}.`:"";return{ui:x,_instructions:`A confirmation panel has been opened for buying ${o} with ${u} ${i??"the selected token"}.${L} 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. 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,a]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:s,payPrice:a}),!s||!a)return null;let i=Number(n);if(!Number.isFinite(i)||i<=0)return null;let l=1.02,u=i*s/a;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*l)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?M: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 a=be(e);if(!a)return null;let i=u=>s===void 0?u:Wt(u,s);if(a.kind==="token")return i($t(e)??this.toPlainDecimal(a.value));if(a.kind==="percent"){if(!r)return null;let u=await this.readPayBalance(r,t,n);if(this.dbg("resolvePayAmountSpec: percent",{percent:a.percent,paySymbol:o,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??s??18;return a.percent>=100?this.cleanAmountString(u.balanceFormatted):Vt(u.balanceFormatted,BigInt(Math.round(a.percent*1e6)),100000000n,d)}let l=await this.getUsdPrice(t,n);return this.dbg("resolvePayAmountSpec: usd",{usd:a.usd,paySymbol:o,price:l}),l?i(this.trimAmount(a.usd/l)):null}async resolveBuyAmountSpec(e,t,n,r){let o=be(e);if(!o)return null;if(o.kind==="token")return $t(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:a}=e;try{let l=await(await ye.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:s,tokenDecimals:o,quoteData:a});if(!l.isNeeded)return;let u=l.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=l.contractAddress;if(!d)return;let m=Ge({abi:Ln,functionName:"approve",args:[d,BigInt(s)]});return{chainId:t,to:r,data:m,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 a=BigInt(r||"0")*10n**BigInt(t)+BigInt(s||"0");return a<=0n?null:a.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,a=this.moralis,i=n.walletAddress,l=await a.getWalletTokenBalances({address:i,chain:s,excludeSpam:!0,excludeUnverifiedContracts:!0}),u=l.success?l.data?.result??[]:[],d=o?.toLowerCase(),m=r.trim().toLowerCase(),p=u.filter(k=>!k.symbol||m&&k.symbol.toLowerCase()===m?!1:k.native_token?d!=="native":!(!k.token_address||d&&k.token_address.toLowerCase()===d)).sort((k,w)=>(w.usd_value??0)-(k.usd_value??0)).slice(0,8);if(p.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 h=e.buyAmount??this.normaliseAmount(t.buy_amount),g=e.payAmount??this.normaliseAmount(t.pay_with_amount),f=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:p.map(k=>{let w=k.symbol,b=k.name?.trim()||w,v=k.balance_formatted?`${this.cleanAmountString(k.balance_formatted)} `:"",A=typeof k.usd_value=="number"&&k.usd_value>0?` ($${k.usd_value.toFixed(2)})`:"",S=`${b}: ${v}${w}${A}`,C=h?this.buildBuyWithPrompt(f,r,w,h,null):this.buildBuyWithPrompt(f,r,w,null,g);return{label:S,prompt:C}}),_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:a,payAmount:i,buyAmount:l,derivedFromBuy:u}=e,d=n.walletAddress,m=await this.readPayBalance(d,a,r),p=e.paySymbol??m?.symbol??"the selected token";if(!m){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:p});let k=await this.buildPayWithPicker({args:t,userContext:n,destSymbol:o,destContract:s,buyAmount:l,payAmount:i});return"actionButtons"in k?{error:"no_pay_balance",actionButtons:k.actionButtons,_instructions:`The user wanted to spend ${p} to buy ${o}, but their wallet holds no ${p} 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 ${p} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${p} 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.`}:k}if(!i||e.amountSizedToBalance)return null;let h=m.decimals!==void 0?Wt(i,m.decimals):i;if(On(h,m.balanceFormatted)<=0)return null;let g=this.cleanAmountString(m.balanceFormatted),f=this.percentSpendButtons({balanceFormatted:m.balanceFormatted,balanceNum:m.balanceNum,decimals:m.decimals,paySymbol:p,destSymbol:o,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:""}),y=u?`Buying ${u} ${o} needs about ${i} ${p}, but they only have ${g} ${p} 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 ${i} ${p}, which is more than their balance of ${g} ${p}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${i} ${p} to buy ${o}, but they only have ${g} ${p} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${i} ${p} exceeds their balance of ${g} ${p}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:f,_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:!0,excludeUnverifiedContracts:!0}),o=r.success?r.data?.result??[]:[];this.dbg("readPayBalance",{payAddr:t,chain:n,ok:r.success,count:o.length,held:o.map(l=>({sym:l.symbol,addr:l.token_address,bal:l.balance_formatted}))});let s=t.toLowerCase(),a=o.find(l=>s==="native"?l.native_token===!0:l.token_address?.toLowerCase()===s);if(!a?.balance_formatted)return this.dbg("readPayBalance: pay token NOT held \u2192 null",{payAddr:t}),null;let i=Number(a.balance_formatted);if(!Number.isFinite(i)||i<=0)return this.dbg("readPayBalance: zero/invalid balance \u2192 null",{payAddr:t,balance:a.balance_formatted}),null;if(s==="native"&&n){let l=await Ot(n,"swap"),u=Bt(i,l,n);if(this.dbg("readPayBalance: native spendable",{balanceNum:i,spendable:u}),u<=0)return this.dbg("readPayBalance: native spendable \u2264 0 \u2192 null",{balanceNum:i}),null;let d=this.trimAmount(u),m=typeof a.decimals=="number"?a.decimals:18;return{balanceFormatted:d,balanceNum:u,symbol:a.symbol,decimals:m}}return this.dbg("readPayBalance: held",{payAddr:t,balance:a.balance_formatted,symbol:a.symbol}),{balanceFormatted:a.balance_formatted,balanceNum:i,symbol:a.symbol,decimals:typeof a.decimals=="number"?a.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,paySymbol:r,destSymbol:o,buyWithTemplate:s}=e,a=n??18;return[25,50,75,100].map(l=>{let u=Vt(this.cleanAmountString(t),BigInt(l),100n,a);return{label:`${l}%`,prompt:this.buildBuyWithPrompt(s,o,r,null,u)}})}async buildAmountPicker(e){let{userContext:t,chain:n,destSymbol:r,payAddr:o,buyWithTemplate:s}=e,a=t.walletAddress,i=await this.readPayBalance(a,o,n),l=e.paySymbol??i?.symbol;if(!i||!l)return null;let u=this.percentSpendButtons({balanceFormatted:i.balanceFormatted,balanceNum:i.balanceNum,decimals:i.decimals,paySymbol:l,destSymbol:r,buyWithTemplate:s}),d=this.cleanAmountString(i.balanceFormatted);return{actionButtons:u,_instructions:`The user's spendable balance is ${d} ${l}. 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 ${l} balance (e.g., 'B\u1EA1n mu\u1ED1n mua ${r} b\u1EB1ng ${l}, hi\u1EC7n c\xF3 ${d} ${l} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to buy ${r} with ${l}; you have ${d} ${l} 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),[a,i=""]=r.split("."),l=a+i,u;if(s>=0){let d=a.length+s;u=d>=l.length?l.padEnd(d,"0"):`${l.slice(0,d)}.${l.slice(d)}`}else u=`0.${"0".repeat(-s-a.length)}${l}`;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}),a=s.success?s.data??[]:[];if(a.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 i=a.filter(p=>p.symbol),l=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",u=i.map(p=>{let h=p.symbol;return{label:h,prompt:this.buildBuyPrompt(l,h)}}),m=i.map((p,h)=>{let g=p.name?.trim()||p.symbol,f=p.symbol,y=typeof p.usdPrice=="number"&&p.usdPrice>0?`$${this.formatPrice(p.usdPrice)}`:"N/A",k=p.pricePercentChange?.["24h"],w=typeof k=="number"&&Number.isFinite(k)?` (${k>0?"+":k<0?"-":""}${this.formatPercent(Math.abs(k))}%)`:"";return`${h+1}. ${g} (${f}) \u2014 ${y}${w}`}).join(`
178
+ `+(g.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':"")+(g.length>0?"3) ":"2) ")+this.linkInstruction(d)+`
179
+ Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:m||void 0,addLiquidityLink:d,count:g.length,pools:g.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 z(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:[E(i)],supportedChains:this.service.listSupportedChains().map(E)};let a=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:a});return d?this.poolsResult([d],a,!0):{error:`No pool found at ${n} on ${E(a)}.`}}if(r.length>0){let d=await this.service.searchPools({tokens:r,chain:a,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 ${E(a)}. Ask the user to check the token symbols, or try a different pair.`};let p=r.length===2?await this.fetchCoinPoolPairs(a,r):[];return this.poolsResult(d.slice(0,8),a,!0,p)}let c=await this.service.searchPools({tokens:[],chain:a,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:a,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:de(e)}}};function Ce(l){if(typeof l=="number")return Number.isFinite(l)&&l>0?{kind:"token",value:l,raw:String(l)}:null;if(typeof l!="string")return null;let e=l.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 Ir(l,e){switch(l.kind){case"token":return{ok:!0,amount:l.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*l.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:l.usd/e.usdPrice}}}var zi={send:30000n,swap:1000000n},Qi={"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"]};async function Xi(l){let e=l.toLowerCase(),n=[Mt(l),...Qi[e]??[]].filter(r=>!!r);for(let r of n)try{let o=await Ne(r,"eth_gasPrice",[]),s=BigInt(o);if(s>0n)return s}catch{}return 0n}async function Zt(l,e){let t=await Xi(l);return t<=0n?0n:zi[e]*t}function en(l,e,t){if(e<=0n)return l;let n=J(t)?.native.decimals;if(n===void 0)return l;let r=Number(e)/10**n;return!Number.isFinite(r)||r<=0?l:Math.max(0,l-r)}var fe=class extends T{kind="action";category="wallet-action";noSuggestions=!0;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=F(e.trim()),s=a=>o?(a.token_address??"").toLowerCase()===r:(a.symbol??"").toLowerCase()===r;if(n){let a=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let c=a.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),a=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??a??u;if(!d)return{token:void 0};let p=await this.resolveContractAddress(d,o,s);return p?{token:{address:p.address,symbol:a??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:a,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 ie(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return F(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=Ce(t);if(!i)return null;let a=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=Ir(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 ${a} 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 ${a} 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 ${a} 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 ${a} 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 Zt(e,t);return en(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:!0,excludeUnverifiedContracts:!0}),o=r.success?r.data?.result??[]:[],s=e.toLowerCase()==="native",i=e.toLowerCase(),a=o.find(u=>s?u.native_token===!0:(u.token_address??"").toLowerCase()===i);if(!a)return;let c=a.balance_formatted!=null?Number(a.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof a.usd_price=="number"&&a.usd_price>0?a.usd_price:void 0,balanceFormatted:a.balance_formatted,symbol:a.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,a=""]=r.split("."),c=i+a,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=rt(e.chain,t);if(r){let f=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${f} on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to ${f} on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can ${f} 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 f=typeof t?.query=="string"?t.query:void 0;return st(this.actionType.replace(/_/g," "),f)}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={action:this.actionType,chainId:o,walletAddress:n.address,parameters:s},a={component:this.component,props:i},c=i.parameters,u=f=>{let y=c[f];return y!=null&&y!==""},d=this.userInputFields.filter(f=>!(Array.isArray(f.key)?f.key:[f.key]).some(u)).map(f=>f.label),p=this.userInputFields.map(f=>{let b=(Array.isArray(f.key)?f.key:[f.key]).find(u);return b?`${f.label}: ${c[b]}`:null}).filter(f=>f!=null),m=this.actionType.replace(/_/g," "),g='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.',h=d.length>0?`The ${m} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${d.join(", ")}. `+(p.length>0?`Already provided: ${p.join("; ")}. `:"")+`Do NOT say "review and confirm" yet \u2014 there are still missing details to collect. ${g} Wait for the user to provide the missing details before proceeding.`:`The ${m} has all required details. In the user's language, ask the user to review and confirm to complete the ${m}. `+(p.length>0?`Details provided: ${p.join("; ")}. `:"")+`${g} Wait for the user to confirm or edit before proceeding.`;return{ui:a,action:this.actionType,chainId:o,parameters:i.parameters,_instructions:h}}};var tn=class extends fe{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=zo(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. 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) 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 c=s?.symbol||"the native coin";return{error:"no_native_balance",_instructions:`The user wants to send ${c} but their wallet holds 0 ${c} on this chain. Tell them, in their language, that they do not have any ${c} to send and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}if(e.to_address!=null){let c=this.normaliseAddress(e.to_address);c?n.to_address=c:typeof e.to_address=="string"&&e.to_address.trim()&&(n.to_address=e.to_address.trim())}let i=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:r,walletAddress:o,gasKind:"send"});if(i&&"error"in i)return i;i&&(n.amount=i.amount);let a=await this.resolveNativeSpendableFormatted(r,o,"send");return a!==void 0&&(n.spendable=a),n}};var nn=class extends fe{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. Put the localized verb and the "to" preposition directly in the text. English example: "send {amount} {symbol} to {to}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to}". Japanese example: "{to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to} 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:!0,excludeUnverifiedContracts:!0}),g=(p.success?p.data?.result??[]:[]).filter(w=>w.symbol&&(w.native_token||w.token_address)).sort((w,v)=>(v.usd_value??0)-(w.usd_value??0)).slice(0,8);if(g.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,f=this.normaliseAmount(e.amount),y=typeof e.send_prompt_template=="string"?e.send_prompt_template:"";return{actionButtons:g.map(w=>{let v=w.symbol,k=w.balance_formatted?this.cleanAmountString(w.balance_formatted):"",A=w.name?w.name:"",x=w.usd_value?`($${w.usd_value.toFixed(2)})`:"";return{label:`${A}:${k} ${v} ${x}`.trim(),prompt:this.buildSendPrompt(y,v,f,h)}}),_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 a=i?.token,c={};if(a?.address&&(c.contract_address=a.address),a?.symbol&&(c.token_symbol=a.symbol),a?.decimals!==void 0&&(c.decimals=String(a.decimals)),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(a?.address){let u=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:a.address,symbol:a.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(),a=r!=null,c=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!0,excludeUnverifiedContracts:!0}),d=(c.success?c.data?.result??[]:[]).find(m=>a?(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)}}}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){let s=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,n??"");return r?s=s.replace(/\{to\}/g,r):s=s.replace(/\s*\S+\s*\{to\}/g,"").replace(/\{to\}\s*\S+\s*/g,"").replace(/\{to\}/g,""),s.replace(/\s+/g," ").trim()}};var on=class extends fe{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 a=e.amount.trim(),c=parseFloat(a);Number.isFinite(c)&&c>=0&&(i.amount=a)}else typeof e.amount=="number"&&Number.isFinite(e.amount)&&e.amount>=0&&(i.amount=String(e.amount));return i}};function Ji(l){return oo(String(l))??"0"}function oo(l){let e=l.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,a;return i<=0?a=`0.${"0".repeat(-i)}${s}`:i>=s.length?a=s+"0".repeat(i-s.length):a=`${s.slice(0,i)}.${s.slice(i)}`,a=a.replace(/^0+(?=\d)/,""),a.includes(".")&&(a=a.replace(/0+$/,"").replace(/\.$/,"")),(a===""||a==="-")&&(a="0"),a==="0"?"0":t+a}function Io(l){let e=oo(l);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function Zi(l,e){let t=l<0n,n=(t?-l:l).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 rn(l){if(typeof l=="number")return Number.isFinite(l)&&l>0?Ji(l):null;if(typeof l!="string")return null;let e=l.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=oo(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function sn(l,e){let t=oo(l);if(t===null||e<0)return l;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 an(l,e,t,n){let r=Io(l);if(!r||t<=0n||n<0)return l;let o=r.mant*e*10n**BigInt(n)/(t*10n**BigInt(r.frac));return Zi(o,n)}function ro(l,e){let t=Io(l),n=Io(e);if(!t||!n){let i=Number(l),a=Number(e);return i<a?-1:i>a?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 ln=class extends T{name="open-buy-token-form";kind="action";category="wallet-action";noSuggestions=!0;moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new D(e),this.pantograph=new ee({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=rt(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 st("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"),a=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,g=d.decimals,h=await this.resolveBuyAmountSpec(e.buy_amount,a,o,c),f=p?await this.resolvePayAmountSpec(e.pay_with_amount,p,o,s,m,g??(p==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),y=Ce(e.pay_with_amount),b=!!y&&y.kind!=="token",w=null;if(this.dbg("resolved sides",{dest:{destContract:a,destSymbol:c,destDecimals:u},pay:{payAddr:p,paySymbol:m,payDecimals:g},buyAmount:h,payAmount:f}),!a)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:a,buyAmount:h,payAmount:f});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&&!f){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:h,destSymbol:c,paySymbol:m});let v=await this.derivePayAmountFromBuy({chain:o,buyAmount:h,destContract:a,destSymbol:c,payAddr:p,paySymbol:m});if(!v)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.`};f=v,w=h,b=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:f,derivedFromBuy:w})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:p,paySymbol:m,payAmount:f});let v=await this.checkPayBalance({args:e,userContext:t,chain:o,destSymbol:c,destContract:a,payAddr:p,paySymbol:m,payAmount:f,buyAmount:h,derivedFromBuy:w,amountSizedToBalance:b});if(v)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:v.error,hasButtons:Array.isArray(v.actionButtons)}),v;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!h&&!f&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let v=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(v)return this.dbg("\u2192 Branch 1.5: amount picker returned"),v;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(f&&(g!==void 0||p==="native")){this.dbg("Branch 1.75: building confirm tx");let v=await this.buildConfirmTx({userContext:t,chain:o,destContract:a,destSymbol:c,destDecimals:u,payAddr:p,paySymbol:m,payDecimals:g,payAmount:f});return v&&"ui"in v?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),v):v&&"quoteError"in v?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:v.quoteError}),{error:"quote_failed",quoteError:v.quoteError,_instructions:`Could not quote buying ${c} with ${m??"the selected token"}. The swap provider reported: "${v.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 F(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():"",a=s.length>0,c=i.length>0;if(a===c)return;let u=a?s:i,d=u.match(/[0-9]*\.?[0-9]+/)?.[0];if(!d)return;let p=this.nearestSymbolSide(n,d,r,o);p&&(p==="pay"&&a?(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(),a=o.toLowerCase(),c=s.toLowerCase(),u=a==="native"||c==="native",d=[];if(o&&a!=="native"&&d.push(a),c&&c!=="native"&&d.push(c),u){d.push("native");let m=this.requireChain(e,t)??void 0,g=m?J(m)?.native.symbol:void 0;g&&d.push(g.toLowerCase())}d.some(m=>F(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 a=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(a===void 0)return;let c=parseFloat(a);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()),a=this.indexOfToken(o,r.toLowerCase());if(s<0||i<0||a<0)return null;let c=(p,m)=>Math.max(0,p-(s+t.length),s-(p+m)),u=c(i,n.length),d=c(a,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=F(e.trim()),s=a=>o?(a.token_address??"").toLowerCase()===r:(a.symbol??"").toLowerCase()===r;if(n){let a=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let c=a.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 a=this.normaliseAddress(e),c=i||void 0,u=m=>m.toLowerCase()===$?"native":m,d=a??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}:a?{address:u(a),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,destContract:r,destSymbol:o,destDecimals:s,payAddr:i,paySymbol:a,payDecimals:c,payAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let p=J(n),m=Number.parseInt(n,16);if(!p||!Number.isFinite(m))return null;let g=i==="native",h=g?p.native.decimals??18:c;if(h===void 0)return null;let f=this.toRawAmount(u,h);if(!f)return null;let y=g?$:i,b=r==="native"?$:r,w;try{w=await(await _e.getServiceByProvider("debridge")).getQuote({srcChainId:m,srcTokenAddress:y,srcTokenAmount:f,dstChainId:m,dstTokenAddress:b,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(_){return{quoteError:_ instanceof Error?_.message:String(_)}}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 v=w.tx;if(!v.to||typeof v.data!="string")return null;let k={chainId:n,to:v.to,data:v.data,value:v.value??"0",from:d},A=this.extractOutRaw(w),x=A&&s!==void 0?this.trimAmount(Number(A)/10**s):void 0,S;g||(S=await this.buildApproveTx({chain:n,walletAddress:d,payAddr:i,payDec:h,rawAmount:f,quote:w}));let C={component:"BuyTokenConfirmTx",props:{chain:{hexId:n,name:p.name},payToken:{address:g?"native":i,symbol:a,decimals:h,amount:u,rawAmount:f},buyToken:{address:r,symbol:o,decimals:s,amount:x,rawAmount:A},estimatedOut:x,estimatedOutRaw:A,provider:w.provider,swapTx:k,approveTx:S}},B=x?` They will receive about ${x} ${o}.`:"";return{ui:C,_instructions:`The purchase of ${o} with ${u} ${a??"the selected token"} is ready for the user to confirm.${B} 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 a=Number(n);if(!Number.isFinite(a)||a<=0)return null;let c=1.02,u=a*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"?$: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=Ce(e);if(!i)return null;let a=u=>s===void 0?u:sn(u,s);if(i.kind==="token")return a(rn(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):an(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?a(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,n,r){let o=Ce(e);if(!o)return null;if(o.kind==="token")return rn(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 _e.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=it({abi:no,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,a=n.walletAddress,c=await i.getWalletTokenBalances({address:a,chain:s,excludeSpam:!0,excludeUnverifiedContracts:!0}),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 g=e.buyAmount??this.normaliseAmount(t.buy_amount),h=e.payAmount??this.normaliseAmount(t.pay_with_amount),f=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:m.map(b=>{let w=b.symbol,v=b.name?.trim()||w,k=b.balance_formatted?`${this.cleanAmountString(b.balance_formatted)} `:"",A=typeof b.usd_value=="number"&&b.usd_value>0?` ($${b.usd_value.toFixed(2)})`:"",x=`${v}: ${k}${w}${A}`,S=g?this.buildBuyWithPrompt(f,r,w,g,null):this.buildBuyWithPrompt(f,r,w,null,h);return{label:x,prompt:S}}),_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:a,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:a});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(!a||e.amountSizedToBalance)return null;let g=p.decimals!==void 0?sn(a,p.decimals):a;if(ro(g,p.balanceFormatted)<=0)return null;let h=this.cleanAmountString(p.balanceFormatted),f=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 ${a} ${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 ${a} ${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 ${a} ${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 ${a} ${m} exceeds their balance of ${h} ${m}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:f,_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:!0,excludeUnverifiedContracts:!0}),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 a=Number(i.balance_formatted);if(!Number.isFinite(a)||a<=0)return this.dbg("readPayBalance: zero/invalid balance \u2192 null",{payAddr:t,balance:i.balance_formatted}),null;if(s==="native"&&n){let c=await Zt(n,"swap"),u=en(a,c,n);if(this.dbg("readPayBalance: native spendable",{balanceNum:a,spendable:u}),u<=0)return this.dbg("readPayBalance: native spendable \u2264 0 \u2192 null",{balanceNum:a}),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:a,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=an(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,a=await this.readPayBalance(i,o,n),c=e.paySymbol??a?.symbol;if(!a||!c)return null;let u=this.percentSpendButtons({balanceFormatted:a.balanceFormatted,balanceNum:a.balanceNum,decimals:a.decimals,paySymbol:c,destSymbol:r,buyWithTemplate:s}),d=this.cleanAmountString(a.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,a=""]=r.split("."),c=i+a,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 a=i.filter(m=>m.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",u=a.map(m=>{let g=m.symbol;return{label:g,prompt:this.buildBuyPrompt(c,g)}}),p=a.map((m,g)=>{let h=m.name?.trim()||m.symbol,f=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`${g+1}. ${h} (${f}) \u2014 ${y}${w}`}).join(`
180
180
  `)+`
181
181
 
182
- Is there any token you want to buy?`;return{actionButtons:u,_instructions:`The trending tokens are on ${n?N(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:
182
+ Is there any token you want to buy?`;return{actionButtons:u,_instructions:`The trending tokens are on ${n?E(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:
183
183
 
184
- ${m}`}}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 Gt=class extends T{name="open-swap-token-form";kind="action";category="wallet-action";noSuggestions=!0;moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new R(e),this.pantograph=new te({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=He(e.chain,t);return r?{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.`}:this.requireChain(e,t)?this.buildResult(e,t):{error:"missing_chain",_instructions:'No chain is set. Pass the hex chain id explicitly (e.g. "0x1") or set userContext.chain before calling.'}}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,a=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:s,walletAddress:a,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: source picker (no source token named)"),await this.buildSourcePicker(e,t);let i=await this.resolveSide(e.from_address,n,s,a,"from"),l=i.address,u=i.symbol??n,d=i.decimals,m=await this.resolveSide(e.to_address,o,s,a,"to"),p=m.address,h=m.symbol??o,g=m.decimals,f=await this.resolveToAmountSpec(e.to_amount,p,s,h),y=l?await this.resolveFromAmountSpec(e.from_amount,l,s,a,u,d??(l==="native"?18:void 0)):this.normaliseAmount(e.from_amount),k=be(e.from_amount),w=!!k&&k.kind!=="token",b=null;if(this.dbg("resolved sides",{from:{fromContract:l,fromSym:u,fromDecimals:d},to:{toContract:p,toSym:h,toDecimals:g},fromAmount:y,toAmount:f}),!l)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(!p&&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:l,fromAmount:y,toAmount:f});if(!p)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(f&&!y){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:f,fromSym:u,toSym:h});let v=await this.deriveFromAmountFromTo({chain:s,toAmount:f,toContract:p,toSym:h,fromContract:l,fromSym:u});if(!v)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 ${f} ${h} 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=v,b=f,w=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:y,derivedFromTo:b})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:l,fromSym:u,fromAmount:y});let v=await this.checkFromBalance({args:e,userContext:t,chain:s,fromContract:l,fromSym:u,fromAmount:y,toAmount:f,derivedFromTo:b,amountSizedToBalance:w});if(v)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:v.error,hasButtons:Array.isArray(v.actionButtons)}),v;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!y&&!f&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let v=await this.buildAmountPicker({userContext:t,chain:s,fromContract:l,fromSym:u,toSym:h,swapToTemplate:typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:""});if(v)return this.dbg("\u2192 Branch 1.5: amount picker returned"),v;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(y&&(d!==void 0||l==="native")){this.dbg("Branch 1.75: building confirm tx");let v=await this.buildConfirmTx({userContext:t,chain:s,toContract:p,toSym:h,toDecimals:g,fromContract:l,fromSym:u,fromDecimals:d,fromAmount:y});return v&&"ui"in v?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),v):v&&"quoteError"in v?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:v.quoteError}),{error:"quote_failed",quoteError:v.quoteError,_instructions:`Could not quote swapping ${u??"the source token"} to ${h}. The swap provider reported: "${v.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 ${h} 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 ${h}. 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 B(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=B(e.trim()),s=i=>o?(i.token_address??"").toLowerCase()===r:(i.symbol??"").toLowerCase()===r;if(n){let i=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(i.success&&i.data?.result?.length){let l=i.data.result.find(s);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name,decimals:typeof l.decimals=="number"?l.decimals:void 0}}}let a=await this.moralis.searchTokensByKey({key:e,chain:t});if(a.success&&a.data?.length){let l=a.data.find(s)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name,decimals:typeof l.decimals=="number"?l.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let s=typeof e=="string"?e.trim():"",a=typeof t=="string"?t.trim():"";if(s.toLowerCase()==="native"||a.toLowerCase()==="native")return{address:"native",symbol:a||void 0};let i=this.normaliseAddress(e),l=a||void 0,u=p=>p.toLowerCase()===M?"native":p,d=i??l??(s||void 0);if(!d)return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:a,chain:n,resolved:"none"}),{address:null,symbol:l};let m=await this.resolveContractAddress(d,n,r);return this.dbg(`resolveSide:${o}`,{refStr:s,symbolStr:a,chain:n,key:d,lookup:m}),m?{address:u(m.address),symbol:l??m.symbol,decimals:m.decimals}:i?{address:u(i),symbol:l}:{address:null,symbol:l}}async buildConfirmTx(e){let{userContext:t,chain:n,toContract:r,toSym:o,toDecimals:s,fromContract:a,fromSym:i,fromDecimals:l,fromAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let m=X(n),p=Number.parseInt(n,16);if(!m||!Number.isFinite(p))return null;let h=a==="native",g=h?m.native.decimals??18:l;if(g===void 0)return null;let f=this.toRawAmount(u,g);if(!f)return null;let y=h?M:a,k=r==="native"?M:r,w;try{w=await(await ye.getServiceByProvider("debridge")).getQuote({srcChainId:p,srcTokenAddress:y,srcTokenAmount:f,dstChainId:p,dstTokenAddress:k,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(P){return{quoteError:P instanceof Error?P.message:String(P)}}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 b=w.tx;if(!b.to||typeof b.data!="string")return null;let v={chainId:n,to:b.to,data:b.data,value:b.value??"0",from:d},A=this.extractOutRaw(w),S=A&&s!==void 0?this.trimAmount(Number(A)/10**s):void 0,C;h||(C=await this.buildApproveTx({chain:n,walletAddress:d,fromAddr:a,fromDec:g,rawAmount:f,quote:w}));let x={component:"SwapTokenConfirmTx",props:{chain:{hexId:n,name:m.name},fromToken:{address:h?"native":a,symbol:i,decimals:g,amount:u,rawAmount:f},toToken:{address:r,symbol:o,decimals:s,amount:S,rawAmount:A},estimatedOut:S,estimatedOutRaw:A,provider:w.provider,swapTx:v,approveTx:C}},L=S?` They will receive about ${S} ${o}.`:"";return{ui:x,_instructions:`A confirmation panel has been opened for swapping ${u} ${i??"the source token"} to ${o}.${L} 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. 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,a]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:s,fromPrice:a}),!s||!a)return null;let i=Number(n);if(!Number.isFinite(i)||i<=0)return null;let l=1.02,u=i*s/a;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*l)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?M: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 a=be(e);if(!a)return null;let i=u=>s===void 0?u:Wt(u,s);if(a.kind==="token")return i($t(e)??this.toPlainDecimal(a.value));if(a.kind==="percent"){if(!r)return null;let u=await this.readFromBalance(r,t,n);if(this.dbg("resolveFromAmountSpec: percent",{percent:a.percent,fromSym:o,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??s??18;return a.percent>=100?this.cleanAmountString(u.balanceFormatted):Vt(u.balanceFormatted,BigInt(Math.round(a.percent*1e6)),100000000n,d)}let l=await this.getUsdPrice(t,n);return this.dbg("resolveFromAmountSpec: usd",{usd:a.usd,fromSym:o,price:l}),l?i(this.trimAmount(a.usd/l)):null}async resolveToAmountSpec(e,t,n,r){let o=be(e);if(!o)return null;if(o.kind==="token")return $t(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:a}=e;try{let l=await(await ye.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:s,tokenDecimals:o,quoteData:a});if(!l.isNeeded)return;let u=l.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=l.contractAddress;if(!d)return;let m=Ge({abi:Ln,functionName:"approve",args:[d,BigInt(s)]});return{chainId:t,to:r,data:m,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 a=BigInt(r||"0")*10n**BigInt(t)+BigInt(s||"0");return a<=0n?null:a.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:!0,excludeUnverifiedContracts:!0}),a=(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(a.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 i=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"";return{actionButtons:a.map(u=>{let d=u.symbol,m=u.name?.trim()||d,p=u.balance_formatted?`${this.cleanAmountString(u.balance_formatted)} `:"",h=typeof u.usd_value=="number"&&u.usd_value>0?` ($${u.usd_value.toFixed(2)})`:"";return{label:`${m}: ${p}${d}${h}`,prompt:this.buildSwapFromPrompt(i,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,a=this.pantograph,i=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,l=Math.max(1,Math.min(10,i)),u=await a.getTrendingTokens({chain:s,limit:l+2}),d=u.success?u.data??[]:[],m=o?.toLowerCase(),p=r.toLowerCase(),h=d.filter(v=>!(!v.symbol||m&&m!=="native"&&v.tokenAddress&&v.tokenAddress.toLowerCase()===m||v.symbol.toLowerCase()===p)).slice(0,l);if(h.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 g=e.fromAmount??this.normaliseAmount(t.from_amount),f=e.toAmount??this.normaliseAmount(t.to_amount),y=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",k=h.map(v=>{let A=v.symbol,S=g?this.buildSwapToPrompt(y,r,A,g,null):this.buildSwapToPrompt(y,r,A,null,f);return{label:A,prompt:S}}),b=h.map((v,A)=>{let S=v.name?.trim()||v.symbol,C=v.symbol,D=typeof v.usdPrice=="number"&&v.usdPrice>0?`$${this.formatPrice(v.usdPrice)}`:"N/A",x=v.pricePercentChange?.["24h"],L=typeof x=="number"&&Number.isFinite(x)?` (${x>0?"+":x<0?"-":""}${this.formatPercent(Math.abs(x))}%)`:"";return`${A+1}. ${S} (${C}) \u2014 ${D}${L}`}).join(`
184
+ ${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 T{name="open-swap-token-form";kind="action";category="wallet-action";noSuggestions=!0;moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new D(e),this.pantograph=new ee({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=rt(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 st("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 a=await this.resolveSide(e.from_address,n,s,i,"from"),c=a.address,u=a.symbol??n,d=a.decimals,p=await this.resolveSide(e.to_address,o,s,i,"to"),m=p.address,g=p.symbol??o,h=p.decimals,f=await this.resolveToAmountSpec(e.to_amount,m,s,g),y=c?await this.resolveFromAmountSpec(e.from_amount,c,s,i,u,d??(c==="native"?18:void 0)):this.normaliseAmount(e.from_amount),b=Ce(e.from_amount),w=!!b&&b.kind!=="token",v=null;if(this.dbg("resolved sides",{from:{fromContract:c,fromSym:u,fromDecimals:d},to:{toContract:m,toSym:g,toDecimals:h},fromAmount:y,toAmount:f}),!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:f});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(f&&!y){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:f,fromSym:u,toSym:g});let k=await this.deriveFromAmountFromTo({chain:s,toAmount:f,toContract:m,toSym:g,fromContract:c,fromSym:u});if(!k)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 ${f} ${g} 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=k,v=f,w=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:y,derivedFromTo:v})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:c,fromSym:u,fromAmount:y});let k=await this.checkFromBalance({args:e,userContext:t,chain:s,fromContract:c,fromSym:u,fromAmount:y,toAmount:f,derivedFromTo:v,amountSizedToBalance:w});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(!y&&!f&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let k=await this.buildAmountPicker({userContext:t,chain:s,fromContract:c,fromSym:u,toSym:g,swapToTemplate:typeof e.swap_to_prompt_template=="string"?e.swap_to_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(y&&(d!==void 0||c==="native")){this.dbg("Branch 1.75: building confirm tx");let k=await this.buildConfirmTx({userContext:t,chain:s,toContract:m,toSym:g,toDecimals:h,fromContract:c,fromSym:u,fromDecimals:d,fromAmount:y});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 swapping ${u??"the source token"} to ${g}. 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 swap ${u??"the source token"} to ${g} 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 ${g}. 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 F(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=F(e.trim()),s=a=>o?(a.token_address??"").toLowerCase()===r:(a.symbol??"").toLowerCase()===r;if(n){let a=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let c=a.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 a=this.normaliseAddress(e),c=i||void 0,u=m=>m.toLowerCase()===$?"native":m,d=a??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}:a?{address:u(a),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,toContract:r,toSym:o,toDecimals:s,fromContract:i,fromSym:a,fromDecimals:c,fromAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let p=J(n),m=Number.parseInt(n,16);if(!p||!Number.isFinite(m))return null;let g=i==="native",h=g?p.native.decimals??18:c;if(h===void 0)return null;let f=this.toRawAmount(u,h);if(!f)return null;let y=g?$:i,b=r==="native"?$:r,w;try{w=await(await _e.getServiceByProvider("debridge")).getQuote({srcChainId:m,srcTokenAddress:y,srcTokenAmount:f,dstChainId:m,dstTokenAddress:b,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(_){return{quoteError:_ instanceof Error?_.message:String(_)}}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 v=w.tx;if(!v.to||typeof v.data!="string")return null;let k={chainId:n,to:v.to,data:v.data,value:v.value??"0",from:d},A=this.extractOutRaw(w),x=A&&s!==void 0?this.trimAmount(Number(A)/10**s):void 0,S;g||(S=await this.buildApproveTx({chain:n,walletAddress:d,fromAddr:i,fromDec:h,rawAmount:f,quote:w}));let C={component:"SwapTokenConfirmTx",props:{chain:{hexId:n,name:p.name},fromToken:{address:g?"native":i,symbol:a,decimals:h,amount:u,rawAmount:f},toToken:{address:r,symbol:o,decimals:s,amount:x,rawAmount:A},estimatedOut:x,estimatedOutRaw:A,provider:w.provider,swapTx:k,approveTx:S}},B=x?` They will receive about ${x} ${o}.`:"";return{ui:C,_instructions:`The swap of ${u} ${a??"the source token"} to ${o} is ready for the user to confirm.${B} 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 a=Number(n);if(!Number.isFinite(a)||a<=0)return null;let c=1.02,u=a*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"?$: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=Ce(e);if(!i)return null;let a=u=>s===void 0?u:sn(u,s);if(i.kind==="token")return a(rn(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):an(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?a(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,n,r){let o=Ce(e);if(!o)return null;if(o.kind==="token")return rn(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 _e.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=it({abi:no,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:!0,excludeUnverifiedContracts:!0}),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 a=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)} `:"",g=typeof u.usd_value=="number"&&u.usd_value>0?` ($${u.usd_value.toFixed(2)})`:"";return{label:`${p}: ${m}${d}${g}`,prompt:this.buildSwapFromPrompt(a,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,a=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,a)),u=await i.getTrendingTokens({chain:s,limit:c+2}),d=u.success?u.data??[]:[],p=o?.toLowerCase(),m=r.toLowerCase(),g=d.filter(k=>!(!k.symbol||p&&p!=="native"&&k.tokenAddress&&k.tokenAddress.toLowerCase()===p||k.symbol.toLowerCase()===m)).slice(0,c);if(g.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),f=e.toAmount??this.normaliseAmount(t.to_amount),y=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",b=g.map(k=>{let A=k.symbol,x=h?this.buildSwapToPrompt(y,r,A,h,null):this.buildSwapToPrompt(y,r,A,null,f);return{label:A,prompt:x}}),v=g.map((k,A)=>{let x=k.name?.trim()||k.symbol,S=k.symbol,O=typeof k.usdPrice=="number"&&k.usdPrice>0?`$${this.formatPrice(k.usdPrice)}`:"N/A",C=k.pricePercentChange?.["24h"],B=typeof C=="number"&&Number.isFinite(C)?` (${C>0?"+":C<0?"-":""}${this.formatPercent(Math.abs(C))}%)`:"";return`${A+1}. ${x} (${S}) \u2014 ${O}${B}`}).join(`
185
185
  `)+`
186
186
 
187
- Which token do you want to receive?`;return{actionButtons:k,_instructions:`The user wants to swap ${r} into another token. The trending tokens are on ${s?N(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:
187
+ 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?E(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:
188
188
 
189
- ${b}`}}async checkFromBalance(e){let{args:t,userContext:n,chain:r,fromContract:o,fromAmount:s,derivedFromTo:a}=e,i=n.walletAddress,l=await this.readFromBalance(i,o,r),u=e.fromSym??l?.symbol??"the selected token";if(!l){this.dbg("checkFromBalance: NOT held \u2192 source picker fallback",{fromSym:u});let g=await this.buildSourcePicker(t,n);return"actionButtons"in g?{error:"no_from_balance",actionButtons:g.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.`}:g}if(!s||e.amountSizedToBalance)return null;let d=l.decimals!==void 0?Wt(s,l.decimals):s;if(On(d,l.balanceFormatted)<=0)return null;let m=this.cleanAmountString(l.balanceFormatted),p=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,fromSym:u,toSym:typeof t.to_symbol=="string"?t.to_symbol.trim():l.symbol??"the destination token",swapToTemplate:typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:""}),h=a?`Receiving ${a} of the destination token needs about ${s} ${u}, but they only have ${m} ${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 ${m} ${u}, then ask them to choose a smaller amount \u2014 `:`The user wants to swap ${s} ${u}, but they only have ${m} ${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 ${m} ${u}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_from_balance",actionButtons:p,_instructions:h+'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:!0,excludeUnverifiedContracts:!0}),o=r.success?r.data?.result??[]:[];this.dbg("readFromBalance",{fromAddr:t,chain:n,ok:r.success,count:o.length});let s=t.toLowerCase(),a=o.find(l=>s==="native"?l.native_token===!0:l.token_address?.toLowerCase()===s);if(!a?.balance_formatted)return this.dbg("readFromBalance: source token NOT held \u2192 null",{fromAddr:t}),null;let i=Number(a.balance_formatted);if(!Number.isFinite(i)||i<=0)return this.dbg("readFromBalance: zero/invalid balance \u2192 null",{fromAddr:t,balance:a.balance_formatted}),null;if(s==="native"&&n){let l=await Ot(n,"swap"),u=Bt(i,l,n);if(this.dbg("readFromBalance: native spendable",{balanceNum:i,spendable:u}),u<=0)return this.dbg("readFromBalance: native spendable \u2264 0 \u2192 null",{balanceNum:i}),null;let d=this.trimAmount(u),m=typeof a.decimals=="number"?a.decimals:18;return{balanceFormatted:d,balanceNum:u,symbol:a.symbol,decimals:m}}return this.dbg("readFromBalance: held",{fromAddr:t,balance:a.balance_formatted,symbol:a.symbol}),{balanceFormatted:a.balance_formatted,balanceNum:i,symbol:a.symbol,decimals:typeof a.decimals=="number"?a.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,fromSym:r,toSym:o,swapToTemplate:s}=e,a=n??18;return[25,50,75,100].map(l=>{let u=Vt(this.cleanAmountString(t),BigInt(l),100n,a);return{label:`${l}%`,prompt:this.buildSwapToPrompt(s,r,o,u,null)}})}async buildAmountPicker(e){let{userContext:t,chain:n,fromContract:r,toSym:o,swapToTemplate:s}=e,a=t.walletAddress,i=await this.readFromBalance(a,r,n),l=e.fromSym??i?.symbol;if(!i||!l)return null;let u=this.percentSpendButtons({balanceFormatted:i.balanceFormatted,balanceNum:i.balanceNum,decimals:i.decimals,fromSym:l,toSym:o,swapToTemplate:s}),d=this.cleanAmountString(i.balanceFormatted);return{actionButtons:u,_instructions:`The user's spendable balance is ${d} ${l}. 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 ${l} balance (e.g., 'B\u1EA1n mu\u1ED1n swap ${l} sang ${o}, hi\u1EC7n c\xF3 ${d} ${l} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to swap ${l} to ${o}; you have ${d} ${l} 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),[a,i=""]=r.split("."),l=a+i,u;if(s>=0){let d=a.length+s;u=d>=l.length?l.padEnd(d,"0"):`${l.slice(0,d)}.${l.slice(d)}`}else u=`0.${"0".repeat(-s-a.length)}${l}`;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 Yt=class extends le{name="open-send-nft-form";actionType="send_nft";component="SendNftForm";userInputFields=[{key:"to_address",label:"the recipient address"}];url;constructor(e,t){super(e);let n=t?.url?.trim();this.url=n||void 0}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),a=this.normaliseString(e.nft_name),i=this.normaliseAddress(e.to_address),l=this.normaliseString(e.token_standard),u=this.normaliseAmountInt(e.amount);if(!o&&!s&&!a)return this.websiteNotice("no_nft_specified");if(!this.moralis||!r)return this.paramsFromInputs({contract:o,tokenId:s,toAddress:i,standardArg:l,nftName:a,amountInt:u});let d=await this.moralis.getWalletNFTs({address:r,chain:n,limit:100,excludeSpam:!1}),m=d.success?d.data?.result??[]:[],p=this.matchNfts(m,{contract:o,tokenId:s,nftName:a});if(p.length===0){let h=a??(o&&s?`#${s}`:o??`#${s??""}`),g=N(n);return{error:"nft_not_owned",_instructions:`The user asked to send "${h}" but the wallet does not hold a matching NFT on ${g}. Tell them, in their language, that they do not own that NFT on ${g} 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 p.length===1?this.paramsFromNft(p[0],{toAddress:i,amountInt:u}):this.websiteNotice("multiple_nfts_matched")}websiteNotice(e){let n=`Please select the NFT you would like to send from the list and proceed via ${this.url?`[this website](${this.url})`:"this website"}`;return{error:e,message:n,_instructions:"This is a fixed notice. Reply with a SINGLE sentence in the USER'S language that conveys this message (translate the wording naturally \u2014 do NOT leave it in English when the user wrote another language). "+(this.url?`You MUST reproduce the Markdown link and keep it CLICKABLE: keep the URL byte-for-byte; you may localize only the visible link text. Keep the form [text](${this.url}). NEVER output the sentence without the link, and NEVER show the raw URL on its own. `:"There is NO website link configured: keep the website phrase as PLAIN TEXT. NEVER add, invent, guess, or fabricate any URL or Markdown link \u2014 there is no link to show. ")+`Output ONLY that one sentence \u2014 do NOT also include the original English, a second copy, or any preamble. Do NOT open the form. Do NOT mention tool names, UI, or forms. The message to convey:
189
+ ${v}`}}async checkFromBalance(e){let{args:t,userContext:n,chain:r,fromContract:o,fromAmount:s,derivedFromTo:i}=e,a=n.walletAddress,c=await this.readFromBalance(a,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?sn(s,c.decimals):s;if(ro(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:""}),g=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:g+'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:!0,excludeUnverifiedContracts:!0}),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 a=Number(i.balance_formatted);if(!Number.isFinite(a)||a<=0)return this.dbg("readFromBalance: zero/invalid balance \u2192 null",{fromAddr:t,balance:i.balance_formatted}),null;if(s==="native"&&n){let c=await Zt(n,"swap"),u=en(a,c,n);if(this.dbg("readFromBalance: native spendable",{balanceNum:a,spendable:u}),u<=0)return this.dbg("readFromBalance: native spendable \u2264 0 \u2192 null",{balanceNum:a}),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:a,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=an(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,a=await this.readFromBalance(i,r,n),c=e.fromSym??a?.symbol;if(!a||!c)return null;let u=this.percentSpendButtons({balanceFormatted:a.balanceFormatted,balanceNum:a.balanceNum,decimals:a.decimals,fromSym:c,toSym:o,swapToTemplate:s}),d=this.cleanAmountString(a.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,a=""]=r.split("."),c=i+a,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 un=class extends fe{name="open-send-nft-form";actionType="send_nft";component="SendNftForm";userInputFields=[{key:"to_address",label:"the recipient address"}];url;constructor(e,t){super(e);let n=t?.url?.trim();this.url=n||void 0}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),a=this.normaliseAddress(e.to_address),c=this.normaliseString(e.token_standard),u=this.normaliseAmountInt(e.amount);if(!o&&!s&&!i)return this.websiteNotice("no_nft_specified");if(!this.moralis||!r)return this.paramsFromInputs({contract:o,tokenId:s,toAddress:a,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 g=i??(o&&s?`#${s}`:o??`#${s??""}`),h=E(n);return{error:"nft_not_owned",_instructions:`The user asked to send "${g}" 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:a,amountInt:u}):this.websiteNotice("multiple_nfts_matched")}websiteNotice(e){let n=`Please select the NFT you would like to send from the list and proceed via ${this.url?`[this website](${this.url})`:"this website"}`;return{error:e,message:n,_instructions:"This is a fixed notice. Reply with a SINGLE sentence in the USER'S language that conveys this message (translate the wording naturally \u2014 do NOT leave it in English when the user wrote another language). "+(this.url?`You MUST reproduce the Markdown link and keep it CLICKABLE: keep the URL byte-for-byte; you may localize only the visible link text. Keep the form [text](${this.url}). NEVER output the sentence without the link, and NEVER show the raw URL on its own. `:"There is NO website link configured: keep the website phrase as PLAIN TEXT. NEVER add, invent, guess, or fabricate any URL or Markdown link \u2014 there is no link to show. ")+`Output ONLY that one sentence \u2014 do NOT also include the original English, a second copy, or any preamble. Do NOT open the form. Do NOT mention tool names, UI, or forms. The message to convey:
190
190
 
191
- `+n}}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(),a=(o.name??"").toLowerCase();if(!s.includes(r)&&!a.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 a=e.normalized_metadata?.image||e.media?.original_media_url||"";return a&&(s.nft_image=a),s}};var Kt=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 jt=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(`
191
+ `+n}}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 ea=[{name:"open-send-native-form",description:`Use for ANY intent to SEND the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026): "send eth", "g\u1EEDi ETH", "transfer 1 BNB". This tool does NOT perform the send \u2014 it tells the user they can do it in the app.`,what:"send the native coin"},{name:"open-send-token-form",description:`Use for ANY intent to SEND an ERC-20 token (any coin that is NOT the chain's native one): "send USDC", "transfer some token", "g\u1EEDi token". This tool does NOT perform the send \u2014 it tells the user they can do it in the app.`,what:"send a token"},{name:"open-send-nft-form",description:'Use for ANY intent to SEND / TRANSFER an NFT: "send nft", "transfer nft", "g\u1EEDi nft". This tool does NOT perform the transfer \u2014 it points the user to the NFT website to select and send it there.',what:"send an NFT",linkKind:"nft"},{name:"open-buy-token-form",description:'Use for ANY intent to BUY a token: "buy ETH", "buy a token", "mua token". This tool does NOT perform the purchase \u2014 it tells the user they can do it in the app.',what:"buy a token"},{name:"open-swap-token-form",description:'Use for ANY intent to SWAP a token the user already holds into another: "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang USDT". This tool does NOT perform the swap \u2014 it tells the user they can do it in the app.',what:"swap tokens"},{name:"open-approve-token-form",description:'Use for ANY intent to APPROVE or REVOKE an ERC-20 allowance: "approve USDC", "revoke approval". This tool does NOT perform the approval \u2014 it tells the user they can do it in the app.',what:"approve or revoke a token"}],Cn=class extends T{name;description;category="wallet-action";noSuggestions=!0;parameters=[];what;linkKind;appLink;nftLink;constructor(e,t){super(),this.name=e.name,this.description=e.description,this.what=e.what,this.linkKind=e.linkKind??"app",this.appLink=t?.appLink,this.nftLink=t?.nftLink?.trim()||void 0}async run(){if(this.linkKind==="nft")return this.nftWebsiteNotice();let e=this.appLink?` Give them this link as plain text so they can open it: ${this.appLink} \u2014 write the URL exactly, do NOT shorten it or wrap it in markdown.`:"";return{_instructions:`Tell the user (in their language) that they can ${this.what} directly in the app, and that they should do it there.${e} Keep it short and friendly. Do NOT ask for any details (token, amount, recipient, \u2026) and do NOT mention tool names, forms, or UI.`,...this.appLink?{url:this.appLink}:{}}}nftWebsiteNotice(){let t=`Please select the NFT you would like to send from the list and proceed via ${this.nftLink?`[this website](${this.nftLink})`:"this website"}`;return{message:t,_instructions:"This is a fixed notice. Reply with a SINGLE sentence in the USER'S language that conveys this message (translate the wording naturally \u2014 do NOT leave it in English when the user wrote another language). "+(this.nftLink?`You MUST reproduce the Markdown link and keep it CLICKABLE: keep the URL byte-for-byte; you may localize only the visible link text. Keep the form [text](${this.nftLink}). NEVER output the sentence without the link, and NEVER show the raw URL on its own. `:"There is NO website link configured: keep the website phrase as PLAIN TEXT. NEVER add, invent, guess, or fabricate any URL or Markdown link \u2014 there is no link to show. ")+`Output ONLY that one sentence \u2014 do NOT also include the original English, a second copy, or any preamble. Do NOT mention tool names, UI, or forms. The message to convey:
192
+
193
+ `+t}}};function so(l){return ea.map(e=>new Cn(e,l))}var dn=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 pn=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(`
192
194
  `),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:
193
195
 
194
- ${n}`,timestamp:Date.now()}];return(await this.llm.chat(r)).text}};var pa=`You are a strict FAQ matcher. Given a user query and a list of FAQ entries, determine which FAQ entries the user is SPECIFICALLY asking about.
196
+ ${n}`,timestamp:Date.now()}];return(await this.llm.chat(r)).text}};var ta=`You are a strict FAQ matcher. Given a user query and a list of FAQ entries, determine which FAQ entries the user is SPECIFICALLY asking about.
195
197
 
196
198
  RULES:
197
199
  - Only match when the user's question is CLEARLY about the same topic as the FAQ entry.
@@ -206,13 +208,13 @@ RULES:
206
208
  - Return ONLY the JSON array, no other text.
207
209
 
208
210
  FAQ ENTRIES:
209
- `,zt=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(`
210
- `),r=[{role:"user",content:pa+n+`
211
+ `,mn=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(`
212
+ `),r=[{role:"user",content:ta+n+`
211
213
 
212
- USER QUERY: ${e}`,timestamp:0}];try{let a=(await this.llm.chat(r)).text.trim().match(/\[[\s\S]*\]/);if(!a)return[];let i=JSON.parse(a[0]),l=[];for(let u of i)u.index>=0&&u.index<this.entries.length&&u.score>=.6&&l.push({entry:this.entries[u.index],score:u.score});return l.sort((u,d)=>d.score-u.score),l.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 a=this.tokenize(s.question),i=this.jaccardSimilarity(r,a);i>=n&&o.push({entry:s,score:i})}return o.sort((s,a)=>a.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 ln=require("@upstash/vector"),ha="https://perfect-octopus-59684-us1-vector.upstash.io",ga="ABkFMHBlcmZlY3Qtb2N0b3B1cy01OTY4NC11czFhZG1pbk56WXdOV0k0T0RndFpUaGtOeTAwWWpjMkxXRmtNRFV0WW1WaU9UaGtOMlV5T0ROaQ==",Re=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)??ha,n=e.token??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_TOKEN:void 0)??ga;this.index=new ln.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"?ln.FusionAlgorithm.RRF:ln.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,a;try{a=await s.query({data:e,topK:o,includeMetadata:!0,fusionAlgorithm:this.fusionAlgorithm})}catch(l){return this.debug&&console.warn("[UpstashKnowledgeBase] query failed:",l),[]}let i=[];for(let l of a){if(r&&l.score<this.minScore)continue;let u=l.metadata;!u?.question||!u?.answer||i.push({entry:{question:u.question,answer:u.answer},score:l.score})}return this.debug&&console.log(`[UpstashKnowledgeBase] query="${e}" \u2192 ${i.length}/${a.length} hit(s) `+(r?`above ${this.minScore}`:"(minScore bypassed)")+(i[0]?` (top: ${i[0].score.toFixed(3)})`:"")),i}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}
214
+ USER QUERY: ${e}`,timestamp:0}];try{let i=(await this.llm.chat(r)).text.trim().match(/\[[\s\S]*\]/);if(!i)return[];let a=JSON.parse(i[0]),c=[];for(let u of a)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),a=this.jaccardSimilarity(r,i);a>=n&&o.push({entry:s,score:a})}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 En=require("@upstash/vector"),na="https://perfect-octopus-59684-us1-vector.upstash.io",oa="ABkFMHBlcmZlY3Qtb2N0b3B1cy01OTY4NC11czFhZG1pbk56WXdOV0k0T0RndFpUaGtOeTAwWWpjMkxXRmtNRFV0WW1WaU9UaGtOMlV5T0ROaQ==",$e=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)??na,n=e.token??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_TOKEN:void 0)??oa;this.index=new En.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"?En.FusionAlgorithm.RRF:En.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 a=[];for(let c of i){if(r&&c.score<this.minScore)continue;let u=c.metadata;!u?.question||!u?.answer||a.push({entry:{question:u.question,answer:u.answer},score:c.score})}return this.debug&&console.log(`[UpstashKnowledgeBase] query="${e}" \u2192 ${a.length}/${i.length} hit(s) `+(r?`above ${this.minScore}`:"(minScore bypassed)")+(a[0]?` (top: ${a[0].score.toFixed(3)})`:"")),a}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}
213
215
 
214
- ${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 we(c){return c.filter(e=>e.role!=="tool"&&!(e.role==="assistant"&&e.toolCalls&&e.toolCalls.length>0)&&!e._intermediate)}function tr(c,e){let t=[];for(let n=0;n<c.length;n++){let r=c[n];if(r.role==="assistant"&&r.toolCalls&&r.toolCalls.length>0){if(r.toolCalls.every(i=>e.has(i.toolName))){t.push(r);continue}let s=r.toolCalls.map(i=>i.toolName).join(", ");t.push({role:"assistant",content:`(Previously called external tools: ${s} \u2014 results not visible here.)`,timestamp:r.timestamp});let a=new Set(r.toolCalls.map(i=>i.callId));for(;n+1<c.length;){let i=c[n+1];if(i.role==="tool"&&i.toolCallId&&a.has(i.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 xe(c,e){if(c.length<=e)return[...c];let t=c.length-e;for(;t>0;){if(c[t].role==="tool"){t--;continue}break}let n=c.slice(t),r=0;for(;r<n.length&&n[r].role==="tool";)r++;return n.slice(r)}function nr(c,e){return xe(c,e)}function or(c){for(let e=c.length-1;e>=0;e--){let t=c[e];if(t.role==="assistant"&&!(t.toolCalls&&t.toolCalls.length>0))return t.subagents&&t.subagents.length>0?[...t.subagents]:[]}return[]}function rr(c,e=5){let t=c.filter(s=>s.role==="tool").slice(-e);if(t.length===0)return"";let n=[],r=[];for(let s of t){let a;try{a=JSON.parse(s.content)}catch{continue}if(typeof a!="object"||a===null)continue;let i=a,l=i.pagination;l&&typeof l.cursor=="string"&&l.cursor&&r.push({toolName:s.toolName??"tool",cursor:l.cursor});let u=i.transactions??i.result??i.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(`
215
- `)}var fa=`You are a ROUTER.
216
+ ${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 Ee(l){return l.filter(e=>e.role!=="tool"&&!(e.role==="assistant"&&e.toolCalls&&e.toolCalls.length>0)&&!e._intermediate)}function Lr(l,e){let t=[];for(let n=0;n<l.length;n++){let r=l[n];if(r.role==="assistant"&&r.toolCalls&&r.toolCalls.length>0){if(r.toolCalls.every(a=>e.has(a.toolName))){t.push(r);continue}let s=r.toolCalls.map(a=>a.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(a=>a.callId));for(;n+1<l.length;){let a=l[n+1];if(a.role==="tool"&&a.toolCallId&&i.has(a.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 Ie(l,e){if(l.length<=e)return[...l];let t=l.length-e;for(;t>0;){if(l[t].role==="tool"){t--;continue}break}let n=l.slice(t),r=0;for(;r<n.length&&n[r].role==="tool";)r++;return n.slice(r)}function Dr(l,e){return Ie(l,e)}function Or(l){for(let e=l.length-1;e>=0;e--){let t=l[e];if(t.role==="assistant"&&!(t.toolCalls&&t.toolCalls.length>0))return t.subagents&&t.subagents.length>0?[...t.subagents]:[]}return[]}function Mr(l,e=5){let t=l.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 a=i,c=a.pagination;c&&typeof c.cursor=="string"&&c.cursor&&r.push({toolName:s.toolName??"tool",cursor:c.cursor});let u=a.transactions??a.result??a.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(`
217
+ `)}var ra=`You are a ROUTER.
216
218
 
217
219
  The incoming user query has ALREADY been contextualized upstream \u2014 it is a
218
220
  self-contained, standalone question. Your ONLY job: decide which subagent(s)
@@ -259,33 +261,32 @@ The query may arrive in ANY language (English, Vietnamese, Japanese, Korean, Chi
259
261
  The subagent descriptions are written in English, but they apply equally to the SAME intent expressed in
260
262
  any language. Route by MEANING, never by matching English keywords or script \u2014 a wallet / token / NFT / pool /
261
263
  swap / buy request is the same intent however it is phrased or whichever language it is written in. Token
262
- symbols, contract addresses, and numbers are language-neutral.`,Qt=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??10,this.debug=t?.debug??!1}async route(e,t,n,r,o=[]){let s=n.map(b=>`### ${b.name} (domain: ${b.domain})
263
- ${b.description}`).join(`
264
+ symbols, contract addresses, and numbers are language-neutral.`,hn=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??10,this.debug=t?.debug??!1}async route(e,t,n,r,o=[]){let s=n.map(v=>`### ${v.name} (domain: ${v.domain})
265
+ ${v.description}`).join(`
264
266
 
265
- `),a=[];r?.walletAddress&&a.push(`Connected wallet: ${r.walletAddress}`),r?.chain&&a.push(`Current chain: ${r.chain}`);let i=a.length>0?`
267
+ `),i=[];r?.walletAddress&&i.push(`Connected wallet: ${r.walletAddress}`),r?.chain&&i.push(`Current chain: ${r.chain}`);let a=i.length>0?`
266
268
 
267
269
  User context:
268
- ${a.join(`
269
- `)}`:"",l=o.length>0?`
270
+ ${i.join(`
271
+ `)}`:"",c=o.length>0?`
270
272
 
271
- 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=we(t),d=xe(u,this.historyMessages);this.debug&&(console.log(`
272
- [Router] history window (${d.length} msg${d.length===1?"":"s"}):`),console.log(`[Router] user query: "${e}"`));let m=[{role:"system",content:fa,timestamp:0},...d,{role:"user",content:`Available subagents:
273
- ${s}${i}${l}
273
+ 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=Ee(t),d=Ie(u,this.historyMessages);this.debug&&(console.log(`
274
+ [Router] history window (${d.length} msg${d.length===1?"":"s"}):`),console.log(`[Router] user query: "${e}"`));let p=[{role:"system",content:ra,timestamp:0},...d,{role:"user",content:`Available subagents:
275
+ ${s}${a}${c}
274
276
 
275
- User query: ${e}`,timestamp:Date.now()}],p=Date.now(),h=null,g="",f=null;for(let b=1;b<=2;b++){let v=await this.llm.chat(m);g=v.text;try{h=this.parseJSON(v.text);break}catch(A){f=A,b<2&&(this.debug&&console.log(`[Router] JSON parse failed (attempt ${b}) \u2014 re-prompting for JSON`),m.push({role:"assistant",content:v.text||"",timestamp:Date.now()}),m.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()-p;if(!h)return this.debug&&(console.log(`[Router] JSON parse failed after retry: ${f}`),console.log(`[Router] raw response: ${g.slice(0,300)}`)),{analysis:"Router could not parse response.",assignments:[]};let k=new Set(n.map(b=>b.name)),w=Array.isArray(h.assignments)?h.assignments.filter(b=>!!b&&typeof b.subagent=="string").filter(b=>k.has(b.subagent)).map(b=>({subagent:b.subagent,query:typeof b.query=="string"&&b.query?b.query:e,reasoning:typeof b.reasoning=="string"?b.reasoning:""})):[];if(this.debug){let b=w.length>0?w.map(v=>v.subagent).join(", "):"(none \u2014 direct answer)";if(console.log(`
276
- [Router] (${y}ms)`),console.log(` analysis : ${h.analysis??""}`),console.log(` dispatch : ${b}`),w.length>0)for(let v of w)console.log(` \u2192 ${v.subagent}: "${v.query}"`),console.log(` reason: ${v.reasoning}`)}return{analysis:typeof h.analysis=="string"?h.analysis:"",assignments:w}}async dispatch(e,t,n,r){if(e.assignments.length===0)return[];this.debug&&console.log(`
277
- [Router] dispatching ${e.assignments.length} subagent(s) in parallel\u2026`);let o=Date.now(),s=e.assignments.map(async i=>{let l=t.get(i.subagent);if(!l)return this.debug&&console.log(`[Router] WARN: subagent "${i.subagent}" not registered`),{subagentName:i.subagent,steps:[],finalAnswer:`Subagent "${i.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let u=Date.now(),d=await l.run({query:i.query,reasoning:i.reasoning},n,r);if(this.debug){let m=d.toolResults.map(p=>p.toolName).join(", ")||"\u2014";console.log(`[Router] ${i.subagent} done in ${Date.now()-u}ms | tools: ${m}`)}return d}),a=await Promise.all(s);return this.debug&&console.log(`[Router] all subagents done in ${Date.now()-o}ms total`),a}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 ya=`
277
+ User query: ${e}`,timestamp:Date.now()}],m=Date.now(),g=null,h="",f=null;for(let v=1;v<=2;v++){let k=await this.llm.chat(p);h=k.text;try{g=this.parseJSON(k.text);break}catch(A){f=A,v<2&&(this.debug&&console.log(`[Router] JSON parse failed (attempt ${v}) \u2014 re-prompting for JSON`),p.push({role:"assistant",content:k.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(!g)return this.debug&&(console.log(`[Router] JSON parse failed after retry: ${f}`),console.log(`[Router] raw response: ${h.slice(0,300)}`)),{analysis:"Router could not parse response.",assignments:[]};let b=new Set(n.map(v=>v.name)),w=Array.isArray(g.assignments)?g.assignments.filter(v=>!!v&&typeof v.subagent=="string").filter(v=>b.has(v.subagent)).map(v=>({subagent:v.subagent,query:typeof v.query=="string"&&v.query?v.query:e,reasoning:typeof v.reasoning=="string"?v.reasoning:""})):[];if(this.debug){let v=w.length>0?w.map(k=>k.subagent).join(", "):"(none \u2014 direct answer)";if(console.log(`
278
+ [Router] (${y}ms)`),console.log(` analysis : ${g.analysis??""}`),console.log(` dispatch : ${v}`),w.length>0)for(let k of w)console.log(` \u2192 ${k.subagent}: "${k.query}"`),console.log(` reason: ${k.reasoning}`)}return{analysis:typeof g.analysis=="string"?g.analysis:"",assignments:w}}async dispatch(e,t,n,r){if(e.assignments.length===0)return[];this.debug&&console.log(`
279
+ [Router] dispatching ${e.assignments.length} subagent(s) in parallel\u2026`);let o=Date.now(),s=e.assignments.map(async a=>{let c=t.get(a.subagent);if(!c)return this.debug&&console.log(`[Router] WARN: subagent "${a.subagent}" not registered`),{subagentName:a.subagent,steps:[],finalAnswer:`Subagent "${a.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let u=Date.now(),d=await c.run({query:a.query,reasoning:a.reasoning},n,r);if(this.debug){let p=d.toolResults.map(m=>m.toolName).join(", ")||"\u2014";console.log(`[Router] ${a.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 sa=`
278
280
 
279
- 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.`,j=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+ya,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}}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(`
280
- [${this.name}] query: "${e.query}"`),console.log(` [${this.name}] tools available: ${r.map(v=>v.name).join(", ")}`)),r.length===0)return{subagentName:this.name,steps:[],finalAnswer:`Subagent "${this.name}" has no registered tools available.`,toolResults:[],toolMessages:[]};let o=[],s=[],a=[],i=new Set,l=0,u=!1,d=[];if(n?.walletAddress&&d.push(`Connected wallet: ${n.walletAddress}`),n?.chain){let v=N(n.chain),A=vo(n.chain),S=A?`; native coin: ${A}`:"";d.push(`Current chain: ${v} (${n.chain})${S}`)}let m=d.length>0?`User context:
281
+ 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.`,j=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+sa,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}}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(k=>k.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=[],a=new Set,c=0,u=!1,d=[];if(n?.walletAddress&&d.push(`Connected wallet: ${n.walletAddress}`),n?.chain){let k=E(n.chain),A=Qo(n.chain),x=A?`; native coin: ${A}`:"";d.push(`Current chain: ${k} (${n.chain})${x}`)}let p=d.length>0?`User context:
281
283
  ${d.join(`
282
- `)}`:"",p=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.`:"",h=[m,p,`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(`
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.`:"",g=[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(`
283
285
 
284
- `),g=tr(t,this.toolNames),f=xe(g,this.historyMessages),y=[{role:"system",content:this.systemPrompt,timestamp:0},...f,{role:"user",content:h,timestamp:Date.now()}],k=6e3,w=this.maxToolCalls+2;for(let v=0;v<w;v++){let A=l<this.maxToolCalls,S=A?r:void 0,C=A&&this.mustCallTool&&l===0,D=await this.llm.chat(y,S,C?{forceToolUse:!0}:void 0);if(D.toolCalls.length===0){if(l===0&&this.cortexFallbackTool&&A){this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing fallback to ${this.cortexFallbackTool}`),y.push({role:"user",content:`You answered without calling any tool. This is not allowed for on-chain queries. Call "${this.cortexFallbackTool}" now with a clear, well-formed English prompt that captures the user's intent. Resolve ambiguity with sensible defaults (chain: Ethereum unless specified; result count: top 10; time window: last 24h; sort key: 24h volume for "top/best/trending" queries). Do NOT answer in text \u2014 call the tool.`,timestamp:Date.now()});continue}if(l===0&&this.mustCallTool&&A&&!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 ${l} tool call(s), answer: "${D.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:o,finalAnswer:D.text,toolResults:s,toolMessages:a}}let x={role:"assistant",content:D.text||"",toolCalls:D.toolCalls,timestamp:Date.now()};y.push(x);let L=[];for(let P of D.toolCalls){if(!this.toolNames.has(P.toolName)){let z=`Tool "${P.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${z}`),o.push({phase:"observe",content:z,timestamp:Date.now()}),y.push({role:"tool",content:z,toolName:P.toolName,toolCallId:P.callId,timestamp:Date.now()});continue}let H=`${P.toolName}::${JSON.stringify(P.args)}`;if(i.has(H)){let z=`Skipped duplicate call: ${P.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${P.toolName}`),o.push({phase:"observe",content:z,timestamp:Date.now()}),y.push({role:"tool",content:z,toolName:P.toolName,toolCallId:P.callId,timestamp:Date.now()});continue}i.add(H),l++,this.debug&&console.log(` [${this.name}] call #${l}: ${P.toolName} ${JSON.stringify(P.args)}`),o.push({phase:"think",content:D.text||`Calling ${P.toolName}`,timestamp:Date.now()}),o.push({phase:"act",content:`Calling tool: ${P.toolName}`,toolCall:{toolName:P.toolName,args:P.args},timestamp:Date.now()});let Pe=Date.now(),ce={...n,query:e.query},Q=await this.registry.execute(P.toolName,P.args,ce);s.push(Q);let Z=Q.success?JSON.stringify(Q.data):`Error: ${Q.error}`;if(this.debug){let z=Q.success?"OK":"ERR",me=Q.success?`${Z.slice(0,120)}${Z.length>120?"\u2026":""}`:Q.error;console.log(` [${this.name}] ${z} (${Date.now()-Pe}ms): ${me}`)}o.push({phase:"observe",content:Z,toolResult:Q,timestamp:Date.now()});let ke={role:"tool",content:Z,toolName:P.toolName,toolCallId:P.callId,timestamp:Date.now()};y.push(ke),L.push({...ke,content:Z.length>k?Z.slice(0,k)+"\u2026[truncated]":Z})}L.length>0&&(a.push(x),a.push(...L))}this.debug&&console.log(` [${this.name}] budget exhausted after ${l} 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 b=await this.llm.chat(y);return{subagentName:this.name,steps:o,finalAnswer:b.text,toolResults:s,toolMessages:a}}};var ba=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
286
+ `),h=Lr(t,this.toolNames),f=Ie(h,this.historyMessages),y=[{role:"system",content:this.systemPrompt,timestamp:0},...f,{role:"user",content:g,timestamp:Date.now()}],b=6e3,w=this.maxToolCalls+2;for(let k=0;k<w;k++){let A=c<this.maxToolCalls,x=A?r:void 0,S=A&&this.mustCallTool&&c===0,O=await this.llm.chat(y,x,S?{forceToolUse:!0}:void 0);if(O.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&A){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&&A&&!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: "${O.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:o,finalAnswer:O.text,toolResults:s,toolMessages:i}}let C={role:"assistant",content:O.text||"",toolCalls:O.toolCalls,timestamp:Date.now()};y.push(C);let B=[];for(let _ of O.toolCalls){if(!this.toolNames.has(_.toolName)){let ne=`Tool "${_.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${ne}`),o.push({phase:"observe",content:ne,timestamp:Date.now()}),y.push({role:"tool",content:ne,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()});continue}let N=`${_.toolName}::${JSON.stringify(_.args)}`;if(a.has(N)){let ne=`Skipped duplicate call: ${_.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${_.toolName}`),o.push({phase:"observe",content:ne,timestamp:Date.now()}),y.push({role:"tool",content:ne,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()});continue}a.add(N),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${_.toolName} ${JSON.stringify(_.args)}`),o.push({phase:"think",content:O.text||`Calling ${_.toolName}`,timestamp:Date.now()}),o.push({phase:"act",content:`Calling tool: ${_.toolName}`,toolCall:{toolName:_.toolName,args:_.args},timestamp:Date.now()});let ve=Date.now(),Le={...n,query:e.query},V=await this.registry.execute(_.toolName,_.args,Le);s.push(V);let te=V.success?JSON.stringify(V.data):`Error: ${V.error}`;if(this.debug){let ne=V.success?"OK":"ERR",Te=V.success?`${te.slice(0,120)}${te.length>120?"\u2026":""}`:V.error;console.log(` [${this.name}] ${ne} (${Date.now()-ve}ms): ${Te}`)}o.push({phase:"observe",content:te,toolResult:V,timestamp:Date.now()});let Re={role:"tool",content:te,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()};y.push(Re),B.push({...Re,content:te.length>b?te.slice(0,b)+"\u2026[truncated]":te})}B.length>0&&(i.push(C),i.push(...B))}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 v=await this.llm.chat(y);return{subagentName:this.name,steps:o,finalAnswer:v.text,toolResults:s,toolMessages:i}}};var ia=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
285
287
 
286
288
  SPECIALISED TOOLS (prefer these when intent matches):
287
289
  - get-wallet-token-balances: token + native coin balances
288
- - get-wallet-net-worth: total portfolio value across chains
289
290
  - get-wallet-history: full transaction history
290
291
  - get-transaction-by-hash: decode a single transaction
291
292
  - get-wallet-token-transfers: ERC-20 transfer history
@@ -332,7 +333,7 @@ PAGINATION:
332
333
  pass the cursor from the LAST history response in conversation. Always tell the user
333
334
  how many results were returned and whether more pages exist.
334
335
 
335
- Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea .`,Bn=["get-wallet-token-balances","get-wallet-history","get-wallet-token-transfers","get-wallet-nft-transfers","get-wallet-net-worth","get-wallet-pnl-summary","get-wallet-pnl","get-wallet-approvals","get-wallet-defi-summary","get-wallet-defi-positions","get-wallet-defi-protocol-positions","get-transaction-by-hash","gemini-search-ai"];function cn(c,e,t){return new j({name:"wallet-agent",domain:"wallet",capability:"check a wallet's token balances, portfolio, transaction history, PnL, DeFi positions and token approvals",description:["Wallet-scoped on-chain state. Specialised tools cover balances, net worth, transaction history,","single-tx lookup, ERC-20 / NFT transfers, PnL, DeFi positions, and approvals.","For wallet queries without a direct tool , this agent falls","back to a search-grounded Gemini model internally \u2014 it never refuses a wallet-scoped query","and always calls a tool.","NOT in scope: market-wide token data (\u2192 token-agent), NFT current holdings (\u2192 nft-agent)."].join(" "),toolNames:[...Bn],systemPrompt:ba,cortexFallbackTool:"gemini-search-ai",llm:c,registry:e,options:t})}var wa=`You are the Token domain expert. You answer market-wide token questions, not wallet-specific ones.
336
+ Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea .`,io=["get-wallet-token-balances","get-wallet-history","get-wallet-token-transfers","get-wallet-nft-transfers","get-wallet-pnl-summary","get-wallet-pnl","get-wallet-approvals","get-wallet-defi-summary","get-wallet-defi-positions","get-wallet-defi-protocol-positions","get-transaction-by-hash","gemini-search-ai"];function Rn(l,e,t){return new j({name:"wallet-agent",domain:"wallet",capability:"check a wallet's token balances, portfolio, transaction history, PnL, DeFi positions and token approvals",description:["Wallet-scoped on-chain state. Specialised tools cover balances, net worth, transaction history,","single-tx lookup, ERC-20 / NFT transfers, PnL, DeFi positions, and approvals.","Owns READ-ONLY queries about a WALLET'S OWN DeFi/LP/staking/lending positions \u2014 both across all protocols",'AND within a specific NAMED protocol: "my positions", "my LP positions", "my position on Uniswap",','"my Uniswap positions", "what I have on Aave", "my Lido staking", "my Pendle positions". The "my/their"',"(or connected-wallet) framing makes it wallet-scoped \u2014 route it here even when a protocol like Uniswap is named.","This is VIEWING only. An explicit request to ACT on an LP position \u2014 close / remove / withdraw the pair, or",'collect / claim earned fees ("close my pool", "remove liquidity", "collect my fees", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n") \u2014 is NOT in scope (\u2192 pool-agent).',"For wallet queries without a direct tool , this agent falls","back to a search-grounded Gemini model internally \u2014 it never refuses a wallet-scoped query","and always calls a tool.","NOT in scope: market-wide token data (\u2192 token-agent), NFT current holdings (\u2192 nft-agent),","pool analytics or a position looked up by its NUMERIC NFT id with no wallet (\u2192 pool-subgraph/pool-agent)."].join(" "),toolNames:[...io],systemPrompt:ia,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var aa=`You are the Token domain expert. You answer market-wide token questions, not wallet-specific ones.
336
337
 
337
338
  SPECIALISED TOOLS (prefer these when intent matches):
338
339
  - get-token-info: metadata (name, symbol, decimals, address, logo)
@@ -373,13 +374,12 @@ GENERAL RULES:
373
374
  - Never repeat a tool call with identical arguments.
374
375
  - Answer in the user's language. Do not mention tool names.
375
376
 
376
- Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea. `,Mn=["get-token-info","get-token-holders","get-token-analytics","get-token-score","get-trending-tokens","get-top-gainers","gemini-search-ai"];function un(c,e,t){return new j({name:"token-agent",domain:"token",capability:"look up token info, prices, analytics, holders, trending tokens and top gainers",description:["Market-wide token data. Specialised tools cover metadata, holders, analytics, risk score,","trending, and top gainers. For token category/theme queries (meme, AI, gaming, L2, RWA),","any token question without a direct tool, this agent falls back to a","search-grounded Gemini model internally \u2014 it never refuses a token query and always calls a tool.","NOT in scope: wallet balances or transfer history (\u2192 wallet-agent), NFT data (\u2192 nft-agent)."].join(" "),toolNames:[...Mn],systemPrompt:wa,cortexFallbackTool:"gemini-search-ai",llm:c,registry:e,options:t})}var ka=`You are the NFT domain expert. You answer questions about NFT holdings and metadata, not transfer history.
377
+ Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea. `,ao=["get-token-info","get-token-holders","get-token-analytics","get-token-score","get-trending-tokens","get-top-gainers","gemini-search-ai"];function Un(l,e,t){return new j({name:"token-agent",domain:"token",capability:"look up token info, prices, analytics, holders, trending tokens and top gainers",description:["Market data for a SPECIFIC named token (by symbol or address): metadata, price, holders, analytics,","and risk score \u2014 plus market-wide RANKINGS: trending tokens and top gainers. For a token question","without a direct structured tool, this agent falls back to a search-grounded Gemini model internally \u2014","it never refuses a single-token query and always calls a tool.","NOT in scope: wallet balances or transfer history (\u2192 wallet-agent), NFT data (\u2192 nft-agent),",'broad CATEGORY / THEME discovery lists \u2014 "meme tokens", "AI tokens", "gaming / L2 / RWA tokens" (\u2192 ai-agent).'].join(" "),toolNames:[...ao],systemPrompt:aa,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var la=`You are the NFT domain expert. You answer questions about NFT holdings and metadata, not transfer history.
377
378
 
378
379
  SPECIALISED TOOLS (prefer these when intent matches):
379
380
  - get-wallet-nfts: user wants to view / browse their OWN NFTs / holdings \u2014 returns a fixed website notice
380
381
  - get-nft-metadata: user asks about a SPECIFIC NFT (traits, rarity, floor, recent sales) \u2014 answers from LIVE web data; you build a self-contained \`prompt\`
381
382
  - get-nft-contract-info: user asks about a COLLECTION / contract (floor, supply, holders, volume, socials) \u2014 answers from LIVE web data; you build a self-contained \`prompt\`
382
- - open-send-nft-form: user wants to SEND / transfer an NFT ("send nft", "transfer nft", "g\u1EEDi nft") \u2014 opens a pre-filled SendNftForm
383
383
 
384
384
  get-wallet-nfts (NOTICE TOOL):
385
385
  - Returns a fixed website notice. Follow the tool result's _instructions: reply with ONE sentence in the user's language and keep the Markdown link's URL exactly as-is.
@@ -390,13 +390,6 @@ get-nft-metadata / get-nft-contract-info (LIVE NFT INFO \u2014 fetched via web s
390
390
  - Keep collection names, contract addresses, and token ids verbatim from the user. Do NOT scope by chain \u2014 these tools take no chain; let Gemini find the collection/NFT across chains.
391
391
  - Present the returned info naturally in the user's language per the result's _instructions \u2014 never just point them to a website.
392
392
 
393
- SEND NFT (open-send-nft-form):
394
- - Call it for ANY NFT send/transfer intent, EVEN IF the user did not name a contract, token id, NFT name, or recipient. The tool resolves missing identifiers from the wallet's NFT holdings and returns a fixed website notice when more than one match exists.
395
- - Pass only what the user gave (contract_address, token_id, nft_name, to_address, amount for ERC-1155). Leave the rest blank \u2014 never invent values.
396
- - Only pass to_address if the user explicitly typed a recipient address in this turn. If they did not mention one, leave to_address blank \u2014 never fabricate it from the connected wallet, prior context, holdings, or earlier tool results.
397
- - Distinguish carefully: contract_address = the NFT COLLECTION contract (which NFT); to_address = the RECIPIENT wallet (who receives). They are NEVER the same field. Map by the user's wording: "to X" / "g\u1EEDi \u0111\u1EBFn X" / "cho X" \u2192 to_address; "contract X" / "collection X" / "from X" \u2192 contract_address. A bare 0x address with no preposition is ambiguous \u2014 leave both blank rather than guessing.
398
- - Call this tool ONCE per turn. After it returns (form, website notice, or error), do NOT call it again in the same turn \u2014 even if the result resolved extra fields like contract_address. Just produce the user-facing reply per the result's _instructions.
399
-
400
393
  AI FALLBACK (mandatory when no specialised tool fits):
401
394
  - gemini-search-ai \u2014 a search-grounded Gemini model that handles EVM NFT queries.
402
395
  - Use for: NFT category / theme queries (top PFP, trending mints, gaming NFTs), market-wide NFT
@@ -421,16 +414,14 @@ using up-to-date market data. For each: collection name, contract address, floor
421
414
 
422
415
  SCOPE NOTES:
423
416
  - "What NFTs do I own?" \u2192 handle here.
424
- - "Send / transfer an NFT" (the action) \u2192 handle here (open-send-nft-form).
417
+ - "Send / transfer an NFT" (the action) \u2192 NOT here; that is a wallet action (wallet-action-agent).
425
418
  - "Did I send / receive an NFT?" (past events) \u2192 not here, that is transfer history (wallet-agent).
426
419
 
427
420
  GENERAL RULES:
428
- - Pass "chain" as a hex id (default 0x1) ONLY for open-send-nft-form. get-wallet-nfts takes no arguments, and get-nft-metadata / get-nft-contract-info take only a \`prompt\` (no chain) \u2014 never pass chain to them.
421
+ - get-wallet-nfts takes no arguments; get-nft-metadata / get-nft-contract-info take only a \`prompt\` (no chain) \u2014 never pass chain to any tool.
429
422
  - For a specific NFT, use get-nft-metadata and build a prompt embedding its contract address + token id.
430
423
  - One tool per turn. Never repeat a tool call with identical arguments.
431
- - Answer in the user's language. Do not mention tool names.
432
-
433
- Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea.`,qn=["get-wallet-nfts","get-nft-metadata","get-nft-contract-info","open-send-nft-form","gemini-search-ai"];function dn(c,e,t){return new j({name:"nft-agent",domain:"nft",capability:"send or transfer an NFT",description:["NFT holdings, metadata, and sending. Specialised tools cover NFT holdings, single-NFT metadata,","collection / contract info, and sending/transferring an NFT. For NFT category, theme, or market-wide","questions without a direct tool, this agent falls back to a search-grounded Gemini model internally \u2014","it never refuses an NFT query and always calls a tool.",'Handles the SEND / TRANSFER-an-NFT action ("send nft", "g\u1EEDi nft"); but past NFT transfer history (events) \u2192 wallet-agent.',"Key distinction: nft-agent = NFT holdings / details / send; wallet-agent = NFT TRANSFER-EVENT history."].join(" "),toolNames:[...qn],systemPrompt:ka,cortexFallbackTool:"gemini-search-ai",llm:c,registry:e,options:t})}var va=`You are the Crypto AI fallback expert powered by a search-grounded Gemini model.
424
+ - Answer in the user's language. Do not mention tool names.`,lo=["get-wallet-nfts","get-nft-metadata","get-nft-contract-info","gemini-search-ai"];function Nn(l,e,t){return new j({name:"nft-agent",domain:"nft",capability:"look up NFT holdings, metadata and collection info",description:["Read-only NFT lookups: holdings, single-NFT metadata, and collection / contract info.","For NFT category, theme, or market-wide questions without a direct tool, this agent falls back to a","search-grounded Gemini model internally \u2014 it never refuses an NFT query and always calls a tool.","NOT in scope: SENDING / transferring an NFT (the action \u2192 wallet-action-agent);","past NFT transfer history / events (\u2192 wallet-agent)."].join(" "),toolNames:[...lo],systemPrompt:la,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var ca=`You are the Crypto AI fallback expert powered by a search-grounded Gemini model.
434
425
 
435
426
  You answer ANY blockchain / crypto / token / NFT / DeFi / on-chain question that does not have a
436
427
  direct structured tool in the other agents. The underlying model has live web-search grounding \u2014
@@ -449,7 +440,7 @@ ROUTING:
449
440
  RULES:
450
441
  - ALWAYS call the tool \u2014 NEVER refuse, NEVER answer without calling it.
451
442
  - NEVER retry with the same prompt if the call fails \u2014 return what you have.
452
- - Answer in the user's language. Do NOT mention tool names.`,Fn=["gemini-search-ai"];function mn(c,e,t){return new j({name:"ai-agent",domain:"ai",capability:"answer general crypto, blockchain and DeFi questions, using up-to-date web search when needed",description:["Catch-all crypto / blockchain expert powered by a search-grounded Gemini model (live Google","Search). USE THIS AGENT whenever the query is about blockchain, crypto, tokens, NFTs, DeFi,","wallets, on-chain data, smart contracts, or any supported EVM chain BUT no other agent","(wallet-agent, token-agent, nft-agent, pool-agent) has a direct structured tool for it.","Scope examples: (1) token categories or themes \u2014 meme tokens, AI tokens, gaming tokens, L2 tokens, RWA;",'(2) protocol-specific questions \u2014 "how does X protocol work", "what happened to Y";',"(3) cross-contract or exploratory EVM analysis spanning many contracts;","(4) any open-ended on-chain question without a direct structured tool.","Prefer the specific agents when they clearly match (wallet balances \u2192 wallet-agent,","single-token info/analytics \u2192 token-agent, NFT holdings/metadata \u2192 nft-agent, DEX pools \u2192 pool-agent).","But for anything crypto-related that falls outside those, route HERE \u2014 do not return empty."].join(" "),toolNames:[...Fn],systemPrompt:va,cortexFallbackTool:"gemini-search-ai",llm:c,registry:e,options:t})}var Ta=`You are the Pool / DEX Liquidity domain expert.
443
+ - Answer in the user's language. Do NOT mention tool names.`,co=["gemini-search-ai"];function In(l,e,t){return new j({name:"ai-agent",domain:"ai",capability:"answer general crypto, blockchain and DeFi questions, using up-to-date web search when needed",description:["Catch-all crypto / blockchain expert powered by a search-grounded Gemini model (live Google","Search). USE THIS AGENT whenever the query is about blockchain, crypto, tokens, NFTs, DeFi,","wallets, on-chain data, smart contracts, or any supported EVM chain BUT no other agent","(wallet-agent, token-agent, nft-agent, pool-agent) has a direct structured tool for it.","Scope examples: (1) token categories or themes \u2014 meme tokens, AI tokens, gaming tokens, L2 tokens, RWA;",'(2) protocol-specific questions \u2014 "how does X protocol work", "what happened to Y";',"(3) cross-contract or exploratory EVM analysis spanning many contracts;","(4) any open-ended on-chain question without a direct structured tool.","Prefer the specific agents when they clearly match (wallet balances \u2192 wallet-agent,","single-token info/analytics \u2192 token-agent, NFT holdings/metadata \u2192 nft-agent, DEX pools \u2192 pool-agent).","But for anything crypto-related that falls outside those, route HERE \u2014 do not return empty."].join(" "),toolNames:[...co],systemPrompt:ca,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var ua=`You are the Pool / DEX Liquidity domain expert.
453
444
 
454
445
  You answer questions about decentralized exchange liquidity pools \u2014 specifically Uniswap V2/V3/V4 pools across EVM chains \u2014 AND you guide the user through providing liquidity to a pool.
455
446
 
@@ -461,17 +452,28 @@ CAPABILITIES (tools you own):
461
452
  - Pool search by token symbol/name/address ("find WBTC pools on Optimism", "USDC/ETH pools on Arbitrum", "pools containing PEPE")
462
453
  - Lookup by single 0x address \u2014 V2/V3/V4 pool detail OR pool list for a token, when the user is unsure which kind it is ("what's at 0x88e6...", "tell me about this address")
463
454
  - Yield estimation for a deposit ("n\u1EBFu t\xF4i b\u1ECF 1000$ v\xE0o pool USDC/WETH 0.05% th\xEC m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "if I put $500 into this pool how much do I earn per day?", "APR of WBTC/ETH 0.3% on Arbitrum", "daily income for 1 ETH in this pool")
455
+ - Concentrated-liquidity price-range candidates for a token pair, from the CoinPool platform ("what price range for ETH/USDC?", "best range for USDC/WETH", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC", "which range should I pick?")
464
456
  - Open the Add-Liquidity form for a specific pool ("add liquidity USDC/WETH 0.05% Base", "I want to provide liquidity", "farm this pool", "stake LP", "deposit into this pool", "cung c\u1EA5p thanh kho\u1EA3n", "th\xEAm thanh kho\u1EA3n")
465
457
  - Preview the add-liquidity transaction once the user fills the form (amount + min/max price)
466
458
  - Report the on-chain result after the user broadcasts the signed transaction
459
+ - Manage an EXISTING position \u2014 collect earnings / claim fees, or close / remove / withdraw the pair ("collect earnings", "claim my fees", "close the pair", "close my position", "remove liquidity", "thu ph\xED", "r\xFAt l\xE3i", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n") \u2192 call manage-liquidity-redirect (it returns the CoinPool management link; the action is done there, not in-app)
460
+
461
+ AI FALLBACK (mandatory when no structured tool above fits):
462
+ - pool-fallback-ai \u2014 a search-grounded master liquidity-pool analyst that answers ANY Uniswap / DeFi pool question.
463
+ - Use it for broad, conceptual, strategic, or protocol-level pool questions none of the structured tools can serve ("how do Uniswap V3 pools work", "what is concentrated liquidity", "is Uniswap safe", "Uniswap vs Curve", "narrow vs wide range strategy").
464
+ - You MUST act via a tool every turn. NEVER answer a pool question from your own knowledge, and NEVER stop to ask "which chain?" \u2014 if a structured tool fits, call it (defaulting the chain); only if none fits, call pool-fallback-ai.
465
+ - EXCEPTION \u2014 earnings/yield projection: use estimate-pool-yield, NEVER pool-fallback-ai.
466
+ - EXCEPTION \u2014 price-range questions: use get-pool-price-ranges, NEVER pool-fallback-ai.
467
+ - Build the fallback prompt as a clear, self-contained English instruction with the chain and any token symbols / addresses embedded (the model does not see this conversation). Defaults when vague: chain = the connected chain (else Ethereum), count = top 10, time = last 24h, sort = 24h volume for "top / best / trending".
467
468
 
468
469
  OUT OF SCOPE \u2014 do NOT handle these (route them elsewhere):
469
- - "my LP positions", "my liquidity", "my DeFi positions" \u2192 wallet-agent owns wallet-scoped DeFi data
470
+ - "my LP positions", "my liquidity", "my DeFi positions" \u2192 wallet-agent owns wallet-scoped DeFi data (VIEWING position data only). NOTE: an explicit request to ACT on a position \u2014 collect earnings / close the pair / remove liquidity \u2014 is handled HERE via manage-liquidity-redirect, NOT routed to wallet-agent.
470
471
  - "what is USDC", "token price", "trending tokens" \u2192 token-agent
471
472
  - "my NFTs", "NFT collection" \u2192 nft-agent
472
473
 
473
474
  RULES:
474
- - ALWAYS pass "chain" as a hex id; default to "0x1" (Ethereum) when not specified.
475
+ - ALWAYS pass "chain" as a hex id; default to the connected chain (from User context), else "0x1" (Ethereum). NEVER ask the user "which chain?" \u2014 pick the default and call the tool.
476
+ - NEVER answer the first turn with a clarifying question or plain text. A bare, vague request \u2014 "show pool", "show pools", "pools", "show me pools", "xem pool", "danh s\xE1ch pool" with NO token and NO chain \u2014 maps to get-top-pools on the default chain. Call it immediately; do NOT ask what chain or what pool they mean.
475
477
  - Default protocolVersion to "V3" for both top-pools and search-pools unless the user explicitly asks for V2, V4, or all versions ("ALL").
476
478
  - Default sortBy to "tvl" unless the user asks about volume, activity, or yield. Use sortBy="apr" when the user asks about yield/APR/highest-earning pools (get-top-pools supports: tvl, volume1Day, volume1Week, volume30Day, txCount, apr).
477
479
  - Use ONE tool per turn unless the query asks for genuinely independent data (e.g. two different chains).
@@ -483,7 +485,14 @@ TOOL SELECTION (top-pools vs search-pools vs pool-detail):
483
485
  - "get-top-pools" \u2014 use ONLY when the user asks for the chain-wide ranking with NO specific token mentioned. Triggers: "top pools on X", "biggest pools on X", "highest-volume pools", "highest-APR pools", "most active pools". The result is the network-level leaderboard. get-top-pools CANNOT filter by token.
484
486
  - "search-pools" \u2014 use whenever the user names ONE specific token (or a free-text query) and wants to see pools related to it. Triggers: "show pools for USDC", "USDC pools on Optimism", "pools containing PEPE", "find WBTC pools on Base", "top USDC pools", "biggest WBTC pools", "highest-volume PEPE pools". Words like "top", "biggest", "best", "highest" do NOT promote this to get-top-pools \u2014 if any token symbol is named, it stays search-pools (then sort/rank the response yourself by 24h volume desc when the user asked for "top/biggest"). One-token queries ALWAYS map to search-pools, NEVER to get-top-pools.
485
487
  - "get-pool-detail" \u2014 use when the user names a SPECIFIC POOL by token pair (and optionally fee tier): "USDC/WETH 0.05% on Base", "details of WBTC/USDC pool". Two symbols \u2192 pool detail.
486
- - Quick decision: count token symbols in the user's request. 0 symbols \u2192 get-top-pools. 1 symbol \u2192 search-pools (regardless of words like "top"/"biggest"). 2 symbols \u2192 get-pool-detail. A 0x address \u2192 lookup-pool-by-address.
488
+ - "get-pool-price-ranges" \u2014 use when the user names a token PAIR and asks specifically about PRICE RANGES / which range to pick / best concentrated range ("best range for ETH/USDC", "what price range should I use?", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1", "kho\u1EA3ng gi\xE1 n\xE0o t\u1ED1t nh\u1EA5t"). Pass tokens=[sym0, sym1] and chain. This is the CoinPool range-suggestion flow \u2014 NOT for "show me ETH/USDC pools" (that stays get-pool-detail / search-pools).
489
+ - Quick decision: count token symbols in the user's request. 0 symbols \u2192 get-top-pools. 1 symbol \u2192 search-pools (regardless of words like "top"/"biggest"). 2 symbols \u2192 get-pool-detail (or get-pool-price-ranges when the ask is explicitly about price ranges). A 0x address \u2192 lookup-pool-by-address.
490
+
491
+ COINPOOL RANGE GUIDANCE (when using get-pool-price-ranges):
492
+ - The APR in each entry is the APR earned ONLY within that specific price range. NEVER present it as the overall pool APR.
493
+ - Always show each entry's fee tier (the "fee" field, e.g. "0.3%") alongside its APR and min\u2013max range, e.g. "Fee 0.3% \xB7 APR 14.3% (range: 1800 \u2013 2200 USDC/ETH)".
494
+ - When suggesting the best range, point to the highest-APR entry and note that narrower ranges = higher concentration = higher returns but more risk of going out of range.
495
+ - If no CoinPool range data is returned, say so plainly and offer the pool's overall stats via get-pool-detail instead.
487
496
 
488
497
  POOL DETAIL FLOW:
489
498
  - "get-pool-detail" identifies the pool BY TOKEN PAIR, never by address. Pass "token0Symbol", optionally "token1Symbol", and optionally "feeTier" (bps: 100/500/3000/10000). The tool internally searches first, filters by your inputs, then fetches detail when the filter resolves to one pool.
@@ -498,7 +507,7 @@ ADDRESS LOOKUP FLOW:
498
507
  - If the user already says "this is a pool address" or "this is a token address", you can still use this tool \u2014 it works for either case.
499
508
  - Use "get-pool-detail" (token-pair flow) when the user describes a pool BY SYMBOLS, and "lookup-pool-by-address" when they paste a raw address.
500
509
 
501
- YIELD ESTIMATION FLOW (estimate_pool_yield):
510
+ YIELD ESTIMATION FLOW (estimate-pool-yield):
502
511
 
503
512
  Intent recognition \u2014 the user wants a yield estimate when they say things like:
504
513
  "n\u1EBFu t\xF4i b\u1ECF X$ v\xE0o pool A/B th\xEC m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "if I put $X into pool A/B how much do I earn per day?",
@@ -506,7 +515,7 @@ Intent recognition \u2014 the user wants a yield estimate when they say things l
506
515
  "daily/weekly/monthly earnings", "how much will I make if I deposit X dollars?", "l\u1EE3i nhu\u1EADn \u01B0\u1EDBc t\xEDnh", "yield estimate".
507
516
  These are INFORMATION questions \u2014 the user has NOT asked to actually deposit yet.
508
517
 
509
- CRITICAL \u2014 minimize back-and-forth. Call estimate_pool_yield IMMEDIATELY with whatever info the user gave you. The tool handles missing info on its own:
518
+ CRITICAL \u2014 minimize back-and-forth. Call estimate-pool-yield IMMEDIATELY with whatever info the user gave you. The tool handles missing info on its own:
510
519
  - ONE token mentioned (e.g. "ETH yield?", "l\u1EDDi bao nhi\xEAu khi farm USDC"): pass just token0Symbol. The tool auto-picks the highest-volume pool. Do NOT ask the user for the other token.
511
520
  - TWO tokens, no fee tier (e.g. "USDC/WETH yield"): pass both symbols. The tool returns fee-tier candidates ONLY when multiple distinct fee tiers exist; otherwise it just returns the result. Ask the user to pick a fee tier ONLY when the tool returns candidates.
512
521
  - No deposit amount: just call the tool. It defaults to $1000 and marks the result as a per-$1000 example. Do NOT ask the user for the deposit amount upfront.
@@ -530,6 +539,7 @@ Intent recognition \u2014 the user wants to add liquidity whenever they say (in
530
539
  "add liquidity", "provide liquidity", "add LP", "supply LP", "deposit into pool", "stake into pool", "farm this pool",
531
540
  "th\xEAm thanh kho\u1EA3n", "cung c\u1EA5p thanh kho\u1EA3n", "b\u1ECF ti\u1EC1n v\xE0o pool", "farm pool", "v\xE0o pool", "add pool", "c\u1EA5p v\u1ED1n pool".
532
541
  Treat all of these as the same intent. Words like "buy" / "swap" / "trade" are NOT this intent \u2014 those go to the token agent or to a swap flow.
542
+ A bare add-liquidity request with NO pool/pair named ("i want to add pool", "add pool", "add liquidity", "i want to add liquidity pool", "th\xEAm thanh kho\u1EA3n", "cung c\u1EA5p thanh kho\u1EA3n") is STILL this intent: NEVER reply in text asking which pool, and NEVER fall back to pool-fallback-ai for it \u2014 IMMEDIATELY call get-top-pools with sortBy="apr" on the default chain, present the candidates with an expert "which pool to add" read, and ask the user to pick one to continue the add-liquidity flow. When the user names exactly ONE token but not the pair ("add liquidity with USDC", "th\xEAm thanh kho\u1EA3n USDC"), call search-pools instead.
533
543
 
534
544
  Context carry-over (IMPORTANT):
535
545
  When the user says "add this pool", "farm this", "I want to add liquidity to this pool" \u2014 referring to a pool already shown in the CURRENT conversation \u2014 extract token0Symbol, token1Symbol, and feeTier directly from the previous tool result (pool.token0.symbol, pool.token1.symbol, pool.feeTierBps) WITHOUT calling any search tool again. Call open-add-liquidity-form immediately with those values.
@@ -538,9 +548,9 @@ Required inputs for open-add-liquidity-form:
538
548
  - token0Symbol, token1Symbol, feeTier (bps: 100/500/3000/10000), chain.
539
549
  - Optional: prefillNativeAmountWei \u2014 pass when the user already named an amount (see "Amount-first inputs" below).
540
550
  - If any required field is missing, do NOT call this tool yet. Resolve the missing piece first:
541
- * Pair given but no fee tier \u2192 call get-pool-detail with just the pair so the user can pick a fee tier from the candidates.
542
- * Only one symbol \u2192 ask the user for the other token (or call search-pools to suggest pools).
543
- * No pool at all ("I want to farm something on Base") \u2192 call get-top-pools sortBy="apr" first, list the candidates, ask the user to pick.
551
+ * Pair given but no fee tier \u2192 call open-add-liquidity-form with just the pair (no feeTier). If multiple fee tiers exist it returns candidates; present them as a numbered list and ask the user to pick a tier. (Only fall back to get-pool-detail for a pure "show me this pool" info question.)
552
+ * Only one symbol \u2192 call search-pools (returns pools containing that token); list them and ask the user to pick. Do NOT ask the user to type the other token from scratch.
553
+ * No pool at all ("I want to farm something on Base", "add pool") \u2192 call get-top-pools sortBy="apr" first, present the candidates with an expert pick, and ask the user to choose.
544
554
 
545
555
  Amount-first inputs (e.g. "add 0.1 ETH to a pool", "th\xEAm 0.5 ETH v\xE0o pool USDC/WETH 0.05% Base", "add $10 to this pool", "10 dollars"):
546
556
  - The user often supplies the AMOUNT before (or together with) the pool. Remember it across turns.
@@ -563,6 +573,13 @@ Price-range prefill (open-add-liquidity-form) \u2014 pass these to skip the user
563
573
  Turn 1: open-add-liquidity-form \u2192 renders AddLiquidityForm UI (pool info + native input + price-range inputs)
564
574
  Turn 2: preview-add-liquidity \u2192 renders ConfirmAddLiquidityTx UI (expected amounts + unsigned tx)
565
575
 
576
+ FAST PATH \u2014 skip the form and call preview-add-liquidity DIRECTLY (do NOT open-add-liquidity-form first) the moment you ALREADY have ALL of these, whether the user typed them in one message or they carry over from context:
577
+ \u2022 a concrete pool ADDRESS (0x\u2026 \u2014 given by the user OR from a prior tool result's pool.address), AND
578
+ \u2022 a native amount, AND
579
+ \u2022 BOTH min and max price.
580
+ The form's ONLY job is to COLLECT those inputs; when they are already provided, opening it just stalls the user. Example that MUST go straight to preview-add-liquidity: "add liquidity to USDC/WETH on Optimism with 0.0000174 ETH, price range 0.000533 to 0.000651, pool=0x\u2026". Pass poolAddress, chain, minPrice, maxPrice, nativeAmount as-is.
581
+ Only when you do NOT have a concrete pool address (just token symbols / a fee tier) do you go through open-add-liquidity-form first \u2014 preview-add-liquidity REQUIRES the exact pool address.
582
+
566
583
  After open-add-liquidity-form returns (Turn 1):
567
584
  - The FE renders the form. Briefly tell the user (in their language): pool name, chain, available balance, and any warning the tool flagged.
568
585
  - Warning="no_balance" \u2192 tell them they must top up before they can add.
@@ -574,6 +591,7 @@ When the user submits the form (Turn 2 \u2192 preview-add-liquidity):
574
591
  - Required: poolAddress, chain, minPrice, maxPrice, nativeAmountWei.
575
592
  - Convert the user's native amount to wei: floor(amount \xD7 10^18) as a plain integer string. Example: 0.1 \u2192 "100000000000000000".
576
593
  - Pass minPrice and maxPrice as plain decimal numbers in the SAME unit as pool.currentPrice. Do NOT convert to ticks \u2014 the BE handles tick conversion.
594
+ - Copy the user's min/max price digits VERBATIM \u2014 every digit and every leading zero. NEVER add or drop a zero, round, or rescale (e.g. "0.000533" must stay 0.000533, not 0.0000533). Tiny decimals are easy to mis-transcribe; pass the user's exact characters.
577
595
  - The tool returns an unsigned tx (in props.unsignedTx) plus expected token0/token1 amounts. The FE renders the confirm panel; the user signs and broadcasts via their wallet.
578
596
 
579
597
  NOTE: many chat clients submit form/confirm panels directly to the BE tool (agent.invokeTool, deterministic path), bypassing the LLM. When you DO see a conversational confirm like "OK, 0.1 ETH range 1500\u20132200" you handle it as above.
@@ -590,7 +608,7 @@ State awareness:
590
608
 
591
609
  Never fabricate pool addresses, tick numbers, prices, or NFT ids. Every value must come from a tool call this turn or the immediately preceding turn.
592
610
 
593
- Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea .`,$n=["get-top-pools","get-pool-detail","search-pools","lookup-pool-by-address","open-add-liquidity-form","preview-add-liquidity","estimate_pool_yield"];function pn(c,e,t){return new j({name:"pool-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Handles questions about decentralized exchange liquidity pools \u2014 Uniswap V2/V3/V4 across EVM chains \u2014","AND walks the user through ADDING LIQUIDITY to a pool (provide LP / farm / stake / deposit / cung c\u1EA5p thanh kho\u1EA3n).","Scope: (1) top pools by chain \u2014 biggest pools ranked by TVL, volume, or transaction count;","(2) pool composition \u2014 which token pairs dominate liquidity on a given network;","(3) pool-level analytics \u2014 fee tier, rolling volume buckets (1d/1w/30d), tx count, both tokens;","(4) pool detail by token pair (and optional fee tier) \u2014 full stats for a single pool including TVL, 24h volume, fees, APR estimate, token reserves, and weekly volume history;","(5) pool search \u2014 find pools that match a free-text query (token symbol, token name, or pool address) on a given chain;","(6) single-address lookup \u2014 when the user pastes one 0x address without saying whether it is a pool or a token, resolve both;",'(7) YIELD ESTIMATION \u2014 estimate daily/weekly/monthly/yearly fee income for a given USD deposit into a specific pool ("if I put $1000 into USDC/WETH 0.05%, how much do I earn per day?", "b\u1ECF 500$ v\xE0o pool n\xE0y l\u1EDDi bao nhi\xEAu?");',"(8) ADD LIQUIDITY \u2014 open the AddLiquidityForm UI for a chosen pool, then build the unsigned mint transaction once the user confirms amount and price range.","NOT in scope: wallet-specific LP positions or DeFi holdings the user already owns (\u2192 wallet-agent),","token metadata or token-level market data (\u2192 token-agent), NFT data (\u2192 nft-agent).",'Key distinction from token-agent: pool-agent answers "which POOLS are biggest / most active" and handles "I want to add LP",','while token-agent answers "what is this TOKEN" and "what is the market doing for this TOKEN".'].join(" "),toolNames:[...$n],systemPrompt:Ta,llm:c,registry:e,options:t})}var Sa=`You are the Uniswap V3 Subgraph DEX-pool expert.
611
+ Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea .`,uo=["get-top-pools","get-pool-detail","search-pools","lookup-pool-by-address","open-add-liquidity-form","preview-add-liquidity","estimate-pool-yield","get-pool-price-ranges","manage-liquidity-redirect","pool-fallback-ai"];function Ln(l,e,t){return new j({name:"pool-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Handles questions about decentralized exchange liquidity pools \u2014 Uniswap V2/V3/V4 across EVM chains \u2014","AND walks the user through ADDING LIQUIDITY to a pool (provide LP / farm / stake / deposit / cung c\u1EA5p thanh kho\u1EA3n).","Scope: (1) top pools by chain \u2014 biggest pools ranked by TVL, volume, or transaction count;","(2) pool composition \u2014 which token pairs dominate liquidity on a given network;","(3) pool-level analytics \u2014 fee tier, rolling volume buckets (1d/1w/30d), tx count, both tokens;","(4) pool detail by token pair (and optional fee tier) \u2014 full stats for a single pool including TVL, 24h volume, fees, APR estimate, token reserves, and weekly volume history;","(5) pool search \u2014 find pools that match a free-text query (token symbol, token name, or pool address) on a given chain;","(6) single-address lookup \u2014 when the user pastes one 0x address without saying whether it is a pool or a token, resolve both;",'(7) YIELD ESTIMATION \u2014 estimate daily/weekly/monthly/yearly fee income for a given USD deposit into a specific pool ("if I put $1000 into USDC/WETH 0.05%, how much do I earn per day?", "b\u1ECF 500$ v\xE0o pool n\xE0y l\u1EDDi bao nhi\xEAu?");',"(8) ADD LIQUIDITY \u2014 open the AddLiquidityForm UI for a chosen pool, then build the unsigned mint transaction once the user confirms amount and price range.","(9) MANAGE / ACT ON AN EXISTING POSITION \u2014 closing / removing / withdrawing the pair OR collecting / claiming earned fees on the user's OWN position",'("close my pool", "close my position", "remove liquidity", "withdraw liquidity", "collect my fees", "claim earnings", "\u0111\xF3ng pool", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "thu ph\xED") \u2014 handled HERE (returns the CoinPool management link).',`NOT in scope: VIEWING a wallet's OWN LP / DeFi position DATA \u2014 "my positions", "my position on Uniswap", "my Uniswap positions",`,'"what I have on Aave", any read-only "my/their positions" query (with or without a protocol named) (\u2192 wallet-agent).',`IMPORTANT distinction: VIEWING / listing one's own positions \u2192 wallet-agent; ACTING on one (close / remove / withdraw / collect fees) \u2192 pool-agent (here), even when phrased as "my pool" / "my position".`,"token metadata or token-level market data (\u2192 token-agent), NFT data (\u2192 nft-agent).",'Key distinction from token-agent: pool-agent answers "which POOLS are biggest / most active" and handles "I want to add LP",','while token-agent answers "what is this TOKEN" and "what is the market doing for this TOKEN".'].join(" "),toolNames:[...uo],systemPrompt:ua,cortexFallbackTool:"pool-fallback-ai",llm:l,registry:e,options:t})}var da=`You are the Uniswap V3 Subgraph DEX-pool expert.
594
612
 
595
613
  You answer questions about Uniswap V3 liquidity pools using The Graph subgraphs. APR values are enriched from DefiLlama Yields. Concentrated-liquidity price-range data comes from the CoinPool platform.
596
614
 
@@ -680,11 +698,12 @@ YIELD / EARNINGS PROJECTION ("how much would I earn"):
680
698
  FOLLOW-UPS / CONTINUATIONS:
681
699
  - Short replies like "yes", "tell me more", "the first one", "show ranges" refer back to the previous turn. Extract tokens/chains/pool addresses from the prior assistant message and call the appropriate tool. NEVER ask for clarification when history clearly shows what was discussed.
682
700
 
683
- NEVER fabricate pool addresses, token prices, APRs, or position ids. Every value must come from a tool call this turn or the immediately preceding turn.`,sr=["subgraph-search-pools","subgraph-trending-pools","subgraph-pool-by-address","subgraph-pool-by-position-id","subgraph-position-detail","subgraph-coinpool-pairs","subgraph-add-pool","pool-fallback-ai"];function uo(c,e,t){return new j({name:"pool-subgraph-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Answers questions about Uniswap V3 liquidity pools using The Graph subgraphs as the primary source","(APR is enriched from DefiLlama Yields; concentrated-liquidity price ranges come from CoinPool).","Scope: (1) pool search by token symbols on one or more EVM chains, with TVL/APR/fee filters and sort by tvl/volume/apr/fee/liquidity;","(2) trending pools ranked by volume past day on a chain;","(3) pool detail for a specific 0x pool address;","(4) lookup the underlying pool for a Uniswap V3 NFT position id (numeric, e.g. 962961);","(5) full position detail (deposits, withdrawals, collected fees) for a numeric position id;","(6) CoinPool concentrated-liquidity price-range candidates with per-range APR for a token pair;","(7) the add-liquidity / add-pool / create-pair INTENT \u2014 resolves the pool (by address or token pair) and surfaces the add-liquidity website link.",'NOT in scope: wallet-wide LP holdings ("my positions"), sending/transferring LP NFTs, building/signing the add-liquidity transaction itself,',"token metadata (\u2192 token-agent), NFT data (\u2192 nft-agent).","Prefer this subagent over pool-agent when the deployment is configured to use Subgraph data (the two are mutually exclusive at config time)."].join(" "),toolNames:[...sr],systemPrompt:Sa,cortexFallbackTool:"pool-fallback-ai",llm:c,registry:e,options:t})}var Aa=`Call exactly ONE tool every turn \u2014 ALWAYS, even for a bare verb with no details ("send token", "buy", "approve"). Never reply in text and never ask the user for missing fields (token, amount, recipient): the tool opens a picker/form that collects them.
701
+ NEVER fabricate pool addresses, token prices, APRs, or position ids. Every value must come from a tool call this turn or the immediately preceding turn.`,Br=["subgraph-search-pools","subgraph-trending-pools","subgraph-pool-by-address","subgraph-pool-by-position-id","subgraph-position-detail","subgraph-coinpool-pairs","subgraph-add-pool","pool-fallback-ai"];function Lo(l,e,t){return new j({name:"pool-subgraph-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Answers questions about Uniswap V3 liquidity pools using The Graph subgraphs as the primary source","(APR is enriched from DefiLlama Yields; concentrated-liquidity price ranges come from CoinPool).","Scope: (1) pool search by token symbols on one or more EVM chains, with TVL/APR/fee filters and sort by tvl/volume/apr/fee/liquidity;","(2) trending pools ranked by volume past day on a chain;","(3) pool detail for a specific 0x pool address;","(4) lookup the underlying pool for a Uniswap V3 NFT position id (numeric, e.g. 962961);","(5) full position detail (deposits, withdrawals, collected fees) for a numeric position id;","(6) CoinPool concentrated-liquidity price-range candidates with per-range APR for a token pair;","(7) the add-liquidity / add-pool / create-pair INTENT \u2014 resolves the pool (by address or token pair) and surfaces the add-liquidity website link.","Handles a position ONLY by its NUMERIC NFT id (e.g. 962961) \u2014 NEVER a wallet's own holdings.",'NOT in scope: ANY wallet-scoped LP/DeFi holdings \u2014 "my positions", "my Uniswap positions", "my position on Uniswap",','"what I have on Aave" and every "my/their" positions query (with or without a protocol named) belong to wallet-agent;',"also out of scope: sending/transferring LP NFTs, building/signing the add-liquidity transaction itself,","token metadata (\u2192 token-agent), NFT data (\u2192 nft-agent).","Prefer this subagent over pool-agent when the deployment is configured to use Subgraph data (the two are mutually exclusive at config time)."].join(" "),toolNames:[...Br],systemPrompt:da,cortexFallbackTool:"pool-fallback-ai",llm:l,registry:e,options:t})}var pa=`Call exactly ONE tool every turn \u2014 ALWAYS, even for a bare verb with no details ("send token", "send nft", "buy", "approve"). Never reply in text and never ask the user for missing fields (token, NFT, amount, recipient): the tool opens a picker/form that collects them.
684
702
 
685
703
  Tools:
686
704
  - open-send-native-form \u2014 ONLY the current chain's native coin (see "native coin" in User context)
687
705
  - open-send-token-form \u2014 ERC-20 (ANY coin that is NOT the current chain's native one)
706
+ - open-send-nft-form \u2014 send / transfer an NFT ("send nft", "transfer nft", "g\u1EEDi nft")
688
707
  - open-buy-token-form \u2014 buy a token (named OR, if none named, returns trending picks)
689
708
  - open-swap-token-form \u2014 swap a token the user ALREADY HOLDS into another ("swap USDC to USDT", "swap USDC")
690
709
  - open-approve-token-form \u2014 ERC-20 approve/revoke
@@ -692,30 +711,57 @@ Tools:
692
711
  Intent \u2192 tool:
693
712
  - "send <coin>": route by the CURRENT chain's native coin (given in User context). If <coin> equals it \u2192 open-send-native-form (native_symbol=<coin>); otherwise <coin> is an ERC-20 on this chain \u2192 open-send-token-form (token_symbol=<coin>). E.g. on BSC (native BNB): "send eth" \u2192 open-send-token-form, "send bnb" \u2192 open-send-native-form.
694
713
  - "send token" / "transfer some token" (no coin named) \u2192 open-send-token-form, leave token_symbol blank \u2192 wallet picker. ALWAYS set token_symbol whenever the user names a token.
714
+ - "send nft" / "transfer nft" / "g\u1EEDi nft" \u2192 open-send-nft-form. Call it for ANY NFT send/transfer intent, EVEN IF the user did not name a contract, token id, NFT name, or recipient \u2014 the form resolves missing identifiers from the wallet's NFT holdings.
695
715
  - "buy <token>" \u2192 open-buy-token-form (with token_symbol); "buy a token / buy trending" (no token named) \u2192 open-buy-token-form (leave token_symbol blank)
696
716
  - "swap <A> to <B>" / "\u0111\u1ED5i <A> sang <B>" / "convert/exchange <A> for <B>" \u2192 open-swap-token-form (from_symbol = A, to_symbol = B); "swap <A>" (only source named) \u2192 open-swap-token-form (from_symbol = A, leave to_symbol blank \u2192 trending picker); "swap" (nothing named) \u2192 open-swap-token-form (leave both blank \u2192 wallet picker). SWAP is when the user spends a token they hold; BUY is when they name a token to acquire and pick a wallet token to pay with.
697
717
  - "approve" \u2192 open-approve-token-form
698
718
 
699
719
  Pass only what the user gave. Leave the rest blank \u2014 the tool / form handles it. Don't invent values.
700
- NFT sends are NOT handled here \u2014 they belong to the nft-agent.
720
+
721
+ SEND NFT (open-send-nft-form) specifics:
722
+ - Pass only what the user gave (contract_address, token_id, nft_name, to_address, amount for ERC-1155). Leave the rest blank \u2014 never invent values.
723
+ - Only pass to_address if the user explicitly typed a recipient address THIS turn. If they did not, leave to_address blank \u2014 never fabricate it from the connected wallet, prior context, holdings, or earlier tool results.
724
+ - contract_address = the NFT COLLECTION contract (which NFT); to_address = the RECIPIENT wallet (who receives). They are NEVER the same field. "to X" / "g\u1EEDi \u0111\u1EBFn X" / "cho X" \u2192 to_address; "contract X" / "collection X" / "from X" \u2192 contract_address. A bare 0x address with no preposition is ambiguous \u2014 leave both blank rather than guessing.
725
+ - Call open-send-nft-form ONCE per turn; after it returns (form, website notice, or error) do NOT call it again this turn \u2014 just reply per the result's _instructions.
701
726
 
702
727
  Skip the tool ONLY if: walletAddress missing (ask to connect) \xB7 user explicitly names a chain different from userContext.chain (ask to switch).
703
728
 
704
- After the tool returns: 1 short sentence in the user's language. Don't list missing fields. Don't mention tool names.`,Wn=["open-send-native-form","open-send-token-form","open-buy-token-form","open-swap-token-form","open-approve-token-form"];function hn(c,e,t){return new j({name:"wallet-action-agent",domain:"wallet-action",capability:"help with wallet actions such as sending, buying or swapping tokens",description:["User wants to PERFORM an on-chain action (send, 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.","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, sending/transferring an NFT (\u2192 nft-agent), liquidity provisioning."].join(" "),toolNames:[...Wn],systemPrompt:Aa,mustCallTool:!0,llm:c,registry:e,options:t})}function Vn(c,e,t,n){let r=(l,u)=>{let d=n?.[l];return d===void 0?u:d},o=r("pool-subgraph",!1),s=n?.pool===!0,a=o?s:r("pool",!0),i=[];return r("wallet",!0)&&i.push(cn(c,e,t)),r("wallet-action",!0)&&i.push(hn(c,e,t)),r("token",!0)&&i.push(un(c,e,t)),r("nft",!0)&&i.push(dn(c,e,t)),a&&i.push(pn(c,e,t)),o&&i.push(uo(c,e,t)),r("ai",!0)&&i.push(mn(c,e,t)),i}var xa=`You are a response synthesizer. Given the user's question and tool execution results, produce a clear, helpful final answer.
729
+ After the tool returns: 1 short sentence in the user's language. Don't list missing fields. Don't mention tool names.`,po=["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 Dn(l,e,t){return new j({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:[...po],systemPrompt:pa,mustCallTool:!0,llm:l,registry:e,options:t})}var ma=`Call exactly ONE tool every turn \u2014 ALWAYS, even for a bare verb with no details ("send token", "send nft", "buy", "swap", "approve"). Never reply in text first and never ask the user for any details (token, NFT, amount, recipient): these actions are NOT performed in chat \u2014 the tool just tells the user they can do it directly in the app.
730
+
731
+ Tools (each only points the user to the app \u2014 none performs the action):
732
+ - open-send-native-form \u2014 ONLY the current chain's native coin (see "native coin" in User context)
733
+ - open-send-token-form \u2014 ERC-20 (ANY coin that is NOT the current chain's native one)
734
+ - open-send-nft-form \u2014 send / transfer an NFT ("send nft", "transfer nft", "g\u1EEDi nft")
735
+ - open-buy-token-form \u2014 buy a token
736
+ - open-swap-token-form \u2014 swap a token the user ALREADY HOLDS into another ("swap USDC to USDT", "swap USDC")
737
+ - open-approve-token-form \u2014 ERC-20 approve / revoke
738
+
739
+ Intent \u2192 tool:
740
+ - "send <coin>": route by the CURRENT chain's native coin (given in User context). If <coin> equals it \u2192 open-send-native-form; otherwise <coin> is an ERC-20 on this chain \u2192 open-send-token-form. E.g. on BSC (native BNB): "send eth" \u2192 open-send-token-form, "send bnb" \u2192 open-send-native-form.
741
+ - "send token" / "transfer some token" (no coin named) \u2192 open-send-token-form.
742
+ - "send nft" / "transfer nft" / "g\u1EEDi nft" \u2192 open-send-nft-form.
743
+ - "buy <token>" / "buy a token" \u2192 open-buy-token-form.
744
+ - "swap <A> to <B>" / "\u0111\u1ED5i <A> sang <B>" / "swap <A>" / "swap" \u2192 open-swap-token-form.
745
+ - "approve" / "revoke" \u2192 open-approve-token-form.
746
+
747
+ These tools take NO arguments and do NOT collect any data \u2014 they only return guidance pointing the user to the app. Just pick the tool matching the intent.
748
+
749
+ After the tool returns: reply in 1 short sentence in the user's language, telling the user they can do it in the app (include the link if one was given). Don't ask for details. Don't mention tool names, forms, or UI.`,qr=["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 Do(l,e,t){return new j({name:"wallet-action-app",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).","In this deployment the action is NOT performed in chat \u2014 this agent picks the matching tool, which only","tells the user they can do the action directly in the app (with a link when configured).",'Includes sending / transferring an NFT ("send nft", "g\u1EEDi nft", "transfer nft").',"NOT in scope: read-only wallet/token/NFT queries, past NFT transfer history / events (\u2192 wallet-agent), liquidity provisioning."].join(" "),toolNames:[...qr],systemPrompt:ma,mustCallTool:!0,llm:l,registry:e,options:t})}function mo(l,e,t,n){let r=(d,p)=>{let m=n?.[d];return m===void 0?p:m},o=r("pool-subgraph",!1),s=n?.pool===!0,i=o?s:r("pool",!0),a=r("wallet-action-app",!1),c=a?!1:r("wallet-action",!0),u=[];return r("wallet",!0)&&u.push(Rn(l,e,t)),c&&u.push(Dn(l,e,t)),a&&u.push(Do(l,e,t)),r("token",!0)&&u.push(Un(l,e,t)),r("nft",!0)&&u.push(Nn(l,e,t)),i&&u.push(Ln(l,e,t)),o&&u.push(Lo(l,e,t)),r("ai",!0)&&u.push(In(l,e,t)),u}var ha=`You are a response synthesizer. Given the user's question and tool execution results, produce a clear, helpful final answer.
705
750
 
706
751
  Rules:
707
752
  - Be concise but complete.
708
753
  - Present data in a readable format (use lists, tables, or bullet points when appropriate).
709
754
  - If tool data contains the answer, cite the relevant facts and numbers.
710
755
  - If tools returned errors, explain honestly what happened.
756
+ - Preserve any markdown links exactly as they appear in the agent reasoning or tool results \u2014 keep clickable links like [label](https://...) verbatim, including the full URL. NEVER strip a link down to plain text, drop its URL, or invent a URL that was not provided.
711
757
  - Respond in the same language as the user's message.
712
758
  - Do NOT mention internal tool names, JSON structures, or technical implementation details.
713
- `,Xt=class{llm;constructor(e){this.llm=e}async synthesise(e,t,n,r){if(!t.steps.some(p=>p.phase==="act")&&t.finalAnswer)return ar(t.finalAnswer);let s=t.steps.filter(p=>p.phase==="observe").map((p,h)=>`[Result ${h+1}]: ${p.content}`).join(`
714
- `),a=we(n),i=xe(a,8),l=(r||"").trim().toLowerCase(),u=l?`IMPORTANT: Reply in BCP-47 language "${l}" (the language the user actually typed). Tool results may contain text in other languages \u2014 ignore that and reply ONLY in "${l}".`:`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:xa,timestamp:0},...i,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",s?`Tool results:
759
+ `,gn=class{llm;constructor(e){this.llm=e}async synthesise(e,t,n,r){if(!t.steps.some(m=>m.phase==="act")&&t.finalAnswer)return Fr(t.finalAnswer);let s=t.steps.filter(m=>m.phase==="observe").map((m,g)=>`[Result ${g+1}]: ${m.content}`).join(`
760
+ `),i=Ee(n),a=Ie(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:ha,timestamp:0},...a,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",s?`Tool results:
715
761
  ${s}`:"","",u].filter(Boolean).join(`
716
- `),timestamp:Date.now()}],m=await this.llm.chat(d);return ar(m.text)}};function ar(c){return c&&c.replace(/^\[[a-z0-9-]+-agent\]\s*/i,"").replace(/\n\n\[[a-z0-9-]+-agent\]\s*/gi,`
762
+ `),timestamp:Date.now()}],p=await this.llm.chat(d);return Fr(p.text)}};function Fr(l){return l&&l.replace(/^\[[a-z0-9-]+-agent\]\s*/i,"").replace(/\n\n\[[a-z0-9-]+-agent\]\s*/gi,`
717
763
 
718
- `)}var Pa=`You are a CONTEXTUALIZER.
764
+ `)}var ga=`You are a CONTEXTUALIZER.
719
765
 
720
766
  Your ONLY job: read the conversation history + the user's latest message,
721
767
  and produce a SELF-CONTAINED version of that message.
@@ -727,7 +773,7 @@ Output STRICT JSON with this shape (no prose, no code fences):
727
773
  "rewrittenQuery": "<self-contained question in the user's language>",
728
774
  "topicChanged": <true|false>,
729
775
  "reasoning": "<one short line, user's language>",
730
- "mentionedChain": "<blockchain network the user explicitly names this turn, e.g. 'unichain', 'polygon', 'ethereum'; empty string if none>",
776
+ "mentionedChain": "<CANONICAL chain name for the network this turn refers to (see RULE 6): one of ethereum|optimism|bsc|polygon|base|arbitrum|avalanche|linea for those networks, the plain common name for any other chain (e.g. 'unichain'), or '' if none>",
731
777
  "needsWebSearch": <true|false>,
732
778
  "aboutAssistant": <true|false>
733
779
  }
@@ -756,9 +802,21 @@ Output STRICT JSON with this shape (no prose, no code fences):
756
802
  active subject (e.g. after discussing tokens, they suddenly ask about
757
803
  a random NFT collection).
758
804
  5. Never answer the user. Never produce tool calls. JSON ONLY.
759
- 6. mentionedChain: set it to the blockchain network the user explicitly names
760
- this turn (resolve it from context for follow-ups). Use the network's common
761
- name. Leave it "" when the user names no specific chain.
805
+ 6. mentionedChain: identify which blockchain network THIS turn refers to, from
806
+ ANY signal \u2014 an explicit name in any language, a hex/decimal chain id, a
807
+ chain-unique native coin (BNB\u2192bsc, MATIC/POL\u2192polygon, AVAX\u2192avalanche), OR a
808
+ block-explorer URL / domain the user pasted. Then NORMALIZE it to the network's
809
+ CANONICAL name. For the networks this assistant supports, output EXACTLY one of:
810
+ ethereum | optimism | bsc | polygon | base | arbitrum | avalanche | linea
811
+ Map explorer hosts to these, e.g.: etherscan.io\u2192ethereum, optimistic.etherscan.io\u2192optimism,
812
+ bscscan.com\u2192bsc, polygonscan.com\u2192polygon, basescan.org\u2192base, arbiscan.io\u2192arbitrum,
813
+ snowtrace.io\u2192avalanche, lineascan.build\u2192linea (a chain's explorer subdomain like
814
+ "optimistic" still maps to its canonical name "optimism"). For another EVM
815
+ network OUTSIDE that supported list, output its plain common name (e.g.
816
+ "unichain", "fantom", "cronos") so the orchestrator can report it as
817
+ unsupported. This assistant is EVM-only \u2014 do NOT try to handle non-EVM chains.
818
+ Resolve from context for follow-ups. Leave it "" when the turn names no chain.
819
+ The "$"/numbers/token symbols in a URL are NOT chains \u2014 only the network is.
762
820
  8. PRESERVE THE USER'S EXPLICIT ACTION/INTENT VERB. When THIS message states an
763
821
  action verb (add / provide / create / remove / buy / sell / swap / send /
764
822
  stake / show / compare \u2026), the rewrite MUST keep that exact intent. You may
@@ -878,7 +936,7 @@ When the user references "this transaction", "that tx", "the transaction above",
878
936
  - Scan the conversation history for tool results (role: "tool") that contain transaction data.
879
937
  - Extract the EXACT hash value (starts with "0x", 66 chars) from the most recent such result.
880
938
  - Include it verbatim in rewrittenQuery. NEVER invent or modify a hash.
881
- - If no hash is found in history, set rewrittenQuery to the original message verbatim so the subagent knows to fetch it.`,_a=`You detect the language of a single user message.
939
+ - If no hash is found in history, set rewrittenQuery to the original message verbatim so the subagent knows to fetch it.`,fa=`You detect the language of a single user message.
882
940
 
883
941
  Output STRICT JSON, no prose, no code fences:
884
942
  {"language": "<BCP-47 tag>"}
@@ -906,24 +964,24 @@ Examples:
906
964
  "\uC548\uB155\uD558\uC138\uC694" \u2192 {"language":"ko"}
907
965
  "\u043F\u0440\u0438\u0432\u0435\u0442" \u2192 {"language":"ru"}
908
966
  "\u0E2A\u0E27\u0E31\u0E2A\u0E14\u0E35" \u2192 {"language":"th"}
909
- "123" \u2192 {"language":""}`,Hn=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??8,this.debug=t?.debug??!1}async rewrite(e,t,n=[]){let r=t.some(k=>k.role==="user"||k.role==="assistant"),o=rr(t),s=we(t),a=xe(s,this.historyMessages),i=[];n.length>0&&i.push(`Domain hint: the previous assistant turn was handled by ${n.join(", ")}. A short follow-up almost certainly still belongs to that domain \u2014 preserve it in the rewrite.`),o&&i.push(o);let l=i.length>0?`
967
+ "123" \u2192 {"language":""}`,ho=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??8,this.debug=t?.debug??!1}async rewrite(e,t,n=[]){let r=t.some(b=>b.role==="user"||b.role==="assistant"),o=Mr(t),s=Ee(t),i=Ie(s,this.historyMessages),a=[];n.length>0&&a.push(`Domain hint: the previous assistant turn was handled by ${n.join(", ")}. A short follow-up almost certainly still belongs to that domain \u2014 preserve it in the rewrite.`),o&&a.push(o);let c=a.length>0?`
910
968
 
911
- ${i.join(`
969
+ ${a.join(`
912
970
 
913
- `)}`:"",u=Date.now(),d=[{role:"system",content:Pa,timestamp:0},...a,{role:"user",content:`Latest user message to contextualize:
914
- ${e}${l}
971
+ `)}`:"",u=Date.now(),d=[{role:"system",content:ga,timestamp:0},...i,{role:"user",content:`Latest user message to contextualize:
972
+ ${e}${c}
915
973
 
916
- Return JSON only.`,timestamp:Date.now()}],m=[{role:"system",content:_a,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[p,h]=await Promise.allSettled([this.llm.chat(d),this.llm.chat(m)]),g={};if(p.status==="fulfilled")try{g=this.parseJSON(p.value.text)}catch(k){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${k}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${p.reason}`);let f="";if(h.status==="fulfilled")try{let k=this.parseJSON(h.value.text);typeof k.language=="string"&&(f=k.language.trim().toLowerCase())}catch(k){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${k}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${h.reason}`);let y={isFollowUp:r&&typeof g.isFollowUp=="boolean"?g.isFollowUp:!1,rewrittenQuery:typeof g.rewrittenQuery=="string"&&g.rewrittenQuery.trim()?g.rewrittenQuery.trim():e,topicChanged:r&&typeof g.topicChanged=="boolean"?g.topicChanged:!1,reasoning:typeof g.reasoning=="string"?g.reasoning:"",language:f,mentionedChain:typeof g.mentionedChain=="string"?g.mentionedChain.trim():"",needsWebSearch:g.needsWebSearch===!0,aboutAssistant:g.aboutAssistant===!0};if(this.debug){let k=Date.now()-u,w=y.rewrittenQuery!==e;console.log(`
917
- [QueryRewriter] (${k}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 O=require("@langchain/langgraph");var se=c=>({reducer:(e,t)=>t,default:c}),Ca=O.Annotation.Root({userMessage:(0,O.Annotation)(),doSuggest:(0,O.Annotation)(se(()=>!0)),overrideLang:(0,O.Annotation)(se(()=>"")),conversationMessages:(0,O.Annotation)(se(()=>[])),lastSubagents:(0,O.Annotation)(se(()=>[])),messageId:(0,O.Annotation)(se(()=>"")),rewrite:(0,O.Annotation)(se(()=>null)),effectiveQuery:(0,O.Annotation)(se(()=>"")),turnLanguage:(0,O.Annotation)(se(()=>"")),kbContext:(0,O.Annotation)(se(()=>"")),decision:(0,O.Annotation)(se(()=>null)),assignment:(0,O.Annotation)(se(()=>null)),assignmentIndex:(0,O.Annotation)(se(()=>0)),subResults:(0,O.Annotation)({reducer:(c,e)=>c.concat(e),default:()=>[]}),response:(0,O.Annotation)(se(()=>null))});function ir(c){let e=async d=>{c.addUserMessage(d.userMessage),c.needsSummary()&&await c.compactHistory();let m=c.conversationForTurn(),p=c.lastAssistantSubagents(m);return c.debug&&p.length>0&&console.log(`[AgentCore] previous turn handled by: ${p.join(", ")}`),{conversationMessages:m,lastSubagents:p,messageId:c.generateMessageId()}},t=async d=>{let m=await c.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),p=d.overrideLang||m.language||"";return{rewrite:m,effectiveQuery:m.rewrittenQuery,turnLanguage:p}},n=async d=>{let m=d.rewrite,p=m.isFollowUp?d.effectiveQuery:d.userMessage,h=await c.searchKB(p),g=c.formatKBContext(h),f=await c.tryAnswerFromKB(d.userMessage,h,g,d.messageId);return f?{kbContext:g,response:{...f,messageId:d.messageId,rewrite:m}}:{kbContext:g}},r=async d=>({decision:await c.route(d.effectiveQuery,d.conversationMessages,c.subagentCards(),d.lastSubagents)}),o=async d=>{let m=await c.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.doSuggest,d.messageId,d.rewrite?.needsWebSearch??!1),p=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...m,messageId:d.messageId,routerDecision:p,rewrite:d.rewrite}}},s=async d=>{let m=await c.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:m}]}},a=async d=>{let m=d.subResults.slice().sort((b,v)=>b.i-v.i).map(b=>b.result);c.persistToolMessages(m);let p=c.mergeTrace(m),h=await c.synthesise(d.userMessage,p,c.synthesiserHistory(),d.turnLanguage||void 0),g=m.map(b=>b.subagentName),f=c.collectUiActions(m,d.turnLanguage||null),y=c.collectActionButtons(m,d.turnLanguage||null),k=c.subResultsTriggerNoSuggestions(m);return{response:{...await c.finaliseAnswer({userMessage:d.userMessage,answer:h,subagents:g,uiActions:f,actionButtons:y,messageId:d.messageId},{generateSuggestions:d.doSuggest&&!k&&y.length===0}),messageId:d.messageId,trace:p,routerDecision:d.decision,subagentResults:m,rewrite:d.rewrite,...f.length>0?{uiActions:f}:{},...y.length>0?{actionButtons:y}:{}}}},i=async d=>{let m=(d.rewrite?.mentionedChain||String(c.connectedChain()??"")).trim();return{response:{...await c.answerUnsupportedChain(m,d.turnLanguage,d.messageId),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},l=d=>d.response?O.END:d.rewrite?.aboutAssistant?"direct":"route",u=d=>{let m=d.decision?.assignments??[];if(m.length===0)return"direct";let p=m.some(g=>g.subagent!=="ai-agent"),h=(d.rewrite?.mentionedChain||c.connectedChain()||"").trim();return p&&h!==""&&!wn(h)?"unsupportedChain":m.map((g,f)=>new O.Send("subagent",{...d,assignment:g,assignmentIndex:f}))};return new O.StateGraph(Ca).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",s).addNode("synthesize",a).addNode("unsupportedChain",i).addEdge(O.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",l,["route","direct",O.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",O.END).addEdge("direct",O.END).addEdge("subagent","synthesize").addEdge("synthesize",O.END).compile()}var lr=require("js-sha3");function Gn(){let c=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(c+e).slice(-8)}var Ea="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",Ua=`
974
+ Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:fa,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[m,g]=await Promise.allSettled([this.llm.chat(d),this.llm.chat(p)]),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 f="";if(g.status==="fulfilled")try{let b=this.parseJSON(g.value.text);typeof b.language=="string"&&(f=b.language.trim().toLowerCase())}catch(b){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${g.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:f,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(`
975
+ [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 q=require("@langchain/langgraph");function Mo(l){return l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var $r="\\s*/\\s*";function Oo(l){return[l.symA.toLowerCase(),l.symB.toLowerCase()].sort().join("|")}function Vr(l){return`(${l.symA}${$r}${l.symB}|${l.symB}${$r}${l.symA})`}function ya(l){let e=Mo(String(l));return`(?<![\\d.])${Number.isInteger(l)?`${e}(?:\\.0+)?`:`${e}0*`}`}function Wr(l,e,t,n){return`${l.slice(0,e)}[${t}](${n})${l.slice(e+t.length)}`}function ba(l,e){let n=new RegExp(`(?<!\\[)\\b${Vr(e)}\\b`,"i").exec(l);return n?Wr(l,n.index,n[1]??n[0],e.url):null}function wa(l,e){if(e.feePercent==null)return null;let n=new RegExp(`(?<!\\[)\\b${Vr(e)}\\b[^\\n\\]]{0,16}?${ya(e.feePercent)}\\s*%`,"i").exec(l);return n?Wr(l,n.index,n[1]??"",e.url):null}var ka=l=>{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 a=r.feeTierPercent;e.push({url:o,symA:Mo(s),symB:Mo(i),feePercent:typeof a=="number"&&Number.isFinite(a)?a:void 0})}};t(l),t(l.pool);for(let n of["pools","candidates"]){let r=l[n];Array.isArray(r)&&r.forEach(t)}return e},va=[ka];function Hr(l,e){if(!l)return l;let t=[];for(let s of e)for(let i of s.toolResults){if(!i.success||!i.data||typeof i.data!="object")continue;let a=i.data;for(let c of va)t.push(...c(a))}if(t.length===0)return l;let n=new Map;for(let s of t)n.set(Oo(s),(n.get(Oo(s))??0)+1);let r=l,o=new Set;for(let s of t){if(o.has(s.url))continue;if(r.includes(s.url)){o.add(s.url);continue}let a=(n.get(Oo(s))??0)>1?wa(r,s):ba(r,s);a&&(r=a,o.add(s.url))}return r}var pe=l=>({reducer:(e,t)=>t,default:l}),Ta=q.Annotation.Root({userMessage:(0,q.Annotation)(),doSuggest:(0,q.Annotation)(pe(()=>!0)),overrideLang:(0,q.Annotation)(pe(()=>"")),conversationMessages:(0,q.Annotation)(pe(()=>[])),lastSubagents:(0,q.Annotation)(pe(()=>[])),messageId:(0,q.Annotation)(pe(()=>"")),rewrite:(0,q.Annotation)(pe(()=>null)),effectiveQuery:(0,q.Annotation)(pe(()=>"")),turnLanguage:(0,q.Annotation)(pe(()=>"")),kbContext:(0,q.Annotation)(pe(()=>"")),decision:(0,q.Annotation)(pe(()=>null)),assignment:(0,q.Annotation)(pe(()=>null)),assignmentIndex:(0,q.Annotation)(pe(()=>0)),subResults:(0,q.Annotation)({reducer:(l,e)=>l.concat(e),default:()=>[]}),response:(0,q.Annotation)(pe(()=>null))});function Gr(l){let e=async d=>{l.addUserMessage(d.userMessage),l.needsSummary()&&await l.compactHistory();let p=l.conversationForTurn(),m=l.lastAssistantSubagents(p);return l.debug&&m.length>0&&console.log(`[AgentCore] previous turn handled by: ${m.join(", ")}`),{conversationMessages:p,lastSubagents:m,messageId:l.generateMessageId()}},t=async d=>{let p=await l.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,g=await l.searchKB(m),h=l.formatKBContext(g),f=await l.tryAnswerFromKB(d.userMessage,g,h,d.messageId);return f?{kbContext:h,response:{...f,messageId:d.messageId,rewrite:p}}:{kbContext:h}},r=async d=>({decision:await l.route(d.effectiveQuery,d.conversationMessages,l.subagentCards(),d.lastSubagents)}),o=async d=>{let p=await l.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.doSuggest,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 l.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:p}]}},i=async d=>{let p=d.subResults.slice().sort((k,A)=>k.i-A.i).map(k=>k.result);l.persistToolMessages(p);let m=l.mergeTrace(p),g=await l.synthesise(d.userMessage,m,l.synthesiserHistory(),d.turnLanguage||void 0),h=Hr(g,p),f=p.map(k=>k.subagentName),y=l.collectUiActions(p,d.turnLanguage||null),b=l.collectActionButtons(p,d.turnLanguage||null),w=l.subResultsTriggerNoSuggestions(p);return{response:{...await l.finaliseAnswer({userMessage:d.userMessage,answer:h,subagents:f,uiActions:y,actionButtons:b,messageId:d.messageId},{generateSuggestions:d.doSuggest&&!w&&b.length===0}),messageId:d.messageId,trace:m,routerDecision:d.decision,subagentResults:p,rewrite:d.rewrite,...y.length>0?{uiActions:y}:{},...b.length>0?{actionButtons:b}:{}}}},a=async d=>{let p=(d.rewrite?.mentionedChain||String(l.connectedChain()??"")).trim();return{response:{...await l.answerUnsupportedChain(p,d.turnLanguage,d.messageId),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},c=d=>d.response?q.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"),g=(d.rewrite?.mentionedChain||l.connectedChain()||"").trim();return m&&g!==""&&!Wn(g)?"unsupportedChain":p.map((h,f)=>new q.Send("subagent",{...d,assignment:h,assignmentIndex:f}))};return new q.StateGraph(Ta).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",s).addNode("synthesize",i).addNode("unsupportedChain",a).addEdge(q.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",q.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",q.END).addEdge("direct",q.END).addEdge("subagent","synthesize").addEdge("synthesize",q.END).compile()}var Yr=require("js-sha3");function go(){let l=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(l+e).slice(-8)}var Aa="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",Sa=`
918
976
 
919
- IDENTITY: If the user asks who or what you are, 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 and steer back to how you can help.`,Yn=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;suggestionsEnabled;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;historyReady;constructor(e){this.secretKey=e.secretKey,ao(e.rpcUrls),bn(e.excludeChains),this.llm=new ne(e.llm),this.registry=new Fe,this.history=new Kt(e.maxHistoryMessages??50),this.summarizer=new jt(this.llm),this.synthesizer=new Xt(this.llm),this.systemPrompt=(e.systemPrompt??Ea)+Ua,this.debug=e.debug??!1,this.suggestionsEnabled=e.generateSuggestions??!0,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new zt(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new Re({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 u=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Je(u)),this.registry.register(new Ye(u)),this.registry.register(new Ze(u)),this.registry.register(new et(u)),this.registry.register(new tt(u)),this.registry.register(new Ke(u)),this.registry.register(new nt(u)),this.registry.register(new ot(u)),this.registry.register(new lt(u)),this.registry.register(new st(u)),this.registry.register(new at(u)),this.registry.register(new it(u)),this.registry.register(new rt(u)),this.registry.register(new Qe(u)),this.registry.register(new Xe(u)),this.registry.register(new je(u)),this.registry.register(new ze(u))}let r=e.nftLink;this.registry.register(new ut({url:r})),this.registry.register(new dt),this.registry.register(new mt),this.registry.register(new pt(e.llm));let o=e.subagents?.["pool-subgraph"]===!0;if((o?e.subagents?.pool===!0:e.subagents?.pool!==!1)&&e.uniswap!==!1){let u=typeof e.uniswap=="object"?e.uniswap:void 0;this.registry.register(new gt(u)),this.registry.register(new ft(u)),this.registry.register(new yt(u)),this.registry.register(new bt(u)),this.registry.register(new Ct(u));let d=u?{isProduction:u.isProduction}:void 0;this.registry.register(new Pt({baseUrl:u?.baseUrl,pool:d,minProvideUsd:u?.minProvideUsd})),this.registry.register(new _t({pool:d}))}if(o&&e.subgraph!==!1){let u=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Et(u)),this.registry.register(new Ut(u)),this.registry.register(new Rt(u)),this.registry.register(new Nt(u)),this.registry.register(new It(u)),this.registry.register(new Lt(u)),this.registry.register(new Dt(u)),this.registry.register(new ht(e.llm))}if(e.subagents?.["wallet-action"]!==!1){let u=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new Mt(u)),this.registry.register(new qt(u)),this.registry.register(new Yt(u,{url:r})),this.registry.register(new Ft(u)),this.registry.register(new Ht(u,{debug:this.debug})),this.registry.register(new Gt(u,{debug:this.debug}))}this.router=new Qt(this.llm,{debug:this.debug}),this.rewriter=new Hn(this.llm,{debug:this.debug});let i=typeof e.subgraph=="object"?e.subgraph:void 0,l=Vn(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:i?.linkAddLiquidity},e.subagents);this.subagents=new Map(l.map(u=>[u.name,u])),this.chatGraph=ir(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:Gn()};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),a=s.data,i=s.success?a?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,l=Gn(),u=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:i,timestamp:Date.now(),subagents:["direct-invoke"],messageId:l};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:i,messageId:l,...u.length>0?{uiActions:u}:{}}}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;let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,lr.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey.");this.licenseChecked=!0}async chat(e,t){this.assertLicense();let n=t?.generateSuggestions??this.suggestionsEnabled,r=typeof t?.language=="string"&&t.language.trim()?t.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let o=Date.now();this.debug&&(console.log(`
920
- ${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=this.chatGraph.invoke({userMessage:e,doSuggest:n,overrideLang:r});this.inFlightTurn=s;let a;try{a=await s}finally{this.inFlightTurn===s&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-o}ms total`),console.log(`${"\u2500".repeat(60)}
921
- `)),a.response??{answer:"",messageId:Gn()}}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=>or(e),generateMessageId:()=>Gn(),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)=>this.answerUnsupportedChain(e,t,n),answerDirectly:(e,t,n,r,o,s)=>this.answerDirectly(e,t,n,r,o,s),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 a=s.toolResults.map(i=>i.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-o}ms | tools: ${a}`)}return s},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>{let e=this.history.getConversation(),t=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return we(t)},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),subResultsTriggerNoSuggestions:e=>this.subResultsTriggerNoSuggestions(e),finaliseAnswer:(e,t)=>this.finaliseAnswer(e,t)}}subResultsTriggerNoSuggestions(e){for(let t of e)for(let n of t.toolResults){if(!n.success)continue;if(this.registry.get(n.toolName)?.noSuggestions===!0)return!0}return!1}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 a of s.actionButtons){if(!a||typeof a!="object"||typeof a.label!="string"||!a.label.trim()||typeof a.prompt!="string"||!a.prompt.trim())continue;let i=this.capitalizeFirst(a.prompt),l={label:a.label,prompt:i,...t?{language:t}:{}},u=n.get(i);u?l.label.length>u.label.length&&n.set(i,l):(n.set(i,l),r.push(i))}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}]
977
+ IDENTITY: If the user asks who or what you are, 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 and steer back to how you can help.`,fo=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;suggestionsEnabled;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;currentAbortController=null;historyReady;constructor(e){this.secretKey=e.secretKey,Ro(e.rpcUrls),$n(e.excludeChains),this.llm=new re(e.llm),this.registry=new et,this.history=new dn(e.maxHistoryMessages??50),this.summarizer=new pn(this.llm),this.synthesizer=new gn(this.llm),this.systemPrompt=(e.systemPrompt??Aa)+Sa,this.debug=e.debug??!1,this.suggestionsEnabled=e.generateSuggestions??!0,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new mn(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new $e({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 d=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new mt(d)),this.registry.register(new at(d)),this.registry.register(new ht(d)),this.registry.register(new gt(d)),this.registry.register(new ft(d)),this.registry.register(new lt(d)),this.registry.register(new yt(d)),this.registry.register(new bt(d)),this.registry.register(new At(d)),this.registry.register(new kt(d)),this.registry.register(new vt(d)),this.registry.register(new Tt(d)),this.registry.register(new wt(d)),this.registry.register(new dt(d)),this.registry.register(new pt(d)),this.registry.register(new ct(d)),this.registry.register(new ut(d))}let r=e.nftLink;this.registry.register(new Pt({url:r})),this.registry.register(new xt),this.registry.register(new _t),this.registry.register(new Ct(e.llm));let o=e.subagents?.["pool-subgraph"]===!0,s=o?e.subagents?.pool===!0:e.subagents?.pool!==!1;if(s&&e.uniswap!==!1){let d=typeof e.uniswap=="object"?e.uniswap:void 0,p=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Rt(d,p)),this.registry.register(new Ut(d)),this.registry.register(new Nt(d)),this.registry.register(new It(d)),this.registry.register(new Wt(d));let m=d?{isProduction:d.isProduction}:void 0;this.registry.register(new $t({baseUrl:d?.baseUrl,pool:m,minProvideUsd:d?.minProvideUsd})),this.registry.register(new Vt({pool:m})),this.registry.register(new Ht),this.registry.register(new Gt)}if((s||o)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new Et(e.llm)),o&&e.subgraph!==!1){let d=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Yt(d)),this.registry.register(new Kt(d)),this.registry.register(new jt(d)),this.registry.register(new zt(d)),this.registry.register(new Qt(d)),this.registry.register(new Xt(d)),this.registry.register(new Jt(d))}let i=e.subagents?.["wallet-action-app"]===!0;if(i?!1:e.subagents?.["wallet-action"]!==!1){let d=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new tn(d)),this.registry.register(new nn(d)),this.registry.register(new un(d,{url:r})),this.registry.register(new on(d)),this.registry.register(new ln(d,{debug:this.debug})),this.registry.register(new cn(d,{debug:this.debug}))}if(i)for(let d of so({appLink:e.walletActionAppLink,nftLink:r}))this.registry.register(d);this.router=new hn(this.llm,{debug:this.debug}),this.rewriter=new ho(this.llm,{debug:this.debug});let c=typeof e.subgraph=="object"?e.subgraph:void 0,u=mo(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:c?.linkAddLiquidity},e.subagents);this.subagents=new Map(u.map(d=>[d.name,d])),this.chatGraph=Gr(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:go()};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,a=s.success?i?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,c=go(),u=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:a,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:a,messageId:c,...u.length>0?{uiActions:u}:{}}}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;let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,Yr.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey.");this.licenseChecked=!0}async chat(e,t){this.assertLicense();let n=t?.generateSuggestions??this.suggestionsEnabled,r=typeof t?.language=="string"&&t.language.trim()?t.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let o=Date.now();this.debug&&(console.log(`
978
+ ${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=new AbortController;this.currentAbortController=s;let{signal:i,cleanup:a}=Ho(s,t?.signal);this.llm.setRequestSignal?.(i);let c=this.history.serialise(),u=this.chatGraph.invoke({userMessage:e,doSuggest:n,overrideLang:r},{signal:i});this.inFlightTurn=u;let d;try{d=await u}catch(p){throw Ze(p)||i.aborted?(this.history.restore(c),new Ge):p}finally{a(),this.llm.setRequestSignal?.(void 0),this.currentAbortController===s&&(this.currentAbortController=null),this.inFlightTurn===u&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-o}ms total`),console.log(`${"\u2500".repeat(60)}
979
+ `)),d.response??{answer:"",messageId:go()}}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=>Or(e),generateMessageId:()=>go(),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)=>this.answerUnsupportedChain(e,t,n),answerDirectly:(e,t,n,r,o,s)=>this.answerDirectly(e,t,n,r,o,s),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(a=>a.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-o}ms | tools: ${i}`)}return s},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>{let e=this.history.getConversation(),t=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return Ee(t)},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),subResultsTriggerNoSuggestions:e=>this.subResultsTriggerNoSuggestions(e),finaliseAnswer:(e,t)=>this.finaliseAnswer(e,t)}}subResultsTriggerNoSuggestions(e){for(let t of e)for(let n of t.toolResults){if(!n.success)continue;if(this.registry.get(n.toolName)?.noSuggestions===!0)return!0}return!1}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 a=this.capitalizeFirst(i.prompt),c={label:i.label,prompt:a,...t?{language:t}:{}},u=n.get(a);u?c.label.length>u.label.length&&n.set(a,c):(n.set(a,c),r.push(a))}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}]
922
980
  Q: ${n.entry.question}
923
981
  A: ${n.entry.answer}`).join(`
924
982
 
925
- `)}async tryAnswerFromKB(e,t,n,r){if(!n||t.length===0)return this.debug&&console.log("[AgentCore] KB skip: no hits \u2192 router pipeline"),null;let o=t[0].score;if(o<this.kbAnswerThreshold)return this.debug&&console.log(`[AgentCore] KB skip: top score ${o.toFixed(3)} < threshold ${this.kbAnswerThreshold} \u2192 router pipeline`),null;this.debug&&console.log(`[AgentCore] KB answer: top score ${o.toFixed(3)} \u2265 threshold ${this.kbAnswerThreshold} \u2192 verifying intent before KB answer`);let a=t.map(g=>g.entry.question).filter(g=>typeof g=="string"&&g.trim().length>0).map((g,f)=>`${f+1}. "${g}"`).join(`
926
- `),i=[{role:"system",content:`You are a STRICT intent classifier. Respond with ONLY "yes" or "no" \u2014 no other text.
983
+ `)}async tryAnswerFromKB(e,t,n,r){if(!n||t.length===0)return this.debug&&console.log("[AgentCore] KB skip: no hits \u2192 router pipeline"),null;let o=t[0].score;if(o<this.kbAnswerThreshold)return this.debug&&console.log(`[AgentCore] KB skip: top score ${o.toFixed(3)} < threshold ${this.kbAnswerThreshold} \u2192 router pipeline`),null;this.debug&&console.log(`[AgentCore] KB answer: top score ${o.toFixed(3)} \u2265 threshold ${this.kbAnswerThreshold} \u2192 verifying intent before KB answer`);let i=t.map(h=>h.entry.question).filter(h=>typeof h=="string"&&h.trim().length>0).map((h,f)=>`${f+1}. "${h}"`).join(`
984
+ `),a=[{role:"system",content:`You are a STRICT intent classifier. Respond with ONLY "yes" or "no" \u2014 no other text.
927
985
 
928
986
  You are given a User message and a numbered list of FAQ questions.
929
987
 
@@ -937,10 +995,10 @@ Answer "no" if, for EVERY FAQ question, ANY of these hold:
937
995
  - They merely share vocabulary or a domain but ask for different things.
938
996
  - The user is asking for real-time data, live lookups, prices, balances, transactions, or anything that requires fetching external data \u2014 even if a FAQ question looks similar.
939
997
  - You are uncertain.`,timestamp:0},{role:"user",content:`FAQ questions:
940
- ${a}
998
+ ${i}
941
999
  User message: "${e}"
942
1000
 
943
- 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(i)).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+`
1001
+ 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(a)).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+`
944
1002
 
945
1003
  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.
946
1004
 
@@ -949,25 +1007,25 @@ REFERENCE MATERIAL:
949
1007
  `+n+`
950
1008
  ---`,timestamp:0},{role:"user",content:`${e}
951
1009
 
952
- (You MUST reply in the same language as the question above, regardless of the reference material language.)`,timestamp:Date.now()}],p=(await this.llm.chat(d)).text,h={role:"assistant",content:p,timestamp:Date.now()};return r&&(h.messageId=r),this.history.add(h),await this.persistHistory(),{answer:p,suggestedPrompts:[]}}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?"":`
1010
+ (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,g={role:"assistant",content:m,timestamp:Date.now()};return r&&(g.messageId=r),this.history.add(g),await this.persistHistory(),{answer:m,suggestedPrompts:[]}}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?"":`
953
1011
 
954
1012
  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:
955
1013
  `+t.join(`
956
- `)}async answerDirectly(e,t,n,r=!0,o,s=!1){this.debug&&console.log(`[AgentCore] Router returned no assignments, answering directly via LLM\u2026 (webSearch=${s})`);let a=s?"":`
1014
+ `)}async answerDirectly(e,t,n,r=!0,o,s=!1){this.debug&&console.log(`[AgentCore] Router returned no assignments, answering directly via LLM\u2026 (webSearch=${s})`);let i=s?"":`
957
1015
 
958
- You are answering WITHOUT live web access. Rely only on knowledge you are confident about. If the question needs real-time or recent information you do not have (current prices, today's news, latest events), say plainly that you do not have up-to-date data instead of guessing. Never fabricate numbers, dates, or facts.`,i=(n?this.systemPrompt+`
1016
+ You are answering WITHOUT live web access. Rely only on knowledge you are confident about. If the question needs real-time or recent information you do not have (current prices, today's news, latest events), say plainly that you do not have up-to-date data instead of guessing. Never fabricate numbers, dates, or facts.`,a=(n?this.systemPrompt+`
959
1017
 
960
1018
  You may use the following reference material if relevant:
961
1019
 
962
1020
  ---
963
1021
  REFERENCE MATERIAL:
964
1022
  `+n+`
965
- ---`:this.systemPrompt)+this.capabilitiesSummary()+a,l=we(t),u=[{role:"system",content:i,timestamp:0},...l,{role:"user",content:e,timestamp:Date.now()}],d=await this.llm.chat(u,void 0,{googleSearch:s});return await this.finaliseAnswer({userMessage:e,answer:d.text,messageId:o},{generateSuggestions:r})}async answerUnsupportedChain(e,t,n){this.debug&&console.log(`[AgentCore] connected chain "${e}" is not supported \u2192 short-circuit with notice`);let r=(t||"").trim(),o=[{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: ${Ne}. 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. `+(r?`Reply in BCP-47 language "${r}".`:"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()}],a=(await this.llm.chat(o)).text?.trim()||`Your currently connected network is not supported yet. Supported networks: ${Ne}.`;return await this.finaliseAnswer({userMessage:`[unsupported chain: ${e}]`,answer:a,messageId:n},{generateSuggestions:!1})}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(`
1023
+ ---`:this.systemPrompt)+this.capabilitiesSummary()+i,c=Ee(t),u=[{role:"system",content:a,timestamp:0},...c,{role:"user",content:e,timestamp:Date.now()}],d=await this.llm.chat(u,void 0,{googleSearch:s});return await this.finaliseAnswer({userMessage:e,answer:d.text,messageId:o},{generateSuggestions:r})}async answerUnsupportedChain(e,t,n){this.debug&&console.log(`[AgentCore] connected chain "${e}" is not supported \u2192 short-circuit with notice`);let r=(t||"").trim(),o=[{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: ${Ye}. 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. `+(r?`Reply in BCP-47 language "${r}".`:"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()}],i=(await this.llm.chat(o)).text?.trim()||`Your currently connected network is not supported yet. Supported networks: ${Ye}.`;return await this.finaliseAnswer({userMessage:`[unsupported chain: ${e}]`,answer:i,messageId:n},{generateSuggestions:!1})}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(`
966
1024
 
967
- `);return{steps:t,finalAnswer:n}}async finaliseAnswer(e,t){let{userMessage:n,answer:r,subagents:o,uiActions:s,actionButtons:a,messageId:i}=e??{},{generateSuggestions:l=!0}=t??{},u=l?await this.generateSuggestions(n,r,o??[]):[],d={role:"assistant",content:r,timestamp:Date.now()};return o&&o.length>0&&(d.subagents=o),u.length>0&&(d.suggestedPrompts=u),s&&s.length>0&&(d.uiActions=s),a&&a.length>0&&(d.actionButtons=a),i&&(d.messageId=i),this.history.add(d),await this.persistHistory(),{answer:r,suggestedPrompts:u,...a&&a.length>0?{actionButtons:a}:{}}}async generateSuggestions(e,t,n){let r=n.includes("pool")?`
1025
+ `);return{steps:t,finalAnswer:n}}async finaliseAnswer(e,t){let{userMessage:n,answer:r,subagents:o,uiActions:s,actionButtons:i,messageId:a}=e??{},{generateSuggestions:c=!0}=t??{},u=c?await this.generateSuggestions(n,r,o??[]):[],d={role:"assistant",content:r,timestamp:Date.now()};return o&&o.length>0&&(d.subagents=o),u.length>0&&(d.suggestedPrompts=u),s&&s.length>0&&(d.uiActions=s),i&&i.length>0&&(d.actionButtons=i),a&&(d.messageId=a),this.history.add(d),await this.persistHistory(),{answer:r,suggestedPrompts:u,...i&&i.length>0?{actionButtons:i}:{}}}async generateSuggestions(e,t,n){let r=n.includes("pool")?`
968
1026
  POOL FUNNEL: This turn was handled by the pool subagent. If the answer references a SPECIFIC pool (token pair + fee tier, or a pool address), the FIRST suggestion MUST propose adding liquidity to THAT exact pool (e.g. "Add liquidity to USDC/WETH 0.05%"). A second suggestion should propose estimating yield for a deposit into the same pool. Skip this funnel only if no specific pool is identifiable in the answer.
969
1027
  `:"",o=n.length>0?`
970
- Handled by subagent(s): ${n.join(", ")}`:"";try{let a=(await this.llm.chat([{role:"user",content:`Analyze this conversation and propose follow-up prompts the user is likely to want NEXT.
1028
+ Handled by subagent(s): ${n.join(", ")}`:"";try{let i=(await this.llm.chat([{role:"user",content:`Analyze this conversation and propose follow-up prompts the user is likely to want NEXT.
971
1029
 
972
1030
  User: ${e}
973
1031
  Assistant: ${t}${o}
@@ -982,4 +1040,4 @@ RULES:
982
1040
  - Suggestions must be diverse \u2014 do not repeat the same intent in different words.
983
1041
  - Use the same language as the user.
984
1042
  - Good example (pool): ["Add liquidity to USDC/WETH 0.05%", "Estimate yield for $1000 here", "Compare with 0.3% fee tier"]
985
- - Bad example: ["What is a pool?", "How do pools work?", "Tell me more"] (generic, no action, no specifics)`,timestamp:0}])).text.match(/\[[\s\S]*\]/);return a?JSON.parse(a[0]).filter(l=>typeof l=="string"&&l.length>0).slice(0,3):[]}catch{return[]}}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()))}getLastSuggestions(){let e=this.getDisplayHistory();for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant")return n.suggestedPrompts??[]}return[]}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 m=e.length-1;m>=0;m--)if(e[m].role==="user"&&(n++,n>=t)){r=m;break}let o=e.slice(r),s=nr(o,o.length),a=e.length-s.length,i=we(e.slice(0,a)),l=this.history.getSummary(),u=[];l&&u.push({role:"user",content:`[Previous context summary]: ${l}`,timestamp:0}),u.push(...i);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 Ra=c=>{let e=JSON.parse(c),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 cr(c,e){let t=c.entries??(c.json?Ra(c.json):[]);return t.length===0?{count:0}:new Re(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseNftMessageTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,MoralisService,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,OpenAddLiquidityFormTool,POOL_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,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,WalletNetWorthTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,ZERO_ADDRESS,buildRangePresets,buildUniswapPoolUrl,clampTick,configureSupportedChains,createAiAgent,createDefaultSubagents,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletAgent,ethCallAt,ethCallByChain,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,priceToTick,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});
1043
+ - Bad example: ["What is a pool?", "How do pools work?", "Tell me more"] (generic, no action, no specifics)`,timestamp:0}])).text.match(/\[[\s\S]*\]/);return i?JSON.parse(i[0]).filter(c=>typeof c=="string"&&c.length>0).slice(0,3):[]}catch{return[]}}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()))}getLastSuggestions(){let e=this.getDisplayHistory();for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant")return n.suggestedPrompts??[]}return[]}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=Dr(o,o.length),i=e.length-s.length,a=Ee(e.slice(0,i)),c=this.history.getSummary(),u=[];c&&u.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),u.push(...a);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 Pa=l=>{let e=JSON.parse(l),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 Kr(l,e){let t=l.entries??(l.json?Pa(l.json):[]);return t.length===0?{count:0}:new $e(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseNftMessageTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,ManageLiquidityRedirectTool,MoralisService,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,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,WalletActionAppTool,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletDefiSummaryTool,WalletHistoryTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,ZERO_ADDRESS,buildRangePresets,buildUniswapPoolUrl,clampTick,configureSupportedChains,createAiAgent,createDefaultSubagents,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletActionAppTools,createWalletAgent,ethCallAt,ethCallByChain,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,isAbortError,normalizePriceRangeToPool,priceToTick,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});