keyring-agent-core 0.2.32 → 0.2.33
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 +0 -4
- package/dist/index.js +3 -3
- package/dist/index.native.js +14 -14
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -3585,7 +3585,6 @@ declare class TokenInfoTool extends BaseTool {
|
|
|
3585
3585
|
private llm;
|
|
3586
3586
|
constructor(config?: TokenInfoToolConfig);
|
|
3587
3587
|
protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<{
|
|
3588
|
-
actionButtons?: SuggestedAction[] | undefined;
|
|
3589
3588
|
research: string | null;
|
|
3590
3589
|
searchResults?: TokenMetadata[] | undefined;
|
|
3591
3590
|
_instructions: string;
|
|
@@ -3596,10 +3595,7 @@ declare class TokenInfoTool extends BaseTool {
|
|
|
3596
3595
|
} | {
|
|
3597
3596
|
error: string;
|
|
3598
3597
|
}>;
|
|
3599
|
-
execute(args: Record<string, unknown>, userContext?: UserContext): Promise<ToolResult>;
|
|
3600
3598
|
private searchToken;
|
|
3601
|
-
/** Substitute the {token} placeholder in an LLM-supplied localized template. */
|
|
3602
|
-
private fillTemplate;
|
|
3603
3599
|
private askGeminiWithSearch;
|
|
3604
3600
|
private findTokenInWallet;
|
|
3605
3601
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var us=Object.create;var Hn=Object.defineProperty;var ds=Object.getOwnPropertyDescriptor;var ps=Object.getOwnPropertyNames;var ms=Object.getPrototypeOf,hs=Object.prototype.hasOwnProperty;var gs=(l,e)=>{for(var t in e)Hn(l,t,{get:e[t],enumerable:!0})},er=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ps(e))!hs.call(l,r)&&r!==t&&Hn(l,r,{get:()=>e[r],enumerable:!(n=ds(e,r))||n.enumerable});return l};var fs=(l,e,t)=>(t=l!=null?us(ms(l)):{},er(e||!l||!l.__esModule?Hn(t,"default",{value:l,enumerable:!0}):t,l)),ys=l=>er(Hn({},"__esModule",{value:!0}),l);var ji={};gs(ji,{AI_AGENT_TOOL_NAMES:()=>bo,AbortError:()=>Ye,AgentCore:()=>So,ApproveTokenTool:()=>cn,BaseNftAiTool:()=>Pe,BaseNftMessageTool:()=>Pt,BaseSwapService:()=>$e,BaseTool:()=>v,BaseWalletActionTool:()=>ye,BuyTokenTool:()=>mn,ChatHistory:()=>fn,DEFAULT_CHAIN:()=>Se,DEFAULT_PROVIDER:()=>Rn,DEFAULT_RPC_BY_CHAIN:()=>fe,DebridgeAdapter:()=>Vt,EstimatePoolYieldTool:()=>jt,GeminiProvider:()=>Z,GeminiSearchAiTool:()=>Ut,HEX_TO_PANTOGRAPH:()=>wr,KnowledgeBase:()=>bn,ManageLiquidityRedirectTool:()=>Qt,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>yo,NFC_AMAZON_DEFAULT_DOMAIN:()=>Lo,NFC_AMAZON_DOMAINS:()=>Io,NFTContractInfoTool:()=>Ct,NFTMetadataTool:()=>_t,NFT_AGENT_TOOL_NAMES:()=>fo,NfcBuyTool:()=>Nt,NfcInfoTool:()=>Rt,OpenAddLiquidityFormTool:()=>Yt,POOL_AGENT_TOOL_NAMES:()=>wo,PantographService:()=>oe,PoolByAddressTool:()=>Ft,PoolDetailTool:()=>Bt,PoolFallbackAiTool:()=>It,PoolPriceRangesTool:()=>zt,PoolSearchTool:()=>qt,PoolService:()=>Xe,PreviewAddLiquidityTool:()=>Kt,RelayAdapter:()=>Ht,Router:()=>wn,SUPPORTED_CHAINS:()=>nt,SUPPORTED_CHAINS_LABEL:()=>Ke,SWAP_PROVIDER_CONFIG:()=>so,SendNativeTool:()=>an,SendNftTool:()=>gn,SendTokenTool:()=>ln,Subagent:()=>Y,SubgraphAddPoolTool:()=>on,SubgraphCoinPoolPairsTool:()=>nn,SubgraphPoolByAddressTool:()=>Zt,SubgraphPoolByPositionIdTool:()=>en,SubgraphPoolSearchTool:()=>Xt,SubgraphPositionDetailTool:()=>tn,SubgraphTrendingPoolsTool:()=>Jt,Summarizer:()=>yn,SwapServiceFactory:()=>Qe,SwapTokenTool:()=>hn,Synthesizer:()=>kn,TOKEN_AGENT_TOOL_NAMES:()=>go,TRANSFER_TOPIC:()=>Hr,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>kr,TokenAnalyticsTool:()=>ut,TokenHoldersTool:()=>ct,TokenInfoTool:()=>lt,TokenScoreTool:()=>dt,ToolRegistry:()=>tt,TopGainersTool:()=>mt,TopPoolsTool:()=>Mt,TransactionByHashTool:()=>St,TrendingTokensTool:()=>pt,UNISWAP_CHAIN_SLUG:()=>Un,UpstashKnowledgeBase:()=>We,WALLET_ACTION_AGENT_TOOL_NAMES:()=>ko,WALLET_AGENT_TOOL_NAMES:()=>ho,WalletActionAppTool:()=>In,WalletApprovalsTool:()=>kt,WalletDefiPositionsTool:()=>vt,WalletDefiProtocolPositionsTool:()=>At,WalletDefiSummaryTool:()=>Tt,WalletHistoryTool:()=>gt,WalletNFTsTool:()=>xt,WalletNftTransfersTool:()=>yt,WalletPnlSummaryTool:()=>bt,WalletPnlTool:()=>wt,WalletTokenBalancesTool:()=>ht,WalletTokenTransfersTool:()=>ft,WebsiteTrustKeyringAgent:()=>Po,ZERO_ADDRESS:()=>$,amazonDomainForLanguage:()=>Do,buildRangePresets:()=>Go,buildUniswapPoolUrl:()=>pe,clampTick:()=>Ce,configureSupportedChains:()=>Kn,createAiAgent:()=>qn,createDefaultSubagents:()=>To,createNfcAgent:()=>Bn,createNftAgent:()=>Mn,createPoolAgent:()=>Fn,createTokenAgent:()=>On,createWalletActionAgent:()=>$n,createWalletActionAppTools:()=>mo,createWalletAgent:()=>Dn,ethCallAt:()=>$r,ethCallByChain:()=>Ho,getAffiliateFee:()=>$t,getChainMeta:()=>te,getDefaultRpcUrl:()=>$a,getGatewayAddress:()=>io,getNativeTokenInfo:()=>Gt,getPositionManagerAddress:()=>lo,getProviderByChain:()=>ro,ingestKnowledgeBase:()=>cs,isAbortError:()=>et,nfcAmazonSearchUrl:()=>Et,normalizePriceRangeToPool:()=>Dt,priceToTick:()=>ze,resolveRpcUrl:()=>Wt,roundTickToSpacing:()=>xe,rpcCall:()=>Ie,setRpcOverrides:()=>Vo,swapServiceFactory:()=>_e,tickToPrice:()=>be,toPantographChain:()=>Cn});module.exports=ys(ji);var nr=fs(require("axios"));var tr="0.2.
|
|
2
|
-
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:rr[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:rr[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 tt=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 nt=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],Ps=new Set(nt),Oe=[...nt],ar=new Set(Oe),Se="0x1",Ke="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function xs(l){return l.map(e=>rt[e]??e).join(", ")}function Kn(l){let e=new Set;if(l)for(let n of l){let r=jn(n);r&&e.add(r)}let t=nt.filter(n=>!e.has(n));Oe=t.length>0?[...t]:[...nt],ar=new Set(Oe),Se=Oe.includes("0x1")?"0x1":Oe[0],Ke=xs(Oe)}var Cs={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708"};function ae(l){let e=jn(l);return e&&ar.has(e)?e:null}function jn(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Cs[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&&Ps.has(n)?n:null}function zn(l){return ae(l)!==null}function he(){return[...Oe]}var ot=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Ke}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Me=l=>typeof l=="string"&&l.trim()!=="";function ie(l,e){if(Me(l)){let t=ae(l);if(t)return t;throw new ot(l.trim())}if(Me(e?.chain)){let t=ae(e.chain);if(t)return t;throw new ot(e.chain.trim())}return null}function Qn(l,e){return ae(l)??ae(e?.chain)??void 0}var rt={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function E(l){let e=jn(l);return e&&rt[e]?rt[e]:typeof l=="string"&&l.trim()?l.trim():"the requested chain"}var _s={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build"};function ir(l,e){let t=jn(l),n=t?_s[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Es={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function lr(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase();return e?Es[e]??null:null}var Rs={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function cr(l){let e=ae(l);return e?Rs[e]??null:null}function st(l,e){if(!Me(l))return null;let t=ae(l),n=ae(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:rt[t]??t,connectedLabel:rt[n]??n}}function ur(l){let e=typeof l=="string"?l.trim():"";return Oe.map(t=>{let n=rt[t]??t;return{label:n,prompt:e?`${e} (${n})`:n}})}function at(l,e){return{actionButtons:ur(e),_instructions:`The user wants to ${l} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var z=class extends Error{code="needs_chain_selection";buttons;constructor(e){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=ur(e)}},Sn=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 j(l,e){if(Me(l))return l.trim();if(Me(e?.walletAddress))return e.walletAddress.trim();throw new Sn}function M(l,e){if(Me(l)){let t=ae(l);if(t)return t;throw new ot(l.trim())}if(Me(e?.chain)){let t=ae(e.chain);if(t)return t;throw new ot(e.chain.trim())}if(Me(e?.walletAddress))throw new z(typeof e?.query=="string"?e.query:void 0);return Se}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=Ns(o);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-r,...s.actionButtons?{actionButtons:s.actionButtons}:{}}}catch(o){return o instanceof z?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-r,actionButtons:o.buttons}:o instanceof Sn?{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 Ns(l){if(!l||typeof l!="object")return{data:l};let e=l,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:l};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var dr=require("js-sha3");function F(l){return typeof l=="string"&&/^0x[0-9a-fA-F]{40}$/.test(l)}function Us(l){return new Uint8Array(dr.keccak256.arrayBuffer(l))}function Pn(l){let e=l.startsWith("0x")?l.slice(2):l,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function pr(l){return"0x"+Array.from(l).map(e=>e.toString(16).padStart(2,"0")).join("")}function mr(l){return new TextEncoder().encode(l)}function je(...l){let e=l.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of l)t.set(r,n),n+=r.length;return t}function Is(l,e=32){let t=new Uint8Array(e);return t.set(l,e-l.length),t}function Ls(l,e=32){let t=new Uint8Array(e);return t.set(l),t}function hr(l){let e=((l%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Pn(e)}function xn(l){return hr(BigInt(l))}function gr(l){return l==="uint"?"uint256":l==="int"?"int256":l.match(/^uint$/)?"uint256":l.match(/^int$/)?"int256":l.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function fr(l){let e=gr(l.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(l.components??[]).map(fr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function Ds(l){let e=(l.inputs??[]).map(fr).join(",");return`${l.name??""}(${e})`}function Eo(l,e){let t=Bs(l.type);if(t){let[r,o]=t;return Os({...l,type:o},e,r)}if(l.type==="tuple")return Ms(l,e);if(l.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:Is(Pn(o.toLowerCase()))}}if(l.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=gr(l.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:xn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:hr(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Pn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ls(o)}}if(n==="bytes"){let r=typeof e=="string"?Pn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:je(xn(r.length),s)}}if(n==="string"){let r=typeof e=="string"?mr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:je(xn(r.length),s)}}throw new Error(`Unsupported ABI type: ${l.type}`)}function Ro(l){let e=0;for(let{dynamic:o,encoded:s}of l)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of l)o?(t.push(xn(e+r)),n.push(s),r+=s.length):t.push(s);return je(...t,...n)}function Os(l,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let a=Eo(l,s);a.dynamic&&(r=!0),o.push(a)}if(n||r){let s=Ro(o);if(n){let a=xn(o.length);return{dynamic:!0,encoded:o.length>0?je(a,s):a}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:je(...o.map(s=>s.encoded))}}function Ms(l,e){let t=l.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],a=Array.isArray(e)?e[o]:e[s.name??""],i=Eo(s,a);i.dynamic&&(n=!0),r.push(i)}return{dynamic:n,encoded:n?Ro(r):je(...r.map(o=>o.encoded))}}function Bs(l){let e=l.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function qs(l,e){if(l.length!==e.length)throw new Error(`Expected ${l.length} values, got ${e.length}`);if(l.length===0)return"0x";let t=l.map((r,o)=>Eo(r,e[o])),n=Ro(t);return pr(n)}function it({abi:l,functionName:e,args:t=[]}){let n=l.find(i=>(i.type==="function"||i.type===void 0)&&i.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=Ds(n),o=Us(mr(r)).slice(0,4),s=n.inputs??[],a=s.length===0||t.length===0?new Uint8Array(0):Pn(qs(s,t).slice(2));return pr(je(o,a))}var Fs="https://wallet-api.pantograph.app",$s="0x0000000000000000000000000000000000000000",wr={"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"]};function Cn(l){return wr[l.toLowerCase()]||l}function yr(l){let e=[];for(let[t,n]of Object.entries(l))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function No(l){let e=l,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function ne(l){if(l==null)return null;let e=typeof l=="number"?l:parseFloat(String(l));return Number.isFinite(e)?e:null}function br(l,e){let t=l.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=ne(l.price_change_percentage_24h)??ne(l.priceChange24h)??ne(l.usd_price_24hr_percent_change)??ne(l.price_change_24h)??ne(l.priceChange);return{chainId:e,tokenAddress:l.address??l.token_address??"",name:l.name??null,symbol:l.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:l.logoURI??l.icon_image??l.logo??null,usdPrice:ne(l.price)??ne(l.usd_price),marketCap:ne(l.market_cap)??ne(l.marketCap),totalVolume:{"24h":ne(l.total_volume)??ne(l.volume24h)},pricePercentChange:{"24h":r}}}var oe=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Fs).replace(/\/+$/,"")}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=Cn(t),r=e.map(u=>u.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(r)}`,s=await P.get(o);if(!s.ok)return;let a=s.data,i=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],c=new Map;for(let u of i)u.address&&c.set(u.address.toLowerCase(),{price:u.price!=null?parseFloat(String(u.price)):NaN,icon_image:u.icon_image});for(let u=0;u<e.length;u++){let d=c.get(e[u].token_address.toLowerCase());d&&(d.icon_image&&(e[u].logo=d.icon_image,e[u].thumbnail=d.icon_image),isNaN(d.price)||(e[u].usd_price=d.price,e[u].usd_value=parseFloat(e[u].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,t){try{let n=Cn(t),r=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await P.get(r);if(!o.ok)return null;let s=o.data,a=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],i=e.toLowerCase()===$s,c=a.find(u=>u.address?.toLowerCase()===e.toLowerCase()||i&&u.address===""||u.token_address?.toLowerCase()===e.toLowerCase()||i&&u.token_address==="");return c?No(c):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=Cn(t),o=`${this.baseUrl}/keyrings/tokens/${r}/v2?addresses=${encodeURIComponent(e.join(","))}`,s=await P.get(o);if(!s.ok)return n;let a=s.data,i=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],c=new Set(e.map(u=>u.toLowerCase()));for(let u of i){let d=u.address?.toLowerCase()||u.token_address?.toLowerCase()||(u.address===""?"":null);d&&c.has(d)&&(n[d]=No(u))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||Se,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=yr({chainId:o,key:t}),a=`${this.baseUrl}/token-list?${s}`,i=await P.get(a);if(!i.ok)throw new Error(L(i));let c=i.data,u=[];return c?.data?u=Array.isArray(c.data)?c.data:Object.values(c.data).flat():typeof c=="object"&&!Array.isArray(c)&&(u=Object.values(c).flat()),{success:!0,data:u.map(No)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Se,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,[a,i]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=a.status==="fulfilled"?a.value:[],u=i.status==="fulfilled"?o.map(g=>i.value[g.toLowerCase()]).filter(g=>g!=null).map(g=>br(g,t)):[],d=new Set,p=[];for(let g of u){let f=g.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(g))}let m=[];for(let g of c){let f=g.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(g))}let h=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(h,t),{success:!0,data:h}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=ne(s.market_cap)??ne(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":ne(s.total_volume)??ne(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=Cn(e),o=yr({duration:n,limit:t}),s=`${this.baseUrl}/token-list/top-gainers/${r}${o?`?${o}`:""}`,a=[];for(let i=0;i<5;i++){let c=await P.get(s);if(!c.ok)throw new Error(L(c));let u=c.data;if(a=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],a.length>0)break;i<4&&await new Promise(d=>setTimeout(d,2e3))}return a.map(i=>br(i,e))}async getTopGainers(e){let t=e?.chain||Se,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 Ws="https://nft.keyring.app",Vs="https://nft.keyring.app",Hs=.01,R=5,V=1e3,Gs="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ys="0x0000000000000000000000000000000000000000",N=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function K(l){return l||Se}function H(l){let e=[];for(let[t,n]of Object.entries(l))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function G(l){return new Promise(e=>setTimeout(e,l))}function Ks(l){if(Array.isArray(l))return l;if(l&&typeof l=="object"){let e=l;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Uo(l){if(Array.isArray(l))return l;if(l&&typeof l=="object"){let e=l;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ws).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Vs).replace(/\/+$/,""),this.pantograph=new oe({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let a=K(n),i="Unknown error";for(let c=1;c<=R;c++)try{let u={chain:a,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(u.token_addresses=r);let d=[],p=null;do{p&&(u.cursor=p);let h=H(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,f=await P.get(g);if(!f.ok)throw new N(f.status,L(f));let y=f.data,b=y?.data??y;b?.result?.length>0&&d.push(...b.result),p=b?.cursor??null}while(p);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(h=>parseFloat(h.balance||"0")>0),m.result=m.result.map(h=>({...h,token_address:h.token_address.toLowerCase()===Gs?Ys:h.token_address})),await this.enrichTokenPrices(m.result,a),m.result=m.result.filter(h=>h.usd_value==null||h.usd_value>=Hs)),{success:!0,data:m}}catch(u){if(i=u instanceof Error?u.message:"Unknown error",u instanceof N&&u.status===400)break;c<R&&await G(V)}return{success:!1,error:i}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=K(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let a=1;a<=R;a++)try{let[i,c]=await Promise.allSettled([P.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${H({chain:r,addresses:[t]})}`),P.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${H({chain:r,include:"percent_change"})}`)]),u=null;if(i.status==="fulfilled"&&i.value.ok){let p=i.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){o="Token metadata not found",a<R&&await G(V);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=10,excludeSpam:o=!0,cursor:s,tokenAddresses:a,includePrices:i,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=K(n),d="Unknown error";for(let p=1;p<=R;p++)try{let m={chain:u,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(m.cursor=s),i&&(m.include_prices=!0),a&&a.length>0&&(m.token_addresses=a);let h=H(m),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${h}`,f=await P.get(g);if(!f.ok)throw new N(f.status,L(f));let y=f.data;return{success:!0,data:y?.data??y}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof N&&m.status===400)break;p<R&&await G(V)}return{success:!1,error:d}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:a=!0,include:i}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!F(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=K(r),u="Unknown error";for(let d=1;d<=R;d++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:a};i&&(p.include=i);let m=H(p),h=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,g=await P.get(h);if(!g.ok)throw new N(g.status,L(g));let f=g.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof N&&p.status===400)break;d<R&&await G(V)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:a,toBlock:i,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=K(n),h=Math.max(1,Math.min(100,Math.floor(r))),g="Unknown error";for(let f=1;f<=R;f++)try{let y={chain:m,limit:h,order:u};o&&(y.from_date=o),s&&(y.to_date=s),a!=null&&(y.from_block=a),i!=null&&(y.to_block=i),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=H(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,T=await P.get(w);if(!T.ok)throw new N(T.status,L(T));let k=T.data;return{success:!0,data:k?.data??k}}catch(y){if(g=y instanceof Error?y.message:"Unknown error",y instanceof N&&y.status===400)break;f<R&&await G(V)}return{success:!1,error:g}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=K(n),m=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let g=1;g<=R;g++)try{let f={chain:p,limit:m,order:d};s&&(f.from_date=s),a&&(f.to_date=a),i!=null&&(f.from_block=i),c!=null&&(f.to_block=c),u&&(f.cursor=u),r?.length&&(f.contract_addresses=r);let y=H(f),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await P.get(b);if(!w.ok)throw new N(w.status,L(w));let T=w.data;return{success:!0,data:T?.data??T}}catch(f){if(h=f instanceof Error?f.message:"Unknown error",f instanceof N&&f.status===400)break;g<R&&await G(V)}return{success:!1,error:h}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let h=K(n),g=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let y=1;y<=R;y++)try{let b={chain:h,limit:g,order:d,format:m};s&&(b.from_date=s),a&&(b.to_date=a),i!=null&&(b.from_block=i),c!=null&&(b.to_block=c),u&&(b.cursor=u),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=H(b),T=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,k=await P.get(T);if(!k.ok)throw new N(k.status,L(k));let A=k.data;return{success:!0,data:A?.data??A}}catch(b){if(f=b instanceof Error?b.message:"Unknown error",b instanceof N&&b.status===400)break;y<R&&await G(V)}return{success:!1,error:f}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!F(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=K(n),s="Unknown error";for(let a=1;a<=R;a++)try{let i={chain:o};r&&(i.days=r);let c=H(i),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:s}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=K(n),a="Unknown error";for(let i=1;i<=R;i++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await P.get(d);if(!p.ok)throw new N(p.status,L(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(a=c instanceof Error?c.message:"Unknown error",c instanceof N&&c.status===400)break;i<R&&await G(V)}return{success:!1,error:a}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=K(n),a="Unknown error";for(let i=1;i<=R;i++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await P.get(d);if(!p.ok)throw new N(p.status,L(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(a=c instanceof Error?c.message:"Unknown error",c instanceof N&&c.status===400)break;i<R&&await G(V)}return{success:!1,error:a}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chains:r}),i=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chains:r}),i=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:Ks(d)}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!F(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=K(r),s="Unknown error";for(let a=1;a<=R;a++)try{let i=H({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${i}`,u=await P.get(c);if(!u.ok)throw new N(u.status,L(u));let m=u.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(g=>({label:g.label,address:g.address,balance_usd:g.balanceUsd??0,total_unclaimed_usd_value:g.unclaimedUsd??0,position_details:g.details,tokens:g.tokens.map(f=>({token_type:f.tokenType,address:f.address,contract_address:f.address,name:f.name??"",symbol:f.symbol??"",decimals:f.decimals??18,logo:f.logo,balance:f.balance??"0",balance_formatted:f.balanceFormatted??"0",usd_price:f.usdPrice,usd_value:f.usdValue}))}))}}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:s}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=R;o++)try{let s={};t&&(s.chain=K(t)),n!=null&&(s.limit=n);let a=H(s),i=`${this.baseUrl}/api/moralis/proxy/tokens/trending${a?`?${a}`:""}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:Uo(d)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof N&&s.status===400)break;o<R&&await G(V)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let a=1;a<=R;a++)try{let i={};t&&(i.chain=K(t)),n&&(i.time_frame=n),r!=null&&(i.min_market_cap=r),o!=null&&(i.security_score=o);let c=H(i),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:Uo(m)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let a=1;a<=R;a++)try{let i={};t&&(i.chain=K(t)),n&&(i.time_frame=n),r!=null&&(i.min_market_cap=r),o!=null&&(i.security_score=o);let c=H(i),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:Uo(m)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var lt=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';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0},{name:"buy_button_label",type:"string",description:`Label for the "Buy" suggestion button shown under the token info, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the Buy button is clicked. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new Z({})}async run(e,t){let n=e.keyword||"",r=M(e.chain,t),o=e.prompt||"",s=e.buy_button_label||"",a=e.buy_prompt_template||"",i=t?.walletAddress||void 0;return n?await this.searchToken(n,r,o,s,a,i):{error:"Missing required parameter: keyword"}}async execute(e,t){let n=await super.execute(e,t),r=n.data;return n.success&&r&&Array.isArray(r.actionButtons)&&r.actionButtons.length>0&&(n.actionButtons=r.actionButtons),n}async searchToken(e,t,n,r,o,s){let a=[s?`User's connected wallet address: ${s}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
|
|
3
|
-
`),[i,c,u]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),s?this.findTokenInWallet(s,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,a):Promise.resolve(null)]),d=i.success&&i.data?Array.isArray(i.data)?i.data:[]:[],p=e.toLowerCase(),m=T=>T.symbol?.toLowerCase()===p||T.token_address?.toLowerCase()===p,h=[...d].sort((T,k)=>(m(T)?0:1)-(m(k)?0:1)),g=null,f=h[0];if(f?.token_address){let T=await this.service.getTokenMetadata({address:f.token_address,chain:t});T.success&&T.data&&(g=T.data)}!g&&f&&(g={...f});let y=g?.symbol?.trim(),b=y?[{label:this.fillTemplate(r,y,"Buy {token}"),prompt:this.fillTemplate(o,y,"buy {token}")}]:[];return{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it. A "Buy" button is shown below your reply automatically \u2014 do NOT mention it, list it, or repeat its text.',chain:t,userHoldsToken:!!c,walletBalance:c,token:g,...d.length>1?{searchResults:h.slice(0,10)}:{},research:u,...b.length>0?{actionButtons:b}:{}}}fillTemplate(e,t,n){return(e&&e.includes("{token}")?e:n).replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),s=r.data.result.find(a=>a.token_address.toLowerCase()===o||a.symbol?.toLowerCase()===o||a.name?.toLowerCase().includes(o));return s||null}};var ct=class extends v{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let a,i;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,a=d.symbol,i=d.name}let c=await this.service.getTokenHolders({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let u=c.data;return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},totalHolders:u.totalHolders,holdersByAcquisition:u.holdersByAcquisition,holderChange:u.holderChange,holderSupply:u.holderSupply,holderDistribution:u.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var ut=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.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let a,i;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,a=d.symbol,i=d.name}let c=await this.service.getTokenAnalytics({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let u=c.data??{};return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},usdPrice:u.usdPrice??null,totalLiquidity:u.totalLiquidity??null,totalFullyDilutedValuation:u.totalFullyDilutedValuation??null,totalBuyVolume:u.totalBuyVolume??null,totalSellVolume:u.totalSellVolume??null,totalBuyers:u.totalBuyers??null,totalSellers:u.totalSellers??null,totalBuys:u.totalBuys??null,totalSells:u.totalSells??null,uniqueWallets:u.uniqueWallets??null,pricePercentChange:u.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var dt=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.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let a,i;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,a=p.symbol,i=p.name}let c=await this.service.getTokenScore({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let u=c.data??{},d=u.metrics??{};return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},score:u.score??null,updatedAt:u.updatedAt??null,metrics:{usdPrice:d.usdPrice??null,liquidityUsd:d.liquidityUsd??null,volumeUsd:d.volumeUsd??null,transactions:d.transactions??null,supply:d.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var pt=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, and more.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;constructor(e){super(),this.service=new oe({baseUrl:e?.pantographUrl})}async run(e,t){let n=Qn(e.chain,t),r=e.buy_button_label||"",o=e.buy_prompt_template||"",s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,a=await this.service.getTrendingTokens({chain:n,limit:s});if(!a.success)return{error:a.error||"Failed to fetch trending tokens"};let i=a.data??[],c=new Set,u=[];for(let d of i){let p=d.symbol?.trim();!p||c.has(p.toLowerCase())||(c.add(p.toLowerCase()),u.push({label:this.fillTemplate(r,p,"Buy {token}"),prompt:this.fillTemplate(o,p,"buy {token}")}))}return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
|
|
1
|
+
"use strict";var us=Object.create;var Hn=Object.defineProperty;var ds=Object.getOwnPropertyDescriptor;var ps=Object.getOwnPropertyNames;var ms=Object.getPrototypeOf,hs=Object.prototype.hasOwnProperty;var gs=(l,e)=>{for(var t in e)Hn(l,t,{get:e[t],enumerable:!0})},er=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ps(e))!hs.call(l,r)&&r!==t&&Hn(l,r,{get:()=>e[r],enumerable:!(n=ds(e,r))||n.enumerable});return l};var fs=(l,e,t)=>(t=l!=null?us(ms(l)):{},er(e||!l||!l.__esModule?Hn(t,"default",{value:l,enumerable:!0}):t,l)),ys=l=>er(Hn({},"__esModule",{value:!0}),l);var ji={};gs(ji,{AI_AGENT_TOOL_NAMES:()=>bo,AbortError:()=>Ye,AgentCore:()=>So,ApproveTokenTool:()=>cn,BaseNftAiTool:()=>Pe,BaseNftMessageTool:()=>Pt,BaseSwapService:()=>$e,BaseTool:()=>v,BaseWalletActionTool:()=>ye,BuyTokenTool:()=>mn,ChatHistory:()=>fn,DEFAULT_CHAIN:()=>Se,DEFAULT_PROVIDER:()=>Rn,DEFAULT_RPC_BY_CHAIN:()=>fe,DebridgeAdapter:()=>Vt,EstimatePoolYieldTool:()=>jt,GeminiProvider:()=>Z,GeminiSearchAiTool:()=>Ut,HEX_TO_PANTOGRAPH:()=>wr,KnowledgeBase:()=>bn,ManageLiquidityRedirectTool:()=>Qt,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>yo,NFC_AMAZON_DEFAULT_DOMAIN:()=>Lo,NFC_AMAZON_DOMAINS:()=>Io,NFTContractInfoTool:()=>Ct,NFTMetadataTool:()=>_t,NFT_AGENT_TOOL_NAMES:()=>fo,NfcBuyTool:()=>Nt,NfcInfoTool:()=>Rt,OpenAddLiquidityFormTool:()=>Yt,POOL_AGENT_TOOL_NAMES:()=>wo,PantographService:()=>oe,PoolByAddressTool:()=>Ft,PoolDetailTool:()=>Bt,PoolFallbackAiTool:()=>It,PoolPriceRangesTool:()=>zt,PoolSearchTool:()=>qt,PoolService:()=>Xe,PreviewAddLiquidityTool:()=>Kt,RelayAdapter:()=>Ht,Router:()=>wn,SUPPORTED_CHAINS:()=>nt,SUPPORTED_CHAINS_LABEL:()=>Ke,SWAP_PROVIDER_CONFIG:()=>so,SendNativeTool:()=>an,SendNftTool:()=>gn,SendTokenTool:()=>ln,Subagent:()=>Y,SubgraphAddPoolTool:()=>on,SubgraphCoinPoolPairsTool:()=>nn,SubgraphPoolByAddressTool:()=>Zt,SubgraphPoolByPositionIdTool:()=>en,SubgraphPoolSearchTool:()=>Xt,SubgraphPositionDetailTool:()=>tn,SubgraphTrendingPoolsTool:()=>Jt,Summarizer:()=>yn,SwapServiceFactory:()=>Qe,SwapTokenTool:()=>hn,Synthesizer:()=>kn,TOKEN_AGENT_TOOL_NAMES:()=>go,TRANSFER_TOPIC:()=>Hr,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>kr,TokenAnalyticsTool:()=>ut,TokenHoldersTool:()=>ct,TokenInfoTool:()=>lt,TokenScoreTool:()=>dt,ToolRegistry:()=>tt,TopGainersTool:()=>mt,TopPoolsTool:()=>Mt,TransactionByHashTool:()=>St,TrendingTokensTool:()=>pt,UNISWAP_CHAIN_SLUG:()=>Un,UpstashKnowledgeBase:()=>We,WALLET_ACTION_AGENT_TOOL_NAMES:()=>ko,WALLET_AGENT_TOOL_NAMES:()=>ho,WalletActionAppTool:()=>In,WalletApprovalsTool:()=>kt,WalletDefiPositionsTool:()=>vt,WalletDefiProtocolPositionsTool:()=>At,WalletDefiSummaryTool:()=>Tt,WalletHistoryTool:()=>gt,WalletNFTsTool:()=>xt,WalletNftTransfersTool:()=>yt,WalletPnlSummaryTool:()=>bt,WalletPnlTool:()=>wt,WalletTokenBalancesTool:()=>ht,WalletTokenTransfersTool:()=>ft,WebsiteTrustKeyringAgent:()=>Po,ZERO_ADDRESS:()=>$,amazonDomainForLanguage:()=>Do,buildRangePresets:()=>Go,buildUniswapPoolUrl:()=>pe,clampTick:()=>Ce,configureSupportedChains:()=>Kn,createAiAgent:()=>qn,createDefaultSubagents:()=>To,createNfcAgent:()=>Bn,createNftAgent:()=>Mn,createPoolAgent:()=>Fn,createTokenAgent:()=>On,createWalletActionAgent:()=>$n,createWalletActionAppTools:()=>mo,createWalletAgent:()=>Dn,ethCallAt:()=>$r,ethCallByChain:()=>Ho,getAffiliateFee:()=>$t,getChainMeta:()=>te,getDefaultRpcUrl:()=>$a,getGatewayAddress:()=>io,getNativeTokenInfo:()=>Gt,getPositionManagerAddress:()=>lo,getProviderByChain:()=>ro,ingestKnowledgeBase:()=>cs,isAbortError:()=>et,nfcAmazonSearchUrl:()=>Et,normalizePriceRangeToPool:()=>Dt,priceToTick:()=>ze,resolveRpcUrl:()=>Wt,roundTickToSpacing:()=>xe,rpcCall:()=>Ie,setRpcOverrides:()=>Vo,swapServiceFactory:()=>_e,tickToPrice:()=>be,toPantographChain:()=>Cn});module.exports=ys(ji);var nr=fs(require("axios"));var tr="0.2.33";var ws=`keyring-agent-core/${tr} (Keyring Chatbot Agent; +https://keyring.app)`,ks=3e4,Ts=typeof process<"u"&&process.versions?.node!=null,Co=class{instance;constructor(e={}){this.instance=nr.default.create({baseURL:e.baseURL,timeout:e.timeout??ks,validateStatus:()=>!0,headers:{Accept:"application/json",...Ts?{"User-Agent":e.userAgent??ws}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[a,i]of Object.entries(o.headers??{}))i!=null&&(s[a.toLowerCase()]=String(i));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:s}}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},P=new Co;function L(l){let{data:e,status:t,statusText:n}=l,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=i=>i&&typeof i=="object"?i.message:void 0,a=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let i of a)if(typeof i=="string"&&i.trim())return i.trim()}return r}var Ye=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function et(l){if(!l||typeof l!="object")return!1;let e=l;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function _o(l){if(l?.aborted)throw new Ye}function or(l,e){if(!e)return{signal:l.signal,cleanup:()=>{}};if(e.aborted)return l.abort(),{signal:l.signal,cleanup:()=>{}};let t=()=>l.abort();return e.addEventListener("abort",t),{signal:l.signal,cleanup:()=>e.removeEventListener("abort",t)}}var rr={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},vs="https://nft.keyring.app/api/gemini-stable",As=new Set([408,429,500,502,503,504]),sr=3e4,Gn=l=>new Promise(e=>setTimeout(e,l));function Yn(l,e,t){if(t!=null&&t>0)return Math.min(t,sr);let n=Math.min(e*2**(l-1),sr);return n/2+Math.random()*(n/2)}function Ss(l){if(!l)return null;let e=Number(l);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(l);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var 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??vs}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:a=1e3}=n??{},i=n?.signal??this.requestSignal;_o(i);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 h=m.parts.map(g=>g.functionCall?`fc:${g.functionCall.name}`:g.functionResponse?`fr:${g.functionResponse.name}`:`text:${(g.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${h}]`)}}let u={contents:c,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(u.systemInstruction=r),t?.length?(u.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(u.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(u.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){_o(i);let h;try{h=await P.post(d,u,{headers:{"Content-Type":"application/json"},signal:i})}catch(k){if(et(k))throw k;if(p=k instanceof Error?k.message:String(k),m>=s)break;await Gn(Yn(m,a));continue}if(!h.ok){let k=typeof h.data=="string"?h.data:JSON.stringify(h.data)||h.statusText;if(p=`Gemini proxy error ${h.status}: ${k}`,!As.has(h.status))throw new Error(p);if(m>=s)break;let A=Ss(h.headers["retry-after"]??null);await Gn(Yn(m,a,A));continue}if(h.data==null||typeof h.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await Gn(Yn(m,a));continue}let g=h.data,f=g.candidates?.[0];if(!f)return{text:"",toolCalls:[]};let y="",b=[],w=f.content?.parts;if(!Array.isArray(w)||w.length===0){let k=f.finishReason;if(!(k==="SAFETY"||k==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${k??"none"})`,await Gn(Yn(m,a));continue}return{text:"",toolCalls:[]}}for(let k of w)k.text&&(y+=k.text),k.functionCall&&b.push({toolName:k.functionCall.name,args:k.functionCall.args??{},callId:k.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let T=g.usageMetadata?{promptTokens:g.usageMetadata.promptTokenCount??0,completionTokens:g.usageMetadata.candidatesTokenCount??0,totalTokens:g.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:b,usage:T}}throw new Error(p)}toContents(e){let t=[],n=[];for(let a of e){if(a.role==="system"){t.push(a.content);continue}if(a.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:a.toolName??"unknown",response:{result:a.content},...a.toolCallId?{id:a.toolCallId}:{}}}]});continue}if(a.role==="assistant"&&a.toolCalls?.length){n.push({role:"model",parts:a.toolCalls.map(i=>({functionCall:{name:i.toolName,args:i.args,...i.callId?{id:i.callId}:{}}}))});continue}n.push({role:a.role==="assistant"?"model":"user",parts:[{text:a.content}]})}let r=[];for(let a of n){let i=r[r.length-1],c=a.parts.some(d=>d.functionCall),u=i?.parts.some(d=>d.functionCall);i&&i.role===a.role&&!c&&!u?i.parts.push(...a.parts):r.push({...a,parts:[...a.parts]})}let o=[];for(let a=0;a<r.length;a++){let i=r[a],c=o[o.length-1];i.role==="function"&&!c?.parts.some(d=>d.functionCall)||i.role==="model"&&i.parts.some(d=>d.functionCall)&&!(r[a+1]?.role==="function")||o.push(i)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
|
|
2
|
+
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:rr[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:rr[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 tt=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 nt=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],Ps=new Set(nt),Oe=[...nt],ar=new Set(Oe),Se="0x1",Ke="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function xs(l){return l.map(e=>rt[e]??e).join(", ")}function Kn(l){let e=new Set;if(l)for(let n of l){let r=jn(n);r&&e.add(r)}let t=nt.filter(n=>!e.has(n));Oe=t.length>0?[...t]:[...nt],ar=new Set(Oe),Se=Oe.includes("0x1")?"0x1":Oe[0],Ke=xs(Oe)}var Cs={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708"};function ae(l){let e=jn(l);return e&&ar.has(e)?e:null}function jn(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Cs[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&&Ps.has(n)?n:null}function zn(l){return ae(l)!==null}function he(){return[...Oe]}var ot=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Ke}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Me=l=>typeof l=="string"&&l.trim()!=="";function ie(l,e){if(Me(l)){let t=ae(l);if(t)return t;throw new ot(l.trim())}if(Me(e?.chain)){let t=ae(e.chain);if(t)return t;throw new ot(e.chain.trim())}return null}function Qn(l,e){return ae(l)??ae(e?.chain)??void 0}var rt={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function E(l){let e=jn(l);return e&&rt[e]?rt[e]:typeof l=="string"&&l.trim()?l.trim():"the requested chain"}var _s={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build"};function ir(l,e){let t=jn(l),n=t?_s[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Es={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function lr(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase();return e?Es[e]??null:null}var Rs={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function cr(l){let e=ae(l);return e?Rs[e]??null:null}function st(l,e){if(!Me(l))return null;let t=ae(l),n=ae(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:rt[t]??t,connectedLabel:rt[n]??n}}function ur(l){let e=typeof l=="string"?l.trim():"";return Oe.map(t=>{let n=rt[t]??t;return{label:n,prompt:e?`${e} (${n})`:n}})}function at(l,e){return{actionButtons:ur(e),_instructions:`The user wants to ${l} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var z=class extends Error{code="needs_chain_selection";buttons;constructor(e){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=ur(e)}},Sn=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 j(l,e){if(Me(l))return l.trim();if(Me(e?.walletAddress))return e.walletAddress.trim();throw new Sn}function M(l,e){if(Me(l)){let t=ae(l);if(t)return t;throw new ot(l.trim())}if(Me(e?.chain)){let t=ae(e.chain);if(t)return t;throw new ot(e.chain.trim())}if(Me(e?.walletAddress))throw new z(typeof e?.query=="string"?e.query:void 0);return Se}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=Ns(o);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-r,...s.actionButtons?{actionButtons:s.actionButtons}:{}}}catch(o){return o instanceof z?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-r,actionButtons:o.buttons}:o instanceof Sn?{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 Ns(l){if(!l||typeof l!="object")return{data:l};let e=l,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:l};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var dr=require("js-sha3");function F(l){return typeof l=="string"&&/^0x[0-9a-fA-F]{40}$/.test(l)}function Us(l){return new Uint8Array(dr.keccak256.arrayBuffer(l))}function Pn(l){let e=l.startsWith("0x")?l.slice(2):l,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function pr(l){return"0x"+Array.from(l).map(e=>e.toString(16).padStart(2,"0")).join("")}function mr(l){return new TextEncoder().encode(l)}function je(...l){let e=l.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of l)t.set(r,n),n+=r.length;return t}function Is(l,e=32){let t=new Uint8Array(e);return t.set(l,e-l.length),t}function Ls(l,e=32){let t=new Uint8Array(e);return t.set(l),t}function hr(l){let e=((l%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Pn(e)}function xn(l){return hr(BigInt(l))}function gr(l){return l==="uint"?"uint256":l==="int"?"int256":l.match(/^uint$/)?"uint256":l.match(/^int$/)?"int256":l.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function fr(l){let e=gr(l.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(l.components??[]).map(fr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function Ds(l){let e=(l.inputs??[]).map(fr).join(",");return`${l.name??""}(${e})`}function Eo(l,e){let t=Bs(l.type);if(t){let[r,o]=t;return Os({...l,type:o},e,r)}if(l.type==="tuple")return Ms(l,e);if(l.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:Is(Pn(o.toLowerCase()))}}if(l.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=gr(l.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:xn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:hr(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Pn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ls(o)}}if(n==="bytes"){let r=typeof e=="string"?Pn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:je(xn(r.length),s)}}if(n==="string"){let r=typeof e=="string"?mr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:je(xn(r.length),s)}}throw new Error(`Unsupported ABI type: ${l.type}`)}function Ro(l){let e=0;for(let{dynamic:o,encoded:s}of l)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of l)o?(t.push(xn(e+r)),n.push(s),r+=s.length):t.push(s);return je(...t,...n)}function Os(l,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let a=Eo(l,s);a.dynamic&&(r=!0),o.push(a)}if(n||r){let s=Ro(o);if(n){let a=xn(o.length);return{dynamic:!0,encoded:o.length>0?je(a,s):a}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:je(...o.map(s=>s.encoded))}}function Ms(l,e){let t=l.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],a=Array.isArray(e)?e[o]:e[s.name??""],i=Eo(s,a);i.dynamic&&(n=!0),r.push(i)}return{dynamic:n,encoded:n?Ro(r):je(...r.map(o=>o.encoded))}}function Bs(l){let e=l.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function qs(l,e){if(l.length!==e.length)throw new Error(`Expected ${l.length} values, got ${e.length}`);if(l.length===0)return"0x";let t=l.map((r,o)=>Eo(r,e[o])),n=Ro(t);return pr(n)}function it({abi:l,functionName:e,args:t=[]}){let n=l.find(i=>(i.type==="function"||i.type===void 0)&&i.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=Ds(n),o=Us(mr(r)).slice(0,4),s=n.inputs??[],a=s.length===0||t.length===0?new Uint8Array(0):Pn(qs(s,t).slice(2));return pr(je(o,a))}var Fs="https://wallet-api.pantograph.app",$s="0x0000000000000000000000000000000000000000",wr={"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"]};function Cn(l){return wr[l.toLowerCase()]||l}function yr(l){let e=[];for(let[t,n]of Object.entries(l))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function No(l){let e=l,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function ne(l){if(l==null)return null;let e=typeof l=="number"?l:parseFloat(String(l));return Number.isFinite(e)?e:null}function br(l,e){let t=l.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=ne(l.price_change_percentage_24h)??ne(l.priceChange24h)??ne(l.usd_price_24hr_percent_change)??ne(l.price_change_24h)??ne(l.priceChange);return{chainId:e,tokenAddress:l.address??l.token_address??"",name:l.name??null,symbol:l.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:l.logoURI??l.icon_image??l.logo??null,usdPrice:ne(l.price)??ne(l.usd_price),marketCap:ne(l.market_cap)??ne(l.marketCap),totalVolume:{"24h":ne(l.total_volume)??ne(l.volume24h)},pricePercentChange:{"24h":r}}}var oe=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Fs).replace(/\/+$/,"")}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=Cn(t),r=e.map(u=>u.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(r)}`,s=await P.get(o);if(!s.ok)return;let a=s.data,i=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],c=new Map;for(let u of i)u.address&&c.set(u.address.toLowerCase(),{price:u.price!=null?parseFloat(String(u.price)):NaN,icon_image:u.icon_image});for(let u=0;u<e.length;u++){let d=c.get(e[u].token_address.toLowerCase());d&&(d.icon_image&&(e[u].logo=d.icon_image,e[u].thumbnail=d.icon_image),isNaN(d.price)||(e[u].usd_price=d.price,e[u].usd_value=parseFloat(e[u].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,t){try{let n=Cn(t),r=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await P.get(r);if(!o.ok)return null;let s=o.data,a=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],i=e.toLowerCase()===$s,c=a.find(u=>u.address?.toLowerCase()===e.toLowerCase()||i&&u.address===""||u.token_address?.toLowerCase()===e.toLowerCase()||i&&u.token_address==="");return c?No(c):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=Cn(t),o=`${this.baseUrl}/keyrings/tokens/${r}/v2?addresses=${encodeURIComponent(e.join(","))}`,s=await P.get(o);if(!s.ok)return n;let a=s.data,i=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],c=new Set(e.map(u=>u.toLowerCase()));for(let u of i){let d=u.address?.toLowerCase()||u.token_address?.toLowerCase()||(u.address===""?"":null);d&&c.has(d)&&(n[d]=No(u))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||Se,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=yr({chainId:o,key:t}),a=`${this.baseUrl}/token-list?${s}`,i=await P.get(a);if(!i.ok)throw new Error(L(i));let c=i.data,u=[];return c?.data?u=Array.isArray(c.data)?c.data:Object.values(c.data).flat():typeof c=="object"&&!Array.isArray(c)&&(u=Object.values(c).flat()),{success:!0,data:u.map(No)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Se,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,[a,i]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=a.status==="fulfilled"?a.value:[],u=i.status==="fulfilled"?o.map(g=>i.value[g.toLowerCase()]).filter(g=>g!=null).map(g=>br(g,t)):[],d=new Set,p=[];for(let g of u){let f=g.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(g))}let m=[];for(let g of c){let f=g.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(g))}let h=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(h,t),{success:!0,data:h}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=ne(s.market_cap)??ne(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":ne(s.total_volume)??ne(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=Cn(e),o=yr({duration:n,limit:t}),s=`${this.baseUrl}/token-list/top-gainers/${r}${o?`?${o}`:""}`,a=[];for(let i=0;i<5;i++){let c=await P.get(s);if(!c.ok)throw new Error(L(c));let u=c.data;if(a=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],a.length>0)break;i<4&&await new Promise(d=>setTimeout(d,2e3))}return a.map(i=>br(i,e))}async getTopGainers(e){let t=e?.chain||Se,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 Ws="https://nft.keyring.app",Vs="https://nft.keyring.app",Hs=.01,R=5,V=1e3,Gs="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ys="0x0000000000000000000000000000000000000000",N=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function K(l){return l||Se}function H(l){let e=[];for(let[t,n]of Object.entries(l))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function G(l){return new Promise(e=>setTimeout(e,l))}function Ks(l){if(Array.isArray(l))return l;if(l&&typeof l=="object"){let e=l;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Uo(l){if(Array.isArray(l))return l;if(l&&typeof l=="object"){let e=l;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ws).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Vs).replace(/\/+$/,""),this.pantograph=new oe({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let a=K(n),i="Unknown error";for(let c=1;c<=R;c++)try{let u={chain:a,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(u.token_addresses=r);let d=[],p=null;do{p&&(u.cursor=p);let h=H(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,f=await P.get(g);if(!f.ok)throw new N(f.status,L(f));let y=f.data,b=y?.data??y;b?.result?.length>0&&d.push(...b.result),p=b?.cursor??null}while(p);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(h=>parseFloat(h.balance||"0")>0),m.result=m.result.map(h=>({...h,token_address:h.token_address.toLowerCase()===Gs?Ys:h.token_address})),await this.enrichTokenPrices(m.result,a),m.result=m.result.filter(h=>h.usd_value==null||h.usd_value>=Hs)),{success:!0,data:m}}catch(u){if(i=u instanceof Error?u.message:"Unknown error",u instanceof N&&u.status===400)break;c<R&&await G(V)}return{success:!1,error:i}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=K(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let a=1;a<=R;a++)try{let[i,c]=await Promise.allSettled([P.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${H({chain:r,addresses:[t]})}`),P.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${H({chain:r,include:"percent_change"})}`)]),u=null;if(i.status==="fulfilled"&&i.value.ok){let p=i.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){o="Token metadata not found",a<R&&await G(V);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=10,excludeSpam:o=!0,cursor:s,tokenAddresses:a,includePrices:i,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=K(n),d="Unknown error";for(let p=1;p<=R;p++)try{let m={chain:u,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(m.cursor=s),i&&(m.include_prices=!0),a&&a.length>0&&(m.token_addresses=a);let h=H(m),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${h}`,f=await P.get(g);if(!f.ok)throw new N(f.status,L(f));let y=f.data;return{success:!0,data:y?.data??y}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof N&&m.status===400)break;p<R&&await G(V)}return{success:!1,error:d}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:a=!0,include:i}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!F(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=K(r),u="Unknown error";for(let d=1;d<=R;d++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:a};i&&(p.include=i);let m=H(p),h=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,g=await P.get(h);if(!g.ok)throw new N(g.status,L(g));let f=g.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof N&&p.status===400)break;d<R&&await G(V)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:a,toBlock:i,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=K(n),h=Math.max(1,Math.min(100,Math.floor(r))),g="Unknown error";for(let f=1;f<=R;f++)try{let y={chain:m,limit:h,order:u};o&&(y.from_date=o),s&&(y.to_date=s),a!=null&&(y.from_block=a),i!=null&&(y.to_block=i),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=H(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,T=await P.get(w);if(!T.ok)throw new N(T.status,L(T));let k=T.data;return{success:!0,data:k?.data??k}}catch(y){if(g=y instanceof Error?y.message:"Unknown error",y instanceof N&&y.status===400)break;f<R&&await G(V)}return{success:!1,error:g}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=K(n),m=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let g=1;g<=R;g++)try{let f={chain:p,limit:m,order:d};s&&(f.from_date=s),a&&(f.to_date=a),i!=null&&(f.from_block=i),c!=null&&(f.to_block=c),u&&(f.cursor=u),r?.length&&(f.contract_addresses=r);let y=H(f),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await P.get(b);if(!w.ok)throw new N(w.status,L(w));let T=w.data;return{success:!0,data:T?.data??T}}catch(f){if(h=f instanceof Error?f.message:"Unknown error",f instanceof N&&f.status===400)break;g<R&&await G(V)}return{success:!1,error:h}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let h=K(n),g=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let y=1;y<=R;y++)try{let b={chain:h,limit:g,order:d,format:m};s&&(b.from_date=s),a&&(b.to_date=a),i!=null&&(b.from_block=i),c!=null&&(b.to_block=c),u&&(b.cursor=u),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=H(b),T=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,k=await P.get(T);if(!k.ok)throw new N(k.status,L(k));let A=k.data;return{success:!0,data:A?.data??A}}catch(b){if(f=b instanceof Error?b.message:"Unknown error",b instanceof N&&b.status===400)break;y<R&&await G(V)}return{success:!1,error:f}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!F(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=K(n),s="Unknown error";for(let a=1;a<=R;a++)try{let i={chain:o};r&&(i.days=r);let c=H(i),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:s}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=K(n),a="Unknown error";for(let i=1;i<=R;i++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await P.get(d);if(!p.ok)throw new N(p.status,L(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(a=c instanceof Error?c.message:"Unknown error",c instanceof N&&c.status===400)break;i<R&&await G(V)}return{success:!1,error:a}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=K(n),a="Unknown error";for(let i=1;i<=R;i++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await P.get(d);if(!p.ok)throw new N(p.status,L(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(a=c instanceof Error?c.message:"Unknown error",c instanceof N&&c.status===400)break;i<R&&await G(V)}return{success:!1,error:a}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chains:r}),i=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chains:r}),i=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:Ks(d)}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!F(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=K(r),s="Unknown error";for(let a=1;a<=R;a++)try{let i=H({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${i}`,u=await P.get(c);if(!u.ok)throw new N(u.status,L(u));let m=u.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(g=>({label:g.label,address:g.address,balance_usd:g.balanceUsd??0,total_unclaimed_usd_value:g.unclaimedUsd??0,position_details:g.details,tokens:g.tokens.map(f=>({token_type:f.tokenType,address:f.address,contract_address:f.address,name:f.name??"",symbol:f.symbol??"",decimals:f.decimals??18,logo:f.logo,balance:f.balance??"0",balance_formatted:f.balanceFormatted??"0",usd_price:f.usdPrice,usd_value:f.usdValue}))}))}}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:s}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=K(n),o="Unknown error";for(let s=1;s<=R;s++)try{let a=H({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${a}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;s<R&&await G(V)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=R;o++)try{let s={};t&&(s.chain=K(t)),n!=null&&(s.limit=n);let a=H(s),i=`${this.baseUrl}/api/moralis/proxy/tokens/trending${a?`?${a}`:""}`,c=await P.get(i);if(!c.ok)throw new N(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:Uo(d)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof N&&s.status===400)break;o<R&&await G(V)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let a=1;a<=R;a++)try{let i={};t&&(i.chain=K(t)),n&&(i.time_frame=n),r!=null&&(i.min_market_cap=r),o!=null&&(i.security_score=o);let c=H(i),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:Uo(m)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let a=1;a<=R;a++)try{let i={};t&&(i.chain=K(t)),n&&(i.time_frame=n),r!=null&&(i.min_market_cap=r),o!=null&&(i.security_score=o);let c=H(i),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:Uo(m)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;a<R&&await G(V)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var lt=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';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new Z({})}async run(e,t){let n=e.keyword||"",r=M(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
|
+
`),[s,a,i]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),r?this.findTokenInWallet(r,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,o):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],u=e.toLowerCase(),d=f=>f.symbol?.toLowerCase()===u||f.token_address?.toLowerCase()===u,p=[...c].sort((f,y)=>(d(f)?0:1)-(d(y)?0:1)),m=null,h=p[0];if(h?.token_address){let f=await this.service.getTokenMetadata({address:h.token_address,chain:t});f.success&&f.data&&(m=f.data)}return!m&&h&&(m={...h}),{_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:!!a,walletBalance:a,token:m,...c.length>1?{searchResults:p.slice(0,10)}:{},research:i}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),s=r.data.result.find(a=>a.token_address.toLowerCase()===o||a.symbol?.toLowerCase()===o||a.name?.toLowerCase().includes(o));return s||null}};var ct=class extends v{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let a,i;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,a=d.symbol,i=d.name}let c=await this.service.getTokenHolders({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let u=c.data;return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},totalHolders:u.totalHolders,holdersByAcquisition:u.holdersByAcquisition,holderChange:u.holderChange,holderSupply:u.holderSupply,holderDistribution:u.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var ut=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.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let a,i;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,a=d.symbol,i=d.name}let c=await this.service.getTokenAnalytics({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let u=c.data??{};return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},usdPrice:u.usdPrice??null,totalLiquidity:u.totalLiquidity??null,totalFullyDilutedValuation:u.totalFullyDilutedValuation??null,totalBuyVolume:u.totalBuyVolume??null,totalSellVolume:u.totalSellVolume??null,totalBuyers:u.totalBuyers??null,totalSellers:u.totalSellers??null,totalBuys:u.totalBuys??null,totalSells:u.totalSells??null,uniqueWallets:u.uniqueWallets??null,pricePercentChange:u.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var dt=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.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let a,i;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,a=p.symbol,i=p.name}let c=await this.service.getTokenScore({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let u=c.data??{},d=u.metrics??{};return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},score:u.score??null,updatedAt:u.updatedAt??null,metrics:{usdPrice:d.usdPrice??null,liquidityUsd:d.liquidityUsd??null,volumeUsd:d.volumeUsd??null,transactions:d.transactions??null,supply:d.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var pt=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, and more.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;constructor(e){super(),this.service=new oe({baseUrl:e?.pantographUrl})}async run(e,t){let n=Qn(e.chain,t),r=e.buy_button_label||"",o=e.buy_prompt_template||"",s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,a=await this.service.getTrendingTokens({chain:n,limit:s});if(!a.success)return{error:a.error||"Failed to fetch trending tokens"};let i=a.data??[],c=new Set,u=[];for(let d of i){let p=d.symbol?.trim();!p||c.has(p.toLowerCase())||(c.add(p.toLowerCase()),u.push({label:this.fillTemplate(r,p,"Buy {token}"),prompt:this.fillTemplate(o,p,"buy {token}")}))}return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
|
|
4
4
|
<rank>. <name> (<symbol>)
|
|
5
5
|
- Price: <usdPrice>
|
|
6
6
|
- Market Cap: <marketCap>
|