keyring-agent-core 0.2.38 → 0.2.39
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.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.native.js +2 -2
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -7543,7 +7543,7 @@ declare function createX402SignatureProvider(opts: {
|
|
|
7543
7543
|
*/
|
|
7544
7544
|
|
|
7545
7545
|
interface PantographServiceConfig {
|
|
7546
|
-
/** Pantograph API base URL (default: https://
|
|
7546
|
+
/** Pantograph API base URL (default: https://wallet-api.pantograph.app) */
|
|
7547
7547
|
baseUrl?: string;
|
|
7548
7548
|
}
|
|
7549
7549
|
/** Maps hex chain ID → Pantograph chain name */
|
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.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(`
|
|
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.39";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://wallet-api.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>
|
package/dist/index.native.js
CHANGED
|
@@ -437,8 +437,8 @@ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}
|
|
|
437
437
|
`);return a===-1?"":i.stack.slice(a+1)})();try{if(!n.stack)n.stack=o;else if(o){let a=o.indexOf(`
|
|
438
438
|
`),s=a===-1?-1:o.indexOf(`
|
|
439
439
|
`,a+1),l=s===-1?"":o.slice(s+1);String(n.stack).endsWith(l)||(n.stack+=`
|
|
440
|
-
`+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=po(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&hm.assertOptions(n,{silentJSONParsing:Ai.transitional(Ai.boolean),forcedJSONParsing:Ai.transitional(Ai.boolean),clarifyTimeoutError:Ai.transitional(Ai.boolean),legacyInterceptorReqResOrdering:Ai.transitional(Ai.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:hm.assertOptions(i,{encode:Ai.function,serialize:Ai.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),hm.assertOptions(r,{baseUrl:Ai.spelling("baseURL"),withXsrfToken:Ai.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&j.merge(o.common,o[r.method]);o&&j.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=hr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||gd;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let u=[];this.interceptors.response.forEach(function(y){u.push(y.fulfilled,y.rejected)});let c,d=0,h;if(!l){let g=[Jb.bind(this),void 0];for(g.unshift(...s),g.push(...u),h=g.length,c=Promise.resolve(r);d<h;)c=c.then(g[d++],g[d++]);return c}h=s.length;let m=r;for(;d<h;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{c=Jb.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=po(this.defaults,e);let r=fm(e.baseURL,e.url,e.allowAbsoluteUrls);return um(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){wd.prototype[e]=function(r,n){return this.request(po(n||{},{method:e,url:r,data:(n||{}).data}))}});j.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(po(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}wd.prototype[e]=r(),e!=="query"&&(wd.prototype[e+"Form"]=r(!0))});var mm=wd;p();var sA=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new jo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},cU=sA;p();function lA(t){return function(r){return t.apply(null,r)}}p();function uA(t){return j.isObject(t)&&t.isAxiosError===!0}p();var cA={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(cA).forEach(([t,e])=>{cA[e]=t});var dU=cA;function pU(t){let e=new mm(t),r=im(mm.prototype.request,e);return j.extend(r,mm.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return pU(po(t,i))},r}var kr=pU(_d);kr.Axios=mm;kr.CanceledError=jo;kr.CancelToken=cU;kr.isCancel=dm;kr.VERSION=vd;kr.toFormData=gl;kr.AxiosError=Me;kr.Cancel=kr.CanceledError;kr.all=function(e){return Promise.all(e)};kr.spread=lA;kr.isAxiosError=uA;kr.mergeConfig=po;kr.AxiosHeaders=hr;kr.formToJSON=t=>Gb(j.isHTMLForm(t)?new FormData(t):t);kr.getAdapter=Yb.getAdapter;kr.HttpStatusCode=dU;kr.default=kr;var Qb=kr;var{Axios:aVe,AxiosError:sVe,CanceledError:lVe,isCancel:uVe,CancelToken:cVe,VERSION:dVe,all:pVe,Cancel:fVe,isAxiosError:hVe,spread:mVe,toFormData:gVe,AxiosHeaders:yVe,HttpStatusCode:_Ve,formToJSON:bVe,getAdapter:vVe,mergeConfig:wVe,create:SVe}=Qb;var fU="0.2.38";var rQ=`keyring-agent-core/${fU} (Keyring Chatbot Agent; +https://keyring.app)`,nQ="payment-required",dA=null;function hU(t){dA=t}function iQ(t){return t?Object.keys(t).some(e=>e.toLowerCase()==="payment-signature"):!1}var oQ=3e4,aQ=typeof process<"u"&&process.versions?.node!=null,pA=class{constructor(e={}){f(this,"instance");this.instance=Qb.create({baseURL:e.baseURL,timeout:e.timeout??oQ,validateStatus:()=>!0,headers:{Accept:"application/json",...aQ?{"User-Agent":e.userAgent??rQ}:{},...e.headers}})}async request(e,r,n,i={}){let o=await this.instance.request({...i,method:e,url:r,data:n}),a={};for(let[l,u]of Object.entries(o.headers??{}))u!=null&&(a[l.toLowerCase()]=String(u));let s={ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:a};if(s.status===402&&s.headers[nQ]&&dA&&!iQ(i.headers)){let l=await dA(s,{url:r,method:String(e),body:n,headers:i.headers});if(l)return this.request(e,r,n,{...i,headers:{...i.headers,...l}})}return s}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},De=new pA;function nt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}var sQ={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"}]},mU="payment-required",lQ="PAYMENT-SIGNATURE";function uQ(t){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(t,"utf8").toString("base64")}function cQ(t){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(t,"base64").toString("utf8")}function dQ(){let t=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<32;r++)t[r]=Math.floor(Math.random()*256);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function pQ(t){let[e,r]=String(t).split(":"),n=parseInt(r,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${t}`);return n}function gU(t){if(!t.query||Object.keys(t.query).length===0)return t.url;let e=Object.entries(t.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return t.url.includes("?")?`${t.url}&${e}`:`${t.url}?${e}`}function yU(t){return JSON.parse(cQ(t))}function fA(t,e,r,n){let i=t.headers[mU];if(!i)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=yU(i),a=o.accepts?.[0];if(!a)throw new Error("402 response offered no payment requirements");if(a.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${a.scheme} (only "exact" is supported)`);if(!r)throw new Error("No connected wallet address to build the payment from");let s=pQ(a.network),l=Math.floor(Date.now()/1e3),u={from:r,to:a.payTo,value:String(a.amount),validAfter:"0",validBefore:String(l+(a.maxTimeoutSeconds??300)),nonce:dQ()},c={domain:{name:a.extra?.name,version:a.extra?.version,chainId:s,verifyingContract:a.asset},types:sQ,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:gU(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:a,authorization:u,typedData:c,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:u},resource:o.resource,accepted:a,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function fQ(t,e,r,n){let i=gU(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:fA(o,e,r,n)};if(!o.ok)throw new Error(nt(o));return{status:"ok",data:o.data}}async function hA(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...mA(e,r)}});if(s.ok)return s.data;let l=s.headers[mU];if(l)try{let u=yU(l);if(u.error)throw new Error(`x402 payment rejected: ${u.error}`)}catch(u){if(u instanceof Error&&u.message.startsWith("x402 payment rejected"))throw u}throw new Error(nt(s))}var hQ={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function mA(t,e){let r={...t.paymentDraft,payload:{authorization:t.authorization,signature:e}};return{[lQ]:uQ(JSON.stringify(r))}}function _U(t){let e=t.requirements,r=t.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:hQ[e.network]||e.network,payTo:e.payTo,...r?.description?{description:r.description}:{},resourceUrl:t.request.url}}function gA(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=fA(e,{url:r.url,method:r.method,body:r.body,headers:r.headers},n)}catch{return null}let a;try{a=await i({typedData:o.typedData,display:_U(o)})}catch{a=null}return a?mA(o,a):null}}p();p();var Zu=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Sd(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function yA(t){if(t?.aborted)throw new Zu}function bU(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var vU={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},mQ="https://nft.keyring.app/api/gemini-stable",gQ=new Set([408,429,500,502,503,504]),wU=3e4,ev=t=>new Promise(e=>setTimeout(e,t));function tv(t,e,r){if(r!=null&&r>0)return Math.min(r,wU);let n=Math.min(e*2**(t-1),wU);return n/2+Math.random()*(n/2)}function yQ(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pr=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??mQ}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;yA(l);let u=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of u){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let c={contents:u,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(c.systemInstruction=i),r?.length?(c.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(c.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(c.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,h="Unknown error";for(let m=1;m<=a;m++){yA(l);let g;try{g=await De.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(Sd(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await ev(tv(m,s));continue}if(!g.ok){let C=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(h=`Gemini proxy error ${g.status}: ${C}`,!gQ.has(g.status))throw new Error(h);if(m>=a)break;let N=yQ(g.headers["retry-after"]??null);await ev(tv(m,s,N));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await ev(tv(m,s));continue}let y=g.data,_=y.candidates?.[0];if(!_)return{text:"",toolCalls:[]};let b="",w=[],T=_.content?.parts;if(!Array.isArray(T)||T.length===0){let C=_.finishReason;if(!(C==="SAFETY"||C==="RECITATION")&&m<a){h=`Gemini returned an empty turn (finishReason=${C??"none"})`,await ev(tv(m,s));continue}return{text:"",toolCalls:[]}}for(let C of T)C.text&&(b+=C.text),C.functionCall&&w.push({toolName:C.functionCall.name,args:C.functionCall.args??{},callId:C.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let E=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:b,toolCalls:w,usage:E}}throw new Error(h)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],u=s.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!u&&!c?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],u=o[o.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
|
|
441
|
-
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:vU[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:vU[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&i.push(o.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};p();var Td=class{constructor(){f(this,"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(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)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 i.execute(r,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};p();p();p();p();p();var kd=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],_Q=new Set(kd),yl=[...kd],_A=new Set(yl),Ci="0x1",Ad="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function bQ(t){return t.map(e=>Ed[e]??e).join(", ")}function rv(t){let e=new Set;if(t)for(let n of t){let i=nv(n);i&&e.add(i)}let r=kd.filter(n=>!e.has(n));yl=r.length>0?[...r]:[...kd],_A=new Set(yl),Ci=yl.includes("0x1")?"0x1":yl[0],Ad=bQ(yl)}var vQ={"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 tr(t){let e=nv(t);return e&&_A.has(e)?e:null}function nv(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=vQ[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&_Q.has(n)?n:null}function fo(t){return tr(t)!==null}function xi(){return[...yl]}var Pd=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Ad}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},_l=t=>typeof t=="string"&&t.trim()!=="";function Fn(t,e){if(_l(t)){let r=tr(t);if(r)return r;throw new Pd(t.trim())}if(_l(e?.chain)){let r=tr(e.chain);if(r)return r;throw new Pd(e.chain.trim())}return null}function iv(t,e){return tr(t)??tr(e?.chain)??void 0}var Ed={"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 Ce(t){let e=nv(t);return e&&Ed[e]?Ed[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var wQ={"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 SU(t,e){let r=nv(t),n=r?wQ[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var SQ={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function TU(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?SQ[e]??null:null}var TQ={"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 kU(t){let e=tr(t);return e?TQ[e]??null:null}function Cd(t,e){if(!_l(t))return null;let r=tr(t),n=tr(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:Ed[r]??r,connectedLabel:Ed[n]??n}}function PU(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>_A.has(o)):[];return(n.length?n:yl).map(o=>{let a=Ed[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function xd(t,e){return{actionButtons:PU(e),_instructions:`The user wants to ${t} 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 mr=class extends Error{constructor(r,n){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");f(this,"code","needs_chain_selection");f(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=PU(r,n)}},gm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");f(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function Er(t,e){if(_l(t))return t.trim();if(_l(e?.walletAddress))return e.walletAddress.trim();throw new gm}function Lr(t,e,r){if(_l(t)){let n=tr(t);if(n)return n;throw new Pd(t.trim())}if(_l(e?.chain)){let n=tr(e.chain);if(n)return n;throw new Pd(e.chain.trim())}if(_l(e?.walletAddress))throw new mr(typeof e?.query=="string"?e.query:void 0,r);return Ci}var oe=class{constructor(){f(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=kQ(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{}}}catch(o){return o instanceof mr?{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()-i,actionButtons:o.buttons}:o instanceof gm?{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()-i}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-i}}}};function kQ(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons;if(!Array.isArray(r)||r.length===0)return{data:t};let{actionButtons:n,...i}=e;return{data:i,actionButtons:r}}p();p();var EU=ub(av());function Bt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function PQ(t){return new Uint8Array(EU.keccak256.arrayBuffer(t))}function ym(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function AU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function CU(t){return new TextEncoder().encode(t)}function Hu(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function EQ(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function AQ(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function xU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return ym(e)}function _m(t){return xU(BigInt(t))}function IU(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function OU(t){let e=IU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(OU).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function CQ(t){let e=(t.inputs??[]).map(OU).join(",");return`${t.name??""}(${e})`}function bA(t,e){let r=OQ(t.type);if(r){let[i,o]=r;return xQ({...t,type:o},e,i)}if(t.type==="tuple")return IQ(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:EQ(ym(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=IU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:_m(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:xU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?ym(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:AQ(o)}}if(n==="bytes"){let i=typeof e=="string"?ym(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Hu(_m(i.length),a)}}if(n==="string"){let i=typeof e=="string"?CU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Hu(_m(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function vA(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(_m(e+i)),n.push(a),i+=a.length):r.push(a);return Hu(...r,...n)}function xQ(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=bA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=vA(o);if(n){let s=_m(o.length);return{dynamic:!0,encoded:o.length>0?Hu(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:Hu(...o.map(a=>a.encoded))}}function IQ(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=bA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?vA(i):Hu(...i.map(o=>o.encoded))}}function OQ(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function RQ(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>bA(i,e[o])),n=vA(r);return AU(n)}function Id({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=CQ(n),o=PQ(CU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):ym(RQ(a,r).slice(2));return AU(Hu(o,s))}p();var NQ="https://deblo-api-dev.pantograph.app",$Q="0x0000000000000000000000000000000000000000",$U={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},MU={"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 MQ(t){return $U[t.toLowerCase()]||t}function RU(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function wA(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,o=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function SA(t){if(Array.isArray(t))return t;let e=t;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Sn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function NU(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=Sn(t.price_change_percentage_24h)??Sn(t.priceChange24h)??Sn(t.usd_price_24hr_percent_change)??Sn(t.price_change_24h)??Sn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:Sn(t.price)??Sn(t.usd_price),marketCap:Sn(t.market_cap)??Sn(t.marketCap),totalVolume:{"24h":Sn(t.total_volume)??Sn(t.volume24h)},pricePercentChange:{"24h":i}}}var Tn=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??NQ).replace(/\/+$/,"")}tokensUrl(e,r){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),i=this.tokensUrl(r,n),o=await De.get(i);if(!o.ok)return;let a=SA(o.data),s=new Map;for(let l of a)l.address&&s.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 u=s.get(e[l].token_address.toLowerCase());u&&(u.icon_image&&(e[l].logo=u.icon_image,e[l].thumbnail=u.icon_image),isNaN(u.price)||(e[l].usd_price=u.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*u.price))}}catch{}}async getTokenMetadata(e,r){try{let n=this.tokensUrl(r,e),i=await De.get(n);if(!i.ok)return null;let o=SA(i.data),a=e.toLowerCase()===$Q,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?wA(s):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=this.tokensUrl(r,e.join(",")),o=await De.get(i);if(!o.ok)return n;let a=SA(o.data),s=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let u=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);u&&s.has(u)&&(n[u]=wA(l))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ci,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=RU({chainId:o,key:r}),s=`${this.baseUrl}/token-list/all?${a}`,l=await De.get(s);if(!l.ok)throw new Error(nt(l));let u=l.data,c=u?.result??u?.data??u,d=[];return Array.isArray(c)?d=c:c&&typeof c=="object"&&(d=Object.values(c).flat()),{success:!0,data:d.map(wA)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ci,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=MU[r.toLowerCase()]??[],a=i!=null?i+o.length:n+o.length,[s,l]=await Promise.allSettled([this.fetchTopGainers(r,a),o.length>0?this.getTokensMetadata(o,r):Promise.resolve({})]),u=s.status==="fulfilled"?s.value:[],c=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>NU(y,r)):[],d=new Set,h=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...h,...m].slice(0,i):[...h,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=Sn(a.market_cap)??Sn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":Sn(a.total_volume)??Sn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=parseInt(e,16),o=RU({chainId:i,duration:n,limit:r}),a=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,s=[];for(let l=0;l<5;l++){let u=await De.get(a);if(!u.ok)throw new Error(nt(u));let c=u.data;if(s=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>NU(l,e))}async getTopGainers(e){let r=e?.chain||Ci,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var DQ="https://nft.keyring.app",UQ="https://nft.keyring.app",LQ=.01,et=5,ir=1e3,qQ="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",jQ="0x0000000000000000000000000000000000000000",tt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function gr(t){return t||Ci}function or(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ar(t){return new Promise(e=>setTimeout(e,t))}function FQ(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.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(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function TA(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var pt=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??DQ).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??UQ).replace(/\/+$/,""),this.pantograph=new Tn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=gr(n),l="Unknown error";for(let u=1;u<=et;u++)try{let c={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(c.token_addresses=i);let d=[],h=null;do{h&&(c.cursor=h);let g=or(c),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),h=w?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===qQ?jQ:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=LQ)),{success:!0,data:m}}catch(c){if(l=c instanceof Error?c.message:"Unknown error",c instanceof tt&&c.status===400)break;u<et&&await ar(ir)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=gr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=et;s++)try{let[l,u]=await Promise.allSettled([De.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${or({chain:i,addresses:[r]})}`),De.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${or({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;c=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!c){o="Token metadata not found",s<et&&await ar(ir);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let h=u.value.data;d=h?.data??h}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:o=!0,cursor:a,tokenAddresses:s,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=gr(n),d="Unknown error";for(let h=1;h<=et;h++)try{let m={chain:c,format:u,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(m.cursor=a),l&&(m.include_prices=!0),s&&s.length>0&&(m.token_addresses=s);let g=or(m),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data;return{success:!0,data:b?.data??b}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof tt&&m.status===400)break;h<et&&await ar(ir)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!Bt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=gr(i),c="Unknown error";for(let d=1;d<=et;d++)try{let h={chain:u,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=or(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await De.get(g);if(!y.ok)throw new tt(y.status,nt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(c=h instanceof Error?h.message:"Unknown error",h instanceof tt&&h.status===400)break;d<et&&await ar(ir)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=gr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=et;_++)try{let b={chain:m,limit:g,order:c};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),u&&(b.cursor=u),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let w=or(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await De.get(T);if(!E.ok)throw new tt(E.status,nt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof tt&&b.status===400)break;_<et&&await ar(ir)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=gr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=et;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),u!=null&&(_.to_block=u),c&&(_.cursor=c),i?.length&&(_.contract_addresses=i);let b=or(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await De.get(w);if(!T.ok)throw new tt(T.status,nt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof tt&&_.status===400)break;y<et&&await ar(ir)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=gr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=et;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),u!=null&&(w.to_block=u),c&&(w.cursor=c),i?.length&&(w.contract_addresses=i),h!=null&&(w.include_prices=h);let T=or(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await De.get(E);if(!C.ok)throw new tt(C.status,nt(C));let N=C.data;return{success:!0,data:N?.data??N}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof tt&&w.status===400)break;b<et&&await ar(ir)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Bt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=gr(n),a="Unknown error";for(let s=1;s<=et;s++)try{let l={chain:o};i&&(l.days=i);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data;return{success:!0,data:h?.data??h}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i&&(u.days=i),o&&o.length>0&&(u.token_addresses=o.slice(0,25));let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i!=null&&(u.limit=i),o&&(u.cursor=o);let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:FQ(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=gr(i),a="Unknown error";for(let s=1;s<=et;s++)try{let l=or({chains:o}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await De.get(u);if(!c.ok)throw new tt(c.status,nt(c));let m=c.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(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=et;o++)try{let a={};r&&(a.chain=gr(r)),n!=null&&(a.limit=n);let s=or(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:TA(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof tt&&a.status===400)break;o<et&&await ar(ir)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:TA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:TA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Od=class extends oe{constructor(r){super();f(this,"name","get-token-info");f(this,"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');f(this,"category","blockchain-data");f(this,"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}]);f(this,"service");f(this,"llm");this.service=new pt(r),this.llm=new Pr(r?.llm??{})}async run(r,n){let i=r.keyword||"",o=Lr(r.chain,n),a=r.prompt||"",s=n?.walletAddress||void 0;return i?await this.searchToken(i,o,a,s):{error:"Missing required parameter: keyword"}}async searchToken(r,n,i,o){let a=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, 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(`
|
|
440
|
+
`+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=po(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&hm.assertOptions(n,{silentJSONParsing:Ai.transitional(Ai.boolean),forcedJSONParsing:Ai.transitional(Ai.boolean),clarifyTimeoutError:Ai.transitional(Ai.boolean),legacyInterceptorReqResOrdering:Ai.transitional(Ai.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:hm.assertOptions(i,{encode:Ai.function,serialize:Ai.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),hm.assertOptions(r,{baseUrl:Ai.spelling("baseURL"),withXsrfToken:Ai.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&j.merge(o.common,o[r.method]);o&&j.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=hr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||gd;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let u=[];this.interceptors.response.forEach(function(y){u.push(y.fulfilled,y.rejected)});let c,d=0,h;if(!l){let g=[Jb.bind(this),void 0];for(g.unshift(...s),g.push(...u),h=g.length,c=Promise.resolve(r);d<h;)c=c.then(g[d++],g[d++]);return c}h=s.length;let m=r;for(;d<h;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{c=Jb.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=po(this.defaults,e);let r=fm(e.baseURL,e.url,e.allowAbsoluteUrls);return um(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){wd.prototype[e]=function(r,n){return this.request(po(n||{},{method:e,url:r,data:(n||{}).data}))}});j.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(po(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}wd.prototype[e]=r(),e!=="query"&&(wd.prototype[e+"Form"]=r(!0))});var mm=wd;p();var sA=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new jo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},cU=sA;p();function lA(t){return function(r){return t.apply(null,r)}}p();function uA(t){return j.isObject(t)&&t.isAxiosError===!0}p();var cA={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(cA).forEach(([t,e])=>{cA[e]=t});var dU=cA;function pU(t){let e=new mm(t),r=im(mm.prototype.request,e);return j.extend(r,mm.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return pU(po(t,i))},r}var kr=pU(_d);kr.Axios=mm;kr.CanceledError=jo;kr.CancelToken=cU;kr.isCancel=dm;kr.VERSION=vd;kr.toFormData=gl;kr.AxiosError=Me;kr.Cancel=kr.CanceledError;kr.all=function(e){return Promise.all(e)};kr.spread=lA;kr.isAxiosError=uA;kr.mergeConfig=po;kr.AxiosHeaders=hr;kr.formToJSON=t=>Gb(j.isHTMLForm(t)?new FormData(t):t);kr.getAdapter=Yb.getAdapter;kr.HttpStatusCode=dU;kr.default=kr;var Qb=kr;var{Axios:aVe,AxiosError:sVe,CanceledError:lVe,isCancel:uVe,CancelToken:cVe,VERSION:dVe,all:pVe,Cancel:fVe,isAxiosError:hVe,spread:mVe,toFormData:gVe,AxiosHeaders:yVe,HttpStatusCode:_Ve,formToJSON:bVe,getAdapter:vVe,mergeConfig:wVe,create:SVe}=Qb;var fU="0.2.39";var rQ=`keyring-agent-core/${fU} (Keyring Chatbot Agent; +https://keyring.app)`,nQ="payment-required",dA=null;function hU(t){dA=t}function iQ(t){return t?Object.keys(t).some(e=>e.toLowerCase()==="payment-signature"):!1}var oQ=3e4,aQ=typeof process<"u"&&process.versions?.node!=null,pA=class{constructor(e={}){f(this,"instance");this.instance=Qb.create({baseURL:e.baseURL,timeout:e.timeout??oQ,validateStatus:()=>!0,headers:{Accept:"application/json",...aQ?{"User-Agent":e.userAgent??rQ}:{},...e.headers}})}async request(e,r,n,i={}){let o=await this.instance.request({...i,method:e,url:r,data:n}),a={};for(let[l,u]of Object.entries(o.headers??{}))u!=null&&(a[l.toLowerCase()]=String(u));let s={ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:a};if(s.status===402&&s.headers[nQ]&&dA&&!iQ(i.headers)){let l=await dA(s,{url:r,method:String(e),body:n,headers:i.headers});if(l)return this.request(e,r,n,{...i,headers:{...i.headers,...l}})}return s}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},De=new pA;function nt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}var sQ={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"}]},mU="payment-required",lQ="PAYMENT-SIGNATURE";function uQ(t){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(t,"utf8").toString("base64")}function cQ(t){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(t,"base64").toString("utf8")}function dQ(){let t=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<32;r++)t[r]=Math.floor(Math.random()*256);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function pQ(t){let[e,r]=String(t).split(":"),n=parseInt(r,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${t}`);return n}function gU(t){if(!t.query||Object.keys(t.query).length===0)return t.url;let e=Object.entries(t.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return t.url.includes("?")?`${t.url}&${e}`:`${t.url}?${e}`}function yU(t){return JSON.parse(cQ(t))}function fA(t,e,r,n){let i=t.headers[mU];if(!i)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=yU(i),a=o.accepts?.[0];if(!a)throw new Error("402 response offered no payment requirements");if(a.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${a.scheme} (only "exact" is supported)`);if(!r)throw new Error("No connected wallet address to build the payment from");let s=pQ(a.network),l=Math.floor(Date.now()/1e3),u={from:r,to:a.payTo,value:String(a.amount),validAfter:"0",validBefore:String(l+(a.maxTimeoutSeconds??300)),nonce:dQ()},c={domain:{name:a.extra?.name,version:a.extra?.version,chainId:s,verifyingContract:a.asset},types:sQ,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:gU(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:a,authorization:u,typedData:c,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:u},resource:o.resource,accepted:a,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function fQ(t,e,r,n){let i=gU(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:fA(o,e,r,n)};if(!o.ok)throw new Error(nt(o));return{status:"ok",data:o.data}}async function hA(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...mA(e,r)}});if(s.ok)return s.data;let l=s.headers[mU];if(l)try{let u=yU(l);if(u.error)throw new Error(`x402 payment rejected: ${u.error}`)}catch(u){if(u instanceof Error&&u.message.startsWith("x402 payment rejected"))throw u}throw new Error(nt(s))}var hQ={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function mA(t,e){let r={...t.paymentDraft,payload:{authorization:t.authorization,signature:e}};return{[lQ]:uQ(JSON.stringify(r))}}function _U(t){let e=t.requirements,r=t.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:hQ[e.network]||e.network,payTo:e.payTo,...r?.description?{description:r.description}:{},resourceUrl:t.request.url}}function gA(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=fA(e,{url:r.url,method:r.method,body:r.body,headers:r.headers},n)}catch{return null}let a;try{a=await i({typedData:o.typedData,display:_U(o)})}catch{a=null}return a?mA(o,a):null}}p();p();var Zu=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Sd(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function yA(t){if(t?.aborted)throw new Zu}function bU(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var vU={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},mQ="https://nft.keyring.app/api/gemini-stable",gQ=new Set([408,429,500,502,503,504]),wU=3e4,ev=t=>new Promise(e=>setTimeout(e,t));function tv(t,e,r){if(r!=null&&r>0)return Math.min(r,wU);let n=Math.min(e*2**(t-1),wU);return n/2+Math.random()*(n/2)}function yQ(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pr=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??mQ}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;yA(l);let u=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of u){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let c={contents:u,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(c.systemInstruction=i),r?.length?(c.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(c.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(c.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,h="Unknown error";for(let m=1;m<=a;m++){yA(l);let g;try{g=await De.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(Sd(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await ev(tv(m,s));continue}if(!g.ok){let C=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(h=`Gemini proxy error ${g.status}: ${C}`,!gQ.has(g.status))throw new Error(h);if(m>=a)break;let N=yQ(g.headers["retry-after"]??null);await ev(tv(m,s,N));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await ev(tv(m,s));continue}let y=g.data,_=y.candidates?.[0];if(!_)return{text:"",toolCalls:[]};let b="",w=[],T=_.content?.parts;if(!Array.isArray(T)||T.length===0){let C=_.finishReason;if(!(C==="SAFETY"||C==="RECITATION")&&m<a){h=`Gemini returned an empty turn (finishReason=${C??"none"})`,await ev(tv(m,s));continue}return{text:"",toolCalls:[]}}for(let C of T)C.text&&(b+=C.text),C.functionCall&&w.push({toolName:C.functionCall.name,args:C.functionCall.args??{},callId:C.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let E=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:b,toolCalls:w,usage:E}}throw new Error(h)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],u=s.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!u&&!c?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],u=o[o.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
|
|
441
|
+
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:vU[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:vU[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&i.push(o.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};p();var Td=class{constructor(){f(this,"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(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)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 i.execute(r,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};p();p();p();p();p();var kd=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],_Q=new Set(kd),yl=[...kd],_A=new Set(yl),Ci="0x1",Ad="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function bQ(t){return t.map(e=>Ed[e]??e).join(", ")}function rv(t){let e=new Set;if(t)for(let n of t){let i=nv(n);i&&e.add(i)}let r=kd.filter(n=>!e.has(n));yl=r.length>0?[...r]:[...kd],_A=new Set(yl),Ci=yl.includes("0x1")?"0x1":yl[0],Ad=bQ(yl)}var vQ={"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 tr(t){let e=nv(t);return e&&_A.has(e)?e:null}function nv(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=vQ[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&_Q.has(n)?n:null}function fo(t){return tr(t)!==null}function xi(){return[...yl]}var Pd=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Ad}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},_l=t=>typeof t=="string"&&t.trim()!=="";function Fn(t,e){if(_l(t)){let r=tr(t);if(r)return r;throw new Pd(t.trim())}if(_l(e?.chain)){let r=tr(e.chain);if(r)return r;throw new Pd(e.chain.trim())}return null}function iv(t,e){return tr(t)??tr(e?.chain)??void 0}var Ed={"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 Ce(t){let e=nv(t);return e&&Ed[e]?Ed[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var wQ={"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 SU(t,e){let r=nv(t),n=r?wQ[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var SQ={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function TU(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?SQ[e]??null:null}var TQ={"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 kU(t){let e=tr(t);return e?TQ[e]??null:null}function Cd(t,e){if(!_l(t))return null;let r=tr(t),n=tr(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:Ed[r]??r,connectedLabel:Ed[n]??n}}function PU(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>_A.has(o)):[];return(n.length?n:yl).map(o=>{let a=Ed[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function xd(t,e){return{actionButtons:PU(e),_instructions:`The user wants to ${t} 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 mr=class extends Error{constructor(r,n){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");f(this,"code","needs_chain_selection");f(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=PU(r,n)}},gm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");f(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function Er(t,e){if(_l(t))return t.trim();if(_l(e?.walletAddress))return e.walletAddress.trim();throw new gm}function Lr(t,e,r){if(_l(t)){let n=tr(t);if(n)return n;throw new Pd(t.trim())}if(_l(e?.chain)){let n=tr(e.chain);if(n)return n;throw new Pd(e.chain.trim())}if(_l(e?.walletAddress))throw new mr(typeof e?.query=="string"?e.query:void 0,r);return Ci}var oe=class{constructor(){f(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=kQ(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{}}}catch(o){return o instanceof mr?{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()-i,actionButtons:o.buttons}:o instanceof gm?{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()-i}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-i}}}};function kQ(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons;if(!Array.isArray(r)||r.length===0)return{data:t};let{actionButtons:n,...i}=e;return{data:i,actionButtons:r}}p();p();var EU=ub(av());function Bt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function PQ(t){return new Uint8Array(EU.keccak256.arrayBuffer(t))}function ym(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function AU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function CU(t){return new TextEncoder().encode(t)}function Hu(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function EQ(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function AQ(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function xU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return ym(e)}function _m(t){return xU(BigInt(t))}function IU(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function OU(t){let e=IU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(OU).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function CQ(t){let e=(t.inputs??[]).map(OU).join(",");return`${t.name??""}(${e})`}function bA(t,e){let r=OQ(t.type);if(r){let[i,o]=r;return xQ({...t,type:o},e,i)}if(t.type==="tuple")return IQ(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:EQ(ym(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=IU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:_m(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:xU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?ym(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:AQ(o)}}if(n==="bytes"){let i=typeof e=="string"?ym(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Hu(_m(i.length),a)}}if(n==="string"){let i=typeof e=="string"?CU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Hu(_m(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function vA(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(_m(e+i)),n.push(a),i+=a.length):r.push(a);return Hu(...r,...n)}function xQ(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=bA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=vA(o);if(n){let s=_m(o.length);return{dynamic:!0,encoded:o.length>0?Hu(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:Hu(...o.map(a=>a.encoded))}}function IQ(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=bA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?vA(i):Hu(...i.map(o=>o.encoded))}}function OQ(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function RQ(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>bA(i,e[o])),n=vA(r);return AU(n)}function Id({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=CQ(n),o=PQ(CU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):ym(RQ(a,r).slice(2));return AU(Hu(o,s))}p();var NQ="https://wallet-api.pantograph.app",$Q="0x0000000000000000000000000000000000000000",$U={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},MU={"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 MQ(t){return $U[t.toLowerCase()]||t}function RU(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function wA(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,o=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function SA(t){if(Array.isArray(t))return t;let e=t;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Sn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function NU(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=Sn(t.price_change_percentage_24h)??Sn(t.priceChange24h)??Sn(t.usd_price_24hr_percent_change)??Sn(t.price_change_24h)??Sn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:Sn(t.price)??Sn(t.usd_price),marketCap:Sn(t.market_cap)??Sn(t.marketCap),totalVolume:{"24h":Sn(t.total_volume)??Sn(t.volume24h)},pricePercentChange:{"24h":i}}}var Tn=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??NQ).replace(/\/+$/,"")}tokensUrl(e,r){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),i=this.tokensUrl(r,n),o=await De.get(i);if(!o.ok)return;let a=SA(o.data),s=new Map;for(let l of a)l.address&&s.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 u=s.get(e[l].token_address.toLowerCase());u&&(u.icon_image&&(e[l].logo=u.icon_image,e[l].thumbnail=u.icon_image),isNaN(u.price)||(e[l].usd_price=u.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*u.price))}}catch{}}async getTokenMetadata(e,r){try{let n=this.tokensUrl(r,e),i=await De.get(n);if(!i.ok)return null;let o=SA(i.data),a=e.toLowerCase()===$Q,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?wA(s):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=this.tokensUrl(r,e.join(",")),o=await De.get(i);if(!o.ok)return n;let a=SA(o.data),s=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let u=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);u&&s.has(u)&&(n[u]=wA(l))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ci,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=RU({chainId:o,key:r}),s=`${this.baseUrl}/token-list/all?${a}`,l=await De.get(s);if(!l.ok)throw new Error(nt(l));let u=l.data,c=u?.result??u?.data??u,d=[];return Array.isArray(c)?d=c:c&&typeof c=="object"&&(d=Object.values(c).flat()),{success:!0,data:d.map(wA)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ci,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=MU[r.toLowerCase()]??[],a=i!=null?i+o.length:n+o.length,[s,l]=await Promise.allSettled([this.fetchTopGainers(r,a),o.length>0?this.getTokensMetadata(o,r):Promise.resolve({})]),u=s.status==="fulfilled"?s.value:[],c=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>NU(y,r)):[],d=new Set,h=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...h,...m].slice(0,i):[...h,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=Sn(a.market_cap)??Sn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":Sn(a.total_volume)??Sn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=parseInt(e,16),o=RU({chainId:i,duration:n,limit:r}),a=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,s=[];for(let l=0;l<5;l++){let u=await De.get(a);if(!u.ok)throw new Error(nt(u));let c=u.data;if(s=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>NU(l,e))}async getTopGainers(e){let r=e?.chain||Ci,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var DQ="https://nft.keyring.app",UQ="https://nft.keyring.app",LQ=.01,et=5,ir=1e3,qQ="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",jQ="0x0000000000000000000000000000000000000000",tt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function gr(t){return t||Ci}function or(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ar(t){return new Promise(e=>setTimeout(e,t))}function FQ(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.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(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function TA(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var pt=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??DQ).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??UQ).replace(/\/+$/,""),this.pantograph=new Tn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=gr(n),l="Unknown error";for(let u=1;u<=et;u++)try{let c={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(c.token_addresses=i);let d=[],h=null;do{h&&(c.cursor=h);let g=or(c),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),h=w?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===qQ?jQ:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=LQ)),{success:!0,data:m}}catch(c){if(l=c instanceof Error?c.message:"Unknown error",c instanceof tt&&c.status===400)break;u<et&&await ar(ir)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=gr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=et;s++)try{let[l,u]=await Promise.allSettled([De.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${or({chain:i,addresses:[r]})}`),De.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${or({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;c=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!c){o="Token metadata not found",s<et&&await ar(ir);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let h=u.value.data;d=h?.data??h}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:o=!0,cursor:a,tokenAddresses:s,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=gr(n),d="Unknown error";for(let h=1;h<=et;h++)try{let m={chain:c,format:u,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(m.cursor=a),l&&(m.include_prices=!0),s&&s.length>0&&(m.token_addresses=s);let g=or(m),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data;return{success:!0,data:b?.data??b}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof tt&&m.status===400)break;h<et&&await ar(ir)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!Bt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=gr(i),c="Unknown error";for(let d=1;d<=et;d++)try{let h={chain:u,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=or(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await De.get(g);if(!y.ok)throw new tt(y.status,nt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(c=h instanceof Error?h.message:"Unknown error",h instanceof tt&&h.status===400)break;d<et&&await ar(ir)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=gr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=et;_++)try{let b={chain:m,limit:g,order:c};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),u&&(b.cursor=u),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let w=or(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await De.get(T);if(!E.ok)throw new tt(E.status,nt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof tt&&b.status===400)break;_<et&&await ar(ir)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=gr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=et;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),u!=null&&(_.to_block=u),c&&(_.cursor=c),i?.length&&(_.contract_addresses=i);let b=or(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await De.get(w);if(!T.ok)throw new tt(T.status,nt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof tt&&_.status===400)break;y<et&&await ar(ir)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=gr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=et;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),u!=null&&(w.to_block=u),c&&(w.cursor=c),i?.length&&(w.contract_addresses=i),h!=null&&(w.include_prices=h);let T=or(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await De.get(E);if(!C.ok)throw new tt(C.status,nt(C));let N=C.data;return{success:!0,data:N?.data??N}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof tt&&w.status===400)break;b<et&&await ar(ir)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Bt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=gr(n),a="Unknown error";for(let s=1;s<=et;s++)try{let l={chain:o};i&&(l.days=i);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data;return{success:!0,data:h?.data??h}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i&&(u.days=i),o&&o.length>0&&(u.token_addresses=o.slice(0,25));let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i!=null&&(u.limit=i),o&&(u.cursor=o);let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:FQ(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=gr(i),a="Unknown error";for(let s=1;s<=et;s++)try{let l=or({chains:o}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await De.get(u);if(!c.ok)throw new tt(c.status,nt(c));let m=c.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(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=et;o++)try{let a={};r&&(a.chain=gr(r)),n!=null&&(a.limit=n);let s=or(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:TA(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof tt&&a.status===400)break;o<et&&await ar(ir)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:TA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:TA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Od=class extends oe{constructor(r){super();f(this,"name","get-token-info");f(this,"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');f(this,"category","blockchain-data");f(this,"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}]);f(this,"service");f(this,"llm");this.service=new pt(r),this.llm=new Pr(r?.llm??{})}async run(r,n){let i=r.keyword||"",o=Lr(r.chain,n),a=r.prompt||"",s=n?.walletAddress||void 0;return i?await this.searchToken(i,o,a,s):{error:"Missing required parameter: keyword"}}async searchToken(r,n,i,o){let a=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, 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(`
|
|
442
442
|
`),[s,l,u]=await Promise.all([this.service.searchTokensByKey({key:r,chain:n}),o?this.findTokenInWallet(o,n,r):Promise.resolve(null),i?this.askGeminiWithSearch(i,a):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],d=r.toLowerCase(),h=b=>b.symbol?.toLowerCase()===d||b.token_address?.toLowerCase()===d,m=[...c].sort((b,w)=>(h(b)?0:1)-(h(w)?0:1)),g=null,y=m[0];if(y?.token_address){let b=await this.service.getTokenMetadata({address:y.token_address,chain:n});b.success&&b.data&&(g=b.data)}return!g&&y&&(g={...y}),{_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:n,userHoldsToken:!!l,walletBalance:l,token:g,...c.length>1?{searchResults:m.slice(0,10)}:{},research:u}}async askGeminiWithSearch(r,n){let i=Date.now();try{return(await this.llm.chat([...n?[{role:"system",content:n,timestamp:i}]:[],{role:"user",content:r,timestamp:i}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(r,n,i){if(!i)return null;let o=await this.service.getWalletTokenBalances({address:r,chain:n,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!o.success||!o.data?.result)return null;let a=i.toLowerCase(),s=o.data.result.find(l=>l.token_address.toLowerCase()===a||l.symbol?.toLowerCase()===a||l.name?.toLowerCase().includes(a));return s||null}};p();var Rd=class extends oe{constructor(r){super();f(this,"name","get-token-holders");f(this,"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. ');f(this,"category","blockchain-data");f(this,"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}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenHolders({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Nd=class extends oe{constructor(r){super();f(this,"name","get-token-analytics");f(this,"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.`);f(this,"category","blockchain-data");f(this,"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}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenAnalytics({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"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(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var $d=class extends oe{constructor(r){super();f(this,"name","get-token-score");f(this,"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.`);f(this,"category","blockchain-data");f(this,"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}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let m=await this.resolveContractAddress(a,i,o);if(!m)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,l=m.symbol,u=m.name}let c=await this.service.getTokenScore({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},h=d.metrics??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:h.usdPrice??null,liquidityUsd:h.liquidityUsd??null,volumeUsd:h.volumeUsd??null,transactions:h.transactions??null,supply:h.supply??null}}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Md=class extends oe{constructor(r){super();f(this,"name","get-trending-tokens");f(this,"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.');f(this,"category","blockchain-data");f(this,"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}]);f(this,"service");this.service=new Tn({baseUrl:r?.pantographUrl})}async run(r,n){let i=iv(r.chain,n),o=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.floor(r.limit):void 0,a=await this.service.getTrendingTokens({chain:i,limit:o});if(!a.success)return{error:a.error||"Failed to fetch trending tokens"};let s=a.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):
|
|
443
443
|
<rank>. <name> (<symbol>)
|
|
444
444
|
- Price: <usdPrice>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keyring-agent-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.39",
|
|
4
4
|
"description": "Core AI chat agent with multi-agent architecture, ReAct pattern, and modular tool system powered by Gemini",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"react-native": "dist/index.native.js",
|