keyring-agent-core 0.2.37 → 0.2.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -437,8 +437,8 @@ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}
437
437
  `);return a===-1?"":i.stack.slice(a+1)})();try{if(!n.stack)n.stack=o;else if(o){let a=o.indexOf(`
438
438
  `),s=a===-1?-1:o.indexOf(`
439
439
  `,a+1),l=s===-1?"":o.slice(s+1);String(n.stack).endsWith(l)||(n.stack+=`
440
- `+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=po(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&hm.assertOptions(n,{silentJSONParsing:Ai.transitional(Ai.boolean),forcedJSONParsing:Ai.transitional(Ai.boolean),clarifyTimeoutError:Ai.transitional(Ai.boolean),legacyInterceptorReqResOrdering:Ai.transitional(Ai.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:hm.assertOptions(i,{encode:Ai.function,serialize:Ai.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),hm.assertOptions(r,{baseUrl:Ai.spelling("baseURL"),withXsrfToken:Ai.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&j.merge(o.common,o[r.method]);o&&j.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=hr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||gd;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let u=[];this.interceptors.response.forEach(function(y){u.push(y.fulfilled,y.rejected)});let c,d=0,h;if(!l){let g=[Jb.bind(this),void 0];for(g.unshift(...s),g.push(...u),h=g.length,c=Promise.resolve(r);d<h;)c=c.then(g[d++],g[d++]);return c}h=s.length;let m=r;for(;d<h;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{c=Jb.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=po(this.defaults,e);let r=fm(e.baseURL,e.url,e.allowAbsoluteUrls);return um(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){wd.prototype[e]=function(r,n){return this.request(po(n||{},{method:e,url:r,data:(n||{}).data}))}});j.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(po(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}wd.prototype[e]=r(),e!=="query"&&(wd.prototype[e+"Form"]=r(!0))});var mm=wd;p();var sA=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new jo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},cU=sA;p();function lA(t){return function(r){return t.apply(null,r)}}p();function uA(t){return j.isObject(t)&&t.isAxiosError===!0}p();var cA={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(cA).forEach(([t,e])=>{cA[e]=t});var dU=cA;function pU(t){let e=new mm(t),r=im(mm.prototype.request,e);return j.extend(r,mm.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return pU(po(t,i))},r}var kr=pU(_d);kr.Axios=mm;kr.CanceledError=jo;kr.CancelToken=cU;kr.isCancel=dm;kr.VERSION=vd;kr.toFormData=gl;kr.AxiosError=Me;kr.Cancel=kr.CanceledError;kr.all=function(e){return Promise.all(e)};kr.spread=lA;kr.isAxiosError=uA;kr.mergeConfig=po;kr.AxiosHeaders=hr;kr.formToJSON=t=>Gb(j.isHTMLForm(t)?new FormData(t):t);kr.getAdapter=Yb.getAdapter;kr.HttpStatusCode=dU;kr.default=kr;var Qb=kr;var{Axios:aVe,AxiosError:sVe,CanceledError:lVe,isCancel:uVe,CancelToken:cVe,VERSION:dVe,all:pVe,Cancel:fVe,isAxiosError:hVe,spread:mVe,toFormData:gVe,AxiosHeaders:yVe,HttpStatusCode:_Ve,formToJSON:bVe,getAdapter:vVe,mergeConfig:wVe,create:SVe}=Qb;var fU="0.2.37";var rQ=`keyring-agent-core/${fU} (Keyring Chatbot Agent; +https://keyring.app)`,nQ="payment-required",dA=null;function hU(t){dA=t}function iQ(t){return t?Object.keys(t).some(e=>e.toLowerCase()==="payment-signature"):!1}var oQ=3e4,aQ=typeof process<"u"&&process.versions?.node!=null,pA=class{constructor(e={}){f(this,"instance");this.instance=Qb.create({baseURL:e.baseURL,timeout:e.timeout??oQ,validateStatus:()=>!0,headers:{Accept:"application/json",...aQ?{"User-Agent":e.userAgent??rQ}:{},...e.headers}})}async request(e,r,n,i={}){let o=await this.instance.request({...i,method:e,url:r,data:n}),a={};for(let[l,u]of Object.entries(o.headers??{}))u!=null&&(a[l.toLowerCase()]=String(u));let s={ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:a};if(s.status===402&&s.headers[nQ]&&dA&&!iQ(i.headers)){let l=await dA(s,{url:r,method:String(e),body:n,headers:i.headers});if(l)return this.request(e,r,n,{...i,headers:{...i.headers,...l}})}return s}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},De=new pA;function nt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}var sQ={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},mU="payment-required",lQ="PAYMENT-SIGNATURE";function uQ(t){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(t,"utf8").toString("base64")}function cQ(t){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(t,"base64").toString("utf8")}function dQ(){let t=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<32;r++)t[r]=Math.floor(Math.random()*256);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function pQ(t){let[e,r]=String(t).split(":"),n=parseInt(r,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${t}`);return n}function gU(t){if(!t.query||Object.keys(t.query).length===0)return t.url;let e=Object.entries(t.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return t.url.includes("?")?`${t.url}&${e}`:`${t.url}?${e}`}function yU(t){return JSON.parse(cQ(t))}function fA(t,e,r,n){let i=t.headers[mU];if(!i)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=yU(i),a=o.accepts?.[0];if(!a)throw new Error("402 response offered no payment requirements");if(a.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${a.scheme} (only "exact" is supported)`);if(!r)throw new Error("No connected wallet address to build the payment from");let s=pQ(a.network),l=Math.floor(Date.now()/1e3),u={from:r,to:a.payTo,value:String(a.amount),validAfter:"0",validBefore:String(l+(a.maxTimeoutSeconds??300)),nonce:dQ()},c={domain:{name:a.extra?.name,version:a.extra?.version,chainId:s,verifyingContract:a.asset},types:sQ,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:gU(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:a,authorization:u,typedData:c,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:u},resource:o.resource,accepted:a,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function fQ(t,e,r,n){let i=gU(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:fA(o,e,r,n)};if(!o.ok)throw new Error(nt(o));return{status:"ok",data:o.data}}async function hA(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...mA(e,r)}});if(s.ok)return s.data;let l=s.headers[mU];if(l)try{let u=yU(l);if(u.error)throw new Error(`x402 payment rejected: ${u.error}`)}catch(u){if(u instanceof Error&&u.message.startsWith("x402 payment rejected"))throw u}throw new Error(nt(s))}var hQ={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function mA(t,e){let r={...t.paymentDraft,payload:{authorization:t.authorization,signature:e}};return{[lQ]:uQ(JSON.stringify(r))}}function _U(t){let e=t.requirements,r=t.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:hQ[e.network]||e.network,payTo:e.payTo,...r?.description?{description:r.description}:{},resourceUrl:t.request.url}}function gA(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=fA(e,{url:r.url,method:r.method,body:r.body,headers:r.headers},n)}catch{return null}let a;try{a=await i({typedData:o.typedData,display:_U(o)})}catch{a=null}return a?mA(o,a):null}}p();p();var Zu=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Sd(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function yA(t){if(t?.aborted)throw new Zu}function bU(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var vU={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},mQ="https://nft.keyring.app/api/gemini-stable",gQ=new Set([408,429,500,502,503,504]),wU=3e4,ev=t=>new Promise(e=>setTimeout(e,t));function tv(t,e,r){if(r!=null&&r>0)return Math.min(r,wU);let n=Math.min(e*2**(t-1),wU);return n/2+Math.random()*(n/2)}function yQ(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pr=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??mQ}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;yA(l);let u=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of u){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let c={contents:u,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(c.systemInstruction=i),r?.length?(c.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(c.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(c.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,h="Unknown error";for(let m=1;m<=a;m++){yA(l);let g;try{g=await De.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(Sd(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await ev(tv(m,s));continue}if(!g.ok){let C=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(h=`Gemini proxy error ${g.status}: ${C}`,!gQ.has(g.status))throw new Error(h);if(m>=a)break;let N=yQ(g.headers["retry-after"]??null);await ev(tv(m,s,N));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await ev(tv(m,s));continue}let y=g.data,_=y.candidates?.[0];if(!_)return{text:"",toolCalls:[]};let b="",w=[],T=_.content?.parts;if(!Array.isArray(T)||T.length===0){let C=_.finishReason;if(!(C==="SAFETY"||C==="RECITATION")&&m<a){h=`Gemini returned an empty turn (finishReason=${C??"none"})`,await ev(tv(m,s));continue}return{text:"",toolCalls:[]}}for(let C of T)C.text&&(b+=C.text),C.functionCall&&w.push({toolName:C.functionCall.name,args:C.functionCall.args??{},callId:C.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let E=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:b,toolCalls:w,usage:E}}throw new Error(h)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],u=s.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!u&&!c?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],u=o[o.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
441
- `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:vU[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:vU[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&i.push(o.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};p();var Td=class{constructor(){f(this,"tools",new Map)}register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await i.execute(r,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};p();p();p();p();p();var kd=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],_Q=new Set(kd),yl=[...kd],_A=new Set(yl),Ci="0x1",Ad="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function bQ(t){return t.map(e=>Ed[e]??e).join(", ")}function rv(t){let e=new Set;if(t)for(let n of t){let i=nv(n);i&&e.add(i)}let r=kd.filter(n=>!e.has(n));yl=r.length>0?[...r]:[...kd],_A=new Set(yl),Ci=yl.includes("0x1")?"0x1":yl[0],Ad=bQ(yl)}var vQ={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function tr(t){let e=nv(t);return e&&_A.has(e)?e:null}function nv(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=vQ[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&_Q.has(n)?n:null}function fo(t){return tr(t)!==null}function xi(){return[...yl]}var Pd=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Ad}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},_l=t=>typeof t=="string"&&t.trim()!=="";function Fn(t,e){if(_l(t)){let r=tr(t);if(r)return r;throw new Pd(t.trim())}if(_l(e?.chain)){let r=tr(e.chain);if(r)return r;throw new Pd(e.chain.trim())}return null}function iv(t,e){return tr(t)??tr(e?.chain)??void 0}var Ed={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function Ce(t){let e=nv(t);return e&&Ed[e]?Ed[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var wQ={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function SU(t,e){let r=nv(t),n=r?wQ[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var SQ={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function TU(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?SQ[e]??null:null}var TQ={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function kU(t){let e=tr(t);return e?TQ[e]??null:null}function Cd(t,e){if(!_l(t))return null;let r=tr(t),n=tr(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:Ed[r]??r,connectedLabel:Ed[n]??n}}function PU(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>_A.has(o)):[];return(n.length?n:yl).map(o=>{let a=Ed[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function xd(t,e){return{actionButtons:PU(e),_instructions:`The user wants to ${t} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var mr=class extends Error{constructor(r,n){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");f(this,"code","needs_chain_selection");f(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=PU(r,n)}},gm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");f(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function Er(t,e){if(_l(t))return t.trim();if(_l(e?.walletAddress))return e.walletAddress.trim();throw new gm}function Lr(t,e,r){if(_l(t)){let n=tr(t);if(n)return n;throw new Pd(t.trim())}if(_l(e?.chain)){let n=tr(e.chain);if(n)return n;throw new Pd(e.chain.trim())}if(_l(e?.walletAddress))throw new mr(typeof e?.query=="string"?e.query:void 0,r);return Ci}var oe=class{constructor(){f(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=kQ(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{}}}catch(o){return o instanceof mr?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-i,actionButtons:o.buttons}:o instanceof gm?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-i}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-i}}}};function kQ(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons;if(!Array.isArray(r)||r.length===0)return{data:t};let{actionButtons:n,...i}=e;return{data:i,actionButtons:r}}p();p();var EU=ub(av());function Bt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function PQ(t){return new Uint8Array(EU.keccak256.arrayBuffer(t))}function ym(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function AU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function CU(t){return new TextEncoder().encode(t)}function Hu(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function EQ(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function AQ(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function xU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return ym(e)}function _m(t){return xU(BigInt(t))}function IU(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function OU(t){let e=IU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(OU).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function CQ(t){let e=(t.inputs??[]).map(OU).join(",");return`${t.name??""}(${e})`}function bA(t,e){let r=OQ(t.type);if(r){let[i,o]=r;return xQ({...t,type:o},e,i)}if(t.type==="tuple")return IQ(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:EQ(ym(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=IU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:_m(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:xU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?ym(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:AQ(o)}}if(n==="bytes"){let i=typeof e=="string"?ym(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Hu(_m(i.length),a)}}if(n==="string"){let i=typeof e=="string"?CU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Hu(_m(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function vA(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(_m(e+i)),n.push(a),i+=a.length):r.push(a);return Hu(...r,...n)}function xQ(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=bA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=vA(o);if(n){let s=_m(o.length);return{dynamic:!0,encoded:o.length>0?Hu(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:Hu(...o.map(a=>a.encoded))}}function IQ(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=bA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?vA(i):Hu(...i.map(o=>o.encoded))}}function OQ(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function RQ(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>bA(i,e[o])),n=vA(r);return AU(n)}function Id({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=CQ(n),o=PQ(CU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):ym(RQ(a,r).slice(2));return AU(Hu(o,s))}p();var NQ="https://deblo-api-dev.pantograph.app",$Q="0x0000000000000000000000000000000000000000",$U={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},MU={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function MQ(t){return $U[t.toLowerCase()]||t}function RU(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function wA(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,o=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function SA(t){if(Array.isArray(t))return t;let e=t;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Sn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function NU(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=Sn(t.price_change_percentage_24h)??Sn(t.priceChange24h)??Sn(t.usd_price_24hr_percent_change)??Sn(t.price_change_24h)??Sn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:Sn(t.price)??Sn(t.usd_price),marketCap:Sn(t.market_cap)??Sn(t.marketCap),totalVolume:{"24h":Sn(t.total_volume)??Sn(t.volume24h)},pricePercentChange:{"24h":i}}}var Tn=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??NQ).replace(/\/+$/,"")}tokensUrl(e,r){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),i=this.tokensUrl(r,n),o=await De.get(i);if(!o.ok)return;let a=SA(o.data),s=new Map;for(let l of a)l.address&&s.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let u=s.get(e[l].token_address.toLowerCase());u&&(u.icon_image&&(e[l].logo=u.icon_image,e[l].thumbnail=u.icon_image),isNaN(u.price)||(e[l].usd_price=u.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*u.price))}}catch{}}async getTokenMetadata(e,r){try{let n=this.tokensUrl(r,e),i=await De.get(n);if(!i.ok)return null;let o=SA(i.data),a=e.toLowerCase()===$Q,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?wA(s):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=this.tokensUrl(r,e.join(",")),o=await De.get(i);if(!o.ok)return n;let a=SA(o.data),s=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let u=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);u&&s.has(u)&&(n[u]=wA(l))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ci,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=RU({chainId:o,key:r}),s=`${this.baseUrl}/token-list/all?${a}`,l=await De.get(s);if(!l.ok)throw new Error(nt(l));let u=l.data,c=u?.result??u?.data??u,d=[];return Array.isArray(c)?d=c:c&&typeof c=="object"&&(d=Object.values(c).flat()),{success:!0,data:d.map(wA)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ci,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=MU[r.toLowerCase()]??[],a=i!=null?i+o.length:n+o.length,[s,l]=await Promise.allSettled([this.fetchTopGainers(r,a),o.length>0?this.getTokensMetadata(o,r):Promise.resolve({})]),u=s.status==="fulfilled"?s.value:[],c=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>NU(y,r)):[],d=new Set,h=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...h,...m].slice(0,i):[...h,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=Sn(a.market_cap)??Sn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":Sn(a.total_volume)??Sn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=parseInt(e,16),o=RU({chainId:i,duration:n,limit:r}),a=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,s=[];for(let l=0;l<5;l++){let u=await De.get(a);if(!u.ok)throw new Error(nt(u));let c=u.data;if(s=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>NU(l,e))}async getTopGainers(e){let r=e?.chain||Ci,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var DQ="https://nft.keyring.app",UQ="https://nft.keyring.app",LQ=.01,et=5,ir=1e3,qQ="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",jQ="0x0000000000000000000000000000000000000000",tt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function gr(t){return t||Ci}function or(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ar(t){return new Promise(e=>setTimeout(e,t))}function FQ(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function TA(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var pt=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??DQ).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??UQ).replace(/\/+$/,""),this.pantograph=new Tn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=gr(n),l="Unknown error";for(let u=1;u<=et;u++)try{let c={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(c.token_addresses=i);let d=[],h=null;do{h&&(c.cursor=h);let g=or(c),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),h=w?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===qQ?jQ:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=LQ)),{success:!0,data:m}}catch(c){if(l=c instanceof Error?c.message:"Unknown error",c instanceof tt&&c.status===400)break;u<et&&await ar(ir)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=gr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=et;s++)try{let[l,u]=await Promise.allSettled([De.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${or({chain:i,addresses:[r]})}`),De.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${or({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;c=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!c){o="Token metadata not found",s<et&&await ar(ir);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let h=u.value.data;d=h?.data??h}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:o=!0,cursor:a,tokenAddresses:s,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=gr(n),d="Unknown error";for(let h=1;h<=et;h++)try{let m={chain:c,format:u,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(m.cursor=a),l&&(m.include_prices=!0),s&&s.length>0&&(m.token_addresses=s);let g=or(m),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data;return{success:!0,data:b?.data??b}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof tt&&m.status===400)break;h<et&&await ar(ir)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!Bt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=gr(i),c="Unknown error";for(let d=1;d<=et;d++)try{let h={chain:u,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=or(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await De.get(g);if(!y.ok)throw new tt(y.status,nt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(c=h instanceof Error?h.message:"Unknown error",h instanceof tt&&h.status===400)break;d<et&&await ar(ir)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=gr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=et;_++)try{let b={chain:m,limit:g,order:c};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),u&&(b.cursor=u),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let w=or(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await De.get(T);if(!E.ok)throw new tt(E.status,nt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof tt&&b.status===400)break;_<et&&await ar(ir)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=gr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=et;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),u!=null&&(_.to_block=u),c&&(_.cursor=c),i?.length&&(_.contract_addresses=i);let b=or(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await De.get(w);if(!T.ok)throw new tt(T.status,nt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof tt&&_.status===400)break;y<et&&await ar(ir)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=gr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=et;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),u!=null&&(w.to_block=u),c&&(w.cursor=c),i?.length&&(w.contract_addresses=i),h!=null&&(w.include_prices=h);let T=or(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await De.get(E);if(!C.ok)throw new tt(C.status,nt(C));let N=C.data;return{success:!0,data:N?.data??N}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof tt&&w.status===400)break;b<et&&await ar(ir)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Bt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=gr(n),a="Unknown error";for(let s=1;s<=et;s++)try{let l={chain:o};i&&(l.days=i);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data;return{success:!0,data:h?.data??h}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i&&(u.days=i),o&&o.length>0&&(u.token_addresses=o.slice(0,25));let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i!=null&&(u.limit=i),o&&(u.cursor=o);let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:FQ(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=gr(i),a="Unknown error";for(let s=1;s<=et;s++)try{let l=or({chains:o}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await De.get(u);if(!c.ok)throw new tt(c.status,nt(c));let m=c.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=et;o++)try{let a={};r&&(a.chain=gr(r)),n!=null&&(a.limit=n);let s=or(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:TA(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof tt&&a.status===400)break;o<et&&await ar(ir)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:TA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:TA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Od=class extends oe{constructor(r){super();f(this,"name","get-token-info");f(this,"description",'Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad');f(this,"category","blockchain-data");f(this,"parameters",[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}]);f(this,"service");f(this,"llm");this.service=new pt(r),this.llm=new Pr({})}async run(r,n){let i=r.keyword||"",o=Lr(r.chain,n),a=r.prompt||"",s=n?.walletAddress||void 0;return i?await this.searchToken(i,o,a,s):{error:"Missing required parameter: keyword"}}async searchToken(r,n,i,o){let a=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
440
+ `+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=po(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&hm.assertOptions(n,{silentJSONParsing:Ai.transitional(Ai.boolean),forcedJSONParsing:Ai.transitional(Ai.boolean),clarifyTimeoutError:Ai.transitional(Ai.boolean),legacyInterceptorReqResOrdering:Ai.transitional(Ai.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:hm.assertOptions(i,{encode:Ai.function,serialize:Ai.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),hm.assertOptions(r,{baseUrl:Ai.spelling("baseURL"),withXsrfToken:Ai.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&j.merge(o.common,o[r.method]);o&&j.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=hr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||gd;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let u=[];this.interceptors.response.forEach(function(y){u.push(y.fulfilled,y.rejected)});let c,d=0,h;if(!l){let g=[Jb.bind(this),void 0];for(g.unshift(...s),g.push(...u),h=g.length,c=Promise.resolve(r);d<h;)c=c.then(g[d++],g[d++]);return c}h=s.length;let m=r;for(;d<h;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{c=Jb.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=po(this.defaults,e);let r=fm(e.baseURL,e.url,e.allowAbsoluteUrls);return um(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){wd.prototype[e]=function(r,n){return this.request(po(n||{},{method:e,url:r,data:(n||{}).data}))}});j.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(po(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}wd.prototype[e]=r(),e!=="query"&&(wd.prototype[e+"Form"]=r(!0))});var mm=wd;p();var sA=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new jo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},cU=sA;p();function lA(t){return function(r){return t.apply(null,r)}}p();function uA(t){return j.isObject(t)&&t.isAxiosError===!0}p();var cA={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(cA).forEach(([t,e])=>{cA[e]=t});var dU=cA;function pU(t){let e=new mm(t),r=im(mm.prototype.request,e);return j.extend(r,mm.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return pU(po(t,i))},r}var kr=pU(_d);kr.Axios=mm;kr.CanceledError=jo;kr.CancelToken=cU;kr.isCancel=dm;kr.VERSION=vd;kr.toFormData=gl;kr.AxiosError=Me;kr.Cancel=kr.CanceledError;kr.all=function(e){return Promise.all(e)};kr.spread=lA;kr.isAxiosError=uA;kr.mergeConfig=po;kr.AxiosHeaders=hr;kr.formToJSON=t=>Gb(j.isHTMLForm(t)?new FormData(t):t);kr.getAdapter=Yb.getAdapter;kr.HttpStatusCode=dU;kr.default=kr;var Qb=kr;var{Axios:aVe,AxiosError:sVe,CanceledError:lVe,isCancel:uVe,CancelToken:cVe,VERSION:dVe,all:pVe,Cancel:fVe,isAxiosError:hVe,spread:mVe,toFormData:gVe,AxiosHeaders:yVe,HttpStatusCode:_Ve,formToJSON:bVe,getAdapter:vVe,mergeConfig:wVe,create:SVe}=Qb;var fU="0.2.38";var rQ=`keyring-agent-core/${fU} (Keyring Chatbot Agent; +https://keyring.app)`,nQ="payment-required",dA=null;function hU(t){dA=t}function iQ(t){return t?Object.keys(t).some(e=>e.toLowerCase()==="payment-signature"):!1}var oQ=3e4,aQ=typeof process<"u"&&process.versions?.node!=null,pA=class{constructor(e={}){f(this,"instance");this.instance=Qb.create({baseURL:e.baseURL,timeout:e.timeout??oQ,validateStatus:()=>!0,headers:{Accept:"application/json",...aQ?{"User-Agent":e.userAgent??rQ}:{},...e.headers}})}async request(e,r,n,i={}){let o=await this.instance.request({...i,method:e,url:r,data:n}),a={};for(let[l,u]of Object.entries(o.headers??{}))u!=null&&(a[l.toLowerCase()]=String(u));let s={ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:a};if(s.status===402&&s.headers[nQ]&&dA&&!iQ(i.headers)){let l=await dA(s,{url:r,method:String(e),body:n,headers:i.headers});if(l)return this.request(e,r,n,{...i,headers:{...i.headers,...l}})}return s}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},De=new pA;function nt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}var sQ={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},mU="payment-required",lQ="PAYMENT-SIGNATURE";function uQ(t){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(t,"utf8").toString("base64")}function cQ(t){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(t,"base64").toString("utf8")}function dQ(){let t=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<32;r++)t[r]=Math.floor(Math.random()*256);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function pQ(t){let[e,r]=String(t).split(":"),n=parseInt(r,10);if(e!=="eip155"||Number.isNaN(n))throw new Error(`Unsupported x402 network: ${t}`);return n}function gU(t){if(!t.query||Object.keys(t.query).length===0)return t.url;let e=Object.entries(t.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return t.url.includes("?")?`${t.url}&${e}`:`${t.url}?${e}`}function yU(t){return JSON.parse(cQ(t))}function fA(t,e,r,n){let i=t.headers[mU];if(!i)throw new Error("402 response is missing the PAYMENT-REQUIRED header");let o=yU(i),a=o.accepts?.[0];if(!a)throw new Error("402 response offered no payment requirements");if(a.scheme!=="exact")throw new Error(`Unsupported x402 scheme: ${a.scheme} (only "exact" is supported)`);if(!r)throw new Error("No connected wallet address to build the payment from");let s=pQ(a.network),l=Math.floor(Date.now()/1e3),u={from:r,to:a.payTo,value:String(a.amount),validAfter:"0",validBefore:String(l+(a.maxTimeoutSeconds??300)),nonce:dQ()},c={domain:{name:a.extra?.name,version:a.extra?.version,chainId:s,verifyingContract:a.asset},types:sQ,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:gU(e),method:e.method??"GET",body:e.body,headers:e.headers},requirements:a,authorization:u,typedData:c,paymentDraft:{x402Version:o.x402Version??2,payload:{authorization:u},resource:o.resource,accepted:a,...o.extensions?{extensions:o.extensions}:{}},...n?{userQuery:n}:{}}}async function fQ(t,e,r,n){let i=gU(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:fA(o,e,r,n)};if(!o.ok)throw new Error(nt(o));return{status:"ok",data:o.data}}async function hA(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...mA(e,r)}});if(s.ok)return s.data;let l=s.headers[mU];if(l)try{let u=yU(l);if(u.error)throw new Error(`x402 payment rejected: ${u.error}`)}catch(u){if(u instanceof Error&&u.message.startsWith("x402 payment rejected"))throw u}throw new Error(nt(s))}var hQ={"eip155:1":"Ethereum","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:10":"Optimism","eip155:42161":"Arbitrum","eip155:137":"Polygon"};function mA(t,e){let r={...t.paymentDraft,payload:{authorization:t.authorization,signature:e}};return{[lQ]:uQ(JSON.stringify(r))}}function _U(t){let e=t.requirements,r=t.paymentDraft.resource;return{amount:e.amount,asset:e.extra?.name||"USDC",network:e.network,networkLabel:hQ[e.network]||e.network,payTo:e.payTo,...r?.description?{description:r.description}:{},resourceUrl:t.request.url}}function gA(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=fA(e,{url:r.url,method:r.method,body:r.body,headers:r.headers},n)}catch{return null}let a;try{a=await i({typedData:o.typedData,display:_U(o)})}catch{a=null}return a?mA(o,a):null}}p();p();var Zu=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Sd(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function yA(t){if(t?.aborted)throw new Zu}function bU(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var vU={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},mQ="https://nft.keyring.app/api/gemini-stable",gQ=new Set([408,429,500,502,503,504]),wU=3e4,ev=t=>new Promise(e=>setTimeout(e,t));function tv(t,e,r){if(r!=null&&r>0)return Math.min(r,wU);let n=Math.min(e*2**(t-1),wU);return n/2+Math.random()*(n/2)}function yQ(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pr=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??mQ}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;yA(l);let u=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of u){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let c={contents:u,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(c.systemInstruction=i),r?.length?(c.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(c.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(c.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,h="Unknown error";for(let m=1;m<=a;m++){yA(l);let g;try{g=await De.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(Sd(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await ev(tv(m,s));continue}if(!g.ok){let C=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(h=`Gemini proxy error ${g.status}: ${C}`,!gQ.has(g.status))throw new Error(h);if(m>=a)break;let N=yQ(g.headers["retry-after"]??null);await ev(tv(m,s,N));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await ev(tv(m,s));continue}let y=g.data,_=y.candidates?.[0];if(!_)return{text:"",toolCalls:[]};let b="",w=[],T=_.content?.parts;if(!Array.isArray(T)||T.length===0){let C=_.finishReason;if(!(C==="SAFETY"||C==="RECITATION")&&m<a){h=`Gemini returned an empty turn (finishReason=${C??"none"})`,await ev(tv(m,s));continue}return{text:"",toolCalls:[]}}for(let C of T)C.text&&(b+=C.text),C.functionCall&&w.push({toolName:C.functionCall.name,args:C.functionCall.args??{},callId:C.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let E=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:b,toolCalls:w,usage:E}}throw new Error(h)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],u=s.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!u&&!c?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],u=o[o.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
441
+ `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:vU[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:vU[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&i.push(o.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};p();var Td=class{constructor(){f(this,"tools",new Map)}register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await i.execute(r,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};p();p();p();p();p();var kd=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],_Q=new Set(kd),yl=[...kd],_A=new Set(yl),Ci="0x1",Ad="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function bQ(t){return t.map(e=>Ed[e]??e).join(", ")}function rv(t){let e=new Set;if(t)for(let n of t){let i=nv(n);i&&e.add(i)}let r=kd.filter(n=>!e.has(n));yl=r.length>0?[...r]:[...kd],_A=new Set(yl),Ci=yl.includes("0x1")?"0x1":yl[0],Ad=bQ(yl)}var vQ={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function tr(t){let e=nv(t);return e&&_A.has(e)?e:null}function nv(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=vQ[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&_Q.has(n)?n:null}function fo(t){return tr(t)!==null}function xi(){return[...yl]}var Pd=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Ad}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},_l=t=>typeof t=="string"&&t.trim()!=="";function Fn(t,e){if(_l(t)){let r=tr(t);if(r)return r;throw new Pd(t.trim())}if(_l(e?.chain)){let r=tr(e.chain);if(r)return r;throw new Pd(e.chain.trim())}return null}function iv(t,e){return tr(t)??tr(e?.chain)??void 0}var Ed={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function Ce(t){let e=nv(t);return e&&Ed[e]?Ed[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var wQ={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build","0x64":"https://gnosisscan.io","0x3e7":"https://hyperevmscan.io","0x1388":"https://mantlescan.xyz","0x8f":"https://monadscan.com"};function SU(t,e){let r=nv(t),n=r?wQ[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var SQ={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function TU(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?SQ[e]??null:null}var TQ={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH","0x64":"XDAI","0x3e7":"HYPE","0x1388":"MNT","0x8f":"MON"};function kU(t){let e=tr(t);return e?TQ[e]??null:null}function Cd(t,e){if(!_l(t))return null;let r=tr(t),n=tr(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:Ed[r]??r,connectedLabel:Ed[n]??n}}function PU(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>_A.has(o)):[];return(n.length?n:yl).map(o=>{let a=Ed[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function xd(t,e){return{actionButtons:PU(e),_instructions:`The user wants to ${t} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var mr=class extends Error{constructor(r,n){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");f(this,"code","needs_chain_selection");f(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=PU(r,n)}},gm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");f(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function Er(t,e){if(_l(t))return t.trim();if(_l(e?.walletAddress))return e.walletAddress.trim();throw new gm}function Lr(t,e,r){if(_l(t)){let n=tr(t);if(n)return n;throw new Pd(t.trim())}if(_l(e?.chain)){let n=tr(e.chain);if(n)return n;throw new Pd(e.chain.trim())}if(_l(e?.walletAddress))throw new mr(typeof e?.query=="string"?e.query:void 0,r);return Ci}var oe=class{constructor(){f(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=kQ(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{}}}catch(o){return o instanceof mr?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-i,actionButtons:o.buttons}:o instanceof gm?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-i}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-i}}}};function kQ(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons;if(!Array.isArray(r)||r.length===0)return{data:t};let{actionButtons:n,...i}=e;return{data:i,actionButtons:r}}p();p();var EU=ub(av());function Bt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function PQ(t){return new Uint8Array(EU.keccak256.arrayBuffer(t))}function ym(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function AU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function CU(t){return new TextEncoder().encode(t)}function Hu(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function EQ(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function AQ(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function xU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return ym(e)}function _m(t){return xU(BigInt(t))}function IU(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function OU(t){let e=IU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(OU).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function CQ(t){let e=(t.inputs??[]).map(OU).join(",");return`${t.name??""}(${e})`}function bA(t,e){let r=OQ(t.type);if(r){let[i,o]=r;return xQ({...t,type:o},e,i)}if(t.type==="tuple")return IQ(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:EQ(ym(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=IU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:_m(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:xU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?ym(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:AQ(o)}}if(n==="bytes"){let i=typeof e=="string"?ym(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Hu(_m(i.length),a)}}if(n==="string"){let i=typeof e=="string"?CU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Hu(_m(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function vA(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(_m(e+i)),n.push(a),i+=a.length):r.push(a);return Hu(...r,...n)}function xQ(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=bA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=vA(o);if(n){let s=_m(o.length);return{dynamic:!0,encoded:o.length>0?Hu(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:Hu(...o.map(a=>a.encoded))}}function IQ(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=bA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?vA(i):Hu(...i.map(o=>o.encoded))}}function OQ(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function RQ(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>bA(i,e[o])),n=vA(r);return AU(n)}function Id({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=CQ(n),o=PQ(CU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):ym(RQ(a,r).slice(2));return AU(Hu(o,s))}p();var NQ="https://deblo-api-dev.pantograph.app",$Q="0x0000000000000000000000000000000000000000",$U={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},MU={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function MQ(t){return $U[t.toLowerCase()]||t}function RU(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function wA(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,o=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function SA(t){if(Array.isArray(t))return t;let e=t;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Sn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function NU(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=Sn(t.price_change_percentage_24h)??Sn(t.priceChange24h)??Sn(t.usd_price_24hr_percent_change)??Sn(t.price_change_24h)??Sn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:Sn(t.price)??Sn(t.usd_price),marketCap:Sn(t.market_cap)??Sn(t.marketCap),totalVolume:{"24h":Sn(t.total_volume)??Sn(t.volume24h)},pricePercentChange:{"24h":i}}}var Tn=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??NQ).replace(/\/+$/,"")}tokensUrl(e,r){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),i=this.tokensUrl(r,n),o=await De.get(i);if(!o.ok)return;let a=SA(o.data),s=new Map;for(let l of a)l.address&&s.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let u=s.get(e[l].token_address.toLowerCase());u&&(u.icon_image&&(e[l].logo=u.icon_image,e[l].thumbnail=u.icon_image),isNaN(u.price)||(e[l].usd_price=u.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*u.price))}}catch{}}async getTokenMetadata(e,r){try{let n=this.tokensUrl(r,e),i=await De.get(n);if(!i.ok)return null;let o=SA(i.data),a=e.toLowerCase()===$Q,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?wA(s):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=this.tokensUrl(r,e.join(",")),o=await De.get(i);if(!o.ok)return n;let a=SA(o.data),s=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let u=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);u&&s.has(u)&&(n[u]=wA(l))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ci,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=RU({chainId:o,key:r}),s=`${this.baseUrl}/token-list/all?${a}`,l=await De.get(s);if(!l.ok)throw new Error(nt(l));let u=l.data,c=u?.result??u?.data??u,d=[];return Array.isArray(c)?d=c:c&&typeof c=="object"&&(d=Object.values(c).flat()),{success:!0,data:d.map(wA)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ci,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=MU[r.toLowerCase()]??[],a=i!=null?i+o.length:n+o.length,[s,l]=await Promise.allSettled([this.fetchTopGainers(r,a),o.length>0?this.getTokensMetadata(o,r):Promise.resolve({})]),u=s.status==="fulfilled"?s.value:[],c=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>NU(y,r)):[],d=new Set,h=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...h,...m].slice(0,i):[...h,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=Sn(a.market_cap)??Sn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":Sn(a.total_volume)??Sn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=parseInt(e,16),o=RU({chainId:i,duration:n,limit:r}),a=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,s=[];for(let l=0;l<5;l++){let u=await De.get(a);if(!u.ok)throw new Error(nt(u));let c=u.data;if(s=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>NU(l,e))}async getTopGainers(e){let r=e?.chain||Ci,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var DQ="https://nft.keyring.app",UQ="https://nft.keyring.app",LQ=.01,et=5,ir=1e3,qQ="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",jQ="0x0000000000000000000000000000000000000000",tt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function gr(t){return t||Ci}function or(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ar(t){return new Promise(e=>setTimeout(e,t))}function FQ(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function TA(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var pt=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??DQ).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??UQ).replace(/\/+$/,""),this.pantograph=new Tn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=gr(n),l="Unknown error";for(let u=1;u<=et;u++)try{let c={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(c.token_addresses=i);let d=[],h=null;do{h&&(c.cursor=h);let g=or(c),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),h=w?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===qQ?jQ:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=LQ)),{success:!0,data:m}}catch(c){if(l=c instanceof Error?c.message:"Unknown error",c instanceof tt&&c.status===400)break;u<et&&await ar(ir)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=gr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=et;s++)try{let[l,u]=await Promise.allSettled([De.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${or({chain:i,addresses:[r]})}`),De.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${or({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;c=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!c){o="Token metadata not found",s<et&&await ar(ir);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let h=u.value.data;d=h?.data??h}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:o=!0,cursor:a,tokenAddresses:s,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=gr(n),d="Unknown error";for(let h=1;h<=et;h++)try{let m={chain:c,format:u,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(m.cursor=a),l&&(m.include_prices=!0),s&&s.length>0&&(m.token_addresses=s);let g=or(m),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${g}`,_=await De.get(y);if(!_.ok)throw new tt(_.status,nt(_));let b=_.data;return{success:!0,data:b?.data??b}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof tt&&m.status===400)break;h<et&&await ar(ir)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!Bt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=gr(i),c="Unknown error";for(let d=1;d<=et;d++)try{let h={chain:u,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=or(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await De.get(g);if(!y.ok)throw new tt(y.status,nt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(c=h instanceof Error?h.message:"Unknown error",h instanceof tt&&h.status===400)break;d<et&&await ar(ir)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=gr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=et;_++)try{let b={chain:m,limit:g,order:c};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),u&&(b.cursor=u),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let w=or(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await De.get(T);if(!E.ok)throw new tt(E.status,nt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof tt&&b.status===400)break;_<et&&await ar(ir)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=gr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=et;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),u!=null&&(_.to_block=u),c&&(_.cursor=c),i?.length&&(_.contract_addresses=i);let b=or(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await De.get(w);if(!T.ok)throw new tt(T.status,nt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof tt&&_.status===400)break;y<et&&await ar(ir)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=gr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=et;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),u!=null&&(w.to_block=u),c&&(w.cursor=c),i?.length&&(w.contract_addresses=i),h!=null&&(w.include_prices=h);let T=or(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await De.get(E);if(!C.ok)throw new tt(C.status,nt(C));let N=C.data;return{success:!0,data:N?.data??N}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof tt&&w.status===400)break;b<et&&await ar(ir)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Bt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=gr(n),a="Unknown error";for(let s=1;s<=et;s++)try{let l={chain:o};i&&(l.days=i);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data;return{success:!0,data:h?.data??h}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i&&(u.days=i),o&&o.length>0&&(u.token_addresses=o.slice(0,25));let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=gr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let u={chain:a};i!=null&&(u.limit=i),o&&(u.cursor=o);let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,h=await De.get(d);if(!h.ok)throw new tt(h.status,nt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;l<et&&await ar(ir)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:FQ(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=gr(i),a="Unknown error";for(let s=1;s<=et;s++)try{let l=or({chains:o}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await De.get(u);if(!c.ok)throw new tt(c.status,nt(c));let m=c.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=gr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ar(ir)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=et;o++)try{let a={};r&&(a.chain=gr(r)),n!=null&&(a.limit=n);let s=or(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,u=await De.get(l);if(!u.ok)throw new tt(u.status,nt(u));let c=u.data,d=c?.data??c;return{success:!0,data:TA(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof tt&&a.status===400)break;o<et&&await ar(ir)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:TA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=gr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await De.get(c);if(!d.ok)throw new tt(d.status,nt(d));let h=d.data,m=h?.data??h;return{success:!0,data:TA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ar(ir)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Od=class extends oe{constructor(r){super();f(this,"name","get-token-info");f(this,"description",'Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad');f(this,"category","blockchain-data");f(this,"parameters",[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}]);f(this,"service");f(this,"llm");this.service=new pt(r),this.llm=new Pr(r?.llm??{})}async run(r,n){let i=r.keyword||"",o=Lr(r.chain,n),a=r.prompt||"",s=n?.walletAddress||void 0;return i?await this.searchToken(i,o,a,s):{error:"Missing required parameter: keyword"}}async searchToken(r,n,i,o){let a=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
442
442
  `),[s,l,u]=await Promise.all([this.service.searchTokensByKey({key:r,chain:n}),o?this.findTokenInWallet(o,n,r):Promise.resolve(null),i?this.askGeminiWithSearch(i,a):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],d=r.toLowerCase(),h=b=>b.symbol?.toLowerCase()===d||b.token_address?.toLowerCase()===d,m=[...c].sort((b,w)=>(h(b)?0:1)-(h(w)?0:1)),g=null,y=m[0];if(y?.token_address){let b=await this.service.getTokenMetadata({address:y.token_address,chain:n});b.success&&b.data&&(g=b.data)}return!g&&y&&(g={...y}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:n,userHoldsToken:!!l,walletBalance:l,token:g,...c.length>1?{searchResults:m.slice(0,10)}:{},research:u}}async askGeminiWithSearch(r,n){let i=Date.now();try{return(await this.llm.chat([...n?[{role:"system",content:n,timestamp:i}]:[],{role:"user",content:r,timestamp:i}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(r,n,i){if(!i)return null;let o=await this.service.getWalletTokenBalances({address:r,chain:n,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!o.success||!o.data?.result)return null;let a=i.toLowerCase(),s=o.data.result.find(l=>l.token_address.toLowerCase()===a||l.symbol?.toLowerCase()===a||l.name?.toLowerCase().includes(a));return s||null}};p();var Rd=class extends oe{constructor(r){super();f(this,"name","get-token-holders");f(this,"description",'Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ');f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenHolders({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Nd=class extends oe{constructor(r){super();f(this,"name","get-token-analytics");f(this,"description",`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenAnalytics({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var $d=class extends oe{constructor(r){super();f(this,"name","get-token-score");f(this,"description",`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Lr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let m=await this.resolveContractAddress(a,i,o);if(!m)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ce(i):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,l=m.symbol,u=m.name}let c=await this.service.getTokenScore({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},h=d.metrics??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:h.usdPrice??null,liquidityUsd:h.liquidityUsd??null,volumeUsd:h.volumeUsd??null,transactions:h.transactions??null,supply:h.supply??null}}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Md=class extends oe{constructor(r){super();f(this,"name","get-trending-tokens");f(this,"description",'List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad, and more.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1}]);f(this,"service");this.service=new Tn({baseUrl:r?.pantographUrl})}async run(r,n){let i=iv(r.chain,n),o=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.floor(r.limit):void 0,a=await this.service.getTrendingTokens({chain:i,limit:o});if(!a.success)return{error:a.error||"Failed to fetch trending tokens"};let s=a.data??[];return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
443
443
  <rank>. <name> (<symbol>)
444
444
  - Price: <usdPrice>
@@ -453,7 +453,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
453
453
  - 24h Volume: <totalVolume.24h>
454
454
  Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:i?Ce(i):"all",timeFrame:a??null,count:c.length,tokens:c}}};p();p();var Ud=class extends oe{constructor(r){super();f(this,"name","get-wallet-token-balances");f(this,"description",'Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ');f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}]);f(this,"service");this.service=new pt(r)}truncateUsd(r){if(!Number.isFinite(r))return"0.00";let n=r<0,[i,o=""]=Math.abs(r).toFixed(8).split(".");return`${n?"-":""}${i}.${(o+"00").slice(0,2)}`}async run(r,n){let i=Er(r.address,n),o=Fn(r.chain,n);if(o){let l=await this.service.getWalletTokenBalances({address:i,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return l.success?this.renderBalances(i,o,l.data?.result||[]):{error:l.error||"Failed to fetch token balances"}}let a=xi(),s=await Promise.all(a.map(async l=>{let u=await this.service.getWalletTokenBalances({address:i,chain:l,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:l,tokens:u.success?u.data?.result||[]:[]}}));return this.renderBalancesByChain(i,s)}toTokenLine(r){let n=r.name||r.symbol||"Unknown",i=r.balance_formatted??"0",o=r.symbol||"",a=typeof r.usd_value=="number"?`$${this.truncateUsd(r.usd_value)}`:"$-";return`- ${n}: ${i} ${o} (${a})`.replace(/\s+/g," ").trim()}renderBalances(r,n,i){let o=i.reduce((a,s)=>a+(s.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:r,chain:n,totalUsdValue:`$${this.truncateUsd(o)}`,tokens:i.map(a=>this.toTokenLine(a))}}renderBalancesByChain(r,n){let i=n.map(a=>{let s=a.tokens.reduce((u,c)=>u+(c.usd_value||0),0),l=a.tokens.slice().sort((u,c)=>(c.usd_value||0)-(u.usd_value||0));return{chain:Ce(a.chain),total:s,tokens:l}}).filter(a=>a.tokens.length>0).sort((a,s)=>s.total-a.total),o=i.reduce((a,s)=>a+s.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:r,chain:"all",totalUsdValue:`$${this.truncateUsd(o)}`,chains:i.map(a=>({chain:a.chain,totalUsdValue:`$${this.truncateUsd(a.total)}`,tokens:a.tokens.map(s=>this.toTokenLine(s))}))}}};p();var Ld=class extends oe{constructor(r){super();f(this,"name","get-wallet-history");f(this,"description",`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Er(r.address,n),o=Lr(r.chain,n),a=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,s=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,l=typeof r.fromBlock=="number"?r.fromBlock:typeof r.fromBlock=="string"&&r.fromBlock?Number(r.fromBlock):void 0,u=typeof r.toBlock=="number"?r.toBlock:typeof r.toBlock=="string"&&r.toBlock?Number(r.toBlock):void 0,c=Number.isFinite(l)?l:void 0,d=Number.isFinite(u)?u:void 0,h=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,g=(typeof r.order=="string"?r.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",y=typeof r.includeInternalTransactions=="boolean"?r.includeInternalTransactions:void 0,_=typeof r.nftMetadata=="boolean"?r.nftMetadata:void 0,b=typeof r.limit=="number"?r.limit:typeof r.limit=="string"?Number(r.limit):void 0,w=Number.isFinite(b)&&b>0?b:10,T=await this.service.getWalletHistory({address:i,chain:o,limit:w,fromDate:a,toDate:s,fromBlock:c,toBlock:d,cursor:h,order:g,includeInternalTransactions:y,nftMetadata:_});if(!T.success)return{error:T.error||"Failed to fetch wallet history"};let C=(T.data?.result||[]).map(N=>{let D=SU(o,N.hash);return D?{...N,explorerUrl:D}:N});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:i,chain:o||"default",pagination:{cursor:T.data?.cursor??null,hasMore:!!T.data?.cursor},transactionCount:C.length,transactions:C}}};p();function BQ(t){if(t.value_decimal)return t.value_decimal;let e=parseInt(t.token_decimals??"18",10);if(isNaN(e)||e===0)return t.value;try{let r=BigInt(t.value),n=BigInt(10)**BigInt(e),i=r/n,a=(r%n).toString().padStart(e,"0").replace(/0+$/,"");return a?`${i}.${a}`:`${i}`}catch{return t.value}}var qd=class extends oe{constructor(r){super();f(this,"name","get-wallet-token-transfers");f(this,"description",`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Er(r.address,n),o=Lr(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):25,l=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,u=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,c=this.parseBlock(r.fromBlock),d=this.parseBlock(r.toBlock),h=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,g=(typeof r.order=="string"?r.order.toUpperCase():"")==="ASC"?"ASC":"DESC",y=typeof r.direction=="string"?r.direction.trim().toLowerCase():"all",_=y==="send"?"send":y==="receive"?"receive":"all",b=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,w=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(x=>typeof x=="string"&&!!x).map(x=>x.trim()):void 0,T,E;if(b){let x=await this.resolveContractAddressBySymbol(b,i,o);x&&(w=[x.address],T=x.symbol,E=x.name)}let C=await this.service.getWalletTokenTransfers({address:i,chain:o,contractAddresses:w,limit:s,fromDate:l,toDate:u,fromBlock:c,toBlock:d,cursor:h,order:g});if(!C.success)return{error:C.error||"Failed to fetch token transfers"};let N=i.toLowerCase(),A=(C.data?.result||[]).map(x=>{let O=x.from_address.toLowerCase()===N,L=O?"send":"receive",F=O?x.to_address:x.from_address,G=O?x.to_address_label??void 0:x.from_address_label??void 0,X=O?x.to_address_entity??void 0:x.from_address_entity??void 0;return{...x,direction:L,amount_formatted:BQ(x),counterparty:F,counterparty_label:G,counterparty_entity:X}}),U=_==="all"?A:A.filter(x=>x.direction===_);if(b&&!w){let x=b.toLowerCase();U=U.filter(O=>(O.token_symbol??"").toLowerCase()===x)}let M=this.buildCounterparties(U);return{walletAddress:i,chain:o||"default",resolvedToken:T?{symbol:T,name:E,contractAddress:w?.[0]}:null,filters:{tokenSymbol:b||null,contractAddresses:w||null,direction:_,limit:s,order:g,fromDate:l||null,toDate:u||null,fromBlock:c??null,toBlock:d??null},pagination:{cursor:C.data?.cursor??null,pageSize:C.data?.page_size??s,page:C.data?.page??null,hasMore:!!C.data?.cursor},transferCount:U.length,transfers:U,counterparties:M}}async resolveContractAddressBySymbol(r,n,i){let o=r.toLowerCase(),a=await this.service.getWalletTokenBalances({address:n,chain:i});if(a.success&&a.data?.result?.length){let l=a.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}let s=await this.service.searchTokensByKey({key:r,chain:i});if(s.success&&s.data?.length){let u=s.data.find(c=>(c.symbol??"").toLowerCase()===o)??s.data[0];if(u?.token_address)return{address:u.token_address,symbol:u.symbol,name:u.name}}}buildCounterparties(r){let n=new Map,i=new Map;for(let a of r){let s=a.direction==="send"?n:i,l=a.counterparty.toLowerCase(),u=parseFloat(a.amount_formatted)||0,c=s.get(l);c?(c.total+=u,c.count+=1,!c.label&&a.counterparty_label&&(c.label=a.counterparty_label),!c.entity&&a.counterparty_entity&&(c.entity=a.counterparty_entity),a.block_timestamp<c.first&&(c.first=a.block_timestamp),a.block_timestamp>c.last&&(c.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,total:u,count:1,first:a.block_timestamp,last:a.block_timestamp})}let o=a=>Array.from(a.entries()).sort((s,l)=>l[1].count-s[1].count).map(([s,l])=>({address:s,label:l.label,entity:l.entity,total_amount:l.total.toFixed(6).replace(/\.?0+$/,""),tx_count:l.count,first_seen:l.first,last_seen:l.last}));return{sent:o(n),received:o(i)}}parseBlock(r){if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"&&r){let n=Number(r);return Number.isFinite(n)?n:void 0}}};p();var jd=class extends oe{constructor(r){super();f(this,"name","get-wallet-nft-transfers");f(this,"description",`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Er(r.address,n),o=Lr(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):25,l=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,u=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,c=this.parseBlock(r.fromBlock),d=this.parseBlock(r.toBlock),h=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,g=(typeof r.order=="string"?r.order.toUpperCase():"")==="ASC"?"ASC":"DESC",y=typeof r.includePrices=="boolean"?r.includePrices:void 0,_=typeof r.direction=="string"?r.direction.trim().toLowerCase():"all",b=_==="send"?"send":_==="receive"?"receive":"all",w=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(U=>typeof U=="string"&&!!U).map(U=>U.trim()):void 0,T=await this.service.getWalletNftTransfers({address:i,chain:o,contractAddresses:w,limit:s,fromDate:l,toDate:u,fromBlock:c,toBlock:d,cursor:h,order:g,includePrices:y});if(!T.success)return{error:T.error||"Failed to fetch NFT transfers"};let E=i.toLowerCase(),N=(T.data?.result||[]).map(U=>{let M=U.from_address.toLowerCase()===E,x=M?"send":"receive",O=M?U.to_address:U.from_address,L=M?U.to_address_label??void 0:U.from_address_label??void 0,F=M?U.to_address_entity??void 0:U.from_address_entity??void 0;return{...U,direction:x,counterparty:O,counterparty_label:L,counterparty_entity:F}}),D=b==="all"?N:N.filter(U=>U.direction===b),A=this.buildCounterparties(D);return{walletAddress:i,chain:o||"default",filters:{contractAddresses:w||null,direction:b,limit:s,order:g,fromDate:l||null,toDate:u||null,fromBlock:c??null,toBlock:d??null,includePrices:y??null},pagination:{cursor:T.data?.cursor??null,pageSize:T.data?.page_size??s,page:T.data?.page??null,hasMore:!!T.data?.cursor},transferCount:D.length,transfers:D,counterparties:A}}buildCounterparties(r){let n=new Map,i=new Map;for(let a of r){let s=a.direction==="send"?n:i,l=a.counterparty.toLowerCase(),u=a.token_name??a.token_address,c=s.get(l);c?(c.tokenIds.add(a.token_id),c.collections.add(u),c.count+=1,!c.label&&a.counterparty_label&&(c.label=a.counterparty_label),!c.entity&&a.counterparty_entity&&(c.entity=a.counterparty_entity),a.block_timestamp<c.first&&(c.first=a.block_timestamp),a.block_timestamp>c.last&&(c.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,tokenIds:new Set([a.token_id]),collections:new Set([u]),count:1,first:a.block_timestamp,last:a.block_timestamp})}let o=a=>Array.from(a.entries()).sort((s,l)=>l[1].count-s[1].count).map(([s,l])=>({address:s,label:l.label,entity:l.entity,token_ids:Array.from(l.tokenIds),collections:Array.from(l.collections),tx_count:l.count,first_seen:l.first,last_seen:l.last}));return{sent:o(n),received:o(i)}}parseBlock(r){if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"&&r){let n=Number(r);return Number.isFinite(n)?n:void 0}}};p();var zQ=["all","7","30","60","90"],Fd=class extends oe{constructor(r){super();f(this,"name","get-wallet-pnl-summary");f(this,"description",`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Er(r.address,n),o=Fn(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=zQ.includes(a)?a:void 0;if(o){let _=await this.service.getWalletPnlSummary({address:i,chain:o,days:s});return _.success?{walletAddress:i,chain:o,days:s??"all",summary:this.mapSummary(_.data)}:{error:_.error||"Failed to fetch wallet PnL summary"}}let u=(await Promise.all(xi().map(async _=>{let b=await this.service.getWalletPnlSummary({address:i,chain:_,days:s});return{chain:_,data:b.success?b.data:void 0}}))).flatMap(_=>_.data&&_.data.total_count_of_trades>0?[{chain:_.chain,data:_.data}]:[]),c=u.map(_=>({chain:Ce(_.chain),summary:this.mapSummary(_.data)})),d=u.reduce((_,b)=>_+Number(b.data.total_realized_profit_usd||0),0),h=u.reduce((_,b)=>_+Number(b.data.total_bought_volume_usd||0),0),m=u.reduce((_,b)=>_+Number(b.data.total_sold_volume_usd||0),0),g=u.reduce((_,b)=>_+Number(b.data.total_trade_volume||0),0),y={totalCountOfTrades:u.reduce((_,b)=>_+b.data.total_count_of_trades,0),totalTradeVolume:g,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:h>0?d/h*100:0,totalBuys:u.reduce((_,b)=>_+b.data.total_buys,0),totalSells:u.reduce((_,b)=>_+b.data.total_sells,0),totalBoughtVolumeUsd:h,totalSoldVolumeUsd:m};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:i,chain:"all",days:s??"all",summary:y,chains:c}}mapSummary(r){return{totalCountOfTrades:r.total_count_of_trades,totalTradeVolume:r.total_trade_volume,totalRealizedProfitUsd:r.total_realized_profit_usd,totalRealizedProfitPercentage:r.total_realized_profit_percentage,totalBuys:r.total_buys,totalSells:r.total_sells,totalBoughtVolumeUsd:r.total_bought_volume_usd,totalSoldVolumeUsd:r.total_sold_volume_usd}}};p();var VQ=["all","7","30","60","90"],sv=25,Bd=class extends oe{constructor(r){super();f(this,"name","get-wallet-pnl");f(this,"description",`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${sv}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${sv}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${sv}.`,required:!1,items:{type:"string"}}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Er(r.address,n),o=Fn(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=VQ.includes(a)?a:void 0,l=Array.isArray(r.tokenSymbols)?r.tokenSymbols.filter(h=>typeof h=="string"&&!!h.trim()).map(h=>h.trim()):[],u=Array.isArray(r.tokenAddresses)?r.tokenAddresses.filter(h=>typeof h=="string"&&!!h.trim()).map(h=>h.trim()):[];if(o){let h=await this.fetchChainPnl(i,o,s,l,u);return h.ok?{walletAddress:i,chain:o,days:s??"all",filters:{tokenAddresses:h.tokenAddresses??null,resolvedSymbols:h.resolvedFromSymbols.length>0?h.resolvedFromSymbols:null,unresolvedSymbols:h.unresolvedSymbols.length>0?h.unresolvedSymbols:null},tokenCount:h.tokens.length,tokens:h.tokens}:{error:h.error||"Failed to fetch wallet PnL"}}let d=(await Promise.all(xi().map(async h=>({chain:h,res:await this.fetchChainPnl(i,h,s,l,u)})))).filter(h=>h.res.ok&&h.res.tokens.length>0).map(h=>({chain:Ce(h.chain),tokenCount:h.res.tokens.length,tokens:h.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:i,chain:"all",days:s??"all",filters:{requestedSymbols:l.length>0?l:null,requestedAddresses:u.length>0?u:null},tokenCount:d.reduce((h,m)=>h+m.tokenCount,0),chains:d}}async fetchChainPnl(r,n,i,o,a){let s=[],l=[];o.length>0&&(await Promise.all(o.map(m=>this.resolveContractAddress(m,n,r)))).forEach((m,g)=>{m?s.push({symbol:o[g],address:m.address}):l.push(o[g])});let u=ZQ([...s.map(h=>h.address),...a]).slice(0,sv),c=u.length>0?u:void 0,d=await this.service.getWalletPnl({address:r,chain:n,days:i,tokenAddresses:c});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:c,resolvedFromSymbols:s,unresolvedSymbols:l}}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}}}};function ZQ(t){let e=new Set,r=[];for(let n of t){let i=n.toLowerCase();e.has(i)||(e.add(i),r.push(n))}return r}p();var HQ=BigInt(2)**BigInt(255),zd=class extends oe{constructor(r){super();f(this,"name","get-wallet-approvals");f(this,"description",`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Er(r.address,n),o=Lr(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):100,l=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,u=await this.service.getWalletApprovals({address:i,chain:o,limit:s,cursor:l});if(!u.success)return{error:u.error||"Failed to fetch wallet approvals"};let c=u.data,h=(c.result||[]).map(_=>GQ(_)),m=0,g=0,y=[];for(let _ of h){_.isUnlimited&&(g+=1);let b=parseFloat(_.token.usdAtRisk??"");Number.isFinite(b)&&(m+=b);let w=_.token.possibleSpam||_.token.verifiedContract===!1,T=!_.spender.label&&!_.spender.entity;(w||_.isUnlimited&&T)&&y.push(_)}return{walletAddress:i,chain:o||"default",filters:{limit:s,cursor:l??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??s,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:h.length,unlimitedApprovals:g,totalUsdAtRisk:m,riskyApprovalCount:y.length},approvals:h,riskyApprovals:y}}};function GQ(t){let e=WQ(t.value);return{blockNumber:t.block_number,blockTimestamp:t.block_timestamp??null,transactionHash:t.transaction_hash??null,value:t.value,valueFormatted:t.value_formatted??null,isUnlimited:e,token:{address:t.token.address,addressLabel:t.token.address_label??null,name:t.token.name??null,symbol:t.token.symbol??null,logo:t.token.logo??null,possibleSpam:!!t.token.possible_spam,verifiedContract:t.token.verified_contract??null,currentBalance:t.token.current_balance??null,currentBalanceFormatted:t.token.current_balance_formatted??null,usdPrice:t.token.usd_price??null,usdAtRisk:t.token.usd_at_risk??null},spender:{address:t.spender.address,label:t.spender.address_label??null,entity:t.spender.entity??null,entityLogo:t.spender.entity_logo??null}}}function WQ(t){if(!t)return!1;try{return BigInt(t)>=HQ}catch{return!1}}p();var Vd=class extends oe{constructor(r){super();f(this,"name","get-wallet-defi-summary");f(this,"description",`Get a wallet's DeFi protocols summary: which protocols the wallet is using, total USD value locked across all protocols, total unclaimed rewards/fees, number of active protocols, and total number of positions. Returns a per-protocol breakdown (protocol name, logo, url, positions count, usd value, unclaimed). Use for questions like: "Which DeFi protocols am I using?", "What's my total DeFi value?", "How much do I have in DeFi?", "Show my DeFi portfolio overview", "Unclaimed rewards across protocols". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Do NOT use for: detailed per-position data \u2192 get-wallet-defi-positions; positions inside a single protocol \u2192 get-wallet-defi-protocol-positions.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Er(r.address,n),o=Fn(r.chain,n);if(o){let l=await this.service.getWalletDefiSummary({address:i,chain:o});return l.success?{walletAddress:i,chain:o,...this.summaryFields(l.data)}:{error:l.error||"Failed to fetch wallet DeFi summary"}}let s=(await Promise.all(xi().map(async l=>{let u=await this.service.getWalletDefiSummary({address:i,chain:l});return{chain:l,data:u.success?u.data:void 0}}))).flatMap(l=>l.data&&l.data.active_protocols>0?[{chain:Ce(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.summaryFields(l.data)})).sort((l,u)=>u.totalUsdValue-l.totalUsdValue);return{_instructions:"These DeFi summaries cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains with DeFi activity, highest total value first). Present one section per chain, in order: the chain name then its protocols. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:i,chain:"all",totalUsdValue:s.reduce((l,u)=>l+u.totalUsdValue,0),totalUnclaimedUsdValue:s.reduce((l,u)=>l+u.totalUnclaimedUsdValue,0),chains:s}}summaryFields(r){return{activeProtocols:r.active_protocols,totalPositions:r.total_positions,totalUsdValue:r.total_usd_value,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,protocols:(r.protocols||[]).map(n=>({protocolName:n.protocol_name,protocolId:n.protocol_id,protocolUrl:n.protocol_url,protocolLogo:n.protocol_logo,positions:n.positions,totalUsdValue:n.total_usd_value,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,accountHealthFactor:n.account_health_factor??null}))}}};p();var Zd=class extends oe{constructor(r){super();f(this,"name","get-wallet-defi-positions");f(this,"description",'Get every DeFi position a wallet holds across all supported protocols, with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Do NOT use for: aggregate totals \u2192 get-wallet-defi-summary; positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=Er(r.address,n),o=Fn(r.chain,n);if(o){let l=await this.service.getWalletDefiPositions({address:i,chain:o});if(!l.success)return{error:l.error||"Failed to fetch wallet DeFi positions"};let u=l.data||[];return{walletAddress:i,chain:o,positionCount:u.length,positions:u.map(LU)}}let s=(await Promise.all(xi().map(async l=>{let u=await this.service.getWalletDefiPositions({address:i,chain:l});return{chain:l,rows:u.success?u.data||[]:[]}}))).filter(l=>l.rows.length>0).map(l=>({chain:Ce(l.chain),positionCount:l.rows.length,positions:l.rows.map(LU)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:i,chain:"all",positionCount:s.reduce((l,u)=>l+u.positionCount,0),chains:s}}};function LU(t){return{protocolName:t.protocol_name,protocolId:t.protocol_id,protocolUrl:t.protocol_url,protocolLogo:t.protocol_logo,accountHealthFactor:t.account_data?.health_factor??null,position:KQ(t.position)}}function KQ(t){return{label:t.label,address:t.address,balanceUsd:t.balance_usd,totalUnclaimedUsdValue:t.total_unclaimed_usd_value,tokens:(t.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:t.position_details??null}}p();var Hd=class extends oe{constructor(r){super();f(this,"name","get-wallet-defi-protocol-positions");f(this,"description",'Get every position a wallet holds inside a specific DeFi protocol, with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "what do I have on Aave v3", "show my Lido staking", "my Curve pools", "Pendle positions". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions; totals only \u2192 get-wallet-defi-summary.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-summary to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=r.protocol?.trim();if(!i)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=Er(r.address,n),a=Fn(r.chain,n);if(a){let u=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:a});return u.success?u.data?{walletAddress:o,chain:a,...this.protocolFields(u.data)}:{error:"No data returned for this protocol"}:{error:u.error||"Failed to fetch wallet DeFi protocol positions"}}let l=(await Promise.all(xi().map(async u=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:u});return{chain:u,data:c.success?c.data:void 0}}))).flatMap(u=>u.data&&(u.data.positions||[]).length>0?[{chain:Ce(u.chain),data:u.data}]:[]).map(u=>({chain:u.chain,...this.protocolFields(u.data)})).sort((u,c)=>c.totalUsdValue-u.totalUsdValue);return{_instructions:`These ${i} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:i,totalUsdValue:l.reduce((u,c)=>u+c.totalUsdValue,0),chains:l}}protocolFields(r){return{protocolName:r.protocol_name,protocolId:r.protocol_id,protocolUrl:r.protocol_url,protocolLogo:r.protocol_logo,totalUsdValue:r.total_usd_value,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,accountHealthFactor:r.account_data?.health_factor??null,positionCount:(r.positions||[]).length,positions:(r.positions||[]).map(YQ)}}};function YQ(t){return{label:t.label,address:t.address,balanceUsd:t.balance_usd,totalUnclaimedUsdValue:t.total_unclaimed_usd_value,tokens:(t.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:t.position_details??null}}p();function JQ(t){try{return(Number(BigInt(t))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return t}}var Gd=class extends oe{constructor(r){super();f(this,"name","get-transaction-by-hash");f(this,"description",'Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=r.transactionHash;if(!i)return{error:"Transaction hash is required."};let o=Lr(r.chain,n),a=await this.service.getTransactionByHash({transactionHash:i,chain:o});if(!a.success||!a.data)return{error:a.error||"Failed to fetch transaction"};let s=a.data,l=(s.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),u=s.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:s.hash,status:s.receipt_status==="1"?"success":s.receipt_status==="0"?"failed":"unknown",timestamp:s.block_timestamp,blockNumber:s.block_number,from:{address:s.from_address,label:s.from_address_label||null,entity:s.from_address_entity||null},to:s.to_address?{address:s.to_address,label:s.to_address_label||null,entity:s.to_address_entity||null}:null,valueEth:JQ(s.value||"0"),fee:s.transaction_fee,gasUsed:s.receipt_gas_used,gasPriceGwei:s.gas_price?(Number(s.gas_price)/1e9).toFixed(4):null,decodedCall:s.decoded_call?{signature:s.decoded_call.signature,label:s.decoded_call.label,params:s.decoded_call.params}:null,decodedEvents:l,contractCreated:s.receipt_contract_address||null,logs:u}}};p();var Wd=class extends oe{constructor(r){super();f(this,"kind","data");f(this,"category","nft");f(this,"noSuggestions",!0);f(this,"parameters",[]);f(this,"linkPhrase","this website");f(this,"url");let n=r?.url?.trim();this.url=n||void 0}async run(){let r=this.url?`[${this.linkPhrase}](${this.url})`:this.linkPhrase,n=this.template.replace("{link}",r);return{message:n,_instructions:"This is a fixed notice that ALREADY contains the correct Markdown link. Reply with a SINGLE sentence in the USER'S language that conveys it (translate the wording naturally \u2014 do NOT leave it in English when the user wrote another language). "+(this.url?`You MUST reproduce the Markdown link and keep it CLICKABLE: keep the URL byte-for-byte; you may localize only the visible link text. Keep the form [text](${this.url}). NEVER output the sentence without the link, and NEVER show the raw URL on its own. `:"There is NO website link configured: keep the website phrase as PLAIN TEXT. NEVER add, invent, guess, or fabricate any URL or Markdown link \u2014 there is no link to show. ")+`Output ONLY that one sentence \u2014 do NOT also include the original English, a second copy, or any preamble. Do not mention tools. The exact message to convey (it already includes the link):
455
455
 
456
- `+n}}};p();p();var Kd=class extends Wd{constructor(){super(...arguments);f(this,"name","get-wallet-nfts");f(this,"description",'Use when the user wants to view their NFTs / NFT collection / holdings ("my NFTs", "show my NFTs", "what NFTs do I own", "NFT collection"). Returns a fixed notice directing them to the NFT website. Takes no arguments.');f(this,"template","Please view your NFT collection on {link} for more details")}};p();p();var XQ="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",Fo=class extends oe{constructor(){super();f(this,"kind","data");f(this,"category","nft");f(this,"llm");this.llm=new Pr({})}static promptParams(r){return[{name:"prompt",type:"string",description:r,required:!0}]}async run(r){let n=typeof r.prompt=="string"?r.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let i=await this.askGeminiWithSearch(n);return i?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:i}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(r){let n=Date.now();try{return(await this.llm.chat([{role:"system",content:XQ,timestamp:n},{role:"user",content:r,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Yd=class extends Fo{constructor(){super(...arguments);f(this,"name","get-nft-contract-info");f(this,"description",'Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.');f(this,"parameters",Fo.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`));f(this,"presentInstructions","Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks.")}};p();var Jd=class extends Fo{constructor(){super(...arguments);f(this,"name","get-nft-metadata");f(this,"description",'Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.');f(this,"parameters",Fo.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`));f(this,"presentInstructions","Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points.")}};p();p();p();p();var kA={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},PA="amazon.com";function QQ(t){return t?t.trim().toLowerCase().split(/[-_]/)[0]:""}function EA(t){let e=QQ(t);return kA[e]??PA}function lv(t){return`https://${EA(t)}/s?k=NFC%20Tag`}p();function uv(t){if(!t)return"";let e=t.trim().toUpperCase().split(/[-_]/),r=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(r)?r:""}var eee=720*60*1e3,qU=new Map,jU=3;function tee(t){return[`A user in country "${t}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${jU} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function ree(t){if(!t)return[];let e=t.indexOf("["),r=t.lastIndexOf("]");if(e===-1||r===-1||r<=e)return[];let n;try{n=JSON.parse(t.slice(e,r+1))}catch{return[]}if(!Array.isArray(n))return[];let i=[],o=new Set;for(let a of n){if(!a||typeof a!="object")continue;let s=a.label,l=a.url;if(typeof s!="string"||!s.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let u=l.trim().toLowerCase();if(!o.has(u)&&(o.add(u),i.push({label:s.trim(),url:l.trim()}),i.length>=jU))break}return i}async function AA(t,e){let r=uv(t);if(!r||!e)return null;let n=qU.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:tee(r),timestamp:i}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=ree(a.text);if(s.length)return qU.set(r,{links:s,expires:Date.now()+eee}),s}catch{}return null}async function Xd(t){let e=await AA(t.country,t.llm);return e&&e.length?e:[{label:"Amazon",url:lv(t.language)}]}function nee(t){return t.length<=1?t.length===1?`[${t[0].label}](${t[0].url})`:"":t.map((e,r)=>`${r+1}. [${e.label}](${e.url})`).join(`
456
+ `+n}}};p();p();var Kd=class extends Wd{constructor(){super(...arguments);f(this,"name","get-wallet-nfts");f(this,"description",'Use when the user wants to view their NFTs / NFT collection / holdings ("my NFTs", "show my NFTs", "what NFTs do I own", "NFT collection"). Returns a fixed notice directing them to the NFT website. Takes no arguments.');f(this,"template","Please view your NFT collection on {link} for more details")}};p();p();var XQ="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",Fo=class extends oe{constructor(r){super();f(this,"kind","data");f(this,"category","nft");f(this,"llm");this.llm=new Pr(r??{})}static promptParams(r){return[{name:"prompt",type:"string",description:r,required:!0}]}async run(r){let n=typeof r.prompt=="string"?r.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let i=await this.askGeminiWithSearch(n);return i?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:i}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(r){let n=Date.now();try{return(await this.llm.chat([{role:"system",content:XQ,timestamp:n},{role:"user",content:r,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Yd=class extends Fo{constructor(){super(...arguments);f(this,"name","get-nft-contract-info");f(this,"description",'Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.');f(this,"parameters",Fo.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`));f(this,"presentInstructions","Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks.")}};p();var Jd=class extends Fo{constructor(){super(...arguments);f(this,"name","get-nft-metadata");f(this,"description",'Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.');f(this,"parameters",Fo.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`));f(this,"presentInstructions","Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points.")}};p();p();p();p();var kA={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},PA="amazon.com";function QQ(t){return t?t.trim().toLowerCase().split(/[-_]/)[0]:""}function EA(t){let e=QQ(t);return kA[e]??PA}function lv(t){return`https://${EA(t)}/s?k=NFC%20Tag`}p();function uv(t){if(!t)return"";let e=t.trim().toUpperCase().split(/[-_]/),r=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(r)?r:""}var eee=720*60*1e3,qU=new Map,jU=3;function tee(t){return[`A user in country "${t}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${jU} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function ree(t){if(!t)return[];let e=t.indexOf("["),r=t.lastIndexOf("]");if(e===-1||r===-1||r<=e)return[];let n;try{n=JSON.parse(t.slice(e,r+1))}catch{return[]}if(!Array.isArray(n))return[];let i=[],o=new Set;for(let a of n){if(!a||typeof a!="object")continue;let s=a.label,l=a.url;if(typeof s!="string"||!s.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let u=l.trim().toLowerCase();if(!o.has(u)&&(o.add(u),i.push({label:s.trim(),url:l.trim()}),i.length>=jU))break}return i}async function AA(t,e){let r=uv(t);if(!r||!e)return null;let n=qU.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:tee(r),timestamp:i}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=ree(a.text);if(s.length)return qU.set(r,{links:s,expires:Date.now()+eee}),s}catch{}return null}async function Xd(t){let e=await AA(t.country,t.llm);return e&&e.length?e:[{label:"Amazon",url:lv(t.language)}]}function nee(t){return t.length<=1?t.length===1?`[${t[0].label}](${t[0].url})`:"":t.map((e,r)=>`${r+1}. [${e.label}](${e.url})`).join(`
457
457
  `)}var FU=["WHAT IT IS: NFC (Near-Field Communication) is a short-range wireless standard operating at 13.56 MHz, a",'subset of the older RFID family. An "NFC tag" is a tiny passive chip + antenna (often embedded in a','sticker, card, keyfob, wristband, or ring). "Passive" means it has no battery \u2014 it draws all its power from',"the electromagnetic field of the reader (a smartphone or dedicated reader) when held within ~2\u20134 cm. The","tag does nothing on its own; it simply waits to be tapped, then hands over the small piece of data it holds.","","HOW IT WORKS: When an NFC-enabled phone comes close, the reader emits a 13.56 MHz radio field. Through","inductive (magnetic) coupling that field powers the tag, which then transmits its stored data back to the","reader \u2014 no pairing, no app launch, no internet required for the handshake. The exchange is bidirectional","and near-instant (well under a second). Tags can be READ many times and, unless locked, also re-WRITTEN.","Data is stored in the standardised NDEF format (NFC Data Exchange Format) so any NFC phone can parse it the","same way. NFC works in three modes: reader/writer (phone reads or writes a tag), peer-to-peer (two devices","exchange data), and card-emulation (the phone itself acts like a tag, e.g. for tap-to-pay).","","WHAT'S INSIDE AN NFC TAG: just two parts \u2014 (1) a microchip (the integrated circuit) that holds a small","block of memory plus simple logic, and (2) a thin coiled antenna (usually etched copper or aluminium) that","both harvests power from the reader's field and carries the data signal. There is no battery and no moving","parts, which is why tags are paper-thin, cheap, and last for years (often rated for ~10 years of storage","and 100,000+ rewrites). Common chips differ mainly by memory size: NTAG213 (~144 bytes), NTAG215","(~504 bytes), NTAG216 (~888 bytes); larger/industrial families (e.g. ICODE, MIFARE) add more memory or","security features.","","WHAT IT CAN STORE: capacity is small \u2014 tens to a few hundred bytes of usable memory \u2014 so a tag holds a","compact payload, not files. Typical contents: a website URL, plain text, a contact card (vCard), Wi-Fi","credentials (SSID + password for one-tap join), an app-launch or deep link, a phone number / email,","geo-coordinates, a Bluetooth pairing handoff, or a small identifier/token. It is NOT mass storage \u2014 large","content lives elsewhere and the tag holds a pointer (a link or ID) to it.","","COMMON REAL-WORLD USES: contactless payments (Apple Pay / Google Pay via card emulation); transit and","access cards (metro, office door badges, hotel keys); product tags and anti-counterfeit / authenticity","checks; smart posters and marketing (tap to open a page, menu, or promo); pairing speakers/headphones with",'one tap; digital business cards and "tap to share contact"; smart-home automations (tap a tag by the door',"to run a routine); inventory, asset tracking, and ticketing; and tap-to-act crypto flows (e.g. open a","wallet address or a dapp link).","","HOW TO USE ONE: (1) Get an NFC tag (sticker/card/keyfob). (2) Make sure the phone has NFC enabled","(Settings \u2192 Connections/NFC; most modern Android phones and iPhone XS and later support it). (3) To WRITE,",'install an NFC writer app (e.g. "NFC Tools"), choose the record type (URL, text, Wi-Fi\u2026), enter the data,',"and tap the phone to the tag to program it. (4) To READ, just tap the phone to the tag \u2014 the action fires","automatically. (5) Optionally LOCK the tag to make it read-only so the data cannot be overwritten. Keep the","tag away from metal surfaces, which can detune the antenna and block reads.","","WHY THEY ARE POPULAR: they are extremely cheap (cents each), battery-free and maintenance-free, work with","the phone almost everyone already carries, and need just a tap \u2014 no app pairing, codes, or setup. The very","short range is a feature, not a bug: you must deliberately bring the devices together, which makes NFC","trusted for payments and access where accidental or remote reads would be a security risk.","","CRYPTO / WALLET CONTEXT: because a tag can hold a short identifier or address, NFC is handy for tap-to-act","flows \u2014 e.g. encoding a public wallet address or a deep link. Private keys/seed phrases should never be","written to an open, re-writable tag; treat tags as public, tamper-readable pointers, not secure key vaults.","","PRACTICAL TIPS: re-writable blank tags are inexpensive; pick a chip with enough memory for the payload",'(NTAG215+ for longer URLs or vCards). Use a metal-shielded ("on-metal") tag if you must stick it to a',"metal surface. Range is intentionally tiny (a few cm) for security \u2014 you must deliberately tap."].join(`
458
458
  `),Qd=class extends oe{constructor(r){super();f(this,"kind","data");f(this,"name","nfc-info");f(this,"category","nfc");f(this,"description",'Use when the user asks a conceptual / how-to question about NFC tags \u2014 what an NFC tag is, how NFC works, what data a tag can store, tag types/capacity, or how to read/write/use one ("what is an NFC tag", "how does NFC work", "what can I store on an NFC tag", "how do I use an NFC tag"). Returns an expert reference to answer from, plus a country-appropriate Amazon buy link to close with. Pass the current turn\'s BCP-47 `language` so the right storefront is picked. For a pure "where to buy" question with no explanation needed, prefer nfc-buy-link.');f(this,"parameters",[{name:"language",type:"string",description:`The BCP-47 language tag of the user's current message (e.g. "en", "vi", "ja", "zh", "de"). Used only to pick the local Amazon storefront for the closing buy link. Optional (defaults to amazon.com).`,required:!1}]);f(this,"llm");r&&(this.llm=new Pr(r))}async run(r,n){let i=typeof r.language=="string"&&r.language.trim()?r.language.trim():void 0,o=await Xd({country:n?.country,language:i,llm:this.llm}),a=nee(o),s=o.length>1;return{reference:FU,marketplaceLinks:o,_instructions:`Answer the user's NFC question as a knowledgeable, friendly expert, writing in the USER'S language (translate naturally \u2014 never leave it in English when they wrote another language). Draw on the reference below for the facts (do NOT invent anything beyond it), but write a polished, well-organized answer \u2014 not a terse one-liner. FORMAT: Use short Markdown section headings (bold or "##") and bullet points so it is easy to scan, similar to a great encyclopedia entry. For a broad question like "what is an NFC tag", give a thorough multi-section answer: open with a 1\u20132 sentence plain-language definition, then cover sections such as "How it works", "What's inside", "What it can store", "Common uses", "How to use one", and "Why they're popular" \u2014 include concrete specifics (the 13.56 MHz frequency, chip names + byte capacities, example payloads, numbered steps). Aim for genuinely useful depth, several short paragraphs/lists, not a wall of dense text. For a NARROW question (e.g. only "what can it store" or "how do I write one"), answer just that part in focused detail and skip the unrelated sections. Do not mention tools, this reference, or that anything is canned. AT THE END, add a short closing line telling them where they can buy NFC tags, then include EACH of these exact CLICKABLE Markdown links `+(s?"as a NUMBERED Markdown list (1., 2., 3.), ONE store per line, in this exact order and numbering":"inline")+` (keep every URL byte-for-byte; localize only the visible text; keep the form [text](url)):
459
459
  ${a}
@@ -1485,7 +1485,7 @@ Return JSON only.`,timestamp:Date.now()}],h=[{role:"system",content:Gte,timestam
1485
1485
 
1486
1486
  IDENTITY: This applies ONLY when the user asks who or what you are. In that case, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline. This identity rule does NOT change how you handle restricted topics below \u2014 for those, follow the RESTRICTED TOPICS rule exactly.`,H4e=`
1487
1487
 
1488
- RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,LP=class{constructor(e){f(this,"llm");f(this,"registry");f(this,"history");f(this,"summarizer");f(this,"router");f(this,"rewriter");f(this,"subagents");f(this,"synthesizer");f(this,"chatGraph");f(this,"systemPrompt");f(this,"debug");f(this,"secretKey");f(this,"licenseChecked",!1);f(this,"userContext",{});f(this,"storage");f(this,"storageKey");f(this,"persistHistoryEnabled");f(this,"x402Signer",null);f(this,"kb");f(this,"kbEntries");f(this,"vectorKB",null);f(this,"vectorKBAutoIngested",!1);f(this,"vectorKBAutoIngestPromise",null);f(this,"autoIngestEnabled",!1);f(this,"kbAnswerThreshold");f(this,"suggestionsEnabled");f(this,"historyLoaded",!1);f(this,"historyLoadingPromise",null);f(this,"inFlightTurn",null);f(this,"currentAbortController",null);f(this,"historyReady");this.secretKey=e.secretKey,$A(e.rpcUrls),rv(e.excludeChains),this.llm=new Pr(e.llm),this.registry=new Td,this.history=new qp(e.maxHistoryMessages??50),this.summarizer=new jp(this.llm),this.synthesizer=new zp(this.llm),this.systemPrompt=(e.systemPrompt??V4e)+Z4e+H4e,this.debug=e.debug??!1,this.suggestionsEnabled=e.generateSuggestions??!0,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new Fp(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let r=e.vectorKB;r?.enabled?(r.provider?this.kb=r.provider:(this.vectorKB=new kl({url:r.url,token:r.token,namespace:r.namespace,minScore:r.minScore,defaultTopK:r.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=r.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${r.provider?"custom provider":"Upstash"}`+(r.namespace?`, ns=${r.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:r?.enabled&&!r.provider?this.kbAnswerThreshold=r.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let d=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Ud(d)),this.registry.register(new Od(d)),this.registry.register(new Ld(d)),this.registry.register(new qd(d)),this.registry.register(new jd(d)),this.registry.register(new Rd(d)),this.registry.register(new Fd(d)),this.registry.register(new Bd(d)),this.registry.register(new Gd(d)),this.registry.register(new Vd(d)),this.registry.register(new Zd(d)),this.registry.register(new Hd(d)),this.registry.register(new zd(d)),this.registry.register(new Md(d)),this.registry.register(new Dd(d)),this.registry.register(new Nd(d)),this.registry.register(new $d(d))}let i=e.nftLink;this.registry.register(new Kd({url:i})),this.registry.register(new Yd),this.registry.register(new Jd),e.subagents?.nfc===!0&&(this.registry.register(new Qd(e.llm)),this.registry.register(new ep(e.llm))),this.registry.register(new tp(e.llm));let o=e.subagents?.["pool-subgraph"]===!0,a=o?e.subagents?.pool===!0:e.subagents?.pool!==!1;if(a&&e.uniswap!==!1){let d=typeof e.uniswap=="object"?e.uniswap:void 0,h=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new pp(d,h)),this.registry.register(new fp(d)),this.registry.register(new hp(d)),this.registry.register(new mp(d)),this.registry.register(new _p(d));let m=d?{isProduction:d.isProduction}:void 0;this.registry.register(new gp({baseUrl:d?.baseUrl,pool:m,minProvideUsd:d?.minProvideUsd})),this.registry.register(new yp({pool:m})),this.registry.register(new bp),this.registry.register(new vp)}if((a||o)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new rp(e.llm)),o&&e.subgraph!==!1){let d=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new wp(d)),this.registry.register(new Sp(d)),this.registry.register(new Tp(d)),this.registry.register(new kp(d)),this.registry.register(new Pp(d)),this.registry.register(new Ep(d)),this.registry.register(new Ap(d))}let s=e.subagents?.["wallet-action-app"]===!0;if(s?!1:e.subagents?.["wallet-action"]!==!1){let d=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new Ip(d)),this.registry.register(new Op(d)),this.registry.register(new Lp(d,{url:i})),this.registry.register(new Rp(d)),this.registry.register(new Dp(d,{debug:this.debug})),this.registry.register(new Up(d,{debug:this.debug}))}if(s)for(let d of Pv({appLink:e.walletActionAppLink,nftLink:i}))this.registry.register(d);this.router=new Bp(this.llm,{debug:this.debug}),this.rewriter=new $v(this.llm,{debug:this.debug});let u=typeof e.subgraph=="object"?e.subgraph:void 0,c=Nv(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:u?.linkAddLiquidity},e.subagents);this.subagents=new Map(c.map(d=>[d.name,d])),this.chatGraph=KY(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let r of e)this.registry.register(r)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,r,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:v_()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(r)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,timestamp:Date.now()});let a=await this.registry.execute(e,r,this.userContext),s=a.data,l=a.success?s?.summary??"Done.":`Action failed: ${a.error??"unknown error"}`,u=v_(),c=a.success&&a.ui?[this.stampLanguage(a.ui,null)]:[],d={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:u};return c.length>0&&(d.uiActions=c),this.history.add(d),await this.persistHistory(),{answer:l,messageId:u,...c.length>0?{uiActions:c}:{}}}setX402Signer(e){this.x402Signer=e,hU(e?gA({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,r,n){this.assertLicense(),await this.loadHistory();let i=v_(),o=e,a=n?.userQuery||o?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let s;try{s=await hA(De,o,r)}catch(u){let d=`The payment couldn't be completed: ${u instanceof Error?u.message:String(u)}. Please try again.`;return this.history.add({role:"assistant",content:d,timestamp:Date.now(),messageId:i}),await this.persistHistory(),{answer:d,messageId:i}}return{...await this.synthesizeFromPaidData(a,s,i,n?.generateSuggestions??!0),messageId:i}}async synthesizeFromPaidData(e,r,n,i){let o=typeof r=="string"?r:JSON.stringify(r),a=this.systemPrompt+this.capabilitiesSummary(),s=`The user's question was: "${e}".
1488
+ RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,LP=class{constructor(e){f(this,"llm");f(this,"registry");f(this,"history");f(this,"summarizer");f(this,"router");f(this,"rewriter");f(this,"subagents");f(this,"synthesizer");f(this,"chatGraph");f(this,"systemPrompt");f(this,"debug");f(this,"secretKey");f(this,"licenseChecked",!1);f(this,"userContext",{});f(this,"storage");f(this,"storageKey");f(this,"persistHistoryEnabled");f(this,"x402Signer",null);f(this,"kb");f(this,"kbEntries");f(this,"vectorKB",null);f(this,"vectorKBAutoIngested",!1);f(this,"vectorKBAutoIngestPromise",null);f(this,"autoIngestEnabled",!1);f(this,"kbAnswerThreshold");f(this,"suggestionsEnabled");f(this,"historyLoaded",!1);f(this,"historyLoadingPromise",null);f(this,"inFlightTurn",null);f(this,"currentAbortController",null);f(this,"historyReady");this.secretKey=e.secretKey,$A(e.rpcUrls),rv(e.excludeChains),this.llm=new Pr(e.llm),this.registry=new Td,this.history=new qp(e.maxHistoryMessages??50),this.summarizer=new jp(this.llm),this.synthesizer=new zp(this.llm),this.systemPrompt=(e.systemPrompt??V4e)+Z4e+H4e,this.debug=e.debug??!1,this.suggestionsEnabled=e.generateSuggestions??!0,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new Fp(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let r=e.vectorKB;r?.enabled?(r.provider?this.kb=r.provider:(this.vectorKB=new kl({url:r.url,token:r.token,namespace:r.namespace,minScore:r.minScore,defaultTopK:r.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=r.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${r.provider?"custom provider":"Upstash"}`+(r.namespace?`, ns=${r.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:r?.enabled&&!r.provider?this.kbAnswerThreshold=r.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let d=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Ud(d)),this.registry.register(new Od({...d,llm:e.llm})),this.registry.register(new Ld(d)),this.registry.register(new qd(d)),this.registry.register(new jd(d)),this.registry.register(new Rd(d)),this.registry.register(new Fd(d)),this.registry.register(new Bd(d)),this.registry.register(new Gd(d)),this.registry.register(new Vd(d)),this.registry.register(new Zd(d)),this.registry.register(new Hd(d)),this.registry.register(new zd(d)),this.registry.register(new Md(d)),this.registry.register(new Dd(d)),this.registry.register(new Nd(d)),this.registry.register(new $d(d))}let i=e.nftLink;this.registry.register(new Kd({url:i})),this.registry.register(new Yd(e.llm)),this.registry.register(new Jd(e.llm)),e.subagents?.nfc===!0&&(this.registry.register(new Qd(e.llm)),this.registry.register(new ep(e.llm))),this.registry.register(new tp(e.llm));let o=e.subagents?.["pool-subgraph"]===!0,a=o?e.subagents?.pool===!0:e.subagents?.pool!==!1;if(a&&e.uniswap!==!1){let d=typeof e.uniswap=="object"?e.uniswap:void 0,h=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new pp(d,h)),this.registry.register(new fp(d)),this.registry.register(new hp(d)),this.registry.register(new mp(d)),this.registry.register(new _p(d));let m=d?{isProduction:d.isProduction}:void 0;this.registry.register(new gp({baseUrl:d?.baseUrl,pool:m,minProvideUsd:d?.minProvideUsd})),this.registry.register(new yp({pool:m})),this.registry.register(new bp),this.registry.register(new vp)}if((a||o)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new rp(e.llm)),o&&e.subgraph!==!1){let d=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new wp(d)),this.registry.register(new Sp(d)),this.registry.register(new Tp(d)),this.registry.register(new kp(d)),this.registry.register(new Pp(d)),this.registry.register(new Ep(d)),this.registry.register(new Ap(d))}let s=e.subagents?.["wallet-action-app"]===!0;if(s?!1:e.subagents?.["wallet-action"]!==!1){let d=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new Ip(d)),this.registry.register(new Op(d)),this.registry.register(new Lp(d,{url:i})),this.registry.register(new Rp(d)),this.registry.register(new Dp(d,{debug:this.debug})),this.registry.register(new Up(d,{debug:this.debug}))}if(s)for(let d of Pv({appLink:e.walletActionAppLink,nftLink:i}))this.registry.register(d);this.router=new Bp(this.llm,{debug:this.debug}),this.rewriter=new $v(this.llm,{debug:this.debug});let u=typeof e.subgraph=="object"?e.subgraph:void 0,c=Nv(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:u?.linkAddLiquidity},e.subagents);this.subagents=new Map(c.map(d=>[d.name,d])),this.chatGraph=KY(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let r of e)this.registry.register(r)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,r,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:v_()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(r)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,timestamp:Date.now()});let a=await this.registry.execute(e,r,this.userContext),s=a.data,l=a.success?s?.summary??"Done.":`Action failed: ${a.error??"unknown error"}`,u=v_(),c=a.success&&a.ui?[this.stampLanguage(a.ui,null)]:[],d={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:u};return c.length>0&&(d.uiActions=c),this.history.add(d),await this.persistHistory(),{answer:l,messageId:u,...c.length>0?{uiActions:c}:{}}}setX402Signer(e){this.x402Signer=e,hU(e?gA({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,r,n){this.assertLicense(),await this.loadHistory();let i=v_(),o=e,a=n?.userQuery||o?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let s;try{s=await hA(De,o,r)}catch(u){let d=`The payment couldn't be completed: ${u instanceof Error?u.message:String(u)}. Please try again.`;return this.history.add({role:"assistant",content:d,timestamp:Date.now(),messageId:i}),await this.persistHistory(),{answer:d,messageId:i}}return{...await this.synthesizeFromPaidData(a,s,i,n?.generateSuggestions??!0),messageId:i}}async synthesizeFromPaidData(e,r,n,i){let o=typeof r=="string"?r:JSON.stringify(r),a=this.systemPrompt+this.capabilitiesSummary(),s=`The user's question was: "${e}".
1489
1489
 
1490
1490
  A paid API returned this data:
1491
1491
  ${o}