keyring-agent-core 0.2.64 → 0.2.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -3
- package/dist/index.native.js +4 -3
- package/package.json +1 -1
package/dist/index.native.js
CHANGED
|
@@ -437,7 +437,7 @@ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}
|
|
|
437
437
|
`);return a===-1?"":i.stack.slice(a+1)})();try{if(!n.stack)n.stack=o;else if(o){let a=o.indexOf(`
|
|
438
438
|
`),s=a===-1?-1:o.indexOf(`
|
|
439
439
|
`,a+1),l=s===-1?"":o.slice(s+1);String(n.stack).endsWith(l)||(n.stack+=`
|
|
440
|
-
`+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Co(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&uy.assertOptions(n,{silentJSONParsing:zi.transitional(zi.boolean),forcedJSONParsing:zi.transitional(zi.boolean),clarifyTimeoutError:zi.transitional(zi.boolean),legacyInterceptorReqResOrdering:zi.transitional(zi.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:uy.assertOptions(i,{encode:zi.function,serialize:zi.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),uy.assertOptions(r,{baseUrl:zi.spelling("baseURL"),withXsrfToken:zi.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=kr.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||Rp;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let u,d=0,h;if(!l){let g=[p0.bind(this),void 0];for(g.unshift(...s),g.push(...c),h=g.length,u=Promise.resolve(r);d<h;)u=u.then(g[d++],g[d++]);return u}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{u=p0.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=c.length;d<h;)u=u.then(c[d++],c[d++]);return u}getUri(e){e=Co(this.defaults,e);let r=cy(e.baseURL,e.url,e.allowAbsoluteUrls);return oy(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){Up.prototype[e]=function(r,n){return this.request(Co(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(Co(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Up.prototype[e]=r(),e!=="query"&&(Up.prototype[e+"Form"]=r(!0))});var dy=Up;p();var sI=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 la(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}}},dF=sI;p();function lI(t){return function(r){return t.apply(null,r)}}p();function cI(t){return j.isObject(t)&&t.isAxiosError===!0}p();var uI={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(uI).forEach(([t,e])=>{uI[e]=t});var pF=uI;function hF(t){let e=new dy(t),r=ey(dy.prototype.request,e);return j.extend(r,dy.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return hF(Co(t,i))},r}var Nr=hF(Mp);Nr.Axios=dy;Nr.CanceledError=la;Nr.CancelToken=dF;Nr.isCancel=sy;Nr.VERSION=Dp;Nr.toFormData=Kl;Nr.AxiosError=De;Nr.Cancel=Nr.CanceledError;Nr.all=function(e){return Promise.all(e)};Nr.spread=lI;Nr.isAxiosError=cI;Nr.mergeConfig=Co;Nr.AxiosHeaders=kr;Nr.formToJSON=t=>l0(j.isHTMLForm(t)?new FormData(t):t);Nr.getAdapter=d0.getAdapter;Nr.HttpStatusCode=pF;Nr.default=Nr;var f0=Nr;var{Axios:jWe,AxiosError:FWe,CanceledError:BWe,isCancel:zWe,CancelToken:VWe,VERSION:HWe,all:ZWe,Cancel:GWe,isAxiosError:WWe,spread:KWe,toFormData:YWe,AxiosHeaders:JWe,HttpStatusCode:XWe,formToJSON:QWe,getAdapter:e9e,mergeConfig:t9e,create:r9e}=f0;var fF="0.2.
|
|
440
|
+
`+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Co(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&uy.assertOptions(n,{silentJSONParsing:zi.transitional(zi.boolean),forcedJSONParsing:zi.transitional(zi.boolean),clarifyTimeoutError:zi.transitional(zi.boolean),legacyInterceptorReqResOrdering:zi.transitional(zi.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:uy.assertOptions(i,{encode:zi.function,serialize:zi.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),uy.assertOptions(r,{baseUrl:zi.spelling("baseURL"),withXsrfToken:zi.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=kr.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||Rp;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let u,d=0,h;if(!l){let g=[p0.bind(this),void 0];for(g.unshift(...s),g.push(...c),h=g.length,u=Promise.resolve(r);d<h;)u=u.then(g[d++],g[d++]);return u}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{u=p0.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=c.length;d<h;)u=u.then(c[d++],c[d++]);return u}getUri(e){e=Co(this.defaults,e);let r=cy(e.baseURL,e.url,e.allowAbsoluteUrls);return oy(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){Up.prototype[e]=function(r,n){return this.request(Co(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(Co(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Up.prototype[e]=r(),e!=="query"&&(Up.prototype[e+"Form"]=r(!0))});var dy=Up;p();var sI=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 la(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}}},dF=sI;p();function lI(t){return function(r){return t.apply(null,r)}}p();function cI(t){return j.isObject(t)&&t.isAxiosError===!0}p();var uI={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(uI).forEach(([t,e])=>{uI[e]=t});var pF=uI;function hF(t){let e=new dy(t),r=ey(dy.prototype.request,e);return j.extend(r,dy.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return hF(Co(t,i))},r}var Nr=hF(Mp);Nr.Axios=dy;Nr.CanceledError=la;Nr.CancelToken=dF;Nr.isCancel=sy;Nr.VERSION=Dp;Nr.toFormData=Kl;Nr.AxiosError=De;Nr.Cancel=Nr.CanceledError;Nr.all=function(e){return Promise.all(e)};Nr.spread=lI;Nr.isAxiosError=cI;Nr.mergeConfig=Co;Nr.AxiosHeaders=kr;Nr.formToJSON=t=>l0(j.isHTMLForm(t)?new FormData(t):t);Nr.getAdapter=d0.getAdapter;Nr.HttpStatusCode=pF;Nr.default=Nr;var f0=Nr;var{Axios:jWe,AxiosError:FWe,CanceledError:BWe,isCancel:zWe,CancelToken:VWe,VERSION:HWe,all:ZWe,Cancel:GWe,isAxiosError:WWe,spread:KWe,toFormData:YWe,AxiosHeaders:JWe,HttpStatusCode:XWe,formToJSON:QWe,getAdapter:e9e,mergeConfig:t9e,create:r9e}=f0;var fF="0.2.65";var Oie=`keyring-agent-core/${fF} (Keyring Chatbot Agent; +https://keyring.app)`,dI=null;function mF(t){dI=t}var Rie=["payment-signature","x-payment"];function Nie(t){return t?Object.keys(t).some(e=>Rie.includes(e.toLowerCase())):!1}var gF;function py(t){gF=t}var Mie=3e4,$ie=typeof process<"u"&&process.versions?.node!=null,pI=class{constructor(e={}){f(this,"instance");this.instance=f0.create({baseURL:e.baseURL,timeout:e.timeout??Mie,validateStatus:()=>!0,headers:{Accept:"application/json",...$ie?{"User-Agent":e.userAgent??Oie}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??gF,a=await this.instance.request({...i,signal:o,method:e,url:r,data:n}),s={};for(let[c,u]of Object.entries(a.headers??{}))u!=null&&(s[c.toLowerCase()]=String(u));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:s};if(l.status===402&&dI&&!Nie(i.headers)){let c=await dI(l,{url:r,method:String(e),body:n,headers:i.headers});if(c)return this.request(e,r,n,{...i,headers:{...i.headers,...c}})}return l}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},ve=new pI;function Xe(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}p();p();p();p();function Die(t){return t instanceof yt?t.details||t.shortMessage:t instanceof Error?t.message:typeof t=="string"?t:""}var yt=class extends Error{constructor(r,n={}){let i=n.details??Die(n.cause),o=n.metaMessages??[],a=[r||"An error occurred.",...o.length>0?["",...o]:[],...i?["",`Details: ${i}`]:[]].join(`
|
|
441
441
|
`);super(a,n.cause!==void 0?{cause:n.cause}:void 0);f(this,"name","BaseError");f(this,"shortMessage");f(this,"details");f(this,"metaMessages");this.shortMessage=r,this.details=i,this.metaMessages=o,n.name&&(this.name=n.name)}walk(r){return yF(this,r)}};function yF(t,e){if(e?.(t))return t;let r=t&&typeof t=="object"?t.cause:void 0;return r!=null?yF(r,e):e?null:t}var Yl=class extends yt{constructor(r){super(`Type "${r}" is not a valid ABI type.`,{metaMessages:["Supported: address, bool, string, bytes, bytesN, (u)intN, tuple, and arrays of those."]});f(this,"name","AbiParameterTypeError")}},m0=class extends yt{constructor({expectedLength:r,givenLength:n}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${r}`,`Given length (values): ${n}`]});f(this,"name","AbiEncodingLengthMismatchError")}},g0=class extends yt{constructor({expectedLength:r,givenLength:n,type:i}){super(`ABI encoding array length mismatch for type ${i}.`,{metaMessages:[`Expected length: ${r}`,`Given length: ${n}`]});f(this,"name","AbiEncodingArrayLengthMismatchError")}},xo=class extends yt{constructor({type:r,value:n,reason:i}){super(`Invalid value for ABI type "${r}".`,{metaMessages:[`Value: ${_F(n)}`,`Reason: ${i}`]});f(this,"name","InvalidAbiValueError")}},y0=class extends yt{constructor({type:r,value:n,min:i,max:o}){super(`Number "${n}" is not in safe ${r} range.`,{metaMessages:[`Range: ${i} \u2026 ${o}`]});f(this,"name","IntegerOutOfRangeError")}},Lp=class extends yt{constructor(r){super(`Address "${_F(r)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]});f(this,"name","InvalidAddressError")}};function _F(t){if(typeof t=="bigint")return t.toString();if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var _0=class extends yt{constructor({expectedSize:r,value:n}){super(`Size of bytes "${n}" does not match expected size of bytes${r}.`);f(this,"name","AbiEncodingBytesSizeMismatchError")}},Jl=class extends yt{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{metaMessages:["The contract returned no data. Usually this means:","- the address is not a contract on this chain,","- the function does not exist on it, or","- the call was made before the contract was deployed."]});f(this,"name","AbiDecodingZeroDataError")}},b0=class extends yt{constructor({data:r,params:n,size:i}){super(`Data size of ${i} bytes is too small for given parameters.`,{metaMessages:[`Params: (${n.map(o=>o.type).join(", ")})`,`Data: ${r} (${i} bytes)`]});f(this,"name","AbiDecodingDataSizeTooSmallError");f(this,"data");f(this,"params");f(this,"size");this.data=r,this.params=n,this.size=i}},qp=class extends yt{constructor({position:r,length:n}){super(`Position ${r} is out of bounds (${n} bytes).`,{metaMessages:["The return data is truncated or not ABI-encoded."]});f(this,"name","AbiDecodingOutOfBoundsError")}},v0=class extends yt{constructor({name:r,type:n="function"}){super(`${n[0].toUpperCase()}${n.slice(1)} "${r}" not found on ABI.`,{metaMessages:["Make sure you are using the correct ABI and that the item exists on it."]});f(this,"name","AbiItemNotFoundError")}},Xl=class extends yt{constructor(r,n){super(`Invalid ABI signature: "${r}".`,{metaMessages:n?[n]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']});f(this,"name","InvalidAbiSignatureError")}};p();var Uie=/^0x[0-9a-fA-F]*$/;function zu(t,{strict:e=!0}={}){return typeof t!="string"?!1:e?Uie.test(t):t.startsWith("0x")}function ca(t){return t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t}function hy(t){return typeof t=="string"?Math.ceil(ca(t).length/2):t.length}function Vu(t,e,r){let n=ca(t),i=(e??0)*2,o=r===void 0?n.length:r*2;return`0x${n.slice(i,o)}`}function w0(t){return`0x${t.map(ca).join("")}`}function Hu(t){let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e}function Ql(t){let e=ca(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 il(t){let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return`0x${e}`}function hI(t){return new TextEncoder().encode(t)}function fI(t){return new TextDecoder().decode(t)}function ti(t,e={}){let{size:r,signed:n}=e,i=BigInt(t);if(i<0n){if(!r)throw new Error("numberToHex: negative values require a `size`");i+=1n<<BigInt(r*8)}else if(n&&r){let a=(1n<<BigInt(r*8-1))-1n;if(i>a)throw new Error(`numberToHex: ${t} overflows int${r*8}`)}let o=i.toString(16);if(!r)return`0x${o}`;if(o.length>r*2)throw new Error(`numberToHex: ${t} overflows ${r} bytes`);return`0x${o.padStart(r*2,"0")}`}function mI(t,e=32){if(t.length>e)throw new Error(`padLeft: ${t.length} bytes exceeds ${e}`);let r=new Uint8Array(e);return r.set(t,e-t.length),r}function gI(t,e=32){if(t.length>e)throw new Error(`padRight: ${t.length} bytes exceeds ${e}`);let r=new Uint8Array(e);return r.set(t),r}function Zu(t){let e=1n<<256n,r=(t%e+e)%e;return Ql(r.toString(16).padStart(64,"0"))}function jp(t,{signed:e=!1}={}){let r=BigInt(il(t));if(!e)return r;let n=BigInt(t.length*8);return r>=1n<<n-1n?r-(1n<<n):r}function Io(t,{signed:e=!1}={}){return ca(t)?jp(Ql(t),{signed:e}):0n}function S0(t,e={}){return Number(Io(t,e))}p();var bF=Fg(fy());var Lie=/^0x[0-9a-fA-F]{40}$/;function Ve(t){return typeof t=="string"&&Lie.test(t)}function Fp(t){let e=ca(t).toLowerCase(),r=(0,bF.keccak_256)(e),n="";for(let i=0;i<e.length;i++)n+=parseInt(r[i],16)>=8?e[i].toUpperCase():e[i];return`0x${n}`}function yI(t){if(!Ve(t))throw new Error(`Address "${t}" is invalid.`);return Fp(t)}function _I(t,e){return Ve(t)&&Ve(e)&&t.toLowerCase()===e.toLowerCase()}p();var bI=Fg(fy());function vF(t){return`0x${(0,bI.keccak_256)(new TextEncoder().encode(t))}`}function ec(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function tc(t){return t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function my(t){let e=tc(t.type);return e==="tuple"||e.startsWith("tuple[")?`(${(t.components??[]).map(my).join(",")})${e.slice(5)}`:e}function Bp(t){return`${t.name??""}(${(t.inputs??[]).map(my).join(",")})`}function ol(t){let e=typeof t=="string"?t:Bp(t);return`0x${(0,bI.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function vI(t){let e=typeof t=="string"?t:Bp(t);return vF(e)}function wF(t,e){let r=tc(e.type),n=ec(r);if(n){let[i,o]=n;return!Array.isArray(t)||i!==null&&t.length!==i?!1:t.every(a=>wF(a,{...e,type:o}))}if(r==="tuple"){let i=e.components??[];return Array.isArray(t)?t.length===i.length:typeof t=="object"&&t!==null}return r==="address"?typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t):r==="bool"?typeof t=="boolean":r==="string"?typeof t=="string":r.startsWith("bytes")?typeof t=="string"||t instanceof Uint8Array:r.startsWith("uint")||r.startsWith("int")?typeof t=="number"||typeof t=="bigint"||typeof t=="string":!0}function rc({abi:t,name:e,args:r,type:n}){let i=n??"function",o=t.filter(s=>(s.type??"function")===i);if(e.startsWith("0x")&&e.length===10)return o.find(s=>ol(s)===e.toLowerCase());if(e.includes("("))return o.find(s=>Bp(s)===e);let a=o.filter(s=>s.name===e);return a.length<=1||!r?a[0]:a.find(s=>{let l=s.inputs??[];return l.length===r.length&&l.every((c,u)=>wF(r[u],c))})??a[0]}function Gu(t){let e=rc(t);if(!e)throw new v0({name:t.name,type:t.type??"function"});return e}p();function SF(t){let e=new Uint8Array(Math.ceil(t.length/32)*32);return e.set(t),{dynamic:!0,encoded:Hu([Zu(BigInt(t.length)),e])}}function kF(t,e){let r=t.slice(e.length),n=r===""?256:Number(r);if(!Number.isInteger(n)||n<8||n>256||n%8!==0)throw new Yl(t);return n}function TF(t,e){if(typeof t=="bigint")return t;if(typeof t=="number"){if(!Number.isInteger(t))throw new xo({type:e,value:t,reason:"expected an integer, got a fractional number"});return BigInt(t)}if(typeof t=="string"&&t.trim()!=="")try{return BigInt(t.trim())}catch{throw new xo({type:e,value:t,reason:"string is not a valid integer"})}throw new xo({type:e,value:t,reason:"expected a bigint, number or numeric string"})}function PF(t,{bits:e,signed:r,type:n}){let i=r?(1n<<BigInt(e-1))-1n:(1n<<BigInt(e))-1n,o=r?-(1n<<BigInt(e-1)):0n;if(t<o||t>i)throw new y0({type:n,value:t,min:o,max:i})}function AF(t,e){if(t instanceof Uint8Array)return t;if(typeof t=="string"){if(!zu(t))throw new xo({type:e,value:t,reason:"expected 0x-prefixed hex"});return Ql(t)}throw new xo({type:e,value:t,reason:"expected a hex string or Uint8Array"})}function wI(t,e){let r=ec(t.type);if(r){let[i,o]=r;if(!Array.isArray(e))throw new xo({type:t.type,value:e,reason:"expected an array"});return qie({...t,type:o},e,i,t.type)}if(t.type==="tuple")return jie(t,e);let n=tc(t.type);if(n==="address"){if(!Ve(e))throw new Lp(e);return{dynamic:!1,encoded:mI(Ql(ca(e).toLowerCase()))}}if(n==="bool"){if(typeof e!="boolean")throw new xo({type:n,value:e,reason:"expected a boolean"});let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}if(/^uint\d*$/.test(n)){let i=TF(e,n);return PF(i,{bits:kF(n,"uint"),signed:!1,type:n}),{dynamic:!1,encoded:Zu(i)}}if(/^int\d*$/.test(n)){let i=TF(e,n);return PF(i,{bits:kF(n,"int"),signed:!0,type:n}),i<0n&&(i+=1n<<256n),{dynamic:!1,encoded:Zu(i)}}if(/^bytes\d+$/.test(n)){let i=Number(n.slice(5));if(i<1||i>32)throw new Yl(t.type);let o=AF(e,n);if(o.length!==i)throw new _0({expectedSize:i,value:String(e)});return{dynamic:!1,encoded:gI(o)}}if(n==="bytes")return SF(AF(e,n));if(n==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new xo({type:n,value:e,reason:"expected a string"});return SF(typeof e=="string"?hI(e):e)}throw new Yl(t.type)}function SI(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(Zu(BigInt(e+i))),n.push(a),i+=a.length):r.push(a);return Hu([...r,...n])}function qie(t,e,r,n){let i=r===null;if(!i&&e.length!==r)throw new g0({expectedLength:r,givenLength:e.length,type:n});let o=!1,a=[];for(let s of e){let l=wI(t,s);l.dynamic&&(o=!0),a.push(l)}if(i||o){let s=SI(a);if(!i)return{dynamic:!0,encoded:s};let l=Zu(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?Hu([l,s]):l}}return{dynamic:!1,encoded:Hu(a.map(s=>s.encoded))}}function jie(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=wI(a,Array.isArray(e)?e[o]:e[a.name??""]);s.dynamic&&(n=!0),i.push(s)}return{dynamic:n,encoded:n?SI(i):Hu(i.map(o=>o.encoded))}}function zp(t,e){if(t.length!==e.length)throw new m0({expectedLength:t.length,givenLength:e.length});return t.length===0?"0x":il(SI(t.map((r,n)=>wI(r,e[n]))))}p();function gt({abi:t,functionName:e,args:r=[]}){let n=Gu({abi:t,name:e,args:r,type:"function"}),i=ol(n),o=n.inputs??[];return o.length===0?i:w0([i,zp(o,r)])}function kI({abi:t,errorName:e,args:r=[]}){let n=Gu({abi:t,name:e,args:r,type:"error"}),i=n.inputs??[],o=ol(n);return i.length===0?o:w0([o,zp(i,r)])}p();function Fie(t){let e=t.replace(/^u?int/,"");return e?Number(e):256}function gy(t,e){if(e<0||e+32>t.length)throw new qp({position:e,length:t.length});return t.subarray(e,e+32)}function AI(t,e){let r=jp(gy(t,e));if(r>BigInt(t.length))throw new qp({position:Number(r),length:t.length});return Number(r)}function TI(t){let e=ec(t.type);if(e){let[n,i]=e;return n===null||TI({...t,type:i})}if(t.type==="tuple")return(t.components??[]).some(TI);let r=tc(t.type);return r==="bytes"||r==="string"}function PI(t){let e=ec(t.type);if(e){let[r,n]=e;return r===null?32:r*PI({...t,type:n})}return t.type==="tuple"?(t.components??[]).reduce((r,n)=>r+PI(n),0):32}function EI(t,e,r){let n=[],i=e;for(let o of r)TI(o)?(n.push(EF(t,e+AI(t,i),o)),i+=32):(n.push(EF(t,i,o)),i+=PI(o));return n}function Bie(t,e,r,n){let i=n===null?AI(t,e):n,o=n===null?e+32:e;return EI(t,o,new Array(i).fill(r))}function zie(t,e,r){let n=r.components??[],i=EI(t,e,n);if(n.length===0||n.some(s=>!s.name))return i;let a={};return n.forEach((s,l)=>{a[s.name]=i[l]}),a}function EF(t,e,r){let n=ec(r.type);if(n){let[o,a]=n;return Bie(t,e,{...r,type:a},o)}if(r.type==="tuple")return zie(t,e,r);let i=tc(r.type);if(i==="address")return Fp(il(gy(t,e).subarray(12)));if(i==="bool")return jp(gy(t,e))!==0n;if(/^u?int\d*$/.test(i)){let o=i.startsWith("int"),a=jp(gy(t,e),{signed:o});return Fie(i)>48?a:Number(a)}if(/^bytes\d+$/.test(i)){let o=Number(i.slice(5));return il(gy(t,e).subarray(0,o))}if(i==="bytes"||i==="string"){let o=AI(t,e),a=e+32;if(a+o>t.length)throw new qp({position:a+o,length:t.length});let s=t.subarray(a,a+o);return i==="bytes"?il(s):fI(s)}throw new Yl(r.type)}function Mn(t,e){let r=typeof e=="string"?Ql(e):e;if(r.length===0){if(t.length>0)throw new Jl;return[]}if(r.length<32)throw new b0({data:typeof e=="string"?e:il(e),params:t,size:r.length});return EI(r,0,t)}p();function Gr(t){if(!t)return null;try{let[e]=Mn([{type:"uint256"}],t);return e}catch{return null}}function rr(t){if(!t)return null;try{let[e]=Mn([{type:"address"}],t),r=e;return/^0x0{40}$/i.test(r)?null:r}catch{return null}}function yy(t){if(!t)return null;try{let[e]=Mn([{type:"string"}],t),r=CF(e);if(r)return r}catch{}try{let[e]=Mn([{type:"bytes32"}],t);return P0(e)}catch{return null}}function Vp(t){return T0(Gr(t))}function T0(t){let e=typeof t=="bigint"?Number(t):typeof t=="number"?t:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function P0(t){return typeof t!="string"||!t.startsWith("0x")?null:CF(Buffer.from(t.slice(2),"hex").toString("utf8"))||null}function CF(t){return t.replace(/[^\x20-\x7e]/g,"").trim()}p();function ua({abi:t,functionName:e,args:r,data:n}){let o=Gu({abi:t,name:e,args:r,type:"function"}).outputs??[],a=Mn(o,n);if(a.length!==0)return a.length===1?a[0]:a}function CI({abi:t,data:e}){let r=Vu(e,0,4),n=Gu({abi:t,name:r,type:"function"}),i=n.inputs??[];return{functionName:n.name,args:i.length===0||hy(e)<=4?[]:Mn(i,Vu(e,4))}}p();var xF={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},IF={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},OF={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array.",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."};function Hp({abi:t=[],data:e}){let r=Vu(e,0,4);if(hy(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let n=[...t,xF,IF],i=rc({abi:n,name:r,type:"error"})??n.find(a=>(a.type??"")==="error"&&ol(a)===r);if(!i)throw new Error(`Unknown error selector "${r}".`);let o=i.inputs??[];return{abiItem:i,errorName:i.name,args:o.length>0?Mn(o,Vu(e,4)):void 0}}function _y({abi:t,data:e}){if(!(!e||e==="0x"))try{let{errorName:r,args:n}=Hp({abi:t,data:e});if(r==="Error")return String(n?.[0]??"");if(r==="Panic"){let i=Number(n?.[0]??0);return OF[i]??`Panic code ${i}.`}return!n||n.length===0?r:`${r}(${n.map(i=>String(i)).join(", ")})`}catch{return}}p();var Vie=new Set(["pure","view","nonpayable","payable"]),Hie=new Set(["external","public","internal","private","calldata","memory","storage"]);function II(t,e){let r=0;for(let n=e;n<t.length;n++)if(t[n]==="(")r++;else if(t[n]===")"&&(r--,r===0))return n;throw new Xl(t,"Unbalanced parentheses.")}function NF(t){let e=[],r=0,n="";for(let i of t){if(i==="("&&r++,i===")"&&r--,i===","&&r===0){e.push(n),n="";continue}n+=i}return n.trim()&&e.push(n),e.map(i=>i.trim()).filter(Boolean)}function Zie(t){let e=t.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function RF(t,e){let r=!1,n;for(let i of t)i==="indexed"?r=!0:Hie.has(i)||(n=i);return{...e,...n?{name:n}:{},...r?{indexed:!0}:{}}}function OI(t){let e=t.trim();if(e.startsWith("(")){let i=II(e,0),o=NF(e.slice(1,i)).map(OI),{suffix:a,rest:s}=Zie(e.slice(i+1).trim());return RF(s.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:o})}let[r,...n]=e.split(/\s+/).filter(Boolean);if(!r)throw new Xl(t,"Missing parameter type.");return RF(n,{type:r})}function vy(t){return NF(t).map(OI)}function by(t,e,r){let n=t.indexOf("(",e);if(n===-1)throw new Xl(r,"Missing parameter list.");let i=II(t,n);return{name:t.slice(e,n).trim(),params:vy(t.slice(n+1,i)),rest:t.slice(i+1).trim()}}function xI(t,e){return t.split(/[\s()]+/).find(n=>Vie.has(n))??e}function A0(t){let e=t.trim();if(e.startsWith("function ")){let{name:r,params:n,rest:i}=by(e,9,t),o=i.indexOf("returns"),a=o===-1?i:i.slice(0,o),s=[];if(o!==-1){let l=i.indexOf("(",o);if(l===-1)throw new Xl(t,"`returns` without a parameter list.");s=vy(i.slice(l+1,II(i,l)))}return{type:"function",name:r,inputs:n,outputs:s,stateMutability:xI(a,"nonpayable")}}if(e.startsWith("event ")){let{name:r,params:n}=by(e,6,t);return{type:"event",name:r,inputs:n}}if(e.startsWith("error ")){let{name:r,params:n}=by(e,6,t);return{type:"error",name:r,inputs:n}}if(e.startsWith("constructor")){let{params:r,rest:n}=by(e,11,t);return{type:"constructor",inputs:r,stateMutability:xI(n,"nonpayable")}}if(e.startsWith("fallback")){let{rest:r}=by(e,8,t);return{type:"fallback",stateMutability:xI(r,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new Xl(t,"Expected function, event, error, constructor, fallback or receive.")}function RI(t){return t.map(A0)}p();p();p();p();function da({blockNumber:t,blockTag:e="latest"}={}){return t!==void 0?ti(t):e}function wy(t){let{account:e,to:r,data:n,value:i,gas:o,gasPrice:a,maxFeePerGas:s,maxPriorityFeePerGas:l,nonce:c}=t,u={};return e&&(u.from=e),r&&(u.to=r),n&&(u.data=n),i!==void 0&&(u.value=ti(i)),o!==void 0&&(u.gas=ti(o)),a!==void 0&&(u.gasPrice=ti(a)),s!==void 0&&(u.maxFeePerGas=ti(s)),l!==void 0&&(u.maxPriorityFeePerGas=ti(l)),c!==void 0&&(u.nonce=ti(c)),u}function NI(t){let e={};for(let[r,n]of Object.entries(t)){let i={};n.balance!==void 0&&(i.balance=ti(n.balance)),n.nonce!==void 0&&(i.nonce=ti(n.nonce)),n.code!==void 0&&(i.code=n.code),n.state&&(i.state=n.state),n.stateDiff&&(i.stateDiff=n.stateDiff),e[r]=i}return e}async function Zp(t){return Io(await t.request({method:"eth_blockNumber"}))}async function Gp(t){return S0(await t.request({method:"eth_chainId"}))}async function Wp(t,{address:e,...r}){return Io(await t.request({method:"eth_getBalance",params:[e,da(r)]}))}async function nc(t,{address:e,...r}){let n=await t.request({method:"eth_getCode",params:[e,da(r)]});return!n||n==="0x"?void 0:n}async function Kp(t,{address:e,slot:r,...n}){return await t.request({method:"eth_getStorageAt",params:[e,r,da(n)]})??void 0}async function Yp(t,{address:e,...r}){return S0(await t.request({method:"eth_getTransactionCount",params:[e,da(r)]}))}async function Jp(t){return Io(await t.request({method:"eth_gasPrice"}))}async function E0(t){return Io(await t.request({method:"eth_maxPriorityFeePerGas"}))}async function Xp(t,{blockNumber:e,blockTag:r,...n}){return Io(await t.request({method:"eth_estimateGas",params:[wy(n),da({blockNumber:e,blockTag:r})]}))}async function Qp(t,{includeTransactions:e=!1,...r}={}){let n=await t.request({method:"eth_getBlockByNumber",params:[da(r),e]});return n?{...n,blockNumber:n.number?Io(n.number):void 0,blockTimestamp:n.timestamp?Io(n.timestamp):void 0,baseFee:n.baseFeePerGas?Io(n.baseFeePerGas):void 0}:null}p();var sr="0xcA11bde05977b3631167028862bE2a173976CA11",MF={id:1,hexId:"0x1",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io"}},contracts:{multicall3:{address:sr,blockCreated:14353601}}},$F={id:10,hexId:"0xa",name:"Optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io","https://optimism-rpc.publicnode.com","https://optimism.drpc.org"]}},blockExplorers:{default:{name:"Optimistic Etherscan",url:"https://optimistic.etherscan.io"}},contracts:{multicall3:{address:sr,blockCreated:4286263}}},DF={id:56,hexId:"0x38",name:"BSC",nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18},rpcUrls:{default:{http:["https://bsc-dataseed.binance.org","https://bsc-rpc.publicnode.com","https://bsc.drpc.org"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com"}},contracts:{multicall3:{address:sr}}},UF={id:137,hexId:"0x89",name:"Polygon",nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com"}},contracts:{multicall3:{address:sr,blockCreated:25770160}}},LF={id:8453,hexId:"0x2105",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org","https://base-rpc.publicnode.com","https://base.drpc.org"]}},blockExplorers:{default:{name:"BaseScan",url:"https://basescan.org"}},contracts:{multicall3:{address:sr,blockCreated:5022}}},qF={id:42161,hexId:"0xa4b1",name:"Arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc","https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io"}},contracts:{multicall3:{address:sr,blockCreated:7654707}}},jF={id:43114,hexId:"0xa86a",name:"Avalanche",nativeCurrency:{name:"Avalanche",symbol:"AVAX",decimals:18},rpcUrls:{default:{http:["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io"}},contracts:{multicall3:{address:sr}}},FF={id:59144,hexId:"0xe708",name:"Linea",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build","https://linea-rpc.publicnode.com","https://linea.drpc.org"]}},blockExplorers:{default:{name:"LineaScan",url:"https://lineascan.build"}},contracts:{multicall3:{address:sr}}},BF={id:100,hexId:"0x64",name:"Gnosis",nativeCurrency:{name:"xDAI",symbol:"XDAI",decimals:18},rpcUrls:{default:{http:["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"]}},blockExplorers:{default:{name:"Gnosisscan",url:"https://gnosisscan.io"}},contracts:{multicall3:{address:sr}}},zF={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:sr}}},VF={id:5e3,hexId:"0x1388",name:"Mantle",nativeCurrency:{name:"Mantle",symbol:"MNT",decimals:18},rpcUrls:{default:{http:["https://rpc.mantle.xyz","https://mantle-rpc.publicnode.com"]}},blockExplorers:{default:{name:"Mantle Explorer",url:"https://explorer.mantle.xyz"}},contracts:{multicall3:{address:sr}}},HF={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:sr}}},Wu=[MF,$F,DF,UF,LF,qF,jF,FF,BF,zF,VF,HF];var ZF=new Map,MI=new Map;function Gie(t,e){return`${t??"unknown"}|${e.toLowerCase()}`}async function GF(t,e=sr){let r=Gie(t.chain?.id??t.chain?.hexId,e),n=ZF.get(r);if(n!==void 0)return n;let i=MI.get(r);if(i)return i;let o=(async()=>{try{let s=await nc(t,{address:e})!==void 0;return ZF.set(r,s),s}catch{return!0}finally{MI.delete(r)}})();return MI.set(r,o),o}async function Ku(t,e,r=!1){return r||typeof t.batch?.multicall=="object"&&t.batch.multicall.assumeMulticall3?!0:GF(t,e)}p();p();var Oo=[{type:"function",name:"aggregate3",stateMutability:"payable",inputs:[{name:"calls",type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],outputs:[{name:"returnData",type:"tuple[]",components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}]}]},{type:"function",name:"getEthBalance",stateMutability:"view",inputs:[{name:"addr",type:"address"}],outputs:[{name:"balance",type:"uint256"}]},{type:"function",name:"getBlockNumber",stateMutability:"view",inputs:[],outputs:[{name:"blockNumber",type:"uint256"}]},{type:"function",name:"getCurrentBlockTimestamp",stateMutability:"view",inputs:[],outputs:[{name:"timestamp",type:"uint256"}]}];p();var Zt=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint8"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{name:"from",type:"address",indexed:!0},{name:"to",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]},{type:"event",name:"Approval",inputs:[{name:"owner",type:"address",indexed:!0},{name:"spender",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]}],eh=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];p();var th=[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"address"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]}];p();var C0=[{type:"function",name:"uri",stateMutability:"view",inputs:[{name:"id",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"},{name:"id",type:"uint256"}],outputs:[{name:"",type:"uint256"}]}];p();var pa=[{type:"function",name:"asset",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"totalAssets",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"convertToAssets",stateMutability:"view",inputs:[{name:"shares",type:"uint256"}],outputs:[{name:"assets",type:"uint256"}]},{type:"function",name:"convertToShares",stateMutability:"view",inputs:[{name:"assets",type:"uint256"}],outputs:[{name:"shares",type:"uint256"}]}];p();p();var rh=class extends yt{constructor(r){super(`Chain "${r}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]});f(this,"name","ChainNotFoundError")}},Yu=class extends yt{constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]});f(this,"name","ClientChainNotConfiguredError")}},ic=class extends yt{constructor({chain:r,contract:n,blockNumber:i}){super(i!==void 0?`Chain "${r}" does not support contract "${n}" at block ${i}.`:`Chain "${r}" does not support contract "${n}".`,{metaMessages:["Pass the contract address explicitly to use it on this chain."]});f(this,"name","ChainDoesNotSupportContractError")}};p();async function $I(t,e,r){let n=new Array(t.length);if(t.length===0)return n;let i=0,o=Math.max(1,Math.min(e>0?e:t.length,t.length));async function a(){for(;;){let s=i++;if(s>=t.length)return;try{n[s]={status:"fulfilled",value:await r(t[s],s)}}catch(l){n[s]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:o},a)),n}p();p();function Sy({blockNumber:t,chain:e,contract:r}){let n=e.contracts?.[r];if(!n)throw new ic({chain:e.name,contract:r});if(t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(t))throw new ic({blockNumber:t,chain:e.name,contract:r});return n.address}p();var nh=class extends yt{constructor({data:r,shortMessage:n="The contract call reverted."}){super(n);f(this,"name","RawContractError");f(this,"data");this.data=r}},DI=class extends yt{constructor({abi:r,data:n,functionName:i}){let o=n?_y({abi:r,data:n}):void 0,a,s;if(n&&n!=="0x")try{let l=Hp({abi:r,data:n});a=l.errorName,s=l.args}catch{}super(o?`The contract function "${i??"call"}" reverted with the following reason:
|
|
442
442
|
${o}`:`The contract function "${i??"call"}" reverted.`,{metaMessages:n&&n!=="0x"?[`Revert data: ${n}`]:[]});f(this,"name","ContractFunctionRevertedError");f(this,"errorName");f(this,"errorArgs");f(this,"reason");f(this,"data");this.reason=o,this.errorName=a,this.errorArgs=s,this.data=n}},UI=class extends yt{constructor({functionName:r}){super(`The contract function "${r??"call"}" returned no data ("0x").`,{metaMessages:["This usually means:","- the address is not a contract on this chain,","- the ABI does not match the deployed contract, or","- the block predates the contract deployment."]});f(this,"name","ContractFunctionZeroDataError")}},LI=class extends yt{constructor(r,{abi:n,address:i,args:o,functionName:a,sender:s}){let l=n&&a?rc({abi:n,name:a,args:o}):void 0,c=l?Bp(l):a,u=o&&o.length>0?` args: (${o.map(h=>Wie(h)).join(", ")})`:void 0,d=l?.inputs?.length?`(${l.inputs.map(my).join(", ")})`:"()";super(r instanceof yt?r.shortMessage:`An error occurred calling "${a??"contract"}".`,{cause:r,metaMessages:[...i?[`Contract: ${i}`]:[],...c?[`Function: ${c}${l?"":d}`]:[],...u?[u]:[],...s?[`Sender: ${s}`]:[]]});f(this,"name","ContractFunctionExecutionError");f(this,"abi");f(this,"address");f(this,"args");f(this,"functionName");this.abi=n,this.address=i,this.args=o,this.functionName=a}},ky=class extends yt{constructor(r,{to:n,data:i}){super(r instanceof yt?r.shortMessage:"The call failed.",{cause:r,metaMessages:[...n?[`To: ${n}`]:[],...i?[`Data: ${i}`]:[]]});f(this,"name","CallExecutionError")}};function Wie(t){if(typeof t=="bigint")return t.toString();if(typeof t=="string")return t;try{return JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString():r)}catch{return String(t)}}function WF(t){if(!t||typeof t!="object")return;let e=t,r=e.data;if(typeof r=="string"&&r.startsWith("0x"))return r;if(r&&typeof r=="object"){let n=r.data;if(typeof n=="string"&&n.startsWith("0x"))return n}return e.cause?WF(e.cause):void 0}function ih(t,{abi:e,address:r,args:n,functionName:i,sender:o}){let a=WF(t),s=t instanceof Jl?new UI({functionName:i}):a!==void 0?new DI({abi:e,data:a,functionName:i}):t;return new LI(s,{abi:e,address:r,args:n,functionName:i,sender:o})}p();var qI=new Map;function Ty({fn:t,id:e,shouldSplitBatch:r,wait:n=0}){let i=()=>qI.get(e)??void 0,o=s=>qI.set(e,s),a=async s=>{i()===s&&qI.delete(e);try{let l=await t(s.map(c=>c.item));s.forEach((c,u)=>c.resolve(l[u]))}catch(l){s.forEach(c=>c.reject(l))}};return{schedule(s){return new Promise((l,c)=>{let u={item:s,resolve:l,reject:c},d=i();if(d)if(r?.([...d.map(m=>m.item),s]))a(d);else{d.push(u);return}let h=[u];o(h),setTimeout(()=>{a(h)},n)})}}}function Kie(t){return!!(t.data&&t.to&&!t.account&&!t.value&&!t.gas&&!t.gasPrice&&!t.maxFeePerGas&&!t.maxPriorityFeePerGas&&t.nonce===void 0&&!t.stateOverride)}async function Yie(t,e){let{batchSize:r=1024,wait:n=0}=typeof t.batch?.multicall=="object"?t.batch.multicall:{},{blockNumber:i,blockTag:o="latest",data:a,to:s}=e;if(!t.chain)throw new Yu;let l=Sy({blockNumber:i,chain:t.chain,contract:"multicall3"});if(!await Ku(t,l,!1))throw new ic({chain:t.chain.name,contract:"multicall3"});let c=i!==void 0?ti(i):o,{schedule:u}=Ty({id:`${t.uid}.call.${c}`,wait:n,shouldSplitBatch:m=>m.reduce((g,y)=>g+(y.data.length-2)/2,0)>r,fn:async m=>{let g=gt({abi:Oo,functionName:"aggregate3",args:[m.map(_=>({allowFailure:!0,callData:_.data,target:_.to}))]}),y=await t.request({method:"eth_call",params:[{to:l,data:g},c]});return ua({abi:Oo,functionName:"aggregate3",data:y})}}),{returnData:d,success:h}=await u({data:a,to:s});if(!h)throw new nh({data:d});return d}async function ha(t,e){let{blockNumber:r,blockTag:n,stateOverride:i,skipBatch:o,...a}=e;if(t.batch?.multicall&&!o&&Kie(e))try{let l=await Yie(t,{blockNumber:r,blockTag:n,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof Yu||l instanceof ic))throw new ky(l,{to:a.to,data:a.data})}let s=[wy(a),da({blockNumber:r,blockTag:n})];i&&s.push(NI(i));try{let l=await t.request({method:"eth_call",params:s});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new ky(l,{to:a.to,data:a.data})}}var jI=8;function KF(t,e){if(e!==void 0&&e>0)return e;let r=typeof t.batch?.multicall=="object"?t.batch.multicall.fallbackConcurrency:void 0;return r!==void 0&&r>0?r:jI}function Py(t,e,r){if(e)return e;if(!t.chain)throw new Yu;let n=t.chain.contracts?.multicall3;return n?r!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(r)?sr:n.address:sr}async function oh(t,e,r={}){let{concurrency:n,account:i,blockNumber:o,blockTag:a,stateOverride:s}=r;return(await $I(e,KF(t,n),async c=>{let{data:u}=await ha(t,{to:c.target,data:c.callData,account:i,blockNumber:o,blockTag:a,stateOverride:s,skipBatch:!0});return u??"0x"})).map(c=>c.status==="fulfilled"?{success:!0,returnData:c.value}:{success:!1,returnData:"0x",error:c.reason})}p();async function fa(t,e){let{abi:r,address:n,functionName:i,args:o,...a}=e;try{let s=gt({abi:r,functionName:i,args:o}),{data:l}=await ha(t,{...a,to:n,data:s});return ua({abi:r,functionName:i,args:o,data:l??"0x"})}catch(s){throw ih(s,{abi:r,address:n,args:o,functionName:i,sender:a.account})}}var Jie=1024,Xie=50;async function oc(t,e){let{calls:r,account:n,blockNumber:i,blockTag:o,batchSize:a=Jie,maxCalls:s=Xie,multicallAddress:l,stateOverride:c,fallbackConcurrency:u}=e,d=r.map(()=>({success:!1,returnData:"0x"}));if(r.length===0)return d;let h=Py(t,l,i),m=[];if(r.forEach((b,v)=>{Ve(b.target)&&zu(b.callData)&&m.push({index:v,call:b})}),m.length===0)return d;if(!await Ku(t,h,l!==void 0))return(await oh(t,m.map(v=>v.call),{account:n,blockNumber:i,blockTag:o,stateOverride:c,concurrency:u})).forEach((v,S)=>{d[m[S].index]={success:v.success,returnData:v.returnData}}),d;let g=[],y;return m.forEach(({call:b,index:v})=>{let S=(b.callData.length-2)/2,T=a>0&&y!==void 0&&y.size+S>a,C=s>0&&y!==void 0&&y.calls.length>=s;(!y||(T||C)&&y.calls.length>0)&&(y={calls:[],indexes:[],size:0},g.push(y)),y.calls.push(b),y.indexes.push(v),y.size+=S}),(await Promise.allSettled(g.map(b=>fa(t,{abi:Oo,address:h,functionName:"aggregate3",args:[b.calls.map(v=>({target:v.target,allowFailure:!0,callData:v.callData}))],account:n,blockNumber:i,blockTag:o,stateOverride:c})))).forEach((b,v)=>{b.status==="fulfilled"&&g[v].indexes.forEach((S,T)=>{let C=b.value[T];C&&(d[S]={success:!!C.success,returnData:C.returnData??"0x"})})}),d}p();p();var YF="https://wallet-api.pantograph.app/keyring/chains_v6",Qie=6,eoe=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,JF={},ah=null;function toe(t){let e=Array.isArray(t.rpcs)?t.rpcs:[],r=typeof t.linkProvider=="string"?[t.linkProvider]:[],n=[];for(let i of[...r,...e]){if(typeof i!="string")continue;let o=i.trim();if(!(!o.startsWith("https://")||eoe.test(o))&&(n.includes(o)||n.push(o),n.length>=Qie))break}return n}function XF(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[r,n]of Object.entries(t)){if(!n||typeof n!="object")continue;let i=n,o=ma(r)??(typeof i.chainId=="number"?ma(i.chainId):void 0);if(!o)continue;let a=toe(i);a.length>0&&(e[o]=a)}return e}function QF(t){JF=t}function FI(t){let e=ma(t);return e?JF[e]??[]:[]}function BI(){ah||x0()}function x0(t={}){let{url:e=YF,force:r=!1,debug:n=!1}=t;return ah&&!r||(ah=(async()=>{try{let i=await ve.get(e);if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=XF(i.data),a=Object.keys(o).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return QF(o),n&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${e}`),!0}catch(i){if(n){let o=i instanceof Error?i.message:String(i);console.warn(`[chains] remote RPC catalogue unavailable (${o}); using built-in endpoints`)}return ah=null,!1}})()),ah}var roe=new Map(Wu.map(t=>[t.hexId.toLowerCase(),t])),noe=new Map(Wu.map(t=>[t.id,t]));function ma(t){if(typeof t=="number")return Number.isFinite(t)&&t>=0?`0x${t.toString(16)}`:void 0;let e=t.trim().toLowerCase();if(e)return e.startsWith("0x")?/^0x[0-9a-f]+$/.test(e)?e:void 0:/^\d+$/.test(e)?`0x${Number(e).toString(16)}`:void 0}function al(t){if(typeof t=="number")return noe.get(t);let e=ma(t);return e?roe.get(e):void 0}var Vi=Object.fromEntries(Wu.map(t=>[t.hexId,t.rpcUrls.default.http[0]]));function zI(t){return al(t)?.rpcUrls.default.http[0]}var VI={};function Ju(t){let e={};if(t)for(let[r,n]of Object.entries(t)){if(typeof n!="string"||!n.trim())continue;let i=ma(r)??r.toLowerCase();e[i]=n.trim()}VI=e}function Ay(){return{...VI}}function Xu(t){BI();let e=ma(t),r=e?VI[e]:void 0,n=FI(t),i=al(t)?.rpcUrls.default.http??[];return[...new Set([...r?[r]:[],...n,...i])]}function Qu(t){return Xu(t)[0]}function HI(t){let e=al(t);if(!e)return;let r=Xu(t),n=e.rpcUrls.default.http;return r.length===0||r.length===n.length&&r.every((i,o)=>i===n[o])?e:{...e,rpcUrls:{default:{http:r}}}}p();p();p();var ac=class extends yt{constructor({body:r,details:n,headers:i,status:o,url:a}){super("HTTP request failed.",{details:n,metaMessages:[`URL: ${a}`,...o?[`Status: ${o}`]:[],...r?[`Request body: ${JSON.stringify(r)}`]:[]]});f(this,"name","HttpRequestError");f(this,"status");f(this,"url");f(this,"body");f(this,"headers");this.status=o,this.url=a,this.body=r,this.headers=i}},sh=class extends yt{constructor({body:r,url:n,timeout:i}){super("The request took too long to respond.",{details:`The request timed out after ${i}ms.`,metaMessages:[`URL: ${n}`,...r?[`Request body: ${JSON.stringify(r)}`]:[]]});f(this,"name","TimeoutError")}},lh=class extends yt{constructor({cause:r,url:n}){super("Could not reach the RPC endpoint.",{cause:r,metaMessages:[`URL: ${n}`]});f(this,"name","NetworkError")}},I0=class extends yt{constructor(){super("No RPC URL was provided.",{metaMessages:['Pass one to the transport \u2014 http("https://\u2026") \u2014 or give the client a chain that has a default RPC URL.']});f(this,"name","UrlRequiredError")}},Ey=class extends yt{constructor({cause:r,count:n}){super(`All ${n} fallback transports failed.`,{cause:r});f(this,"name","FallbackTransportError")}};p();p();var ch=class extends yt{constructor({body:r,error:n,url:i,shortMessage:o}){super(o??"RPC request failed.",{details:n.message,metaMessages:[...i?[`URL: ${i}`]:[],...r?[`Request body: ${JSON.stringify(r)}`]:[],`Error code: ${n.code}`]});f(this,"name","RpcRequestError");f(this,"code");f(this,"data");this.code=n.code,this.data=n.data}};function Hi(t,e,r){var n;return n=class extends ch{constructor(o){super({...o,shortMessage:r});f(this,"name",t)}},f(n,"code",e),n}var ioe=Hi("ParseRpcError",-32700,"The node could not parse the JSON request."),ooe=Hi("InvalidRequestRpcError",-32600,"The JSON request is not valid."),aoe=Hi("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),soe=Hi("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),loe=Hi("InternalRpcError",-32603,"The node reported an internal error."),coe=Hi("InvalidInputRpcError",-32e3,"The RPC input is not valid."),uoe=Hi("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),doe=Hi("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),poe=Hi("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),hoe=Hi("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),ZI=Hi("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),foe=Hi("UserRejectedRequestError",4001,"The user rejected the request."),moe=new Map([[-32700,ioe],[-32600,ooe],[-32601,aoe],[-32602,soe],[-32603,loe],[-32e3,coe],[-32001,uoe],[-32002,doe],[-32003,poe],[-32004,hoe],[-32005,ZI],[4001,foe]]);function eB(t){let e=moe.get(t.error.code);return e?new e(t):new ch(t)}p();function tB(t){return new Promise(e=>setTimeout(e,t))}async function GI(t,{retryCount:e=2,delay:r=150,shouldRetry:n=()=>!0}={}){let i=0;for(;;)try{return await t()}catch(o){if(i++,i>e||!n({count:i,error:o}))throw o;let a=typeof r=="function"?r({count:i,error:o}):r*2**(i-1);a>0&&await tB(a)}}function WI(t){let e=t?.["retry-after"];if(!e)return;let r=Number(e);if(Number.isFinite(r))return r*1e3;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}var goe=new Set([408,413,429,500,502,503,504]),yoe=new Set([401,402,403]);function O0(t){return t instanceof sh||t instanceof lh?!0:t instanceof ac?t.status?goe.has(t.status)||t.status>=500:!0:t instanceof ZI?!0:t instanceof ch?t.code===-32603:!1}function R0(t){return t instanceof ac&&t.status&&yoe.has(t.status)?!0:O0(t)}function N0(t,{retryCount:e=3,retryDelay:r=150}={}){return function(i,o={}){return GI(()=>t(i),{retryCount:o.retryCount??e,shouldRetry:({error:a})=>O0(a),delay:({count:a,error:s})=>{let l=s instanceof ac?WI(s.headers):void 0;return l!==void 0?l:(o.retryDelay??r)*2**(a-1)}})}}p();function sc({key:t,name:e,type:r,request:n,retryCount:i=3,retryDelay:o=150,timeout:a=1e4},s){return{config:{key:t,name:e,type:r,request:n,retryCount:i,retryDelay:o,timeout:a},request:N0(n,{retryCount:i,retryDelay:o}),value:s}}function lc(t,e={}){let{key:r="fallback",name:n="Fallback",retryCount:i=0,retryDelay:o,onTransportError:a}=e;return(s={})=>{let l=t.map(u=>u(s));if(l.length===0)throw new Ey({count:0});return sc({key:r,name:n,type:"fallback",request:async u=>{let d;for(let h=0;h<l.length;h++)try{return await l[h].request(u)}catch(m){if(d=m,a?.({error:m,index:h,method:u.method}),!R0(m))throw m}throw new Ey({cause:d,count:l.length})},retryCount:i,retryDelay:o,timeout:s.timeout},{transports:l})}}p();p();var rB=0;function nB(){return rB+=1,rB}function _oe(t){let e=t?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let r=t?.message??"";return/timeout/i.test(r)}var uh=class{constructor(e,{timeout:r=1e4,fetchOptions:n={}}={}){f(this,"url");f(this,"timeout");f(this,"fetchOptions");this.url=e,this.timeout=r,this.fetchOptions=n}async post(e){let r;try{r=await ve.post(this.url,e,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(n){throw _oe(n)?new sh({body:e,url:this.url,timeout:this.timeout}):new lh({cause:n,url:this.url})}if(!r.ok)throw new ac({body:e,details:Xe(r),headers:r.headers,status:r.status,url:this.url});return r.data}async request(e){let r={jsonrpc:"2.0",id:nB(),...e};return await this.post(r)??{id:r.id}}async requestBatch(e){let r=e.map(o=>({jsonrpc:"2.0",id:nB(),...o})),n=await this.post(r);if(!Array.isArray(n))return r.map(o=>({id:o.id,error:n?.error??{code:-32603,message:"Malformed batch response."}}));let i=new Map(n.map(o=>[o.id,o]));return r.map((o,a)=>i.get(o.id)??n[a]??{id:o.id,error:{code:-32603,message:"Missing response for batched request."}})}};function iB(t,e,r){if(t.error)throw eB({body:e,error:t.error,url:r});return t.result}function Ro(t,e={}){let{batch:r,fetchOptions:n,key:i="http",name:o="HTTP JSON-RPC",retryCount:a,retryDelay:s,timeout:l}=e;return({chain:c,retryCount:u,retryDelay:d,timeout:h}={})=>{let{batchSize:m=1e3,wait:g=0}=typeof r=="object"?r:{},y=l??h??1e4,_=t??c?.rpcUrls.default.http[0];if(!_)throw new I0;let b=new uh(_,{timeout:y,fetchOptions:n});return sc({key:i,name:o,type:"http",retryCount:a??u,retryDelay:s??d,timeout:y,async request({method:v,params:S}){let T={method:v,params:S};if(r){let{schedule:C}=Ty({id:`${_}:${m}:${g}`,wait:g,shouldSplitBatch:I=>I.length>m,fn:I=>b.requestBatch(I)});return iB(await C(T),T,_)}return iB(await b.request(T),T,_)}},{url:_})}}p();p();var boe=1024;async function dh(t,e){let{contracts:r,allowFailure:n=!0,account:i,blockNumber:o,blockTag:a,multicallAddress:s,stateOverride:l,fallbackConcurrency:c}=e,u=e.batchSize??(typeof t.batch?.multicall=="object"&&t.batch.multicall.batchSize||boe),d=new Array(r.length);if(r.length===0)return n?d:[];let h=Py(t,s,o),m=[],g;r.forEach((b,v)=>{let{abi:S,address:T,functionName:C,args:I}=b,R;try{if(!Ve(T))throw new Lp(T);R=gt({abi:S,functionName:C,args:I})}catch(U){let D=ih(U,{abi:S,address:T,args:I,functionName:C,sender:i});if(!n)throw D;d[v]={status:"failure",error:D};return}let E=(R.length-2)/2;(!g||u>0&&g.size+E>u&&g.calls.length>0)&&(g={calls:[],indexes:[],size:0},m.push(g)),g.calls.push({target:T,allowFailure:!0,callData:R}),g.indexes.push(v),g.size+=E}),(await Ku(t,h,s!==void 0)?await Promise.allSettled(m.map(b=>fa(t,{abi:Oo,address:h,functionName:"aggregate3",args:[b.calls],account:i,blockNumber:o,blockTag:a,stateOverride:l}))):await(async()=>{let b=m.flatMap(S=>S.calls.map((T,C)=>({target:T.target,callData:T.callData,index:S.indexes[C]}))),v=await oh(t,b,{account:i,blockNumber:o,blockTag:a,stateOverride:l,concurrency:c});return m.length=0,v.map((S,T)=>(m.push({calls:[],indexes:[b[T].index],size:0}),S.success?{status:"fulfilled",value:[{success:!0,returnData:S.returnData}]}:{status:"rejected",reason:S.error}))})()).forEach((b,v)=>{let S=m[v];if(b.status==="rejected"){for(let T of S.indexes){let C=r[T],I=ih(b.reason,{abi:C.abi,address:C.address,args:C.args,functionName:C.functionName,sender:i});if(!n)throw I;d[T]={status:"failure",error:I}}return}S.indexes.forEach((T,C)=>{let I=r[T],R=b.value[C];try{if(!R)throw new Error("Multicall returned fewer results than calls.");if(!R.success)throw new nh({data:R.returnData});if(!R.returnData||R.returnData==="0x")throw new Jl;let E=ua({abi:I.abi,functionName:I.functionName,args:I.args,data:R.returnData});d[T]={status:"success",result:E}}catch(E){let U=ih(E,{abi:I.abi,address:I.address,args:I.args,functionName:I.functionName,sender:i});if(!n)throw U;d[T]={status:"failure",error:U}}})});for(let b=0;b<r.length;b++){if(d[b])continue;let v=new Error("Multicall returned no result for this call.");if(!n)throw v;d[b]={status:"failure",error:v}}return n?d:d.map(b=>b.result)}var voe=0,ed=class{constructor(e={}){f(this,"key");f(this,"name");f(this,"uid");f(this,"chain");f(this,"transport");f(this,"batch");f(this,"request");let{batch:r,key:n="public",name:i="Public Client",retryCount:o,retryDelay:a,timeout:s}=e;this.chain=Soe(e.chain),this.key=n,this.name=i,this.batch=r,this.uid=`${n}-${++voe}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??woe(e.rpcUrl,this.chain))({chain:this.chain,retryCount:o,retryDelay:a,timeout:s});this.transport={...c.config,...c.value},this.request=c.request}call(e){return ha(this,e)}readContract(e){return fa(this,e)}multicall(e){return dh(this,e)}multicallRaw(e){return oc(this,e)}getBlockNumber(){return Zp(this)}getChainId(){return Gp(this)}getBalance(e){return Wp(this,e)}getCode(e){return nc(this,e)}getStorageAt(e){return Kp(this,e)}getTransactionCount(e){return Yp(this,e)}getGasPrice(){return Jp(this)}estimateMaxPriorityFeePerGas(){return E0(this)}estimateGas(e){return Xp(this,e)}getBlock(e){return Qp(this,e)}rpc(e,r){return this.request({method:e,params:r})}extend(e){let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return Object.assign(r,e(r))}};function woe(t,e){if(t)return Ro(t);let r=e?.rpcUrls.default.http??[];return r.length>1?lc(r.map(n=>Ro(n,{retryCount:1}))):Ro(r[0])}function Soe(t){if(t===void 0)return;if(typeof t=="object")return t;let e=HI(t);if(!e)throw new rh(t);return e}function cc(t={}){return new ed(t)}var KI=new Map;function koe(t,e){return{id:parseInt(t,16),hexId:t,name:`Chain ${parseInt(t,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:e}},contracts:{multicall3:{address:sr}}}}function ri(t,e={}){let{batch:r=!0,pinRpcUrl:n=!1,fallbackConcurrency:i,assumeMulticall3:o}=e,a=ma(t),s=e.rpcUrl?.trim(),l=a?Xu(a):[],c=s?n?[s]:[...new Set([s,...l])]:l;if(c.length===0)throw new rh(t);let u=`${a??t}|${c.join(",")}|${r?1:0}|${i??""}|${o?1:0}`,d=KI.get(u);if(d)return d;let h=cc({chain:a&&!al(a)?koe(a,c):a,transport:c.length===1?Ro(c[0]):lc(c.map(m=>Ro(m,{retryCount:1}))),batch:r?{multicall:{fallbackConcurrency:i,assumeMulticall3:o}}:void 0});return KI.set(u,h),h}function M0(){KI.clear()}function JI(t,e){try{return ri(t,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function ni(t,e,r){let n=new Array(e.length).fill(null),i=e.length>0?JI(t,r):null;if(!i)return n;let o=[];if(e.forEach((a,s)=>{!Ve(a.target)||!zu(a.callData)||o.push({index:s,target:a.target,callData:a.callData})}),o.length===0)return n;try{(await oc(i,{calls:o})).forEach((s,l)=>{s.success&&(n[o[l].index]=s.returnData)})}catch{}return n}function $0(t){return t?.status==="success"?t.result:void 0}async function YI(t,e){try{return await t.multicall({contracts:e})}catch{return[]}}async function oB(t,e,r){let n=e.map(()=>({symbol:null,decimals:null})),i=e.length>0?JI(t,r):null;if(!i)return n;let o=[];if(e.forEach((l,c)=>{Ve(l)&&o.push({index:c,address:l})}),o.length===0)return n;let a=await YI(i,o.flatMap(l=>[{address:l.address,abi:Zt,functionName:"symbol"},{address:l.address,abi:Zt,functionName:"decimals"}]));o.forEach((l,c)=>{let u=$0(a[c*2]);typeof u=="string"&&u.trim()&&(n[l.index].symbol=u.trim()),n[l.index].decimals=T0($0(a[c*2+1]))});let s=o.filter(l=>n[l.index].symbol===null);if(s.length>0){let l=await YI(i,s.map(c=>({address:c.address,abi:eh,functionName:"symbol"})));s.forEach((c,u)=>{n[c.index].symbol=P0($0(l[u]))})}return n}async function aB(t,e,r){let n=new Array(e.length).fill(null),i=e.length>0?JI(t,r):null;if(!i)return n;let o=[];return e.forEach((s,l)=>{if(Ve(s.contract))try{o.push({index:l,address:s.contract,tokenId:BigInt(s.tokenId)})}catch{}}),o.length===0||(await YI(i,o.map(s=>({address:s.address,abi:th,functionName:"tokenURI",args:[s.tokenId]})))).forEach((s,l)=>{let c=$0(s);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(n[o[l].index]=u)}),n}p();function Toe(t){return D0(String(t))??"0"}function D0(t){let e=t.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let r=e[1]==="-"?"-":"",n=e[2]??"",i=e[3]??"";if(n===""&&i==="")return null;let o=e[4]?parseInt(e[4],10):0,a=n+i,s=n.length+o,l;return s<=0?l=`0.${"0".repeat(-s)}${a}`:s>=a.length?l=a+"0".repeat(s-a.length):l=`${a.slice(0,s)}.${a.slice(s)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":r+l}function XI(t){let e=D0(t);if(e===null||e.startsWith("-"))return null;let[r,n=""]=e.split(".");return{mant:BigInt(r+n),frac:n.length}}function QI(t,e){let r=t<0n,n=(r?-t:t).toString(),i;if(e===0)i=n;else{let o=n.padStart(e+1,"0"),a=o.length-e;i=`${o.slice(0,a)}.${o.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return r?`-${i}`:i}function ph(t){if(typeof t=="number")return Number.isFinite(t)&&t>0?Toe(t):null;if(typeof t!="string")return null;let e=t.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let r=D0(e[0]);return r&&r!=="0"&&!r.startsWith("-")?r:null}function uc(t,e){let r=D0(t);if(r===null||e<0)return t;let n=r.startsWith("-"),[i,o=""]=(n?r.slice(1):r).split(".");if(o.length<=e)return r;let a=e===0?i:`${i}.${o.slice(0,e)}`,s=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${s}`:s}function hh(t,e,r,n){let i=XI(t);if(!i||r<=0n||n<0)return t;let o=i.mant*e*10n**BigInt(n)/(r*10n**BigInt(i.frac));return QI(o,n)}function td(t,e){let r=XI(t),n=XI(e);if(!r||!n){let s=Number(t),l=Number(e);return s<l?-1:s>l?1:0}let i=Math.max(r.frac,n.frac),o=r.mant*10n**BigInt(i-r.frac),a=n.mant*10n**BigInt(i-n.frac);return o<a?-1:o>a?1:0}var Poe={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"}]},Aoe="payment-required",Eoe="PAYMENT-SIGNATURE",Coe="X-PAYMENT",xoe="payment-response",Ioe="x-payment-response",Ooe=600,Roe=300,Noe={ethereum:1,sepolia:11155111,abstract:2741,"abstract-testnet":11124,base:8453,"base-sepolia":84532,avalanche:43114,"avalanche-fuji":43113,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338,story:1514,educhain:41923,"skale-base-sepolia":324705682,megaeth:4326,monad:143,stable:988,"stable-testnet":2201};function sB(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 cB(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 Moe(){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 uB(t){let e=String(t);if(e.includes(":")){let[n,i]=e.split(":"),o=parseInt(i,10);if(n!=="eip155"||Number.isNaN(o))throw new Error(`Unsupported x402 network: ${t} (only EVM "eip155:*" is supported)`);return o}let r=Noe[e.toLowerCase()];if(r===void 0)throw new Error(`Unsupported x402 network: ${t}`);return r}function dB(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 U0(t){let e=t.headers[Aoe];if(e){let i=lB($oe(e));return i&&Array.isArray(i.accepts)?{version:2,payload:i}:null}let r=t.data,n=r&&typeof r=="object"?r:lB(r);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function lB(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}function $oe(t){try{return cB(t)}catch{return null}}function Doe(t){let e=t.amount??t.maxAmountRequired;return typeof t.scheme!="string"||typeof t.network!="string"||e==null||typeof t.asset!="string"||typeof t.payTo!="string"?null:{scheme:t.scheme,network:t.network,amount:String(e),asset:t.asset,payTo:t.payTo,...typeof t.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:t.maxTimeoutSeconds}:{},...t.extra&&typeof t.extra=="object"?{extra:t.extra}:{},...typeof t.resource=="string"?{resource:t.resource}:{},...typeof t.description=="string"?{description:t.description}:{},...typeof t.mimeType=="string"?{mimeType:t.mimeType}:{},...t.outputSchema!=null?{outputSchema:t.outputSchema}:{}}}function Uoe(t){let e=null;for(let r of t){let n=Doe(r);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return uB(n.network),n}catch(i){e=i instanceof Error?i.message:String(i)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function eO(t,e,r,n){let i=U0(t);if(!i)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:a}=i,s=Uoe(a.accepts??[]);if(!r)throw new Error("No connected wallet address to build the payment from");let l=uB(s.network),c=Math.floor(Date.now()/1e3),u={from:r,to:s.payTo,value:String(s.amount),validAfter:String(Math.max(0,c-Ooe)),validBefore:String(c+(s.maxTimeoutSeconds??Roe)),nonce:Moe()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:l,verifyingContract:s.asset},types:Poe,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:dB(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:o,requirements:s,authorization:u,typedData:d,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...n?{userQuery:n}:{}}}async function Loe(t,e,r,n){let i=dB(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:eO(o,e,r,n)};if(!o.ok)throw new Error(Xe(o));return{status:"ok",data:o.data}}async function tO(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...rO(e,r)}});if(s.ok)return s.data;throw new Error(joe(s)??Xe(s))}function qoe(t){return U0(t)!==null}function pB(t){let e=hB(t);return e?.errorReason?e.errorReason:U0(t)?.payload.error??null}function joe(t){let e=pB(t);return e?`x402 payment rejected: ${e}`:null}var Foe={1:"Ethereum",10:"Optimism",137:"Polygon",143:"Monad",988:"Stable",1328:"Sei Testnet",1329:"Sei",1514:"Story",2201:"Stable Testnet",2741:"Abstract",3338:"Peaq",4326:"MegaETH",4689:"IoTeX",8453:"Base",11124:"Abstract Testnet",41923:"EDU Chain",42161:"Arbitrum",43113:"Avalanche Fuji",43114:"Avalanche",80002:"Polygon Amoy",84532:"Base Sepolia",324705682:"SKALE Base Sepolia",11155111:"Sepolia"};function rO(t,e){let{requirements:r,authorization:n}=t,i={signature:e,authorization:n};if(t.x402Version===1){let a={x402Version:1,scheme:r.scheme,network:r.network,payload:i};return{[Coe]:sB(JSON.stringify(a))}}let o={x402Version:2,...t.resource!=null?{resource:t.resource}:{},accepted:Boe(r),payload:i,...t.extensions!=null?{extensions:t.extensions}:{}};return{[Eoe]:sB(JSON.stringify(o))}}function Boe(t){let{resource:e,description:r,mimeType:n,outputSchema:i,...o}=t;return o}function hB(t){let e=t.headers[xoe]??t.headers[Ioe];if(!e)return null;try{return JSON.parse(cB(e))}catch{return null}}function zoe(t,e){return t==null?e:Foe[t]??`Chain ${t}`}async function fB(t){let e=t.requirements,n=t.resource?.description||e.description,i=t.chainId??null,o=null,a=null;if(i!=null){let[l]=await oB("0x"+i.toString(16),[e.asset]);o=l?.symbol??null,a=l?.decimals??null}let s=String(e.amount);if(a!==null)try{s=QI(BigInt(e.amount),a)}catch{}return{amount:s,asset:o||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:i!=null?`eip155:${i}`:e.network,networkRaw:e.network,chainId:i,networkLabel:zoe(i,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:t.request.url}}function nO(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=eO(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:await fB(o)})}catch{a=null}return a?rO(o,a):null}}p();p();var dc=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function rd(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Cy(t){if(t?.aborted)throw new dc}function iO(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 mB={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},Voe="https://nft.keyring.app/api/gemini-stable",Hoe="https://generativelanguage.googleapis.com",Zoe=new Set([408,429,500,502,503,504]),gB=3e4,L0=t=>new Promise(e=>setTimeout(e,t));function q0(t,e,r){if(r!=null&&r>0)return Math.min(r,gB);let n=Math.min(e*2**(t-1),gB);return n/2+Math.random()*(n/2)}function Goe(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 Mr=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"apiKey");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?Hoe:Voe)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}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;Cy(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let y of c){let _=y.parts.map(b=>b.functionCall?`fc:${b.functionCall.name}`:b.functionResponse?`fr:${b.functionResponse.name}`:`text:${(b.text??"").slice(0,40)}`).join(", ");console.log(` ${y.role}: [${_}]`)}}let u=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),d={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let h={contents:c,generationConfig:d};i&&(h.systemInstruction=i),r?.length?(h.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(h.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(h.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,g="Unknown error";for(let y=1;y<=a;y++){Cy(l);let _;try{_=await ve.post(m,h,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(R){if(rd(R))throw R;if(g=R instanceof Error?R.message:String(R),y>=a)break;await L0(q0(y,s));continue}if(!_.ok){let R=typeof _.data=="string"?_.data:JSON.stringify(_.data)||_.statusText;if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${_.status}: ${R}`,!Zoe.has(_.status))throw new Error(g);if(y>=a)break;let E=Goe(_.headers["retry-after"]??null);await L0(q0(y,s,E));continue}if(_.data==null||typeof _.data!="object"){if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,y>=a)break;await L0(q0(y,s));continue}let b=_.data,v=b.candidates?.[0];if(!v)return{text:"",toolCalls:[]};let S="",T=[],C=v.content?.parts;if(!Array.isArray(C)||C.length===0){let R=v.finishReason;if(!(R==="SAFETY"||R==="RECITATION")&&y<a){g=`Gemini returned an empty turn (finishReason=${R??"none"})`,await L0(q0(y,s));continue}return{text:"",toolCalls:[]}}for(let R of C)R.text&&(S+=R.text),R.functionCall&&T.push({toolName:R.functionCall.name,args:R.functionCall.args??{},callId:R.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let I=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0}:void 0;return{text:S,toolCalls:T,usage:I}}throw new Error(g)}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],c=s.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!c&&!u?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],c=o[o.length-1];l.role==="function"&&!c?.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(`
|
|
443
443
|
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:mB[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:mB[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 fh=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 mh=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Woe=new Set(mh),pc=[...mh],oO=new Set(pc),Zi="0x1",yh="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Koe(t){return t.map(e=>gh[e]??e).join(", ")}function j0(t){let e=new Set;if(t)for(let n of t){let i=F0(n);i&&e.add(i)}let r=mh.filter(n=>!e.has(n));pc=r.length>0?[...r]:[...mh],oO=new Set(pc),Zi=pc.includes("0x1")?"0x1":pc[0],yh=Koe(pc)}var Yoe={"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 _t(t){let e=F0(t);return e&&oO.has(e)?e:null}function F0(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=Yoe[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&&Woe.has(n)?n:null}function No(t){return _t(t)!==null}function ii(){return[...pc]}var fc=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${yh}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},hc=t=>typeof t=="string"&&t.trim()!=="";function hr(t,e){if(hc(t)){let r=_t(t);if(r)return r;throw new fc(t.trim())}if(hc(e?.chain)){let r=_t(e.chain);if(r)return r;throw new fc(e.chain.trim())}return null}function B0(t,e){return _t(t)??_t(e?.chain)??void 0}var gh={"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 Q(t){let e=F0(t);return e&&gh[e]?gh[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var Joe={"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 yB(t,e){let r=F0(t),n=r?Joe[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Xoe={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function _B(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?Xoe[e]??null:null}var Qoe={"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 bB(t){let e=_t(t);return e?Qoe[e]??null:null}function _h(t,e){if(!hc(t))return null;let r=_t(t),n=_t(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:gh[r]??r,connectedLabel:gh[n]??n}}function vB(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>oO.has(o)):[];return(n.length?n:pc).map(o=>{let a=gh[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function bh(t,e){return{actionButtons:vB(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 Tr=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=vB(r,n)}},xy=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 fr(t,e){if(hc(t))return t.trim();if(hc(e?.walletAddress))return e.walletAddress.trim();throw new xy}function Wr(t,e,r){if(hc(t)){let n=_t(t);if(n)return n;throw new fc(t.trim())}if(hc(e?.chain)){let n=_t(e.chain);if(n)return n;throw new fc(e.chain.trim())}if(hc(e?.walletAddress))throw new Tr(typeof e?.query=="string"?e.query:void 0,r);return Zi}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=eae(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(o){return o instanceof Tr?{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 xy?{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 eae(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons,n=Array.isArray(r)&&r.length>0?r:void 0,i=e.ui,o=i&&typeof i=="object"&&typeof i.component=="string"?i:void 0;if(!n&&!o)return{data:t};let{actionButtons:a,ui:s,...l}=e;return{data:l,...n?{actionButtons:n}:{},...o?{ui:o}:{}}}p();p();p();var tae="https://wallet-api.pantograph.app",rae="0x0000000000000000000000000000000000000000",kB={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},TB={"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 nae(t){return kB[t.toLowerCase()]||t}function wB(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 aO(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 z0(t){if(Array.isArray(t))return t;let e=t;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function $n(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function SB(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=$n(t.price_change_percentage_24h)??$n(t.priceChange24h)??$n(t.usd_price_24hr_percent_change)??$n(t.price_change_24h)??$n(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:$n(t.price)??$n(t.usd_price),marketCap:$n(t.market_cap)??$n(t.marketCap),totalVolume:{"24h":$n(t.total_volume)??$n(t.volume24h)},pricePercentChange:{"24h":i}}}var jr=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??tae).replace(/\/+$/,"")}tokensUrl(e,r){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async enrichTokenPrices(e,r){let n=new Map;if(e.length===0)return n;try{let i=e.map(c=>c.token_address).join(","),o=this.tokensUrl(r,i),a=await ve.get(o);if(!a.ok)return n;let s=z0(a.data),l=new Map;for(let c of s)if(c.address){let u=c.address.toLowerCase();l.set(u,{price:c.price!=null?parseFloat(String(c.price)):NaN,icon_image:c.icon_image}),("yieldProtocol"in c||"yieldAsset"in c)&&n.set(u,{yieldProtocol:c.yieldProtocol,yieldAsset:c.yieldAsset})}for(let c=0;c<e.length;c++){let u=l.get(e[c].token_address.toLowerCase());u&&(u.icon_image&&(e[c].logo=u.icon_image,e[c].thumbnail=u.icon_image),isNaN(u.price)||(e[c].usd_price=u.price,e[c].usd_value=parseFloat(e[c].balance_formatted||"0")*u.price))}}catch{}return n}async getYieldPricingTokens(e,r){let n=(r??[]).map(o=>String(o??"").trim()).filter(Boolean);if(n.length===0)return[];let i=typeof e=="number"?e:String(e).startsWith("0x")?parseInt(String(e),16):parseInt(String(e),10);if(!Number.isFinite(i))return[];try{let o=`${this.baseUrl}/keyrings/tokens/all/${i}?addresses=${encodeURIComponent(n.join(","))}`,a=await ve.get(o);return a.ok?z0(a.data):[]}catch{return[]}}async getTokenMetadata(e,r){try{let n=this.tokensUrl(r,e),i=await ve.get(n);if(!i.ok)return null;let o=z0(i.data),a=e.toLowerCase()===rae,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?aO(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 ve.get(i);if(!o.ok)return n;let a=z0(o.data),s=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&s.has(c)&&(n[c]=aO(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||Zi,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=wB({chainId:o,key:r}),s=`${this.baseUrl}/token-list/all?${a}`,l=await ve.get(s);if(!l.ok)throw new Error(Xe(l));let c=l.data,u=c?.result??c?.data??c,d=[];return Array.isArray(u)?d=u:u&&typeof u=="object"&&(d=Object.values(u).flat()),{success:!0,data:d.map(aO)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Zi,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=TB[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({})]),c=s.status==="fulfilled"?s.value:[],u=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>SB(y,r)):[],d=new Set,h=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of c){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=$n(a.market_cap)??$n(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":$n(a.total_volume)??$n(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=parseInt(e,16),o=wB({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 c=await ve.get(a);if(!c.ok)throw new Error(Xe(c));let u=c.data;if(s=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>SB(l,e))}async getTopGainers(e){let r=e?.chain||Zi,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"}}}};p();p();p();p();p();p();p();p();p();var sO=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}];p();var Iy=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]},{type:"function",name:"liquidity",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint128"}]},{type:"function",name:"tickSpacing",stateMutability:"view",inputs:[],outputs:[{name:"",type:"int24"}]},{type:"function",name:"fee",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint24"}]},{type:"function",name:"token0",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"token1",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];p();var V0=[{type:"function",name:"getReserveData",stateMutability:"view",inputs:[{name:"asset",type:"address"}],outputs:[{name:"reserveData",type:"tuple",components:[{name:"configuration",type:"uint256"},{name:"liquidityIndex",type:"uint128"},{name:"currentLiquidityRate",type:"uint128"}]}]}],vh=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],lO=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];p();var nd=[{inputs:[],name:"getUtilization",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseToken",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"utilization",type:"uint256"}],name:"getSupplyRate",outputs:[{name:"",type:"uint64"}],stateMutability:"view",type:"function"}];p();var wh=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],id=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],cO=[{inputs:[],name:"susds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var PB=7;function gn(t,e,r,n=[]){return{target:t,callData:gt({abi:e,functionName:r,args:n})}}var H0=1e27,AB=10n**27n,EB=31536e3,aae=10;function Ry(t){return Number.isFinite(t)&&t>=0&&t<=aae?t:null}function CB(t){return Math.expm1(t)}var sae=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|
|
@@ -453,9 +453,10 @@ ${o}`:`The contract function "${i??"call"}" reverted.`,{metaMessages:n&&n!=="0x"
|
|
|
453
453
|
}`;function lae(t){return(t||[]).flatMap(e=>{let r=Number(e?.extraSupplyApr?.value);return!Number.isFinite(r)||r<=0?[]:[{fraction:CB(r),tokenSymbol:e?.rewardTokenSymbol??e?.payoutToken?.symbol??null,conditions:e?.customMessage?.trim()||null}]})}var cae=`query VaultV2ByAddress($address: String!, $chainId: Int!, $options: TimeseriesOptions) {
|
|
454
454
|
vaultV2ByAddress(address: $address, chainId: $chainId) {
|
|
455
455
|
netApy
|
|
456
|
+
avgNetApy(lookback: SEVEN_DAYS)
|
|
456
457
|
historicalState { avgNetApy(options: $options) { x y } }
|
|
457
458
|
}
|
|
458
|
-
}`,Sh=class{underlyingCall(e){return gn(e.contract,pa,"asset")}liveRateCall(e,r){return null}followUpRateCall(e,r){return null}decodeSize(e,r){if(!Number.isInteger(r.decimals)||r.decimals<0)return null;let n=Gr(e);return n===null?null:mc(n,r.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,r){return this.balanceIsUnderlying?null:gn(e.contract,pa,"convertToAssets",[r])}},Oy=class extends Sh{constructor(){super(...arguments);f(this,"type","spark");f(this,"balanceIsUnderlying",!1)}sizeCall(r){return gn(r.contract,pa,"totalAssets")}fetchApy(r,n,i){return gO(r,n,i)}},uO=class extends Oy{constructor(){super(...arguments);f(this,"type","spark")}liveRateCall(r){return gn(r.contract,wh,"rateProvider")}followUpRateCall(r,n){let i=rr(n);return i===null?null:gn(i,id,"getAPR")}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ry(Math.expm1(Number(n)/H0))}},dO=class extends Oy{constructor(){super(...arguments);f(this,"type","spark-ethereum")}liveRateCall(r){return gn(r.contract,wh,"vsr")}decodeLiveRate(r){let n=Gr(r);if(n===null||n<=0n)return null;let i=Number(n-AB)/H0;return i>-1?Ry(Math.expm1(Math.log1p(i)*EB)):null}},pO=class extends Sh{constructor(){super(...arguments);f(this,"type","spark-l2-susds");f(this,"balanceIsUnderlying",!1)}underlyingCall(){return null}sizeCall(r){return gn(r.token,Zt,"totalSupply")}liveRateCall(r){return gn(r.contract,id,"getAPR")}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ry(Math.expm1(Number(n)/H0))}convertToAssetsCall(r){return gn(r.contract,id,"getConversionRate")}fetchApy(r,n,i){return gO(r,n,i)}};function kh(t,e,r,n){if(e<=0n||!Number.isInteger(r)||!Number.isInteger(n)||r<0||n<0)return null;let i=t*e/AB,o=n-r;return o===0?i:o>0?i*10n**BigInt(o):i/10n**BigInt(-o)}var hO=class extends Sh{constructor(){super(...arguments);f(this,"type","aave-v3");f(this,"balanceIsUnderlying",!0)}underlyingCall(r){return gn(r.token,vh,"UNDERLYING_ASSET_ADDRESS")}sizeCall(r){return gn(r.token,Zt,"totalSupply")}liveRateCall(r,n){return gn(r.contract,V0,"getReserveData",[n.address])}decodeLiveRate(r){if(!r)return null;let n;try{let[i]=Mn(V0[0].outputs,r);n=i.currentLiquidityRate}catch{return null}return Ry(CB(Number(n)/H0))}async fetchApy(r,n,i,o){let a={chainId:n.chainId,market:r.contract,underlyingToken:o.address,window:"LAST_WEEK"},s=await ve.post(i.aaveApiUrl,{operationName:"SupplyAPYHistory",query:sae,variables:{request:a,reserve:{chainId:n.chainId,market:r.contract,underlyingToken:o.address}}});if(!s.ok)throw new Error(Xe(s));return{samples:(s.data?.data?.value||[]).filter(l=>l?.avgRate?.value!==null&&l?.avgRate?.value!==void 0).map(l=>({timeMs:Date.parse(l?.date??""),fraction:Number(l?.avgRate?.value)})),current:null,rewards:lae(s.data?.data?.reserve?.incentives)}}},fO=class extends Sh{constructor(){super(...arguments);f(this,"type","compound-v3");f(this,"balanceIsUnderlying",!0)}underlyingCall(r){return gn(r.contract,nd,"baseToken")}sizeCall(r){return gn(r.token,Zt,"totalSupply")}liveRateCall(r){return gn(r.contract,nd,"getUtilization")}followUpRateCall(r,n){let i=Gr(n);return i===null?null:gn(r.contract,nd,"getSupplyRate",[i])}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ry(Number(n)/1e18*EB)}fetchApy(r,n,i){return gO(r,n,i)}},mO=class extends Oy{constructor(){super(...arguments);f(this,"type","morpho-v2")}async fetchApy(r,n,i){let o=Math.floor(Date.now()/1e3),a=await ve.post(i.morphoApiUrl,{operationName:"VaultV2ByAddress",query:cae,variables:{address:r.contract,chainId:n.chainId,options:{startTimestamp:o-PB*86400,endTimestamp:o,interval:"HOUR"}}});if(!a.ok)throw new Error(Xe(a));let s=a.data?.data?.vaultV2ByAddress,l=Number(s?.netApy);return{samples:(s?.historicalState?.avgNetApy||[]).filter(c=>c?.y!==null&&c?.y!==void 0).map(c=>({timeMs:Number(c?.x)*1e3,fraction:Number(c?.y)})),current:Number.isFinite(l)?l:null,rewards:[]}}};async function gO(t,e,r){let n=`${r.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${t.token}?range=h&day=${PB}`,i=await ve.get(n);if(!i.ok)throw new Error(Xe(i));return{samples:(Array.isArray(i.data)?i.data:i.data?.data||[]).filter(a=>a?.rate!==null&&a?.rate!==void 0).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.rate)})),current:null,rewards:[]}}var xB={"aave-v3":new hO,"compound-v3":new fO,spark:new uO,"spark-ethereum":new dO,"spark-l2-susds":new pO,"morpho-v2":new mO},uae=xB.spark;function od(t){return xB[t.type]??uae}var dae={"aave-v3":"Aave V3","compound-v3":"Compound V3",spark:"Spark","spark-ethereum":"Spark","spark-l2-susds":"Spark","morpho-v2":"Morpho V2"};function Mo(t){return dae[t]??null}var pae={"aave-v3":"https://app.aave.com","compound-v3":"https://app.compound.finance",spark:"https://app.spark.fi","spark-ethereum":"https://app.spark.fi","spark-l2-susds":"https://app.spark.fi","morpho-v2":"https://app.morpho.org"};function Z0(t){return pae[t]??null}function mc(t,e){return Number(t)/10**e}function G0(t){return new Date(t).toISOString().slice(0,10)}p();p();var ad="0x0000000000000000000000000000000000000000";function Ny(t){let e=parseInt(t,16);return Number.isFinite(e)?{chainId:e}:null}function sl(t){if(typeof t=="number")return Number.isInteger(t)&&t>0?`0x${t.toString(16)}`:null;if(typeof t!="string")return null;let e=t.trim().toLowerCase();if(!e)return null;if(!/^(0x[0-9a-f]+|\d+)$/.test(e))return _t(e);let r=e.startsWith("0x")?parseInt(e,16):Number(e);return Number.isInteger(r)&&r>0?`0x${r.toString(16)}`:null}var hae={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function W0(t){let e=sl(t);return e?hae[e]??null:null}function IB(t){return["susds","usds","rateProvider"].map(e=>({target:t,callData:gt({abi:cO,functionName:e})}))}var OB=3,fae={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function yO(t){let e=sl(t),r=e?fae[e]:void 0;return r?{target:r,callData:gt({abi:id,functionName:"getConversionRate"})}:null}var mae=new Set(["spark","spark-ethereum","spark-l2-susds","morpho-v2"]),RB="spark-l2-susds";function K0(t){return!!t&&mae.has(t)}var _O=t=>{if(t==null||t==="")return null;let e=Number(t);return!Number.isInteger(e)||e<0||e>36?null:e},gae=t=>{if(t==null||t==="")return null;let e=Number(t);return Number.isFinite(e)&&e>0?e:null};function My(t){let e=gae(t.yieldAsset?.fixedPrice);return e!==null?e:Number.isFinite(t.priceUSD)?t.priceUSD:0}function NB(t){if(!K0(t.yieldProtocol)||_O(t.yieldAsset?.decimals)===null||t.yieldProtocol===RB&&!yO(t.chain))return!1;let e=My(t);return Number.isFinite(e)&&e>0}function bO(t){let e=[],r=[];for(let n of t)if(!(n.rawBalance<=0n)&&NB(n)){if(n.yieldProtocol===RB){let i=yO(n.chain);if(!i)continue;e.push({key:n.key,...i}),r.push(n.key);continue}e.push({key:n.key,target:n.address,callData:gt({abi:pa,functionName:"convertToAssets",args:[n.rawBalance]})})}return{calls:e,rateKeys:r}}function Y0(t,e,r){let n=new Map(t.map(s=>[s.key,s])),i=new Set(e.rateKeys),o=new Map;e.calls.forEach((s,l)=>{let c=Gr(r[l]??null);if(c===null)return;if(!i.has(s.key)){o.set(s.key,c);return}let u=n.get(s.key),d=_O(u?.yieldAsset?.decimals);if(!u||d===null)return;let h=kh(u.rawBalance,c,u.decimals,d);h!==null&&o.set(s.key,h)});let a=new Map;for(let s of t){let l=mc(s.rawBalance,s.decimals),c=My(s),u=o.get(s.key),d={underlyingAmount:l,valueUSD:l*c,pricePerTokenUSD:c,converted:!1};if(u===void 0){a.set(s.key,d);continue}let h=_O(s.yieldAsset?.decimals);if(h===null){a.set(s.key,d);continue}let m=mc(u,h),g=m*c;a.set(s.key,{underlyingAmount:m,valueUSD:g,pricePerTokenUSD:l>0?g/l:c,converted:!0})}return a}async function J0(t,e,r={}){let n=e.map(a=>a.chain==null?{...a,chain:t}:a),i=bO(n);if(i.calls.length===0)return Y0(n,i,[]);let o=await ni(String(t),i.calls,r.rpcUrl);return Y0(n,i,o)}async function yae(t,e,r={}){let n=await _ae(t,e,r.apiBaseUrl);return n?$B(t,n,r):null}async function $B(t,e,r={}){let n=MB(e?.price),i=l=>l!=null&&l>0?l:null;if(!K0(e?.yieldProtocol))return i(n);let o=My({key:"price",address:"",rawBalance:0n,decimals:0,priceUSD:n??0,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:t});if(!(o>0))return null;let a=Math.trunc(MB(e?.decimals)??18);if(!Number.isInteger(a)||a<0||a>36)return i(n);let s={key:"price",address:String(e?.address??"").toLowerCase(),rawBalance:10n**BigInt(a),decimals:a,priceUSD:o,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:t};try{let c=(await J0(t,[s],r)).get(s.key);return c?.converted?i(c.pricePerTokenUSD):null}catch{return null}}async function _ae(t,e,r){let n=String(e??"").toLowerCase();if(!n)return null;try{return(await new jr(r?{baseUrl:r}:void 0).getYieldPricingTokens(t,[n])).find(a=>String(a?.address??"").toLowerCase()===n)??null}catch{return null}}function MB(t){if(t==null||t==="")return null;let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:null}var bae="https://nft.keyring.app",vae="https://nft.keyring.app",wae=.01,rt=5,lr=1e3,Sae=25,kae="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Tae="0x0000000000000000000000000000000000000000",nt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function mr(t){return t||Zi}function cr(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 ur(t){return new Promise(e=>setTimeout(e,t))}function Pae(t){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!t||typeof t!="object")return e;let r=t;if("active_protocols"in r||"total_usd_value"in r){let i=r;return{...e,...i,protocols:i.protocols||[]}}let n=r.result;return!n||typeof n!="object"?e:{active_protocols:n.activeProtocols??0,total_positions:n.totalPositions??0,total_usd_value:n.totalUsd??0,total_unclaimed_usd_value:n.totalUnclaimedUsd??0,protocols:(n.protocols||[]).map(i=>({protocol_id:i.protocolId,protocol_name:i.protocolName,protocol_url:i.protocolUrl??"",protocol_logo:i.protocolLogo??"",positions:i.positionCount??0,total_usd_value:i.totalUsd??0,total_unclaimed_usd_value:i.totalUnclaimedUsd??0,account_health_factor:i.accountHealthFactor??null}))}}function Aae(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 vO(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 ct=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??bae).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??vae).replace(/\/+$/,""),this.pantograph=new jr({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1,convertYieldValues:s=!0}=e;if(!r)return{success:!1,error:"Address is required"};let l=mr(n),c="Unknown error";for(let u=1;u<=rt;u++)try{let d={chain:l,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(d.token_addresses=i);let h=[],m=null;do{m&&(d.cursor=m);let y=cr(d),_=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${y}`,b=await ve.get(_);if(!b.ok)throw new nt(b.status,Xe(b));let v=b.data,S=v?.data??v;S?.result?.length>0&&h.push(...S.result),m=S?.cursor??null}while(m);let g={result:h};if(g?.result?.length>0){g.result=g.result.filter(_=>parseFloat(_.balance||"0")>0),g.result=g.result.map(_=>({..._,token_address:_.token_address.toLowerCase()===kae?Tae:_.token_address}));let y=await this.enrichTokenPrices(g.result,l);s&&await this.applyYieldValues(g.result,l,y),g.result=g.result.filter(_=>_.usd_value==null||_.usd_value>=wae)}return{success:!0,data:g}}catch(d){if(c=d instanceof Error?d.message:"Unknown error",d instanceof nt&&d.status===400)break;u<rt&&await ur(lr)}return{success:!1,error:c}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=mr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=rt;s++)try{let[l,c]=await Promise.allSettled([ve.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${cr({chain:i,addresses:[r]})}`),ve.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${cr({chain:i,include:"percent_change"})}`)]),u=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;u=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!u){o="Token metadata not found",s<rt&&await ur(lr);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let h=c.value.data;d=h?.data??h}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof nt&&l.status===400)break;s<rt&&await ur(lr)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=100,excludeSpam:o=!1,cursor:a,tokenAddresses:s,includePrices:l,format:c="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let u=mr(n),d=[],h=a,m,g;for(let y=0;y<Sae;y++){let _=await this.fetchWalletNftsPage({address:r,moralisChain:u,limit:i,excludeSpam:o,cursor:h,tokenAddresses:s,includePrices:l,format:c});if(!_.success){if(d.length===0)return _;break}let b=_.data;if(!b)break;let{result:v,cursor:S,page:T,page_size:C}=b;if(Array.isArray(v)&&d.push(...v),m=T,g=C,h=typeof S=="string"&&S.trim()?S:void 0,!h)break}return{success:!0,data:{result:d,cursor:h,page:m,page_size:g}}}async fetchWalletNftsPage(e){let{address:r,moralisChain:n,limit:i,excludeSpam:o,cursor:a,tokenAddresses:s,includePrices:l,format:c}=e,u="Unknown error";for(let d=1;d<=rt;d++)try{let h={chain:n,format:c,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(h.cursor=a),l&&(h.include_prices=!0),s&&s.length>0&&(h.token_addresses=s);let m=cr(h),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${m}`,y=await ve.get(g);if(!y.ok)throw new nt(y.status,Xe(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(u=h instanceof Error?h.message:"Unknown error",h instanceof nt&&h.status===400)break;d<rt&&await ur(lr)}return{success:!1,error:u}}async getWalletNftCollections(e){let{address:r,chain:n,limit:i=100,excludeSpam:o=!0,cursor:a}=e;if(!r)return{success:!1,error:"Address is required"};let s=mr(n),l="Unknown error";for(let c=1;c<=rt;c++)try{let u={chain:s,limit:i,exclude_spam:o};a&&(u.cursor=a);let d=cr(u),h=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/collections?${d}`,m=await ve.get(h);if(!m.ok)throw new nt(m.status,Xe(m));let g=m.data;return{success:!0,data:g?.data??g}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof nt&&u.status===400)break;c<rt&&await ur(lr)}return{success:!1,error:l}}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(!Ve(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=mr(i),u="Unknown error";for(let d=1;d<=rt;d++)try{let h={chain:c,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=cr(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await ve.get(g);if(!y.ok)throw new nt(y.status,Xe(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(u=h instanceof Error?h.message:"Unknown error",h instanceof nt&&h.status===400)break;d<rt&&await ur(lr)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=mr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=rt;_++)try{let b={chain:m,limit:g,order:u};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),c&&(b.cursor=c),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let v=cr(b),S=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${v}`,T=await ve.get(S);if(!T.ok)throw new nt(T.status,Xe(T));let C=T.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof nt&&b.status===400)break;_<rt&&await ur(lr)}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:c,cursor:u,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=mr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=rt;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),c!=null&&(_.to_block=c),u&&(_.cursor=u),i?.length&&(_.contract_addresses=i);let b=cr(_),v=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,S=await ve.get(v);if(!S.ok)throw new nt(S.status,Xe(S));let T=S.data;return{success:!0,data:T?.data??T}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof nt&&_.status===400)break;y<rt&&await ur(lr)}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:c,cursor:u,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=mr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=rt;b++)try{let v={chain:g,limit:y,order:d,format:m};a&&(v.from_date=a),s&&(v.to_date=s),l!=null&&(v.from_block=l),c!=null&&(v.to_block=c),u&&(v.cursor=u),i?.length&&(v.contract_addresses=i),h!=null&&(v.include_prices=h);let S=cr(v),T=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${S}`,C=await ve.get(T);if(!C.ok)throw new nt(C.status,Xe(C));let I=C.data;return{success:!0,data:I?.data??I}}catch(v){if(_=v instanceof Error?v.message:"Unknown error",v instanceof nt&&v.status===400)break;b<rt&&await ur(lr)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Ve(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=mr(n),a="Unknown error";for(let s=1;s<=rt;s++)try{let l={chain:o};i&&(l.days=i);let c=cr(l),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${c}`,d=await ve.get(u);if(!d.ok)throw new nt(d.status,Xe(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 nt&&l.status===400)break;s<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=mr(n),s="Unknown error";for(let l=1;l<=rt;l++)try{let c={chain:a};i&&(c.days=i),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=cr(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${u}`,h=await ve.get(d);if(!h.ok)throw new nt(h.status,Xe(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(c){if(s=c instanceof Error?c.message:"Unknown error",c instanceof nt&&c.status===400)break;l<rt&&await ur(lr)}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=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=mr(n),s="Unknown error";for(let l=1;l<=rt;l++)try{let c={chain:a};i!=null&&(c.limit=i),o&&(c.cursor=o);let u=cr(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${u}`,h=await ve.get(d);if(!h.ok)throw new nt(h.status,Xe(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(c){if(s=c instanceof Error?c.message:"Unknown error",c instanceof nt&&c.status===400)break;l<rt&&await ur(lr)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data,d=u?.data??u;return{success:!0,data:Pae(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data,d=u?.data??u;return{success:!0,data:Aae(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=mr(i),a="Unknown error";for(let s=1;s<=rt;s++)try{let l=cr({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,u=await ve.get(c);if(!u.ok)throw new nt(u.status,Xe(u));let m=u.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(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 nt&&l.status===400)break;s<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=rt;o++)try{let a={};r&&(a.chain=mr(r)),n!=null&&(a.limit=n);let s=cr(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data,d=u?.data??u;return{success:!0,data:vO(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof nt&&a.status===400)break;o<rt&&await ur(lr)}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<=rt;s++)try{let l={};r&&(l.chain=mr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let c=cr(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await ve.get(u);if(!d.ok)throw new nt(d.status,Xe(d));let h=d.data,m=h?.data??h;return{success:!0,data:vO(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof nt&&l.status===400)break;s<rt&&await ur(lr)}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<=rt;s++)try{let l={};r&&(l.chain=mr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let c=cr(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await ve.get(u);if(!d.ok)throw new nt(d.status,Xe(d));let h=d.data,m=h?.data??h;return{success:!0,data:vO(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof nt&&l.status===400)break;s<rt&&await ur(lr)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}async applyYieldValues(e,r,n){if(e.length===0||n.size===0)return;let i=[],o=new Map;if(e.forEach((a,s)=>{let l=n.get(a.token_address.toLowerCase());if(!l?.yieldProtocol||!/^\d+$/.test(a.balance??""))return;let c=BigInt(a.balance);if(c<=0n)return;let u=String(s);o.set(u,a),i.push({key:u,address:a.token_address,rawBalance:c,decimals:a.decimals,priceUSD:a.usd_price??0,yieldProtocol:l.yieldProtocol,yieldAsset:l.yieldAsset,chain:r})}),i.length!==0)try{let a=await J0(r,i);for(let[s,l]of a){let c=o.get(s);c&&(!Number.isFinite(l.valueUSD)||!Number.isFinite(l.pricePerTokenUSD)||l.pricePerTokenUSD<=0||(c.usd_value=l.valueUSD,c.usd_price=l.pricePerTokenUSD))}}catch{}}};var Th=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 ct(r),this.llm=new Mr(r?.llm??{})}async run(r,n){let i=r.keyword||"",o=r.prompt||"",a=n?.walletAddress||void 0;if(!i)return{error:"Missing required parameter: keyword"};let s;try{s=Wr(r.chain,n)}catch(l){if(l instanceof fc)return await this.researchTokenChainAgnostic(i,o,a);throw l}return await this.searchToken(i,s,o,a)}async researchTokenChainAgnostic(r,n,i){let o=[i?`User's connected wallet address: ${i}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
|
|
459
|
+
}`,Sh=class{underlyingCall(e){return gn(e.contract,pa,"asset")}liveRateCall(e,r){return null}followUpRateCall(e,r){return null}decodeSize(e,r){if(!Number.isInteger(r.decimals)||r.decimals<0)return null;let n=Gr(e);return n===null?null:mc(n,r.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,r){return this.balanceIsUnderlying?null:gn(e.contract,pa,"convertToAssets",[r])}},Oy=class extends Sh{constructor(){super(...arguments);f(this,"type","spark");f(this,"balanceIsUnderlying",!1)}sizeCall(r){return gn(r.contract,pa,"totalAssets")}fetchApy(r,n,i){return gO(r,n,i)}},uO=class extends Oy{constructor(){super(...arguments);f(this,"type","spark")}liveRateCall(r){return gn(r.contract,wh,"rateProvider")}followUpRateCall(r,n){let i=rr(n);return i===null?null:gn(i,id,"getAPR")}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ry(Math.expm1(Number(n)/H0))}},dO=class extends Oy{constructor(){super(...arguments);f(this,"type","spark-ethereum")}liveRateCall(r){return gn(r.contract,wh,"vsr")}decodeLiveRate(r){let n=Gr(r);if(n===null||n<=0n)return null;let i=Number(n-AB)/H0;return i>-1?Ry(Math.expm1(Math.log1p(i)*EB)):null}},pO=class extends Sh{constructor(){super(...arguments);f(this,"type","spark-l2-susds");f(this,"balanceIsUnderlying",!1)}underlyingCall(){return null}sizeCall(r){return gn(r.token,Zt,"totalSupply")}liveRateCall(r){return gn(r.contract,id,"getAPR")}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ry(Math.expm1(Number(n)/H0))}convertToAssetsCall(r){return gn(r.contract,id,"getConversionRate")}fetchApy(r,n,i){return gO(r,n,i)}};function kh(t,e,r,n){if(e<=0n||!Number.isInteger(r)||!Number.isInteger(n)||r<0||n<0)return null;let i=t*e/AB,o=n-r;return o===0?i:o>0?i*10n**BigInt(o):i/10n**BigInt(-o)}var hO=class extends Sh{constructor(){super(...arguments);f(this,"type","aave-v3");f(this,"balanceIsUnderlying",!0)}underlyingCall(r){return gn(r.token,vh,"UNDERLYING_ASSET_ADDRESS")}sizeCall(r){return gn(r.token,Zt,"totalSupply")}liveRateCall(r,n){return gn(r.contract,V0,"getReserveData",[n.address])}decodeLiveRate(r){if(!r)return null;let n;try{let[i]=Mn(V0[0].outputs,r);n=i.currentLiquidityRate}catch{return null}return Ry(CB(Number(n)/H0))}async fetchApy(r,n,i,o){let a={chainId:n.chainId,market:r.contract,underlyingToken:o.address,window:"LAST_WEEK"},s=await ve.post(i.aaveApiUrl,{operationName:"SupplyAPYHistory",query:sae,variables:{request:a,reserve:{chainId:n.chainId,market:r.contract,underlyingToken:o.address}}});if(!s.ok)throw new Error(Xe(s));return{samples:(s.data?.data?.value||[]).filter(l=>l?.avgRate?.value!==null&&l?.avgRate?.value!==void 0).map(l=>({timeMs:Date.parse(l?.date??""),fraction:Number(l?.avgRate?.value)})),current:null,rewards:lae(s.data?.data?.reserve?.incentives)}}},fO=class extends Sh{constructor(){super(...arguments);f(this,"type","compound-v3");f(this,"balanceIsUnderlying",!0)}underlyingCall(r){return gn(r.contract,nd,"baseToken")}sizeCall(r){return gn(r.token,Zt,"totalSupply")}liveRateCall(r){return gn(r.contract,nd,"getUtilization")}followUpRateCall(r,n){let i=Gr(n);return i===null?null:gn(r.contract,nd,"getSupplyRate",[i])}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ry(Number(n)/1e18*EB)}fetchApy(r,n,i){return gO(r,n,i)}},mO=class extends Oy{constructor(){super(...arguments);f(this,"type","morpho-v2")}async fetchApy(r,n,i){let o=Math.floor(Date.now()/1e3),a=await ve.post(i.morphoApiUrl,{operationName:"VaultV2ByAddress",query:cae,variables:{address:r.contract,chainId:n.chainId,options:{startTimestamp:o-PB*86400,endTimestamp:o,interval:"HOUR"}}});if(!a.ok)throw new Error(Xe(a));let s=a.data?.data?.vaultV2ByAddress,l=Number(s?.netApy),c=Number(s?.avgNetApy);return{avgOverride:Number.isFinite(c)?c:null,samples:(s?.historicalState?.avgNetApy||[]).filter(u=>u?.y!==null&&u?.y!==void 0).map(u=>({timeMs:Number(u?.x)*1e3,fraction:Number(u?.y)})),current:Number.isFinite(l)?l:null,rewards:[]}}};async function gO(t,e,r){let n=`${r.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${t.token}?range=h&day=${PB}`,i=await ve.get(n);if(!i.ok)throw new Error(Xe(i));return{samples:(Array.isArray(i.data)?i.data:i.data?.data||[]).filter(a=>a?.rate!==null&&a?.rate!==void 0).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.rate)})),current:null,rewards:[]}}var xB={"aave-v3":new hO,"compound-v3":new fO,spark:new uO,"spark-ethereum":new dO,"spark-l2-susds":new pO,"morpho-v2":new mO},uae=xB.spark;function od(t){return xB[t.type]??uae}var dae={"aave-v3":"Aave V3","compound-v3":"Compound V3",spark:"Spark","spark-ethereum":"Spark","spark-l2-susds":"Spark","morpho-v2":"Morpho V2"};function Mo(t){return dae[t]??null}var pae={"aave-v3":"https://app.aave.com","compound-v3":"https://app.compound.finance",spark:"https://app.spark.fi","spark-ethereum":"https://app.spark.fi","spark-l2-susds":"https://app.spark.fi","morpho-v2":"https://app.morpho.org"};function Z0(t){return pae[t]??null}function mc(t,e){return Number(t)/10**e}function G0(t){return new Date(t).toISOString().slice(0,10)}p();p();var ad="0x0000000000000000000000000000000000000000";function Ny(t){let e=parseInt(t,16);return Number.isFinite(e)?{chainId:e}:null}function sl(t){if(typeof t=="number")return Number.isInteger(t)&&t>0?`0x${t.toString(16)}`:null;if(typeof t!="string")return null;let e=t.trim().toLowerCase();if(!e)return null;if(!/^(0x[0-9a-f]+|\d+)$/.test(e))return _t(e);let r=e.startsWith("0x")?parseInt(e,16):Number(e);return Number.isInteger(r)&&r>0?`0x${r.toString(16)}`:null}var hae={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function W0(t){let e=sl(t);return e?hae[e]??null:null}function IB(t){return["susds","usds","rateProvider"].map(e=>({target:t,callData:gt({abi:cO,functionName:e})}))}var OB=3,fae={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function yO(t){let e=sl(t),r=e?fae[e]:void 0;return r?{target:r,callData:gt({abi:id,functionName:"getConversionRate"})}:null}var mae=new Set(["spark","spark-ethereum","spark-l2-susds","morpho-v2"]),RB="spark-l2-susds";function K0(t){return!!t&&mae.has(t)}var _O=t=>{if(t==null||t==="")return null;let e=Number(t);return!Number.isInteger(e)||e<0||e>36?null:e},gae=t=>{if(t==null||t==="")return null;let e=Number(t);return Number.isFinite(e)&&e>0?e:null};function My(t){let e=gae(t.yieldAsset?.fixedPrice);return e!==null?e:Number.isFinite(t.priceUSD)?t.priceUSD:0}function NB(t){if(!K0(t.yieldProtocol)||_O(t.yieldAsset?.decimals)===null||t.yieldProtocol===RB&&!yO(t.chain))return!1;let e=My(t);return Number.isFinite(e)&&e>0}function bO(t){let e=[],r=[];for(let n of t)if(!(n.rawBalance<=0n)&&NB(n)){if(n.yieldProtocol===RB){let i=yO(n.chain);if(!i)continue;e.push({key:n.key,...i}),r.push(n.key);continue}e.push({key:n.key,target:n.address,callData:gt({abi:pa,functionName:"convertToAssets",args:[n.rawBalance]})})}return{calls:e,rateKeys:r}}function Y0(t,e,r){let n=new Map(t.map(s=>[s.key,s])),i=new Set(e.rateKeys),o=new Map;e.calls.forEach((s,l)=>{let c=Gr(r[l]??null);if(c===null)return;if(!i.has(s.key)){o.set(s.key,c);return}let u=n.get(s.key),d=_O(u?.yieldAsset?.decimals);if(!u||d===null)return;let h=kh(u.rawBalance,c,u.decimals,d);h!==null&&o.set(s.key,h)});let a=new Map;for(let s of t){let l=mc(s.rawBalance,s.decimals),c=My(s),u=o.get(s.key),d={underlyingAmount:l,valueUSD:l*c,pricePerTokenUSD:c,converted:!1};if(u===void 0){a.set(s.key,d);continue}let h=_O(s.yieldAsset?.decimals);if(h===null){a.set(s.key,d);continue}let m=mc(u,h),g=m*c;a.set(s.key,{underlyingAmount:m,valueUSD:g,pricePerTokenUSD:l>0?g/l:c,converted:!0})}return a}async function J0(t,e,r={}){let n=e.map(a=>a.chain==null?{...a,chain:t}:a),i=bO(n);if(i.calls.length===0)return Y0(n,i,[]);let o=await ni(String(t),i.calls,r.rpcUrl);return Y0(n,i,o)}async function yae(t,e,r={}){let n=await _ae(t,e,r.apiBaseUrl);return n?$B(t,n,r):null}async function $B(t,e,r={}){let n=MB(e?.price),i=l=>l!=null&&l>0?l:null;if(!K0(e?.yieldProtocol))return i(n);let o=My({key:"price",address:"",rawBalance:0n,decimals:0,priceUSD:n??0,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:t});if(!(o>0))return null;let a=Math.trunc(MB(e?.decimals)??18);if(!Number.isInteger(a)||a<0||a>36)return i(n);let s={key:"price",address:String(e?.address??"").toLowerCase(),rawBalance:10n**BigInt(a),decimals:a,priceUSD:o,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:t};try{let c=(await J0(t,[s],r)).get(s.key);return c?.converted?i(c.pricePerTokenUSD):null}catch{return null}}async function _ae(t,e,r){let n=String(e??"").toLowerCase();if(!n)return null;try{return(await new jr(r?{baseUrl:r}:void 0).getYieldPricingTokens(t,[n])).find(a=>String(a?.address??"").toLowerCase()===n)??null}catch{return null}}function MB(t){if(t==null||t==="")return null;let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:null}var bae="https://nft.keyring.app",vae="https://nft.keyring.app",wae=.01,rt=5,lr=1e3,Sae=25,kae="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Tae="0x0000000000000000000000000000000000000000",nt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function mr(t){return t||Zi}function cr(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 ur(t){return new Promise(e=>setTimeout(e,t))}function Pae(t){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!t||typeof t!="object")return e;let r=t;if("active_protocols"in r||"total_usd_value"in r){let i=r;return{...e,...i,protocols:i.protocols||[]}}let n=r.result;return!n||typeof n!="object"?e:{active_protocols:n.activeProtocols??0,total_positions:n.totalPositions??0,total_usd_value:n.totalUsd??0,total_unclaimed_usd_value:n.totalUnclaimedUsd??0,protocols:(n.protocols||[]).map(i=>({protocol_id:i.protocolId,protocol_name:i.protocolName,protocol_url:i.protocolUrl??"",protocol_logo:i.protocolLogo??"",positions:i.positionCount??0,total_usd_value:i.totalUsd??0,total_unclaimed_usd_value:i.totalUnclaimedUsd??0,account_health_factor:i.accountHealthFactor??null}))}}function Aae(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 vO(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 ct=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??bae).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??vae).replace(/\/+$/,""),this.pantograph=new jr({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1,convertYieldValues:s=!0}=e;if(!r)return{success:!1,error:"Address is required"};let l=mr(n),c="Unknown error";for(let u=1;u<=rt;u++)try{let d={chain:l,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(d.token_addresses=i);let h=[],m=null;do{m&&(d.cursor=m);let y=cr(d),_=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${y}`,b=await ve.get(_);if(!b.ok)throw new nt(b.status,Xe(b));let v=b.data,S=v?.data??v;S?.result?.length>0&&h.push(...S.result),m=S?.cursor??null}while(m);let g={result:h};if(g?.result?.length>0){g.result=g.result.filter(_=>parseFloat(_.balance||"0")>0),g.result=g.result.map(_=>({..._,token_address:_.token_address.toLowerCase()===kae?Tae:_.token_address}));let y=await this.enrichTokenPrices(g.result,l);s&&await this.applyYieldValues(g.result,l,y),g.result=g.result.filter(_=>_.usd_value==null||_.usd_value>=wae)}return{success:!0,data:g}}catch(d){if(c=d instanceof Error?d.message:"Unknown error",d instanceof nt&&d.status===400)break;u<rt&&await ur(lr)}return{success:!1,error:c}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=mr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=rt;s++)try{let[l,c]=await Promise.allSettled([ve.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${cr({chain:i,addresses:[r]})}`),ve.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${cr({chain:i,include:"percent_change"})}`)]),u=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;u=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!u){o="Token metadata not found",s<rt&&await ur(lr);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let h=c.value.data;d=h?.data??h}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof nt&&l.status===400)break;s<rt&&await ur(lr)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=100,excludeSpam:o=!1,cursor:a,tokenAddresses:s,includePrices:l,format:c="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let u=mr(n),d=[],h=a,m,g;for(let y=0;y<Sae;y++){let _=await this.fetchWalletNftsPage({address:r,moralisChain:u,limit:i,excludeSpam:o,cursor:h,tokenAddresses:s,includePrices:l,format:c});if(!_.success){if(d.length===0)return _;break}let b=_.data;if(!b)break;let{result:v,cursor:S,page:T,page_size:C}=b;if(Array.isArray(v)&&d.push(...v),m=T,g=C,h=typeof S=="string"&&S.trim()?S:void 0,!h)break}return{success:!0,data:{result:d,cursor:h,page:m,page_size:g}}}async fetchWalletNftsPage(e){let{address:r,moralisChain:n,limit:i,excludeSpam:o,cursor:a,tokenAddresses:s,includePrices:l,format:c}=e,u="Unknown error";for(let d=1;d<=rt;d++)try{let h={chain:n,format:c,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(h.cursor=a),l&&(h.include_prices=!0),s&&s.length>0&&(h.token_addresses=s);let m=cr(h),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${m}`,y=await ve.get(g);if(!y.ok)throw new nt(y.status,Xe(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(u=h instanceof Error?h.message:"Unknown error",h instanceof nt&&h.status===400)break;d<rt&&await ur(lr)}return{success:!1,error:u}}async getWalletNftCollections(e){let{address:r,chain:n,limit:i=100,excludeSpam:o=!0,cursor:a}=e;if(!r)return{success:!1,error:"Address is required"};let s=mr(n),l="Unknown error";for(let c=1;c<=rt;c++)try{let u={chain:s,limit:i,exclude_spam:o};a&&(u.cursor=a);let d=cr(u),h=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/collections?${d}`,m=await ve.get(h);if(!m.ok)throw new nt(m.status,Xe(m));let g=m.data;return{success:!0,data:g?.data??g}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof nt&&u.status===400)break;c<rt&&await ur(lr)}return{success:!1,error:l}}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(!Ve(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=mr(i),u="Unknown error";for(let d=1;d<=rt;d++)try{let h={chain:c,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=cr(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await ve.get(g);if(!y.ok)throw new nt(y.status,Xe(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(u=h instanceof Error?h.message:"Unknown error",h instanceof nt&&h.status===400)break;d<rt&&await ur(lr)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=mr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=rt;_++)try{let b={chain:m,limit:g,order:u};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),c&&(b.cursor=c),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let v=cr(b),S=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${v}`,T=await ve.get(S);if(!T.ok)throw new nt(T.status,Xe(T));let C=T.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof nt&&b.status===400)break;_<rt&&await ur(lr)}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:c,cursor:u,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=mr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=rt;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),c!=null&&(_.to_block=c),u&&(_.cursor=u),i?.length&&(_.contract_addresses=i);let b=cr(_),v=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,S=await ve.get(v);if(!S.ok)throw new nt(S.status,Xe(S));let T=S.data;return{success:!0,data:T?.data??T}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof nt&&_.status===400)break;y<rt&&await ur(lr)}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:c,cursor:u,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=mr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=rt;b++)try{let v={chain:g,limit:y,order:d,format:m};a&&(v.from_date=a),s&&(v.to_date=s),l!=null&&(v.from_block=l),c!=null&&(v.to_block=c),u&&(v.cursor=u),i?.length&&(v.contract_addresses=i),h!=null&&(v.include_prices=h);let S=cr(v),T=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${S}`,C=await ve.get(T);if(!C.ok)throw new nt(C.status,Xe(C));let I=C.data;return{success:!0,data:I?.data??I}}catch(v){if(_=v instanceof Error?v.message:"Unknown error",v instanceof nt&&v.status===400)break;b<rt&&await ur(lr)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Ve(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=mr(n),a="Unknown error";for(let s=1;s<=rt;s++)try{let l={chain:o};i&&(l.days=i);let c=cr(l),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${c}`,d=await ve.get(u);if(!d.ok)throw new nt(d.status,Xe(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 nt&&l.status===400)break;s<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=mr(n),s="Unknown error";for(let l=1;l<=rt;l++)try{let c={chain:a};i&&(c.days=i),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=cr(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${u}`,h=await ve.get(d);if(!h.ok)throw new nt(h.status,Xe(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(c){if(s=c instanceof Error?c.message:"Unknown error",c instanceof nt&&c.status===400)break;l<rt&&await ur(lr)}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=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=mr(n),s="Unknown error";for(let l=1;l<=rt;l++)try{let c={chain:a};i!=null&&(c.limit=i),o&&(c.cursor=o);let u=cr(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${u}`,h=await ve.get(d);if(!h.ok)throw new nt(h.status,Xe(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(c){if(s=c instanceof Error?c.message:"Unknown error",c instanceof nt&&c.status===400)break;l<rt&&await ur(lr)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data,d=u?.data??u;return{success:!0,data:Pae(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ve(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data,d=u?.data??u;return{success:!0,data:Aae(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=mr(i),a="Unknown error";for(let s=1;s<=rt;s++)try{let l=cr({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,u=await ve.get(c);if(!u.ok)throw new nt(u.status,Xe(u));let m=u.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(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 nt&&l.status===400)break;s<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}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(!Ve(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=rt;a++)try{let s=cr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof nt&&s.status===400)break;a<rt&&await ur(lr)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=rt;o++)try{let a={};r&&(a.chain=mr(r)),n!=null&&(a.limit=n);let s=cr(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,c=await ve.get(l);if(!c.ok)throw new nt(c.status,Xe(c));let u=c.data,d=u?.data??u;return{success:!0,data:vO(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof nt&&a.status===400)break;o<rt&&await ur(lr)}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<=rt;s++)try{let l={};r&&(l.chain=mr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let c=cr(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await ve.get(u);if(!d.ok)throw new nt(d.status,Xe(d));let h=d.data,m=h?.data??h;return{success:!0,data:vO(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof nt&&l.status===400)break;s<rt&&await ur(lr)}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<=rt;s++)try{let l={};r&&(l.chain=mr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let c=cr(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await ve.get(u);if(!d.ok)throw new nt(d.status,Xe(d));let h=d.data,m=h?.data??h;return{success:!0,data:vO(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof nt&&l.status===400)break;s<rt&&await ur(lr)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}async applyYieldValues(e,r,n){if(e.length===0||n.size===0)return;let i=[],o=new Map;if(e.forEach((a,s)=>{let l=n.get(a.token_address.toLowerCase());if(!l?.yieldProtocol||!/^\d+$/.test(a.balance??""))return;let c=BigInt(a.balance);if(c<=0n)return;let u=String(s);o.set(u,a),i.push({key:u,address:a.token_address,rawBalance:c,decimals:a.decimals,priceUSD:a.usd_price??0,yieldProtocol:l.yieldProtocol,yieldAsset:l.yieldAsset,chain:r})}),i.length!==0)try{let a=await J0(r,i);for(let[s,l]of a){let c=o.get(s);c&&(!Number.isFinite(l.valueUSD)||!Number.isFinite(l.pricePerTokenUSD)||l.pricePerTokenUSD<=0||(c.usd_value=l.valueUSD,c.usd_price=l.pricePerTokenUSD))}}catch{}}};var Th=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 ct(r),this.llm=new Mr(r?.llm??{})}async run(r,n){let i=r.keyword||"",o=r.prompt||"",a=n?.walletAddress||void 0;if(!i)return{error:"Missing required parameter: keyword"};let s;try{s=Wr(r.chain,n)}catch(l){if(l instanceof fc)return await this.researchTokenChainAgnostic(i,o,a);throw l}return await this.searchToken(i,s,o,a)}async researchTokenChainAgnostic(r,n,i){let o=[i?`User's connected wallet address: ${i}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
|
|
459
460
|
`),a=n?await this.askGeminiWithSearch(n,o):null;return{_instructions:'The token info comes from web research only (the user is on a chain this app does not support on-chain). Present a clear summary of the token using the research: what it is, current USD price and 24h change, market data, recent news and the catalyst behind any price move, and a brief, clearly-hedged sense of market direction (no financial advice). Do NOT add a labelled "AI Analysis" heading and do NOT mention that the analysis came from AI \u2014 write it as a normal token summary. If a field is unknown, omit it. Do NOT mention chains, tools, or that anything is unsupported; just answer the question.',keyword:r,token:null,userHoldsToken:!1,research:a}}async searchToken(r,n,i,o){let a=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
|
|
460
461
|
`),[s,l,c]=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)]),u=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=[...u].sort((b,v)=>(h(b)?0:1)-(h(v)?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,...u.length>1?{searchResults:m.slice(0,10)}:{},research:c}}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:!1,excludeUnverifiedContracts:!1});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 Ph=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 ct(r)}async run(r,n){let i=Wr(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,c;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?Q(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,c=h.name}let u=await this.service.getTokenHolders({address:s,chain:i});if(!u.success)return{error:u.error||"Failed to fetch token holder stats"};let d=u.data;return{token:{symbol:l??a??null,name:c??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(c=>(c.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(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Ah=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 ct(r)}async run(r,n){let i=Wr(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,c;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?Q(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,c=h.name}let u=await this.service.getTokenAnalytics({address:s,chain:i});if(!u.success)return{error:u.error||"Failed to fetch token analytics"};let d=u.data??{};return{token:{symbol:l??a??null,name:c??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(c=>(c.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(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Eh=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 ct(r)}async run(r,n){let i=Wr(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,c;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?Q(i):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,l=m.symbol,c=m.name}let u=await this.service.getTokenScore({address:s,chain:i});if(!u.success)return{error:u.error||"Failed to fetch token score"};let d=u.data??{},h=d.metrics??{};return{token:{symbol:l??a??null,name:c??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(c=>(c.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(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Ch=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 jr({baseUrl:r?.pantographUrl})}async run(r,n){let i=B0(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):
|
|
461
462
|
<rank>. <name> (<symbol>)
|
|
@@ -469,7 +470,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
|
|
|
469
470
|
- Market Cap: <marketCap>
|
|
470
471
|
- Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
|
|
471
472
|
- 24h Volume: <totalVolume.24h>
|
|
472
|
-
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?Q(i):"all",timeFrame:a??null,count:u.length,tokens:u}}};p();p();var Ih=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 ct(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=fr(r.address,n),o=hr(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=ii(),s=await Promise.all(a.map(async l=>{let c=await this.service.getWalletTokenBalances({address:i,chain:l,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:l,tokens:c.success?c.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((c,u)=>c+(u.usd_value||0),0),l=a.tokens.slice().sort((c,u)=>(u.usd_value||0)-(c.usd_value||0));return{chain:Q(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 Oh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=Wr(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,c=typeof r.toBlock=="number"?r.toBlock:typeof r.toBlock=="string"&&r.toBlock?Number(r.toBlock):void 0,u=Number.isFinite(l)?l:void 0,d=Number.isFinite(c)?c: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,v=Number.isFinite(b)&&b>0?b:10,S=await this.service.getWalletHistory({address:i,chain:o,limit:v,fromDate:a,toDate:s,fromBlock:u,toBlock:d,cursor:h,order:g,includeInternalTransactions:y,nftMetadata:_});if(!S.success)return{error:S.error||"Failed to fetch wallet history"};let C=(S.data?.result||[]).map(I=>{let R=yB(o,I.hash);return R?{...I,explorerUrl:R}:I});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:S.data?.cursor??null,hasMore:!!S.data?.cursor},transactionCount:C.length,transactions:C}}};p();function Eae(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 Rh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=Wr(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,c=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,u=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,v=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(x=>typeof x=="string"&&!!x).map(x=>x.trim()):void 0,S,T;if(b){let x=await this.resolveContractAddressBySymbol(b,i,o);x&&(v=[x.address],S=x.symbol,T=x.name)}let C=await this.service.getWalletTokenTransfers({address:i,chain:o,contractAddresses:v,limit:s,fromDate:l,toDate:c,fromBlock:u,toBlock:d,cursor:h,order:g});if(!C.success)return{error:C.error||"Failed to fetch token transfers"};let I=i.toLowerCase(),E=(C.data?.result||[]).map(x=>{let N=x.from_address.toLowerCase()===I,L=N?"send":"receive",F=N?x.to_address:x.from_address,W=N?x.to_address_label??void 0:x.from_address_label??void 0,X=N?x.to_address_entity??void 0:x.from_address_entity??void 0;return{...x,direction:L,amount_formatted:Eae(x),counterparty:F,counterparty_label:W,counterparty_entity:X}}),U=_==="all"?E:E.filter(x=>x.direction===_);if(b&&!v){let x=b.toLowerCase();U=U.filter(N=>(N.token_symbol??"").toLowerCase()===x)}let D=this.buildCounterparties(U);return{walletAddress:i,chain:o||"default",resolvedToken:S?{symbol:S,name:T,contractAddress:v?.[0]}:null,filters:{tokenSymbol:b||null,contractAddresses:v||null,direction:_,limit:s,order:g,fromDate:l||null,toDate:c||null,fromBlock:u??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:D}}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(c=>(c.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 c=s.data.find(u=>(u.symbol??"").toLowerCase()===o)??s.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.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(),c=parseFloat(a.amount_formatted)||0,u=s.get(l);u?(u.total+=c,u.count+=1,!u.label&&a.counterparty_label&&(u.label=a.counterparty_label),!u.entity&&a.counterparty_entity&&(u.entity=a.counterparty_entity),a.block_timestamp<u.first&&(u.first=a.block_timestamp),a.block_timestamp>u.last&&(u.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,total:c,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 Nh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=Wr(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,c=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,u=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",v=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(U=>typeof U=="string"&&!!U).map(U=>U.trim()):void 0,S=await this.service.getWalletNftTransfers({address:i,chain:o,contractAddresses:v,limit:s,fromDate:l,toDate:c,fromBlock:u,toBlock:d,cursor:h,order:g,includePrices:y});if(!S.success)return{error:S.error||"Failed to fetch NFT transfers"};let T=i.toLowerCase(),I=(S.data?.result||[]).map(U=>{let D=U.from_address.toLowerCase()===T,x=D?"send":"receive",N=D?U.to_address:U.from_address,L=D?U.to_address_label??void 0:U.from_address_label??void 0,F=D?U.to_address_entity??void 0:U.from_address_entity??void 0;return{...U,direction:x,counterparty:N,counterparty_label:L,counterparty_entity:F}}),R=b==="all"?I:I.filter(U=>U.direction===b),E=this.buildCounterparties(R);return{walletAddress:i,chain:o||"default",filters:{contractAddresses:v||null,direction:b,limit:s,order:g,fromDate:l||null,toDate:c||null,fromBlock:u??null,toBlock:d??null,includePrices:y??null},pagination:{cursor:S.data?.cursor??null,pageSize:S.data?.page_size??s,page:S.data?.page??null,hasMore:!!S.data?.cursor},transferCount:R.length,transfers:R,counterparties:E}}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(),c=a.token_name??a.token_address,u=s.get(l);u?(u.tokenIds.add(a.token_id),u.collections.add(c),u.count+=1,!u.label&&a.counterparty_label&&(u.label=a.counterparty_label),!u.entity&&a.counterparty_entity&&(u.entity=a.counterparty_entity),a.block_timestamp<u.first&&(u.first=a.block_timestamp),a.block_timestamp>u.last&&(u.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,tokenIds:new Set([a.token_id]),collections:new Set([c]),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 Cae=["all","7","30","60","90"],Mh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=hr(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=Cae.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 c=(await Promise.all(ii().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}]:[]),u=c.map(_=>({chain:Q(_.chain),summary:this.mapSummary(_.data)})),d=c.reduce((_,b)=>_+Number(b.data.total_realized_profit_usd||0),0),h=c.reduce((_,b)=>_+Number(b.data.total_bought_volume_usd||0),0),m=c.reduce((_,b)=>_+Number(b.data.total_sold_volume_usd||0),0),g=c.reduce((_,b)=>_+Number(b.data.total_trade_volume||0),0),y={totalCountOfTrades:c.reduce((_,b)=>_+b.data.total_count_of_trades,0),totalTradeVolume:g,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:h>0?d/h*100:0,totalBuys:c.reduce((_,b)=>_+b.data.total_buys,0),totalSells:c.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:u}}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 xae=["all","7","30","60","90"],X0=25,$h=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 ${X0}. 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 ${X0}.`,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 ${X0}.`,required:!1,items:{type:"string"}}]);f(this,"service");this.service=new ct(r)}async run(r,n){let i=fr(r.address,n),o=hr(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=xae.includes(a)?a:void 0,l=Array.isArray(r.tokenSymbols)?r.tokenSymbols.filter(h=>typeof h=="string"&&!!h.trim()).map(h=>h.trim()):[],c=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,c);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(ii().map(async h=>({chain:h,res:await this.fetchChainPnl(i,h,s,l,c)})))).filter(h=>h.res.ok&&h.res.tokens.length>0).map(h=>({chain:Q(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:c.length>0?c: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 c=Iae([...s.map(h=>h.address),...a]).slice(0,X0),u=c.length>0?c:void 0,d=await this.service.getWalletPnl({address:r,chain:n,days:i,tokenAddresses:u});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:u,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(c=>(c.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(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};function Iae(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 Oae=BigInt(2)**BigInt(255),Dh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=Wr(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,c=await this.service.getWalletApprovals({address:i,chain:o,limit:s,cursor:l});if(!c.success)return{error:c.error||"Failed to fetch wallet approvals"};let u=c.data,h=(u.result||[]).map(_=>Rae(_)),m=0,g=0,y=[];for(let _ of h){_.isUnlimited&&(g+=1);let b=parseFloat(_.token.usdAtRisk??"");Number.isFinite(b)&&(m+=b);let v=_.token.possibleSpam||_.token.verifiedContract===!1,S=!_.spender.label&&!_.spender.entity;(v||_.isUnlimited&&S)&&y.push(_)}return{walletAddress:i,chain:o||"default",filters:{limit:s,cursor:l??null},pagination:{cursor:u.cursor??null,pageSize:u.page_size??s,page:u.page??null,hasMore:!!u.cursor},summary:{totalApprovals:h.length,unlimitedApprovals:g,totalUsdAtRisk:m,riskyApprovalCount:y.length},approvals:h,riskyApprovals:y}}};function Rae(t){let e=Nae(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 Nae(t){if(!t)return!1;try{return BigInt(t)>=Oae}catch{return!1}}p();var Uh=class extends oe{constructor(r){super();f(this,"name","get-wallet-defi-positions");f(this,"description",`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 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.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: 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 ct(r)}async run(r,n){let i=fr(r.address,n),o=hr(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 c=l.data||[];return{walletAddress:i,chain:o,positionCount:c.length,positions:c.map(LB)}}let s=(await Promise.all(ii().map(async l=>{let c=await this.service.getWalletDefiPositions({address:i,chain:l});return{chain:l,rows:c.success?c.data||[]:[]}}))).filter(l=>l.rows.length>0).map(l=>({chain:Q(l.chain),positionCount:l.rows.length,positions:l.rows.map(LB)}));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,c)=>l+c.positionCount,0),chains:s}}};function LB(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:Mae(t.position)}}function Mae(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 Lh=class extends oe{constructor(r){super();f(this,"name","get-wallet-defi-protocol-positions");f(this,"description",`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 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.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". 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). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-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:"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-positions 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 ct(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=fr(r.address,n),a=hr(r.chain,n);if(a){let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:a});return c.success?c.data?{walletAddress:o,chain:a,...this.protocolFields(c.data)}:{error:"No data returned for this protocol"}:{error:c.error||"Failed to fetch wallet DeFi protocol positions"}}let l=(await Promise.all(ii().map(async c=>{let u=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:c});return{chain:c,data:u.success?u.data:void 0}}))).flatMap(c=>c.data&&(c.data.positions||[]).length>0?[{chain:Q(c.chain),data:c.data}]:[]).map(c=>({chain:c.chain,...this.protocolFields(c.data)})).sort((c,u)=>u.totalUsdValue-c.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((c,u)=>c+u.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($ae)}}};function $ae(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 Dae(t){try{return(Number(BigInt(t))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return t}}var qh=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 ct(r)}async run(r,n){let i=r.transactionHash;if(!i)return{error:"Transaction hash is required."};let o=Wr(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(u=>!!u.decoded_event).map(u=>({contract:u.address,signature:u.decoded_event.signature,label:u.decoded_event.label,params:u.decoded_event.params})),c=s.logs.map(u=>({address:u.address,decodedEvent:u.decoded_event?{signature:u.decoded_event.signature,label:u.decoded_event.label,params:u.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:Dae(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:c}}};p();p();p();p();p();var qB=new Map;function Uae(t){let e=qB.get(t);if(e)return e;let r=cc({rpcUrl:t});return qB.set(t,r),r}async function jB(t,e,r=[]){let n=await Uae(t).rpc(e,r);if(n===void 0)throw new Error(`RPC ${e}: empty result`);return n}function FB(t,e,r){return jB(t,"eth_call",[{to:e,data:r},"latest"])}async function Lae(t,e,r){let n=Qu(t);if(!n)return null;try{return await FB(n,e,r)}catch{return null}}p();p();p();function ut(t,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${t}`):console.log(`[LEND] ${t}`,JSON.stringify(e,qae)))}function qae(t,e){return typeof e=="bigint"?`${e}n`:e}var jae=6e4,wO=new Map;async function $y(t,e){let r=sl(e),n=r?parseInt(r,16):NaN;if(!r||!Number.isFinite(n))return[];let i=`${t}|${r}`,o=wO.get(i);if(o&&Date.now()-o.at<jae)return o.markets;let a=Fae(t,r,n),s=a.then(l=>l.markets);return wO.set(i,{at:Date.now(),markets:s}),a.then(l=>{l.answered||wO.delete(i)}),s}async function Q0(t,e){return(await $y(t,e)).length>0}async function Fae(t,e,r){try{let n=`${t}/supply/v2?chainId=${r}&limit=100&page=1`;ut("catalog: GET",n);let i=await ve.get(n);if(!i.ok){let a=i.status>=400&&i.status<500;return ut(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:i.status,message:Xe(i)}),{markets:[],answered:a}}let o=(i.data?.data?.items||[]).flatMap(a=>{let s=Bae(a,e);return s?[s]:[]});return ut("catalog: got markets",{chain:e,rawItems:i.data?.data?.items?.length??0,usable:o.length,tokens:o.map(a=>a.token)}),{markets:o,answered:!0}}catch(n){return ut("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:n?.message}),{markets:[],answered:!1}}}function BB(t,e){let r=e.trim().toLowerCase();if(!r)return[];if(Ve(r))return t.filter(i=>i.contract===r||i.token===r);let n=t.filter(i=>i.name.trim().toLowerCase()===r);return n.length>0?n:t.filter(i=>{let o=i.name.trim().toLowerCase(),a=i.protocol.trim().toLowerCase();return o.includes(r)||r.includes(o)||a.includes(r)||r.includes(a)})}function Bae(t,e){if(t?.isDeleted===!0)return null;let r=typeof t?.contract=="string"?t.contract.toLowerCase():"";if(!Ve(r))return null;let n=typeof t?.token=="string"&&Ve(t.token)?t.token.toLowerCase():r,i=Number(t?.rating?.balanceScore),o=t?.type?.trim()||"unknown";return{chain:e,name:t?.name?.trim()||"USDC lending market",protocol:t?.protocolId?.name?.trim()||"Unknown",protocolLabel:Mo(o),protocolUrl:t?.protocolId?.domain?.trim()||null,type:o,contract:r,token:n,platformScore:Number.isFinite(i)?i:null}}function SO(){return ii()}async function eS(t){let e=SO(),r=await Promise.all(e.map(n=>Q0(t,n)));return e.filter((n,i)=>r[i])}async function tS(t,e){let r=_t(e);return r?Q0(t,r):!1}async function zB(t,e){let r=e.map(o=>_t(o)).filter(o=>!!o),n=[...new Set(r)],i=await Promise.all(n.map(o=>Q0(t,o)));return n.filter((o,a)=>i[a])}p();function jh(t){return Z0(t)}var VB=5;async function HB(t,e,r){let n=e.map(b=>Ve(b)?b.toLowerCase():null);if(n.every(b=>b===null))return ut("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let i=W0(t),o;try{ut("discovery: probing 5 accessors per token",{chain:t,tokens:n,psm:i}),o=await ni(t,[...n.flatMap(b=>b?zae(b):[]),...i?IB(i):[]])}catch(b){return ut("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:t,message:b?.message}),e.map(()=>null)}let a=i?o.slice(o.length-OB):[],s=rr(a[0])?.toLowerCase()??null,l=rr(a[1]),c=rr(a[2]),u=s&&l&&c?{susds:s,usds:l,oracle:c}:null;i&&ut("discovery: PSM3 lookup",{psm:i,susds:s,usds:l,oracle:c});let d=0,h=n.map(b=>{if(!b)return null;let v=o.slice(d,d+VB);return d+=VB,ut("discovery: probe answers",{token:b,"POOL()":rr(v[0]),"UNDERLYING_ASSET_ADDRESS()":rr(v[1]),"baseToken()":rr(v[2]),"asset()":rr(v[3]),"vsr()":Gr(v[4])?.toString()??null}),{token:b,slice:v}}),m=new Set;for(let b of h){if(!b)continue;let v=rr(b.slice[0]);v&&rr(b.slice[1])&&m.add(v.toLowerCase())}let g=await Vae(t,[...m]);m.size>0&&ut("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let y=h.flatMap(b=>b?rr(b.slice[0])&&rr(b.slice[1])||rr(b.slice[2])?[]:rr(b.slice[3])?[b.token]:[]:[]),_=await Hae(t,[...new Set(y)],r);return y.length>0&&ut("discovery: Morpho vault lookup",{asked:[...new Set(y)],recognised:[..._.keys()]}),h.map(b=>{if(!b)return null;let{token:v,slice:S}=b,T={chain:t,protocolUrl:null,token:v,platformScore:null};if(u&&v===u.susds)return ut("discovery: classified",{token:v,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...T,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Mo("spark-l2-susds"),protocolUrl:jh("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let C=rr(S[0]);if(C&&rr(S[1])){let I=g.has(C.toLowerCase());return ut("discovery: classified",{token:v,as:I?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:C}),I?{...T,name:"Aave v3",protocol:"AAVE",protocolLabel:Mo("aave-v3"),protocolUrl:jh("aave-v3"),type:"aave-v3",contract:C}:null}if(rr(S[2]))return ut("discovery: classified",{token:v,as:"compound-v3"}),{...T,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Mo("compound-v3"),protocolUrl:jh("compound-v3"),type:"compound-v3",contract:v};if(rr(S[3])){if(_.has(v)){ut("discovery: classified",{token:v,as:"morpho-v2"});let E=_.get(v)||"Morpho V2";return{...T,name:E,protocol:"MORPHO",protocolLabel:Mo("morpho-v2"),protocolUrl:jh("morpho-v2"),type:"morpho-v2",contract:v}}let R=Gr(S[4])!==null;return ut("discovery: classified",{token:v,as:R?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),R?{...T,name:"Spark",protocol:"SPARK",protocolLabel:Mo("spark-ethereum"),protocolUrl:jh("spark-ethereum"),type:"spark-ethereum",contract:v}:{...T,name:"Spark",protocol:"SPARK",protocolLabel:Mo("spark"),protocolUrl:jh("spark"),type:"spark",contract:v}}return ut("discovery: classified",{token:v,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function zae(t){return[{target:t,callData:gt({abi:vh,functionName:"POOL"})},{target:t,callData:gt({abi:vh,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:t,callData:gt({abi:nd,functionName:"baseToken"})},{target:t,callData:gt({abi:pa,functionName:"asset"})},{target:t,callData:gt({abi:wh,functionName:"vsr"})}]}async function Vae(t,e){if(e.length===0)return new Set;try{let r=await ni(t,e.map(n=>({target:n,callData:gt({abi:lO,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,i)=>rr(r[i])!==null))}catch{return new Set}}async function Hae(t,e,r){let n=parseInt(t,16);if(e.length===0||!Number.isFinite(n))return new Map;let i=await Promise.all(e.map(async o=>{try{let a=await ve.post(r,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:o,c:n}}),s=a.ok?a.data?.data?.vaultV2ByAddress:null;return s?[o,s.name?.trim()||""]:null}catch{return null}}));return new Map(i.filter(o=>o!==null))}var Zae=.01;function Gae(t){return t.reduce((e,r)=>r.conditions===null?e+r.apyPercent:e,0)}function Wae(t,e){if(typeof e!="string"||!e.trim())return;let r=e.trim(),n=Ay();n[t]!==r&&Ju({...n,[t]:r})}var Fh=class{constructor(e,r,n){f(this,"coinPoolBaseUrl",e);f(this,"endpoints",r);f(this,"describer",n)}async describeReceiptTokens(e,r,n){let i=Date.now();ut("describeReceiptTokens: START",{chain:e,tokens:r,hasRpcUrl:!!n});let o=sl(e);o&&Wae(o,n);let a=o?Ny(o):null,s=[...new Set(r.filter(Ve).map(h=>h.toLowerCase()))];if(ut("describeReceiptTokens: chain resolved",{hex:o,hasChainInfo:!!a,wanted:s}),!o||!a||s.length===0)return ut("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:o,hasChainInfo:!!a,wantedCount:s.length}),new Map;ut("describeReceiptTokens: on-chain discovery for",s);let l=await HB(o,s,this.endpoints.morphoApiUrl),u=[...new Map(s.flatMap((h,m)=>{let g=l[m];return ut("describeReceiptTokens: discovery result",{token:h,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[h,g]]:[]})).entries()];if(u.length===0)return ut("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-i}),new Map;ut("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([h,m])=>({token:h,type:m.type,contract:m.contract}))});let d=await this.describer.describe(o,a,u.map(([,h])=>h));return ut("describeReceiptTokens: DONE",{ms:Date.now()-i,overviews:d.map(h=>({name:h.name,protocol:h.protocol,asset:h.asset?.symbol,assetDecimals:h.asset?.decimals,currentApyPercent:h.currentApyPercent,baseApyPercent:h.baseApyPercent,rewardApyPercent:h.rewardApyPercent,avgApyPercent:h.avgApyPercent,apyChangePercent:h.apyChangePercent,totalSuppliedUsdc:h.totalSuppliedUsdc,apyHistoryPoints:h.apyHistory?.length??0}))}),new Map(d.map((h,m)=>[u[m][0],h]))}async findMarketByReceiptToken(e,r,n){if(ut("findMarketByReceiptToken: called",{chain:e,receiptToken:r,hasRpcUrl:!!n}),!Ve(r))return ut("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:r}),null;let o=(await this.describeReceiptTokens(e,[r],n)).get(r.toLowerCase())??null;return ut("findMarketByReceiptToken: returning",{found:!!o}),o}async getSupplyPositions(e){if(!Ve(e.address))return[];let r=await zB(this.coinPoolBaseUrl,e.chains);return(await Promise.all(r.map(i=>this.positionsForChain(i,e.address)))).flat().sort((i,o)=>o.suppliedUsdc-i.suppliedUsdc||(o.avgApyPercent??0)-(i.avgApyPercent??0))}async describeResolvedMarkets(e,r){let n=sl(e),i=n?Ny(n):null;return n&&i?this.describer.describe(n,i,r):[]}async positionsForChain(e,r){let n=Ny(e),i=await $y(this.coinPoolBaseUrl,e);if(!n||i.length===0)return[];let o=await this.describer.readBalances(e,r,i);if(o.length===0)return[];let a=await this.describer.describe(e,n,o.map(l=>l.market)),s=await this.describer.convertToUnderlying(e,o,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=s[c];return u<Zae?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Gae(l.rewards))/100}]})}};p();var kO=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Bh=class{constructor(e){f(this,"coinPoolBaseUrl",e)}async listChains(){return eS(this.coinPoolBaseUrl)}async isSupported(e){return tS(this.coinPoolBaseUrl,e)}async getMarkets(e){let r=_t(e);return r?$y(this.coinPoolBaseUrl,r):[]}async findMarket(e,r){let n=await this.getMarkets(e);return BB(n,r)}canSupply(e){return kO.includes(e.type)}async readReceiptToken(e,r){let n=od(r).balanceIsUnderlying;try{let i=await ni(e,[{target:r.token,callData:gt({abi:Zt,functionName:"symbol"})},{target:r.token,callData:gt({abi:Zt,functionName:"decimals"})}]);return{symbol:yy(i[0]),decimals:Vp(i[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};p();p();var Kae={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Yae={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",130:"proto_unichain_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},Jae={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Xae={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function rS(t){let e=ase(t.chain);return(e===null?null:Qae(t,e))??Z0(t.type)??ose(t,e)}function Qae(t,e){switch(t.type){case"morpho-v2":{let r=Kae[e];if(!r||!t.contract)return null;let n=`https://app.morpho.org/${r}/vault/${TO(t.contract)}`,i=rse(t.name);return i?`${n}/${i}`:n}case"aave-v3":{let r=Yae[e],n=ese(t);return!r||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${TO(n)}&marketName=${r}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let r=Jae[e],n=ise(t);return!r||!n?null:`https://app.spark.fi/savings/${r}/${n}`}case"compound-v3":{let r=Xae[e],n=nse(t);return!r||!n?null:`https://app.compound.finance/?market=${n}-${r}`}default:return null}}function ese(t){let e=t.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var tse=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function rse(t){let e=t?.trim().toLowerCase()||"";return!e||tse.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function nse(t){let e=t.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function ise(t){let e=`${t.name||""} ${t.token||""}`.toLowerCase();for(let n of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(e.includes(n))return n;let r=t.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]{2,11}$/.test(r)?t.type==="spark-ethereum"?`sp${r}`:`s${r}`:null}function ose(t,e){let r=t.protocolUrl?.trim();if(!r)return null;let n=/^https?:\/\//i.test(r)?r:`https://${r.replace(/^\/+/,"")}`;try{let i=new URL(n);return e!==null&&i.searchParams.set("chainId",String(e)),t.contract&&i.searchParams.set("contract",TO(t.contract)),i.toString()}catch{return n}}function TO(t){let e=t.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function ase(t){let e=t?.trim();if(!e)return null;let r=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(r)&&r>0?r:null}var sse=8;function lse(t,e,r){if(t.market.type!=="spark-l2-susds")return Gr(e);let n=Gr(e);return n===null||t.tokenDecimals===null?null:kh(t.rawBalance,n,t.tokenDecimals,r)}var nS=class{constructor(e){f(this,"endpoints",e);f(this,"apyLimiter",new PO(sse));f(this,"pantograph",new jr)}async describe(e,r,n){if(n.length===0)return[];ut("describe: START",{chain:e,count:n.length,types:n.map(s=>s.type)});let i=await this.resolveAssets(e,n);ut("describe: assets resolved",i);let[o,a]=await Promise.all([this.readMarketState(e,n,i),Promise.all(n.map((s,l)=>this.apyLimiter.run(()=>this.fetchApy(s,r,i[l]))))]);return ut("describe: on-chain state",o),ut("describe: APY fetched",a.map((s,l)=>({type:n[l].type,rawSamples:s.samples.length,sourceCurrent:s.current}))),n.map((s,l)=>{let{totalSuppliedUsdc:c,liveApyFraction:u}=o[l],d=use(a[l].samples,u??a[l].current,a[l].rewards);return ut("describe: summarised",{market:s.name,type:s.type,liveFrom:u!==null?"on-chain":a[l].current!==null?"api":"none",rawSamples:a[l].samples.length,historyPoints:d.history.length,currentApyPercent:d.currentApyPercent,avgApyPercent:d.avgApyPercent,apyChangePercent:d.apyChangePercent,totalSuppliedUsdc:c,asset:i[l]?.symbol}),{...s,protocolUrl:rS({...s,asset:i[l]}),asset:i[l],totalSuppliedUsdc:c,avgApyPercent:d.avgApyPercent,currentApyPercent:d.currentApyPercent,baseApyPercent:d.baseApyPercent,rewardApyPercent:d.rewardApyPercent,rewards:d.rewards,apyChangePercent:d.apyChangePercent,apyHistory:d.history}})}async readBalances(e,r,n){let i=gt({abi:Zt,functionName:"balanceOf",args:[r]}),o=gt({abi:Zt,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:i},{target:l.token,callData:o}]),s=await ni(e,a);return n.flatMap((l,c)=>{let u=Gr(s[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Vp(s[c*2+1])}]})}async convertToUnderlying(e,r,n){let i=[],o=r.map(s=>{let l=od(s.market).convertToAssetsCall(s.market,s.rawBalance);return l?(i.push(l),i.length-1):-1}),a=await ni(e,i);return r.map((s,l)=>{let c=n[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(o[l]<0)return mc(s.rawBalance,c);let u=lse(s,a[o[l]],c);return u===null?mc(s.rawBalance,s.tokenDecimals??c):mc(u,c)})}async resolveAssets(e,r){let n={address:ad,decimals:NaN,symbol:null,logo:null},i=[],o=r.map(u=>{let d=od(u).underlyingCall(u);return d?(i.push(d),i.length-1):-1}),a;try{let u=i.length>0?await ni(e,i):[];a=o.map(d=>d<0?null:rr(u[d]))}catch{a=r.map(()=>null)}a=a.map((u,d)=>u??r[d]?.assetAddress??null);let s=[...new Set(a.filter(u=>!!u).map(u=>u.toLowerCase()))],[l,c]=await Promise.all([this.readAssetMetadata(e,s),this.fetchAssetLogos(e,s)]);return a.map(u=>{if(!u)return n;let d=u.toLowerCase(),h=l.get(d),m=c.get(d)??null;return h?.decimals!==null&&h?.decimals!==void 0?{address:u,decimals:h.decimals,symbol:h.symbol??null,logo:m}:{address:u,decimals:NaN,symbol:null,logo:m}})}async readAssetMetadata(e,r){let n=new Map;if(r.length===0)return n;let i=gt({abi:Zt,functionName:"decimals"}),o=gt({abi:Zt,functionName:"symbol"});try{let a=await ni(e,r.flatMap(s=>[{target:s,callData:i},{target:s,callData:o}]));r.forEach((s,l)=>{n.set(s,{decimals:Vp(a[l*2]),symbol:yy(a[l*2+1])})})}catch{}return n}async fetchAssetLogos(e,r){let n=new Map;if(r.length===0)return n;try{let i=await this.pantograph.getTokensMetadata(r,e);for(let[o,a]of Object.entries(i)){let s=a.icon_image||a.logo||a.logoURI;s&&n.set(o.toLowerCase(),s)}}catch{}return ut("resolveAssets: logos",{chain:e,requested:r.length,found:n.size}),n}async readMarketState(e,r,n){let i=[],o=r.map((u,d)=>{let h=od(u),m=n[d],g={market:u,protocol:h,asset:m,size:i.length,rate:-1};i.push(h.sizeCall(u,m));let y=h.liveRateCall(u,m);return y&&(g.rate=i.length,i.push(y)),g}),a=await ni(e,i),s=[],l=o.map(u=>{if(u.rate<0)return-1;let d=u.protocol.followUpRateCall(u.market,a[u.rate]);return d?(s.push(d),s.length-1):-1}),c=s.length>0?await ni(e,s):[];return o.map((u,d)=>{let h=u.rate<0?null:a[u.rate],m=l[d]>=0?c[l[d]]:h;return{totalSuppliedUsdc:u.protocol.decodeSize(a[u.size],u.asset),liveApyFraction:m===null?null:u.protocol.decodeLiveRate(m)}})}async fetchApy(e,r,n){try{ut("fetchApy: requesting",{market:e.name,type:e.type,asset:n?.symbol});let i=await od(e).fetchApy(e,r,this.endpoints,n);return ut("fetchApy: got",{market:e.name,samples:i.samples.length,current:i.current}),i}catch(i){return ut("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:i?.message}),{samples:[],current:null,rewards:[]}}}},PO=class{constructor(e){f(this,"limit",e);f(this,"active",0);f(this,"waiting",[])}async run(e){this.active>=this.limit?await new Promise(r=>this.waiting.push(r)):this.active++;try{return await e()}finally{let r=this.waiting.shift();r?r():this.active--}}};function cse(t,e){let r=G0(Date.now()),n=new Map,i=null;for(let s of t)!Number.isFinite(s.timeMs)||!Number.isFinite(s.fraction)||s.fraction<0||G0(s.timeMs)>r||((!i||s.timeMs>i.timeMs)&&(i=s),n.set(s.timeMs,s.fraction));let o=[...n.entries()].sort((s,l)=>s[0]-l[0]).map(([s,l])=>({date:new Date(s).toISOString(),apyPercent:l*100})),a=e??(i&&G0(i.timeMs)===r?i.fraction:null);return{history:o,live:a}}function use(t,e,r=[]){let{history:n,live:i}=cse(t,e),o=i===null?null:i*100,a=r.map(d=>({apyPercent:d.fraction*100,tokenSymbol:d.tokenSymbol,conditions:d.conditions})),s=a.length===0?null:a.reduce((d,h)=>d+h.apyPercent,0),l=o===null?null:o+(s??0),c={baseApyPercent:o,rewardApyPercent:s,rewards:a};if(n.length===0)return{history:n,avgApyPercent:null,currentApyPercent:l,apyChangePercent:null,...c};let u=n.reduce((d,h)=>d+h.apyPercent,0);return{history:n,avgApyPercent:u/n.length,currentApyPercent:l,apyChangePercent:pse(n,o),...c}}var ZB=3600*1e3,dse=ZB/2;function pse(t,e){if(e===null)return null;let r=Date.now()-ZB,n=null,i=Number.POSITIVE_INFINITY;for(let o=t.length-1;o>=0;o--){let a=Math.abs(Date.parse(t[o].date)-r);if(a>i)break;i=a,n=t[o]}return!n||i>dse?null:e-n.apyPercent}function GB(t,e){if(!Number.isFinite(t))return t;let r=10**e,n=Number((t*r).toPrecision(15));return(t<0?-Math.floor(-n):Math.floor(n))/r+0}var $o=class{constructor(e={}){f(this,"read");f(this,"supply");let r=e.coinPoolBaseUrl||"https://api.coinpool.app",n={coinPoolBaseUrl:r,lendingRatesBaseUrl:e.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},i=new nS(n);this.read=new Fh(r,n,i),this.supply=new Bh(r)}async listSupportedChains(){return this.supply.listChains()}async isSupported(e){return this.supply.isSupported(e)}async getMarkets(e){return this.supply.getMarkets(e)}async findMarket(e,r){return this.supply.findMarket(e,r)}canSupply(e){return this.supply.canSupply(e)}async readReceiptToken(e,r){return this.supply.readReceiptToken(e,r)}async describeReceiptTokens(e,r,n){return this.read.describeReceiptTokens(e,r,n)}async findMarketByReceiptToken(e,r,n){return this.read.findMarketByReceiptToken(e,r,n)}async describeResolvedMarkets(e,r){return this.read.describeResolvedMarkets(e,r)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async n=>this.read.describeResolvedMarkets(n,await this.getMarkets(n))))).flat().sort((n,i)=>(i.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};p();var Dy="{market}",YB=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],oS=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],JB="[[LIST]]",XB=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',QB=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function e4(t,e,r){let[n]=hse([t],e,r),[i]=t.canSupply?AO(t,e,r):[];return{name:t.name?.trim()||t.protocol,protocol:t.protocol,protocolUrl:t.protocolUrl,chain:r,apyPercent:t.apyPercent,detailPrompt:n?.prompt??"",detailLabel:n?.label??"",supplyPrompt:i?.prompt??"",supplyLabel:i?.label??""}}function hse(t,e,r){return t4(t,{labelTemplate:iS(e.detail_button_label),promptTemplate:iS(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Dy}`,...r===void 0?{}:{chainName:r}})}function AO(t,e,r){return t4([t],{labelTemplate:iS(e.supply_button_label),promptTemplate:iS(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Dy}`,promptFallback:`supply to ${Dy}`,...r===void 0?{}:{chainName:r},max:1})}function t4(t,e){let r=typeof e.chainName=="string"?e.chainName.trim():"",n=[],i=new Set;for(let o of t){if(e.max!==void 0&&n.length>=e.max)break;let a=o.name?.trim();!a||i.has(a.toLowerCase())||(i.add(a.toLowerCase()),n.push({label:WB(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:WB(fse(e.promptTemplate),a,e.promptFallback)+mse(o.contract,r)}))}return n}function fse(t){let[e,r]=[t[0],t[1]];return e===void 0||e===e.toLowerCase()||r!==void 0&&r!==r.toLowerCase()?t:e.toLowerCase()+t.slice(1)}function iS(t){return typeof t=="string"?t:""}function mse(t,e){let r=t?.trim();if(!r||!/^0x[a-fA-F0-9]{40}$/.test(r))return"";let n=e?.trim();return n?` (market: ${r} - ${n})`:` (market: ${r})`}function WB(t,e,r,n=!0){let o=t&&(!n||t.includes(Dy))?t:r;return gse(o).split(Dy).join(e).replace(/\s+/g," ").trim()}var KB="{chain}";function gse(t){if(!t.includes(KB))return t;let e=KB.replace(/[{}]/g,"\\$&");return t.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}p();var aS=[{id:"aave-v3",label:"Aave v3",types:["aave-v3"],aliases:["aave","aavev3","aave3","ave"]},{id:"compound-v3",label:"Compound v3",types:["compound-v3"],aliases:["compound","compoundv3","compound3","comet","comp"]},{id:"spark-any",label:"Spark",types:["spark","spark-ethereum"],aliases:["spark","sparkfi","sparklend","sparkprotocol"]},{id:"morpho-v2",label:"Morpho",types:["morpho-v2"],aliases:["morpho","morphov2","morpho2","morphoblue","metamorpho"]}],CO=aS.map(t=>t.label),EO={euler:"Euler",venus:"Venus",radiant:"Radiant",benqi:"Benqi",qi:"Benqi",fluid:"Fluid",instadapp:"Fluid",silo:"Silo",moonwell:"Moonwell",sonne:"Sonne",granary:"Granary",ironbank:"Iron Bank",cream:"Cream",maker:"Maker",makerdao:"Maker",sky:"Sky",justlend:"JustLend",kamino:"Kamino",solend:"Solend",marginfi:"marginfi",save:"Save",curve:"Curve",yearn:"Yearn",convex:"Convex",pendle:"Pendle",ethena:"Ethena",gearbox:"Gearbox",notional:"Notional",exactly:"Exactly",seamless:"Seamless",zerolend:"ZeroLend",dforce:"dForce",tectonic:"Tectonic",liqee:"Liqee"};function r4(t){let e=typeof t=="string"?t.trim():"";if(!e)return{kind:"none"};let r=vse(e);if(!r)return{kind:"none"};let n=yse(r);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let i=bse(r);return i?{kind:"unsupported",label:i,requested:e}:{kind:"unknown",requested:e}}function yse(t){let e=aS.filter(r=>r.aliases.includes(t));if(e.length===1)return e[0];if(e.length>1)return null;if(t.length>=3){let r=aS.filter(n=>n.aliases.some(i=>i.includes(t)||t.includes(i)));if(r.length===1)return r[0];if(r.length>1)return null}return _se(t)}function _se(t){let e=null,r=!1;for(let n of aS)for(let i of n.aliases){let o=n4(i);if(o===0||Math.abs(i.length-t.length)>o)continue;let a=i4(t,i,o);a>o||(!e||a<e.distance?(e={spec:n,distance:a},r=!1):a===e.distance&&n!==e.spec&&(r=!0))}return e&&!r?e.spec:null}function n4(t){return t.length<=4?0:t.length<=9?2:3}function bse(t){let e=EO[t];if(e)return e;if(t.length>=4){let i=new Set(Object.entries(EO).filter(([o])=>o.length>=4&&(o.includes(t)||t.includes(o))).map(([,o])=>o));if(i.size===1)return[...i][0];if(i.size>1)return null}let r=null,n=!1;for(let[i,o]of Object.entries(EO)){let a=n4(i);if(a===0||Math.abs(i.length-t.length)>a)continue;let s=i4(t,i,a);s>a||(!r||s<r.distance?(r={label:o,distance:s},n=!1):s===r.distance&&o!==r.label&&(n=!0))}return r&&!n?r.label:null}function vse(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function i4(t,e,r){if(t===e)return 0;if(!t.length)return e.length;if(!e.length)return t.length;let n=new Array(e.length+1),i=Array.from({length:e.length+1},(a,s)=>s),o=new Array(e.length+1);for(let a=1;a<=t.length;a++){o[0]=a;let s=o[0];for(let c=1;c<=e.length;c++){let u=i[c-1]+(t[a-1]===e[c-1]?0:1),d=Math.min(o[c-1]+1,i[c]+1,u);a>1&&c>1&&t[a-1]===e[c-2]&&t[a-2]===e[c-1]&&(d=Math.min(d,n[c-2]+1)),o[c]=d,d<s&&(s=d)}if(s>r)return r+1;let l=n;n=i,i=o,o=l}return i[e.length]}p();function Pr(t,e){return t==null?null:GB(t,e)}var Dn=2,gc=2;function sS(t){let e=Pr(t.currentApyPercent,Dn),r=t.rewards.map(o=>({apyPercent:Pr(o.apyPercent,Dn)??0,tokenSymbol:o.tokenSymbol,conditions:o.conditions})),n=t.rewardApyPercent===null?null:r.reduce((o,a)=>o+Math.round(a.apyPercent*100),0)/100;if(n===null||e===null)return{currentApyPercent:e,rewardApyPercent:n,rewards:r,baseApyPercent:Pr(t.baseApyPercent,Dn)};let i=Math.round(e*100)-Math.round(n*100);return{currentApyPercent:e,rewardApyPercent:n,rewards:r,baseApyPercent:i/100}}var wse=["apy","score","size"],o4=3,a4=40,zh=class extends oe{constructor(r){super();f(this,"name","get-lending-markets");f(this,"kind","ui");f(this,"description",'BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${CO.join(", ")}. Set it whenever the user names a protocol \u2014 "supply aave", "morpho vaults", "l\xE3i su\u1EA5t b\xEAn Compound" \u2014 and pass what they wrote, VERBATIM. Do NOT correct their spelling, do NOT translate it, and do NOT map it to a name from the supported list yourself: misspellings are resolved for you, and a protocol that is NOT supported is reported back so you can tell the user. Pass it even when you believe the protocol is unsupported \u2014 that is how the user gets told. OMIT it when the user named no protocol; never guess one to narrow a list they asked for in full.`,required:!1},{name:"limit",type:"number",description:`How many markets to return, 1-${a4}. Default ${o4} \u2014 the top markets by the chosen ranking, which answers "where can I earn on my USDC" on its own. Raise it ONLY when the user asks for more than that, for the full list, or to compare broadly; lower it when they want a shorter shortlist.`,required:!1},{name:"sort",type:"string",description:'Ranking: "apy" (default, highest live protocol APY first), "score" (safest / best-rated first \u2014 use when the user asks for safe, reliable or trusted markets), or "size" (largest market first \u2014 use when the user asks for the biggest or most liquid markets).',required:!1},...YB,...oS]);f(this,"service");this.service=new $o(r)}async run(r,n){let i=hr(r.chain,void 0),o=i?null:_t(n?.chain),a=i??o,s=a?await this.service.isSupported(a):!1,l=s?[]:await this.service.listSupportedChains();if(a&&!s)return{_instructions:`There are no lending markets on ${Q(a)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:Q(a),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:l.map(S=>Q(S))};let c=r4(r.protocol);if(c.kind==="unsupported"||c.kind==="unknown")return this.unsupportedProtocol(c);let u=a?[a]:l,d=kse(r.sort),h=Tse(r.limit),m=await this.service.getMarketOverviews({chains:u}),g=c.kind==="supported"?m.filter(S=>c.matches(S)):m;if(c.kind==="supported"&&g.length===0&&m.length>0)return{_instructions:`There are no ${c.label} lending markets on ${a?Q(a):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${c.label} market. Do NOT mention tool names.`,requestedProtocol:c.label,chain:a?Q(a):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(m.map(S=>S.protocol))]};let y=[...g].sort(Sse[d]).slice(0,h),_=y.map(S=>e4({name:S.name,contract:S.contract,protocol:S.protocol,protocolUrl:S.protocolUrl,apyPercent:Pr(S.currentApyPercent,Dn),canSupply:this.service.supply.canSupply(S)},r,Q(S.chain))),v={component:"LendingMarketList",props:{chain:a?Q(a):"all",multiChain:new Set(_.map(S=>S.chain)).size>1,markets:_}};return{..._.length>0?{ui:v}:{},_instructions:this.instructions(y,d,_.length>0,c.kind==="supported"?c.label:null),chain:a?Q(a):"all",chainsQueried:u.map(S=>Q(S)),...c.kind==="supported"?{protocolFilter:c.label}:{},sortedBy:d,marketCount:_.length,totalMarketsAvailable:g.length,marketNames:_.map(S=>S.name)}}unsupportedProtocol(r){let n=r.kind==="unsupported",i=n?r.label:`"${r.requested}"`;return{_instructions:`The user asked about ${i}, which has no lending markets here. In their language: tell them plainly that ${i} is ${n?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${i} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:n?r.label:r.requested,protocolSupported:!1,supportedProtocols:[...CO],marketCount:0,marketNames:[]}}instructions(r,n,i=!1,o=null){if(r.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let a={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[n];return[o?`These are the ${o} lending markets the user can supply to, ${a}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${a}.`,`Write your reply in TWO parts separated by a line containing exactly ${JB} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",n==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(r.map(s=>s.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${Q(r[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${a} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",i?XB:""].filter(Boolean).join(" ")}},Sse={apy:(t,e)=>(e.currentApyPercent??-1)-(t.currentApyPercent??-1),score:(t,e)=>(e.platformScore??-1)-(t.platformScore??-1),size:(t,e)=>(e.totalSuppliedUsdc??-1)-(t.totalSuppliedUsdc??-1)};function kse(t){let e=typeof t=="string"?t.trim().toLowerCase():"";return wse.includes(e)?e:"apy"}function Tse(t){let e=typeof t=="number"?t:Number(t);return!Number.isFinite(e)||e<1?o4:Math.min(Math.floor(e),a4)}p();p();function s4(t){let{currentApyPercent:e,avgApyPercent:r,totalSuppliedUsdc:n,rewardApyPercent:i,baseApyPercent:o,platformScore:a}=t;return t.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:i!==null&&o!==null&&i>o*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:e!==null&&r!==null&&r>0&&e>r*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:n!==null&&n<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&n!==null&&n>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:n!==null&&n>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}p();function lS(t){let e=typeof t=="string"?t.trim():"",r=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(e);if(r)return r[1];let n=/0x[a-fA-F0-9]{40}/.exec(e);return n&&n[0]!==e?n[0]:e}var Vh=class extends oe{constructor(r){super();f(this,"name","get-lending-market-detail");f(this,"category","blockchain-data");f(this,"description",'Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.');f(this,"parameters",[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...oS]);f(this,"service");this.service=new $o(r)}async run(r,n){let o=hr(r.chain,void 0)??_t(n?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let h=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:Q(o),chainsWithLendingMarkets:h.map(m=>Q(m)),_instructions:`There are no lending markets on ${Q(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let a=lS(r.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let s=await this.service.findMarket(o,a);if(s.length===0)return{error:"market_not_found",market:a,chain:Q(o),_instructions:`No lending market matching "${a}" exists on ${Q(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(s.length>1)return{error:"ambiguous_market",market:a,chain:Q(o),candidates:s.map(h=>({marketName:h.name,protocol:h.protocol})),_instructions:`"${a}" matches ${s.length} different markets on ${Q(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+a+`" and chain for ${Q(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let l=s[0],c=await this.describeOne(o,l);if(!c)return{error:"market_unavailable",marketName:l.name,chain:Q(o),_instructions:`${l.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let u=this.service.supply.canSupply(l),d=u?AO({name:l.name,contract:l.contract},r,Q(o)):[];return{_instructions:this.instructions(c,d.length>0,u),...d.length>0?{actionButtons:d}:{},marketName:c.name,protocol:c.protocolLabel??c.protocol,protocolUrl:c.protocolUrl,chain:Q(c.chain),suppliedAssetSymbol:c.asset.symbol,totalSuppliedUsdc:Pr(c.totalSuppliedUsdc,gc),...sS(c),avgApyPercent:Pr(c.avgApyPercent,Dn),apyChangePercent:Pr(c.apyChangePercent,Dn),platformScore:c.platformScore,supplySupported:u}}async describeOne(r,n){try{let[i]=await this.service.describeResolvedMarkets(r,[n]);return i??null}catch{return null}}instructions(r,n,i){let o=s4(r);return[`This is the full picture of ONE lending market, ${r.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',i?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",n?QB:""].filter(Boolean).join(" ")}};p();var Hh=class extends oe{constructor(r){super();f(this,"name","get-wallet-lending-positions");f(this,"description",'Get a wallet\'s own LENDING / SUPPLY (earn, deposit, savings) positions in the curated lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much it has supplied there, the AVERAGE supply APY over the last week (plus the live rate and the day-over-day change), the estimated yearly yield on that balance, and the market total supplied. Balances are read on-chain, so they match the app. Use for questions like: "Which protocols am I supplying on?", "Show my lending positions", "How much am I earning on my USDC?", "What APY am I getting?", "Where is my USDC deposited?", "My Aave / Compound / Spark / Morpho supply", "what am I earning on Aave", "my savings positions". This is the PREFERRED tool for any "what am I earning / supplying / depositing" question, even when the user names a protocol ("my Aave v3 supply", "my Spark deposit") \u2014 it is the only source of the 7-day average APY, the estimated yearly yield and the platform safety score. Each position reports its OWN asset, which is usually USDC but need not be \u2014 never assume the amounts are dollars without checking `suppliedAssetSymbol`. Chains and markets come from the live catalogue, so do not rule a chain out from memory: call the tool and let it answer. For protocols outside Aave v3 / Compound v3 / Spark / Morpho (Aave v2, MakerDAO\u2026), or when this tool reports nothing but the user insists they have a deposit, fall back to get-wallet-defi-positions. Do NOT use for: markets the wallet has NOT supplied to yet \u2014 where to deposit, best available APY, "promising lending" \u2192 get-lending-markets; the BORROW side of these same protocols, plus LP / staking \u2192 get-wallet-defi-positions (or get-wallet-defi-protocol-positions for one named protocol); plain token 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 to scope to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry lending markets is resolved at call time, so do NOT filter the request against a list you remember. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 positions are then read on the connected wallet's own chain.`,required:!1}]);f(this,"service");this.service=new $o(r)}async run(r,n){let i=fr(r.address,n);if(!Ve(i))return{error:`"${i}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=hr(r.chain,n),a=o?await this.service.isSupported(o):!1,s=a?[]:await this.service.listSupportedChains();if(o&&!a)return{_instructions:`There are no lending markets on ${Q(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:i,chain:Q(o),positionCount:0,positions:[],chainsWithLendingMarkets:s.map(u=>Q(u))};let l=o?[o]:s,c=await this.service.getSupplyPositions({address:i,chains:l});return{_instructions:this.instructions(c),walletAddress:i,chain:o?Q(o):"all",chainsQueried:l.map(u=>Q(u)),positionCount:c.length,totals:Pse(c),positions:c.map(u=>({marketName:u.name,protocol:u.protocol,protocolUrl:u.protocolUrl,chain:Q(u.chain),suppliedUsdc:Pr(u.suppliedUsdc,gc),suppliedAssetSymbol:u.asset.symbol,avgApyPercent:Pr(u.avgApyPercent,Dn),...sS(u),apyChangePercent:Pr(u.apyChangePercent,Dn),estimatedAnnualYieldUsdc:Pr(u.estimatedAnnualYieldUsdc,gc),marketTotalSuppliedUsdc:Pr(u.totalSuppliedUsdc,gc),apyHistory:u.apyHistory.map(d=>({...d,apyPercent:Pr(d.apyPercent,Dn)})),platformScore:u.platformScore}))}}instructions(r){return r.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(r.map(i=>i.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Pse(t){if(new Set(t.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let n=t.reduce((a,s)=>a+s.suppliedUsdc,0),i=t.filter(a=>a.avgApyPercent!==null),o=i.reduce((a,s)=>a+s.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:t[0]?.asset.symbol??null,suppliedUsdc:Pr(n,gc),estimatedAnnualYieldUsdc:Pr(t.reduce((a,s)=>a+(s.estimatedAnnualYieldUsdc??0),0),gc),weightedAvgApyPercent:Pr(o>0?i.reduce((a,s)=>a+s.suppliedUsdc*s.avgApyPercent,0)/o:null,Dn)}}p();var Zh=class extends oe{constructor(r){super();f(this,"name","open-supply-usdc-form");f(this,"kind","ui");f(this,"category","lending-action");f(this,"description",'Open the SUPPLY form so the user can DEPOSIT into a specific lending market and start earning yield. This is the tool for a supply COMMAND: the user names a market and tells you to act on it, in any wording and any language \u2014 "supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare "Supply Aave", or a tapped "Supply \u2026" button. A supply verb plus a market name is already a complete command; terseness is not ambiguity, and the words the user left out are supplied by context rather than looked up. Each market deposits its OWN asset (usually USDC), resolved from the market itself \u2014 so a message that names no asset is still this tool: resolve the market from whatever the user did name. An amount is optional. Pass `market` \u2014 the market name or protocol exactly as it was shown to them (e.g. "Aave v3 USDC", "Spark"), and `amount` ONLY when they named one. Supports Aave v3, Compound v3, Spark and Morpho vaults, on whichever chains currently carry them \u2014 that set is resolved at call time, so never refuse a chain from memory. PRECONDITION: a connected wallet. The boundary is command vs question: use this to ACT on one market; to LIST or compare markets \u2192 get-lending-markets; for what the wallet already supplies \u2192 get-wallet-lending-positions.');f(this,"parameters",[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}]);f(this,"service");f(this,"moralis");this.service=new $o(r),this.moralis=new ct(r?.moralis)}async run(r,n){let i=n?.walletAddress;if(!i)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let a=hr(r.chain,void 0)??_t(n?.chain);if(!a)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};if(!await this.service.isSupported(a)){let v=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:Q(a),chainsWithLendingMarkets:v.map(S=>Q(S)),_instructions:`There are no lending markets on ${Q(a)}, so nothing can be supplied there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=lS(r.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let l=await this.service.findMarket(a,s);if(l.length===0)return{error:"market_not_found",market:s,chain:Q(a),_instructions:`No lending market matching "${s}" exists on ${Q(a)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(l.length>1)return{error:"ambiguous_market",market:s,chain:Q(a),candidates:l.map(v=>({marketName:v.name,protocol:v.protocol})),_instructions:`"${s}" matches ${l.length} different markets on ${Q(a)}, so the supply cannot target one yet. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${Q(a)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let c=l[0];if(!this.service.supply.canSupply(c))return{error:"unsupported_protocol",marketName:c.name,protocol:c.protocol,_instructions:`Supplying to ${c.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let u=await this.describeOne(a,c),d=Ase(u);if(!d)return{error:"asset_unresolved",marketName:c.name,chain:Q(a),_instructions:`The asset ${c.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[h,m]=await Promise.all([this.assetBalance(i,a,d.address),this.service.readReceiptToken(a,c)]);if(h&&td(h.amount,"0")<=0)return{error:"no_asset_balance",marketName:c.name,chain:Q(a),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${c.name} on ${Q(a)}. In the user's language, tell them plainly that they have no ${d.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let g=Ese(r.amount),y=g?uc(g,d.decimals):null;if(y&&h&&td(y,h.amount)>0)return{error:"insufficient_asset_balance",marketName:c.name,chain:Q(a),assetSymbol:d.symbol,requestedAmount:g,assetBalance:h.amount,_instructions:`The user wants to supply ${g} ${d.symbol} to ${c.name}, but they only hold ${h.amount} ${d.symbol} on ${Q(a)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${g} ${d.symbol} exceeds their balance of ${h.amount} ${d.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let _={action:"supply_usdc",chainId:a,chainName:Q(a),walletAddress:i,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:u?.protocolUrl??rS(c),contract:c.contract,token:c.token,apyPercent:u?.currentApyPercent??u?.avgApyPercent??null,receiptToken:m},asset:d,...y?{prefillAmount:y}:{},...h?{spendable:h.amount}:{},...h?.usd?{spendableUsd:h.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:_},marketName:c.name,protocol:c.protocol,chain:Q(a),apyPercent:Pr(_.market.apyPercent,Dn),assetSymbol:d.symbol,assetBalance:h?.amount??null,_instructions:this.instructions(c,d.symbol)}}async describeOne(r,n){try{let[i]=await this.service.describeResolvedMarkets(r,[n]);return i??null}catch{return null}}async assetBalance(r,n,i){try{let o=await this.moralis.getWalletTokenBalances({address:r,chain:n,tokenAddresses:[i]});if(!o.success)return null;let a=(o.data?.result??[]).find(l=>(l.token_address||"").toLowerCase()===i.toLowerCase());if(!a?.balance_formatted)return{amount:"0",usd:null};let s=typeof a.usd_value=="number"?String(a.usd_value):null;return{amount:String(a.balance_formatted),usd:s}}catch{return null}}instructions(r,n){return[`The supply action for ${r.name} is ready.`,`In the user's language, invite them to enter the amount of ${n} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${n}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function Ase(t){let e=t?.asset;return!e?.address||e.address===ad||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Ese(t){let e=typeof t=="string"?t.trim():typeof t=="number"?String(t):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}p();p();p();var cS="https://ipfs.pantograph.app/ipfs/",l4=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function sd(t){let e=t?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let r=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return r?`${cS}${r[1]}`:l4.test(e)?`${cS}${e}`:null}function c4(t){let e=t?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let r=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return r?`${cS}${r[1]}`:l4.test(e)?`${cS}${e}`:null}function u4(t){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(t)}function xO(t){if(!t||typeof t!="object")return;let e=t,r=e.image??e.image_url??e.imageUrl;return typeof r=="string"&&r.trim()?r.trim():void 0}function Cse(t){if(typeof atob=="function"){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder().decode(r)}if(typeof Buffer<"u")return Buffer.from(t,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function xse(t){let e=t.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let r=e[1]??"",n=e[2]??"";try{let i=/;base64/i.test(r)?Cse(n):decodeURIComponent(n);return JSON.parse(i)}catch{try{return JSON.parse(n)}catch{return null}}}function d4(t){let e=t?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let r=xse(e);return r?sd(xO(r)):null}p();var Ise=12,Ose=6e3;async function Rse(t,e,r){let n=new Array(t.length),i=0,o=new Array(Math.max(1,Math.min(e,t.length))).fill(0).map(async()=>{for(;i<t.length;){let a=i++;n[a]=await r(t[a],a)}});return await Promise.all(o),n}async function Nse(t,e){try{let r=await ve.get(t,{timeout:e});if(!r.ok)return null;let n=r.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function Mse(t,e){let r=t?.trim();if(!r)return null;if(/^data:/i.test(r))return d4(r);let n=c4(r);if(!n)return null;if(u4(n))return n;let i=await Nse(n,e);if(i){let o=sd(xO(i));if(o)return o}return null}async function uS(t,e,r){if(e.length===0)return[];let n=r?.concurrency??Ise,i=r?.timeoutMs??Ose,o=await aB(t,e,r?.rpcUrl);return Rse(o,n,a=>Mse(a,i))}var p4=100,$se=100,Gh="{name}",h4="{chain}",Wh=class extends oe{constructor(r){super();f(this,"name","get-wallet-nfts");f(this,"description",`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`);f(this,"category","nft");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 (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). 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, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}]);f(this,"service");this.service=new ct(r)}async run(r,n){let i=fr(r.address,n),o=hr(r.chain,n),a=o?[o]:ii(),s=Fse(r.contract_address),l=g4(r.collection_name);return s||l?this.listNfts({address:i,chains:a,singleChain:!!o,contract:s,collectionName:l}):this.listCollections({address:i,chains:a,singleChain:!!o,args:r})}async listCollections(r){let{address:n,chains:i,singleChain:o,args:a}=r,s=await Promise.all(i.map(async u=>{let d=await this.service.getWalletNftCollections({address:n,chain:u,limit:p4});return{chain:u,rows:d.success?f4(d.data?.result??[]):[],ok:d.success}}));if(o&&!s[0].ok)return{error:"Failed to fetch wallet NFT collections"};let l=s.flatMap(u=>u.rows.map(d=>({name:Use(d),contractAddress:d.token_address,chain:Q(u.chain),nftCount:d.count??null})));if(l.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:n,collectionCount:0,collections:[]};let c=qse(l,a);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:n,collectionCount:l.length,collections:l,...c.length>0?{actionButtons:c}:{}}}async listNfts(r){let{address:n,chains:i,singleChain:o,contract:a,collectionName:s}=r,l=await Promise.all(i.map(async g=>{let y=await this.service.getWalletNFTs({address:n,chain:g,limit:p4,...a?{tokenAddresses:[a]}:{}});return{chain:g,rows:y.success?f4(y.data?.result??[]):[],ok:y.success}}));if(o&&!l[0].ok)return{error:"Failed to fetch wallet NFTs"};let c=l.flatMap(g=>g.rows.filter(y=>Dse(y,{contract:a,collectionName:s})).map(y=>({chain:g.chain,row:y})));if(c.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${s??a??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let u=c[0].row.name?.trim()||s||c[0].row.token_address,d=await this.resolveOnchainImages(c),h=c.map(({chain:g,row:y},_)=>{let b=Lse(y);return{name:b.name,tokenId:b.tokenId,contractAddress:b.contractAddress,image:d[_]??b.image,chain:Q(g)}});return{ui:{component:"WalletNftList",props:{walletAddress:n,collectionName:u,nfts:h}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:n,collectionName:u,nftCount:c.length}}async resolveOnchainImages(r){let n=new Array(r.length).fill(null),i=new Map;r.forEach((o,a)=>{let s=i.get(o.chain)??[];s.push(a),i.set(o.chain,s)});try{await Promise.all([...i.entries()].map(async([o,a])=>{let s=a.map(c=>({contract:r[c].row.token_address,tokenId:r[c].row.token_id})),l=await uS(o,s);a.forEach((c,u)=>{n[c]=l[u]??null})}))}catch{}return n}};function f4(t){return t.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Dse(t,e){if(e.contract)return t.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let r=e.collectionName.toLowerCase();return(t.name??"").toLowerCase().includes(r)}return!1}function Use(t){let e=t.name?.trim();if(e)return e;let r=t.token_address??"";return r.length>10?`${r.slice(0,6)}\u2026${r.slice(-4)}`:r}function Lse(t){return{name:t.normalized_metadata?.name||t.name||`#${t.token_id}`,tokenId:t.token_id,contractAddress:t.token_address,image:sd(t.normalized_metadata?.image||t.media?.original_media_url)}}function qse(t,e){let r=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",i=[];for(let o of t){if(i.length>=$se)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",s=a?`show my ${Gh} NFTs on ${h4}`:`show my ${Gh} NFTs`,l=m4(n,{[Gh]:o.name,[h4]:a},s);a&&!l.includes(a)&&(l=`${l} (${a})`),i.push({label:jse(r,o.name,Gh),prompt:`${l} (${o.contractAddress})`})}return i}function m4(t,e,r){let n=t&&t.includes(Gh)?t:r;for(let[i,o]of Object.entries(e))n=n.split(i).join(o);return n.replace(/\s+/g," ").trim()}function jse(t,e,r){return m4(t,{[Gh]:e},r)}function g4(t){if(typeof t!="string")return;let e=t.trim();return e||void 0}function Fse(t){let e=g4(t);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}p();p();var Bse="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.",ga=class extends oe{constructor(r){super();f(this,"kind","data");f(this,"category","nft");f(this,"llm");this.llm=new Mr(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:Bse,timestamp:n},{role:"user",content:r,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Kh=class extends ga{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",ga.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 Yh=class extends ga{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",ga.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 IO={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"},OO="amazon.com";function zse(t){return t?t.trim().toLowerCase().split(/[-_]/)[0]:""}function RO(t){let e=zse(t);return IO[e]??OO}function dS(t){return`https://${RO(t)}/s?k=NFC%20Tag`}p();function pS(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 Vse=720*60*1e3,y4=new Map,_4=3;function Hse(t){return[`A user in country "${t}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${_4} 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 Zse(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 c=l.trim().toLowerCase();if(!o.has(c)&&(o.add(c),i.push({label:s.trim(),url:l.trim()}),i.length>=_4))break}return i}async function NO(t,e){let r=pS(t);if(!r||!e)return null;let n=y4.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:Hse(r),timestamp:i}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=Zse(a.text);if(s.length)return y4.set(r,{links:s,expires:Date.now()+Vse}),s}catch{}return null}async function Jh(t){let e=await NO(t.country,t.llm);return e&&e.length?e:[{label:"Amazon",url:dS(t.language)}]}function Gse(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(`
|
|
473
|
+
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?Q(i):"all",timeFrame:a??null,count:u.length,tokens:u}}};p();p();var Ih=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 ct(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=fr(r.address,n),o=hr(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=ii(),s=await Promise.all(a.map(async l=>{let c=await this.service.getWalletTokenBalances({address:i,chain:l,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:l,tokens:c.success?c.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((c,u)=>c+(u.usd_value||0),0),l=a.tokens.slice().sort((c,u)=>(u.usd_value||0)-(c.usd_value||0));return{chain:Q(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 Oh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=Wr(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,c=typeof r.toBlock=="number"?r.toBlock:typeof r.toBlock=="string"&&r.toBlock?Number(r.toBlock):void 0,u=Number.isFinite(l)?l:void 0,d=Number.isFinite(c)?c: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,v=Number.isFinite(b)&&b>0?b:10,S=await this.service.getWalletHistory({address:i,chain:o,limit:v,fromDate:a,toDate:s,fromBlock:u,toBlock:d,cursor:h,order:g,includeInternalTransactions:y,nftMetadata:_});if(!S.success)return{error:S.error||"Failed to fetch wallet history"};let C=(S.data?.result||[]).map(I=>{let R=yB(o,I.hash);return R?{...I,explorerUrl:R}:I});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:S.data?.cursor??null,hasMore:!!S.data?.cursor},transactionCount:C.length,transactions:C}}};p();function Eae(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 Rh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=Wr(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,c=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,u=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,v=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(x=>typeof x=="string"&&!!x).map(x=>x.trim()):void 0,S,T;if(b){let x=await this.resolveContractAddressBySymbol(b,i,o);x&&(v=[x.address],S=x.symbol,T=x.name)}let C=await this.service.getWalletTokenTransfers({address:i,chain:o,contractAddresses:v,limit:s,fromDate:l,toDate:c,fromBlock:u,toBlock:d,cursor:h,order:g});if(!C.success)return{error:C.error||"Failed to fetch token transfers"};let I=i.toLowerCase(),E=(C.data?.result||[]).map(x=>{let N=x.from_address.toLowerCase()===I,L=N?"send":"receive",F=N?x.to_address:x.from_address,W=N?x.to_address_label??void 0:x.from_address_label??void 0,X=N?x.to_address_entity??void 0:x.from_address_entity??void 0;return{...x,direction:L,amount_formatted:Eae(x),counterparty:F,counterparty_label:W,counterparty_entity:X}}),U=_==="all"?E:E.filter(x=>x.direction===_);if(b&&!v){let x=b.toLowerCase();U=U.filter(N=>(N.token_symbol??"").toLowerCase()===x)}let D=this.buildCounterparties(U);return{walletAddress:i,chain:o||"default",resolvedToken:S?{symbol:S,name:T,contractAddress:v?.[0]}:null,filters:{tokenSymbol:b||null,contractAddresses:v||null,direction:_,limit:s,order:g,fromDate:l||null,toDate:c||null,fromBlock:u??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:D}}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(c=>(c.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 c=s.data.find(u=>(u.symbol??"").toLowerCase()===o)??s.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.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(),c=parseFloat(a.amount_formatted)||0,u=s.get(l);u?(u.total+=c,u.count+=1,!u.label&&a.counterparty_label&&(u.label=a.counterparty_label),!u.entity&&a.counterparty_entity&&(u.entity=a.counterparty_entity),a.block_timestamp<u.first&&(u.first=a.block_timestamp),a.block_timestamp>u.last&&(u.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,total:c,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 Nh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=Wr(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,c=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,u=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",v=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(U=>typeof U=="string"&&!!U).map(U=>U.trim()):void 0,S=await this.service.getWalletNftTransfers({address:i,chain:o,contractAddresses:v,limit:s,fromDate:l,toDate:c,fromBlock:u,toBlock:d,cursor:h,order:g,includePrices:y});if(!S.success)return{error:S.error||"Failed to fetch NFT transfers"};let T=i.toLowerCase(),I=(S.data?.result||[]).map(U=>{let D=U.from_address.toLowerCase()===T,x=D?"send":"receive",N=D?U.to_address:U.from_address,L=D?U.to_address_label??void 0:U.from_address_label??void 0,F=D?U.to_address_entity??void 0:U.from_address_entity??void 0;return{...U,direction:x,counterparty:N,counterparty_label:L,counterparty_entity:F}}),R=b==="all"?I:I.filter(U=>U.direction===b),E=this.buildCounterparties(R);return{walletAddress:i,chain:o||"default",filters:{contractAddresses:v||null,direction:b,limit:s,order:g,fromDate:l||null,toDate:c||null,fromBlock:u??null,toBlock:d??null,includePrices:y??null},pagination:{cursor:S.data?.cursor??null,pageSize:S.data?.page_size??s,page:S.data?.page??null,hasMore:!!S.data?.cursor},transferCount:R.length,transfers:R,counterparties:E}}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(),c=a.token_name??a.token_address,u=s.get(l);u?(u.tokenIds.add(a.token_id),u.collections.add(c),u.count+=1,!u.label&&a.counterparty_label&&(u.label=a.counterparty_label),!u.entity&&a.counterparty_entity&&(u.entity=a.counterparty_entity),a.block_timestamp<u.first&&(u.first=a.block_timestamp),a.block_timestamp>u.last&&(u.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,tokenIds:new Set([a.token_id]),collections:new Set([c]),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 Cae=["all","7","30","60","90"],Mh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=hr(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=Cae.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 c=(await Promise.all(ii().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}]:[]),u=c.map(_=>({chain:Q(_.chain),summary:this.mapSummary(_.data)})),d=c.reduce((_,b)=>_+Number(b.data.total_realized_profit_usd||0),0),h=c.reduce((_,b)=>_+Number(b.data.total_bought_volume_usd||0),0),m=c.reduce((_,b)=>_+Number(b.data.total_sold_volume_usd||0),0),g=c.reduce((_,b)=>_+Number(b.data.total_trade_volume||0),0),y={totalCountOfTrades:c.reduce((_,b)=>_+b.data.total_count_of_trades,0),totalTradeVolume:g,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:h>0?d/h*100:0,totalBuys:c.reduce((_,b)=>_+b.data.total_buys,0),totalSells:c.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:u}}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 xae=["all","7","30","60","90"],X0=25,$h=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 ${X0}. 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 ${X0}.`,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 ${X0}.`,required:!1,items:{type:"string"}}]);f(this,"service");this.service=new ct(r)}async run(r,n){let i=fr(r.address,n),o=hr(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=xae.includes(a)?a:void 0,l=Array.isArray(r.tokenSymbols)?r.tokenSymbols.filter(h=>typeof h=="string"&&!!h.trim()).map(h=>h.trim()):[],c=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,c);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(ii().map(async h=>({chain:h,res:await this.fetchChainPnl(i,h,s,l,c)})))).filter(h=>h.res.ok&&h.res.tokens.length>0).map(h=>({chain:Q(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:c.length>0?c: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 c=Iae([...s.map(h=>h.address),...a]).slice(0,X0),u=c.length>0?c:void 0,d=await this.service.getWalletPnl({address:r,chain:n,days:i,tokenAddresses:u});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:u,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(c=>(c.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(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};function Iae(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 Oae=BigInt(2)**BigInt(255),Dh=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 ct(r)}async run(r,n){let i=fr(r.address,n),o=Wr(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,c=await this.service.getWalletApprovals({address:i,chain:o,limit:s,cursor:l});if(!c.success)return{error:c.error||"Failed to fetch wallet approvals"};let u=c.data,h=(u.result||[]).map(_=>Rae(_)),m=0,g=0,y=[];for(let _ of h){_.isUnlimited&&(g+=1);let b=parseFloat(_.token.usdAtRisk??"");Number.isFinite(b)&&(m+=b);let v=_.token.possibleSpam||_.token.verifiedContract===!1,S=!_.spender.label&&!_.spender.entity;(v||_.isUnlimited&&S)&&y.push(_)}return{walletAddress:i,chain:o||"default",filters:{limit:s,cursor:l??null},pagination:{cursor:u.cursor??null,pageSize:u.page_size??s,page:u.page??null,hasMore:!!u.cursor},summary:{totalApprovals:h.length,unlimitedApprovals:g,totalUsdAtRisk:m,riskyApprovalCount:y.length},approvals:h,riskyApprovals:y}}};function Rae(t){let e=Nae(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 Nae(t){if(!t)return!1;try{return BigInt(t)>=Oae}catch{return!1}}p();var Uh=class extends oe{constructor(r){super();f(this,"name","get-wallet-defi-positions");f(this,"description",`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 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.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: 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 ct(r)}async run(r,n){let i=fr(r.address,n),o=hr(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 c=l.data||[];return{walletAddress:i,chain:o,positionCount:c.length,positions:c.map(LB)}}let s=(await Promise.all(ii().map(async l=>{let c=await this.service.getWalletDefiPositions({address:i,chain:l});return{chain:l,rows:c.success?c.data||[]:[]}}))).filter(l=>l.rows.length>0).map(l=>({chain:Q(l.chain),positionCount:l.rows.length,positions:l.rows.map(LB)}));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,c)=>l+c.positionCount,0),chains:s}}};function LB(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:Mae(t.position)}}function Mae(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 Lh=class extends oe{constructor(r){super();f(this,"name","get-wallet-defi-protocol-positions");f(this,"description",`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 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.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". 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). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-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:"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-positions 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 ct(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=fr(r.address,n),a=hr(r.chain,n);if(a){let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:a});return c.success?c.data?{walletAddress:o,chain:a,...this.protocolFields(c.data)}:{error:"No data returned for this protocol"}:{error:c.error||"Failed to fetch wallet DeFi protocol positions"}}let l=(await Promise.all(ii().map(async c=>{let u=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:c});return{chain:c,data:u.success?u.data:void 0}}))).flatMap(c=>c.data&&(c.data.positions||[]).length>0?[{chain:Q(c.chain),data:c.data}]:[]).map(c=>({chain:c.chain,...this.protocolFields(c.data)})).sort((c,u)=>u.totalUsdValue-c.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((c,u)=>c+u.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($ae)}}};function $ae(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 Dae(t){try{return(Number(BigInt(t))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return t}}var qh=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 ct(r)}async run(r,n){let i=r.transactionHash;if(!i)return{error:"Transaction hash is required."};let o=Wr(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(u=>!!u.decoded_event).map(u=>({contract:u.address,signature:u.decoded_event.signature,label:u.decoded_event.label,params:u.decoded_event.params})),c=s.logs.map(u=>({address:u.address,decodedEvent:u.decoded_event?{signature:u.decoded_event.signature,label:u.decoded_event.label,params:u.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:Dae(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:c}}};p();p();p();p();p();var qB=new Map;function Uae(t){let e=qB.get(t);if(e)return e;let r=cc({rpcUrl:t});return qB.set(t,r),r}async function jB(t,e,r=[]){let n=await Uae(t).rpc(e,r);if(n===void 0)throw new Error(`RPC ${e}: empty result`);return n}function FB(t,e,r){return jB(t,"eth_call",[{to:e,data:r},"latest"])}async function Lae(t,e,r){let n=Qu(t);if(!n)return null;try{return await FB(n,e,r)}catch{return null}}p();p();p();function ut(t,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${t}`):console.log(`[LEND] ${t}`,JSON.stringify(e,qae)))}function qae(t,e){return typeof e=="bigint"?`${e}n`:e}var jae=6e4,wO=new Map;async function $y(t,e){let r=sl(e),n=r?parseInt(r,16):NaN;if(!r||!Number.isFinite(n))return[];let i=`${t}|${r}`,o=wO.get(i);if(o&&Date.now()-o.at<jae)return o.markets;let a=Fae(t,r,n),s=a.then(l=>l.markets);return wO.set(i,{at:Date.now(),markets:s}),a.then(l=>{l.answered||wO.delete(i)}),s}async function Q0(t,e){return(await $y(t,e)).length>0}async function Fae(t,e,r){try{let n=`${t}/supply/v2?chainId=${r}&limit=100&page=1`;ut("catalog: GET",n);let i=await ve.get(n);if(!i.ok){let a=i.status>=400&&i.status<500;return ut(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:i.status,message:Xe(i)}),{markets:[],answered:a}}let o=(i.data?.data?.items||[]).flatMap(a=>{let s=Bae(a,e);return s?[s]:[]});return ut("catalog: got markets",{chain:e,rawItems:i.data?.data?.items?.length??0,usable:o.length,tokens:o.map(a=>a.token)}),{markets:o,answered:!0}}catch(n){return ut("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:n?.message}),{markets:[],answered:!1}}}function BB(t,e){let r=e.trim().toLowerCase();if(!r)return[];if(Ve(r))return t.filter(i=>i.contract===r||i.token===r);let n=t.filter(i=>i.name.trim().toLowerCase()===r);return n.length>0?n:t.filter(i=>{let o=i.name.trim().toLowerCase(),a=i.protocol.trim().toLowerCase();return o.includes(r)||r.includes(o)||a.includes(r)||r.includes(a)})}function Bae(t,e){if(t?.isDeleted===!0)return null;let r=typeof t?.contract=="string"?t.contract.toLowerCase():"";if(!Ve(r))return null;let n=typeof t?.token=="string"&&Ve(t.token)?t.token.toLowerCase():r,i=Number(t?.rating?.balanceScore),o=t?.type?.trim()||"unknown";return{chain:e,name:t?.name?.trim()||"USDC lending market",protocol:t?.protocolId?.name?.trim()||"Unknown",protocolLabel:Mo(o),protocolUrl:t?.protocolId?.domain?.trim()||null,type:o,contract:r,token:n,platformScore:Number.isFinite(i)?i:null}}function SO(){return ii()}async function eS(t){let e=SO(),r=await Promise.all(e.map(n=>Q0(t,n)));return e.filter((n,i)=>r[i])}async function tS(t,e){let r=_t(e);return r?Q0(t,r):!1}async function zB(t,e){let r=e.map(o=>_t(o)).filter(o=>!!o),n=[...new Set(r)],i=await Promise.all(n.map(o=>Q0(t,o)));return n.filter((o,a)=>i[a])}p();function jh(t){return Z0(t)}var VB=5;async function HB(t,e,r){let n=e.map(b=>Ve(b)?b.toLowerCase():null);if(n.every(b=>b===null))return ut("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let i=W0(t),o;try{ut("discovery: probing 5 accessors per token",{chain:t,tokens:n,psm:i}),o=await ni(t,[...n.flatMap(b=>b?zae(b):[]),...i?IB(i):[]])}catch(b){return ut("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:t,message:b?.message}),e.map(()=>null)}let a=i?o.slice(o.length-OB):[],s=rr(a[0])?.toLowerCase()??null,l=rr(a[1]),c=rr(a[2]),u=s&&l&&c?{susds:s,usds:l,oracle:c}:null;i&&ut("discovery: PSM3 lookup",{psm:i,susds:s,usds:l,oracle:c});let d=0,h=n.map(b=>{if(!b)return null;let v=o.slice(d,d+VB);return d+=VB,ut("discovery: probe answers",{token:b,"POOL()":rr(v[0]),"UNDERLYING_ASSET_ADDRESS()":rr(v[1]),"baseToken()":rr(v[2]),"asset()":rr(v[3]),"vsr()":Gr(v[4])?.toString()??null}),{token:b,slice:v}}),m=new Set;for(let b of h){if(!b)continue;let v=rr(b.slice[0]);v&&rr(b.slice[1])&&m.add(v.toLowerCase())}let g=await Vae(t,[...m]);m.size>0&&ut("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let y=h.flatMap(b=>b?rr(b.slice[0])&&rr(b.slice[1])||rr(b.slice[2])?[]:rr(b.slice[3])?[b.token]:[]:[]),_=await Hae(t,[...new Set(y)],r);return y.length>0&&ut("discovery: Morpho vault lookup",{asked:[...new Set(y)],recognised:[..._.keys()]}),h.map(b=>{if(!b)return null;let{token:v,slice:S}=b,T={chain:t,protocolUrl:null,token:v,platformScore:null};if(u&&v===u.susds)return ut("discovery: classified",{token:v,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...T,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Mo("spark-l2-susds"),protocolUrl:jh("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let C=rr(S[0]);if(C&&rr(S[1])){let I=g.has(C.toLowerCase());return ut("discovery: classified",{token:v,as:I?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:C}),I?{...T,name:"Aave v3",protocol:"AAVE",protocolLabel:Mo("aave-v3"),protocolUrl:jh("aave-v3"),type:"aave-v3",contract:C}:null}if(rr(S[2]))return ut("discovery: classified",{token:v,as:"compound-v3"}),{...T,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Mo("compound-v3"),protocolUrl:jh("compound-v3"),type:"compound-v3",contract:v};if(rr(S[3])){if(_.has(v)){ut("discovery: classified",{token:v,as:"morpho-v2"});let E=_.get(v)||"Morpho V2";return{...T,name:E,protocol:"MORPHO",protocolLabel:Mo("morpho-v2"),protocolUrl:jh("morpho-v2"),type:"morpho-v2",contract:v}}let R=Gr(S[4])!==null;return ut("discovery: classified",{token:v,as:R?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),R?{...T,name:"Spark",protocol:"SPARK",protocolLabel:Mo("spark-ethereum"),protocolUrl:jh("spark-ethereum"),type:"spark-ethereum",contract:v}:{...T,name:"Spark",protocol:"SPARK",protocolLabel:Mo("spark"),protocolUrl:jh("spark"),type:"spark",contract:v}}return ut("discovery: classified",{token:v,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function zae(t){return[{target:t,callData:gt({abi:vh,functionName:"POOL"})},{target:t,callData:gt({abi:vh,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:t,callData:gt({abi:nd,functionName:"baseToken"})},{target:t,callData:gt({abi:pa,functionName:"asset"})},{target:t,callData:gt({abi:wh,functionName:"vsr"})}]}async function Vae(t,e){if(e.length===0)return new Set;try{let r=await ni(t,e.map(n=>({target:n,callData:gt({abi:lO,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,i)=>rr(r[i])!==null))}catch{return new Set}}async function Hae(t,e,r){let n=parseInt(t,16);if(e.length===0||!Number.isFinite(n))return new Map;let i=await Promise.all(e.map(async o=>{try{let a=await ve.post(r,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:o,c:n}}),s=a.ok?a.data?.data?.vaultV2ByAddress:null;return s?[o,s.name?.trim()||""]:null}catch{return null}}));return new Map(i.filter(o=>o!==null))}var Zae=.01;function Gae(t){return t.reduce((e,r)=>r.conditions===null?e+r.apyPercent:e,0)}function Wae(t,e){if(typeof e!="string"||!e.trim())return;let r=e.trim(),n=Ay();n[t]!==r&&Ju({...n,[t]:r})}var Fh=class{constructor(e,r,n){f(this,"coinPoolBaseUrl",e);f(this,"endpoints",r);f(this,"describer",n)}async describeReceiptTokens(e,r,n){let i=Date.now();ut("describeReceiptTokens: START",{chain:e,tokens:r,hasRpcUrl:!!n});let o=sl(e);o&&Wae(o,n);let a=o?Ny(o):null,s=[...new Set(r.filter(Ve).map(h=>h.toLowerCase()))];if(ut("describeReceiptTokens: chain resolved",{hex:o,hasChainInfo:!!a,wanted:s}),!o||!a||s.length===0)return ut("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:o,hasChainInfo:!!a,wantedCount:s.length}),new Map;ut("describeReceiptTokens: on-chain discovery for",s);let l=await HB(o,s,this.endpoints.morphoApiUrl),u=[...new Map(s.flatMap((h,m)=>{let g=l[m];return ut("describeReceiptTokens: discovery result",{token:h,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[h,g]]:[]})).entries()];if(u.length===0)return ut("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-i}),new Map;ut("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([h,m])=>({token:h,type:m.type,contract:m.contract}))});let d=await this.describer.describe(o,a,u.map(([,h])=>h));return ut("describeReceiptTokens: DONE",{ms:Date.now()-i,overviews:d.map(h=>({name:h.name,protocol:h.protocol,asset:h.asset?.symbol,assetDecimals:h.asset?.decimals,currentApyPercent:h.currentApyPercent,baseApyPercent:h.baseApyPercent,rewardApyPercent:h.rewardApyPercent,avgApyPercent:h.avgApyPercent,apyChangePercent:h.apyChangePercent,totalSuppliedUsdc:h.totalSuppliedUsdc,apyHistoryPoints:h.apyHistory?.length??0}))}),new Map(d.map((h,m)=>[u[m][0],h]))}async findMarketByReceiptToken(e,r,n){if(ut("findMarketByReceiptToken: called",{chain:e,receiptToken:r,hasRpcUrl:!!n}),!Ve(r))return ut("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:r}),null;let o=(await this.describeReceiptTokens(e,[r],n)).get(r.toLowerCase())??null;return ut("findMarketByReceiptToken: returning",{found:!!o}),o}async getSupplyPositions(e){if(!Ve(e.address))return[];let r=await zB(this.coinPoolBaseUrl,e.chains);return(await Promise.all(r.map(i=>this.positionsForChain(i,e.address)))).flat().sort((i,o)=>o.suppliedUsdc-i.suppliedUsdc||(o.avgApyPercent??0)-(i.avgApyPercent??0))}async describeResolvedMarkets(e,r){let n=sl(e),i=n?Ny(n):null;return n&&i?this.describer.describe(n,i,r):[]}async positionsForChain(e,r){let n=Ny(e),i=await $y(this.coinPoolBaseUrl,e);if(!n||i.length===0)return[];let o=await this.describer.readBalances(e,r,i);if(o.length===0)return[];let a=await this.describer.describe(e,n,o.map(l=>l.market)),s=await this.describer.convertToUnderlying(e,o,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=s[c];return u<Zae?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Gae(l.rewards))/100}]})}};p();var kO=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Bh=class{constructor(e){f(this,"coinPoolBaseUrl",e)}async listChains(){return eS(this.coinPoolBaseUrl)}async isSupported(e){return tS(this.coinPoolBaseUrl,e)}async getMarkets(e){let r=_t(e);return r?$y(this.coinPoolBaseUrl,r):[]}async findMarket(e,r){let n=await this.getMarkets(e);return BB(n,r)}canSupply(e){return kO.includes(e.type)}async readReceiptToken(e,r){let n=od(r).balanceIsUnderlying;try{let i=await ni(e,[{target:r.token,callData:gt({abi:Zt,functionName:"symbol"})},{target:r.token,callData:gt({abi:Zt,functionName:"decimals"})}]);return{symbol:yy(i[0]),decimals:Vp(i[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};p();p();var Kae={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Yae={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",130:"proto_unichain_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},Jae={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Xae={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function rS(t){let e=ase(t.chain);return(e===null?null:Qae(t,e))??Z0(t.type)??ose(t,e)}function Qae(t,e){switch(t.type){case"morpho-v2":{let r=Kae[e];if(!r||!t.contract)return null;let n=`https://app.morpho.org/${r}/vault/${TO(t.contract)}`,i=rse(t.name);return i?`${n}/${i}`:n}case"aave-v3":{let r=Yae[e],n=ese(t);return!r||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${TO(n)}&marketName=${r}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let r=Jae[e],n=ise(t);return!r||!n?null:`https://app.spark.fi/savings/${r}/${n}`}case"compound-v3":{let r=Xae[e],n=nse(t);return!r||!n?null:`https://app.compound.finance/?market=${n}-${r}`}default:return null}}function ese(t){let e=t.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var tse=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function rse(t){let e=t?.trim().toLowerCase()||"";return!e||tse.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function nse(t){let e=t.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function ise(t){let e=`${t.name||""} ${t.token||""}`.toLowerCase();for(let n of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(e.includes(n))return n;let r=t.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]{2,11}$/.test(r)?t.type==="spark-ethereum"?`sp${r}`:`s${r}`:null}function ose(t,e){let r=t.protocolUrl?.trim();if(!r)return null;let n=/^https?:\/\//i.test(r)?r:`https://${r.replace(/^\/+/,"")}`;try{let i=new URL(n);return e!==null&&i.searchParams.set("chainId",String(e)),t.contract&&i.searchParams.set("contract",TO(t.contract)),i.toString()}catch{return n}}function TO(t){let e=t.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function ase(t){let e=t?.trim();if(!e)return null;let r=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(r)&&r>0?r:null}var sse=8;function lse(t,e,r){if(t.market.type!=="spark-l2-susds")return Gr(e);let n=Gr(e);return n===null||t.tokenDecimals===null?null:kh(t.rawBalance,n,t.tokenDecimals,r)}var nS=class{constructor(e){f(this,"endpoints",e);f(this,"apyLimiter",new PO(sse));f(this,"pantograph",new jr)}async describe(e,r,n){if(n.length===0)return[];ut("describe: START",{chain:e,count:n.length,types:n.map(s=>s.type)});let i=await this.resolveAssets(e,n);ut("describe: assets resolved",i);let[o,a]=await Promise.all([this.readMarketState(e,n,i),Promise.all(n.map((s,l)=>this.apyLimiter.run(()=>this.fetchApy(s,r,i[l]))))]);return ut("describe: on-chain state",o),ut("describe: APY fetched",a.map((s,l)=>({type:n[l].type,rawSamples:s.samples.length,sourceCurrent:s.current}))),n.map((s,l)=>{let{totalSuppliedUsdc:c,liveApyFraction:u}=o[l],d=use(a[l].samples,u??a[l].current,a[l].rewards,a[l].avgOverride??null);return ut("describe: summarised",{market:s.name,type:s.type,liveFrom:u!==null?"on-chain":a[l].current!==null?"api":"none",rawSamples:a[l].samples.length,historyPoints:d.history.length,currentApyPercent:d.currentApyPercent,avgApyPercent:d.avgApyPercent,apyChangePercent:d.apyChangePercent,totalSuppliedUsdc:c,asset:i[l]?.symbol}),{...s,protocolUrl:rS({...s,asset:i[l]}),asset:i[l],totalSuppliedUsdc:c,avgApyPercent:d.avgApyPercent,currentApyPercent:d.currentApyPercent,baseApyPercent:d.baseApyPercent,rewardApyPercent:d.rewardApyPercent,rewards:d.rewards,apyChangePercent:d.apyChangePercent,apyHistory:d.history}})}async readBalances(e,r,n){let i=gt({abi:Zt,functionName:"balanceOf",args:[r]}),o=gt({abi:Zt,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:i},{target:l.token,callData:o}]),s=await ni(e,a);return n.flatMap((l,c)=>{let u=Gr(s[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Vp(s[c*2+1])}]})}async convertToUnderlying(e,r,n){let i=[],o=r.map(s=>{let l=od(s.market).convertToAssetsCall(s.market,s.rawBalance);return l?(i.push(l),i.length-1):-1}),a=await ni(e,i);return r.map((s,l)=>{let c=n[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(o[l]<0)return mc(s.rawBalance,c);let u=lse(s,a[o[l]],c);return u===null?mc(s.rawBalance,s.tokenDecimals??c):mc(u,c)})}async resolveAssets(e,r){let n={address:ad,decimals:NaN,symbol:null,logo:null},i=[],o=r.map(u=>{let d=od(u).underlyingCall(u);return d?(i.push(d),i.length-1):-1}),a;try{let u=i.length>0?await ni(e,i):[];a=o.map(d=>d<0?null:rr(u[d]))}catch{a=r.map(()=>null)}a=a.map((u,d)=>u??r[d]?.assetAddress??null);let s=[...new Set(a.filter(u=>!!u).map(u=>u.toLowerCase()))],[l,c]=await Promise.all([this.readAssetMetadata(e,s),this.fetchAssetLogos(e,s)]);return a.map(u=>{if(!u)return n;let d=u.toLowerCase(),h=l.get(d),m=c.get(d)??null;return h?.decimals!==null&&h?.decimals!==void 0?{address:u,decimals:h.decimals,symbol:h.symbol??null,logo:m}:{address:u,decimals:NaN,symbol:null,logo:m}})}async readAssetMetadata(e,r){let n=new Map;if(r.length===0)return n;let i=gt({abi:Zt,functionName:"decimals"}),o=gt({abi:Zt,functionName:"symbol"});try{let a=await ni(e,r.flatMap(s=>[{target:s,callData:i},{target:s,callData:o}]));r.forEach((s,l)=>{n.set(s,{decimals:Vp(a[l*2]),symbol:yy(a[l*2+1])})})}catch{}return n}async fetchAssetLogos(e,r){let n=new Map;if(r.length===0)return n;try{let i=await this.pantograph.getTokensMetadata(r,e);for(let[o,a]of Object.entries(i)){let s=a.icon_image||a.logo||a.logoURI;s&&n.set(o.toLowerCase(),s)}}catch{}return ut("resolveAssets: logos",{chain:e,requested:r.length,found:n.size}),n}async readMarketState(e,r,n){let i=[],o=r.map((u,d)=>{let h=od(u),m=n[d],g={market:u,protocol:h,asset:m,size:i.length,rate:-1};i.push(h.sizeCall(u,m));let y=h.liveRateCall(u,m);return y&&(g.rate=i.length,i.push(y)),g}),a=await ni(e,i),s=[],l=o.map(u=>{if(u.rate<0)return-1;let d=u.protocol.followUpRateCall(u.market,a[u.rate]);return d?(s.push(d),s.length-1):-1}),c=s.length>0?await ni(e,s):[];return o.map((u,d)=>{let h=u.rate<0?null:a[u.rate],m=l[d]>=0?c[l[d]]:h;return{totalSuppliedUsdc:u.protocol.decodeSize(a[u.size],u.asset),liveApyFraction:m===null?null:u.protocol.decodeLiveRate(m)}})}async fetchApy(e,r,n){try{ut("fetchApy: requesting",{market:e.name,type:e.type,asset:n?.symbol});let i=await od(e).fetchApy(e,r,this.endpoints,n);return ut("fetchApy: got",{market:e.name,samples:i.samples.length,current:i.current,avgOverride:i.avgOverride??null}),i}catch(i){return ut("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:i?.message}),{samples:[],current:null,rewards:[]}}}},PO=class{constructor(e){f(this,"limit",e);f(this,"active",0);f(this,"waiting",[])}async run(e){this.active>=this.limit?await new Promise(r=>this.waiting.push(r)):this.active++;try{return await e()}finally{let r=this.waiting.shift();r?r():this.active--}}};function cse(t,e){let r=G0(Date.now()),n=new Map,i=null;for(let s of t)!Number.isFinite(s.timeMs)||!Number.isFinite(s.fraction)||s.fraction<0||G0(s.timeMs)>r||((!i||s.timeMs>i.timeMs)&&(i=s),n.set(s.timeMs,s.fraction));let o=[...n.entries()].sort((s,l)=>s[0]-l[0]).map(([s,l])=>({date:new Date(s).toISOString(),apyPercent:l*100})),a=e??(i&&G0(i.timeMs)===r?i.fraction:null);return{history:o,live:a}}function use(t,e,r=[],n=null){let{history:i,live:o}=cse(t,e),a=o===null?null:o*100,s=r.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=s.length===0?null:s.reduce((m,g)=>m+g.apyPercent,0),c=a===null?null:a+(l??0),u={baseApyPercent:a,rewardApyPercent:l,rewards:s},d=n!==null&&Number.isFinite(n)?n*100:null;if(i.length===0)return{history:i,avgApyPercent:d,currentApyPercent:c,apyChangePercent:null,...u};let h=i.reduce((m,g)=>m+g.apyPercent,0);return{history:i,avgApyPercent:d??h/i.length,currentApyPercent:c,apyChangePercent:pse(i,a),...u}}var ZB=3600*1e3,dse=ZB/2;function pse(t,e){if(e===null)return null;let r=Date.now()-ZB,n=null,i=Number.POSITIVE_INFINITY;for(let o=t.length-1;o>=0;o--){let a=Math.abs(Date.parse(t[o].date)-r);if(a>i)break;i=a,n=t[o]}return!n||i>dse?null:e-n.apyPercent}function GB(t,e){if(!Number.isFinite(t))return t;let r=10**e,n=Number((t*r).toPrecision(15));return(t<0?-Math.floor(-n):Math.floor(n))/r+0}var $o=class{constructor(e={}){f(this,"read");f(this,"supply");let r=e.coinPoolBaseUrl||"https://api.coinpool.app",n={coinPoolBaseUrl:r,lendingRatesBaseUrl:e.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},i=new nS(n);this.read=new Fh(r,n,i),this.supply=new Bh(r)}async listSupportedChains(){return this.supply.listChains()}async isSupported(e){return this.supply.isSupported(e)}async getMarkets(e){return this.supply.getMarkets(e)}async findMarket(e,r){return this.supply.findMarket(e,r)}canSupply(e){return this.supply.canSupply(e)}async readReceiptToken(e,r){return this.supply.readReceiptToken(e,r)}async describeReceiptTokens(e,r,n){return this.read.describeReceiptTokens(e,r,n)}async findMarketByReceiptToken(e,r,n){return this.read.findMarketByReceiptToken(e,r,n)}async describeResolvedMarkets(e,r){return this.read.describeResolvedMarkets(e,r)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async n=>this.read.describeResolvedMarkets(n,await this.getMarkets(n))))).flat().sort((n,i)=>(i.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};p();var Dy="{market}",YB=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],oS=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],JB="[[LIST]]",XB=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',QB=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function e4(t,e,r){let[n]=hse([t],e,r),[i]=t.canSupply?AO(t,e,r):[];return{name:t.name?.trim()||t.protocol,protocol:t.protocol,protocolUrl:t.protocolUrl,chain:r,apyPercent:t.apyPercent,detailPrompt:n?.prompt??"",detailLabel:n?.label??"",supplyPrompt:i?.prompt??"",supplyLabel:i?.label??""}}function hse(t,e,r){return t4(t,{labelTemplate:iS(e.detail_button_label),promptTemplate:iS(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Dy}`,...r===void 0?{}:{chainName:r}})}function AO(t,e,r){return t4([t],{labelTemplate:iS(e.supply_button_label),promptTemplate:iS(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Dy}`,promptFallback:`supply to ${Dy}`,...r===void 0?{}:{chainName:r},max:1})}function t4(t,e){let r=typeof e.chainName=="string"?e.chainName.trim():"",n=[],i=new Set;for(let o of t){if(e.max!==void 0&&n.length>=e.max)break;let a=o.name?.trim();!a||i.has(a.toLowerCase())||(i.add(a.toLowerCase()),n.push({label:WB(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:WB(fse(e.promptTemplate),a,e.promptFallback)+mse(o.contract,r)}))}return n}function fse(t){let[e,r]=[t[0],t[1]];return e===void 0||e===e.toLowerCase()||r!==void 0&&r!==r.toLowerCase()?t:e.toLowerCase()+t.slice(1)}function iS(t){return typeof t=="string"?t:""}function mse(t,e){let r=t?.trim();if(!r||!/^0x[a-fA-F0-9]{40}$/.test(r))return"";let n=e?.trim();return n?` (market: ${r} - ${n})`:` (market: ${r})`}function WB(t,e,r,n=!0){let o=t&&(!n||t.includes(Dy))?t:r;return gse(o).split(Dy).join(e).replace(/\s+/g," ").trim()}var KB="{chain}";function gse(t){if(!t.includes(KB))return t;let e=KB.replace(/[{}]/g,"\\$&");return t.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}p();var aS=[{id:"aave-v3",label:"Aave v3",types:["aave-v3"],aliases:["aave","aavev3","aave3","ave"]},{id:"compound-v3",label:"Compound v3",types:["compound-v3"],aliases:["compound","compoundv3","compound3","comet","comp"]},{id:"spark-any",label:"Spark",types:["spark","spark-ethereum"],aliases:["spark","sparkfi","sparklend","sparkprotocol"]},{id:"morpho-v2",label:"Morpho",types:["morpho-v2"],aliases:["morpho","morphov2","morpho2","morphoblue","metamorpho"]}],CO=aS.map(t=>t.label),EO={euler:"Euler",venus:"Venus",radiant:"Radiant",benqi:"Benqi",qi:"Benqi",fluid:"Fluid",instadapp:"Fluid",silo:"Silo",moonwell:"Moonwell",sonne:"Sonne",granary:"Granary",ironbank:"Iron Bank",cream:"Cream",maker:"Maker",makerdao:"Maker",sky:"Sky",justlend:"JustLend",kamino:"Kamino",solend:"Solend",marginfi:"marginfi",save:"Save",curve:"Curve",yearn:"Yearn",convex:"Convex",pendle:"Pendle",ethena:"Ethena",gearbox:"Gearbox",notional:"Notional",exactly:"Exactly",seamless:"Seamless",zerolend:"ZeroLend",dforce:"dForce",tectonic:"Tectonic",liqee:"Liqee"};function r4(t){let e=typeof t=="string"?t.trim():"";if(!e)return{kind:"none"};let r=vse(e);if(!r)return{kind:"none"};let n=yse(r);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let i=bse(r);return i?{kind:"unsupported",label:i,requested:e}:{kind:"unknown",requested:e}}function yse(t){let e=aS.filter(r=>r.aliases.includes(t));if(e.length===1)return e[0];if(e.length>1)return null;if(t.length>=3){let r=aS.filter(n=>n.aliases.some(i=>i.includes(t)||t.includes(i)));if(r.length===1)return r[0];if(r.length>1)return null}return _se(t)}function _se(t){let e=null,r=!1;for(let n of aS)for(let i of n.aliases){let o=n4(i);if(o===0||Math.abs(i.length-t.length)>o)continue;let a=i4(t,i,o);a>o||(!e||a<e.distance?(e={spec:n,distance:a},r=!1):a===e.distance&&n!==e.spec&&(r=!0))}return e&&!r?e.spec:null}function n4(t){return t.length<=4?0:t.length<=9?2:3}function bse(t){let e=EO[t];if(e)return e;if(t.length>=4){let i=new Set(Object.entries(EO).filter(([o])=>o.length>=4&&(o.includes(t)||t.includes(o))).map(([,o])=>o));if(i.size===1)return[...i][0];if(i.size>1)return null}let r=null,n=!1;for(let[i,o]of Object.entries(EO)){let a=n4(i);if(a===0||Math.abs(i.length-t.length)>a)continue;let s=i4(t,i,a);s>a||(!r||s<r.distance?(r={label:o,distance:s},n=!1):s===r.distance&&o!==r.label&&(n=!0))}return r&&!n?r.label:null}function vse(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function i4(t,e,r){if(t===e)return 0;if(!t.length)return e.length;if(!e.length)return t.length;let n=new Array(e.length+1),i=Array.from({length:e.length+1},(a,s)=>s),o=new Array(e.length+1);for(let a=1;a<=t.length;a++){o[0]=a;let s=o[0];for(let c=1;c<=e.length;c++){let u=i[c-1]+(t[a-1]===e[c-1]?0:1),d=Math.min(o[c-1]+1,i[c]+1,u);a>1&&c>1&&t[a-1]===e[c-2]&&t[a-2]===e[c-1]&&(d=Math.min(d,n[c-2]+1)),o[c]=d,d<s&&(s=d)}if(s>r)return r+1;let l=n;n=i,i=o,o=l}return i[e.length]}p();function Pr(t,e){return t==null?null:GB(t,e)}var Dn=2,gc=2;function sS(t){let e=Pr(t.currentApyPercent,Dn),r=t.rewards.map(o=>({apyPercent:Pr(o.apyPercent,Dn)??0,tokenSymbol:o.tokenSymbol,conditions:o.conditions})),n=t.rewardApyPercent===null?null:r.reduce((o,a)=>o+Math.round(a.apyPercent*100),0)/100;if(n===null||e===null)return{currentApyPercent:e,rewardApyPercent:n,rewards:r,baseApyPercent:Pr(t.baseApyPercent,Dn)};let i=Math.round(e*100)-Math.round(n*100);return{currentApyPercent:e,rewardApyPercent:n,rewards:r,baseApyPercent:i/100}}var wse=["apy","score","size"],o4=3,a4=40,zh=class extends oe{constructor(r){super();f(this,"name","get-lending-markets");f(this,"kind","ui");f(this,"description",'BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${CO.join(", ")}. Set it whenever the user names a protocol \u2014 "supply aave", "morpho vaults", "l\xE3i su\u1EA5t b\xEAn Compound" \u2014 and pass what they wrote, VERBATIM. Do NOT correct their spelling, do NOT translate it, and do NOT map it to a name from the supported list yourself: misspellings are resolved for you, and a protocol that is NOT supported is reported back so you can tell the user. Pass it even when you believe the protocol is unsupported \u2014 that is how the user gets told. OMIT it when the user named no protocol; never guess one to narrow a list they asked for in full.`,required:!1},{name:"limit",type:"number",description:`How many markets to return, 1-${a4}. Default ${o4} \u2014 the top markets by the chosen ranking, which answers "where can I earn on my USDC" on its own. Raise it ONLY when the user asks for more than that, for the full list, or to compare broadly; lower it when they want a shorter shortlist.`,required:!1},{name:"sort",type:"string",description:'Ranking: "apy" (default, highest live protocol APY first), "score" (safest / best-rated first \u2014 use when the user asks for safe, reliable or trusted markets), or "size" (largest market first \u2014 use when the user asks for the biggest or most liquid markets).',required:!1},...YB,...oS]);f(this,"service");this.service=new $o(r)}async run(r,n){let i=hr(r.chain,void 0),o=i?null:_t(n?.chain),a=i??o,s=a?await this.service.isSupported(a):!1,l=s?[]:await this.service.listSupportedChains();if(a&&!s)return{_instructions:`There are no lending markets on ${Q(a)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:Q(a),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:l.map(S=>Q(S))};let c=r4(r.protocol);if(c.kind==="unsupported"||c.kind==="unknown")return this.unsupportedProtocol(c);let u=a?[a]:l,d=kse(r.sort),h=Tse(r.limit),m=await this.service.getMarketOverviews({chains:u}),g=c.kind==="supported"?m.filter(S=>c.matches(S)):m;if(c.kind==="supported"&&g.length===0&&m.length>0)return{_instructions:`There are no ${c.label} lending markets on ${a?Q(a):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${c.label} market. Do NOT mention tool names.`,requestedProtocol:c.label,chain:a?Q(a):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(m.map(S=>S.protocol))]};let y=[...g].sort(Sse[d]).slice(0,h),_=y.map(S=>e4({name:S.name,contract:S.contract,protocol:S.protocol,protocolUrl:S.protocolUrl,apyPercent:Pr(S.currentApyPercent,Dn),canSupply:this.service.supply.canSupply(S)},r,Q(S.chain))),v={component:"LendingMarketList",props:{chain:a?Q(a):"all",multiChain:new Set(_.map(S=>S.chain)).size>1,markets:_}};return{..._.length>0?{ui:v}:{},_instructions:this.instructions(y,d,_.length>0,c.kind==="supported"?c.label:null),chain:a?Q(a):"all",chainsQueried:u.map(S=>Q(S)),...c.kind==="supported"?{protocolFilter:c.label}:{},sortedBy:d,marketCount:_.length,totalMarketsAvailable:g.length,marketNames:_.map(S=>S.name)}}unsupportedProtocol(r){let n=r.kind==="unsupported",i=n?r.label:`"${r.requested}"`;return{_instructions:`The user asked about ${i}, which has no lending markets here. In their language: tell them plainly that ${i} is ${n?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${i} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:n?r.label:r.requested,protocolSupported:!1,supportedProtocols:[...CO],marketCount:0,marketNames:[]}}instructions(r,n,i=!1,o=null){if(r.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let a={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[n];return[o?`These are the ${o} lending markets the user can supply to, ${a}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${a}.`,`Write your reply in TWO parts separated by a line containing exactly ${JB} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",n==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(r.map(s=>s.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${Q(r[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${a} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",i?XB:""].filter(Boolean).join(" ")}},Sse={apy:(t,e)=>(e.currentApyPercent??-1)-(t.currentApyPercent??-1),score:(t,e)=>(e.platformScore??-1)-(t.platformScore??-1),size:(t,e)=>(e.totalSuppliedUsdc??-1)-(t.totalSuppliedUsdc??-1)};function kse(t){let e=typeof t=="string"?t.trim().toLowerCase():"";return wse.includes(e)?e:"apy"}function Tse(t){let e=typeof t=="number"?t:Number(t);return!Number.isFinite(e)||e<1?o4:Math.min(Math.floor(e),a4)}p();p();function s4(t){let{currentApyPercent:e,avgApyPercent:r,totalSuppliedUsdc:n,rewardApyPercent:i,baseApyPercent:o,platformScore:a}=t;return t.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:i!==null&&o!==null&&i>o*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:e!==null&&r!==null&&r>0&&e>r*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:n!==null&&n<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&n!==null&&n>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:n!==null&&n>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}p();function lS(t){let e=typeof t=="string"?t.trim():"",r=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(e);if(r)return r[1];let n=/0x[a-fA-F0-9]{40}/.exec(e);return n&&n[0]!==e?n[0]:e}var Vh=class extends oe{constructor(r){super();f(this,"name","get-lending-market-detail");f(this,"category","blockchain-data");f(this,"description",'Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.');f(this,"parameters",[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...oS]);f(this,"service");this.service=new $o(r)}async run(r,n){let o=hr(r.chain,void 0)??_t(n?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let h=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:Q(o),chainsWithLendingMarkets:h.map(m=>Q(m)),_instructions:`There are no lending markets on ${Q(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let a=lS(r.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let s=await this.service.findMarket(o,a);if(s.length===0)return{error:"market_not_found",market:a,chain:Q(o),_instructions:`No lending market matching "${a}" exists on ${Q(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(s.length>1)return{error:"ambiguous_market",market:a,chain:Q(o),candidates:s.map(h=>({marketName:h.name,protocol:h.protocol})),_instructions:`"${a}" matches ${s.length} different markets on ${Q(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+a+`" and chain for ${Q(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let l=s[0],c=await this.describeOne(o,l);if(!c)return{error:"market_unavailable",marketName:l.name,chain:Q(o),_instructions:`${l.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let u=this.service.supply.canSupply(l),d=u?AO({name:l.name,contract:l.contract},r,Q(o)):[];return{_instructions:this.instructions(c,d.length>0,u),...d.length>0?{actionButtons:d}:{},marketName:c.name,protocol:c.protocolLabel??c.protocol,protocolUrl:c.protocolUrl,chain:Q(c.chain),suppliedAssetSymbol:c.asset.symbol,totalSuppliedUsdc:Pr(c.totalSuppliedUsdc,gc),...sS(c),avgApyPercent:Pr(c.avgApyPercent,Dn),apyChangePercent:Pr(c.apyChangePercent,Dn),platformScore:c.platformScore,supplySupported:u}}async describeOne(r,n){try{let[i]=await this.service.describeResolvedMarkets(r,[n]);return i??null}catch{return null}}instructions(r,n,i){let o=s4(r);return[`This is the full picture of ONE lending market, ${r.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',i?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",n?QB:""].filter(Boolean).join(" ")}};p();var Hh=class extends oe{constructor(r){super();f(this,"name","get-wallet-lending-positions");f(this,"description",'Get a wallet\'s own LENDING / SUPPLY (earn, deposit, savings) positions in the curated lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much it has supplied there, the AVERAGE supply APY over the last week (plus the live rate and the day-over-day change), the estimated yearly yield on that balance, and the market total supplied. Balances are read on-chain, so they match the app. Use for questions like: "Which protocols am I supplying on?", "Show my lending positions", "How much am I earning on my USDC?", "What APY am I getting?", "Where is my USDC deposited?", "My Aave / Compound / Spark / Morpho supply", "what am I earning on Aave", "my savings positions". This is the PREFERRED tool for any "what am I earning / supplying / depositing" question, even when the user names a protocol ("my Aave v3 supply", "my Spark deposit") \u2014 it is the only source of the 7-day average APY, the estimated yearly yield and the platform safety score. Each position reports its OWN asset, which is usually USDC but need not be \u2014 never assume the amounts are dollars without checking `suppliedAssetSymbol`. Chains and markets come from the live catalogue, so do not rule a chain out from memory: call the tool and let it answer. For protocols outside Aave v3 / Compound v3 / Spark / Morpho (Aave v2, MakerDAO\u2026), or when this tool reports nothing but the user insists they have a deposit, fall back to get-wallet-defi-positions. Do NOT use for: markets the wallet has NOT supplied to yet \u2014 where to deposit, best available APY, "promising lending" \u2192 get-lending-markets; the BORROW side of these same protocols, plus LP / staking \u2192 get-wallet-defi-positions (or get-wallet-defi-protocol-positions for one named protocol); plain token 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 to scope to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry lending markets is resolved at call time, so do NOT filter the request against a list you remember. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 positions are then read on the connected wallet's own chain.`,required:!1}]);f(this,"service");this.service=new $o(r)}async run(r,n){let i=fr(r.address,n);if(!Ve(i))return{error:`"${i}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=hr(r.chain,n),a=o?await this.service.isSupported(o):!1,s=a?[]:await this.service.listSupportedChains();if(o&&!a)return{_instructions:`There are no lending markets on ${Q(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:i,chain:Q(o),positionCount:0,positions:[],chainsWithLendingMarkets:s.map(u=>Q(u))};let l=o?[o]:s,c=await this.service.getSupplyPositions({address:i,chains:l});return{_instructions:this.instructions(c),walletAddress:i,chain:o?Q(o):"all",chainsQueried:l.map(u=>Q(u)),positionCount:c.length,totals:Pse(c),positions:c.map(u=>({marketName:u.name,protocol:u.protocol,protocolUrl:u.protocolUrl,chain:Q(u.chain),suppliedUsdc:Pr(u.suppliedUsdc,gc),suppliedAssetSymbol:u.asset.symbol,avgApyPercent:Pr(u.avgApyPercent,Dn),...sS(u),apyChangePercent:Pr(u.apyChangePercent,Dn),estimatedAnnualYieldUsdc:Pr(u.estimatedAnnualYieldUsdc,gc),marketTotalSuppliedUsdc:Pr(u.totalSuppliedUsdc,gc),apyHistory:u.apyHistory.map(d=>({...d,apyPercent:Pr(d.apyPercent,Dn)})),platformScore:u.platformScore}))}}instructions(r){return r.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(r.map(i=>i.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Pse(t){if(new Set(t.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let n=t.reduce((a,s)=>a+s.suppliedUsdc,0),i=t.filter(a=>a.avgApyPercent!==null),o=i.reduce((a,s)=>a+s.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:t[0]?.asset.symbol??null,suppliedUsdc:Pr(n,gc),estimatedAnnualYieldUsdc:Pr(t.reduce((a,s)=>a+(s.estimatedAnnualYieldUsdc??0),0),gc),weightedAvgApyPercent:Pr(o>0?i.reduce((a,s)=>a+s.suppliedUsdc*s.avgApyPercent,0)/o:null,Dn)}}p();var Zh=class extends oe{constructor(r){super();f(this,"name","open-supply-usdc-form");f(this,"kind","ui");f(this,"category","lending-action");f(this,"description",'Open the SUPPLY form so the user can DEPOSIT into a specific lending market and start earning yield. This is the tool for a supply COMMAND: the user names a market and tells you to act on it, in any wording and any language \u2014 "supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare "Supply Aave", or a tapped "Supply \u2026" button. A supply verb plus a market name is already a complete command; terseness is not ambiguity, and the words the user left out are supplied by context rather than looked up. Each market deposits its OWN asset (usually USDC), resolved from the market itself \u2014 so a message that names no asset is still this tool: resolve the market from whatever the user did name. An amount is optional. Pass `market` \u2014 the market name or protocol exactly as it was shown to them (e.g. "Aave v3 USDC", "Spark"), and `amount` ONLY when they named one. Supports Aave v3, Compound v3, Spark and Morpho vaults, on whichever chains currently carry them \u2014 that set is resolved at call time, so never refuse a chain from memory. PRECONDITION: a connected wallet. The boundary is command vs question: use this to ACT on one market; to LIST or compare markets \u2192 get-lending-markets; for what the wallet already supplies \u2192 get-wallet-lending-positions.');f(this,"parameters",[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}]);f(this,"service");f(this,"moralis");this.service=new $o(r),this.moralis=new ct(r?.moralis)}async run(r,n){let i=n?.walletAddress;if(!i)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let a=hr(r.chain,void 0)??_t(n?.chain);if(!a)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};if(!await this.service.isSupported(a)){let v=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:Q(a),chainsWithLendingMarkets:v.map(S=>Q(S)),_instructions:`There are no lending markets on ${Q(a)}, so nothing can be supplied there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=lS(r.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let l=await this.service.findMarket(a,s);if(l.length===0)return{error:"market_not_found",market:s,chain:Q(a),_instructions:`No lending market matching "${s}" exists on ${Q(a)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(l.length>1)return{error:"ambiguous_market",market:s,chain:Q(a),candidates:l.map(v=>({marketName:v.name,protocol:v.protocol})),_instructions:`"${s}" matches ${l.length} different markets on ${Q(a)}, so the supply cannot target one yet. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${Q(a)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let c=l[0];if(!this.service.supply.canSupply(c))return{error:"unsupported_protocol",marketName:c.name,protocol:c.protocol,_instructions:`Supplying to ${c.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let u=await this.describeOne(a,c),d=Ase(u);if(!d)return{error:"asset_unresolved",marketName:c.name,chain:Q(a),_instructions:`The asset ${c.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[h,m]=await Promise.all([this.assetBalance(i,a,d.address),this.service.readReceiptToken(a,c)]);if(h&&td(h.amount,"0")<=0)return{error:"no_asset_balance",marketName:c.name,chain:Q(a),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${c.name} on ${Q(a)}. In the user's language, tell them plainly that they have no ${d.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let g=Ese(r.amount),y=g?uc(g,d.decimals):null;if(y&&h&&td(y,h.amount)>0)return{error:"insufficient_asset_balance",marketName:c.name,chain:Q(a),assetSymbol:d.symbol,requestedAmount:g,assetBalance:h.amount,_instructions:`The user wants to supply ${g} ${d.symbol} to ${c.name}, but they only hold ${h.amount} ${d.symbol} on ${Q(a)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${g} ${d.symbol} exceeds their balance of ${h.amount} ${d.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let _={action:"supply_usdc",chainId:a,chainName:Q(a),walletAddress:i,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:u?.protocolUrl??rS(c),contract:c.contract,token:c.token,apyPercent:u?.currentApyPercent??u?.avgApyPercent??null,receiptToken:m},asset:d,...y?{prefillAmount:y}:{},...h?{spendable:h.amount}:{},...h?.usd?{spendableUsd:h.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:_},marketName:c.name,protocol:c.protocol,chain:Q(a),apyPercent:Pr(_.market.apyPercent,Dn),assetSymbol:d.symbol,assetBalance:h?.amount??null,_instructions:this.instructions(c,d.symbol)}}async describeOne(r,n){try{let[i]=await this.service.describeResolvedMarkets(r,[n]);return i??null}catch{return null}}async assetBalance(r,n,i){try{let o=await this.moralis.getWalletTokenBalances({address:r,chain:n,tokenAddresses:[i]});if(!o.success)return null;let a=(o.data?.result??[]).find(l=>(l.token_address||"").toLowerCase()===i.toLowerCase());if(!a?.balance_formatted)return{amount:"0",usd:null};let s=typeof a.usd_value=="number"?String(a.usd_value):null;return{amount:String(a.balance_formatted),usd:s}}catch{return null}}instructions(r,n){return[`The supply action for ${r.name} is ready.`,`In the user's language, invite them to enter the amount of ${n} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${n}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function Ase(t){let e=t?.asset;return!e?.address||e.address===ad||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Ese(t){let e=typeof t=="string"?t.trim():typeof t=="number"?String(t):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}p();p();p();var cS="https://ipfs.pantograph.app/ipfs/",l4=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function sd(t){let e=t?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let r=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return r?`${cS}${r[1]}`:l4.test(e)?`${cS}${e}`:null}function c4(t){let e=t?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let r=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return r?`${cS}${r[1]}`:l4.test(e)?`${cS}${e}`:null}function u4(t){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(t)}function xO(t){if(!t||typeof t!="object")return;let e=t,r=e.image??e.image_url??e.imageUrl;return typeof r=="string"&&r.trim()?r.trim():void 0}function Cse(t){if(typeof atob=="function"){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder().decode(r)}if(typeof Buffer<"u")return Buffer.from(t,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function xse(t){let e=t.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let r=e[1]??"",n=e[2]??"";try{let i=/;base64/i.test(r)?Cse(n):decodeURIComponent(n);return JSON.parse(i)}catch{try{return JSON.parse(n)}catch{return null}}}function d4(t){let e=t?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let r=xse(e);return r?sd(xO(r)):null}p();var Ise=12,Ose=6e3;async function Rse(t,e,r){let n=new Array(t.length),i=0,o=new Array(Math.max(1,Math.min(e,t.length))).fill(0).map(async()=>{for(;i<t.length;){let a=i++;n[a]=await r(t[a],a)}});return await Promise.all(o),n}async function Nse(t,e){try{let r=await ve.get(t,{timeout:e});if(!r.ok)return null;let n=r.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function Mse(t,e){let r=t?.trim();if(!r)return null;if(/^data:/i.test(r))return d4(r);let n=c4(r);if(!n)return null;if(u4(n))return n;let i=await Nse(n,e);if(i){let o=sd(xO(i));if(o)return o}return null}async function uS(t,e,r){if(e.length===0)return[];let n=r?.concurrency??Ise,i=r?.timeoutMs??Ose,o=await aB(t,e,r?.rpcUrl);return Rse(o,n,a=>Mse(a,i))}var p4=100,$se=100,Gh="{name}",h4="{chain}",Wh=class extends oe{constructor(r){super();f(this,"name","get-wallet-nfts");f(this,"description",`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`);f(this,"category","nft");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 (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). 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, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}]);f(this,"service");this.service=new ct(r)}async run(r,n){let i=fr(r.address,n),o=hr(r.chain,n),a=o?[o]:ii(),s=Fse(r.contract_address),l=g4(r.collection_name);return s||l?this.listNfts({address:i,chains:a,singleChain:!!o,contract:s,collectionName:l}):this.listCollections({address:i,chains:a,singleChain:!!o,args:r})}async listCollections(r){let{address:n,chains:i,singleChain:o,args:a}=r,s=await Promise.all(i.map(async u=>{let d=await this.service.getWalletNftCollections({address:n,chain:u,limit:p4});return{chain:u,rows:d.success?f4(d.data?.result??[]):[],ok:d.success}}));if(o&&!s[0].ok)return{error:"Failed to fetch wallet NFT collections"};let l=s.flatMap(u=>u.rows.map(d=>({name:Use(d),contractAddress:d.token_address,chain:Q(u.chain),nftCount:d.count??null})));if(l.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:n,collectionCount:0,collections:[]};let c=qse(l,a);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:n,collectionCount:l.length,collections:l,...c.length>0?{actionButtons:c}:{}}}async listNfts(r){let{address:n,chains:i,singleChain:o,contract:a,collectionName:s}=r,l=await Promise.all(i.map(async g=>{let y=await this.service.getWalletNFTs({address:n,chain:g,limit:p4,...a?{tokenAddresses:[a]}:{}});return{chain:g,rows:y.success?f4(y.data?.result??[]):[],ok:y.success}}));if(o&&!l[0].ok)return{error:"Failed to fetch wallet NFTs"};let c=l.flatMap(g=>g.rows.filter(y=>Dse(y,{contract:a,collectionName:s})).map(y=>({chain:g.chain,row:y})));if(c.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${s??a??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let u=c[0].row.name?.trim()||s||c[0].row.token_address,d=await this.resolveOnchainImages(c),h=c.map(({chain:g,row:y},_)=>{let b=Lse(y);return{name:b.name,tokenId:b.tokenId,contractAddress:b.contractAddress,image:d[_]??b.image,chain:Q(g)}});return{ui:{component:"WalletNftList",props:{walletAddress:n,collectionName:u,nfts:h}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:n,collectionName:u,nftCount:c.length}}async resolveOnchainImages(r){let n=new Array(r.length).fill(null),i=new Map;r.forEach((o,a)=>{let s=i.get(o.chain)??[];s.push(a),i.set(o.chain,s)});try{await Promise.all([...i.entries()].map(async([o,a])=>{let s=a.map(c=>({contract:r[c].row.token_address,tokenId:r[c].row.token_id})),l=await uS(o,s);a.forEach((c,u)=>{n[c]=l[u]??null})}))}catch{}return n}};function f4(t){return t.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Dse(t,e){if(e.contract)return t.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let r=e.collectionName.toLowerCase();return(t.name??"").toLowerCase().includes(r)}return!1}function Use(t){let e=t.name?.trim();if(e)return e;let r=t.token_address??"";return r.length>10?`${r.slice(0,6)}\u2026${r.slice(-4)}`:r}function Lse(t){return{name:t.normalized_metadata?.name||t.name||`#${t.token_id}`,tokenId:t.token_id,contractAddress:t.token_address,image:sd(t.normalized_metadata?.image||t.media?.original_media_url)}}function qse(t,e){let r=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",i=[];for(let o of t){if(i.length>=$se)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",s=a?`show my ${Gh} NFTs on ${h4}`:`show my ${Gh} NFTs`,l=m4(n,{[Gh]:o.name,[h4]:a},s);a&&!l.includes(a)&&(l=`${l} (${a})`),i.push({label:jse(r,o.name,Gh),prompt:`${l} (${o.contractAddress})`})}return i}function m4(t,e,r){let n=t&&t.includes(Gh)?t:r;for(let[i,o]of Object.entries(e))n=n.split(i).join(o);return n.replace(/\s+/g," ").trim()}function jse(t,e,r){return m4(t,{[Gh]:e},r)}function g4(t){if(typeof t!="string")return;let e=t.trim();return e||void 0}function Fse(t){let e=g4(t);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}p();p();var Bse="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.",ga=class extends oe{constructor(r){super();f(this,"kind","data");f(this,"category","nft");f(this,"llm");this.llm=new Mr(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:Bse,timestamp:n},{role:"user",content:r,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Kh=class extends ga{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",ga.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 Yh=class extends ga{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",ga.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 IO={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"},OO="amazon.com";function zse(t){return t?t.trim().toLowerCase().split(/[-_]/)[0]:""}function RO(t){let e=zse(t);return IO[e]??OO}function dS(t){return`https://${RO(t)}/s?k=NFC%20Tag`}p();function pS(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 Vse=720*60*1e3,y4=new Map,_4=3;function Hse(t){return[`A user in country "${t}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${_4} 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 Zse(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 c=l.trim().toLowerCase();if(!o.has(c)&&(o.add(c),i.push({label:s.trim(),url:l.trim()}),i.length>=_4))break}return i}async function NO(t,e){let r=pS(t);if(!r||!e)return null;let n=y4.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:Hse(r),timestamp:i}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=Zse(a.text);if(s.length)return y4.set(r,{links:s,expires:Date.now()+Vse}),s}catch{}return null}async function Jh(t){let e=await NO(t.country,t.llm);return e&&e.length?e:[{label:"Amazon",url:dS(t.language)}]}function Gse(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(`
|
|
473
474
|
`)}var b4=["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(`
|
|
474
475
|
`),Xh=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 Mr(r))}async run(r,n){let i=typeof r.language=="string"&&r.language.trim()?r.language.trim():void 0,o=await Jh({country:n?.country,language:i,llm:this.llm}),a=Gse(o),s=o.length>1;return{reference:b4,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)):
|
|
475
476
|
${a}
|