keyring-agent-core 0.2.28 → 0.2.29
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 +4 -4
- package/dist/index.js +5 -4
- package/dist/index.native.js +5 -4
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1886,7 +1886,7 @@ interface WebsiteTrustInput {
|
|
|
1886
1886
|
}
|
|
1887
1887
|
/** Structured trust signals returned alongside the natural-language answer. */
|
|
1888
1888
|
interface WebsiteTrustExtraData {
|
|
1889
|
-
/** The site that was analyzed
|
|
1889
|
+
/** The site that was analyzed — echoed exactly as the caller passed it (scheme/path preserved). */
|
|
1890
1890
|
currentSite: string;
|
|
1891
1891
|
/**
|
|
1892
1892
|
* True under either criterion: (1) it impersonates a WELL-KNOWN brand
|
|
@@ -1898,9 +1898,9 @@ interface WebsiteTrustExtraData {
|
|
|
1898
1898
|
*/
|
|
1899
1899
|
isPhishing: boolean;
|
|
1900
1900
|
/**
|
|
1901
|
-
* The reputable site this one is judged to copy / impersonate
|
|
1902
|
-
*
|
|
1903
|
-
* imitates another site.
|
|
1901
|
+
* The reputable site this one is judged to copy / impersonate — the official
|
|
1902
|
+
* site URL WITH scheme when known (e.g. "https://relay.link"), else a domain
|
|
1903
|
+
* or brand name. Present ONLY when the verdict is that it imitates another site.
|
|
1904
1904
|
*/
|
|
1905
1905
|
copiedSite?: string;
|
|
1906
1906
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Qr=Object.create;var qn=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Zr=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var ts=(l,e)=>{for(var t in e)qn(l,t,{get:e[t],enumerable:!0})},Wo=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jr(e))!es.call(l,r)&&r!==t&&qn(l,r,{get:()=>e[r],enumerable:!(n=Xr(e,r))||n.enumerable});return l};var ns=(l,e,t)=>(t=l!=null?Qr(Zr(l)):{},Wo(e||!l||!l.__esModule?qn(t,"default",{value:l,enumerable:!0}):t,l)),os=l=>Wo(qn({},"__esModule",{value:!0}),l);var Ra={};ts(Ra,{AI_AGENT_TOOL_NAMES:()=>uo,AbortError:()=>Ye,AgentCore:()=>yo,ApproveTokenTool:()=>rn,BaseNftAiTool:()=>Pe,BaseNftMessageTool:()=>Pt,BaseSwapService:()=>$e,BaseTool:()=>T,BaseWalletActionTool:()=>ye,BuyTokenTool:()=>cn,ChatHistory:()=>pn,DEFAULT_CHAIN:()=>Se,DEFAULT_PROVIDER:()=>xn,DEFAULT_RPC_BY_CHAIN:()=>fe,DebridgeAdapter:()=>qt,EstimatePoolYieldTool:()=>Ht,GeminiProvider:()=>J,GeminiSearchAiTool:()=>Et,HEX_TO_PANTOGRAPH:()=>lr,KnowledgeBase:()=>hn,ManageLiquidityRedirectTool:()=>Yt,MoralisService:()=>D,NFTContractInfoTool:()=>_t,NFTMetadataTool:()=>Ct,NFT_AGENT_TOOL_NAMES:()=>co,OpenAddLiquidityFormTool:()=>Vt,POOL_AGENT_TOOL_NAMES:()=>po,PantographService:()=>ne,PoolByAddressTool:()=>Ot,PoolDetailTool:()=>Lt,PoolFallbackAiTool:()=>Rt,PoolPriceRangesTool:()=>Gt,PoolSearchTool:()=>Dt,PoolService:()=>Xe,PreviewAddLiquidityTool:()=>Wt,RelayAdapter:()=>Ft,Router:()=>gn,SUPPORTED_CHAINS:()=>nt,SUPPORTED_CHAINS_LABEL:()=>Ke,SWAP_PROVIDER_CONFIG:()=>Zn,SendNativeTool:()=>nn,SendNftTool:()=>dn,SendTokenTool:()=>on,Subagent:()=>j,SubgraphAddPoolTool:()=>Zt,SubgraphCoinPoolPairsTool:()=>Jt,SubgraphPoolByAddressTool:()=>zt,SubgraphPoolByPositionIdTool:()=>Qt,SubgraphPoolSearchTool:()=>Kt,SubgraphPositionDetailTool:()=>Xt,SubgraphTrendingPoolsTool:()=>jt,Summarizer:()=>mn,SwapServiceFactory:()=>Qe,SwapTokenTool:()=>un,Synthesizer:()=>fn,TOKEN_AGENT_TOOL_NAMES:()=>lo,TRANSFER_TOPIC:()=>Nr,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>cr,TokenAnalyticsTool:()=>ut,TokenHoldersTool:()=>ct,TokenInfoTool:()=>lt,TokenScoreTool:()=>dt,ToolRegistry:()=>tt,TopGainersTool:()=>mt,TopPoolsTool:()=>It,TransactionByHashTool:()=>St,TrendingTokensTool:()=>pt,UNISWAP_CHAIN_SLUG:()=>Cn,UpstashKnowledgeBase:()=>Ve,WALLET_ACTION_AGENT_TOOL_NAMES:()=>mo,WALLET_AGENT_TOOL_NAMES:()=>ao,WalletActionAppTool:()=>En,WalletApprovalsTool:()=>kt,WalletDefiPositionsTool:()=>Tt,WalletDefiProtocolPositionsTool:()=>At,WalletDefiSummaryTool:()=>vt,WalletHistoryTool:()=>gt,WalletNFTsTool:()=>xt,WalletNftTransfersTool:()=>yt,WalletPnlSummaryTool:()=>bt,WalletPnlTool:()=>wt,WalletTokenBalancesTool:()=>ht,WalletTokenTransfersTool:()=>ft,WebsiteTrustKeyringAgent:()=>bo,ZERO_ADDRESS:()=>$,buildRangePresets:()=>Lo,buildUniswapPoolUrl:()=>pe,clampTick:()=>_e,configureSupportedChains:()=>Vn,createAiAgent:()=>Ln,createDefaultSubagents:()=>ho,createNftAgent:()=>In,createPoolAgent:()=>Dn,createTokenAgent:()=>Un,createWalletActionAgent:()=>On,createWalletActionAppTools:()=>io,createWalletAgent:()=>Nn,ethCallAt:()=>Cr,ethCallByChain:()=>Io,getAffiliateFee:()=>Mt,getChainMeta:()=>ee,getDefaultRpcUrl:()=>Si,getGatewayAddress:()=>to,getNativeTokenInfo:()=>$t,getPositionManagerAddress:()=>no,getProviderByChain:()=>Jn,ingestKnowledgeBase:()=>zr,isAbortError:()=>et,normalizePriceRangeToPool:()=>Ut,priceToTick:()=>ze,resolveRpcUrl:()=>Bt,roundTickToSpacing:()=>xe,rpcCall:()=>Ie,setRpcOverrides:()=>Uo,swapServiceFactory:()=>Ce,tickToPrice:()=>be,toPantographChain:()=>An});module.exports=os(Ra);var Go=ns(require("axios"));var Ho="0.2.
|
|
1
|
+
"use strict";var Qr=Object.create;var qn=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Zr=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var ts=(l,e)=>{for(var t in e)qn(l,t,{get:e[t],enumerable:!0})},Wo=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jr(e))!es.call(l,r)&&r!==t&&qn(l,r,{get:()=>e[r],enumerable:!(n=Xr(e,r))||n.enumerable});return l};var ns=(l,e,t)=>(t=l!=null?Qr(Zr(l)):{},Wo(e||!l||!l.__esModule?qn(t,"default",{value:l,enumerable:!0}):t,l)),os=l=>Wo(qn({},"__esModule",{value:!0}),l);var Ra={};ts(Ra,{AI_AGENT_TOOL_NAMES:()=>uo,AbortError:()=>Ye,AgentCore:()=>yo,ApproveTokenTool:()=>rn,BaseNftAiTool:()=>Pe,BaseNftMessageTool:()=>Pt,BaseSwapService:()=>$e,BaseTool:()=>T,BaseWalletActionTool:()=>ye,BuyTokenTool:()=>cn,ChatHistory:()=>pn,DEFAULT_CHAIN:()=>Se,DEFAULT_PROVIDER:()=>xn,DEFAULT_RPC_BY_CHAIN:()=>fe,DebridgeAdapter:()=>qt,EstimatePoolYieldTool:()=>Ht,GeminiProvider:()=>J,GeminiSearchAiTool:()=>Et,HEX_TO_PANTOGRAPH:()=>lr,KnowledgeBase:()=>hn,ManageLiquidityRedirectTool:()=>Yt,MoralisService:()=>D,NFTContractInfoTool:()=>_t,NFTMetadataTool:()=>Ct,NFT_AGENT_TOOL_NAMES:()=>co,OpenAddLiquidityFormTool:()=>Vt,POOL_AGENT_TOOL_NAMES:()=>po,PantographService:()=>ne,PoolByAddressTool:()=>Ot,PoolDetailTool:()=>Lt,PoolFallbackAiTool:()=>Rt,PoolPriceRangesTool:()=>Gt,PoolSearchTool:()=>Dt,PoolService:()=>Xe,PreviewAddLiquidityTool:()=>Wt,RelayAdapter:()=>Ft,Router:()=>gn,SUPPORTED_CHAINS:()=>nt,SUPPORTED_CHAINS_LABEL:()=>Ke,SWAP_PROVIDER_CONFIG:()=>Zn,SendNativeTool:()=>nn,SendNftTool:()=>dn,SendTokenTool:()=>on,Subagent:()=>j,SubgraphAddPoolTool:()=>Zt,SubgraphCoinPoolPairsTool:()=>Jt,SubgraphPoolByAddressTool:()=>zt,SubgraphPoolByPositionIdTool:()=>Qt,SubgraphPoolSearchTool:()=>Kt,SubgraphPositionDetailTool:()=>Xt,SubgraphTrendingPoolsTool:()=>jt,Summarizer:()=>mn,SwapServiceFactory:()=>Qe,SwapTokenTool:()=>un,Synthesizer:()=>fn,TOKEN_AGENT_TOOL_NAMES:()=>lo,TRANSFER_TOPIC:()=>Nr,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>cr,TokenAnalyticsTool:()=>ut,TokenHoldersTool:()=>ct,TokenInfoTool:()=>lt,TokenScoreTool:()=>dt,ToolRegistry:()=>tt,TopGainersTool:()=>mt,TopPoolsTool:()=>It,TransactionByHashTool:()=>St,TrendingTokensTool:()=>pt,UNISWAP_CHAIN_SLUG:()=>Cn,UpstashKnowledgeBase:()=>Ve,WALLET_ACTION_AGENT_TOOL_NAMES:()=>mo,WALLET_AGENT_TOOL_NAMES:()=>ao,WalletActionAppTool:()=>En,WalletApprovalsTool:()=>kt,WalletDefiPositionsTool:()=>Tt,WalletDefiProtocolPositionsTool:()=>At,WalletDefiSummaryTool:()=>vt,WalletHistoryTool:()=>gt,WalletNFTsTool:()=>xt,WalletNftTransfersTool:()=>yt,WalletPnlSummaryTool:()=>bt,WalletPnlTool:()=>wt,WalletTokenBalancesTool:()=>ht,WalletTokenTransfersTool:()=>ft,WebsiteTrustKeyringAgent:()=>bo,ZERO_ADDRESS:()=>$,buildRangePresets:()=>Lo,buildUniswapPoolUrl:()=>pe,clampTick:()=>_e,configureSupportedChains:()=>Vn,createAiAgent:()=>Ln,createDefaultSubagents:()=>ho,createNftAgent:()=>In,createPoolAgent:()=>Dn,createTokenAgent:()=>Un,createWalletActionAgent:()=>On,createWalletActionAppTools:()=>io,createWalletAgent:()=>Nn,ethCallAt:()=>Cr,ethCallByChain:()=>Io,getAffiliateFee:()=>Mt,getChainMeta:()=>ee,getDefaultRpcUrl:()=>Si,getGatewayAddress:()=>to,getNativeTokenInfo:()=>$t,getPositionManagerAddress:()=>no,getProviderByChain:()=>Jn,ingestKnowledgeBase:()=>zr,isAbortError:()=>et,normalizePriceRangeToPool:()=>Ut,priceToTick:()=>ze,resolveRpcUrl:()=>Bt,roundTickToSpacing:()=>xe,rpcCall:()=>Ie,setRpcOverrides:()=>Uo,swapServiceFactory:()=>Ce,tickToPrice:()=>be,toPantographChain:()=>An});module.exports=os(Ra);var Go=ns(require("axios"));var Ho="0.2.29";var ss=`keyring-agent-core/${Ho} (Keyring Chatbot Agent; +https://keyring.app)`,is=3e4,as=typeof process<"u"&&process.versions?.node!=null,wo=class{instance;constructor(e={}){this.instance=Go.default.create({baseURL:e.baseURL,timeout:e.timeout??is,validateStatus:()=>!0,headers:{Accept:"application/json",...as?{"User-Agent":e.userAgent??ss}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[i,a]of Object.entries(o.headers??{}))a!=null&&(s[i.toLowerCase()]=String(a));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:s}}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},P=new wo;function L(l){let{data:e,status:t,statusText:n}=l,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=a=>a&&typeof a=="object"?a.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let a of i)if(typeof a=="string"&&a.trim())return a.trim()}return r}var 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 ko(l){if(l?.aborted)throw new Ye}function Yo(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 Ko={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},ls="https://nft.keyring.app/api/gemini-stable",cs=new Set([408,429,500,502,503,504]),jo=3e4,Fn=l=>new Promise(e=>setTimeout(e,l));function $n(l,e,t){if(t!=null&&t>0)return Math.min(t,jo);let n=Math.min(e*2**(l-1),jo);return n/2+Math.random()*(n/2)}function us(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 J=class{model;maxTokens;temperature;baseUrl;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??ls}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},a=n?.signal??this.requestSignal;ko(a);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of c){let g=m.parts.map(h=>h.functionCall?`fc:${h.functionCall.name}`:h.functionResponse?`fr:${h.functionResponse.name}`:`text:${(h.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let u={contents:c,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(u.systemInstruction=r),t?.length?(u.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(u.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(u.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){ko(a);let g;try{g=await P.post(d,u,{headers:{"Content-Type":"application/json"},signal:a})}catch(k){if(et(k))throw k;if(p=k instanceof Error?k.message:String(k),m>=s)break;await Fn($n(m,i));continue}if(!g.ok){let k=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(p=`Gemini proxy error ${g.status}: ${k}`,!cs.has(g.status))throw new Error(p);if(m>=s)break;let A=us(g.headers["retry-after"]??null);await Fn($n(m,i,A));continue}if(g.data==null||typeof g.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await Fn($n(m,i));continue}let h=g.data,f=h.candidates?.[0];if(!f)return{text:"",toolCalls:[]};let y="",b=[],w=f.content?.parts;if(!Array.isArray(w)||w.length===0){let k=f.finishReason;if(!(k==="SAFETY"||k==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${k??"none"})`,await Fn($n(m,i));continue}return{text:"",toolCalls:[]}}for(let k of w)k.text&&(y+=k.text),k.functionCall&&b.push({toolName:k.functionCall.name,args:k.functionCall.args??{},callId:k.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let v=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:b,usage:v}}throw new Error(p)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(a=>({functionCall:{name:a.toolName,args:a.args,...a.callId?{id:a.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let a=r[r.length-1],c=i.parts.some(d=>d.functionCall),u=a?.parts.some(d=>d.functionCall);a&&a.role===i.role&&!c&&!u?a.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let a=r[i],c=o[o.length-1];a.role==="function"&&!c?.parts.some(d=>d.functionCall)||a.role==="model"&&a.parts.some(d=>d.functionCall)&&!(r[i+1]?.role==="function")||o.push(a)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
|
|
2
2
|
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:Ko[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:Ko[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"],ds=new Set(nt),Oe=[...nt],zo=new Set(Oe),Se="0x1",Ke="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function ps(l){return l.map(e=>rt[e]??e).join(", ")}function Vn(l){let e=new Set;if(l)for(let n of l){let r=Wn(n);r&&e.add(r)}let t=nt.filter(n=>!e.has(n));Oe=t.length>0?[...t]:[...nt],zo=new Set(Oe),Se=Oe.includes("0x1")?"0x1":Oe[0],Ke=ps(Oe)}var ms={"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 ie(l){let e=Wn(l);return e&&zo.has(e)?e:null}function Wn(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=ms[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&&ds.has(n)?n:null}function Hn(l){return ie(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 ae(l,e){if(Me(l)){let t=ie(l);if(t)return t;throw new ot(l.trim())}if(Me(e?.chain)){let t=ie(e.chain);if(t)return t;throw new ot(e.chain.trim())}return null}function Gn(l,e){return ie(l)??ie(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=Wn(l);return e&&rt[e]?rt[e]:typeof l=="string"&&l.trim()?l.trim():"the requested chain"}var hs={"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 Qo(l,e){let t=Wn(l),n=t?hs[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var gs={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function Xo(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase();return e?gs[e]??null:null}var fs={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function Jo(l){let e=ie(l);return e?fs[e]??null:null}function st(l,e){if(!Me(l))return null;let t=ie(l),n=ie(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:rt[t]??t,connectedLabel:rt[n]??n}}function Zo(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 it(l,e){return{actionButtons:Zo(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=Zo(e)}},kn=class extends Error{code="no_wallet_connected";constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one."),this.name="NoWalletConnectedError"}};function K(l,e){if(Me(l))return l.trim();if(Me(e?.walletAddress))return e.walletAddress.trim();throw new kn}function M(l,e){if(Me(l)){let t=ie(l);if(t)return t;throw new ot(l.trim())}if(Me(e?.chain)){let t=ie(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 T=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s=ys(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 kn?{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 ys(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 er=require("js-sha3");function F(l){return typeof l=="string"&&/^0x[0-9a-fA-F]{40}$/.test(l)}function bs(l){return new Uint8Array(er.keccak256.arrayBuffer(l))}function vn(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 tr(l){return"0x"+Array.from(l).map(e=>e.toString(16).padStart(2,"0")).join("")}function nr(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 ws(l,e=32){let t=new Uint8Array(e);return t.set(l,e-l.length),t}function ks(l,e=32){let t=new Uint8Array(e);return t.set(l),t}function or(l){let e=((l%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return vn(e)}function Tn(l){return or(BigInt(l))}function rr(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 sr(l){let e=rr(l.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(l.components??[]).map(sr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function vs(l){let e=(l.inputs??[]).map(sr).join(",");return`${l.name??""}(${e})`}function vo(l,e){let t=Ss(l.type);if(t){let[r,o]=t;return Ts({...l,type:o},e,r)}if(l.type==="tuple")return As(l,e);if(l.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:ws(vn(o.toLowerCase()))}}if(l.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=rr(l.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:Tn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:or(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?vn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:ks(o)}}if(n==="bytes"){let r=typeof e=="string"?vn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:je(Tn(r.length),s)}}if(n==="string"){let r=typeof e=="string"?nr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:je(Tn(r.length),s)}}throw new Error(`Unsupported ABI type: ${l.type}`)}function To(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(Tn(e+r)),n.push(s),r+=s.length):t.push(s);return je(...t,...n)}function Ts(l,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let i=vo(l,s);i.dynamic&&(r=!0),o.push(i)}if(n||r){let s=To(o);if(n){let i=Tn(o.length);return{dynamic:!0,encoded:o.length>0?je(i,s):i}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:je(...o.map(s=>s.encoded))}}function As(l,e){let t=l.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],i=Array.isArray(e)?e[o]:e[s.name??""],a=vo(s,i);a.dynamic&&(n=!0),r.push(a)}return{dynamic:n,encoded:n?To(r):je(...r.map(o=>o.encoded))}}function Ss(l){let e=l.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Ps(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)=>vo(r,e[o])),n=To(t);return tr(n)}function at({abi:l,functionName:e,args:t=[]}){let n=l.find(a=>(a.type==="function"||a.type===void 0)&&a.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=vs(n),o=bs(nr(r)).slice(0,4),s=n.inputs??[],i=s.length===0||t.length===0?new Uint8Array(0):vn(Ps(s,t).slice(2));return tr(je(o,i))}var xs="https://wallet-api.pantograph.app",_s="0x0000000000000000000000000000000000000000",lr={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},cr={"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 An(l){return lr[l.toLowerCase()]||l}function ir(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 Ao(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 te(l){if(l==null)return null;let e=typeof l=="number"?l:parseFloat(String(l));return Number.isFinite(e)?e:null}function ar(l,e){let t=l.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=te(l.price_change_percentage_24h)??te(l.priceChange24h)??te(l.usd_price_24hr_percent_change)??te(l.price_change_24h)??te(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:te(l.price)??te(l.usd_price),marketCap:te(l.market_cap)??te(l.marketCap),totalVolume:{"24h":te(l.total_volume)??te(l.volume24h)},pricePercentChange:{"24h":r}}}var ne=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??xs).replace(/\/+$/,"")}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=An(t),r=e.map(u=>u.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(r)}`,s=await P.get(o);if(!s.ok)return;let i=s.data,a=Array.isArray(i)?i:Array.isArray(i.data)?i.data:[],c=new Map;for(let u of a)u.address&&c.set(u.address.toLowerCase(),{price:u.price!=null?parseFloat(String(u.price)):NaN,icon_image:u.icon_image});for(let u=0;u<e.length;u++){let d=c.get(e[u].token_address.toLowerCase());d&&(d.icon_image&&(e[u].logo=d.icon_image,e[u].thumbnail=d.icon_image),isNaN(d.price)||(e[u].usd_price=d.price,e[u].usd_value=parseFloat(e[u].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,t){try{let n=An(t),r=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await P.get(r);if(!o.ok)return null;let s=o.data,i=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],a=e.toLowerCase()===_s,c=i.find(u=>u.address?.toLowerCase()===e.toLowerCase()||a&&u.address===""||u.token_address?.toLowerCase()===e.toLowerCase()||a&&u.token_address==="");return c?Ao(c):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=An(t),o=`${this.baseUrl}/keyrings/tokens/${r}/v2?addresses=${encodeURIComponent(e.join(","))}`,s=await P.get(o);if(!s.ok)return n;let i=s.data,a=Array.isArray(i)?i:Array.isArray(i.data)?i.data:[],c=new Set(e.map(u=>u.toLowerCase()));for(let u of a){let d=u.address?.toLowerCase()||u.token_address?.toLowerCase()||(u.address===""?"":null);d&&c.has(d)&&(n[d]=Ao(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=ir({chainId:o,key:t}),i=`${this.baseUrl}/token-list?${s}`,a=await P.get(i);if(!a.ok)throw new Error(L(a));let c=a.data,u=[];return c?.data?u=Array.isArray(c.data)?c.data:Object.values(c.data).flat():typeof c=="object"&&!Array.isArray(c)&&(u=Object.values(c).flat()),{success:!0,data:u.map(Ao)}}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=cr[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[i,a]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],u=a.status==="fulfilled"?o.map(h=>a.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>ar(h,t)):[],d=new Set,p=[];for(let h of u){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(h))}let m=[];for(let h of c){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(h))}let g=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,t),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=te(s.market_cap)??te(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":te(s.total_volume)??te(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=An(e),o=ir({duration:n,limit:t}),s=`${this.baseUrl}/token-list/top-gainers/${r}${o?`?${o}`:""}`,i=[];for(let a=0;a<5;a++){let c=await P.get(s);if(!c.ok)throw new Error(L(c));let u=c.data;if(i=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],i.length>0)break;a<4&&await new Promise(d=>setTimeout(d,2e3))}return i.map(a=>ar(a,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 Cs="https://nft.keyring.app",Es="https://nft.keyring.app",Rs=.01,R=5,W=1e3,Ns="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Us="0x0000000000000000000000000000000000000000",N=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function Y(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 Is(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 So(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??Cs).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Es).replace(/\/+$/,""),this.pantograph=new ne({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=Y(n),a="Unknown error";for(let c=1;c<=R;c++)try{let u={chain:i,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(u.token_addresses=r);let d=[],p=null;do{p&&(u.cursor=p);let g=H(u),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${g}`,f=await P.get(h);if(!f.ok)throw new 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(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===Ns?Us:g.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=Rs)),{success:!0,data:m}}catch(u){if(a=u instanceof Error?u.message:"Unknown error",u instanceof N&&u.status===400)break;c<R&&await G(W)}return{success:!1,error:a}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=Y(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let i=1;i<=R;i++)try{let[a,c]=await Promise.allSettled([P.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${H({chain:r,addresses:[t]})}`),P.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${H({chain:r,include:"percent_change"})}`)]),u=null;if(a.status==="fulfilled"&&a.value.ok){let p=a.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){o="Token metadata not found",i<R&&await G(W);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=10,excludeSpam:o=!0,cursor:s,tokenAddresses:i,includePrices:a,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=Y(n),d="Unknown error";for(let p=1;p<=R;p++)try{let m={chain:u,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(m.cursor=s),a&&(m.include_prices=!0),i&&i.length>0&&(m.token_addresses=i);let g=H(m),h=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${g}`,f=await P.get(h);if(!f.ok)throw new 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(W)}return{success:!1,error:d}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:i=!0,include:a}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!F(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=Y(r),u="Unknown error";for(let d=1;d<=R;d++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:i};a&&(p.include=a);let m=H(p),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await P.get(g);if(!h.ok)throw new N(h.status,L(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof N&&p.status===400)break;d<R&&await G(W)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:i,toBlock:a,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=Y(n),g=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let f=1;f<=R;f++)try{let y={chain:m,limit:g,order:u};o&&(y.from_date=o),s&&(y.to_date=s),i!=null&&(y.from_block=i),a!=null&&(y.to_block=a),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=H(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,v=await P.get(w);if(!v.ok)throw new N(v.status,L(v));let k=v.data;return{success:!0,data:k?.data??k}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof N&&y.status===400)break;f<R&&await G(W)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:a,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=Y(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let h=1;h<=R;h++)try{let f={chain:p,limit:m,order:d};s&&(f.from_date=s),i&&(f.to_date=i),a!=null&&(f.from_block=a),c!=null&&(f.to_block=c),u&&(f.cursor=u),r?.length&&(f.contract_addresses=r);let y=H(f),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await P.get(b);if(!w.ok)throw new N(w.status,L(w));let v=w.data;return{success:!0,data:v?.data??v}}catch(f){if(g=f instanceof Error?f.message:"Unknown error",f instanceof N&&f.status===400)break;h<R&&await G(W)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:a,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=Y(n),h=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let y=1;y<=R;y++)try{let b={chain:g,limit:h,order:d,format:m};s&&(b.from_date=s),i&&(b.to_date=i),a!=null&&(b.from_block=a),c!=null&&(b.to_block=c),u&&(b.cursor=u),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=H(b),v=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,k=await P.get(v);if(!k.ok)throw new 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(W)}return{success:!1,error:f}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!F(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=Y(n),s="Unknown error";for(let i=1;i<=R;i++)try{let a={chain:o};r&&(a.days=r);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:s}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=Y(n),i="Unknown error";for(let a=1;a<=R;a++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await P.get(d);if(!p.ok)throw new N(p.status,L(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof N&&c.status===400)break;a<R&&await G(W)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=Y(n),i="Unknown error";for(let a=1;a<=R;a++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await P.get(d);if(!p.ok)throw new N(p.status,L(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof N&&c.status===400)break;a<R&&await G(W)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chains:r}),a=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chains:r}),a=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:Is(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!F(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=Y(r),s="Unknown error";for(let i=1;i<=R;i++)try{let a=H({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${a}`,u=await P.get(c);if(!u.ok)throw new 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(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(f=>({token_type:f.tokenType,address:f.address,contract_address:f.address,name:f.name??"",symbol:f.symbol??"",decimals:f.decimals??18,logo:f.logo,balance:f.balance??"0",balance_formatted:f.balanceFormatted??"0",usd_price:f.usdPrice,usd_value:f.usdValue}))}))}}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:s}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=R;o++)try{let s={};t&&(s.chain=Y(t)),n!=null&&(s.limit=n);let i=H(s),a=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:So(d)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof N&&s.status===400)break;o<R&&await G(W)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=R;i++)try{let a={};t&&(a.chain=Y(t)),n&&(a.time_frame=n),r!=null&&(a.min_market_cap=r),o!=null&&(a.security_score=o);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:So(m)}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=R;i++)try{let a={};t&&(a.chain=Y(t)),n&&(a.time_frame=n),r!=null&&(a.min_market_cap=r),o!=null&&(a.security_score=o);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:So(m)}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var lt=class extends T{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0},{name:"buy_button_label",type:"string",description:`Label for the "Buy" suggestion button shown under the token info, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the Buy button is clicked. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new J({})}async run(e,t){let n=e.keyword||"",r=M(e.chain,t),o=e.prompt||"",s=e.buy_button_label||"",i=e.buy_prompt_template||"",a=t?.walletAddress||void 0;return n?await this.searchToken(n,r,o,s,i,a):{error:"Missing required parameter: keyword"}}async execute(e,t){let n=await super.execute(e,t),r=n.data;return n.success&&r&&Array.isArray(r.actionButtons)&&r.actionButtons.length>0&&(n.actionButtons=r.actionButtons),n}async searchToken(e,t,n,r,o,s){let i=[s?`User's connected wallet address: ${s}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
|
|
3
3
|
`),[a,c,u]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),s?this.findTokenInWallet(s,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,i):Promise.resolve(null)]),d=a.success&&a.data?Array.isArray(a.data)?a.data:[]:[],p=e.toLowerCase(),m=v=>v.symbol?.toLowerCase()===p||v.token_address?.toLowerCase()===p,g=[...d].sort((v,k)=>(m(v)?0:1)-(m(k)?0:1)),h=null,f=g[0];if(f?.token_address){let v=await this.service.getTokenMetadata({address:f.token_address,chain:t});v.success&&v.data&&(h=v.data)}!h&&f&&(h={...f});let y=h?.symbol?.trim(),b=y?[{label:this.fillTemplate(r,y,"Buy {token}"),prompt:this.fillTemplate(o,y,"buy {token}")}]:[];return{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it. A "Buy" button is shown below your reply automatically \u2014 do NOT mention it, list it, or repeat its text.',chain:t,userHoldsToken:!!c,walletBalance:c,token:h,...d.length>1?{searchResults:g.slice(0,10)}:{},research:u,...b.length>0?{actionButtons:b}:{}}}fillTemplate(e,t,n){return(e&&e.includes("{token}")?e:n).replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),s=r.data.result.find(i=>i.token_address.toLowerCase()===o||i.symbol?.toLowerCase()===o||i.name?.toLowerCase().includes(o));return s||null}};var ct=class extends T{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,a;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,i=d.symbol,a=d.name}let c=await this.service.getTokenHolders({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let u=c.data;return{token:{symbol:i??o??null,name:a??null,contractAddress:s,chain:n||"default"},totalHolders:u.totalHolders,holdersByAcquisition:u.holdersByAcquisition,holderChange:u.holderChange,holderSupply:u.holderSupply,holderDistribution:u.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(a=>(a.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var ut=class extends T{name="get-token-analytics";description=`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,a;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,i=d.symbol,a=d.name}let c=await this.service.getTokenAnalytics({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let u=c.data??{};return{token:{symbol:i??o??null,name:a??null,contractAddress:s,chain:n||"default"},usdPrice:u.usdPrice??null,totalLiquidity:u.totalLiquidity??null,totalFullyDilutedValuation:u.totalFullyDilutedValuation??null,totalBuyVolume:u.totalBuyVolume??null,totalSellVolume:u.totalSellVolume??null,totalBuyers:u.totalBuyers??null,totalSellers:u.totalSellers??null,totalBuys:u.totalBuys??null,totalSells:u.totalSells??null,uniqueWallets:u.uniqueWallets??null,pricePercentChange:u.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(a=>(a.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var dt=class extends T{name="get-token-score";description=`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=M(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,a;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,i=p.symbol,a=p.name}let c=await this.service.getTokenScore({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let u=c.data??{},d=u.metrics??{};return{token:{symbol:i??o??null,name:a??null,contractAddress:s,chain:n||"default"},score:u.score??null,updatedAt:u.updatedAt??null,metrics:{usdPrice:d.usdPrice??null,liquidityUsd:d.liquidityUsd??null,volumeUsd:d.volumeUsd??null,transactions:d.transactions??null,supply:d.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(a=>(a.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var pt=class extends T{name="get-trending-tokens";description='List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, and more.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;constructor(e){super(),this.service=new ne({baseUrl:e?.pantographUrl})}async run(e,t){let n=Gn(e.chain,t),r=e.buy_button_label||"",o=e.buy_prompt_template||"",s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,i=await this.service.getTrendingTokens({chain:n,limit:s});if(!i.success)return{error:i.error||"Failed to fetch trending tokens"};let a=i.data??[],c=new Set,u=[];for(let d of a){let p=d.symbol?.trim();!p||c.has(p.toLowerCase())||(c.add(p.toLowerCase()),u.push({label:this.fillTemplate(r,p,"Buy {token}"),prompt:this.fillTemplate(o,p,"buy {token}")}))}return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
|
|
4
4
|
<rank>. <name> (<symbol>)
|
|
@@ -1042,12 +1042,12 @@ RULES:
|
|
|
1042
1042
|
- Suggestions must be diverse \u2014 do not repeat the same intent in different words.
|
|
1043
1043
|
- Use the same language as the user.
|
|
1044
1044
|
- Good example (pool): ["Add liquidity to USDC/WETH 0.05%", "Estimate yield for $1000 here", "Compare with 0.3% fee tier"]
|
|
1045
|
-
- Bad example: ["What is a pool?", "How do pools work?", "Tell me more"] (generic, no action, no specifics)`,timestamp:0}])).text.match(/\[[\s\S]*\]/);return i?JSON.parse(i[0]).filter(c=>typeof c=="string"&&c.length>0).slice(0,3):[]}catch{return[]}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}getLastSuggestions(){let e=this.getDisplayHistory();for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant")return n.suggestedPrompts??[]}return[]}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),t=6,n=0,r=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(n++,n>=t)){r=p;break}let o=e.slice(r),s=Mr(o,o.length),i=e.length-s.length,a=Re(e.slice(0,i)),c=this.history.getSummary(),u=[];c&&u.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),u.push(...a);let d=await this.summarizer.summarize(u);this.history.compactWith(d,s)}persistToolMessages(e){for(let t of e)t.toolMessages.length>0&&(this.history.addMany(t.toolMessages),this.history.add({role:"assistant",content:t.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${t.toolMessages.length} tool message(s) + finalAnswer from ${t.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};var Ca='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',bo=class{llm;debug;constructor(e={}){this.llm=e.provider??new J({temperature:.8,...e.llm}),this.debug=e.debug??!1}async chat(e){let t=(e?.url??"").trim();if(!t)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(t),r=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let d=await this.describeOfficial(t,o),{answer:p}=await this.present(n,{isPhishing:!1,description:d,reasons:[]},r,o);return{answer:p,extraData:{currentSite:
|
|
1045
|
+
- Bad example: ["What is a pool?", "How do pools work?", "Tell me more"] (generic, no action, no specifics)`,timestamp:0}])).text.match(/\[[\s\S]*\]/);return i?JSON.parse(i[0]).filter(c=>typeof c=="string"&&c.length>0).slice(0,3):[]}catch{return[]}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}getLastSuggestions(){let e=this.getDisplayHistory();for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant")return n.suggestedPrompts??[]}return[]}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),t=6,n=0,r=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(n++,n>=t)){r=p;break}let o=e.slice(r),s=Mr(o,o.length),i=e.length-s.length,a=Re(e.slice(0,i)),c=this.history.getSummary(),u=[];c&&u.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),u.push(...a);let d=await this.summarizer.summarize(u);this.history.compactWith(d,s)}persistToolMessages(e){for(let t of e)t.toolMessages.length>0&&(this.history.addMany(t.toolMessages),this.history.add({role:"assistant",content:t.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${t.toolMessages.length} tool message(s) + finalAnswer from ${t.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};var Ca='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',bo=class{llm;debug;constructor(e={}){this.llm=e.provider??new J({temperature:.8,...e.llm}),this.debug=e.debug??!1}async chat(e){let t=(e?.url??"").trim();if(!t)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(t),r=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let d=await this.describeOfficial(t,o),{answer:p}=await this.present(n,{isPhishing:!1,description:d,reasons:[]},r,o);return{answer:p,extraData:{currentSite:t,isPhishing:!1}}}let s=await this.investigate(t,n,o),i=this.buildVerdict(n,s);this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",n),console.log("[WebsiteTrustKeyringAgent] investigation:",s),console.log("[WebsiteTrustKeyringAgent] verdict:",i));let{answer:a,reasons:c}=await this.present(n,{isPhishing:i.isPhishing,description:s.description,copiedSite:i.copiedSite,reasons:i.reasons},r,o),u={currentSite:t,isPhishing:i.isPhishing};return i.copiedSite&&(u.copiedSite=i.copiedSite),i.isPhishing&&c.length>0&&(u.reasons=c),{answer:a,extraData:u}}catch(s){throw new Error(`WebsiteTrustKeyringAgent.chat failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}buildVerdict(e,t){let n=[t.officialDomain,...t.affiliatedDomains].filter(p=>!!p),r=n.length>0?n.some(p=>this.isSameRegistrableDomain(e,p)):t.exactMatchOfficial,s=(t.resemblesBrand||this.carriesBrandName(e,t.officialDomain,t.brand))&&!r&&t.brandIsWellKnown&&(n.length>0||!t.hasOwnLegitPresence),a=!(r||t.hasOwnLegitPresence&&!s)&&t.scamReports.length>0,c=s||a;if(!c)return{isPhishing:!1,reasons:[]};let u=[];if(s){let p=t.officialDomain?this.describeLookAlike(e,t.officialDomain):void 0;p&&u.push(p),t.impersonationEvidence.length>0?u.push(...t.impersonationEvidence):p||u.push(t.officialDomain?`This address (${e}) is not the official ${t.brand??"brand"} domain \u2014 the real one is ${t.officialDomain}; the look-alike is easy to miss at a glance.`:`This domain (${e}) imitates ${t.brand??"a known brand"} but is not its official site and has no legitimate presence of its own.`)}a&&u.push(...t.scamReports);let d=s?t.officialUrl??t.officialDomain??t.brand:void 0;return{isPhishing:c,copiedSite:d,reasons:this.dedupe(u)}}async investigate(e,t,n){let r=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${t}
|
|
1046
1046
|
URL: ${e}
|
|
1047
1047
|
|
|
1048
1048
|
Investigate, using web search, whether this EXACT domain is a legitimate official site or a phishing / look-alike / scam site. Work through:
|
|
1049
1049
|
A. Describe what this site is or claims to be for the user: the product/service it offers, what it does, and who appears to operate it. This is the main information the user wants about the site \u2014 be concrete.
|
|
1050
|
-
B. Does the domain carry or RESEMBLE a recognizable brand / product / service \u2014 exactly, or via a typo, an extra/missing/swapped letter, a homoglyph, an ADDED WORD or hyphen (e.g. brand+"rpc"/"wallet"/"app"/"pro"/"support"/"finance"), or the brand placed on a different TLD or in a subdomain/path? Treat "the official name with extra text bolted on" as RESEMBLING the brand \u2014 set resemblesBrand=true. If it references ANY identifiable brand/product, you MUST search for and return that brand's OFFICIAL canonical domain in \`officialDomain\` (do not leave it null when the brand is identifiable). A "did you mean" correction to the REAL domain helps you learn the official domain but does NOT make the domain under test legitimate.
|
|
1050
|
+
B. Does the domain carry or RESEMBLE a recognizable brand / product / service \u2014 exactly, or via a typo, an extra/missing/swapped letter, a homoglyph, an ADDED WORD or hyphen (e.g. brand+"rpc"/"wallet"/"app"/"pro"/"support"/"finance"), or the brand placed on a different TLD or in a subdomain/path? Treat "the official name with extra text bolted on" as RESEMBLING the brand \u2014 set resemblesBrand=true. If it references ANY identifiable brand/product, you MUST search for and return that brand's OFFICIAL canonical domain in \`officialDomain\` (do not leave it null when the brand is identifiable). Also return that brand's full official site URL \u2014 including the real scheme (https:// or http://) you confirm via search \u2014 in \`officialUrl\`. A "did you mean" correction to the REAL domain helps you learn the official domain but does NOT make the domain under test legitimate.
|
|
1051
1051
|
A name within 1-2 letters of a well-known domain (missing / doubled / swapped letter, e.g. "opensee" for "opensea", "binanse" for "binance") is a TYPOSQUAT: set resemblesBrand=true, name the intended brand, and return its official domain. Identifying the brand it MIMICS is REQUIRED; it never makes the typo legitimate.
|
|
1052
1052
|
B2. Is that brand a WELL-KNOWN, established project \u2014 prominent in crypto, blockchain, NFT, DeFi or Web3 (or otherwise a major, widely-recognized brand)? A scammer only bothers faking a name people trust, so set brandIsWellKnown=true only for a genuinely recognized project; for an obscure or no-name brand set false.
|
|
1053
1053
|
C. Compare the FULL registrable domain + TLD of the domain under test against that official domain \u2014 they match ONLY if identical in BOTH the name AND the TLD. Reusing the brand name with anything added or changed is NOT a match and is NOT the official site.
|
|
@@ -1064,12 +1064,13 @@ Return ONLY this JSON:
|
|
|
1064
1064
|
"brand": string | null, // the brand it resembles, or null
|
|
1065
1065
|
"brandIsWellKnown": boolean, // is that brand a well-known crypto/web3 (or major) project worth faking?
|
|
1066
1066
|
"officialDomain": string | null, // that brand's real official domain (e.g. "relay.link"), or null if unknown
|
|
1067
|
+
"officialUrl": string | null, // that brand's official site URL WITH scheme (e.g. "https://relay.link"), or null if unknown
|
|
1067
1068
|
"exactMatchOfficial": boolean, // is the domain under test EXACTLY the official domain (name AND TLD)?
|
|
1068
1069
|
"affiliatedDomains": string[], // ALL verified official/authorized domains of the brand (canonical + regional); [] if unsure
|
|
1069
1070
|
"hasOwnLegitPresence": boolean, // does THIS exact domain have its own legitimate presence?
|
|
1070
1071
|
"impersonationEvidence": string[], // >=3 specific points if impersonating; [] otherwise
|
|
1071
1072
|
"scamReports": string[] // SOURCED findings (each with a markdown-link source) accusing THIS exact domain; [] if none/unsourced
|
|
1072
|
-
}`,o=await this.askJson(r,{signal:n,maxRetries:3});return{description:this.cleanStr(o?.description)??"",resemblesBrand:o?.resemblesBrand===!0,brand:this.cleanStr(o?.brand),brandIsWellKnown:o?.brandIsWellKnown===!0,officialDomain:this.cleanStr(o?.officialDomain),exactMatchOfficial:o?.exactMatchOfficial===!0,affiliatedDomains:this.cleanStrArray(o?.affiliatedDomains),hasOwnLegitPresence:o?.hasOwnLegitPresence===!0,impersonationEvidence:this.cleanStrArray(o?.impersonationEvidence),scamReports:this.cleanStrArray(o?.scamReports)}}async describeOfficial(e,t){let n=`This website is officially verified as legitimate: ${e}
|
|
1073
|
+
}`,o=await this.askJson(r,{signal:n,maxRetries:3});return{description:this.cleanStr(o?.description)??"",resemblesBrand:o?.resemblesBrand===!0,brand:this.cleanStr(o?.brand),brandIsWellKnown:o?.brandIsWellKnown===!0,officialDomain:this.cleanStr(o?.officialDomain),officialUrl:this.cleanStr(o?.officialUrl),exactMatchOfficial:o?.exactMatchOfficial===!0,affiliatedDomains:this.cleanStrArray(o?.affiliatedDomains),hasOwnLegitPresence:o?.hasOwnLegitPresence===!0,impersonationEvidence:this.cleanStrArray(o?.impersonationEvidence),scamReports:this.cleanStrArray(o?.scamReports)}}async describeOfficial(e,t){let n=`This website is officially verified as legitimate: ${e}
|
|
1073
1074
|
Using web search, describe what this website / platform is and what it does (its purpose, who runs it).
|
|
1074
1075
|
|
|
1075
1076
|
Return ONLY this JSON: { "description": string } // 1-3 concise sentences`,r=await this.askJson(n,{signal:t,maxRetries:3});return this.cleanStr(r?.description)??""}async present(e,t,n,r){let o=this.languageLabel(n),i=`Here is a COMPLETED web-security assessment (facts only \u2014 do not re-investigate):
|
package/dist/index.native.js
CHANGED
|
@@ -437,7 +437,7 @@ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}
|
|
|
437
437
|
`);return a===-1?"":i.stack.slice(a+1)})();try{if(!n.stack)n.stack=o;else if(o){let a=o.indexOf(`
|
|
438
438
|
`),s=a===-1?-1:o.indexOf(`
|
|
439
439
|
`,a+1),l=s===-1?"":o.slice(s+1);String(n.stack).endsWith(l)||(n.stack+=`
|
|
440
|
-
`+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=oo(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&tm.assertOptions(n,{silentJSONParsing:ki.transitional(ki.boolean),forcedJSONParsing:ki.transitional(ki.boolean),clarifyTimeoutError:ki.transitional(ki.boolean),legacyInterceptorReqResOrdering:ki.transitional(ki.boolean)},!1),i!=null&&(F.isFunction(i)?r.paramsSerializer={serialize:i}:tm.assertOptions(i,{encode:ki.function,serialize:ki.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),tm.assertOptions(r,{baseUrl:ki.spelling("baseURL"),withXsrfToken:ki.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&F.merge(o.common,o[r.method]);o&&F.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=fr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||ud;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let u=[];this.interceptors.response.forEach(function(y){u.push(y.fulfilled,y.rejected)});let c,d=0,h;if(!l){let g=[Ub.bind(this),void 0];for(g.unshift(...s),g.push(...u),h=g.length,c=Promise.resolve(r);d<h;)c=c.then(g[d++],g[d++]);return c}h=s.length;let m=r;for(;d<h;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{c=Ub.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=oo(this.defaults,e);let r=em(e.baseURL,e.url,e.allowAbsoluteUrls);return Jh(r,e.params,e.paramsSerializer)}};F.forEach(["delete","get","head","options"],function(e){hd.prototype[e]=function(r,n){return this.request(oo(n||{},{method:e,url:r,data:(n||{}).data}))}});F.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(oo(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}hd.prototype[e]=r(),e!=="query"&&(hd.prototype[e+"Form"]=r(!0))});var rm=hd;p();var zE=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new Oo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},RD=zE;p();function VE(t){return function(r){return t.apply(null,r)}}p();function ZE(t){return F.isObject(t)&&t.isAxiosError===!0}p();var HE={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(HE).forEach(([t,e])=>{HE[e]=t});var ND=HE;function $D(t){let e=new rm(t),r=Zh(rm.prototype.request,e);return F.extend(r,rm.prototype,e,{allOwnKeys:!0}),F.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return $D(oo(t,i))},r}var Sr=$D(dd);Sr.Axios=rm;Sr.CanceledError=Oo;Sr.CancelToken=RD;Sr.isCancel=Xh;Sr.VERSION=fd;Sr.toFormData=ll;Sr.AxiosError=$e;Sr.Cancel=Sr.CanceledError;Sr.all=function(e){return Promise.all(e)};Sr.spread=VE;Sr.isAxiosError=ZE;Sr.mergeConfig=oo;Sr.AxiosHeaders=fr;Sr.formToJSON=t=>Nb(F.isHTMLForm(t)?new FormData(t):t);Sr.getAdapter=Db.getAdapter;Sr.HttpStatusCode=ND;Sr.default=Sr;var Lb=Sr;var{Axios:Zze,AxiosError:Hze,CanceledError:Gze,isCancel:Wze,CancelToken:Kze,VERSION:Jze,all:Yze,Cancel:Xze,isAxiosError:Qze,spread:e6e,toFormData:t6e,AxiosHeaders:r6e,HttpStatusCode:n6e,formToJSON:i6e,getAdapter:o6e,mergeConfig:a6e,create:s6e}=Lb;var MD="0.2.28";var fX=`keyring-agent-core/${MD} (Keyring Chatbot Agent; +https://keyring.app)`,hX=3e4,mX=typeof process<"u"&&process.versions?.node!=null,GE=class{constructor(e={}){f(this,"instance");this.instance=Lb.create({baseURL:e.baseURL,timeout:e.timeout??hX,validateStatus:()=>!0,headers:{Accept:"application/json",...mX?{"User-Agent":e.userAgent??fX}:{},...e.headers}})}async request(e,r,n,i={}){let o=await this.instance.request({...i,method:e,url:r,data:n}),a={};for(let[s,l]of Object.entries(o.headers??{}))l!=null&&(a[s.toLowerCase()]=String(l));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:a}}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},Fe=new GE;function dt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}p();var Du=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function md(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function WE(t){if(t?.aborted)throw new Du}function DD(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var UD={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},gX="https://nft.keyring.app/api/gemini-stable",yX=new Set([408,429,500,502,503,504]),qD=3e4,jb=t=>new Promise(e=>setTimeout(e,t));function Fb(t,e,r){if(r!=null&&r>0)return Math.min(r,qD);let n=Math.min(e*2**(t-1),qD);return n/2+Math.random()*(n/2)}function _X(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var rn=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??gX}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;WE(l);let u=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of u){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let c={contents:u,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(c.systemInstruction=i),r?.length?(c.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(c.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(c.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,h="Unknown error";for(let m=1;m<=a;m++){WE(l);let g;try{g=await Fe.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(md(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await jb(Fb(m,s));continue}if(!g.ok){let C=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(h=`Gemini proxy error ${g.status}: ${C}`,!yX.has(g.status))throw new Error(h);if(m>=a)break;let R=_X(g.headers["retry-after"]??null);await jb(Fb(m,s,R));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await jb(Fb(m,s));continue}let y=g.data,_=y.candidates?.[0];if(!_)return{text:"",toolCalls:[]};let b="",w=[],T=_.content?.parts;if(!Array.isArray(T)||T.length===0){let C=_.finishReason;if(!(C==="SAFETY"||C==="RECITATION")&&m<a){h=`Gemini returned an empty turn (finishReason=${C??"none"})`,await jb(Fb(m,s));continue}return{text:"",toolCalls:[]}}for(let C of T)C.text&&(b+=C.text),C.functionCall&&w.push({toolName:C.functionCall.name,args:C.functionCall.args??{},callId:C.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let E=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:b,toolCalls:w,usage:E}}throw new Error(h)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],u=s.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!u&&!c?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],u=o[o.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
|
|
440
|
+
`+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=oo(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&tm.assertOptions(n,{silentJSONParsing:ki.transitional(ki.boolean),forcedJSONParsing:ki.transitional(ki.boolean),clarifyTimeoutError:ki.transitional(ki.boolean),legacyInterceptorReqResOrdering:ki.transitional(ki.boolean)},!1),i!=null&&(F.isFunction(i)?r.paramsSerializer={serialize:i}:tm.assertOptions(i,{encode:ki.function,serialize:ki.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),tm.assertOptions(r,{baseUrl:ki.spelling("baseURL"),withXsrfToken:ki.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&F.merge(o.common,o[r.method]);o&&F.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=fr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||ud;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let u=[];this.interceptors.response.forEach(function(y){u.push(y.fulfilled,y.rejected)});let c,d=0,h;if(!l){let g=[Ub.bind(this),void 0];for(g.unshift(...s),g.push(...u),h=g.length,c=Promise.resolve(r);d<h;)c=c.then(g[d++],g[d++]);return c}h=s.length;let m=r;for(;d<h;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{c=Ub.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=oo(this.defaults,e);let r=em(e.baseURL,e.url,e.allowAbsoluteUrls);return Jh(r,e.params,e.paramsSerializer)}};F.forEach(["delete","get","head","options"],function(e){hd.prototype[e]=function(r,n){return this.request(oo(n||{},{method:e,url:r,data:(n||{}).data}))}});F.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(oo(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}hd.prototype[e]=r(),e!=="query"&&(hd.prototype[e+"Form"]=r(!0))});var rm=hd;p();var zE=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new Oo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},RD=zE;p();function VE(t){return function(r){return t.apply(null,r)}}p();function ZE(t){return F.isObject(t)&&t.isAxiosError===!0}p();var HE={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(HE).forEach(([t,e])=>{HE[e]=t});var ND=HE;function $D(t){let e=new rm(t),r=Zh(rm.prototype.request,e);return F.extend(r,rm.prototype,e,{allOwnKeys:!0}),F.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return $D(oo(t,i))},r}var Sr=$D(dd);Sr.Axios=rm;Sr.CanceledError=Oo;Sr.CancelToken=RD;Sr.isCancel=Xh;Sr.VERSION=fd;Sr.toFormData=ll;Sr.AxiosError=$e;Sr.Cancel=Sr.CanceledError;Sr.all=function(e){return Promise.all(e)};Sr.spread=VE;Sr.isAxiosError=ZE;Sr.mergeConfig=oo;Sr.AxiosHeaders=fr;Sr.formToJSON=t=>Nb(F.isHTMLForm(t)?new FormData(t):t);Sr.getAdapter=Db.getAdapter;Sr.HttpStatusCode=ND;Sr.default=Sr;var Lb=Sr;var{Axios:Zze,AxiosError:Hze,CanceledError:Gze,isCancel:Wze,CancelToken:Kze,VERSION:Jze,all:Yze,Cancel:Xze,isAxiosError:Qze,spread:e6e,toFormData:t6e,AxiosHeaders:r6e,HttpStatusCode:n6e,formToJSON:i6e,getAdapter:o6e,mergeConfig:a6e,create:s6e}=Lb;var MD="0.2.29";var fX=`keyring-agent-core/${MD} (Keyring Chatbot Agent; +https://keyring.app)`,hX=3e4,mX=typeof process<"u"&&process.versions?.node!=null,GE=class{constructor(e={}){f(this,"instance");this.instance=Lb.create({baseURL:e.baseURL,timeout:e.timeout??hX,validateStatus:()=>!0,headers:{Accept:"application/json",...mX?{"User-Agent":e.userAgent??fX}:{},...e.headers}})}async request(e,r,n,i={}){let o=await this.instance.request({...i,method:e,url:r,data:n}),a={};for(let[s,l]of Object.entries(o.headers??{}))l!=null&&(a[s.toLowerCase()]=String(l));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:a}}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},Fe=new GE;function dt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}p();var Du=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function md(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function WE(t){if(t?.aborted)throw new Du}function DD(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var UD={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},gX="https://nft.keyring.app/api/gemini-stable",yX=new Set([408,429,500,502,503,504]),qD=3e4,jb=t=>new Promise(e=>setTimeout(e,t));function Fb(t,e,r){if(r!=null&&r>0)return Math.min(r,qD);let n=Math.min(e*2**(t-1),qD);return n/2+Math.random()*(n/2)}function _X(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var rn=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??gX}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;WE(l);let u=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of u){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let c={contents:u,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(c.systemInstruction=i),r?.length?(c.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(c.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(c.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,h="Unknown error";for(let m=1;m<=a;m++){WE(l);let g;try{g=await Fe.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(md(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await jb(Fb(m,s));continue}if(!g.ok){let C=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(h=`Gemini proxy error ${g.status}: ${C}`,!yX.has(g.status))throw new Error(h);if(m>=a)break;let R=_X(g.headers["retry-after"]??null);await jb(Fb(m,s,R));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await jb(Fb(m,s));continue}let y=g.data,_=y.candidates?.[0];if(!_)return{text:"",toolCalls:[]};let b="",w=[],T=_.content?.parts;if(!Array.isArray(T)||T.length===0){let C=_.finishReason;if(!(C==="SAFETY"||C==="RECITATION")&&m<a){h=`Gemini returned an empty turn (finishReason=${C??"none"})`,await jb(Fb(m,s));continue}return{text:"",toolCalls:[]}}for(let C of T)C.text&&(b+=C.text),C.functionCall&&w.push({toolName:C.functionCall.name,args:C.functionCall.args??{},callId:C.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let E=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:b,toolCalls:w,usage:E}}throw new Error(h)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],u=s.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!u&&!c?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],u=o[o.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
|
|
441
441
|
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:UD[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:UD[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&i.push(o.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};p();var gd=class{constructor(){f(this,"tools",new Map)}register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await i.execute(r,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};p();p();p();p();p();var yd=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],bX=new Set(yd),ul=[...yd],LD=new Set(ul),Ro="0x1",Uu="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function vX(t){return t.map(e=>bd[e]??e).join(", ")}function Bb(t){let e=new Set;if(t)for(let n of t){let i=zb(n);i&&e.add(i)}let r=yd.filter(n=>!e.has(n));ul=r.length>0?[...r]:[...yd],LD=new Set(ul),Ro=ul.includes("0x1")?"0x1":ul[0],Uu=vX(ul)}var wX={"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 Ln(t){let e=zb(t);return e&&LD.has(e)?e:null}function zb(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=wX[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&bX.has(n)?n:null}function Vb(t){return Ln(t)!==null}function Pi(){return[...ul]}var _d=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Uu}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},cl=t=>typeof t=="string"&&t.trim()!=="";function jn(t,e){if(cl(t)){let r=Ln(t);if(r)return r;throw new _d(t.trim())}if(cl(e?.chain)){let r=Ln(e.chain);if(r)return r;throw new _d(e.chain.trim())}return null}function Zb(t,e){return Ln(t)??Ln(e?.chain)??void 0}var bd={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function Je(t){let e=zb(t);return e&&bd[e]?bd[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var SX={"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 jD(t,e){let r=zb(t),n=r?SX[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var TX={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function FD(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?TX[e]??null:null}var kX={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function BD(t){let e=Ln(t);return e?kX[e]??null:null}function vd(t,e){if(!cl(t))return null;let r=Ln(t),n=Ln(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:bd[r]??r,connectedLabel:bd[n]??n}}function zD(t){let e=typeof t=="string"?t.trim():"";return ul.map(r=>{let n=bd[r]??r;return{label:n,prompt:e?`${e} (${n})`:n}})}function wd(t,e){return{actionButtons:zD(e),_instructions:`The user wants to ${t} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var Ir=class extends Error{constructor(r){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");f(this,"code","needs_chain_selection");f(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=zD(r)}},nm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");f(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function Tr(t,e){if(cl(t))return t.trim();if(cl(e?.walletAddress))return e.walletAddress.trim();throw new nm}function vt(t,e){if(cl(t)){let r=Ln(t);if(r)return r;throw new _d(t.trim())}if(cl(e?.chain)){let r=Ln(e.chain);if(r)return r;throw new _d(e.chain.trim())}if(cl(e?.walletAddress))throw new Ir(typeof e?.query=="string"?e.query:void 0);return Ro}var le=class{constructor(){f(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=PX(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{}}}catch(o){return o instanceof Ir?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-i,actionButtons:o.buttons}:o instanceof nm?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-i}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-i}}}};function PX(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons;if(!Array.isArray(r)||r.length===0)return{data:t};let{actionButtons:n,...i}=e;return{data:i,actionButtons:r}}p();p();var VD=K_(Gb());function zt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function EX(t){return new Uint8Array(VD.keccak256.arrayBuffer(t))}function im(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function ZD(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function HD(t){return new TextEncoder().encode(t)}function qu(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function AX(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function CX(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function GD(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return im(e)}function om(t){return GD(BigInt(t))}function WD(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function KD(t){let e=WD(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(KD).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function xX(t){let e=(t.inputs??[]).map(KD).join(",");return`${t.name??""}(${e})`}function KE(t,e){let r=RX(t.type);if(r){let[i,o]=r;return IX({...t,type:o},e,i)}if(t.type==="tuple")return OX(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:AX(im(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=WD(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:om(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:GD(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?im(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:CX(o)}}if(n==="bytes"){let i=typeof e=="string"?im(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:qu(om(i.length),a)}}if(n==="string"){let i=typeof e=="string"?HD(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:qu(om(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function JE(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(om(e+i)),n.push(a),i+=a.length):r.push(a);return qu(...r,...n)}function IX(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=KE(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=JE(o);if(n){let s=om(o.length);return{dynamic:!0,encoded:o.length>0?qu(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:qu(...o.map(a=>a.encoded))}}function OX(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=KE(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?JE(i):qu(...i.map(o=>o.encoded))}}function RX(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function NX(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>KE(i,e[o])),n=JE(r);return ZD(n)}function Sd({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=xX(n),o=EX(HD(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):im(NX(a,r).slice(2));return ZD(qu(o,s))}p();var $X="https://wallet-api.pantograph.app",MX="0x0000000000000000000000000000000000000000",XD={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},QD={"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 am(t){return XD[t.toLowerCase()]||t}function JD(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function YE(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,o=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function wn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function YD(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=wn(t.price_change_percentage_24h)??wn(t.priceChange24h)??wn(t.usd_price_24hr_percent_change)??wn(t.price_change_24h)??wn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:wn(t.price)??wn(t.usd_price),marketCap:wn(t.market_cap)??wn(t.marketCap),totalVolume:{"24h":wn(t.total_volume)??wn(t.volume24h)},pricePercentChange:{"24h":i}}}var Sn=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??$X).replace(/\/+$/,"")}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=am(r),i=e.map(c=>c.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(i)}`,a=await Fe.get(o);if(!a.ok)return;let s=a.data,l=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],u=new Map;for(let c of l)c.address&&u.set(c.address.toLowerCase(),{price:c.price!=null?parseFloat(String(c.price)):NaN,icon_image:c.icon_image});for(let c=0;c<e.length;c++){let d=u.get(e[c].token_address.toLowerCase());d&&(d.icon_image&&(e[c].logo=d.icon_image,e[c].thumbnail=d.icon_image),isNaN(d.price)||(e[c].usd_price=d.price,e[c].usd_value=parseFloat(e[c].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,r){try{let n=am(r),i=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await Fe.get(i);if(!o.ok)return null;let a=o.data,s=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],l=e.toLowerCase()===MX,u=s.find(c=>c.address?.toLowerCase()===e.toLowerCase()||l&&c.address===""||c.token_address?.toLowerCase()===e.toLowerCase()||l&&c.token_address==="");return u?YE(u):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=am(r),o=`${this.baseUrl}/keyrings/tokens/${i}/v2?addresses=${encodeURIComponent(e.join(","))}`,a=await Fe.get(o);if(!a.ok)return n;let s=a.data,l=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],u=new Set(e.map(c=>c.toLowerCase()));for(let c of l){let d=c.address?.toLowerCase()||c.token_address?.toLowerCase()||(c.address===""?"":null);d&&u.has(d)&&(n[d]=YE(c))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ro,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=JD({chainId:o,key:r}),s=`${this.baseUrl}/token-list?${a}`,l=await Fe.get(s);if(!l.ok)throw new Error(dt(l));let u=l.data,c=[];return u?.data?c=Array.isArray(u.data)?u.data:Object.values(u.data).flat():typeof u=="object"&&!Array.isArray(u)&&(c=Object.values(u).flat()),{success:!0,data:c.map(YE)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ro,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=QD[r.toLowerCase()]??[],a=i!=null?i+o.length:n+o.length,[s,l]=await Promise.allSettled([this.fetchTopGainers(r,a),o.length>0?this.getTokensMetadata(o,r):Promise.resolve({})]),u=s.status==="fulfilled"?s.value:[],c=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>YD(y,r)):[],d=new Set,h=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...h,...m].slice(0,i):[...h,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=wn(a.market_cap)??wn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":wn(a.total_volume)??wn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=am(e),o=JD({duration:n,limit:r}),a=`${this.baseUrl}/token-list/top-gainers/${i}${o?`?${o}`:""}`,s=[];for(let l=0;l<5;l++){let u=await Fe.get(a);if(!u.ok)throw new Error(dt(u));let c=u.data;if(s=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>YD(l,e))}async getTopGainers(e){let r=e?.chain||Ro,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var DX="https://nft.keyring.app",UX="https://nft.keyring.app",qX=.01,tt=5,ir=1e3,LX="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",jX="0x0000000000000000000000000000000000000000",rt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function hr(t){return t||Ro}function or(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ar(t){return new Promise(e=>setTimeout(e,t))}function FX(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function XE(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var pt=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??DX).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??UX).replace(/\/+$/,""),this.pantograph=new Sn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=hr(n),l="Unknown error";for(let u=1;u<=tt;u++)try{let c={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(c.token_addresses=i);let d=[],h=null;do{h&&(c.cursor=h);let g=or(c),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await Fe.get(y);if(!_.ok)throw new rt(_.status,dt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),h=w?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===LX?jX:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=qX)),{success:!0,data:m}}catch(c){if(l=c instanceof Error?c.message:"Unknown error",c instanceof rt&&c.status===400)break;u<tt&&await ar(ir)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=hr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=tt;s++)try{let[l,u]=await Promise.allSettled([Fe.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${or({chain:i,addresses:[r]})}`),Fe.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${or({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;c=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!c){o="Token metadata not found",s<tt&&await ar(ir);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let h=u.value.data;d=h?.data??h}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:o=!0,cursor:a,tokenAddresses:s,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=hr(n),d="Unknown error";for(let h=1;h<=tt;h++)try{let m={chain:c,format:u,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(m.cursor=a),l&&(m.include_prices=!0),s&&s.length>0&&(m.token_addresses=s);let g=or(m),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${g}`,_=await Fe.get(y);if(!_.ok)throw new rt(_.status,dt(_));let b=_.data;return{success:!0,data:b?.data??b}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof rt&&m.status===400)break;h<tt&&await ar(ir)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!zt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=hr(i),c="Unknown error";for(let d=1;d<=tt;d++)try{let h={chain:u,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=or(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await Fe.get(g);if(!y.ok)throw new rt(y.status,dt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(c=h instanceof Error?h.message:"Unknown error",h instanceof rt&&h.status===400)break;d<tt&&await ar(ir)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=hr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=hr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=tt;_++)try{let b={chain:m,limit:g,order:c};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),u&&(b.cursor=u),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let w=or(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await Fe.get(T);if(!E.ok)throw new rt(E.status,dt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof rt&&b.status===400)break;_<tt&&await ar(ir)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=hr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=tt;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),u!=null&&(_.to_block=u),c&&(_.cursor=c),i?.length&&(_.contract_addresses=i);let b=or(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await Fe.get(w);if(!T.ok)throw new rt(T.status,dt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof rt&&_.status===400)break;y<tt&&await ar(ir)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=hr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=tt;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),u!=null&&(w.to_block=u),c&&(w.cursor=c),i?.length&&(w.contract_addresses=i),h!=null&&(w.include_prices=h);let T=or(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await Fe.get(E);if(!C.ok)throw new rt(C.status,dt(C));let R=C.data;return{success:!0,data:R?.data??R}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof rt&&w.status===400)break;b<tt&&await ar(ir)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!zt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=hr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=hr(n),a="Unknown error";for(let s=1;s<=tt;s++)try{let l={chain:o};i&&(l.days=i);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data;return{success:!0,data:h?.data??h}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=hr(n),s="Unknown error";for(let l=1;l<=tt;l++)try{let u={chain:a};i&&(u.days=i),o&&o.length>0&&(u.token_addresses=o.slice(0,25));let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,h=await Fe.get(d);if(!h.ok)throw new rt(h.status,dt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof rt&&u.status===400)break;l<tt&&await ar(ir)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=hr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=hr(n),s="Unknown error";for(let l=1;l<=tt;l++)try{let u={chain:a};i!=null&&(u.limit=i),o&&(u.cursor=o);let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,h=await Fe.get(d);if(!h.ok)throw new rt(h.status,dt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof rt&&u.status===400)break;l<tt&&await ar(ir)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=hr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=hr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data,d=c?.data??c;return{success:!0,data:FX(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=hr(i),a="Unknown error";for(let s=1;s<=tt;s++)try{let l=or({chains:o}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await Fe.get(u);if(!c.ok)throw new rt(c.status,dt(c));let m=c.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!zt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=hr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!zt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=hr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=tt;o++)try{let a={};r&&(a.chain=hr(r)),n!=null&&(a.limit=n);let s=or(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data,d=c?.data??c;return{success:!0,data:XE(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof rt&&a.status===400)break;o<tt&&await ar(ir)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=tt;s++)try{let l={};r&&(l.chain=hr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data,m=h?.data??h;return{success:!0,data:XE(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=tt;s++)try{let l={};r&&(l.chain=hr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data,m=h?.data??h;return{success:!0,data:XE(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Td=class extends le{constructor(r){super();f(this,"name","get-token-info");f(this,"description",'Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea');f(this,"category","blockchain-data");f(this,"parameters",[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. 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}]);f(this,"service");f(this,"llm");this.service=new pt(r),this.llm=new rn({})}async run(r,n){let i=r.keyword||"",o=vt(r.chain,n),a=r.prompt||"",s=r.buy_button_label||"",l=r.buy_prompt_template||"",u=n?.walletAddress||void 0;return i?await this.searchToken(i,o,a,s,l,u):{error:"Missing required parameter: keyword"}}async execute(r,n){let i=await super.execute(r,n),o=i.data;return i.success&&o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(i.actionButtons=o.actionButtons),i}async searchToken(r,n,i,o,a,s){let l=[s?`User's connected wallet address: ${s}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
|
|
442
442
|
`),[u,c,d]=await Promise.all([this.service.searchTokensByKey({key:r,chain:n}),s?this.findTokenInWallet(s,n,r):Promise.resolve(null),i?this.askGeminiWithSearch(i,l):Promise.resolve(null)]),h=u.success&&u.data?Array.isArray(u.data)?u.data:[]:[],m=r.toLowerCase(),g=C=>C.symbol?.toLowerCase()===m||C.token_address?.toLowerCase()===m,y=[...h].sort((C,R)=>(g(C)?0:1)-(g(R)?0:1)),_=null,b=y[0];if(b?.token_address){let C=await this.service.getTokenMetadata({address:b.token_address,chain:n});C.success&&C.data&&(_=C.data)}!_&&b&&(_={...b});let w=_?.symbol?.trim(),T=w?[{label:this.fillTemplate(o,w,"Buy {token}"),prompt:this.fillTemplate(a,w,"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:n,userHoldsToken:!!c,walletBalance:c,token:_,...h.length>1?{searchResults:y.slice(0,10)}:{},research:d,...T.length>0?{actionButtons:T}:{}}}fillTemplate(r,n,i){return(r&&r.includes("{token}")?r:i).replace(/\{token\}/g,n).replace(/\s+/g," ").trim()}async askGeminiWithSearch(r,n){let i=Date.now();try{return(await this.llm.chat([...n?[{role:"system",content:n,timestamp:i}]:[],{role:"user",content:r,timestamp:i}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(r,n,i){if(!i)return null;let o=await this.service.getWalletTokenBalances({address:r,chain:n,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!o.success||!o.data?.result)return null;let a=i.toLowerCase(),s=o.data.result.find(l=>l.token_address.toLowerCase()===a||l.symbol?.toLowerCase()===a||l.name?.toLowerCase().includes(a));return s||null}};p();var kd=class extends le{constructor(r){super();f(this,"name","get-token-holders");f(this,"description",'Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. ');f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Je(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenHolders({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Pd=class extends le{constructor(r){super();f(this,"name","get-token-analytics");f(this,"description",`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Je(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenAnalytics({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Ed=class extends le{constructor(r){super();f(this,"name","get-token-score");f(this,"description",`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let m=await this.resolveContractAddress(a,i,o);if(!m)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Je(i):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,l=m.symbol,u=m.name}let c=await this.service.getTokenScore({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},h=d.metrics??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:h.usdPrice??null,liquidityUsd:h.liquidityUsd??null,volumeUsd:h.volumeUsd??null,transactions:h.transactions??null,supply:h.supply??null}}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Ad=class extends le{constructor(r){super();f(this,"name","get-trending-tokens");f(this,"description",'List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, and more.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. 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}]);f(this,"service");this.service=new Sn({baseUrl:r?.pantographUrl})}async run(r,n){let i=Zb(r.chain,n),o=r.buy_button_label||"",a=r.buy_prompt_template||"",s=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.floor(r.limit):void 0,l=await this.service.getTrendingTokens({chain:i,limit:s});if(!l.success)return{error:l.error||"Failed to fetch trending tokens"};let u=l.data??[],c=new Set,d=[];for(let h of u){let m=h.symbol?.trim();!m||c.has(m.toLowerCase())||(c.add(m.toLowerCase()),d.push({label:this.fillTemplate(o,m,"Buy {token}"),prompt:this.fillTemplate(a,m,"buy {token}")}))}return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
|
|
443
443
|
<rank>. <name> (<symbol>)
|
|
@@ -1481,12 +1481,12 @@ RULES:
|
|
|
1481
1481
|
- Suggestions must be diverse \u2014 do not repeat the same intent in different words.
|
|
1482
1482
|
- Use the same language as the user.
|
|
1483
1483
|
- Good example (pool): ["Add liquidity to USDC/WETH 0.05%", "Estimate yield for $1000 here", "Compare with 0.3% fee tier"]
|
|
1484
|
-
- Bad example: ["What is a pool?", "How do pools work?", "Tell me more"] (generic, no action, no specifics)`,timestamp:0}])).text.match(/\[[\s\S]*\]/);return s?JSON.parse(s[0]).filter(u=>typeof u=="string"&&u.length>0).slice(0,3):[]}catch{return[]}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}getLastSuggestions(){let e=this.getDisplayHistory();for(let r=e.length-1;r>=0;r--){let n=e[r];if(n.role==="assistant")return n.suggestedPrompts??[]}return[]}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),r=6,n=0,i=e.length;for(let h=e.length-1;h>=0;h--)if(e[h].role==="user"&&(n++,n>=r)){i=h;break}let o=e.slice(i),a=FU(o,o.length),s=e.length-a.length,l=qo(e.slice(0,s)),u=this.history.getSummary(),c=[];u&&c.push({role:"user",content:`[Previous context summary]: ${u}`,timestamp:0}),c.push(...l);let d=await this.summarizer.summarize(c);this.history.compactWith(d,a)}persistToolMessages(e){for(let r of e)r.toolMessages.length>0&&(this.history.addMany(r.toolMessages),this.history.add({role:"assistant",content:r.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${r.toolMessages.length} tool message(s) + finalAnswer from ${r.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};p();var RFe='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',wP=class{constructor(e={}){f(this,"llm");f(this,"debug");this.llm=e.provider??new rn({temperature:.8,...e.llm}),this.debug=e.debug??!1}async chat(e){let r=(e?.url??"").trim();if(!r)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(r),i=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let d=await this.describeOfficial(r,o),{answer:h}=await this.present(n,{isPhishing:!1,description:d,reasons:[]},i,o);return{answer:h,extraData:{currentSite:
|
|
1484
|
+
- Bad example: ["What is a pool?", "How do pools work?", "Tell me more"] (generic, no action, no specifics)`,timestamp:0}])).text.match(/\[[\s\S]*\]/);return s?JSON.parse(s[0]).filter(u=>typeof u=="string"&&u.length>0).slice(0,3):[]}catch{return[]}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}getLastSuggestions(){let e=this.getDisplayHistory();for(let r=e.length-1;r>=0;r--){let n=e[r];if(n.role==="assistant")return n.suggestedPrompts??[]}return[]}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),r=6,n=0,i=e.length;for(let h=e.length-1;h>=0;h--)if(e[h].role==="user"&&(n++,n>=r)){i=h;break}let o=e.slice(i),a=FU(o,o.length),s=e.length-a.length,l=qo(e.slice(0,s)),u=this.history.getSummary(),c=[];u&&c.push({role:"user",content:`[Previous context summary]: ${u}`,timestamp:0}),c.push(...l);let d=await this.summarizer.summarize(c);this.history.compactWith(d,a)}persistToolMessages(e){for(let r of e)r.toolMessages.length>0&&(this.history.addMany(r.toolMessages),this.history.add({role:"assistant",content:r.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${r.toolMessages.length} tool message(s) + finalAnswer from ${r.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};p();var RFe='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',wP=class{constructor(e={}){f(this,"llm");f(this,"debug");this.llm=e.provider??new rn({temperature:.8,...e.llm}),this.debug=e.debug??!1}async chat(e){let r=(e?.url??"").trim();if(!r)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(r),i=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let d=await this.describeOfficial(r,o),{answer:h}=await this.present(n,{isPhishing:!1,description:d,reasons:[]},i,o);return{answer:h,extraData:{currentSite:r,isPhishing:!1}}}let a=await this.investigate(r,n,o),s=this.buildVerdict(n,a);this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",n),console.log("[WebsiteTrustKeyringAgent] investigation:",a),console.log("[WebsiteTrustKeyringAgent] verdict:",s));let{answer:l,reasons:u}=await this.present(n,{isPhishing:s.isPhishing,description:a.description,copiedSite:s.copiedSite,reasons:s.reasons},i,o),c={currentSite:r,isPhishing:s.isPhishing};return s.copiedSite&&(c.copiedSite=s.copiedSite),s.isPhishing&&u.length>0&&(c.reasons=u),{answer:l,extraData:c}}catch(a){throw new Error(`WebsiteTrustKeyringAgent.chat failed: ${a instanceof Error?a.message:String(a)}`,{cause:a})}}buildVerdict(e,r){let n=[r.officialDomain,...r.affiliatedDomains].filter(h=>!!h),i=n.length>0?n.some(h=>this.isSameRegistrableDomain(e,h)):r.exactMatchOfficial,a=(r.resemblesBrand||this.carriesBrandName(e,r.officialDomain,r.brand))&&!i&&r.brandIsWellKnown&&(n.length>0||!r.hasOwnLegitPresence),l=!(i||r.hasOwnLegitPresence&&!a)&&r.scamReports.length>0,u=a||l;if(!u)return{isPhishing:!1,reasons:[]};let c=[];if(a){let h=r.officialDomain?this.describeLookAlike(e,r.officialDomain):void 0;h&&c.push(h),r.impersonationEvidence.length>0?c.push(...r.impersonationEvidence):h||c.push(r.officialDomain?`This address (${e}) is not the official ${r.brand??"brand"} domain \u2014 the real one is ${r.officialDomain}; the look-alike is easy to miss at a glance.`:`This domain (${e}) imitates ${r.brand??"a known brand"} but is not its official site and has no legitimate presence of its own.`)}l&&c.push(...r.scamReports);let d=a?r.officialUrl??r.officialDomain??r.brand:void 0;return{isPhishing:u,copiedSite:d,reasons:this.dedupe(c)}}async investigate(e,r,n){let i=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${r}
|
|
1485
1485
|
URL: ${e}
|
|
1486
1486
|
|
|
1487
1487
|
Investigate, using web search, whether this EXACT domain is a legitimate official site or a phishing / look-alike / scam site. Work through:
|
|
1488
1488
|
A. Describe what this site is or claims to be for the user: the product/service it offers, what it does, and who appears to operate it. This is the main information the user wants about the site \u2014 be concrete.
|
|
1489
|
-
B. Does the domain carry or RESEMBLE a recognizable brand / product / service \u2014 exactly, or via a typo, an extra/missing/swapped letter, a homoglyph, an ADDED WORD or hyphen (e.g. brand+"rpc"/"wallet"/"app"/"pro"/"support"/"finance"), or the brand placed on a different TLD or in a subdomain/path? Treat "the official name with extra text bolted on" as RESEMBLING the brand \u2014 set resemblesBrand=true. If it references ANY identifiable brand/product, you MUST search for and return that brand's OFFICIAL canonical domain in \`officialDomain\` (do not leave it null when the brand is identifiable). A "did you mean" correction to the REAL domain helps you learn the official domain but does NOT make the domain under test legitimate.
|
|
1489
|
+
B. Does the domain carry or RESEMBLE a recognizable brand / product / service \u2014 exactly, or via a typo, an extra/missing/swapped letter, a homoglyph, an ADDED WORD or hyphen (e.g. brand+"rpc"/"wallet"/"app"/"pro"/"support"/"finance"), or the brand placed on a different TLD or in a subdomain/path? Treat "the official name with extra text bolted on" as RESEMBLING the brand \u2014 set resemblesBrand=true. If it references ANY identifiable brand/product, you MUST search for and return that brand's OFFICIAL canonical domain in \`officialDomain\` (do not leave it null when the brand is identifiable). Also return that brand's full official site URL \u2014 including the real scheme (https:// or http://) you confirm via search \u2014 in \`officialUrl\`. A "did you mean" correction to the REAL domain helps you learn the official domain but does NOT make the domain under test legitimate.
|
|
1490
1490
|
A name within 1-2 letters of a well-known domain (missing / doubled / swapped letter, e.g. "opensee" for "opensea", "binanse" for "binance") is a TYPOSQUAT: set resemblesBrand=true, name the intended brand, and return its official domain. Identifying the brand it MIMICS is REQUIRED; it never makes the typo legitimate.
|
|
1491
1491
|
B2. Is that brand a WELL-KNOWN, established project \u2014 prominent in crypto, blockchain, NFT, DeFi or Web3 (or otherwise a major, widely-recognized brand)? A scammer only bothers faking a name people trust, so set brandIsWellKnown=true only for a genuinely recognized project; for an obscure or no-name brand set false.
|
|
1492
1492
|
C. Compare the FULL registrable domain + TLD of the domain under test against that official domain \u2014 they match ONLY if identical in BOTH the name AND the TLD. Reusing the brand name with anything added or changed is NOT a match and is NOT the official site.
|
|
@@ -1503,12 +1503,13 @@ Return ONLY this JSON:
|
|
|
1503
1503
|
"brand": string | null, // the brand it resembles, or null
|
|
1504
1504
|
"brandIsWellKnown": boolean, // is that brand a well-known crypto/web3 (or major) project worth faking?
|
|
1505
1505
|
"officialDomain": string | null, // that brand's real official domain (e.g. "relay.link"), or null if unknown
|
|
1506
|
+
"officialUrl": string | null, // that brand's official site URL WITH scheme (e.g. "https://relay.link"), or null if unknown
|
|
1506
1507
|
"exactMatchOfficial": boolean, // is the domain under test EXACTLY the official domain (name AND TLD)?
|
|
1507
1508
|
"affiliatedDomains": string[], // ALL verified official/authorized domains of the brand (canonical + regional); [] if unsure
|
|
1508
1509
|
"hasOwnLegitPresence": boolean, // does THIS exact domain have its own legitimate presence?
|
|
1509
1510
|
"impersonationEvidence": string[], // >=3 specific points if impersonating; [] otherwise
|
|
1510
1511
|
"scamReports": string[] // SOURCED findings (each with a markdown-link source) accusing THIS exact domain; [] if none/unsourced
|
|
1511
|
-
}`,o=await this.askJson(i,{signal:n,maxRetries:3});return{description:this.cleanStr(o?.description)??"",resemblesBrand:o?.resemblesBrand===!0,brand:this.cleanStr(o?.brand),brandIsWellKnown:o?.brandIsWellKnown===!0,officialDomain:this.cleanStr(o?.officialDomain),exactMatchOfficial:o?.exactMatchOfficial===!0,affiliatedDomains:this.cleanStrArray(o?.affiliatedDomains),hasOwnLegitPresence:o?.hasOwnLegitPresence===!0,impersonationEvidence:this.cleanStrArray(o?.impersonationEvidence),scamReports:this.cleanStrArray(o?.scamReports)}}async describeOfficial(e,r){let n=`This website is officially verified as legitimate: ${e}
|
|
1512
|
+
}`,o=await this.askJson(i,{signal:n,maxRetries:3});return{description:this.cleanStr(o?.description)??"",resemblesBrand:o?.resemblesBrand===!0,brand:this.cleanStr(o?.brand),brandIsWellKnown:o?.brandIsWellKnown===!0,officialDomain:this.cleanStr(o?.officialDomain),officialUrl:this.cleanStr(o?.officialUrl),exactMatchOfficial:o?.exactMatchOfficial===!0,affiliatedDomains:this.cleanStrArray(o?.affiliatedDomains),hasOwnLegitPresence:o?.hasOwnLegitPresence===!0,impersonationEvidence:this.cleanStrArray(o?.impersonationEvidence),scamReports:this.cleanStrArray(o?.scamReports)}}async describeOfficial(e,r){let n=`This website is officially verified as legitimate: ${e}
|
|
1512
1513
|
Using web search, describe what this website / platform is and what it does (its purpose, who runs it).
|
|
1513
1514
|
|
|
1514
1515
|
Return ONLY this JSON: { "description": string } // 1-3 concise sentences`,i=await this.askJson(n,{signal:r,maxRetries:3});return this.cleanStr(i?.description)??""}async present(e,r,n,i){let o=this.languageLabel(n),s=`Here is a COMPLETED web-security assessment (facts only \u2014 do not re-investigate):
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keyring-agent-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.29",
|
|
4
4
|
"description": "Core AI chat agent with multi-agent architecture, ReAct pattern, and modular tool system powered by Gemini",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"react-native": "dist/index.native.js",
|