keyring-agent-core 0.2.37 → 0.2.38

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,5 +1,5 @@
1
- "use strict";var $s=Object.create;var eo=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Ws=Object.getOwnPropertyNames;var Hs=Object.getPrototypeOf,Gs=Object.prototype.hasOwnProperty;var Ys=(a,e)=>{for(var t in e)eo(a,t,{get:e[t],enumerable:!0})},Ar=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ws(e))!Gs.call(a,r)&&r!==t&&eo(a,r,{get:()=>e[r],enumerable:!(n=Vs(e,r))||n.enumerable});return a};var Ks=(a,e,t)=>(t=a!=null?$s(Hs(a)):{},Ar(e||!a||!a.__esModule?eo(t,"default",{value:a,enumerable:!0}):t,a)),js=a=>Ar(eo({},"__esModule",{value:!0}),a);var Kl={};Ys(Kl,{AI_AGENT_TOOL_NAMES:()=>Ro,AbortError:()=>nt,AgentCore:()=>Oo,ApproveTokenTool:()=>wn,BaseNftAiTool:()=>Ie,BaseNftMessageTool:()=>Lt,BaseSwapService:()=>je,BaseTool:()=>v,BaseWalletActionTool:()=>Se,BuyTokenTool:()=>An,ChatHistory:()=>xn,DEFAULT_CHAIN:()=>be,DEFAULT_PROVIDER:()=>Bn,DEFAULT_RPC_BY_CHAIN:()=>Te,DebridgeAdapter:()=>jt,EstimatePoolYieldTool:()=>rn,GeminiProvider:()=>z,GeminiSearchAiTool:()=>$t,HEX_TO_PANTOGRAPH:()=>Yr,KnowledgeBase:()=>_n,ManageLiquidityRedirectTool:()=>an,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>Eo,NFC_AMAZON_DEFAULT_DOMAIN:()=>Zo,NFC_AMAZON_DOMAINS:()=>Jo,NFTContractInfoTool:()=>Ot,NFTMetadataTool:()=>Mt,NFT_AGENT_TOOL_NAMES:()=>_o,NfcBuyTool:()=>Ft,NfcInfoTool:()=>Bt,OpenAddLiquidityFormTool:()=>nn,POOL_AGENT_TOOL_NAMES:()=>No,PantographService:()=>ie,PoolByAddressTool:()=>tn,PoolDetailTool:()=>Zt,PoolFallbackAiTool:()=>Vt,PoolPriceRangesTool:()=>sn,PoolSearchTool:()=>en,PoolService:()=>ae,PreviewAddLiquidityTool:()=>on,RelayAdapter:()=>zt,Router:()=>En,SUPPORTED_CHAINS:()=>ut,SUPPORTED_CHAINS_LABEL:()=>mt,SWAP_PROVIDER_CONFIG:()=>fo,SendNativeTool:()=>yn,SendNftTool:()=>Pn,SendTokenTool:()=>bn,Subagent:()=>Y,SubgraphAddPoolTool:()=>hn,SubgraphCoinPoolPairsTool:()=>mn,SubgraphPoolByAddressTool:()=>un,SubgraphPoolByPositionIdTool:()=>dn,SubgraphPoolSearchTool:()=>ln,SubgraphPositionDetailTool:()=>pn,SubgraphTrendingPoolsTool:()=>cn,Summarizer:()=>Cn,SwapServiceFactory:()=>st,SwapTokenTool:()=>Sn,Synthesizer:()=>Rn,TOKEN_AGENT_TOOL_NAMES:()=>Co,TRANSFER_TOPIC:()=>bs,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Kr,TokenAnalyticsTool:()=>wt,TokenHoldersTool:()=>bt,TokenInfoTool:()=>yt,TokenScoreTool:()=>kt,ToolRegistry:()=>ct,TopGainersTool:()=>vt,TopPoolsTool:()=>Jt,TransactionByHashTool:()=>It,TrendingTokensTool:()=>Tt,UNISWAP_CHAIN_SLUG:()=>$n,UpstashKnowledgeBase:()=>Qe,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Uo,WALLET_AGENT_TOOL_NAMES:()=>xo,WalletActionAppTool:()=>Vn,WalletApprovalsTool:()=>Et,WalletDefiPositionsTool:()=>Nt,WalletDefiProtocolPositionsTool:()=>Ut,WalletDefiSummaryTool:()=>Rt,WalletHistoryTool:()=>St,WalletNFTsTool:()=>Dt,WalletNftTransfersTool:()=>xt,WalletPnlSummaryTool:()=>Ct,WalletPnlTool:()=>_t,WalletTokenBalancesTool:()=>At,WalletTokenTransfersTool:()=>Pt,WebsiteTrustKeyringAgent:()=>Mo,ZERO_ADDRESS:()=>F,amazonDomainForLanguage:()=>er,apiClient:()=>x,buildChallenge:()=>$o,buildRangePresets:()=>ur,buildUniswapPoolUrl:()=>fe,clampTick:()=>De,completeX402:()=>Vo,configureSupportedChains:()=>oo,createAiAgent:()=>jn,createDefaultSubagents:()=>Io,createNfcAgent:()=>Kn,createNftAgent:()=>Yn,createPoolAgent:()=>zn,createTokenAgent:()=>Gn,createWalletActionAgent:()=>Xn,createWalletActionAppTools:()=>Po,createWalletAgent:()=>Hn,createX402SignatureProvider:()=>Ho,displayFromChallenge:()=>Rr,encodeSignedHeader:()=>Wo,ethCallAt:()=>ms,ethCallByChain:()=>cr,fetchTopMarketplaces:()=>tr,getAffiliateFee:()=>Yt,getChainMeta:()=>ne,getDefaultRpcUrl:()=>Aa,getGatewayAddress:()=>bo,getGatewayChains:()=>wo,getNativeTokenInfo:()=>Xt,getPositionManagerAddress:()=>ko,getProviderByChain:()=>go,ingestKnowledgeBase:()=>Fs,isAbortError:()=>lt,nfcAmazonSearchUrl:()=>ao,normaliseCountry:()=>lo,normalizePriceRangeToPool:()=>Gt,priceToTick:()=>rt,requestWithX402:()=>ai,resolveNfcShopLinks:()=>qt,resolveRpcUrl:()=>Kt,roundTickToSpacing:()=>Le,rpcCall:()=>$e,setRpcOverrides:()=>lr,swapServiceFactory:()=>Oe,tickToPrice:()=>xe,toPantographChain:()=>Ei});module.exports=js(Kl);var Pr=Ks(require("axios"));var Sr="0.2.37";var Xs=`keyring-agent-core/${Sr} (Keyring Chatbot Agent; +https://keyring.app)`,Qs="payment-required",Bo=null;function xr(a){Bo=a}function Js(a){return a?Object.keys(a).some(e=>e.toLowerCase()==="payment-signature"):!1}var Zs=3e4,ei=typeof process<"u"&&process.versions?.node!=null,Fo=class{instance;constructor(e={}){this.instance=Pr.default.create({baseURL:e.baseURL,timeout:e.timeout??Zs,validateStatus:()=>!0,headers:{Accept:"application/json",...ei?{"User-Agent":e.userAgent??Xs}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[l,c]of Object.entries(o.headers??{}))c!=null&&(s[l.toLowerCase()]=String(c));let i={ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:s};if(i.status===402&&i.headers[Qs]&&Bo&&!Js(r.headers)){let l=await Bo(i,{url:t,method:String(e),body:n,headers:r.headers});if(l)return this.request(e,t,n,{...r,headers:{...r.headers,...l}})}return i}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Fo;function I(a){let{data:e,status:t,statusText:n}=a,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=l=>l&&typeof l=="object"?l.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}var ti={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},Cr="payment-required",ni="PAYMENT-SIGNATURE";function oi(a){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(a),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(a,"utf8").toString("base64")}function ri(a){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(a,"base64").toString("utf8")}function si(){let a=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(a);else for(let t=0;t<32;t++)a[t]=Math.floor(Math.random()*256);return"0x"+Array.from(a,t=>t.toString(16).padStart(2,"0")).join("")}function ii(a){let[e,t]=String(a).split(":"),n=parseInt(t,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${a}`);return n}function _r(a){if(!a.query||Object.keys(a.query).length===0)return a.url;let e=Object.entries(a.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return a.url.includes("?")?`${a.url}&${e}`:`${a.url}?${e}`}function Er(a){return JSON.parse(ri(a))}function $o(a,e,t,n){let r=a.headers[Cr];if(!r)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=Er(r),s=o.accepts?.[0];if(!s)throw new Error("402 response offered no payment requirements");if(s.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${s.scheme} (only "exact" is supported)`);if(!t)throw new Error("No connected wallet address to build the payment from");let i=ii(s.network),l=Math.floor(Date.now()/1e3),c={from:t,to:s.payTo,value:String(s.amount),validAfter:"0",validBefore:String(l+(s.maxTimeoutSeconds??300)),nonce:si()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:i,verifyingContract:s.asset},types:ti,primaryType:"TransferWithAuthorization",message:{...c}};return{request:{url:_r(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:s,authorization:c,typedData:d,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:c},resource:o.resource,accepted:s,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function ai(a,e,t,n){let r=_r(e),o=await a.request(e.method??"GET",r,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:$o(o,e,t,n)};if(!o.ok)throw new Error(I(o));return{status:"ok",data:o.data}}async function Vo(a,e,t){let{url:n,method:r,body:o,headers:s}=e.request,i=await a.request(r,n,o,{headers:{...s??{},...Wo(e,t)}});if(i.ok)return i.data;let l=i.headers[Cr];if(l)try{let c=Er(l);if(c.error)throw new Error(`x402 payment rejected: ${c.error}`)}catch(c){if(c instanceof Error&&c.message.startsWith("x402 payment rejected"))throw c}throw new Error(I(i))}var li={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function Wo(a,e){let t={...a.paymentDraft,payload:{authorization:a.authorization,signature:e}};return{[ni]:oi(JSON.stringify(t))}}function Rr(a){let e=a.requirements,t=a.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:li[e.network]||e.network,payTo:e.payTo,...t?.description?{description:t.description}:{},resourceUrl:a.request.url}}function Ho(a){return async(e,t)=>{let n=a.getPayer(),r=a.getSigner();if(!n||!r)return null;let o;try{o=$o(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let s;try{s=await r({typedData:o.typedData,display:Rr(o)})}catch{s=null}return s?Wo(o,s):null}}var nt=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function lt(a){if(!a||typeof a!="object")return!1;let e=a;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Go(a){if(a?.aborted)throw new nt}function Nr(a,e){if(!e)return{signal:a.signal,cleanup:()=>{}};if(e.aborted)return a.abort(),{signal:a.signal,cleanup:()=>{}};let t=()=>a.abort();return e.addEventListener("abort",t),{signal:a.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Ur={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},ci="https://nft.keyring.app/api/gemini-stable",ui=new Set([408,429,500,502,503,504]),Ir=3e4,to=a=>new Promise(e=>setTimeout(e,a));function no(a,e,t){if(t!=null&&t>0)return Math.min(t,Ir);let n=Math.min(e*2**(a-1),Ir);return n/2+Math.random()*(n/2)}function di(a){if(!a)return null;let e=Number(a);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(a);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var z=class{model;maxTokens;temperature;baseUrl;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??ci}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;Go(l);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 f=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}: [${f}]`)}}let d={contents:c,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(d.systemInstruction=r),t?.length?(d.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(d.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(d.tools=[{googleSearch:{}}]);let u=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){Go(l);let f;try{f=await x.post(u,d,{headers:{"Content-Type":"application/json"},signal:l})}catch(T){if(lt(T))throw T;if(p=T instanceof Error?T.message:String(T),m>=s)break;await to(no(m,i));continue}if(!f.ok){let T=typeof f.data=="string"?f.data:JSON.stringify(f.data)||f.statusText;if(p=`Gemini proxy error ${f.status}: ${T}`,!ui.has(f.status))throw new Error(p);if(m>=s)break;let A=di(f.headers["retry-after"]??null);await to(no(m,i,A));continue}if(f.data==null||typeof f.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await to(no(m,i));continue}let h=f.data,g=h.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let y="",b=[],w=g.content?.parts;if(!Array.isArray(w)||w.length===0){let T=g.finishReason;if(!(T==="SAFETY"||T==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${T??"none"})`,await to(no(m,i));continue}return{text:"",toolCalls:[]}}for(let T of w)T.text&&(y+=T.text),T.functionCall&&b.push({toolName:T.functionCall.name,args:T.functionCall.args??{},callId:T.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let k=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:k}}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(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(u=>u.functionCall),d=l?.parts.some(u=>u.functionCall);l&&l.role===i.role&&!c&&!d?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let l=r[i],c=o[o.length-1];l.role==="function"&&!c?.parts.some(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.functionCall)&&!(r[i+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
2
- `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:Ur[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:Ur[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 ct=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 ut=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],pi=new Set(ut),He=[...ut],Yo=new Set(He),be="0x1",mt="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function mi(a){return a.map(e=>pt[e]??e).join(", ")}function oo(a){let e=new Set;if(a)for(let n of a){let r=ro(n);r&&e.add(r)}let t=ut.filter(n=>!e.has(n));He=t.length>0?[...t]:[...ut],Yo=new Set(He),be=He.includes("0x1")?"0x1":He[0],mt=mi(He)}var hi={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function $(a){let e=ro(a);return e&&Yo.has(e)?e:null}function ro(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=hi[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&&pi.has(n)?n:null}function Pe(a){return $(a)!==null}function we(){return[...He]}var dt=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${mt}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ge=a=>typeof a=="string"&&a.trim()!=="";function le(a,e){if(Ge(a)){let t=$(a);if(t)return t;throw new dt(a.trim())}if(Ge(e?.chain)){let t=$(e.chain);if(t)return t;throw new dt(e.chain.trim())}return null}function so(a,e){return $(a)??$(e?.chain)??void 0}var pt={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function P(a){let e=ro(a);return e&&pt[e]?pt[e]:typeof a=="string"&&a.trim()?a.trim():"the requested chain"}var gi={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function Lr(a,e){let t=ro(a),n=t?gi[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var fi={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Dr(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase();return e?fi[e]??null:null}var yi={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function Or(a){let e=$(a);return e?yi[e]??null:null}function ht(a,e){if(!Ge(a))return null;let t=$(a),n=$(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:pt[t]??t,connectedLabel:pt[n]??n}}function Mr(a,e){let t=typeof a=="string"?a.trim():"",n=e&&e.length?e.filter(o=>Yo.has(o)):[];return(n.length?n:He).map(o=>{let s=pt[o]??o;return{label:s,prompt:t?`${t} (${s})`:s}})}function gt(a,e){return{actionButtons:Mr(e),_instructions:`The user wants to ${a} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var K=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=Mr(e,t)}},Ln=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 X(a,e){if(Ge(a))return a.trim();if(Ge(e?.walletAddress))return e.walletAddress.trim();throw new Ln}function Z(a,e,t){if(Ge(a)){let n=$(a);if(n)return n;throw new dt(a.trim())}if(Ge(e?.chain)){let n=$(e.chain);if(n)return n;throw new dt(e.chain.trim())}if(Ge(e?.walletAddress))throw new K(typeof e?.query=="string"?e.query:void 0,t);return be}var v=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s=bi(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 Ln?{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 bi(a){if(!a||typeof a!="object")return{data:a};let e=a,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:a};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var qr=require("js-sha3");function B(a){return typeof a=="string"&&/^0x[0-9a-fA-F]{40}$/.test(a)}function wi(a){return new Uint8Array(qr.keccak256.arrayBuffer(a))}function Dn(a){let e=a.startsWith("0x")?a.slice(2):a,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function Br(a){return"0x"+Array.from(a).map(e=>e.toString(16).padStart(2,"0")).join("")}function Fr(a){return new TextEncoder().encode(a)}function ot(...a){let e=a.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;return t}function ki(a,e=32){let t=new Uint8Array(e);return t.set(a,e-a.length),t}function Ti(a,e=32){let t=new Uint8Array(e);return t.set(a),t}function $r(a){let e=((a%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Dn(e)}function On(a){return $r(BigInt(a))}function Vr(a){return a==="uint"?"uint256":a==="int"?"int256":a.match(/^uint$/)?"uint256":a.match(/^int$/)?"int256":a.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function Wr(a){let e=Vr(a.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(a.components??[]).map(Wr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function vi(a){let e=(a.inputs??[]).map(Wr).join(",");return`${a.name??""}(${e})`}function Ko(a,e){let t=Pi(a.type);if(t){let[r,o]=t;return Ai({...a,type:o},e,r)}if(a.type==="tuple")return Si(a,e);if(a.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:ki(Dn(o.toLowerCase()))}}if(a.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Vr(a.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:On(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:$r(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Dn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ti(o)}}if(n==="bytes"){let r=typeof e=="string"?Dn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:ot(On(r.length),s)}}if(n==="string"){let r=typeof e=="string"?Fr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:ot(On(r.length),s)}}throw new Error(`Unsupported ABI type: ${a.type}`)}function jo(a){let e=0;for(let{dynamic:o,encoded:s}of a)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of a)o?(t.push(On(e+r)),n.push(s),r+=s.length):t.push(s);return ot(...t,...n)}function Ai(a,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let i=Ko(a,s);i.dynamic&&(r=!0),o.push(i)}if(n||r){let s=jo(o);if(n){let i=On(o.length);return{dynamic:!0,encoded:o.length>0?ot(i,s):i}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:ot(...o.map(s=>s.encoded))}}function Si(a,e){let t=a.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],i=Array.isArray(e)?e[o]:e[s.name??""],l=Ko(s,i);l.dynamic&&(n=!0),r.push(l)}return{dynamic:n,encoded:n?jo(r):ot(...r.map(o=>o.encoded))}}function Pi(a){let e=a.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function xi(a,e){if(a.length!==e.length)throw new Error(`Expected ${a.length} values, got ${e.length}`);if(a.length===0)return"0x";let t=a.map((r,o)=>Ko(r,e[o])),n=jo(t);return Br(n)}function ft({abi:a,functionName:e,args:t=[]}){let n=a.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=vi(n),o=wi(Fr(r)).slice(0,4),s=n.inputs??[],i=s.length===0||t.length===0?new Uint8Array(0):Dn(xi(s,t).slice(2));return Br(ot(o,i))}var Ci="https://deblo-api-dev.pantograph.app",_i="0x0000000000000000000000000000000000000000",Yr={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Kr={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function Ei(a){return Yr[a.toLowerCase()]||a}function Hr(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function zo(a){let e=a,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function Xo(a){if(Array.isArray(a))return a;let e=a;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function se(a){if(a==null)return null;let e=typeof a=="number"?a:parseFloat(String(a));return Number.isFinite(e)?e:null}function Gr(a,e){let t=a.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=se(a.price_change_percentage_24h)??se(a.priceChange24h)??se(a.usd_price_24hr_percent_change)??se(a.price_change_24h)??se(a.priceChange);return{chainId:e,tokenAddress:a.address??a.token_address??"",name:a.name??null,symbol:a.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:a.logoURI??a.icon_image??a.logo??null,usdPrice:se(a.price)??se(a.usd_price),marketCap:se(a.market_cap)??se(a.marketCap),totalVolume:{"24h":se(a.total_volume)??se(a.volume24h)},pricePercentChange:{"24h":r}}}var ie=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Ci).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),r=this.tokensUrl(t,n),o=await x.get(r);if(!o.ok)return;let s=Xo(o.data),i=new Map;for(let l of s)l.address&&i.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=i.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),r=await x.get(n);if(!r.ok)return null;let o=Xo(r.data),s=e.toLowerCase()===_i,i=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||s&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||s&&l.token_address==="");return i?zo(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=this.tokensUrl(t,e.join(",")),o=await x.get(r);if(!o.ok)return n;let s=Xo(o.data),i=new Set(e.map(l=>l.toLowerCase()));for(let l of s){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&i.has(c)&&(n[c]=zo(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||be,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=Hr({chainId:o,key:t}),i=`${this.baseUrl}/token-list/all?${s}`,l=await x.get(i);if(!l.ok)throw new Error(I(l));let c=l.data,d=c?.result??c?.data??c,u=[];return Array.isArray(d)?u=d:d&&typeof d=="object"&&(u=Object.values(d).flat()),{success:!0,data:u.map(zo)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||be,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=Kr[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],d=l.status==="fulfilled"?o.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>Gr(h,t)):[],u=new Set,p=[];for(let h of d){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),m.push(h))}let f=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=se(s.market_cap)??se(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":se(s.total_volume)??se(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=parseInt(e,16),o=Hr({chainId:r,duration:n,limit:t}),s=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(s);if(!c.ok)throw new Error(I(c));let d=c.data;if(i=Array.isArray(d)?d:Array.isArray(d.data)?d.data:[],i.length>0)break;l<4&&await new Promise(u=>setTimeout(u,2e3))}return i.map(l=>Gr(l,e))}async getTopGainers(e){let t=e?.chain||be,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 Ri="https://nft.keyring.app",Ni="https://nft.keyring.app",Ui=.01,N=5,W=1e3,Ii="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Li="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function j(a){return a||be}function H(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function G(a){return new Promise(e=>setTimeout(e,a))}function Di(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Qo(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ri).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Ni).replace(/\/+$/,""),this.pantograph=new ie({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=j(n),l="Unknown error";for(let c=1;c<=N;c++)try{let d={chain:i,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(d.token_addresses=r);let u=[],p=null;do{p&&(d.cursor=p);let f=H(d),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${f}`,g=await x.get(h);if(!g.ok)throw new U(g.status,I(g));let y=g.data,b=y?.data??y;b?.result?.length>0&&u.push(...b.result),p=b?.cursor??null}while(p);let m={result:u};return m?.result?.length>0&&(m.result=m.result.filter(f=>parseFloat(f.balance||"0")>0),m.result=m.result.map(f=>({...f,token_address:f.token_address.toLowerCase()===Ii?Li:f.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(f=>f.usd_value==null||f.usd_value>=Ui)),{success:!0,data:m}}catch(d){if(l=d instanceof Error?d.message:"Unknown error",d instanceof U&&d.status===400)break;c<N&&await G(W)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=j(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${H({chain:r,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${H({chain:r,include:"percent_change"})}`)]),d=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;d=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!d){o="Token metadata not found",i<N&&await G(W);continue}let u=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;u=p?.data??p}return{success:!0,data:{...d,...u?.usd_price?{usd_price:u.usd_price}:{},...u?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:u.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await 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:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let d=j(n),u="Unknown error";for(let p=1;p<=N;p++)try{let m={chain:d,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(m.cursor=s),l&&(m.include_prices=!0),i&&i.length>0&&(m.token_addresses=i);let f=H(m),h=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${f}`,g=await x.get(h);if(!g.ok)throw new U(g.status,I(g));let y=g.data;return{success:!0,data:y?.data??y}}catch(m){if(u=m instanceof Error?m.message:"Unknown error",m instanceof U&&m.status===400)break;p<N&&await G(W)}return{success:!1,error:u}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!B(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=j(r),d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:i};l&&(p.include=l);let m=H(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await x.get(f);if(!h.ok)throw new U(h.status,I(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;u<N&&await G(W)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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:l,cursor:c,order:d="DESC",includeInternalTransactions:u,nftMetadata:p}=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 m=j(n),f=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let g=1;g<=N;g++)try{let y={chain:m,limit:f,order:d};o&&(y.from_date=o),s&&(y.to_date=s),i!=null&&(y.from_block=i),l!=null&&(y.to_block=l),c&&(y.cursor=c),u!=null&&(y.include_internal_transactions=u),p!=null&&(y.nft_metadata=p);let b=H(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,k=await x.get(w);if(!k.ok)throw new U(k.status,I(k));let T=k.data;return{success:!0,data:T?.data??T}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;g<N&&await 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:l,toBlock:c,cursor:d,order:u="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 p=j(n),m=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let h=1;h<=N;h++)try{let g={chain:p,limit:m,order:u};s&&(g.from_date=s),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),d&&(g.cursor=d),r?.length&&(g.contract_addresses=r);let y=H(g),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await x.get(b);if(!w.ok)throw new U(w.status,I(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(g){if(f=g instanceof Error?g.message:"Unknown error",g instanceof U&&g.status===400)break;h<N&&await G(W)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=j(n),h=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=N;y++)try{let b={chain:f,limit:h,order:u,format:m};s&&(b.from_date=s),i&&(b.to_date=i),l!=null&&(b.from_block=l),c!=null&&(b.to_block=c),d&&(b.cursor=d),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=H(b),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,T=await x.get(k);if(!T.ok)throw new U(T.status,I(T));let A=T.data;return{success:!0,data:A?.data??A}}catch(b){if(g=b instanceof Error?b.message:"Unknown error",b instanceof U&&b.status===400)break;y<N&&await G(W)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!B(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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(!B(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=j(n),s="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:o};r&&(l.days=r);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data;return{success:!0,data:p?.data??p}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await 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(!B(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let d=H(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await x.get(u);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await 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=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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(!B(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let d=H(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await x.get(u);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await 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(!B(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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(!B(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:Di(u)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&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(!B(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=j(r),s="Unknown error";for(let i=1;i<=N;i++)try{let l=H({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,d=await x.get(c);if(!d.ok)throw new U(d.status,I(d));let m=d.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(g=>({token_type:g.tokenType,address:g.address,contract_address:g.address,name:g.name??"",symbol:g.symbol??"",decimals:g.decimals??18,logo:g.logo,balance:g.balance??"0",balance_formatted:g.balanceFormatted??"0",usd_price:g.usdPrice,usd_value:g.usdValue}))}))}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await 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(!B(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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(!B(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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<=N;o++)try{let s={};t&&(s.chain=j(t)),n!=null&&(s.limit=n);let i=H(s),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:Qo(u)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof U&&s.status===400)break;o<N&&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<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data,m=p?.data??p;return{success:!0,data:Qo(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&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<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data,m=p?.data??p;return{success:!0,data:Qo(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await G(W)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var yt=class extends v{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new z({})}async run(e,t){let n=e.keyword||"",r=Z(e.chain,t),o=e.prompt||"",s=t?.walletAddress||void 0;return n?await this.searchToken(n,r,o,s):{error:"Missing required parameter: keyword"}}async searchToken(e,t,n,r){let o=[r?`User's connected wallet address: ${r}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
1
+ "use strict";var $s=Object.create;var eo=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Ws=Object.getOwnPropertyNames;var Hs=Object.getPrototypeOf,Gs=Object.prototype.hasOwnProperty;var Ys=(a,e)=>{for(var t in e)eo(a,t,{get:e[t],enumerable:!0})},Ar=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ws(e))!Gs.call(a,r)&&r!==t&&eo(a,r,{get:()=>e[r],enumerable:!(n=Vs(e,r))||n.enumerable});return a};var Ks=(a,e,t)=>(t=a!=null?$s(Hs(a)):{},Ar(e||!a||!a.__esModule?eo(t,"default",{value:a,enumerable:!0}):t,a)),js=a=>Ar(eo({},"__esModule",{value:!0}),a);var Kl={};Ys(Kl,{AI_AGENT_TOOL_NAMES:()=>Ro,AbortError:()=>nt,AgentCore:()=>Oo,ApproveTokenTool:()=>wn,BaseNftAiTool:()=>Ie,BaseNftMessageTool:()=>Lt,BaseSwapService:()=>je,BaseTool:()=>v,BaseWalletActionTool:()=>Se,BuyTokenTool:()=>An,ChatHistory:()=>xn,DEFAULT_CHAIN:()=>be,DEFAULT_PROVIDER:()=>Bn,DEFAULT_RPC_BY_CHAIN:()=>Te,DebridgeAdapter:()=>jt,EstimatePoolYieldTool:()=>rn,GeminiProvider:()=>z,GeminiSearchAiTool:()=>$t,HEX_TO_PANTOGRAPH:()=>Yr,KnowledgeBase:()=>_n,ManageLiquidityRedirectTool:()=>an,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>Eo,NFC_AMAZON_DEFAULT_DOMAIN:()=>Zo,NFC_AMAZON_DOMAINS:()=>Jo,NFTContractInfoTool:()=>Ot,NFTMetadataTool:()=>Mt,NFT_AGENT_TOOL_NAMES:()=>_o,NfcBuyTool:()=>Ft,NfcInfoTool:()=>Bt,OpenAddLiquidityFormTool:()=>nn,POOL_AGENT_TOOL_NAMES:()=>No,PantographService:()=>ie,PoolByAddressTool:()=>tn,PoolDetailTool:()=>Zt,PoolFallbackAiTool:()=>Vt,PoolPriceRangesTool:()=>sn,PoolSearchTool:()=>en,PoolService:()=>ae,PreviewAddLiquidityTool:()=>on,RelayAdapter:()=>zt,Router:()=>En,SUPPORTED_CHAINS:()=>ut,SUPPORTED_CHAINS_LABEL:()=>mt,SWAP_PROVIDER_CONFIG:()=>fo,SendNativeTool:()=>yn,SendNftTool:()=>Pn,SendTokenTool:()=>bn,Subagent:()=>Y,SubgraphAddPoolTool:()=>hn,SubgraphCoinPoolPairsTool:()=>mn,SubgraphPoolByAddressTool:()=>un,SubgraphPoolByPositionIdTool:()=>dn,SubgraphPoolSearchTool:()=>ln,SubgraphPositionDetailTool:()=>pn,SubgraphTrendingPoolsTool:()=>cn,Summarizer:()=>Cn,SwapServiceFactory:()=>st,SwapTokenTool:()=>Sn,Synthesizer:()=>Rn,TOKEN_AGENT_TOOL_NAMES:()=>Co,TRANSFER_TOPIC:()=>bs,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Kr,TokenAnalyticsTool:()=>wt,TokenHoldersTool:()=>bt,TokenInfoTool:()=>yt,TokenScoreTool:()=>kt,ToolRegistry:()=>ct,TopGainersTool:()=>vt,TopPoolsTool:()=>Jt,TransactionByHashTool:()=>It,TrendingTokensTool:()=>Tt,UNISWAP_CHAIN_SLUG:()=>$n,UpstashKnowledgeBase:()=>Qe,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Uo,WALLET_AGENT_TOOL_NAMES:()=>xo,WalletActionAppTool:()=>Vn,WalletApprovalsTool:()=>Et,WalletDefiPositionsTool:()=>Nt,WalletDefiProtocolPositionsTool:()=>Ut,WalletDefiSummaryTool:()=>Rt,WalletHistoryTool:()=>St,WalletNFTsTool:()=>Dt,WalletNftTransfersTool:()=>xt,WalletPnlSummaryTool:()=>Ct,WalletPnlTool:()=>_t,WalletTokenBalancesTool:()=>At,WalletTokenTransfersTool:()=>Pt,WebsiteTrustKeyringAgent:()=>Mo,ZERO_ADDRESS:()=>F,amazonDomainForLanguage:()=>er,apiClient:()=>x,buildChallenge:()=>$o,buildRangePresets:()=>ur,buildUniswapPoolUrl:()=>fe,clampTick:()=>De,completeX402:()=>Vo,configureSupportedChains:()=>oo,createAiAgent:()=>jn,createDefaultSubagents:()=>Io,createNfcAgent:()=>Kn,createNftAgent:()=>Yn,createPoolAgent:()=>zn,createTokenAgent:()=>Gn,createWalletActionAgent:()=>Xn,createWalletActionAppTools:()=>Po,createWalletAgent:()=>Hn,createX402SignatureProvider:()=>Ho,displayFromChallenge:()=>Rr,encodeSignedHeader:()=>Wo,ethCallAt:()=>ms,ethCallByChain:()=>cr,fetchTopMarketplaces:()=>tr,getAffiliateFee:()=>Yt,getChainMeta:()=>ne,getDefaultRpcUrl:()=>Aa,getGatewayAddress:()=>bo,getGatewayChains:()=>wo,getNativeTokenInfo:()=>Xt,getPositionManagerAddress:()=>ko,getProviderByChain:()=>go,ingestKnowledgeBase:()=>Fs,isAbortError:()=>lt,nfcAmazonSearchUrl:()=>ao,normaliseCountry:()=>lo,normalizePriceRangeToPool:()=>Gt,priceToTick:()=>rt,requestWithX402:()=>ai,resolveNfcShopLinks:()=>qt,resolveRpcUrl:()=>Kt,roundTickToSpacing:()=>Le,rpcCall:()=>$e,setRpcOverrides:()=>lr,swapServiceFactory:()=>Oe,tickToPrice:()=>xe,toPantographChain:()=>Ei});module.exports=js(Kl);var Pr=Ks(require("axios"));var Sr="0.2.38";var Xs=`keyring-agent-core/${Sr} (Keyring Chatbot Agent; +https://keyring.app)`,Qs="payment-required",Bo=null;function xr(a){Bo=a}function Js(a){return a?Object.keys(a).some(e=>e.toLowerCase()==="payment-signature"):!1}var Zs=3e4,ei=typeof process<"u"&&process.versions?.node!=null,Fo=class{instance;constructor(e={}){this.instance=Pr.default.create({baseURL:e.baseURL,timeout:e.timeout??Zs,validateStatus:()=>!0,headers:{Accept:"application/json",...ei?{"User-Agent":e.userAgent??Xs}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[l,c]of Object.entries(o.headers??{}))c!=null&&(s[l.toLowerCase()]=String(c));let i={ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:s};if(i.status===402&&i.headers[Qs]&&Bo&&!Js(r.headers)){let l=await Bo(i,{url:t,method:String(e),body:n,headers:r.headers});if(l)return this.request(e,t,n,{...r,headers:{...r.headers,...l}})}return i}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Fo;function I(a){let{data:e,status:t,statusText:n}=a,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=l=>l&&typeof l=="object"?l.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}var ti={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},Cr="payment-required",ni="PAYMENT-SIGNATURE";function oi(a){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(a),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(a,"utf8").toString("base64")}function ri(a){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(a,"base64").toString("utf8")}function si(){let a=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(a);else for(let t=0;t<32;t++)a[t]=Math.floor(Math.random()*256);return"0x"+Array.from(a,t=>t.toString(16).padStart(2,"0")).join("")}function ii(a){let[e,t]=String(a).split(":"),n=parseInt(t,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${a}`);return n}function _r(a){if(!a.query||Object.keys(a.query).length===0)return a.url;let e=Object.entries(a.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return a.url.includes("?")?`${a.url}&${e}`:`${a.url}?${e}`}function Er(a){return JSON.parse(ri(a))}function $o(a,e,t,n){let r=a.headers[Cr];if(!r)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=Er(r),s=o.accepts?.[0];if(!s)throw new Error("402 response offered no payment requirements");if(s.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${s.scheme} (only "exact" is supported)`);if(!t)throw new Error("No connected wallet address to build the payment from");let i=ii(s.network),l=Math.floor(Date.now()/1e3),c={from:t,to:s.payTo,value:String(s.amount),validAfter:"0",validBefore:String(l+(s.maxTimeoutSeconds??300)),nonce:si()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:i,verifyingContract:s.asset},types:ti,primaryType:"TransferWithAuthorization",message:{...c}};return{request:{url:_r(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:s,authorization:c,typedData:d,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:c},resource:o.resource,accepted:s,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function ai(a,e,t,n){let r=_r(e),o=await a.request(e.method??"GET",r,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:$o(o,e,t,n)};if(!o.ok)throw new Error(I(o));return{status:"ok",data:o.data}}async function Vo(a,e,t){let{url:n,method:r,body:o,headers:s}=e.request,i=await a.request(r,n,o,{headers:{...s??{},...Wo(e,t)}});if(i.ok)return i.data;let l=i.headers[Cr];if(l)try{let c=Er(l);if(c.error)throw new Error(`x402 payment rejected: ${c.error}`)}catch(c){if(c instanceof Error&&c.message.startsWith("x402 payment rejected"))throw c}throw new Error(I(i))}var li={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function Wo(a,e){let t={...a.paymentDraft,payload:{authorization:a.authorization,signature:e}};return{[ni]:oi(JSON.stringify(t))}}function Rr(a){let e=a.requirements,t=a.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:li[e.network]||e.network,payTo:e.payTo,...t?.description?{description:t.description}:{},resourceUrl:a.request.url}}function Ho(a){return async(e,t)=>{let n=a.getPayer(),r=a.getSigner();if(!n||!r)return null;let o;try{o=$o(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let s;try{s=await r({typedData:o.typedData,display:Rr(o)})}catch{s=null}return s?Wo(o,s):null}}var nt=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function lt(a){if(!a||typeof a!="object")return!1;let e=a;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Go(a){if(a?.aborted)throw new nt}function Nr(a,e){if(!e)return{signal:a.signal,cleanup:()=>{}};if(e.aborted)return a.abort(),{signal:a.signal,cleanup:()=>{}};let t=()=>a.abort();return e.addEventListener("abort",t),{signal:a.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Ur={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},ci="https://nft.keyring.app/api/gemini-stable",ui=new Set([408,429,500,502,503,504]),Ir=3e4,to=a=>new Promise(e=>setTimeout(e,a));function no(a,e,t){if(t!=null&&t>0)return Math.min(t,Ir);let n=Math.min(e*2**(a-1),Ir);return n/2+Math.random()*(n/2)}function di(a){if(!a)return null;let e=Number(a);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(a);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var z=class{model;maxTokens;temperature;baseUrl;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??ci}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;Go(l);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 f=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}: [${f}]`)}}let d={contents:c,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(d.systemInstruction=r),t?.length?(d.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(d.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(d.tools=[{googleSearch:{}}]);let u=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){Go(l);let f;try{f=await x.post(u,d,{headers:{"Content-Type":"application/json"},signal:l})}catch(T){if(lt(T))throw T;if(p=T instanceof Error?T.message:String(T),m>=s)break;await to(no(m,i));continue}if(!f.ok){let T=typeof f.data=="string"?f.data:JSON.stringify(f.data)||f.statusText;if(p=`Gemini proxy error ${f.status}: ${T}`,!ui.has(f.status))throw new Error(p);if(m>=s)break;let A=di(f.headers["retry-after"]??null);await to(no(m,i,A));continue}if(f.data==null||typeof f.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await to(no(m,i));continue}let h=f.data,g=h.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let y="",b=[],w=g.content?.parts;if(!Array.isArray(w)||w.length===0){let T=g.finishReason;if(!(T==="SAFETY"||T==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${T??"none"})`,await to(no(m,i));continue}return{text:"",toolCalls:[]}}for(let T of w)T.text&&(y+=T.text),T.functionCall&&b.push({toolName:T.functionCall.name,args:T.functionCall.args??{},callId:T.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let k=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:k}}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(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(u=>u.functionCall),d=l?.parts.some(u=>u.functionCall);l&&l.role===i.role&&!c&&!d?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let l=r[i],c=o[o.length-1];l.role==="function"&&!c?.parts.some(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.functionCall)&&!(r[i+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
2
+ `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:Ur[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:Ur[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 ct=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 ut=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],pi=new Set(ut),He=[...ut],Yo=new Set(He),be="0x1",mt="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function mi(a){return a.map(e=>pt[e]??e).join(", ")}function oo(a){let e=new Set;if(a)for(let n of a){let r=ro(n);r&&e.add(r)}let t=ut.filter(n=>!e.has(n));He=t.length>0?[...t]:[...ut],Yo=new Set(He),be=He.includes("0x1")?"0x1":He[0],mt=mi(He)}var hi={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function $(a){let e=ro(a);return e&&Yo.has(e)?e:null}function ro(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=hi[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&&pi.has(n)?n:null}function Pe(a){return $(a)!==null}function we(){return[...He]}var dt=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${mt}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ge=a=>typeof a=="string"&&a.trim()!=="";function le(a,e){if(Ge(a)){let t=$(a);if(t)return t;throw new dt(a.trim())}if(Ge(e?.chain)){let t=$(e.chain);if(t)return t;throw new dt(e.chain.trim())}return null}function so(a,e){return $(a)??$(e?.chain)??void 0}var pt={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function P(a){let e=ro(a);return e&&pt[e]?pt[e]:typeof a=="string"&&a.trim()?a.trim():"the requested chain"}var gi={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function Lr(a,e){let t=ro(a),n=t?gi[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var fi={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Dr(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase();return e?fi[e]??null:null}var yi={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function Or(a){let e=$(a);return e?yi[e]??null:null}function ht(a,e){if(!Ge(a))return null;let t=$(a),n=$(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:pt[t]??t,connectedLabel:pt[n]??n}}function Mr(a,e){let t=typeof a=="string"?a.trim():"",n=e&&e.length?e.filter(o=>Yo.has(o)):[];return(n.length?n:He).map(o=>{let s=pt[o]??o;return{label:s,prompt:t?`${t} (${s})`:s}})}function gt(a,e){return{actionButtons:Mr(e),_instructions:`The user wants to ${a} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var K=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=Mr(e,t)}},Ln=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 X(a,e){if(Ge(a))return a.trim();if(Ge(e?.walletAddress))return e.walletAddress.trim();throw new Ln}function Z(a,e,t){if(Ge(a)){let n=$(a);if(n)return n;throw new dt(a.trim())}if(Ge(e?.chain)){let n=$(e.chain);if(n)return n;throw new dt(e.chain.trim())}if(Ge(e?.walletAddress))throw new K(typeof e?.query=="string"?e.query:void 0,t);return be}var v=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s=bi(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 Ln?{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 bi(a){if(!a||typeof a!="object")return{data:a};let e=a,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:a};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var qr=require("js-sha3");function B(a){return typeof a=="string"&&/^0x[0-9a-fA-F]{40}$/.test(a)}function wi(a){return new Uint8Array(qr.keccak256.arrayBuffer(a))}function Dn(a){let e=a.startsWith("0x")?a.slice(2):a,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function Br(a){return"0x"+Array.from(a).map(e=>e.toString(16).padStart(2,"0")).join("")}function Fr(a){return new TextEncoder().encode(a)}function ot(...a){let e=a.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;return t}function ki(a,e=32){let t=new Uint8Array(e);return t.set(a,e-a.length),t}function Ti(a,e=32){let t=new Uint8Array(e);return t.set(a),t}function $r(a){let e=((a%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Dn(e)}function On(a){return $r(BigInt(a))}function Vr(a){return a==="uint"?"uint256":a==="int"?"int256":a.match(/^uint$/)?"uint256":a.match(/^int$/)?"int256":a.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function Wr(a){let e=Vr(a.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(a.components??[]).map(Wr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function vi(a){let e=(a.inputs??[]).map(Wr).join(",");return`${a.name??""}(${e})`}function Ko(a,e){let t=Pi(a.type);if(t){let[r,o]=t;return Ai({...a,type:o},e,r)}if(a.type==="tuple")return Si(a,e);if(a.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:ki(Dn(o.toLowerCase()))}}if(a.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Vr(a.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:On(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:$r(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Dn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ti(o)}}if(n==="bytes"){let r=typeof e=="string"?Dn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:ot(On(r.length),s)}}if(n==="string"){let r=typeof e=="string"?Fr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:ot(On(r.length),s)}}throw new Error(`Unsupported ABI type: ${a.type}`)}function jo(a){let e=0;for(let{dynamic:o,encoded:s}of a)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of a)o?(t.push(On(e+r)),n.push(s),r+=s.length):t.push(s);return ot(...t,...n)}function Ai(a,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let i=Ko(a,s);i.dynamic&&(r=!0),o.push(i)}if(n||r){let s=jo(o);if(n){let i=On(o.length);return{dynamic:!0,encoded:o.length>0?ot(i,s):i}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:ot(...o.map(s=>s.encoded))}}function Si(a,e){let t=a.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],i=Array.isArray(e)?e[o]:e[s.name??""],l=Ko(s,i);l.dynamic&&(n=!0),r.push(l)}return{dynamic:n,encoded:n?jo(r):ot(...r.map(o=>o.encoded))}}function Pi(a){let e=a.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function xi(a,e){if(a.length!==e.length)throw new Error(`Expected ${a.length} values, got ${e.length}`);if(a.length===0)return"0x";let t=a.map((r,o)=>Ko(r,e[o])),n=jo(t);return Br(n)}function ft({abi:a,functionName:e,args:t=[]}){let n=a.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=vi(n),o=wi(Fr(r)).slice(0,4),s=n.inputs??[],i=s.length===0||t.length===0?new Uint8Array(0):Dn(xi(s,t).slice(2));return Br(ot(o,i))}var Ci="https://deblo-api-dev.pantograph.app",_i="0x0000000000000000000000000000000000000000",Yr={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Kr={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function Ei(a){return Yr[a.toLowerCase()]||a}function Hr(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function zo(a){let e=a,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function Xo(a){if(Array.isArray(a))return a;let e=a;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function se(a){if(a==null)return null;let e=typeof a=="number"?a:parseFloat(String(a));return Number.isFinite(e)?e:null}function Gr(a,e){let t=a.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=se(a.price_change_percentage_24h)??se(a.priceChange24h)??se(a.usd_price_24hr_percent_change)??se(a.price_change_24h)??se(a.priceChange);return{chainId:e,tokenAddress:a.address??a.token_address??"",name:a.name??null,symbol:a.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:a.logoURI??a.icon_image??a.logo??null,usdPrice:se(a.price)??se(a.usd_price),marketCap:se(a.market_cap)??se(a.marketCap),totalVolume:{"24h":se(a.total_volume)??se(a.volume24h)},pricePercentChange:{"24h":r}}}var ie=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Ci).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),r=this.tokensUrl(t,n),o=await x.get(r);if(!o.ok)return;let s=Xo(o.data),i=new Map;for(let l of s)l.address&&i.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=i.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),r=await x.get(n);if(!r.ok)return null;let o=Xo(r.data),s=e.toLowerCase()===_i,i=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||s&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||s&&l.token_address==="");return i?zo(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=this.tokensUrl(t,e.join(",")),o=await x.get(r);if(!o.ok)return n;let s=Xo(o.data),i=new Set(e.map(l=>l.toLowerCase()));for(let l of s){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&i.has(c)&&(n[c]=zo(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||be,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=Hr({chainId:o,key:t}),i=`${this.baseUrl}/token-list/all?${s}`,l=await x.get(i);if(!l.ok)throw new Error(I(l));let c=l.data,d=c?.result??c?.data??c,u=[];return Array.isArray(d)?u=d:d&&typeof d=="object"&&(u=Object.values(d).flat()),{success:!0,data:u.map(zo)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||be,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=Kr[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],d=l.status==="fulfilled"?o.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>Gr(h,t)):[],u=new Set,p=[];for(let h of d){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),m.push(h))}let f=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=se(s.market_cap)??se(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":se(s.total_volume)??se(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=parseInt(e,16),o=Hr({chainId:r,duration:n,limit:t}),s=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(s);if(!c.ok)throw new Error(I(c));let d=c.data;if(i=Array.isArray(d)?d:Array.isArray(d.data)?d.data:[],i.length>0)break;l<4&&await new Promise(u=>setTimeout(u,2e3))}return i.map(l=>Gr(l,e))}async getTopGainers(e){let t=e?.chain||be,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 Ri="https://nft.keyring.app",Ni="https://nft.keyring.app",Ui=.01,N=5,W=1e3,Ii="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Li="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function j(a){return a||be}function H(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function G(a){return new Promise(e=>setTimeout(e,a))}function Di(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Qo(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ri).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Ni).replace(/\/+$/,""),this.pantograph=new ie({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=j(n),l="Unknown error";for(let c=1;c<=N;c++)try{let d={chain:i,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(d.token_addresses=r);let u=[],p=null;do{p&&(d.cursor=p);let f=H(d),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${f}`,g=await x.get(h);if(!g.ok)throw new U(g.status,I(g));let y=g.data,b=y?.data??y;b?.result?.length>0&&u.push(...b.result),p=b?.cursor??null}while(p);let m={result:u};return m?.result?.length>0&&(m.result=m.result.filter(f=>parseFloat(f.balance||"0")>0),m.result=m.result.map(f=>({...f,token_address:f.token_address.toLowerCase()===Ii?Li:f.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(f=>f.usd_value==null||f.usd_value>=Ui)),{success:!0,data:m}}catch(d){if(l=d instanceof Error?d.message:"Unknown error",d instanceof U&&d.status===400)break;c<N&&await G(W)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=j(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${H({chain:r,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${H({chain:r,include:"percent_change"})}`)]),d=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;d=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!d){o="Token metadata not found",i<N&&await G(W);continue}let u=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;u=p?.data??p}return{success:!0,data:{...d,...u?.usd_price?{usd_price:u.usd_price}:{},...u?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:u.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await 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:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let d=j(n),u="Unknown error";for(let p=1;p<=N;p++)try{let m={chain:d,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(m.cursor=s),l&&(m.include_prices=!0),i&&i.length>0&&(m.token_addresses=i);let f=H(m),h=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${f}`,g=await x.get(h);if(!g.ok)throw new U(g.status,I(g));let y=g.data;return{success:!0,data:y?.data??y}}catch(m){if(u=m instanceof Error?m.message:"Unknown error",m instanceof U&&m.status===400)break;p<N&&await G(W)}return{success:!1,error:u}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!B(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=j(r),d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:i};l&&(p.include=l);let m=H(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await x.get(f);if(!h.ok)throw new U(h.status,I(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;u<N&&await G(W)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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:l,cursor:c,order:d="DESC",includeInternalTransactions:u,nftMetadata:p}=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 m=j(n),f=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let g=1;g<=N;g++)try{let y={chain:m,limit:f,order:d};o&&(y.from_date=o),s&&(y.to_date=s),i!=null&&(y.from_block=i),l!=null&&(y.to_block=l),c&&(y.cursor=c),u!=null&&(y.include_internal_transactions=u),p!=null&&(y.nft_metadata=p);let b=H(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,k=await x.get(w);if(!k.ok)throw new U(k.status,I(k));let T=k.data;return{success:!0,data:T?.data??T}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;g<N&&await 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:l,toBlock:c,cursor:d,order:u="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 p=j(n),m=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let h=1;h<=N;h++)try{let g={chain:p,limit:m,order:u};s&&(g.from_date=s),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),d&&(g.cursor=d),r?.length&&(g.contract_addresses=r);let y=H(g),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await x.get(b);if(!w.ok)throw new U(w.status,I(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(g){if(f=g instanceof Error?g.message:"Unknown error",g instanceof U&&g.status===400)break;h<N&&await G(W)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=j(n),h=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=N;y++)try{let b={chain:f,limit:h,order:u,format:m};s&&(b.from_date=s),i&&(b.to_date=i),l!=null&&(b.from_block=l),c!=null&&(b.to_block=c),d&&(b.cursor=d),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=H(b),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,T=await x.get(k);if(!T.ok)throw new U(T.status,I(T));let A=T.data;return{success:!0,data:A?.data??A}}catch(b){if(g=b instanceof Error?b.message:"Unknown error",b instanceof U&&b.status===400)break;y<N&&await G(W)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!B(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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(!B(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=j(n),s="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:o};r&&(l.days=r);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data;return{success:!0,data:p?.data??p}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await 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(!B(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let d=H(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await x.get(u);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await 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=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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(!B(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let d=H(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await x.get(u);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await 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(!B(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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(!B(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:Di(u)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&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(!B(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=j(r),s="Unknown error";for(let i=1;i<=N;i++)try{let l=H({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,d=await x.get(c);if(!d.ok)throw new U(d.status,I(d));let m=d.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(g=>({token_type:g.tokenType,address:g.address,contract_address:g.address,name:g.name??"",symbol:g.symbol??"",decimals:g.decimals??18,logo:g.logo,balance:g.balance??"0",balance_formatted:g.balanceFormatted??"0",usd_price:g.usdPrice,usd_value:g.usdValue}))}))}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await 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(!B(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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(!B(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await 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<=N;o++)try{let s={};t&&(s.chain=j(t)),n!=null&&(s.limit=n);let i=H(s),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:Qo(u)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof U&&s.status===400)break;o<N&&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<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data,m=p?.data??p;return{success:!0,data:Qo(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&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<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data,m=p?.data??p;return{success:!0,data:Qo(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await G(W)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var yt=class extends v{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new z(e?.llm??{})}async run(e,t){let n=e.keyword||"",r=Z(e.chain,t),o=e.prompt||"",s=t?.walletAddress||void 0;return n?await this.searchToken(n,r,o,s):{error:"Missing required parameter: keyword"}}async searchToken(e,t,n,r){let o=[r?`User's connected wallet address: ${r}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
3
3
  `),[s,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),r?this.findTokenInWallet(r,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,o):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],d=e.toLowerCase(),u=g=>g.symbol?.toLowerCase()===d||g.token_address?.toLowerCase()===d,p=[...c].sort((g,y)=>(u(g)?0:1)-(u(y)?0:1)),m=null,f=p[0];if(f?.token_address){let g=await this.service.getTokenMetadata({address:f.token_address,chain:t});g.success&&g.data&&(m=g.data)}return!m&&f&&(m={...f}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:t,userHoldsToken:!!i,walletBalance:i,token:m,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!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 bt=class extends v{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Z(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(o){let u=await this.resolveContractAddress(o,n,r);if(!u)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenHolders({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var wt=class extends v{name="get-token-analytics";description=`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Z(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let u=await this.resolveContractAddress(o,n,r);if(!u)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenAnalytics({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var kt=class extends v{name="get-token-score";description=`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Z(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},u=d.metrics??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:u.usdPrice??null,liquidityUsd:u.liquidityUsd??null,volumeUsd:u.volumeUsd??null,transactions:u.transactions??null,supply:u.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Tt=class extends v{name="get-trending-tokens";description='List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad, and more.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1}];service;constructor(e){super(),this.service=new ie({baseUrl:e?.pantographUrl})}async run(e,t){let n=so(e.chain,t),r=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,o=await this.service.getTrendingTokens({chain:n,limit:r});if(!o.success)return{error:o.error||"Failed to fetch trending tokens"};let s=o.data??[];return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
4
4
  <rank>. <name> (<symbol>)
5
5
  - Price: <usdPrice>
@@ -14,7 +14,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
14
14
  - 24h Volume: <totalVolume.24h>
15
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?P(n):"all",timeFrame:o??null,count:c.length,tokens:c}}};var At=class extends v{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,r=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(r+"00").slice(0,2)}`}async run(e,t){let n=X(e.address,t),r=le(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=we(),s=await Promise.all(o.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,s)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",r=e.symbol||"",o=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${r} (${o})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let r=n.reduce((o,s)=>o+(s.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(r)}`,tokens:n.map(o=>this.toTokenLine(o))}}renderBalancesByChain(e,t){let n=t.map(o=>{let s=o.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=o.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:P(o.chain),total:s,tokens:i}}).filter(o=>o.tokens.length>0).sort((o,s)=>s.total-o.total),r=n.reduce((o,s)=>o+s.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(r)}`,chains:n.map(o=>({chain:o.chain,totalUsdValue:`$${this.truncateUsd(o.total)}`,tokens:o.tokens.map(s=>this.toTokenLine(s))}))}}};var St=class extends v{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=X(e.address,t),r=Z(e.chain,t),o=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,s=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,d=Number.isFinite(l)?l:void 0,u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,y=Number.isFinite(g)&&g>0?g:10,b=await this.service.getWalletHistory({address:n,chain:r,limit:y,fromDate:o,toDate:s,fromBlock:c,toBlock:d,cursor:u,order:m,includeInternalTransactions:f,nftMetadata:h});if(!b.success)return{error:b.error||"Failed to fetch wallet history"};let k=(b.data?.result||[]).map(T=>{let A=Lr(r,T.hash);return A?{...T,explorerUrl:A}:T});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:r||"default",pagination:{cursor:b.data?.cursor??null,hasMore:!!b.data?.cursor},transactionCount:k.length,transactions:k}}};function Oi(a){if(a.value_decimal)return a.value_decimal;let e=parseInt(a.token_decimals??"18",10);if(isNaN(e)||e===0)return a.value;try{let t=BigInt(a.value),n=BigInt(10)**BigInt(e),r=t/n,s=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return s?`${r}.${s}`:`${r}`}catch{return a.value}}var Pt=class extends v{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=X(e.address,t),r=Z(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,b,w;if(g){let C=await this.resolveContractAddressBySymbol(g,n,r);C&&(y=[C.address],b=C.symbol,w=C.name)}let k=await this.service.getWalletTokenTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let T=n.toLowerCase(),S=(k.data?.result||[]).map(C=>{let M=C.from_address.toLowerCase()===T,_=M?"send":"receive",Q=M?C.to_address:C.from_address,O=M?C.to_address_label??void 0:C.from_address_label??void 0,Ue=M?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:_,amount_formatted:Oi(C),counterparty:Q,counterparty_label:O,counterparty_entity:Ue}}),R=h==="all"?S:S.filter(C=>C.direction===h);if(g&&!y){let C=g.toLowerCase();R=R.filter(M=>(M.token_symbol??"").toLowerCase()===C)}let E=this.buildCounterparties(R);return{walletAddress:n,chain:r||"default",resolvedToken:b?{symbol:b,name:w,contractAddress:y?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:y||null,direction:h,limit:s,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??s,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:R.length,transfers:R,counterparties:E}}async resolveContractAddressBySymbol(e,t,n){let r=e.toLowerCase(),o=await this.service.getWalletTokenBalances({address:t,chain:n});if(o.success&&o.data?.result?.length){let i=o.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let s=await this.service.searchTokensByKey({key:e,chain:n});if(s.success&&s.data?.length){let l=s.data.find(c=>(c.symbol??"").toLowerCase()===r)??s.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let s=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=parseFloat(o.amount_formatted)||0,c=s.get(i);c?(c.total+=l,c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):s.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,total:l,count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((s,i)=>i[1].count-s[1].count).map(([s,i])=>({address:s,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var xt=class extends v{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=X(e.address,t),r=Z(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(R=>typeof R=="string"&&!!R).map(R=>R.trim()):void 0,b=await this.service.getWalletNftTransfers({address:n,chain:r,contractAddresses:y,limit:s,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m,includePrices:f});if(!b.success)return{error:b.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),T=(b.data?.result||[]).map(R=>{let E=R.from_address.toLowerCase()===w,C=E?"send":"receive",M=E?R.to_address:R.from_address,_=E?R.to_address_label??void 0:R.from_address_label??void 0,Q=E?R.to_address_entity??void 0:R.from_address_entity??void 0;return{...R,direction:C,counterparty:M,counterparty_label:_,counterparty_entity:Q}}),A=g==="all"?T:T.filter(R=>R.direction===g),S=this.buildCounterparties(A);return{walletAddress:n,chain:r||"default",filters:{contractAddresses:y||null,direction:g,limit:s,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null,includePrices:f??null},pagination:{cursor:b.data?.cursor??null,pageSize:b.data?.page_size??s,page:b.data?.page??null,hasMore:!!b.data?.cursor},transferCount: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,i=o.counterparty.toLowerCase(),l=o.token_name??o.token_address,c=s.get(i);c?(c.tokenIds.add(o.token_id),c.collections.add(l),c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):s.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,tokenIds:new Set([o.token_id]),collections:new Set([l]),count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((s,i)=>i[1].count-s[1].count).map(([s,i])=>({address:s,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Mi=["all","7","30","60","90"],Ct=class extends v{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=X(e.address,t),r=le(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=Mi.includes(o)?o:void 0;if(r){let h=await this.service.getWalletPnlSummary({address:n,chain:r,days:s});return h.success?{walletAddress:n,chain:r,days:s??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(we().map(async h=>{let g=await this.service.getWalletPnlSummary({address:n,chain:h,days:s});return{chain:h,data:g.success?g.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:P(h.chain),summary:this.mapSummary(h.data)})),d=l.reduce((h,g)=>h+Number(g.data.total_realized_profit_usd||0),0),u=l.reduce((h,g)=>h+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((h,g)=>h+Number(g.data.total_sold_volume_usd||0),0),m=l.reduce((h,g)=>h+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((h,g)=>h+g.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:u>0?d/u*100:0,totalBuys:l.reduce((h,g)=>h+g.data.total_buys,0),totalSells:l.reduce((h,g)=>h+g.data.total_sells,0),totalBoughtVolumeUsd:u,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:s??"all",summary:f,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var qi=["all","7","30","60","90"],io=25,_t=class extends v{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${io}. 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 ${io}.`,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 ${io}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=X(e.address,t),r=le(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",s=qi.includes(o)?o:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[];if(r){let u=await this.fetchChainPnl(n,r,s,i,l);return u.ok?{walletAddress:n,chain:r,days:s??"all",filters:{tokenAddresses:u.tokenAddresses??null,resolvedSymbols:u.resolvedFromSymbols.length>0?u.resolvedFromSymbols:null,unresolvedSymbols:u.unresolvedSymbols.length>0?u.unresolvedSymbols:null},tokenCount:u.tokens.length,tokens:u.tokens}:{error:u.error||"Failed to fetch wallet PnL"}}let d=(await Promise.all(we().map(async u=>({chain:u,res:await this.fetchChainPnl(n,u,s,i,l)})))).filter(u=>u.res.ok&&u.res.tokens.length>0).map(u=>({chain:P(u.chain),tokenCount:u.res.tokens.length,tokens:u.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:s??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:d.reduce((u,p)=>u+p.tokenCount,0),chains:d}}async fetchChainPnl(e,t,n,r,o){let s=[],i=[];r.length>0&&(await Promise.all(r.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?s.push({symbol:r[m],address:p.address}):i.push(r[m])});let l=Bi([...s.map(u=>u.address),...o]).slice(0,io),c=l.length>0?l:void 0,d=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:c,resolvedFromSymbols:s,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Bi(a){let e=new Set,t=[];for(let n of a){let r=n.toLowerCase();e.has(r)||(e.add(r),t.push(n))}return t}var Fi=BigInt(2)**BigInt(255),Et=class extends v{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=X(e.address,t),r=Z(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),s=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:r,limit:s,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,u=(c.result||[]).map(h=>$i(h)),p=0,m=0,f=[];for(let h of u){h.isUnlimited&&(m+=1);let g=parseFloat(h.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let y=h.token.possibleSpam||h.token.verifiedContract===!1,b=!h.spender.label&&!h.spender.entity;(y||h.isUnlimited&&b)&&f.push(h)}return{walletAddress:n,chain:r||"default",filters:{limit:s,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??s,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:u.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:u,riskyApprovals:f}}};function $i(a){let e=Vi(a.value);return{blockNumber:a.block_number,blockTimestamp:a.block_timestamp??null,transactionHash:a.transaction_hash??null,value:a.value,valueFormatted:a.value_formatted??null,isUnlimited:e,token:{address:a.token.address,addressLabel:a.token.address_label??null,name:a.token.name??null,symbol:a.token.symbol??null,logo:a.token.logo??null,possibleSpam:!!a.token.possible_spam,verifiedContract:a.token.verified_contract??null,currentBalance:a.token.current_balance??null,currentBalanceFormatted:a.token.current_balance_formatted??null,usdPrice:a.token.usd_price??null,usdAtRisk:a.token.usd_at_risk??null},spender:{address:a.spender.address,label:a.spender.address_label??null,entity:a.spender.entity??null,entityLogo:a.spender.entity_logo??null}}}function Vi(a){if(!a)return!1;try{return BigInt(a)>=Fi}catch{return!1}}var Rt=class extends v{name="get-wallet-defi-summary";description=`Get a wallet's DeFi protocols summary: which protocols the wallet is using, total USD value locked across all protocols, total unclaimed rewards/fees, number of active protocols, and total number of positions. Returns a per-protocol breakdown (protocol name, logo, url, positions count, usd value, unclaimed). Use for questions like: "Which DeFi protocols am I using?", "What's my total DeFi value?", "How much do I have in DeFi?", "Show my DeFi portfolio overview", "Unclaimed rewards across protocols". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Do NOT use for: detailed per-position data \u2192 get-wallet-defi-positions; positions inside a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=X(e.address,t),r=le(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(we().map(async i=>{let l=await this.service.getWalletDefiSummary({address:n,chain:i});return{chain:i,data:l.success?l.data:void 0}}))).flatMap(i=>i.data&&i.data.active_protocols>0?[{chain:P(i.chain),data:i.data}]:[]).map(i=>({chain:i.chain,...this.summaryFields(i.data)})).sort((i,l)=>l.totalUsdValue-i.totalUsdValue);return{_instructions:"These DeFi summaries cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains with DeFi activity, highest total value first). Present one section per chain, in order: the chain name then its protocols. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",totalUsdValue:s.reduce((i,l)=>i+l.totalUsdValue,0),totalUnclaimedUsdValue:s.reduce((i,l)=>i+l.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 Nt=class extends v{name="get-wallet-defi-positions";description='Get every DeFi position a wallet holds across all supported protocols, with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Do NOT use for: aggregate totals \u2192 get-wallet-defi-summary; positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=X(e.address,t),r=le(e.chain,t);if(r){let i=await this.service.getWalletDefiPositions({address:n,chain:r});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:r,positionCount:l.length,positions:l.map(Xr)}}let s=(await Promise.all(we().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:P(i.chain),positionCount:i.rows.length,positions:i.rows.map(Xr)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:s.reduce((i,l)=>i+l.positionCount,0),chains:s}}};function Xr(a){return{protocolName:a.protocol_name,protocolId:a.protocol_id,protocolUrl:a.protocol_url,protocolLogo:a.protocol_logo,accountHealthFactor:a.account_data?.health_factor??null,position:Wi(a.position)}}function Wi(a){return{label:a.label,address:a.address,balanceUsd:a.balance_usd,totalUnclaimedUsdValue:a.total_unclaimed_usd_value,tokens:(a.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:a.position_details??null}}var Ut=class extends v{name="get-wallet-defi-protocol-positions";description='Get every position a wallet holds inside a specific DeFi protocol, with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "what do I have on Aave v3", "show my Lido staking", "my Curve pools", "Pendle positions". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions; totals only \u2192 get-wallet-defi-summary.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-summary to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let r=X(e.address,t),o=le(e.chain,t);if(o){let l=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:o});return l.success?l.data?{walletAddress:r,chain:o,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(we().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:P(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:r,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(Hi)}}};function Hi(a){return{label:a.label,address:a.address,balanceUsd:a.balance_usd,totalUnclaimedUsdValue:a.total_unclaimed_usd_value,tokens:(a.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:a.position_details??null}}function Gi(a){try{return(Number(BigInt(a))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return a}}var It=class extends v{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let r=Z(e.chain,t),o=await this.service.getTransactionByHash({transactionHash:n,chain:r});if(!o.success||!o.data)return{error:o.error||"Failed to fetch transaction"};let s=o.data,i=(s.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=s.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:s.hash,status:s.receipt_status==="1"?"success":s.receipt_status==="0"?"failed":"unknown",timestamp:s.block_timestamp,blockNumber:s.block_number,from:{address:s.from_address,label:s.from_address_label||null,entity:s.from_address_entity||null},to:s.to_address?{address:s.to_address,label:s.to_address_label||null,entity:s.to_address_entity||null}:null,valueEth:Gi(s.value||"0"),fee:s.transaction_fee,gasUsed:s.receipt_gas_used,gasPriceGwei:s.gas_price?(Number(s.gas_price)/1e9).toFixed(4):null,decodedCall:s.decoded_call?{signature:s.decoded_call.signature,label:s.decoded_call.label,params:s.decoded_call.params}:null,decodedEvents:i,contractCreated:s.receipt_contract_address||null,logs:l}}};var Lt=class extends v{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 Dt=class extends Lt{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 Yi="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",Ie=class extends v{kind="data";category="nft";llm;constructor(){super(),this.llm=new z({})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:Yi,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Ot=class extends Ie{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=Ie.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 Ie{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=Ie.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 Jo={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},Zo="amazon.com";function Ki(a){return a?a.trim().toLowerCase().split(/[-_]/)[0]:""}function er(a){let e=Ki(a);return Jo[e]??Zo}function ao(a){return`https://${er(a)}/s?k=NFC%20Tag`}function lo(a){if(!a)return"";let e=a.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var ji=720*60*1e3,Qr=new Map,Jr=3;function zi(a){return[`A user in country "${a}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Jr} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function Xi(a){if(!a)return[];let e=a.indexOf("["),t=a.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(a.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let r=[],o=new Set;for(let s of n){if(!s||typeof s!="object")continue;let i=s.label,l=s.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!o.has(c)&&(o.add(c),r.push({label:i.trim(),url:l.trim()}),r.length>=Jr))break}return r}async function tr(a,e){let t=lo(a);if(!t||!e)return null;let n=Qr.get(t);if(n&&n.expires>Date.now())return n.links;let r=Date.now(),o=[{role:"user",content:zi(t),timestamp:r}];try{let s=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),i=Xi(s.text);if(i.length)return Qr.set(t,{links:i,expires:Date.now()+ji}),i}catch{}return null}async function qt(a){let e=await tr(a.country,a.llm);return e&&e.length?e:[{label:"Amazon",url:ao(a.language)}]}function Qi(a){return a.length<=1?a.length===1?`[${a[0].label}](${a[0].url})`:"":a.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
17
+ `+t}}};var Dt=class extends Lt{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 Yi="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",Ie=class extends v{kind="data";category="nft";llm;constructor(e){super(),this.llm=new z(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:Yi,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Ot=class extends Ie{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=Ie.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 Ie{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=Ie.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 Jo={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},Zo="amazon.com";function Ki(a){return a?a.trim().toLowerCase().split(/[-_]/)[0]:""}function er(a){let e=Ki(a);return Jo[e]??Zo}function ao(a){return`https://${er(a)}/s?k=NFC%20Tag`}function lo(a){if(!a)return"";let e=a.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var ji=720*60*1e3,Qr=new Map,Jr=3;function zi(a){return[`A user in country "${a}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Jr} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function Xi(a){if(!a)return[];let e=a.indexOf("["),t=a.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(a.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let r=[],o=new Set;for(let s of n){if(!s||typeof s!="object")continue;let i=s.label,l=s.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!o.has(c)&&(o.add(c),r.push({label:i.trim(),url:l.trim()}),r.length>=Jr))break}return r}async function tr(a,e){let t=lo(a);if(!t||!e)return null;let n=Qr.get(t);if(n&&n.expires>Date.now())return n.links;let r=Date.now(),o=[{role:"user",content:zi(t),timestamp:r}];try{let s=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),i=Xi(s.text);if(i.length)return Qr.set(t,{links:i,expires:Date.now()+ji}),i}catch{}return null}async function qt(a){let e=await tr(a.country,a.llm);return e&&e.length?e:[{label:"Amazon",url:ao(a.language)}]}function Qi(a){return a.length<=1?a.length===1?`[${a[0].label}](${a[0].url})`:"":a.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
18
18
  `)}var Zr=["WHAT IT IS: NFC (Near-Field Communication) is a short-range wireless standard operating at 13.56 MHz, a",'subset of the older RFID family. An "NFC tag" is a tiny passive chip + antenna (often embedded in a','sticker, card, keyfob, wristband, or ring). "Passive" means it has no battery \u2014 it draws all its power from',"the electromagnetic field of the reader (a smartphone or dedicated reader) when held within ~2\u20134 cm. The","tag does nothing on its own; it simply waits to be tapped, then hands over the small piece of data it holds.","","HOW IT WORKS: When an NFC-enabled phone comes close, the reader emits a 13.56 MHz radio field. Through","inductive (magnetic) coupling that field powers the tag, which then transmits its stored data back to the","reader \u2014 no pairing, no app launch, no internet required for the handshake. The exchange is bidirectional","and near-instant (well under a second). Tags can be READ many times and, unless locked, also re-WRITTEN.","Data is stored in the standardised NDEF format (NFC Data Exchange Format) so any NFC phone can parse it the","same way. NFC works in three modes: reader/writer (phone reads or writes a tag), peer-to-peer (two devices","exchange data), and card-emulation (the phone itself acts like a tag, e.g. for tap-to-pay).","","WHAT'S INSIDE AN NFC TAG: just two parts \u2014 (1) a microchip (the integrated circuit) that holds a small","block of memory plus simple logic, and (2) a thin coiled antenna (usually etched copper or aluminium) that","both harvests power from the reader's field and carries the data signal. There is no battery and no moving","parts, which is why tags are paper-thin, cheap, and last for years (often rated for ~10 years of storage","and 100,000+ rewrites). Common chips differ mainly by memory size: NTAG213 (~144 bytes), NTAG215","(~504 bytes), NTAG216 (~888 bytes); larger/industrial families (e.g. ICODE, MIFARE) add more memory or","security features.","","WHAT IT CAN STORE: capacity is small \u2014 tens to a few hundred bytes of usable memory \u2014 so a tag holds a","compact payload, not files. Typical contents: a website URL, plain text, a contact card (vCard), Wi-Fi","credentials (SSID + password for one-tap join), an app-launch or deep link, a phone number / email,","geo-coordinates, a Bluetooth pairing handoff, or a small identifier/token. It is NOT mass storage \u2014 large","content lives elsewhere and the tag holds a pointer (a link or ID) to it.","","COMMON REAL-WORLD USES: contactless payments (Apple Pay / Google Pay via card emulation); transit and","access cards (metro, office door badges, hotel keys); product tags and anti-counterfeit / authenticity","checks; smart posters and marketing (tap to open a page, menu, or promo); pairing speakers/headphones with",'one tap; digital business cards and "tap to share contact"; smart-home automations (tap a tag by the door',"to run a routine); inventory, asset tracking, and ticketing; and tap-to-act crypto flows (e.g. open a","wallet address or a dapp link).","","HOW TO USE ONE: (1) Get an NFC tag (sticker/card/keyfob). (2) Make sure the phone has NFC enabled","(Settings \u2192 Connections/NFC; most modern Android phones and iPhone XS and later support it). (3) To WRITE,",'install an NFC writer app (e.g. "NFC Tools"), choose the record type (URL, text, Wi-Fi\u2026), enter the data,',"and tap the phone to the tag to program it. (4) To READ, just tap the phone to the tag \u2014 the action fires","automatically. (5) Optionally LOCK the tag to make it read-only so the data cannot be overwritten. Keep the","tag away from metal surfaces, which can detune the antenna and block reads.","","WHY THEY ARE POPULAR: they are extremely cheap (cents each), battery-free and maintenance-free, work with","the phone almost everyone already carries, and need just a tap \u2014 no app pairing, codes, or setup. The very","short range is a feature, not a bug: you must deliberately bring the devices together, which makes NFC","trusted for payments and access where accidental or remote reads would be a security risk.","","CRYPTO / WALLET CONTEXT: because a tag can hold a short identifier or address, NFC is handy for tap-to-act","flows \u2014 e.g. encoding a public wallet address or a deep link. Private keys/seed phrases should never be","written to an open, re-writable tag; treat tags as public, tamper-readable pointers, not secure key vaults.","","PRACTICAL TIPS: re-writable blank tags are inexpensive; pick a chip with enough memory for the payload",'(NTAG215+ for longer URLs or vCards). Use a metal-shielded ("on-metal") tag if you must stick it to a',"metal surface. Range is intentionally tiny (a few cm) for security \u2014 you must deliberately tap."].join(`
19
19
  `),Bt=class extends v{kind="data";name="nfc-info";category="nfc";description='Use when the user asks a conceptual / how-to question about NFC tags \u2014 what an NFC tag is, how NFC works, what data a tag can store, tag types/capacity, or how to read/write/use one ("what is an NFC tag", "how does NFC work", "what can I store on an NFC tag", "how do I use an NFC tag"). Returns an expert reference to answer from, plus a country-appropriate Amazon buy link to close with. Pass the current turn\'s BCP-47 `language` so the right storefront is picked. For a pure "where to buy" question with no explanation needed, prefer nfc-buy-link.';parameters=[{name:"language",type:"string",description:`The BCP-47 language tag of the user's current message (e.g. "en", "vi", "ja", "zh", "de"). Used only to pick the local Amazon storefront for the closing buy link. Optional (defaults to amazon.com).`,required:!1}];llm;constructor(e){super(),e&&(this.llm=new z(e))}async run(e,t){let n=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,r=await qt({country:t?.country,language:n,llm:this.llm}),o=Qi(r),s=r.length>1;return{reference:Zr,marketplaceLinks:r,_instructions:`Answer the user's NFC question as a knowledgeable, friendly expert, writing in the USER'S language (translate naturally \u2014 never leave it in English when they wrote another language). Draw on the reference below for the facts (do NOT invent anything beyond it), but write a polished, well-organized answer \u2014 not a terse one-liner. FORMAT: Use short Markdown section headings (bold or "##") and bullet points so it is easy to scan, similar to a great encyclopedia entry. For a broad question like "what is an NFC tag", give a thorough multi-section answer: open with a 1\u20132 sentence plain-language definition, then cover sections such as "How it works", "What's inside", "What it can store", "Common uses", "How to use one", and "Why they're popular" \u2014 include concrete specifics (the 13.56 MHz frequency, chip names + byte capacities, example payloads, numbered steps). Aim for genuinely useful depth, several short paragraphs/lists, not a wall of dense text. For a NARROW question (e.g. only "what can it store" or "how do I write one"), answer just that part in focused detail and skip the unrelated sections. Do not mention tools, this reference, or that anything is canned. AT THE END, add a short closing line telling them where they can buy NFC tags, then include EACH of these exact CLICKABLE Markdown links `+(s?"as a NUMBERED Markdown list (1., 2., 3.), ONE store per line, in this exact order and numbering":"inline")+` (keep every URL byte-for-byte; localize only the visible text; keep the form [text](url)):
20
20
  ${o}
@@ -1046,7 +1046,7 @@ Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:Ul,timestamp
1046
1046
 
1047
1047
  IDENTITY: This applies ONLY when the user asks who or what you are. In that case, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline. This identity rule does NOT change how you handle restricted topics below \u2014 for those, follow the RESTRICTED TOPICS rule exactly.`,Hl=`
1048
1048
 
1049
- RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,Oo=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;x402Signer=null;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,lr(e.rpcUrls),oo(e.excludeChains),this.llm=new z(e.llm),this.registry=new ct,this.history=new xn(e.maxHistoryMessages??50),this.summarizer=new Cn(this.llm),this.synthesizer=new Rn(this.llm),this.systemPrompt=(e.systemPrompt??Vl)+Wl+Hl,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 _n(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new Qe({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 At(u)),this.registry.register(new yt(u)),this.registry.register(new St(u)),this.registry.register(new Pt(u)),this.registry.register(new xt(u)),this.registry.register(new bt(u)),this.registry.register(new Ct(u)),this.registry.register(new _t(u)),this.registry.register(new It(u)),this.registry.register(new Rt(u)),this.registry.register(new Nt(u)),this.registry.register(new Ut(u)),this.registry.register(new Et(u)),this.registry.register(new Tt(u)),this.registry.register(new vt(u)),this.registry.register(new wt(u)),this.registry.register(new kt(u))}let r=e.nftLink;this.registry.register(new Dt({url:r})),this.registry.register(new Ot),this.registry.register(new Mt),e.subagents?.nfc===!0&&(this.registry.register(new Bt(e.llm)),this.registry.register(new Ft(e.llm))),this.registry.register(new $t(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 u=typeof e.uniswap=="object"?e.uniswap:void 0,p=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Jt(u,p)),this.registry.register(new Zt(u)),this.registry.register(new en(u)),this.registry.register(new tn(u)),this.registry.register(new rn(u));let m=u?{isProduction:u.isProduction}:void 0;this.registry.register(new nn({baseUrl:u?.baseUrl,pool:m,minProvideUsd:u?.minProvideUsd})),this.registry.register(new on({pool:m})),this.registry.register(new sn),this.registry.register(new an)}if((s||o)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new Vt(e.llm)),o&&e.subgraph!==!1){let u=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new ln(u)),this.registry.register(new cn(u)),this.registry.register(new un(u)),this.registry.register(new dn(u)),this.registry.register(new pn(u)),this.registry.register(new mn(u)),this.registry.register(new hn(u))}let i=e.subagents?.["wallet-action-app"]===!0;if(i?!1:e.subagents?.["wallet-action"]!==!1){let u=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new yn(u)),this.registry.register(new bn(u)),this.registry.register(new Pn(u,{url:r})),this.registry.register(new wn(u)),this.registry.register(new An(u,{debug:this.debug})),this.registry.register(new Sn(u,{debug:this.debug}))}if(i)for(let u of Po({appLink:e.walletActionAppLink,nftLink:r}))this.registry.register(u);this.router=new En(this.llm,{debug:this.debug}),this.rewriter=new Lo(this.llm,{debug:this.debug});let c=typeof e.subgraph=="object"?e.subgraph:void 0,d=Io(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:c?.linkAddLiquidity},e.subagents);this.subagents=new Map(d.map(u=>[u.name,u])),this.chatGraph=Ms(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:Qn()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,timestamp:Date.now()});let s=await this.registry.execute(e,t,this.userContext),i=s.data,l=s.success?i?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,c=Qn(),d=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],u={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return d.length>0&&(u.uiActions=d),this.history.add(u),await this.persistHistory(),{answer:l,messageId:c,...d.length>0?{uiActions:d}:{}}}setX402Signer(e){this.x402Signer=e,xr(e?Ho({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,t,n){this.assertLicense(),await this.loadHistory();let r=Qn(),o=e,s=n?.userQuery||o?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let i;try{i=await Vo(x,o,t)}catch(c){let u=`The payment couldn't be completed: ${c instanceof Error?c.message:String(c)}. Please try again.`;return this.history.add({role:"assistant",content:u,timestamp:Date.now(),messageId:r}),await this.persistHistory(),{answer:u,messageId:r}}return{...await this.synthesizeFromPaidData(s,i,r,n?.generateSuggestions??!0),messageId:r}}async synthesizeFromPaidData(e,t,n,r){let o=typeof t=="string"?t:JSON.stringify(t),s=this.systemPrompt+this.capabilitiesSummary(),i=`The user's question was: "${e}".
1049
+ RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,Oo=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;x402Signer=null;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,lr(e.rpcUrls),oo(e.excludeChains),this.llm=new z(e.llm),this.registry=new ct,this.history=new xn(e.maxHistoryMessages??50),this.summarizer=new Cn(this.llm),this.synthesizer=new Rn(this.llm),this.systemPrompt=(e.systemPrompt??Vl)+Wl+Hl,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 _n(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new Qe({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 At(u)),this.registry.register(new yt({...u,llm:e.llm})),this.registry.register(new St(u)),this.registry.register(new Pt(u)),this.registry.register(new xt(u)),this.registry.register(new bt(u)),this.registry.register(new Ct(u)),this.registry.register(new _t(u)),this.registry.register(new It(u)),this.registry.register(new Rt(u)),this.registry.register(new Nt(u)),this.registry.register(new Ut(u)),this.registry.register(new Et(u)),this.registry.register(new Tt(u)),this.registry.register(new vt(u)),this.registry.register(new wt(u)),this.registry.register(new kt(u))}let r=e.nftLink;this.registry.register(new Dt({url:r})),this.registry.register(new Ot(e.llm)),this.registry.register(new Mt(e.llm)),e.subagents?.nfc===!0&&(this.registry.register(new Bt(e.llm)),this.registry.register(new Ft(e.llm))),this.registry.register(new $t(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 u=typeof e.uniswap=="object"?e.uniswap:void 0,p=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Jt(u,p)),this.registry.register(new Zt(u)),this.registry.register(new en(u)),this.registry.register(new tn(u)),this.registry.register(new rn(u));let m=u?{isProduction:u.isProduction}:void 0;this.registry.register(new nn({baseUrl:u?.baseUrl,pool:m,minProvideUsd:u?.minProvideUsd})),this.registry.register(new on({pool:m})),this.registry.register(new sn),this.registry.register(new an)}if((s||o)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new Vt(e.llm)),o&&e.subgraph!==!1){let u=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new ln(u)),this.registry.register(new cn(u)),this.registry.register(new un(u)),this.registry.register(new dn(u)),this.registry.register(new pn(u)),this.registry.register(new mn(u)),this.registry.register(new hn(u))}let i=e.subagents?.["wallet-action-app"]===!0;if(i?!1:e.subagents?.["wallet-action"]!==!1){let u=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new yn(u)),this.registry.register(new bn(u)),this.registry.register(new Pn(u,{url:r})),this.registry.register(new wn(u)),this.registry.register(new An(u,{debug:this.debug})),this.registry.register(new Sn(u,{debug:this.debug}))}if(i)for(let u of Po({appLink:e.walletActionAppLink,nftLink:r}))this.registry.register(u);this.router=new En(this.llm,{debug:this.debug}),this.rewriter=new Lo(this.llm,{debug:this.debug});let c=typeof e.subgraph=="object"?e.subgraph:void 0,d=Io(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:c?.linkAddLiquidity},e.subagents);this.subagents=new Map(d.map(u=>[u.name,u])),this.chatGraph=Ms(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:Qn()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,timestamp:Date.now()});let s=await this.registry.execute(e,t,this.userContext),i=s.data,l=s.success?i?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,c=Qn(),d=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],u={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return d.length>0&&(u.uiActions=d),this.history.add(u),await this.persistHistory(),{answer:l,messageId:c,...d.length>0?{uiActions:d}:{}}}setX402Signer(e){this.x402Signer=e,xr(e?Ho({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,t,n){this.assertLicense(),await this.loadHistory();let r=Qn(),o=e,s=n?.userQuery||o?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let i;try{i=await Vo(x,o,t)}catch(c){let u=`The payment couldn't be completed: ${c instanceof Error?c.message:String(c)}. Please try again.`;return this.history.add({role:"assistant",content:u,timestamp:Date.now(),messageId:r}),await this.persistHistory(),{answer:u,messageId:r}}return{...await this.synthesizeFromPaidData(s,i,r,n?.generateSuggestions??!0),messageId:r}}async synthesizeFromPaidData(e,t,n,r){let o=typeof t=="string"?t:JSON.stringify(t),s=this.systemPrompt+this.capabilitiesSummary(),i=`The user's question was: "${e}".
1050
1050
 
1051
1051
  A paid API returned this data:
1052
1052
  ${o}