keyring-agent-core 0.2.41 → 0.2.42

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 CHANGED
@@ -2224,6 +2224,11 @@ declare class WebsiteTrustKeyringAgent {
2224
2224
  * calls where grounding only drags the reply toward the source language.
2225
2225
  * - `maxRetries` lets search-grounded calls survive the occasional empty turn
2226
2226
  * (a single attempt used to blank out the whole analysis).
2227
+ * - `maxOutputTokens` caps the reply per call. Each of these turns is a small,
2228
+ * schema-bound JSON (a handful of fields / 3-5 short array items), so a cap
2229
+ * sized just above the real output keeps latency from the odd rambling turn
2230
+ * without ever truncating a valid reply. Omit to fall back to the provider
2231
+ * default (4096).
2227
2232
  */
2228
2233
  private askJson;
2229
2234
  /**
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ws=Object.create;var no=Object.defineProperty;var Hs=Object.getOwnPropertyDescriptor;var Gs=Object.getOwnPropertyNames;var Ys=Object.getPrototypeOf,Ks=Object.prototype.hasOwnProperty;var js=(a,e)=>{for(var t in e)no(a,t,{get:e[t],enumerable:!0})},xr=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gs(e))!Ks.call(a,r)&&r!==t&&no(a,r,{get:()=>e[r],enumerable:!(n=Hs(e,r))||n.enumerable});return a};var zs=(a,e,t)=>(t=a!=null?Ws(Ys(a)):{},xr(e||!a||!a.__esModule?no(t,"default",{value:a,enumerable:!0}):t,a)),Xs=a=>xr(no({},"__esModule",{value:!0}),a);var zl={};js(zl,{AI_AGENT_TOOL_NAMES:()=>Uo,AbortError:()=>He,AgentCore:()=>Bo,ApproveTokenTool:()=>wn,BaseNftAiTool:()=>Ie,BaseNftMessageTool:()=>Lt,BaseSwapService:()=>Xe,BaseTool:()=>v,BaseWalletActionTool:()=>Se,BuyTokenTool:()=>An,ChatHistory:()=>xn,DEFAULT_CHAIN:()=>be,DEFAULT_PROVIDER:()=>Vn,DEFAULT_RPC_BY_CHAIN:()=>Te,DebridgeAdapter:()=>jt,EstimatePoolYieldTool:()=>rn,GeminiProvider:()=>z,GeminiSearchAiTool:()=>$t,HEX_TO_PANTOGRAPH:()=>zr,KnowledgeBase:()=>_n,ManageLiquidityRedirectTool:()=>an,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>No,NFC_AMAZON_DEFAULT_DOMAIN:()=>nr,NFC_AMAZON_DOMAINS:()=>tr,NFTContractInfoTool:()=>Ot,NFTMetadataTool:()=>Mt,NFT_AGENT_TOOL_NAMES:()=>Ro,NfcBuyTool:()=>Ft,NfcInfoTool:()=>Bt,OpenAddLiquidityFormTool:()=>nn,POOL_AGENT_TOOL_NAMES:()=>Io,PantographService:()=>ie,PoolByAddressTool:()=>tn,PoolDetailTool:()=>Zt,PoolFallbackAiTool:()=>Vt,PoolPriceRangesTool:()=>sn,PoolSearchTool:()=>en,PoolService:()=>ae,PreviewAddLiquidityTool:()=>on,RelayAdapter:()=>zt,Router:()=>En,SUPPORTED_CHAINS:()=>dt,SUPPORTED_CHAINS_LABEL:()=>mt,SWAP_PROVIDER_CONFIG:()=>bo,SendNativeTool:()=>yn,SendNftTool:()=>Pn,SendTokenTool:()=>bn,Subagent:()=>Y,SubgraphAddPoolTool:()=>hn,SubgraphCoinPoolPairsTool:()=>mn,SubgraphPoolByAddressTool:()=>un,SubgraphPoolByPositionIdTool:()=>dn,SubgraphPoolSearchTool:()=>ln,SubgraphPositionDetailTool:()=>pn,SubgraphTrendingPoolsTool:()=>cn,Summarizer:()=>Cn,SwapServiceFactory:()=>at,SwapTokenTool:()=>Sn,Synthesizer:()=>Rn,TOKEN_AGENT_TOOL_NAMES:()=>Eo,TRANSFER_TOPIC:()=>Ts,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Xr,TokenAnalyticsTool:()=>wt,TokenHoldersTool:()=>bt,TokenInfoTool:()=>yt,TokenScoreTool:()=>kt,ToolRegistry:()=>ut,TopGainersTool:()=>vt,TopPoolsTool:()=>Jt,TransactionByHashTool:()=>It,TrendingTokensTool:()=>Tt,UNISWAP_CHAIN_SLUG:()=>Hn,UpstashKnowledgeBase:()=>Ze,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Lo,WALLET_AGENT_TOOL_NAMES:()=>_o,WalletActionAppTool:()=>Gn,WalletApprovalsTool:()=>Et,WalletDefiPositionsTool:()=>Nt,WalletDefiProtocolPositionsTool:()=>Ut,WalletDefiSummaryTool:()=>Rt,WalletHistoryTool:()=>St,WalletNFTsTool:()=>Dt,WalletNftTransfersTool:()=>xt,WalletPnlSummaryTool:()=>Ct,WalletPnlTool:()=>_t,WalletTokenBalancesTool:()=>At,WalletTokenTransfersTool:()=>Pt,WebsiteTrustKeyringAgent:()=>Fo,ZERO_ADDRESS:()=>F,amazonDomainForLanguage:()=>or,apiClient:()=>x,buildChallenge:()=>Ho,buildRangePresets:()=>mr,buildUniswapPoolUrl:()=>fe,clampTick:()=>De,completeX402:()=>Go,configureSupportedChains:()=>so,createAiAgent:()=>Qn,createDefaultSubagents:()=>Do,createNfcAgent:()=>Xn,createNftAgent:()=>zn,createPoolAgent:()=>Jn,createTokenAgent:()=>jn,createWalletActionAgent:()=>Zn,createWalletActionAppTools:()=>Co,createWalletAgent:()=>Kn,createX402SignatureProvider:()=>Ko,displayFromChallenge:()=>Lr,encodeSignedHeader:()=>Yo,ethCallAt:()=>fs,ethCallByChain:()=>pr,fetchTopMarketplaces:()=>rr,getAffiliateFee:()=>Yt,getChainMeta:()=>ne,getDefaultRpcUrl:()=>Pa,getGatewayAddress:()=>ko,getGatewayChains:()=>To,getNativeTokenInfo:()=>Xt,getPositionManagerAddress:()=>vo,getProviderByChain:()=>yo,ingestKnowledgeBase:()=>Vs,isAbortError:()=>rt,nfcAmazonSearchUrl:()=>co,normaliseCountry:()=>uo,normalizePriceRangeToPool:()=>Gt,priceToTick:()=>it,requestWithX402:()=>ci,resolveNfcShopLinks:()=>qt,resolveRpcUrl:()=>Kt,roundTickToSpacing:()=>Le,rpcCall:()=>$e,setRpcOverrides:()=>dr,swapServiceFactory:()=>Oe,tickToPrice:()=>xe,toPantographChain:()=>Ni});module.exports=Xs(zl);var _r=zs(require("axios"));var Cr="0.2.41";var Js=`keyring-agent-core/${Cr} (Keyring Chatbot Agent; +https://keyring.app)`,Zs="payment-required",Vo=null;function Er(a){Vo=a}function ei(a){return a?Object.keys(a).some(e=>e.toLowerCase()==="payment-signature"):!1}var Rr;function Dn(a){Rr=a}var ti=3e4,ni=typeof process<"u"&&process.versions?.node!=null,Wo=class{instance;constructor(e={}){this.instance=_r.default.create({baseURL:e.baseURL,timeout:e.timeout??ti,validateStatus:()=>!0,headers:{Accept:"application/json",...ni?{"User-Agent":e.userAgent??Js}:{},...e.headers}})}async request(e,t,n,r={}){let o=r.signal??Rr,s=await this.instance.request({...r,signal:o,method:e,url:t,data:n}),i={};for(let[c,d]of Object.entries(s.headers??{}))d!=null&&(i[c.toLowerCase()]=String(d));let l={ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,data:s.data,headers:i};if(l.status===402&&l.headers[Zs]&&Vo&&!ei(r.headers)){let c=await Vo(l,{url:t,method:String(e),body:n,headers:r.headers});if(c)return this.request(e,t,n,{...r,headers:{...r.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Wo;function I(a){let{data:e,status:t,statusText:n}=a,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=l=>l&&typeof l=="object"?l.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}var oi={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},Nr="payment-required",ri="PAYMENT-SIGNATURE";function si(a){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(a),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(a,"utf8").toString("base64")}function ii(a){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(a,"base64").toString("utf8")}function ai(){let a=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(a);else for(let t=0;t<32;t++)a[t]=Math.floor(Math.random()*256);return"0x"+Array.from(a,t=>t.toString(16).padStart(2,"0")).join("")}function li(a){let[e,t]=String(a).split(":"),n=parseInt(t,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${a}`);return n}function Ur(a){if(!a.query||Object.keys(a.query).length===0)return a.url;let e=Object.entries(a.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return a.url.includes("?")?`${a.url}&${e}`:`${a.url}?${e}`}function Ir(a){return JSON.parse(ii(a))}function Ho(a,e,t,n){let r=a.headers[Nr];if(!r)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=Ir(r),s=o.accepts?.[0];if(!s)throw new Error("402 response offered no payment requirements");if(s.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${s.scheme} (only "exact" is supported)`);if(!t)throw new Error("No connected wallet address to build the payment from");let i=li(s.network),l=Math.floor(Date.now()/1e3),c={from:t,to:s.payTo,value:String(s.amount),validAfter:"0",validBefore:String(l+(s.maxTimeoutSeconds??300)),nonce:ai()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:i,verifyingContract:s.asset},types:oi,primaryType:"TransferWithAuthorization",message:{...c}};return{request:{url:Ur(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:s,authorization:c,typedData:d,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:c},resource:o.resource,accepted:s,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function ci(a,e,t,n){let r=Ur(e),o=await a.request(e.method??"GET",r,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:Ho(o,e,t,n)};if(!o.ok)throw new Error(I(o));return{status:"ok",data:o.data}}async function Go(a,e,t){let{url:n,method:r,body:o,headers:s}=e.request,i=await a.request(r,n,o,{headers:{...s??{},...Yo(e,t)}});if(i.ok)return i.data;let l=i.headers[Nr];if(l)try{let c=Ir(l);if(c.error)throw new Error(`x402 payment rejected: ${c.error}`)}catch(c){if(c instanceof Error&&c.message.startsWith("x402 payment rejected"))throw c}throw new Error(I(i))}var ui={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function Yo(a,e){let t={...a.paymentDraft,payload:{authorization:a.authorization,signature:e}};return{[ri]:si(JSON.stringify(t))}}function Lr(a){let e=a.requirements,t=a.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:ui[e.network]||e.network,payTo:e.payTo,...t?.description?{description:t.description}:{},resourceUrl:a.request.url}}function Ko(a){return async(e,t)=>{let n=a.getPayer(),r=a.getSigner();if(!n||!r)return null;let o;try{o=Ho(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let s;try{s=await r({typedData:o.typedData,display:Lr(o)})}catch{s=null}return s?Yo(o,s):null}}var He=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function rt(a){if(!a||typeof a!="object")return!1;let e=a;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function On(a){if(a?.aborted)throw new He}function jo(a,e){if(!e)return{signal:a.signal,cleanup:()=>{}};if(e.aborted)return a.abort(),{signal:a.signal,cleanup:()=>{}};let t=()=>a.abort();return e.addEventListener("abort",t),{signal:a.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Dr={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},di="https://nft.keyring.app/api/gemini-stable",pi=new Set([408,429,500,502,503,504]),Or=3e4,oo=a=>new Promise(e=>setTimeout(e,a));function ro(a,e,t){if(t!=null&&t>0)return Math.min(t,Or);let n=Math.min(e*2**(a-1),Or);return n/2+Math.random()*(n/2)}function mi(a){if(!a)return null;let e=Number(a);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(a);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var z=class{model;maxTokens;temperature;baseUrl;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??di}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;On(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of c){let f=m.parts.map(h=>h.functionCall?`fc:${h.functionCall.name}`:h.functionResponse?`fr:${h.functionResponse.name}`:`text:${(h.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${f}]`)}}let d={contents:c,generationConfig:{maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature}};r&&(d.systemInstruction=r),t?.length?(d.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(d.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(d.tools=[{googleSearch:{}}]);let u=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){On(l);let f;try{f=await x.post(u,d,{headers:{"Content-Type":"application/json"},signal:l})}catch(T){if(rt(T))throw T;if(p=T instanceof Error?T.message:String(T),m>=s)break;await oo(ro(m,i));continue}if(!f.ok){let T=typeof f.data=="string"?f.data:JSON.stringify(f.data)||f.statusText;if(p=`Gemini proxy error ${f.status}: ${T}`,!pi.has(f.status))throw new Error(p);if(m>=s)break;let A=mi(f.headers["retry-after"]??null);await oo(ro(m,i,A));continue}if(f.data==null||typeof f.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await oo(ro(m,i));continue}let h=f.data,g=h.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let y="",b=[],w=g.content?.parts;if(!Array.isArray(w)||w.length===0){let T=g.finishReason;if(!(T==="SAFETY"||T==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${T??"none"})`,await oo(ro(m,i));continue}return{text:"",toolCalls:[]}}for(let T of w)T.text&&(y+=T.text),T.functionCall&&b.push({toolName:T.functionCall.name,args:T.functionCall.args??{},callId:T.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let k=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:b,usage:k}}throw new Error(p)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(u=>u.functionCall),d=l?.parts.some(u=>u.functionCall);l&&l.role===i.role&&!c&&!d?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let l=r[i],c=o[o.length-1];l.role==="function"&&!c?.parts.some(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.functionCall)&&!(r[i+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
1
+ "use strict";var Ws=Object.create;var no=Object.defineProperty;var Hs=Object.getOwnPropertyDescriptor;var Gs=Object.getOwnPropertyNames;var Ys=Object.getPrototypeOf,Ks=Object.prototype.hasOwnProperty;var js=(a,e)=>{for(var t in e)no(a,t,{get:e[t],enumerable:!0})},xr=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gs(e))!Ks.call(a,r)&&r!==t&&no(a,r,{get:()=>e[r],enumerable:!(n=Hs(e,r))||n.enumerable});return a};var zs=(a,e,t)=>(t=a!=null?Ws(Ys(a)):{},xr(e||!a||!a.__esModule?no(t,"default",{value:a,enumerable:!0}):t,a)),Xs=a=>xr(no({},"__esModule",{value:!0}),a);var zl={};js(zl,{AI_AGENT_TOOL_NAMES:()=>Uo,AbortError:()=>He,AgentCore:()=>Bo,ApproveTokenTool:()=>wn,BaseNftAiTool:()=>Ie,BaseNftMessageTool:()=>Lt,BaseSwapService:()=>Xe,BaseTool:()=>v,BaseWalletActionTool:()=>Se,BuyTokenTool:()=>An,ChatHistory:()=>xn,DEFAULT_CHAIN:()=>be,DEFAULT_PROVIDER:()=>Vn,DEFAULT_RPC_BY_CHAIN:()=>Te,DebridgeAdapter:()=>jt,EstimatePoolYieldTool:()=>rn,GeminiProvider:()=>z,GeminiSearchAiTool:()=>$t,HEX_TO_PANTOGRAPH:()=>zr,KnowledgeBase:()=>_n,ManageLiquidityRedirectTool:()=>an,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>No,NFC_AMAZON_DEFAULT_DOMAIN:()=>nr,NFC_AMAZON_DOMAINS:()=>tr,NFTContractInfoTool:()=>Ot,NFTMetadataTool:()=>Mt,NFT_AGENT_TOOL_NAMES:()=>Ro,NfcBuyTool:()=>Ft,NfcInfoTool:()=>Bt,OpenAddLiquidityFormTool:()=>nn,POOL_AGENT_TOOL_NAMES:()=>Io,PantographService:()=>ie,PoolByAddressTool:()=>tn,PoolDetailTool:()=>Zt,PoolFallbackAiTool:()=>Vt,PoolPriceRangesTool:()=>sn,PoolSearchTool:()=>en,PoolService:()=>ae,PreviewAddLiquidityTool:()=>on,RelayAdapter:()=>zt,Router:()=>En,SUPPORTED_CHAINS:()=>dt,SUPPORTED_CHAINS_LABEL:()=>mt,SWAP_PROVIDER_CONFIG:()=>bo,SendNativeTool:()=>yn,SendNftTool:()=>Pn,SendTokenTool:()=>bn,Subagent:()=>Y,SubgraphAddPoolTool:()=>hn,SubgraphCoinPoolPairsTool:()=>mn,SubgraphPoolByAddressTool:()=>un,SubgraphPoolByPositionIdTool:()=>dn,SubgraphPoolSearchTool:()=>ln,SubgraphPositionDetailTool:()=>pn,SubgraphTrendingPoolsTool:()=>cn,Summarizer:()=>Cn,SwapServiceFactory:()=>at,SwapTokenTool:()=>Sn,Synthesizer:()=>Rn,TOKEN_AGENT_TOOL_NAMES:()=>Eo,TRANSFER_TOPIC:()=>Ts,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Xr,TokenAnalyticsTool:()=>wt,TokenHoldersTool:()=>bt,TokenInfoTool:()=>yt,TokenScoreTool:()=>kt,ToolRegistry:()=>ut,TopGainersTool:()=>vt,TopPoolsTool:()=>Jt,TransactionByHashTool:()=>It,TrendingTokensTool:()=>Tt,UNISWAP_CHAIN_SLUG:()=>Hn,UpstashKnowledgeBase:()=>Ze,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Lo,WALLET_AGENT_TOOL_NAMES:()=>_o,WalletActionAppTool:()=>Gn,WalletApprovalsTool:()=>Et,WalletDefiPositionsTool:()=>Nt,WalletDefiProtocolPositionsTool:()=>Ut,WalletDefiSummaryTool:()=>Rt,WalletHistoryTool:()=>St,WalletNFTsTool:()=>Dt,WalletNftTransfersTool:()=>xt,WalletPnlSummaryTool:()=>Ct,WalletPnlTool:()=>_t,WalletTokenBalancesTool:()=>At,WalletTokenTransfersTool:()=>Pt,WebsiteTrustKeyringAgent:()=>Fo,ZERO_ADDRESS:()=>F,amazonDomainForLanguage:()=>or,apiClient:()=>x,buildChallenge:()=>Ho,buildRangePresets:()=>mr,buildUniswapPoolUrl:()=>fe,clampTick:()=>De,completeX402:()=>Go,configureSupportedChains:()=>so,createAiAgent:()=>Qn,createDefaultSubagents:()=>Do,createNfcAgent:()=>Xn,createNftAgent:()=>zn,createPoolAgent:()=>Jn,createTokenAgent:()=>jn,createWalletActionAgent:()=>Zn,createWalletActionAppTools:()=>Co,createWalletAgent:()=>Kn,createX402SignatureProvider:()=>Ko,displayFromChallenge:()=>Lr,encodeSignedHeader:()=>Yo,ethCallAt:()=>fs,ethCallByChain:()=>pr,fetchTopMarketplaces:()=>rr,getAffiliateFee:()=>Yt,getChainMeta:()=>ne,getDefaultRpcUrl:()=>Pa,getGatewayAddress:()=>ko,getGatewayChains:()=>To,getNativeTokenInfo:()=>Xt,getPositionManagerAddress:()=>vo,getProviderByChain:()=>yo,ingestKnowledgeBase:()=>Vs,isAbortError:()=>rt,nfcAmazonSearchUrl:()=>co,normaliseCountry:()=>uo,normalizePriceRangeToPool:()=>Gt,priceToTick:()=>it,requestWithX402:()=>ci,resolveNfcShopLinks:()=>qt,resolveRpcUrl:()=>Kt,roundTickToSpacing:()=>Le,rpcCall:()=>$e,setRpcOverrides:()=>dr,swapServiceFactory:()=>Oe,tickToPrice:()=>xe,toPantographChain:()=>Ni});module.exports=Xs(zl);var _r=zs(require("axios"));var Cr="0.2.42";var Js=`keyring-agent-core/${Cr} (Keyring Chatbot Agent; +https://keyring.app)`,Zs="payment-required",Vo=null;function Er(a){Vo=a}function ei(a){return a?Object.keys(a).some(e=>e.toLowerCase()==="payment-signature"):!1}var Rr;function Dn(a){Rr=a}var ti=3e4,ni=typeof process<"u"&&process.versions?.node!=null,Wo=class{instance;constructor(e={}){this.instance=_r.default.create({baseURL:e.baseURL,timeout:e.timeout??ti,validateStatus:()=>!0,headers:{Accept:"application/json",...ni?{"User-Agent":e.userAgent??Js}:{},...e.headers}})}async request(e,t,n,r={}){let o=r.signal??Rr,s=await this.instance.request({...r,signal:o,method:e,url:t,data:n}),i={};for(let[c,d]of Object.entries(s.headers??{}))d!=null&&(i[c.toLowerCase()]=String(d));let l={ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,data:s.data,headers:i};if(l.status===402&&l.headers[Zs]&&Vo&&!ei(r.headers)){let c=await Vo(l,{url:t,method:String(e),body:n,headers:r.headers});if(c)return this.request(e,t,n,{...r,headers:{...r.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Wo;function I(a){let{data:e,status:t,statusText:n}=a,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=l=>l&&typeof l=="object"?l.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}var oi={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},Nr="payment-required",ri="PAYMENT-SIGNATURE";function si(a){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(a),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(a,"utf8").toString("base64")}function ii(a){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(a),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(a,"base64").toString("utf8")}function ai(){let a=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(a);else for(let t=0;t<32;t++)a[t]=Math.floor(Math.random()*256);return"0x"+Array.from(a,t=>t.toString(16).padStart(2,"0")).join("")}function li(a){let[e,t]=String(a).split(":"),n=parseInt(t,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${a}`);return n}function Ur(a){if(!a.query||Object.keys(a.query).length===0)return a.url;let e=Object.entries(a.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return a.url.includes("?")?`${a.url}&${e}`:`${a.url}?${e}`}function Ir(a){return JSON.parse(ii(a))}function Ho(a,e,t,n){let r=a.headers[Nr];if(!r)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=Ir(r),s=o.accepts?.[0];if(!s)throw new Error("402 response offered no payment requirements");if(s.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${s.scheme} (only "exact" is supported)`);if(!t)throw new Error("No connected wallet address to build the payment from");let i=li(s.network),l=Math.floor(Date.now()/1e3),c={from:t,to:s.payTo,value:String(s.amount),validAfter:"0",validBefore:String(l+(s.maxTimeoutSeconds??300)),nonce:ai()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:i,verifyingContract:s.asset},types:oi,primaryType:"TransferWithAuthorization",message:{...c}};return{request:{url:Ur(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:s,authorization:c,typedData:d,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:c},resource:o.resource,accepted:s,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function ci(a,e,t,n){let r=Ur(e),o=await a.request(e.method??"GET",r,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:Ho(o,e,t,n)};if(!o.ok)throw new Error(I(o));return{status:"ok",data:o.data}}async function Go(a,e,t){let{url:n,method:r,body:o,headers:s}=e.request,i=await a.request(r,n,o,{headers:{...s??{},...Yo(e,t)}});if(i.ok)return i.data;let l=i.headers[Nr];if(l)try{let c=Ir(l);if(c.error)throw new Error(`x402 payment rejected: ${c.error}`)}catch(c){if(c instanceof Error&&c.message.startsWith("x402 payment rejected"))throw c}throw new Error(I(i))}var ui={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function Yo(a,e){let t={...a.paymentDraft,payload:{authorization:a.authorization,signature:e}};return{[ri]:si(JSON.stringify(t))}}function Lr(a){let e=a.requirements,t=a.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:ui[e.network]||e.network,payTo:e.payTo,...t?.description?{description:t.description}:{},resourceUrl:a.request.url}}function Ko(a){return async(e,t)=>{let n=a.getPayer(),r=a.getSigner();if(!n||!r)return null;let o;try{o=Ho(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let s;try{s=await r({typedData:o.typedData,display:Lr(o)})}catch{s=null}return s?Yo(o,s):null}}var He=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function rt(a){if(!a||typeof a!="object")return!1;let e=a;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function On(a){if(a?.aborted)throw new He}function jo(a,e){if(!e)return{signal:a.signal,cleanup:()=>{}};if(e.aborted)return a.abort(),{signal:a.signal,cleanup:()=>{}};let t=()=>a.abort();return e.addEventListener("abort",t),{signal:a.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Dr={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},di="https://nft.keyring.app/api/gemini-stable",pi=new Set([408,429,500,502,503,504]),Or=3e4,oo=a=>new Promise(e=>setTimeout(e,a));function ro(a,e,t){if(t!=null&&t>0)return Math.min(t,Or);let n=Math.min(e*2**(a-1),Or);return n/2+Math.random()*(n/2)}function mi(a){if(!a)return null;let e=Number(a);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(a);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var z=class{model;maxTokens;temperature;baseUrl;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??di}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;On(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of c){let f=m.parts.map(h=>h.functionCall?`fc:${h.functionCall.name}`:h.functionResponse?`fr:${h.functionResponse.name}`:`text:${(h.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${f}]`)}}let d={contents:c,generationConfig:{maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature}};r&&(d.systemInstruction=r),t?.length?(d.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(d.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(d.tools=[{googleSearch:{}}]);let u=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){On(l);let f;try{f=await x.post(u,d,{headers:{"Content-Type":"application/json"},signal:l})}catch(T){if(rt(T))throw T;if(p=T instanceof Error?T.message:String(T),m>=s)break;await oo(ro(m,i));continue}if(!f.ok){let T=typeof f.data=="string"?f.data:JSON.stringify(f.data)||f.statusText;if(p=`Gemini proxy error ${f.status}: ${T}`,!pi.has(f.status))throw new Error(p);if(m>=s)break;let A=mi(f.headers["retry-after"]??null);await oo(ro(m,i,A));continue}if(f.data==null||typeof f.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await oo(ro(m,i));continue}let h=f.data,g=h.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let y="",b=[],w=g.content?.parts;if(!Array.isArray(w)||w.length===0){let T=g.finishReason;if(!(T==="SAFETY"||T==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${T??"none"})`,await oo(ro(m,i));continue}return{text:"",toolCalls:[]}}for(let T of w)T.text&&(y+=T.text),T.functionCall&&b.push({toolName:T.functionCall.name,args:T.functionCall.args??{},callId:T.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let k=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:b,usage:k}}throw new Error(p)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(u=>u.functionCall),d=l?.parts.some(u=>u.functionCall);l&&l.role===i.role&&!c&&!d?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let l=r[i],c=o[o.length-1];l.role==="function"&&!c?.parts.some(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.functionCall)&&!(r[i+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
2
2
  `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:Dr[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:Dr[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 ut=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 dt=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],hi=new Set(dt),Ge=[...dt],zo=new Set(Ge),be="0x1",mt="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function gi(a){return a.map(e=>pt[e]??e).join(", ")}function so(a){let e=new Set;if(a)for(let n of a){let r=io(n);r&&e.add(r)}let t=dt.filter(n=>!e.has(n));Ge=t.length>0?[...t]:[...dt],zo=new Set(Ge),be=Ge.includes("0x1")?"0x1":Ge[0],mt=gi(Ge)}var fi={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function $(a){let e=io(a);return e&&zo.has(e)?e:null}function io(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=fi[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&&hi.has(n)?n:null}function Pe(a){return $(a)!==null}function we(){return[...Ge]}var Ke=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${mt}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ye=a=>typeof a=="string"&&a.trim()!=="";function le(a,e){if(Ye(a)){let t=$(a);if(t)return t;throw new Ke(a.trim())}if(Ye(e?.chain)){let t=$(e.chain);if(t)return t;throw new Ke(e.chain.trim())}return null}function ao(a,e){return $(a)??$(e?.chain)??void 0}var pt={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function P(a){let e=io(a);return e&&pt[e]?pt[e]:typeof a=="string"&&a.trim()?a.trim():"the requested chain"}var yi={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function Mr(a,e){let t=io(a),n=t?yi[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var bi={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function qr(a){if(typeof a!="string")return null;let e=a.trim().toLowerCase();return e?bi[e]??null:null}var wi={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function Br(a){let e=$(a);return e?wi[e]??null:null}function ht(a,e){if(!Ye(a))return null;let t=$(a),n=$(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:pt[t]??t,connectedLabel:pt[n]??n}}function Fr(a,e){let t=typeof a=="string"?a.trim():"",n=e&&e.length?e.filter(o=>zo.has(o)):[];return(n.length?n:Ge).map(o=>{let s=pt[o]??o;return{label:s,prompt:t?`${t} (${s})`:s}})}function gt(a,e){return{actionButtons:Fr(e),_instructions:`The user wants to ${a} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var K=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=Fr(e,t)}},Mn=class extends Error{code="no_wallet_connected";constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one."),this.name="NoWalletConnectedError"}};function X(a,e){if(Ye(a))return a.trim();if(Ye(e?.walletAddress))return e.walletAddress.trim();throw new Mn}function Z(a,e,t){if(Ye(a)){let n=$(a);if(n)return n;throw new Ke(a.trim())}if(Ye(e?.chain)){let n=$(e.chain);if(n)return n;throw new Ke(e.chain.trim())}if(Ye(e?.walletAddress))throw new K(typeof e?.query=="string"?e.query:void 0,t);return be}var v=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s=ki(o);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-r,...s.actionButtons?{actionButtons:s.actionButtons}:{}}}catch(o){return o instanceof K?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-r,actionButtons:o.buttons}:o instanceof Mn?{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 ki(a){if(!a||typeof a!="object")return{data:a};let e=a,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:a};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var $r=require("js-sha3");function B(a){return typeof a=="string"&&/^0x[0-9a-fA-F]{40}$/.test(a)}function Ti(a){return new Uint8Array($r.keccak256.arrayBuffer(a))}function qn(a){let e=a.startsWith("0x")?a.slice(2):a,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function Vr(a){return"0x"+Array.from(a).map(e=>e.toString(16).padStart(2,"0")).join("")}function Wr(a){return new TextEncoder().encode(a)}function st(...a){let e=a.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;return t}function vi(a,e=32){let t=new Uint8Array(e);return t.set(a,e-a.length),t}function Ai(a,e=32){let t=new Uint8Array(e);return t.set(a),t}function Hr(a){let e=((a%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return qn(e)}function Bn(a){return Hr(BigInt(a))}function Gr(a){return a==="uint"?"uint256":a==="int"?"int256":a.match(/^uint$/)?"uint256":a.match(/^int$/)?"int256":a.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function Yr(a){let e=Gr(a.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(a.components??[]).map(Yr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function Si(a){let e=(a.inputs??[]).map(Yr).join(",");return`${a.name??""}(${e})`}function Xo(a,e){let t=Ci(a.type);if(t){let[r,o]=t;return Pi({...a,type:o},e,r)}if(a.type==="tuple")return xi(a,e);if(a.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:vi(qn(o.toLowerCase()))}}if(a.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Gr(a.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:Bn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:Hr(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?qn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ai(o)}}if(n==="bytes"){let r=typeof e=="string"?qn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:st(Bn(r.length),s)}}if(n==="string"){let r=typeof e=="string"?Wr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:st(Bn(r.length),s)}}throw new Error(`Unsupported ABI type: ${a.type}`)}function Qo(a){let e=0;for(let{dynamic:o,encoded:s}of a)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of a)o?(t.push(Bn(e+r)),n.push(s),r+=s.length):t.push(s);return st(...t,...n)}function Pi(a,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let i=Xo(a,s);i.dynamic&&(r=!0),o.push(i)}if(n||r){let s=Qo(o);if(n){let i=Bn(o.length);return{dynamic:!0,encoded:o.length>0?st(i,s):i}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:st(...o.map(s=>s.encoded))}}function xi(a,e){let t=a.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],i=Array.isArray(e)?e[o]:e[s.name??""],l=Xo(s,i);l.dynamic&&(n=!0),r.push(l)}return{dynamic:n,encoded:n?Qo(r):st(...r.map(o=>o.encoded))}}function Ci(a){let e=a.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function _i(a,e){if(a.length!==e.length)throw new Error(`Expected ${a.length} values, got ${e.length}`);if(a.length===0)return"0x";let t=a.map((r,o)=>Xo(r,e[o])),n=Qo(t);return Vr(n)}function ft({abi:a,functionName:e,args:t=[]}){let n=a.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=Si(n),o=Ti(Wr(r)).slice(0,4),s=n.inputs??[],i=s.length===0||t.length===0?new Uint8Array(0):qn(_i(s,t).slice(2));return Vr(st(o,i))}var Ei="https://wallet-api.pantograph.app",Ri="0x0000000000000000000000000000000000000000",zr={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Xr={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function Ni(a){return zr[a.toLowerCase()]||a}function Kr(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function Jo(a){let e=a,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function Zo(a){if(Array.isArray(a))return a;let e=a;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function se(a){if(a==null)return null;let e=typeof a=="number"?a:parseFloat(String(a));return Number.isFinite(e)?e:null}function jr(a,e){let t=a.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=se(a.price_change_percentage_24h)??se(a.priceChange24h)??se(a.usd_price_24hr_percent_change)??se(a.price_change_24h)??se(a.priceChange);return{chainId:e,tokenAddress:a.address??a.token_address??"",name:a.name??null,symbol:a.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:a.logoURI??a.icon_image??a.logo??null,usdPrice:se(a.price)??se(a.usd_price),marketCap:se(a.market_cap)??se(a.marketCap),totalVolume:{"24h":se(a.total_volume)??se(a.volume24h)},pricePercentChange:{"24h":r}}}var ie=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Ei).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),r=this.tokensUrl(t,n),o=await x.get(r);if(!o.ok)return;let s=Zo(o.data),i=new Map;for(let l of s)l.address&&i.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=i.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),r=await x.get(n);if(!r.ok)return null;let o=Zo(r.data),s=e.toLowerCase()===Ri,i=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||s&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||s&&l.token_address==="");return i?Jo(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=this.tokensUrl(t,e.join(",")),o=await x.get(r);if(!o.ok)return n;let s=Zo(o.data),i=new Set(e.map(l=>l.toLowerCase()));for(let l of s){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&i.has(c)&&(n[c]=Jo(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||be,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=Kr({chainId:o,key:t}),i=`${this.baseUrl}/token-list/all?${s}`,l=await x.get(i);if(!l.ok)throw new Error(I(l));let c=l.data,d=c?.result??c?.data??c,u=[];return Array.isArray(d)?u=d:d&&typeof d=="object"&&(u=Object.values(d).flat()),{success:!0,data:u.map(Jo)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||be,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=Xr[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],d=l.status==="fulfilled"?o.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>jr(h,t)):[],u=new Set,p=[];for(let h of d){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),m.push(h))}let f=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=se(s.market_cap)??se(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":se(s.total_volume)??se(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=parseInt(e,16),o=Kr({chainId:r,duration:n,limit:t}),s=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(s);if(!c.ok)throw new Error(I(c));let d=c.data;if(i=Array.isArray(d)?d:Array.isArray(d.data)?d.data:[],i.length>0)break;l<4&&await new Promise(u=>setTimeout(u,2e3))}return i.map(l=>jr(l,e))}async getTopGainers(e){let t=e?.chain||be,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,r=e?.duration||"24h";try{let o=await this.fetchTopGainers(t,n,r);return await this.enrichTrendingMarketData(o,t),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var Ui="https://nft.keyring.app",Ii="https://nft.keyring.app",Li=.01,N=5,W=1e3,Di="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Oi="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function j(a){return a||be}function H(a){let e=[];for(let[t,n]of Object.entries(a))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function G(a){return new Promise(e=>setTimeout(e,a))}function Mi(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function er(a){if(Array.isArray(a))return a;if(a&&typeof a=="object"){let e=a;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ui).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Ii).replace(/\/+$/,""),this.pantograph=new ie({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=j(n),l="Unknown error";for(let c=1;c<=N;c++)try{let d={chain:i,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(d.token_addresses=r);let u=[],p=null;do{p&&(d.cursor=p);let f=H(d),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${f}`,g=await x.get(h);if(!g.ok)throw new U(g.status,I(g));let y=g.data,b=y?.data??y;b?.result?.length>0&&u.push(...b.result),p=b?.cursor??null}while(p);let m={result:u};return m?.result?.length>0&&(m.result=m.result.filter(f=>parseFloat(f.balance||"0")>0),m.result=m.result.map(f=>({...f,token_address:f.token_address.toLowerCase()===Di?Oi:f.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(f=>f.usd_value==null||f.usd_value>=Li)),{success:!0,data:m}}catch(d){if(l=d instanceof Error?d.message:"Unknown error",d instanceof U&&d.status===400)break;c<N&&await G(W)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=j(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${H({chain:r,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${H({chain:r,include:"percent_change"})}`)]),d=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;d=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!d){o="Token metadata not found",i<N&&await G(W);continue}let u=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;u=p?.data??p}return{success:!0,data:{...d,...u?.usd_price?{usd_price:u.usd_price}:{},...u?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:u.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await G(W)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=10,excludeSpam:o=!0,cursor:s,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let d=j(n),u="Unknown error";for(let p=1;p<=N;p++)try{let m={chain:d,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(m.cursor=s),l&&(m.include_prices=!0),i&&i.length>0&&(m.token_addresses=i);let f=H(m),h=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${f}`,g=await x.get(h);if(!g.ok)throw new U(g.status,I(g));let y=g.data;return{success:!0,data:y?.data??y}}catch(m){if(u=m instanceof Error?m.message:"Unknown error",m instanceof U&&m.status===400)break;p<N&&await G(W)}return{success:!1,error:u}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!B(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=j(r),d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:i};l&&(p.include=l);let m=H(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await x.get(f);if(!h.ok)throw new U(h.status,I(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;u<N&&await G(W)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await G(W)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:i,toBlock:l,cursor:c,order:d="DESC",includeInternalTransactions:u,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=j(n),f=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let g=1;g<=N;g++)try{let y={chain:m,limit:f,order:d};o&&(y.from_date=o),s&&(y.to_date=s),i!=null&&(y.from_block=i),l!=null&&(y.to_block=l),c&&(y.cursor=c),u!=null&&(y.include_internal_transactions=u),p!=null&&(y.nft_metadata=p);let b=H(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,k=await x.get(w);if(!k.ok)throw new U(k.status,I(k));let T=k.data;return{success:!0,data:T?.data??T}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;g<N&&await G(W)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=j(n),m=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let h=1;h<=N;h++)try{let g={chain:p,limit:m,order:u};s&&(g.from_date=s),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),d&&(g.cursor=d),r?.length&&(g.contract_addresses=r);let y=H(g),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await x.get(b);if(!w.ok)throw new U(w.status,I(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(g){if(f=g instanceof Error?g.message:"Unknown error",g instanceof U&&g.status===400)break;h<N&&await G(W)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=j(n),h=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=N;y++)try{let b={chain:f,limit:h,order:u,format:m};s&&(b.from_date=s),i&&(b.to_date=i),l!=null&&(b.from_block=l),c!=null&&(b.to_block=c),d&&(b.cursor=d),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=H(b),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,T=await x.get(k);if(!T.ok)throw new U(T.status,I(T));let A=T.data;return{success:!0,data:A?.data??A}}catch(b){if(g=b instanceof Error?b.message:"Unknown error",b instanceof U&&b.status===400)break;y<N&&await G(W)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!B(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await G(W)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=j(n),s="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:o};r&&(l.days=r);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data;return{success:!0,data:p?.data??p}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await G(W)}return{success:!1,error:s}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let d=H(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await x.get(u);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await G(W)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await G(W)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=j(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let d=H(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await x.get(u);if(!p.ok)throw new U(p.status,I(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await G(W)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await G(W)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:Mi(u)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await G(W)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!B(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=j(r),s="Unknown error";for(let i=1;i<=N;i++)try{let l=H({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,d=await x.get(c);if(!d.ok)throw new U(d.status,I(d));let m=d.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(g=>({token_type:g.tokenType,address:g.address,contract_address:g.address,name:g.name??"",symbol:g.symbol??"",decimals:g.decimals??18,logo:g.logo,balance:g.balance??"0",balance_formatted:g.balanceFormatted??"0",usd_price:g.usdPrice,usd_value:g.usdValue}))}))}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await G(W)}return{success:!1,error:s}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!B(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await G(W)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!B(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=j(n),o="Unknown error";for(let s=1;s<=N;s++)try{let i=H({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;s<N&&await G(W)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=N;o++)try{let s={};t&&(s.chain=j(t)),n!=null&&(s.limit=n);let i=H(s),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new U(c.status,I(c));let d=c.data,u=d?.data??d;return{success:!0,data:er(u)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof U&&s.status===400)break;o<N&&await G(W)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data,m=p?.data??p;return{success:!0,data:er(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await G(W)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=j(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=H(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new U(u.status,I(u));let p=u.data,m=p?.data??p;return{success:!0,data:er(m)}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await G(W)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var yt=class extends v{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}];service;llm;constructor(e){super(),this.service=new D(e),this.llm=new z(e?.llm??{})}async run(e,t){let n=e.keyword||"",r=e.prompt||"",o=t?.walletAddress||void 0;if(!n)return{error:"Missing required parameter: keyword"};let s;try{s=Z(e.chain,t)}catch(i){if(i instanceof Ke)return await this.researchTokenChainAgnostic(n,r,o);throw i}return await this.searchToken(n,s,r,o)}async researchTokenChainAgnostic(e,t,n){let r=[n?`User's connected wallet address: ${n}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
3
3
  `),o=t?await this.askGeminiWithSearch(t,r):null;return{_instructions:'The token info comes from web research only (the user is on a chain this app does not support on-chain). Present a clear summary of the token using the research: what it is, current USD price and 24h change, market data, recent news and the catalyst behind any price move, and a brief, clearly-hedged sense of market direction (no financial advice). Do NOT add a labelled "AI Analysis" heading and do NOT mention that the analysis came from AI \u2014 write it as a normal token summary. If a field is unknown, omit it. Do NOT mention chains, tools, or that anything is unsupported; just answer the question.',keyword:e,token:null,userHoldsToken:!1,research:o}}async searchToken(e,t,n,r){let o=[r?`User's connected wallet address: ${r}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
4
4
  `),[s,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),r?this.findTokenInWallet(r,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,o):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],d=e.toLowerCase(),u=g=>g.symbol?.toLowerCase()===d||g.token_address?.toLowerCase()===d,p=[...c].sort((g,y)=>(u(g)?0:1)-(u(y)?0:1)),m=null,f=p[0];if(f?.token_address){let g=await this.service.getTokenMetadata({address:f.token_address,chain:t});g.success&&g.data&&(m=g.data)}return!m&&f&&(m={...f}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:t,userHoldsToken:!!i,walletBalance:i,token:m,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),s=r.data.result.find(i=>i.token_address.toLowerCase()===o||i.symbol?.toLowerCase()===o||i.name?.toLowerCase().includes(o));return s||null}};var bt=class extends v{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Z(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(o){let u=await this.resolveContractAddress(o,n,r);if(!u)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenHolders({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var wt=class extends v{name="get-token-analytics";description=`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Z(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let u=await this.resolveContractAddress(o,n,r);if(!u)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenAnalytics({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var kt=class extends v{name="get-token-score";description=`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=Z(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?P(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},u=d.metrics??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:s,chain:n||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:u.usdPrice??null,liquidityUsd:u.liquidityUsd??null,volumeUsd:u.volumeUsd??null,transactions:u.transactions??null,supply:u.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Tt=class extends v{name="get-trending-tokens";description='List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad, and more.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1}];service;constructor(e){super(),this.service=new ie({baseUrl:e?.pantographUrl})}async run(e,t){let n=ao(e.chain,t),r=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,o=await this.service.getTrendingTokens({chain:n,limit:r});if(!o.success)return{error:o.error||"Failed to fetch trending tokens"};let s=o.data??[];return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
@@ -1151,13 +1151,13 @@ Return ONLY this JSON:
1151
1151
  "hasOwnLegitPresence": boolean, // does THIS exact domain have its own legitimate presence?
1152
1152
  "impersonationEvidence": string[], // >=3 specific points if impersonating; [] otherwise
1153
1153
  "scamReports": string[] // SOURCED findings (each with a markdown-link source) accusing THIS exact domain; [] if none/unsourced
1154
- }`,o=await this.askJson(r,{signal:n,maxRetries:3,system:this.gatherSystem()});return{description:this.cleanStr(o?.description)??"",keyFeatures:this.cleanStrArray(o?.keyFeatures),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}
1154
+ }`,o=await this.askJson(r,{signal:n,maxRetries:3,system:this.gatherSystem(),maxOutputTokens:1536});return{description:this.cleanStr(o?.description)??"",keyFeatures:this.cleanStrArray(o?.keyFeatures),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}
1155
1155
  Using web search, describe what this website / platform is and what it does \u2014 its Web3 category (DeFi, DEX, NFT, bridge, wallet, etc.) and blockchain(s) when identifiable, its purpose, and who runs it. Also list 3-5 concrete FEATURES it offers; for EACH, write a full informative sentence naming the feature and what the user can do with it \u2014 NOT one-word labels.
1156
1156
 
1157
- Return ONLY this JSON: { "description": string, "keyFeatures": string[] } // description: 1-3 concise sentences`,r=await this.askJson(n,{signal:t,maxRetries:3,system:this.gatherSystem()});return{description:this.cleanStr(r?.description)??"",keyFeatures:this.cleanStrArray(r?.keyFeatures)}}async gatherKeyFeatures(e,t){let n=`Website: ${e}
1157
+ Return ONLY this JSON: { "description": string, "keyFeatures": string[] } // description: 1-3 concise sentences`,r=await this.askJson(n,{signal:t,maxRetries:3,system:this.gatherSystem(),maxOutputTokens:1024});return{description:this.cleanStr(r?.description)??"",keyFeatures:this.cleanStrArray(r?.keyFeatures)}}async gatherKeyFeatures(e,t){let n=`Website: ${e}
1158
1158
  Using web search, list 3-5 concrete FEATURES this site offers. For EACH, write a full, informative sentence naming the feature AND what the user can do with it (its Web3 actions: swap, bridge, stake, mint, lend, etc.) \u2014 NOT one-word labels, NOT generic filler.
1159
1159
 
1160
- Return ONLY this JSON: { "keyFeatures": string[] } // an array of full-sentence strings`,r=await this.askJson(n,{signal:t,maxRetries:2,system:this.gatherSystem()});return this.cleanStrArray(r?.keyFeatures)}async present(e,t,n,r){let o=this.languageLabel(n),s=!t.isPhishing&&t.keyFeatures.length>0,l=`Here is a COMPLETED web-security assessment (facts only \u2014 do not re-investigate):
1160
+ Return ONLY this JSON: { "keyFeatures": string[] } // an array of full-sentence strings`,r=await this.askJson(n,{signal:t,maxRetries:2,system:this.gatherSystem(),maxOutputTokens:768});return this.cleanStrArray(r?.keyFeatures)}async present(e,t,n,r){let o=this.languageLabel(n),s=!t.isPhishing&&t.keyFeatures.length>0,l=`Here is a COMPLETED web-security assessment (facts only \u2014 do not re-investigate):
1161
1161
  ${[`Website: ${e}`,`Assessment: ${t.isPhishing?"shows signs of a phishing / look-alike / scam site":"no phishing or scam signals found"}`,t.copiedSite?`Impersonates: ${t.copiedSite}`:"",`What the site is: ${t.description||"(could not be determined)"}`,s?`Features:
1162
1162
  ${t.keyFeatures.map((m,f)=>`${f+1}. ${m}`).join(`
1163
1163
  `)}`:"",t.reasons.length?`Evidence:
@@ -1177,6 +1177,6 @@ Write the user-facing result for a NON-TECHNICAL user:
1177
1177
 
1178
1178
  LANGUAGE (MANDATORY): write "answer", every "reasons" item AND every "keyFeatures" item ENTIRELY in ${o}. The facts above are in English ONLY as source material \u2014 your output prose MUST be in ${o}, not English (unless ${o} itself is English). Only domain names, URLs, markdown links and brand names stay verbatim.
1179
1179
 
1180
- Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:r,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2}),d=this.cleanStr(c?.answer)??(t.description||e),u=this.cleanStrArray(c?.reasons),p=this.cleanStrArray(c?.keyFeatures);return{answer:d,reasons:u.length>0?u.slice(0,5):t.reasons.slice(0,5),keyFeatures:s?(p.length>0?p:t.keyFeatures).slice(0,5):[]}}languageLabel(e){let t={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return t[n]??t[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
1180
+ Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:r,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2,maxOutputTokens:1536}),d=this.cleanStr(c?.answer)??(t.description||e),u=this.cleanStrArray(c?.reasons),p=this.cleanStrArray(c?.keyFeatures);return{answer:d,reasons:u.length>0?u.slice(0,5):t.reasons.slice(0,5),keyFeatures:s?(p.length>0?p:t.keyFeatures).slice(0,5):[]}}languageLabel(e){let t={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return t[n]??t[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
1181
1181
 
1182
- ${$s}`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:o=$s,maxRetries:s=2}=t,i=Date.now(),l=[{role:"system",content:o,timestamp:i},{role:"user",content:e,timestamp:i}],c=await this.llm.chat(l,void 0,{googleSearch:r,maxRetries:s,signal:n}),d=this.parseJson(c.text?.trim()??"");return this.debug&&!d&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(c.text??"").slice(0,200)),d}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(t).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(t=>t.startsWith("xn--")?this.punycodeDecodeLabel(t.slice(4)):t).join("."):e}punycodeDecodeLabel(e){let c=(u,p,m)=>{u=m?Math.floor(u/700):u>>1,u+=Math.floor(u/p);let f=0;for(;u>455;)u=Math.floor(u/35),f+=36;return f+Math.floor(36*u/(u+38))},d=u=>u-48<10?u-22:u-65<26?u-65:u-97<26?u-97:36;try{let u=[],p=e.lastIndexOf("-");for(let y=0;y<Math.max(0,p);y++){let b=e.charCodeAt(y);if(b>=128)return e;u.push(b)}let m=0,f=128,h=72,g=p<0?0:p+1;for(;g<e.length;){let y=m,b=1;for(let k=36;;k+=36){if(g>=e.length)return e;let T=d(e.charCodeAt(g++));if(T>=36)return e;m+=T*b;let A=k<=h?1:k>=h+26?26:k-h;if(T<A)break;b*=36-A}let w=u.length+1;h=c(m-y,w,y===0),f+=Math.floor(m/w),m%=w,u.splice(m,0,f),m++}return String.fromCodePoint(...u)}catch{return e}}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(t=>this.alnum(t)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let o=Array.from({length:r+1},(s,i)=>i);for(let s=1;s<=n;s++){let i=[s];for(let l=1;l<=r;l++){let c=e[s-1]===t[l-1]?0:1;i[l]=Math.min(o[l]+1,i[l-1]+1,o[l-1]+c)}o=i}return o[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let o=this.hostLabels(e);return[t?this.brandCore(t):"",this.alnum(n??"")].filter(i=>i.length>=4).some(i=>r.includes(i)||o.some(l=>this.isNearMiss(l,i)))}looksLikeSquatOf(e,t){if(this.isSameRegistrableDomain(e,t))return!1;let n=this.brandCore(t);if(n.length<4)return!1;let r=this.hostLabels(e);return r.includes(n)?!1:r.some(o=>this.isNearMiss(o,n)||o.length>n.length&&o.includes(n))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),s=r.lastIndexOf(".");if(o>0&&s>0){let c=n.slice(0,o),d=r.slice(0,s),u=n.slice(o+1),p=r.slice(s+1);if(c===d&&u!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${u}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.brandCore(r),l=this.hostLabels(n).find(c=>this.isNearMiss(c,i));if(l){let c=this.editDistance(l,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let o=this.coerceToStr(r);o&&n.push(o)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let t=e,n=this.cleanStr(t.feature)??this.cleanStr(t.name)??this.cleanStr(t.title),r=this.cleanStr(t.description)??this.cleanStr(t.detail)??this.cleanStr(t.text)??this.cleanStr(t.value);return n&&r?n===r?n:`${n} \u2014 ${r}`:n||r?n??r:Object.values(t).map(s=>this.cleanStr(s)).filter(s=>!!s).join(" \u2014 ")||void 0}dedupe(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}};var jl=a=>{let e=JSON.parse(a),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((n,r)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${r} is missing "question" or "answer"`);return n})};async function Vs(a,e){let t=a.entries??(a.json?jl(a.json):[]);return t.length===0?{count:0}:new Ze(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseNftMessageTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,ManageLiquidityRedirectTool,MoralisService,NFC_AGENT_TOOL_NAMES,NFC_AMAZON_DEFAULT_DOMAIN,NFC_AMAZON_DOMAINS,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,NfcBuyTool,NfcInfoTool,OpenAddLiquidityFormTool,POOL_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PreviewAddLiquidityTool,RelayAdapter,Router,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapServiceFactory,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UpstashKnowledgeBase,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WalletActionAppTool,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletDefiSummaryTool,WalletHistoryTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustKeyringAgent,ZERO_ADDRESS,amazonDomainForLanguage,apiClient,buildChallenge,buildRangePresets,buildUniswapPoolUrl,clampTick,completeX402,configureSupportedChains,createAiAgent,createDefaultSubagents,createNfcAgent,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletActionAppTools,createWalletAgent,createX402SignatureProvider,displayFromChallenge,encodeSignedHeader,ethCallAt,ethCallByChain,fetchTopMarketplaces,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getGatewayChains,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,isAbortError,nfcAmazonSearchUrl,normaliseCountry,normalizePriceRangeToPool,priceToTick,requestWithX402,resolveNfcShopLinks,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});
1182
+ ${$s}`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:o=$s,maxRetries:s=2,maxOutputTokens:i}=t,l=Date.now(),c=[{role:"system",content:o,timestamp:l},{role:"user",content:e,timestamp:l}],d=await this.llm.chat(c,void 0,{googleSearch:r,maxRetries:s,maxOutputTokens:i,signal:n}),u=this.parseJson(d.text?.trim()??"");return this.debug&&!u&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(d.text??"").slice(0,200)),u}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(t).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(t=>t.startsWith("xn--")?this.punycodeDecodeLabel(t.slice(4)):t).join("."):e}punycodeDecodeLabel(e){let c=(u,p,m)=>{u=m?Math.floor(u/700):u>>1,u+=Math.floor(u/p);let f=0;for(;u>455;)u=Math.floor(u/35),f+=36;return f+Math.floor(36*u/(u+38))},d=u=>u-48<10?u-22:u-65<26?u-65:u-97<26?u-97:36;try{let u=[],p=e.lastIndexOf("-");for(let y=0;y<Math.max(0,p);y++){let b=e.charCodeAt(y);if(b>=128)return e;u.push(b)}let m=0,f=128,h=72,g=p<0?0:p+1;for(;g<e.length;){let y=m,b=1;for(let k=36;;k+=36){if(g>=e.length)return e;let T=d(e.charCodeAt(g++));if(T>=36)return e;m+=T*b;let A=k<=h?1:k>=h+26?26:k-h;if(T<A)break;b*=36-A}let w=u.length+1;h=c(m-y,w,y===0),f+=Math.floor(m/w),m%=w,u.splice(m,0,f),m++}return String.fromCodePoint(...u)}catch{return e}}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(t=>this.alnum(t)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let o=Array.from({length:r+1},(s,i)=>i);for(let s=1;s<=n;s++){let i=[s];for(let l=1;l<=r;l++){let c=e[s-1]===t[l-1]?0:1;i[l]=Math.min(o[l]+1,i[l-1]+1,o[l-1]+c)}o=i}return o[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let o=this.hostLabels(e);return[t?this.brandCore(t):"",this.alnum(n??"")].filter(i=>i.length>=4).some(i=>r.includes(i)||o.some(l=>this.isNearMiss(l,i)))}looksLikeSquatOf(e,t){if(this.isSameRegistrableDomain(e,t))return!1;let n=this.brandCore(t);if(n.length<4)return!1;let r=this.hostLabels(e);return r.includes(n)?!1:r.some(o=>this.isNearMiss(o,n)||o.length>n.length&&o.includes(n))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),s=r.lastIndexOf(".");if(o>0&&s>0){let c=n.slice(0,o),d=r.slice(0,s),u=n.slice(o+1),p=r.slice(s+1);if(c===d&&u!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${u}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.brandCore(r),l=this.hostLabels(n).find(c=>this.isNearMiss(c,i));if(l){let c=this.editDistance(l,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let o=this.coerceToStr(r);o&&n.push(o)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let t=e,n=this.cleanStr(t.feature)??this.cleanStr(t.name)??this.cleanStr(t.title),r=this.cleanStr(t.description)??this.cleanStr(t.detail)??this.cleanStr(t.text)??this.cleanStr(t.value);return n&&r?n===r?n:`${n} \u2014 ${r}`:n||r?n??r:Object.values(t).map(s=>this.cleanStr(s)).filter(s=>!!s).join(" \u2014 ")||void 0}dedupe(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}};var jl=a=>{let e=JSON.parse(a),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((n,r)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${r} is missing "question" or "answer"`);return n})};async function Vs(a,e){let t=a.entries??(a.json?jl(a.json):[]);return t.length===0?{count:0}:new Ze(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseNftMessageTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,ManageLiquidityRedirectTool,MoralisService,NFC_AGENT_TOOL_NAMES,NFC_AMAZON_DEFAULT_DOMAIN,NFC_AMAZON_DOMAINS,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,NfcBuyTool,NfcInfoTool,OpenAddLiquidityFormTool,POOL_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PreviewAddLiquidityTool,RelayAdapter,Router,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapServiceFactory,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UpstashKnowledgeBase,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WalletActionAppTool,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletDefiSummaryTool,WalletHistoryTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustKeyringAgent,ZERO_ADDRESS,amazonDomainForLanguage,apiClient,buildChallenge,buildRangePresets,buildUniswapPoolUrl,clampTick,completeX402,configureSupportedChains,createAiAgent,createDefaultSubagents,createNfcAgent,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletActionAppTools,createWalletAgent,createX402SignatureProvider,displayFromChallenge,encodeSignedHeader,ethCallAt,ethCallByChain,fetchTopMarketplaces,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getGatewayChains,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,isAbortError,nfcAmazonSearchUrl,normaliseCountry,normalizePriceRangeToPool,priceToTick,requestWithX402,resolveNfcShopLinks,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});
@@ -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=po(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&mm.assertOptions(n,{silentJSONParsing:Ai.transitional(Ai.boolean),forcedJSONParsing:Ai.transitional(Ai.boolean),clarifyTimeoutError:Ai.transitional(Ai.boolean),legacyInterceptorReqResOrdering:Ai.transitional(Ai.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:mm.assertOptions(i,{encode:Ai.function,serialize:Ai.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),mm.assertOptions(r,{baseUrl:Ai.spelling("baseURL"),withXsrfToken:Ai.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&j.merge(o.common,o[r.method]);o&&j.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=hr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||_d;_&&_.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=[Qb.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=Qb.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=po(this.defaults,e);let r=hm(e.baseURL,e.url,e.allowAbsoluteUrls);return cm(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){Td.prototype[e]=function(r,n){return this.request(po(n||{},{method:e,url:r,data:(n||{}).data}))}});j.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(po(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Td.prototype[e]=r(),e!=="query"&&(Td.prototype[e+"Form"]=r(!0))});var gm=Td;p();var cA=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new jo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},fU=cA;p();function dA(t){return function(r){return t.apply(null,r)}}p();function pA(t){return j.isObject(t)&&t.isAxiosError===!0}p();var fA={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(fA).forEach(([t,e])=>{fA[e]=t});var hU=fA;function mU(t){let e=new gm(t),r=om(gm.prototype.request,e);return j.extend(r,gm.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return mU(po(t,i))},r}var kr=mU(vd);kr.Axios=gm;kr.CanceledError=jo;kr.CancelToken=fU;kr.isCancel=pm;kr.VERSION=Sd;kr.toFormData=gl;kr.AxiosError=Me;kr.Cancel=kr.CanceledError;kr.all=function(e){return Promise.all(e)};kr.spread=dA;kr.isAxiosError=pA;kr.mergeConfig=po;kr.AxiosHeaders=hr;kr.formToJSON=t=>Kb(j.isHTMLForm(t)?new FormData(t):t);kr.getAdapter=Xb.getAdapter;kr.HttpStatusCode=hU;kr.default=kr;var tv=kr;var{Axios:lVe,AxiosError:uVe,CanceledError:cVe,isCancel:dVe,CancelToken:pVe,VERSION:fVe,all:hVe,Cancel:mVe,isAxiosError:gVe,spread:yVe,toFormData:_Ve,AxiosHeaders:bVe,HttpStatusCode:vVe,formToJSON:wVe,getAdapter:SVe,mergeConfig:TVe,create:kVe}=tv;var gU="0.2.41";var iQ=`keyring-agent-core/${gU} (Keyring Chatbot Agent; +https://keyring.app)`,oQ="payment-required",hA=null;function yU(t){hA=t}function aQ(t){return t?Object.keys(t).some(e=>e.toLowerCase()==="payment-signature"):!1}var _U;function ym(t){_U=t}var sQ=3e4,lQ=typeof process<"u"&&process.versions?.node!=null,mA=class{constructor(e={}){f(this,"instance");this.instance=tv.create({baseURL:e.baseURL,timeout:e.timeout??sQ,validateStatus:()=>!0,headers:{Accept:"application/json",...lQ?{"User-Agent":e.userAgent??iQ}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??_U,a=await this.instance.request({...i,signal:o,method:e,url:r,data:n}),s={};for(let[u,c]of Object.entries(a.headers??{}))c!=null&&(s[u.toLowerCase()]=String(c));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:s};if(l.status===402&&l.headers[oQ]&&hA&&!aQ(i.headers)){let u=await hA(l,{url:r,method:String(e),body:n,headers:i.headers});if(u)return this.request(e,r,n,{...i,headers:{...i.headers,...u}})}return l}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},De=new mA;function nt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}var uQ={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},bU="payment-required",cQ="PAYMENT-SIGNATURE";function dQ(t){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(t,"utf8").toString("base64")}function pQ(t){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(t,"base64").toString("utf8")}function fQ(){let t=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<32;r++)t[r]=Math.floor(Math.random()*256);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function hQ(t){let[e,r]=String(t).split(":"),n=parseInt(r,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${t}`);return n}function vU(t){if(!t.query||Object.keys(t.query).length===0)return t.url;let e=Object.entries(t.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return t.url.includes("?")?`${t.url}&${e}`:`${t.url}?${e}`}function wU(t){return JSON.parse(pQ(t))}function gA(t,e,r,n){let i=t.headers[bU];if(!i)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=wU(i),a=o.accepts?.[0];if(!a)throw new Error("402 response offered no payment requirements");if(a.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${a.scheme} (only "exact" is supported)`);if(!r)throw new Error("No connected wallet address to build the payment from");let s=hQ(a.network),l=Math.floor(Date.now()/1e3),u={from:r,to:a.payTo,value:String(a.amount),validAfter:"0",validBefore:String(l+(a.maxTimeoutSeconds??300)),nonce:fQ()},c={domain:{name:a.extra?.name,version:a.extra?.version,chainId:s,verifyingContract:a.asset},types:uQ,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:vU(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:a,authorization:u,typedData:c,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:u},resource:o.resource,accepted:a,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function mQ(t,e,r,n){let i=vU(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:gA(o,e,r,n)};if(!o.ok)throw new Error(nt(o));return{status:"ok",data:o.data}}async function yA(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},..._A(e,r)}});if(s.ok)return s.data;let l=s.headers[bU];if(l)try{let u=wU(l);if(u.error)throw new Error(`x402 payment rejected: ${u.error}`)}catch(u){if(u instanceof Error&&u.message.startsWith("x402 payment rejected"))throw u}throw new Error(nt(s))}var gQ={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function _A(t,e){let r={...t.paymentDraft,payload:{authorization:t.authorization,signature:e}};return{[cQ]:dQ(JSON.stringify(r))}}function SU(t){let e=t.requirements,r=t.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:gQ[e.network]||e.network,payTo:e.payTo,...r?.description?{description:r.description}:{},resourceUrl:t.request.url}}function bA(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=gA(e,{url:r.url,method:r.method,body:r.body,headers:r.headers},n)}catch{return null}let a;try{a=await i({typedData:o.typedData,display:SU(o)})}catch{a=null}return a?_A(o,a):null}}p();p();var yl=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Gu(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function _m(t){if(t?.aborted)throw new yl}function vA(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 TU={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},yQ="https://nft.keyring.app/api/gemini-stable",_Q=new Set([408,429,500,502,503,504]),kU=3e4,rv=t=>new Promise(e=>setTimeout(e,t));function nv(t,e,r){if(r!=null&&r>0)return Math.min(r,kU);let n=Math.min(e*2**(t-1),kU);return n/2+Math.random()*(n/2)}function bQ(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pr=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??yQ}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;_m(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:n?.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++){_m(l);let g;try{g=await De.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(Gu(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await rv(nv(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}`,!_Q.has(g.status))throw new Error(h);if(m>=a)break;let N=bQ(g.headers["retry-after"]??null);await rv(nv(m,s,N));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await rv(nv(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 rv(nv(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=po(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&mm.assertOptions(n,{silentJSONParsing:Ai.transitional(Ai.boolean),forcedJSONParsing:Ai.transitional(Ai.boolean),clarifyTimeoutError:Ai.transitional(Ai.boolean),legacyInterceptorReqResOrdering:Ai.transitional(Ai.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:mm.assertOptions(i,{encode:Ai.function,serialize:Ai.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),mm.assertOptions(r,{baseUrl:Ai.spelling("baseURL"),withXsrfToken:Ai.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&j.merge(o.common,o[r.method]);o&&j.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=hr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||_d;_&&_.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=[Qb.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=Qb.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=po(this.defaults,e);let r=hm(e.baseURL,e.url,e.allowAbsoluteUrls);return cm(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){Td.prototype[e]=function(r,n){return this.request(po(n||{},{method:e,url:r,data:(n||{}).data}))}});j.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(po(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Td.prototype[e]=r(),e!=="query"&&(Td.prototype[e+"Form"]=r(!0))});var gm=Td;p();var cA=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new jo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},fU=cA;p();function dA(t){return function(r){return t.apply(null,r)}}p();function pA(t){return j.isObject(t)&&t.isAxiosError===!0}p();var fA={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(fA).forEach(([t,e])=>{fA[e]=t});var hU=fA;function mU(t){let e=new gm(t),r=om(gm.prototype.request,e);return j.extend(r,gm.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return mU(po(t,i))},r}var kr=mU(vd);kr.Axios=gm;kr.CanceledError=jo;kr.CancelToken=fU;kr.isCancel=pm;kr.VERSION=Sd;kr.toFormData=gl;kr.AxiosError=Me;kr.Cancel=kr.CanceledError;kr.all=function(e){return Promise.all(e)};kr.spread=dA;kr.isAxiosError=pA;kr.mergeConfig=po;kr.AxiosHeaders=hr;kr.formToJSON=t=>Kb(j.isHTMLForm(t)?new FormData(t):t);kr.getAdapter=Xb.getAdapter;kr.HttpStatusCode=hU;kr.default=kr;var tv=kr;var{Axios:lVe,AxiosError:uVe,CanceledError:cVe,isCancel:dVe,CancelToken:pVe,VERSION:fVe,all:hVe,Cancel:mVe,isAxiosError:gVe,spread:yVe,toFormData:_Ve,AxiosHeaders:bVe,HttpStatusCode:vVe,formToJSON:wVe,getAdapter:SVe,mergeConfig:TVe,create:kVe}=tv;var gU="0.2.42";var iQ=`keyring-agent-core/${gU} (Keyring Chatbot Agent; +https://keyring.app)`,oQ="payment-required",hA=null;function yU(t){hA=t}function aQ(t){return t?Object.keys(t).some(e=>e.toLowerCase()==="payment-signature"):!1}var _U;function ym(t){_U=t}var sQ=3e4,lQ=typeof process<"u"&&process.versions?.node!=null,mA=class{constructor(e={}){f(this,"instance");this.instance=tv.create({baseURL:e.baseURL,timeout:e.timeout??sQ,validateStatus:()=>!0,headers:{Accept:"application/json",...lQ?{"User-Agent":e.userAgent??iQ}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??_U,a=await this.instance.request({...i,signal:o,method:e,url:r,data:n}),s={};for(let[u,c]of Object.entries(a.headers??{}))c!=null&&(s[u.toLowerCase()]=String(c));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:s};if(l.status===402&&l.headers[oQ]&&hA&&!aQ(i.headers)){let u=await hA(l,{url:r,method:String(e),body:n,headers:i.headers});if(u)return this.request(e,r,n,{...i,headers:{...i.headers,...u}})}return l}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},De=new mA;function nt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}var uQ={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},bU="payment-required",cQ="PAYMENT-SIGNATURE";function dQ(t){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(t,"utf8").toString("base64")}function pQ(t){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(t,"base64").toString("utf8")}function fQ(){let t=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<32;r++)t[r]=Math.floor(Math.random()*256);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function hQ(t){let[e,r]=String(t).split(":"),n=parseInt(r,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${t}`);return n}function vU(t){if(!t.query||Object.keys(t.query).length===0)return t.url;let e=Object.entries(t.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return t.url.includes("?")?`${t.url}&${e}`:`${t.url}?${e}`}function wU(t){return JSON.parse(pQ(t))}function gA(t,e,r,n){let i=t.headers[bU];if(!i)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=wU(i),a=o.accepts?.[0];if(!a)throw new Error("402 response offered no payment requirements");if(a.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${a.scheme} (only "exact" is supported)`);if(!r)throw new Error("No connected wallet address to build the payment from");let s=hQ(a.network),l=Math.floor(Date.now()/1e3),u={from:r,to:a.payTo,value:String(a.amount),validAfter:"0",validBefore:String(l+(a.maxTimeoutSeconds??300)),nonce:fQ()},c={domain:{name:a.extra?.name,version:a.extra?.version,chainId:s,verifyingContract:a.asset},types:uQ,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:vU(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:a,authorization:u,typedData:c,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:u},resource:o.resource,accepted:a,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function mQ(t,e,r,n){let i=vU(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:gA(o,e,r,n)};if(!o.ok)throw new Error(nt(o));return{status:"ok",data:o.data}}async function yA(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},..._A(e,r)}});if(s.ok)return s.data;let l=s.headers[bU];if(l)try{let u=wU(l);if(u.error)throw new Error(`x402 payment rejected: ${u.error}`)}catch(u){if(u instanceof Error&&u.message.startsWith("x402 payment rejected"))throw u}throw new Error(nt(s))}var gQ={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function _A(t,e){let r={...t.paymentDraft,payload:{authorization:t.authorization,signature:e}};return{[cQ]:dQ(JSON.stringify(r))}}function SU(t){let e=t.requirements,r=t.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:gQ[e.network]||e.network,payTo:e.payTo,...r?.description?{description:r.description}:{},resourceUrl:t.request.url}}function bA(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=gA(e,{url:r.url,method:r.method,body:r.body,headers:r.headers},n)}catch{return null}let a;try{a=await i({typedData:o.typedData,display:SU(o)})}catch{a=null}return a?_A(o,a):null}}p();p();var yl=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Gu(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function _m(t){if(t?.aborted)throw new yl}function vA(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 TU={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},yQ="https://nft.keyring.app/api/gemini-stable",_Q=new Set([408,429,500,502,503,504]),kU=3e4,rv=t=>new Promise(e=>setTimeout(e,t));function nv(t,e,r){if(r!=null&&r>0)return Math.min(r,kU);let n=Math.min(e*2**(t-1),kU);return n/2+Math.random()*(n/2)}function bQ(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pr=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??yQ}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;_m(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:n?.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++){_m(l);let g;try{g=await De.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(Gu(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await rv(nv(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}`,!_Q.has(g.status))throw new Error(h);if(m>=a)break;let N=bQ(g.headers["retry-after"]??null);await rv(nv(m,s,N));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await rv(nv(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 rv(nv(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:TU[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:TU[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 kd=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 Pd=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],vQ=new Set(Pd),_l=[...Pd],wA=new Set(_l),Ci="0x1",Ad="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function wQ(t){return t.map(e=>Ed[e]??e).join(", ")}function iv(t){let e=new Set;if(t)for(let n of t){let i=ov(n);i&&e.add(i)}let r=Pd.filter(n=>!e.has(n));_l=r.length>0?[...r]:[...Pd],wA=new Set(_l),Ci=_l.includes("0x1")?"0x1":_l[0],Ad=wQ(_l)}var SQ={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function tr(t){let e=ov(t);return e&&wA.has(e)?e:null}function ov(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=SQ[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&&vQ.has(n)?n:null}function fo(t){return tr(t)!==null}function xi(){return[..._l]}var vl=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Ad}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},bl=t=>typeof t=="string"&&t.trim()!=="";function Fn(t,e){if(bl(t)){let r=tr(t);if(r)return r;throw new vl(t.trim())}if(bl(e?.chain)){let r=tr(e.chain);if(r)return r;throw new vl(e.chain.trim())}return null}function av(t,e){return tr(t)??tr(e?.chain)??void 0}var Ed={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function Ce(t){let e=ov(t);return e&&Ed[e]?Ed[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var TQ={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function PU(t,e){let r=ov(t),n=r?TQ[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var kQ={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function EU(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?kQ[e]??null:null}var PQ={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function AU(t){let e=tr(t);return e?PQ[e]??null:null}function Cd(t,e){if(!bl(t))return null;let r=tr(t),n=tr(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:Ed[r]??r,connectedLabel:Ed[n]??n}}function CU(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>wA.has(o)):[];return(n.length?n:_l).map(o=>{let a=Ed[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function xd(t,e){return{actionButtons:CU(e),_instructions:`The user wants to ${t} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var mr=class extends Error{constructor(r,n){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");f(this,"code","needs_chain_selection");f(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=CU(r,n)}},bm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");f(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function Er(t,e){if(bl(t))return t.trim();if(bl(e?.walletAddress))return e.walletAddress.trim();throw new bm}function Lr(t,e,r){if(bl(t)){let n=tr(t);if(n)return n;throw new vl(t.trim())}if(bl(e?.chain)){let n=tr(e.chain);if(n)return n;throw new vl(e.chain.trim())}if(bl(e?.walletAddress))throw new mr(typeof e?.query=="string"?e.query:void 0,r);return Ci}var oe=class{constructor(){f(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=EQ(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{}}}catch(o){return o instanceof mr?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-i,actionButtons:o.buttons}:o instanceof bm?{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 EQ(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 xU=db(lv());function Bt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function AQ(t){return new Uint8Array(xU.keccak256.arrayBuffer(t))}function vm(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 IU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function OU(t){return new TextEncoder().encode(t)}function Wu(...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 CQ(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function xQ(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function RU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return vm(e)}function wm(t){return RU(BigInt(t))}function NU(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 $U(t){let e=NU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map($U).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function IQ(t){let e=(t.inputs??[]).map($U).join(",");return`${t.name??""}(${e})`}function SA(t,e){let r=NQ(t.type);if(r){let[i,o]=r;return OQ({...t,type:o},e,i)}if(t.type==="tuple")return RQ(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:CQ(vm(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=NU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:wm(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:RU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?vm(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:xQ(o)}}if(n==="bytes"){let i=typeof e=="string"?vm(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Wu(wm(i.length),a)}}if(n==="string"){let i=typeof e=="string"?OU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Wu(wm(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function TA(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(wm(e+i)),n.push(a),i+=a.length):r.push(a);return Wu(...r,...n)}function OQ(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=SA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=TA(o);if(n){let s=wm(o.length);return{dynamic:!0,encoded:o.length>0?Wu(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:Wu(...o.map(a=>a.encoded))}}function RQ(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=SA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?TA(i):Wu(...i.map(o=>o.encoded))}}function NQ(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function $Q(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)=>SA(i,e[o])),n=TA(r);return IU(n)}function Id({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=IQ(n),o=AQ(OU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):vm($Q(a,r).slice(2));return IU(Wu(o,s))}p();var MQ="https://wallet-api.pantograph.app",DQ="0x0000000000000000000000000000000000000000",UU={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},LU={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function UQ(t){return UU[t.toLowerCase()]||t}function MU(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 kA(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 PA(t){if(Array.isArray(t))return t;let e=t;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Sn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function DU(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=Sn(t.price_change_percentage_24h)??Sn(t.priceChange24h)??Sn(t.usd_price_24hr_percent_change)??Sn(t.price_change_24h)??Sn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:Sn(t.price)??Sn(t.usd_price),marketCap:Sn(t.market_cap)??Sn(t.marketCap),totalVolume:{"24h":Sn(t.total_volume)??Sn(t.volume24h)},pricePercentChange:{"24h":i}}}var Tn=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??MQ).replace(/\/+$/,"")}tokensUrl(e,r){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),i=this.tokensUrl(r,n),o=await De.get(i);if(!o.ok)return;let a=PA(o.data),s=new Map;for(let l of a)l.address&&s.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let u=s.get(e[l].token_address.toLowerCase());u&&(u.icon_image&&(e[l].logo=u.icon_image,e[l].thumbnail=u.icon_image),isNaN(u.price)||(e[l].usd_price=u.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*u.price))}}catch{}}async getTokenMetadata(e,r){try{let n=this.tokensUrl(r,e),i=await De.get(n);if(!i.ok)return null;let o=PA(i.data),a=e.toLowerCase()===DQ,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?kA(s):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=this.tokensUrl(r,e.join(",")),o=await De.get(i);if(!o.ok)return n;let a=PA(o.data),s=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let u=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);u&&s.has(u)&&(n[u]=kA(l))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ci,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=MU({chainId:o,key:r}),s=`${this.baseUrl}/token-list/all?${a}`,l=await De.get(s);if(!l.ok)throw new Error(nt(l));let u=l.data,c=u?.result??u?.data??u,d=[];return Array.isArray(c)?d=c:c&&typeof c=="object"&&(d=Object.values(c).flat()),{success:!0,data:d.map(kA)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ci,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=LU[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=>DU(y,r)):[],d=new Set,h=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...h,...m].slice(0,i):[...h,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=Sn(a.market_cap)??Sn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":Sn(a.total_volume)??Sn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=parseInt(e,16),o=MU({chainId:i,duration:n,limit:r}),a=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,s=[];for(let l=0;l<5;l++){let u=await De.get(a);if(!u.ok)throw new Error(nt(u));let c=u.data;if(s=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>DU(l,e))}async getTopGainers(e){let r=e?.chain||Ci,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var LQ="https://nft.keyring.app",qQ="https://nft.keyring.app",jQ=.01,et=5,ir=1e3,FQ="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",BQ="0x0000000000000000000000000000000000000000",tt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function gr(t){return t||Ci}function or(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ar(t){return new Promise(e=>setTimeout(e,t))}function zQ(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 EA(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??LQ).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??qQ).replace(/\/+$/,""),this.pantograph=new Tn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=gr(n),l="Unknown error";for(let u=1;u<=et;u++)try{let c={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(c.token_addresses=i);let d=[],h=null;do{h&&(c.cursor=h);let g=or(c),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),h=w?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===FQ?BQ:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=jQ)),{success:!0,data:m}}catch(c){if(l=c instanceof Error?c.message:"Unknown error",c instanceof tt&&c.status===400)break;u<et&&await ar(ir)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=gr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=et;s++)try{let[l,u]=await Promise.allSettled([De.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${or({chain:i,addresses:[r]})}`),De.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${or({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;c=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!c){o="Token metadata not found",s<et&&await ar(ir);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let h=u.value.data;d=h?.data??h}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:o=!0,cursor:a,tokenAddresses:s,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=gr(n),d="Unknown error";for(let h=1;h<=et;h++)try{let m={chain:c,format:u,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(m.cursor=a),l&&(m.include_prices=!0),s&&s.length>0&&(m.token_addresses=s);let g=or(m),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data;return{success:!0,data:b?.data??b}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof tt&&m.status===400)break;h<et&&await ar(ir)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!Bt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=gr(i),c="Unknown error";for(let d=1;d<=et;d++)try{let h={chain:u,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=or(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await De.get(g);if(!y.ok)throw new tt(y.status,nt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(c=h instanceof Error?h.message:"Unknown error",h instanceof tt&&h.status===400)break;d<et&&await ar(ir)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=gr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=et;_++)try{let b={chain:m,limit:g,order:c};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),u&&(b.cursor=u),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let w=or(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await De.get(T);if(!E.ok)throw new tt(E.status,nt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof tt&&b.status===400)break;_<et&&await ar(ir)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=gr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=et;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),u!=null&&(_.to_block=u),c&&(_.cursor=c),i?.length&&(_.contract_addresses=i);let b=or(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await De.get(w);if(!T.ok)throw new tt(T.status,nt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof tt&&_.status===400)break;y<et&&await ar(ir)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=gr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=et;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),u!=null&&(w.to_block=u),c&&(w.cursor=c),i?.length&&(w.contract_addresses=i),h!=null&&(w.include_prices=h);let T=or(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await De.get(E);if(!C.ok)throw new tt(C.status,nt(C));let N=C.data;return{success:!0,data:N?.data??N}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof tt&&w.status===400)break;b<et&&await ar(ir)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Bt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=gr(n),a="Unknown error";for(let s=1;s<=et;s++)try{let l={chain:o};i&&(l.days=i);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data;return{success:!0,data:h?.data??h}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i&&(u.days=i),o&&o.length>0&&(u.token_addresses=o.slice(0,25));let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i!=null&&(u.limit=i),o&&(u.cursor=o);let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:zQ(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=gr(i),a="Unknown error";for(let s=1;s<=et;s++)try{let l=or({chains:o}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await De.get(u);if(!c.ok)throw new tt(c.status,nt(c));let m=c.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=et;o++)try{let a={};r&&(a.chain=gr(r)),n!=null&&(a.limit=n);let s=or(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:EA(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof tt&&a.status===400)break;o<et&&await ar(ir)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:EA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:EA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Od=class extends oe{constructor(r){super();f(this,"name","get-token-info");f(this,"description",'Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad');f(this,"category","blockchain-data");f(this,"parameters",[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}]);f(this,"service");f(this,"llm");this.service=new pt(r),this.llm=new Pr(r?.llm??{})}async run(r,n){let i=r.keyword||"",o=r.prompt||"",a=n?.walletAddress||void 0;if(!i)return{error:"Missing required parameter: keyword"};let s;try{s=Lr(r.chain,n)}catch(l){if(l instanceof vl)return await this.researchTokenChainAgnostic(i,o,a);throw l}return await this.searchToken(i,s,o,a)}async researchTokenChainAgnostic(r,n,i){let o=[i?`User's connected wallet address: ${i}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
442
442
  `),a=n?await this.askGeminiWithSearch(n,o):null;return{_instructions:'The token info comes from web research only (the user is on a chain this app does not support on-chain). Present a clear summary of the token using the research: what it is, current USD price and 24h change, market data, recent news and the catalyst behind any price move, and a brief, clearly-hedged sense of market direction (no financial advice). Do NOT add a labelled "AI Analysis" heading and do NOT mention that the analysis came from AI \u2014 write it as a normal token summary. If a field is unknown, omit it. Do NOT mention chains, tools, or that anything is unsupported; just answer the question.',keyword:r,token:null,userHoldsToken:!1,research:a}}async searchToken(r,n,i,o){let a=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
443
443
  `),[s,l,u]=await Promise.all([this.service.searchTokensByKey({key:r,chain:n}),o?this.findTokenInWallet(o,n,r):Promise.resolve(null),i?this.askGeminiWithSearch(i,a):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],d=r.toLowerCase(),h=b=>b.symbol?.toLowerCase()===d||b.token_address?.toLowerCase()===d,m=[...c].sort((b,w)=>(h(b)?0:1)-(h(w)?0:1)),g=null,y=m[0];if(y?.token_address){let b=await this.service.getTokenMetadata({address:y.token_address,chain:n});b.success&&b.data&&(g=b.data)}return!g&&y&&(g={...y}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:n,userHoldsToken:!!l,walletBalance:l,token:g,...c.length>1?{searchResults:m.slice(0,10)}:{},research:u}}async askGeminiWithSearch(r,n){let i=Date.now();try{return(await this.llm.chat([...n?[{role:"system",content:n,timestamp:i}]:[],{role:"user",content:r,timestamp:i}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(r,n,i){if(!i)return null;let o=await this.service.getWalletTokenBalances({address:r,chain:n,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!o.success||!o.data?.result)return null;let a=i.toLowerCase(),s=o.data.result.find(l=>l.token_address.toLowerCase()===a||l.symbol?.toLowerCase()===a||l.name?.toLowerCase().includes(a));return s||null}};p();var Rd=class extends oe{constructor(r){super();f(this,"name","get-token-holders");f(this,"description",'Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ');f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenHolders({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Nd=class extends oe{constructor(r){super();f(this,"name","get-token-analytics");f(this,"description",`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenAnalytics({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var $d=class extends oe{constructor(r){super();f(this,"name","get-token-score");f(this,"description",`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let m=await this.resolveContractAddress(a,i,o);if(!m)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,l=m.symbol,u=m.name}let c=await this.service.getTokenScore({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},h=d.metrics??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:h.usdPrice??null,liquidityUsd:h.liquidityUsd??null,volumeUsd:h.volumeUsd??null,transactions:h.transactions??null,supply:h.supply??null}}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Md=class extends oe{constructor(r){super();f(this,"name","get-trending-tokens");f(this,"description",'List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad, and more.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1}]);f(this,"service");this.service=new Tn({baseUrl:r?.pantographUrl})}async run(r,n){let i=av(r.chain,n),o=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.floor(r.limit):void 0,a=await this.service.getTrendingTokens({chain:i,limit:o});if(!a.success)return{error:a.error||"Failed to fetch trending tokens"};let s=a.data??[];return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
@@ -1590,13 +1590,13 @@ Return ONLY this JSON:
1590
1590
  "hasOwnLegitPresence": boolean, // does THIS exact domain have its own legitimate presence?
1591
1591
  "impersonationEvidence": string[], // >=3 specific points if impersonating; [] otherwise
1592
1592
  "scamReports": string[] // SOURCED findings (each with a markdown-link source) accusing THIS exact domain; [] if none/unsourced
1593
- }`,o=await this.askJson(i,{signal:n,maxRetries:3,system:this.gatherSystem()});return{description:this.cleanStr(o?.description)??"",keyFeatures:this.cleanStrArray(o?.keyFeatures),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}
1593
+ }`,o=await this.askJson(i,{signal:n,maxRetries:3,system:this.gatherSystem(),maxOutputTokens:1536});return{description:this.cleanStr(o?.description)??"",keyFeatures:this.cleanStrArray(o?.keyFeatures),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}
1594
1594
  Using web search, describe what this website / platform is and what it does \u2014 its Web3 category (DeFi, DEX, NFT, bridge, wallet, etc.) and blockchain(s) when identifiable, its purpose, and who runs it. Also list 3-5 concrete FEATURES it offers; for EACH, write a full informative sentence naming the feature and what the user can do with it \u2014 NOT one-word labels.
1595
1595
 
1596
- Return ONLY this JSON: { "description": string, "keyFeatures": string[] } // description: 1-3 concise sentences`,i=await this.askJson(n,{signal:r,maxRetries:3,system:this.gatherSystem()});return{description:this.cleanStr(i?.description)??"",keyFeatures:this.cleanStrArray(i?.keyFeatures)}}async gatherKeyFeatures(e,r){let n=`Website: ${e}
1596
+ Return ONLY this JSON: { "description": string, "keyFeatures": string[] } // description: 1-3 concise sentences`,i=await this.askJson(n,{signal:r,maxRetries:3,system:this.gatherSystem(),maxOutputTokens:1024});return{description:this.cleanStr(i?.description)??"",keyFeatures:this.cleanStrArray(i?.keyFeatures)}}async gatherKeyFeatures(e,r){let n=`Website: ${e}
1597
1597
  Using web search, list 3-5 concrete FEATURES this site offers. For EACH, write a full, informative sentence naming the feature AND what the user can do with it (its Web3 actions: swap, bridge, stake, mint, lend, etc.) \u2014 NOT one-word labels, NOT generic filler.
1598
1598
 
1599
- Return ONLY this JSON: { "keyFeatures": string[] } // an array of full-sentence strings`,i=await this.askJson(n,{signal:r,maxRetries:2,system:this.gatherSystem()});return this.cleanStrArray(i?.keyFeatures)}async present(e,r,n,i){let o=this.languageLabel(n),a=!r.isPhishing&&r.keyFeatures.length>0,l=`Here is a COMPLETED web-security assessment (facts only \u2014 do not re-investigate):
1599
+ Return ONLY this JSON: { "keyFeatures": string[] } // an array of full-sentence strings`,i=await this.askJson(n,{signal:r,maxRetries:2,system:this.gatherSystem(),maxOutputTokens:768});return this.cleanStrArray(i?.keyFeatures)}async present(e,r,n,i){let o=this.languageLabel(n),a=!r.isPhishing&&r.keyFeatures.length>0,l=`Here is a COMPLETED web-security assessment (facts only \u2014 do not re-investigate):
1600
1600
  ${[`Website: ${e}`,`Assessment: ${r.isPhishing?"shows signs of a phishing / look-alike / scam site":"no phishing or scam signals found"}`,r.copiedSite?`Impersonates: ${r.copiedSite}`:"",`What the site is: ${r.description||"(could not be determined)"}`,a?`Features:
1601
1601
  ${r.keyFeatures.map((m,g)=>`${g+1}. ${m}`).join(`
1602
1602
  `)}`:"",r.reasons.length?`Evidence:
@@ -1616,9 +1616,9 @@ Write the user-facing result for a NON-TECHNICAL user:
1616
1616
 
1617
1617
  LANGUAGE (MANDATORY): write "answer", every "reasons" item AND every "keyFeatures" item ENTIRELY in ${o}. The facts above are in English ONLY as source material \u2014 your output prose MUST be in ${o}, not English (unless ${o} itself is English). Only domain names, URLs, markdown links and brand names stay verbatim.
1618
1618
 
1619
- Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,u=await this.askJson(l,{signal:i,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2}),c=this.cleanStr(u?.answer)??(r.description||e),d=this.cleanStrArray(u?.reasons),h=this.cleanStrArray(u?.keyFeatures);return{answer:c,reasons:d.length>0?d.slice(0,5):r.reasons.slice(0,5),keyFeatures:a?(h.length>0?h:r.keyFeatures).slice(0,5):[]}}languageLabel(e){let r={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return r[n]??r[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
1619
+ Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,u=await this.askJson(l,{signal:i,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2,maxOutputTokens:1536}),c=this.cleanStr(u?.answer)??(r.description||e),d=this.cleanStrArray(u?.reasons),h=this.cleanStrArray(u?.keyFeatures);return{answer:c,reasons:d.length>0?d.slice(0,5):r.reasons.slice(0,5),keyFeatures:a?(h.length>0?h:r.keyFeatures).slice(0,5):[]}}languageLabel(e){let r={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return r[n]??r[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
1620
1620
 
1621
- ${QY}`}async askJson(e,r={}){let{signal:n,googleSearch:i=!0,system:o=QY,maxRetries:a=2}=r,s=Date.now(),l=[{role:"system",content:o,timestamp:s},{role:"user",content:e,timestamp:s}],u=await this.llm.chat(l,void 0,{googleSearch:i,maxRetries:a,signal:n}),c=this.parseJson(u.text?.trim()??"");return this.debug&&!c&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(u.text??"").slice(0,200)),c}normalizeSite(e){try{let r=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(r).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(r=>r.startsWith("xn--")?this.punycodeDecodeLabel(r.slice(4)):r).join("."):e}punycodeDecodeLabel(e){let u=(d,h,m)=>{d=m?Math.floor(d/700):d>>1,d+=Math.floor(d/h);let g=0;for(;d>455;)d=Math.floor(d/35),g+=36;return g+Math.floor(36*d/(d+38))},c=d=>d-48<10?d-22:d-65<26?d-65:d-97<26?d-97:36;try{let d=[],h=e.lastIndexOf("-");for(let b=0;b<Math.max(0,h);b++){let w=e.charCodeAt(b);if(w>=128)return e;d.push(w)}let m=0,g=128,y=72,_=h<0?0:h+1;for(;_<e.length;){let b=m,w=1;for(let E=36;;E+=36){if(_>=e.length)return e;let C=c(e.charCodeAt(_++));if(C>=36)return e;m+=C*w;let N=E<=y?1:E>=y+26?26:E-y;if(C<N)break;w*=36-N}let T=d.length+1;y=u(m-b,T,b===0),g+=Math.floor(m/T),m%=T,d.splice(m,0,g),m++}return String.fromCodePoint(...d)}catch{return e}}isSameRegistrableDomain(e,r){let n=this.toHost(e),i=this.toHost(r);return!n||!i?!1:n===i||n.endsWith(`.${i}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(r=>this.alnum(r)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,r){let n=e.length,i=r.length;if(!n)return i;if(!i)return n;let o=Array.from({length:i+1},(a,s)=>s);for(let a=1;a<=n;a++){let s=[a];for(let l=1;l<=i;l++){let u=e[a-1]===r[l-1]?0:1;s[l]=Math.min(o[l]+1,s[l-1]+1,o[l-1]+u)}o=s}return o[i]}isNearMiss(e,r){if(!e||!r||e===r)return!1;let n=Math.max(e.length,r.length);if(n<4||Math.abs(e.length-r.length)>2)return!1;let i=this.editDistance(e,r);return i>=1&&i<=(n>=8?2:1)}carriesBrandName(e,r,n){let i=this.alnum(this.toHost(e));if(!i)return!1;let o=this.hostLabels(e);return[r?this.brandCore(r):"",this.alnum(n??"")].filter(s=>s.length>=4).some(s=>i.includes(s)||o.some(l=>this.isNearMiss(l,s)))}looksLikeSquatOf(e,r){if(this.isSameRegistrableDomain(e,r))return!1;let n=this.brandCore(r);if(n.length<4)return!1;let i=this.hostLabels(e);return i.includes(n)?!1:i.some(o=>this.isNearMiss(o,n)||o.length>n.length&&o.includes(n))}describeLookAlike(e,r){let n=this.toHost(e),i=this.toHost(r);if(!n||!i||n===i)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${i}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),a=i.lastIndexOf(".");if(o>0&&a>0){let u=n.slice(0,o),c=i.slice(0,a),d=n.slice(o+1),h=i.slice(a+1);if(u===c&&d!==h)return`The address keeps the official name but changes the ending from ".${h}" to ".${d}" (${n} vs ${i}) \u2014 a look-alike that is easy to miss at a glance.`}let s=this.brandCore(i),l=this.hostLabels(n).find(u=>this.isNearMiss(u,s));if(l){let u=this.editDistance(l,s);return`The address "${n}" is a near-copy of the official ${i} \u2014 its name differs by only ${u} letter${u>1?"s":""} ("${l}" vs "${s}"), a typo that is easy to overlook.`}if(s.length>=4&&this.alnum(n).includes(s))return`The address "${n}" reuses the "${s}" name with extra text added to look affiliated with the official ${i}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let r=e.replace(/```(?:json)?/gi,"").trim(),n=r.indexOf("{"),i=r.lastIndexOf("}");if(n===-1||i===-1||i<=n)return null;try{return JSON.parse(r.slice(n,i+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let r=e.trim();if(!r)return;let n=r.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return r}cleanStrArray(e){let r=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let i of r){let o=this.coerceToStr(i);o&&n.push(o)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let r=e,n=this.cleanStr(r.feature)??this.cleanStr(r.name)??this.cleanStr(r.title),i=this.cleanStr(r.description)??this.cleanStr(r.detail)??this.cleanStr(r.text)??this.cleanStr(r.value);return n&&i?n===i?n:`${n} \u2014 ${i}`:n||i?n??i:Object.values(r).map(a=>this.cleanStr(a)).filter(a=>!!a).join(" \u2014 ")||void 0}dedupe(e){let r=new Set,n=[];for(let i of e){let o=i.toLowerCase();r.has(o)||(r.add(o),n.push(i))}return n}};p();var Y4e=t=>{let e=JSON.parse(t),r=Array.isArray(e)?e:e?.entries;if(!Array.isArray(r))throw new Error("JSON must be an array or { entries: [...] }");return r.map((n,i)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${i} is missing "question" or "answer"`);return n})};async function eJ(t,e){let r=t.entries??(t.json?Y4e(t.json):[]);return r.length===0?{count:0}:new El(e).upsert(r)}
1621
+ ${QY}`}async askJson(e,r={}){let{signal:n,googleSearch:i=!0,system:o=QY,maxRetries:a=2,maxOutputTokens:s}=r,l=Date.now(),u=[{role:"system",content:o,timestamp:l},{role:"user",content:e,timestamp:l}],c=await this.llm.chat(u,void 0,{googleSearch:i,maxRetries:a,maxOutputTokens:s,signal:n}),d=this.parseJson(c.text?.trim()??"");return this.debug&&!d&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(c.text??"").slice(0,200)),d}normalizeSite(e){try{let r=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(r).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(r=>r.startsWith("xn--")?this.punycodeDecodeLabel(r.slice(4)):r).join("."):e}punycodeDecodeLabel(e){let u=(d,h,m)=>{d=m?Math.floor(d/700):d>>1,d+=Math.floor(d/h);let g=0;for(;d>455;)d=Math.floor(d/35),g+=36;return g+Math.floor(36*d/(d+38))},c=d=>d-48<10?d-22:d-65<26?d-65:d-97<26?d-97:36;try{let d=[],h=e.lastIndexOf("-");for(let b=0;b<Math.max(0,h);b++){let w=e.charCodeAt(b);if(w>=128)return e;d.push(w)}let m=0,g=128,y=72,_=h<0?0:h+1;for(;_<e.length;){let b=m,w=1;for(let E=36;;E+=36){if(_>=e.length)return e;let C=c(e.charCodeAt(_++));if(C>=36)return e;m+=C*w;let N=E<=y?1:E>=y+26?26:E-y;if(C<N)break;w*=36-N}let T=d.length+1;y=u(m-b,T,b===0),g+=Math.floor(m/T),m%=T,d.splice(m,0,g),m++}return String.fromCodePoint(...d)}catch{return e}}isSameRegistrableDomain(e,r){let n=this.toHost(e),i=this.toHost(r);return!n||!i?!1:n===i||n.endsWith(`.${i}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(r=>this.alnum(r)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,r){let n=e.length,i=r.length;if(!n)return i;if(!i)return n;let o=Array.from({length:i+1},(a,s)=>s);for(let a=1;a<=n;a++){let s=[a];for(let l=1;l<=i;l++){let u=e[a-1]===r[l-1]?0:1;s[l]=Math.min(o[l]+1,s[l-1]+1,o[l-1]+u)}o=s}return o[i]}isNearMiss(e,r){if(!e||!r||e===r)return!1;let n=Math.max(e.length,r.length);if(n<4||Math.abs(e.length-r.length)>2)return!1;let i=this.editDistance(e,r);return i>=1&&i<=(n>=8?2:1)}carriesBrandName(e,r,n){let i=this.alnum(this.toHost(e));if(!i)return!1;let o=this.hostLabels(e);return[r?this.brandCore(r):"",this.alnum(n??"")].filter(s=>s.length>=4).some(s=>i.includes(s)||o.some(l=>this.isNearMiss(l,s)))}looksLikeSquatOf(e,r){if(this.isSameRegistrableDomain(e,r))return!1;let n=this.brandCore(r);if(n.length<4)return!1;let i=this.hostLabels(e);return i.includes(n)?!1:i.some(o=>this.isNearMiss(o,n)||o.length>n.length&&o.includes(n))}describeLookAlike(e,r){let n=this.toHost(e),i=this.toHost(r);if(!n||!i||n===i)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${i}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),a=i.lastIndexOf(".");if(o>0&&a>0){let u=n.slice(0,o),c=i.slice(0,a),d=n.slice(o+1),h=i.slice(a+1);if(u===c&&d!==h)return`The address keeps the official name but changes the ending from ".${h}" to ".${d}" (${n} vs ${i}) \u2014 a look-alike that is easy to miss at a glance.`}let s=this.brandCore(i),l=this.hostLabels(n).find(u=>this.isNearMiss(u,s));if(l){let u=this.editDistance(l,s);return`The address "${n}" is a near-copy of the official ${i} \u2014 its name differs by only ${u} letter${u>1?"s":""} ("${l}" vs "${s}"), a typo that is easy to overlook.`}if(s.length>=4&&this.alnum(n).includes(s))return`The address "${n}" reuses the "${s}" name with extra text added to look affiliated with the official ${i}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let r=e.replace(/```(?:json)?/gi,"").trim(),n=r.indexOf("{"),i=r.lastIndexOf("}");if(n===-1||i===-1||i<=n)return null;try{return JSON.parse(r.slice(n,i+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let r=e.trim();if(!r)return;let n=r.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return r}cleanStrArray(e){let r=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let i of r){let o=this.coerceToStr(i);o&&n.push(o)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let r=e,n=this.cleanStr(r.feature)??this.cleanStr(r.name)??this.cleanStr(r.title),i=this.cleanStr(r.description)??this.cleanStr(r.detail)??this.cleanStr(r.text)??this.cleanStr(r.value);return n&&i?n===i?n:`${n} \u2014 ${i}`:n||i?n??i:Object.values(r).map(a=>this.cleanStr(a)).filter(a=>!!a).join(" \u2014 ")||void 0}dedupe(e){let r=new Set,n=[];for(let i of e){let o=i.toLowerCase();r.has(o)||(r.add(o),n.push(i))}return n}};p();var Y4e=t=>{let e=JSON.parse(t),r=Array.isArray(e)?e:e?.entries;if(!Array.isArray(r))throw new Error("JSON must be an array or { entries: [...] }");return r.map((n,i)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${i} is missing "question" or "answer"`);return n})};async function eJ(t,e){let r=t.entries??(t.json?Y4e(t.json):[]);return r.length===0?{count:0}:new El(e).upsert(r)}
1622
1622
  /*! Bundled license information:
1623
1623
 
1624
1624
  web-streams-polyfill/dist/ponyfill.mjs:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keyring-agent-core",
3
- "version": "0.2.41",
3
+ "version": "0.2.42",
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",