keyring-agent-core 0.2.62 → 0.2.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -437,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=[d0.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=d0.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 oI=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}}},cF=oI;p();function aI(t){return function(r){return t.apply(null,r)}}p();function sI(t){return j.isObject(t)&&t.isAxiosError===!0}p();var lI={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(lI).forEach(([t,e])=>{lI[e]=t});var uF=lI;function dF(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 dF(Co(t,i))},r}var Nr=dF(Mp);Nr.Axios=dy;Nr.CanceledError=la;Nr.CancelToken=cF;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=aI;Nr.isAxiosError=sI;Nr.mergeConfig=Co;Nr.AxiosHeaders=kr;Nr.formToJSON=t=>s0(j.isHTMLForm(t)?new FormData(t):t);Nr.getAdapter=u0.getAdapter;Nr.HttpStatusCode=uF;Nr.default=Nr;var h0=Nr;var{Axios:LWe,AxiosError:qWe,CanceledError:jWe,isCancel:FWe,CancelToken:BWe,VERSION:zWe,all:VWe,Cancel:HWe,isAxiosError:ZWe,spread:GWe,toFormData:WWe,AxiosHeaders:KWe,HttpStatusCode:YWe,formToJSON:JWe,getAdapter:XWe,mergeConfig:QWe,create:e9e}=h0;var pF="0.2.62";var Iie=`keyring-agent-core/${pF} (Keyring Chatbot Agent; +https://keyring.app)`,cI=null;function hF(t){cI=t}var Oie=["payment-signature","x-payment"];function Rie(t){return t?Object.keys(t).some(e=>Oie.includes(e.toLowerCase())):!1}var fF;function py(t){fF=t}var Nie=3e4,Mie=typeof process<"u"&&process.versions?.node!=null,uI=class{constructor(e={}){f(this,"instance");this.instance=h0.create({baseURL:e.baseURL,timeout:e.timeout??Nie,validateStatus:()=>!0,headers:{Accept:"application/json",...Mie?{"User-Agent":e.userAgent??Iie}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??fF,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&&cI&&!Rie(i.headers)){let c=await cI(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 uI;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 $ie(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??$ie(n.cause),o=n.metaMessages??[],a=[r||"An error occurred.",...o.length>0?["",...o]:[],...i?["",`Details: ${i}`]:[]].join(`
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=[d0.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=d0.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 oI=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}}},cF=oI;p();function aI(t){return function(r){return t.apply(null,r)}}p();function sI(t){return j.isObject(t)&&t.isAxiosError===!0}p();var lI={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(lI).forEach(([t,e])=>{lI[e]=t});var uF=lI;function dF(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 dF(Co(t,i))},r}var Nr=dF(Mp);Nr.Axios=dy;Nr.CanceledError=la;Nr.CancelToken=cF;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=aI;Nr.isAxiosError=sI;Nr.mergeConfig=Co;Nr.AxiosHeaders=kr;Nr.formToJSON=t=>s0(j.isHTMLForm(t)?new FormData(t):t);Nr.getAdapter=u0.getAdapter;Nr.HttpStatusCode=uF;Nr.default=Nr;var h0=Nr;var{Axios:LWe,AxiosError:qWe,CanceledError:jWe,isCancel:FWe,CancelToken:BWe,VERSION:zWe,all:VWe,Cancel:HWe,isAxiosError:ZWe,spread:GWe,toFormData:WWe,AxiosHeaders:KWe,HttpStatusCode:YWe,formToJSON:JWe,getAdapter:XWe,mergeConfig:QWe,create:e9e}=h0;var pF="0.2.63";var Iie=`keyring-agent-core/${pF} (Keyring Chatbot Agent; +https://keyring.app)`,cI=null;function hF(t){cI=t}var Oie=["payment-signature","x-payment"];function Rie(t){return t?Object.keys(t).some(e=>Oie.includes(e.toLowerCase())):!1}var fF;function py(t){fF=t}var Nie=3e4,Mie=typeof process<"u"&&process.versions?.node!=null,uI=class{constructor(e={}){f(this,"instance");this.instance=h0.create({baseURL:e.baseURL,timeout:e.timeout??Nie,validateStatus:()=>!0,headers:{Accept:"application/json",...Mie?{"User-Agent":e.userAgent??Iie}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??fF,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&&cI&&!Rie(i.headers)){let c=await cI(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 uI;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 $ie(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??$ie(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 mF(this,r)}};function mF(t,e){if(e?.(t))return t;let r=t&&typeof t=="object"?t.cause:void 0;return r!=null?mF(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")}},f0=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")}},m0=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: ${gF(n)}`,`Reason: ${i}`]});f(this,"name","InvalidAbiValueError")}},g0=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 "${gF(r)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]});f(this,"name","InvalidAddressError")}};function gF(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 y0=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")}},_0=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")}},b0=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 Die=/^0x[0-9a-fA-F]*$/;function zu(t,{strict:e=!0}={}){return typeof t!="string"?!1:e?Die.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 v0(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 dI(t){return new TextEncoder().encode(t)}function pI(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 hI(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 fI(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 w0(t,e={}){return Number(Io(t,e))}p();var yF=Fg(fy());var Uie=/^0x[0-9a-fA-F]{40}$/;function Ve(t){return typeof t=="string"&&Uie.test(t)}function Fp(t){let e=ca(t).toLowerCase(),r=(0,yF.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 mI(t){if(!Ve(t))throw new Error(`Address "${t}" is invalid.`);return Fp(t)}function gI(t,e){return Ve(t)&&Ve(e)&&t.toLowerCase()===e.toLowerCase()}p();var yI=Fg(fy());function _F(t){return`0x${(0,yI.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,yI.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function _I(t){let e=typeof t=="string"?t:Bp(t);return _F(e)}function bF(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=>bF(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)=>bF(r[u],c))})??a[0]}function Gu(t){let e=rc(t);if(!e)throw new b0({name:t.name,type:t.type??"function"});return e}p();function vF(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 wF(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 SF(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 kF(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 g0({type:n,value:t,min:o,max:i})}function TF(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 bI(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 Lie({...t,type:o},e,i,t.type)}if(t.type==="tuple")return qie(t,e);let n=tc(t.type);if(n==="address"){if(!Ve(e))throw new Lp(e);return{dynamic:!1,encoded:hI(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=SF(e,n);return kF(i,{bits:wF(n,"uint"),signed:!1,type:n}),{dynamic:!1,encoded:Zu(i)}}if(/^int\d*$/.test(n)){let i=SF(e,n);return kF(i,{bits:wF(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=TF(e,n);if(o.length!==i)throw new y0({expectedSize:i,value:String(e)});return{dynamic:!1,encoded:fI(o)}}if(n==="bytes")return vF(TF(e,n));if(n==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new xo({type:n,value:e,reason:"expected a string"});return vF(typeof e=="string"?dI(e):e)}throw new Yl(t.type)}function vI(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 Lie(t,e,r,n){let i=r===null;if(!i&&e.length!==r)throw new m0({expectedLength:r,givenLength:e.length,type:n});let o=!1,a=[];for(let s of e){let l=bI(t,s);l.dynamic&&(o=!0),a.push(l)}if(i||o){let s=vI(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 qie(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=bI(a,Array.isArray(e)?e[o]:e[a.name??""]);s.dynamic&&(n=!0),i.push(s)}return{dynamic:n,encoded:n?vI(i):Hu(i.map(o=>o.encoded))}}function zp(t,e){if(t.length!==e.length)throw new f0({expectedLength:t.length,givenLength:e.length});return t.length===0?"0x":il(vI(t.map((r,n)=>bI(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:v0([i,zp(o,r)])}function wI({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:v0([o,zp(i,r)])}p();function jie(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 TI(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 SI(t){let e=ec(t.type);if(e){let[n,i]=e;return n===null||SI({...t,type:i})}if(t.type==="tuple")return(t.components??[]).some(SI);let r=tc(t.type);return r==="bytes"||r==="string"}function kI(t){let e=ec(t.type);if(e){let[r,n]=e;return r===null?32:r*kI({...t,type:n})}return t.type==="tuple"?(t.components??[]).reduce((r,n)=>r+kI(n),0):32}function PI(t,e,r){let n=[],i=e;for(let o of r)SI(o)?(n.push(PF(t,e+TI(t,i),o)),i+=32):(n.push(PF(t,i,o)),i+=kI(o));return n}function Fie(t,e,r,n){let i=n===null?TI(t,e):n,o=n===null?e+32:e;return PI(t,o,new Array(i).fill(r))}function Bie(t,e,r){let n=r.components??[],i=PI(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 PF(t,e,r){let n=ec(r.type);if(n){let[o,a]=n;return Fie(t,e,{...r,type:a},o)}if(r.type==="tuple")return Bie(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 jie(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=TI(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):pI(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 _0({data:typeof e=="string"?e:il(e),params:t,size:r.length});return PI(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=AF(e);if(r)return r}catch{}try{let[e]=Mn([{type:"bytes32"}],t);return T0(e)}catch{return null}}function Vp(t){return k0(Gr(t))}function k0(t){let e=typeof t=="bigint"?Number(t):typeof t=="number"?t:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function T0(t){return typeof t!="string"||!t.startsWith("0x")?null:AF(Buffer.from(t.slice(2),"hex").toString("utf8"))||null}function AF(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 AI({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 EF={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},CF={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},xF={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,EF,CF],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 xF[i]??`Panic code ${i}.`}return!n||n.length===0?r:`${r}(${n.map(i=>String(i)).join(", ")})`}catch{return}}p();var zie=new Set(["pure","view","nonpayable","payable"]),Vie=new Set(["external","public","internal","private","calldata","memory","storage"]);function CI(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 OF(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 Hie(t){let e=t.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function IF(t,e){let r=!1,n;for(let i of t)i==="indexed"?r=!0:Vie.has(i)||(n=i);return{...e,...n?{name:n}:{},...r?{indexed:!0}:{}}}function xI(t){let e=t.trim();if(e.startsWith("(")){let i=CI(e,0),o=OF(e.slice(1,i)).map(xI),{suffix:a,rest:s}=Hie(e.slice(i+1).trim());return IF(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 IF(n,{type:r})}function vy(t){return OF(t).map(xI)}function by(t,e,r){let n=t.indexOf("(",e);if(n===-1)throw new Xl(r,"Missing parameter list.");let i=CI(t,n);return{name:t.slice(e,n).trim(),params:vy(t.slice(n+1,i)),rest:t.slice(i+1).trim()}}function EI(t,e){return t.split(/[\s()]+/).find(n=>zie.has(n))??e}function P0(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,CI(i,l)))}return{type:"function",name:r,inputs:n,outputs:s,stateMutability:EI(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:EI(n,"nonpayable")}}if(e.startsWith("fallback")){let{rest:r}=by(e,8,t);return{type:"fallback",stateMutability:EI(r,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new Xl(t,"Expected function, event, error, constructor, fallback or receive.")}function II(t){return t.map(P0)}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 OI(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 w0(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 w0(await t.request({method:"eth_getTransactionCount",params:[e,da(r)]}))}async function Jp(t){return Io(await t.request({method:"eth_gasPrice"}))}async function A0(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",RF={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}}},NF={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}}},MF={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}}},$F={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}}},DF={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}}},UF={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}}},LF={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}}},qF={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}}},jF={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}}},FF={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}}},BF={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}}},zF={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=[RF,NF,MF,$F,DF,UF,LF,qF,jF,FF,BF,zF];var VF=new Map,RI=new Map;function Zie(t,e){return`${t??"unknown"}|${e.toLowerCase()}`}async function HF(t,e=sr){let r=Zie(t.chain?.id??t.chain?.hexId,e),n=VF.get(r);if(n!==void 0)return n;let i=RI.get(r);if(i)return i;let o=(async()=>{try{let s=await nc(t,{address:e})!==void 0;return VF.set(r,s),s}catch{return!0}finally{RI.delete(r)}})();return RI.set(r,o),o}async function Ku(t,e,r=!1){return r||typeof t.batch?.multicall=="object"&&t.batch.multicall.assumeMulticall3?!0:HF(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 E0=[{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 NI(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}},MI=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}},$I=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")}},DI=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=>Gie(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 Gie(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 ZF(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?ZF(e.cause):void 0}function ih(t,{abi:e,address:r,args:n,functionName:i,sender:o}){let a=ZF(t),s=t instanceof Jl?new $I({functionName:i}):a!==void 0?new MI({abi:e,data:a,functionName:i}):t;return new DI(s,{abi:e,address:r,args:n,functionName:i,sender:o})}p();var UI=new Map;function Ty({fn:t,id:e,shouldSplitBatch:r,wait:n=0}){let i=()=>UI.get(e)??void 0,o=s=>UI.set(e,s),a=async s=>{i()===s&&UI.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 Wie(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 Kie(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&&Wie(e))try{let l=await Kie(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(OI(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 LI=8;function GF(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:LI}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 NI(e,GF(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 Yie=1024,Jie=50;async function oc(t,e){let{calls:r,account:n,blockNumber:i,blockTag:o,batchSize:a=Yie,maxCalls:s=Jie,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 WF="https://wallet-api.pantograph.app/keyring/chains_v6",Xie=6,Qie=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,KF={},ah=null;function eoe(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://")||Qie.test(o))&&(n.includes(o)||n.push(o),n.length>=Xie))break}return n}function YF(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=eoe(i);a.length>0&&(e[o]=a)}return e}function JF(t){KF=t}function qI(t){let e=ma(t);return e?KF[e]??[]:[]}function jI(){ah||C0()}function C0(t={}){let{url:e=WF,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=YF(i.data),a=Object.keys(o).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return JF(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 toe=new Map(Wu.map(t=>[t.hexId.toLowerCase(),t])),roe=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 roe.get(t);let e=ma(t);return e?toe.get(e):void 0}var Vi=Object.fromEntries(Wu.map(t=>[t.hexId,t.rpcUrls.default.http[0]]));function FI(t){return al(t)?.rpcUrls.default.http[0]}var BI={};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()}BI=e}function Ay(){return{...BI}}function Xu(t){jI();let e=ma(t),r=e?BI[e]:void 0,n=qI(t),i=al(t)?.rpcUrls.default.http??[];return[...new Set([...r?[r]:[],...n,...i])]}function Qu(t){return Xu(t)[0]}function zI(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")}},x0=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 noe=Hi("ParseRpcError",-32700,"The node could not parse the JSON request."),ioe=Hi("InvalidRequestRpcError",-32600,"The JSON request is not valid."),ooe=Hi("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),aoe=Hi("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),soe=Hi("InternalRpcError",-32603,"The node reported an internal error."),loe=Hi("InvalidInputRpcError",-32e3,"The RPC input is not valid."),coe=Hi("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),uoe=Hi("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),doe=Hi("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),poe=Hi("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),VI=Hi("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),hoe=Hi("UserRejectedRequestError",4001,"The user rejected the request."),foe=new Map([[-32700,noe],[-32600,ioe],[-32601,ooe],[-32602,aoe],[-32603,soe],[-32e3,loe],[-32001,coe],[-32002,uoe],[-32003,doe],[-32004,poe],[-32005,VI],[4001,hoe]]);function XF(t){let e=foe.get(t.error.code);return e?new e(t):new ch(t)}p();function QF(t){return new Promise(e=>setTimeout(e,t))}async function HI(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 QF(a)}}function ZI(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 moe=new Set([408,413,429,500,502,503,504]),goe=new Set([401,402,403]);function I0(t){return t instanceof sh||t instanceof lh?!0:t instanceof ac?t.status?moe.has(t.status)||t.status>=500:!0:t instanceof VI?!0:t instanceof ch?t.code===-32603:!1}function O0(t){return t instanceof ac&&t.status&&goe.has(t.status)?!0:I0(t)}function R0(t,{retryCount:e=3,retryDelay:r=150}={}){return function(i,o={}){return HI(()=>t(i),{retryCount:o.retryCount??e,shouldRetry:({error:a})=>I0(a),delay:({count:a,error:s})=>{let l=s instanceof ac?ZI(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:R0(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}),!O0(m))throw m}throw new Ey({cause:d,count:l.length})},retryCount:i,retryDelay:o,timeout:s.timeout},{transports:l})}}p();p();var eB=0;function tB(){return eB+=1,eB}function yoe(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 yoe(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:tB(),...e};return await this.post(r)??{id:r.id}}async requestBatch(e){let r=e.map(o=>({jsonrpc:"2.0",id:tB(),...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 rB(t,e,r){if(t.error)throw XF({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 x0;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 rB(await C(T),T,_)}return rB(await b.request(T),T,_)}},{url:_})}}p();p();var _oe=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||_oe),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 boe=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=woe(e.chain),this.key=n,this.name=i,this.batch=r,this.uid=`${n}-${++boe}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??voe(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 A0(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 voe(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 woe(t){if(t===void 0)return;if(typeof t=="object")return t;let e=zI(t);if(!e)throw new rh(t);return e}function cc(t={}){return new ed(t)}var GI=new Map;function Soe(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=GI.get(u);if(d)return d;let h=cc({chain:a&&!al(a)?Soe(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 GI.set(u,h),h}function N0(){GI.clear()}function KI(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?KI(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 M0(t){return t?.status==="success"?t.result:void 0}async function WI(t,e){try{return await t.multicall({contracts:e})}catch{return[]}}async function nB(t,e,r){let n=e.map(()=>({symbol:null,decimals:null})),i=e.length>0?KI(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 WI(i,o.flatMap(l=>[{address:l.address,abi:Zt,functionName:"symbol"},{address:l.address,abi:Zt,functionName:"decimals"}]));o.forEach((l,c)=>{let u=M0(a[c*2]);typeof u=="string"&&u.trim()&&(n[l.index].symbol=u.trim()),n[l.index].decimals=k0(M0(a[c*2+1]))});let s=o.filter(l=>n[l.index].symbol===null);if(s.length>0){let l=await WI(i,s.map(c=>({address:c.address,abi:eh,functionName:"symbol"})));s.forEach((c,u)=>{n[c.index].symbol=T0(M0(l[u]))})}return n}async function iB(t,e,r){let n=new Array(e.length).fill(null),i=e.length>0?KI(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 WI(i,o.map(s=>({address:s.address,abi:th,functionName:"tokenURI",args:[s.tokenId]})))).forEach((s,l)=>{let c=M0(s);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(n[o[l].index]=u)}),n}p();function koe(t){return $0(String(t))??"0"}function $0(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 YI(t){let e=$0(t);if(e===null||e.startsWith("-"))return null;let[r,n=""]=e.split(".");return{mant:BigInt(r+n),frac:n.length}}function JI(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?koe(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=$0(e[0]);return r&&r!=="0"&&!r.startsWith("-")?r:null}function uc(t,e){let r=$0(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=YI(t);if(!i||r<=0n||n<0)return t;let o=i.mant*e*10n**BigInt(n)/(r*10n**BigInt(i.frac));return JI(o,n)}function td(t,e){let r=YI(t),n=YI(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 Toe={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"}]},Poe="payment-required",Aoe="PAYMENT-SIGNATURE",Eoe="X-PAYMENT",Coe="payment-response",xoe="x-payment-response",Ioe=600,Ooe=300,Roe={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 oB(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 sB(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 Noe(){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 lB(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=Roe[e.toLowerCase()];if(r===void 0)throw new Error(`Unsupported x402 network: ${t}`);return r}function cB(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 D0(t){let e=t.headers[Poe];if(e){let i=aB(Moe(e));return i&&Array.isArray(i.accepts)?{version:2,payload:i}:null}let r=t.data,n=r&&typeof r=="object"?r:aB(r);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function aB(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}function Moe(t){try{return sB(t)}catch{return null}}function $oe(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 Doe(t){let e=null;for(let r of t){let n=$oe(r);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return lB(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 XI(t,e,r,n){let i=D0(t);if(!i)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:a}=i,s=Doe(a.accepts??[]);if(!r)throw new Error("No connected wallet address to build the payment from");let l=lB(s.network),c=Math.floor(Date.now()/1e3),u={from:r,to:s.payTo,value:String(s.amount),validAfter:String(Math.max(0,c-Ioe)),validBefore:String(c+(s.maxTimeoutSeconds??Ooe)),nonce:Noe()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:l,verifyingContract:s.asset},types:Toe,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:cB(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 Uoe(t,e,r,n){let i=cB(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:XI(o,e,r,n)};if(!o.ok)throw new Error(Xe(o));return{status:"ok",data:o.data}}async function QI(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...eO(e,r)}});if(s.ok)return s.data;throw new Error(qoe(s)??Xe(s))}function Loe(t){return D0(t)!==null}function uB(t){let e=dB(t);return e?.errorReason?e.errorReason:D0(t)?.payload.error??null}function qoe(t){let e=uB(t);return e?`x402 payment rejected: ${e}`:null}var joe={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 eO(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{[Eoe]:oB(JSON.stringify(a))}}let o={x402Version:2,...t.resource!=null?{resource:t.resource}:{},accepted:Foe(r),payload:i,...t.extensions!=null?{extensions:t.extensions}:{}};return{[Aoe]:oB(JSON.stringify(o))}}function Foe(t){let{resource:e,description:r,mimeType:n,outputSchema:i,...o}=t;return o}function dB(t){let e=t.headers[Coe]??t.headers[xoe];if(!e)return null;try{return JSON.parse(sB(e))}catch{return null}}function Boe(t,e){return t==null?e:joe[t]??`Chain ${t}`}async function pB(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 nB("0x"+i.toString(16),[e.asset]);o=l?.symbol??null,a=l?.decimals??null}let s=String(e.amount);if(a!==null)try{s=JI(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:Boe(i,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:t.request.url}}function tO(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=XI(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 pB(o)})}catch{a=null}return a?eO(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 rO(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 hB={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},zoe="https://nft.keyring.app/api/gemini-stable",Voe="https://generativelanguage.googleapis.com",Hoe=new Set([408,429,500,502,503,504]),fB=3e4,U0=t=>new Promise(e=>setTimeout(e,t));function L0(t,e,r){if(r!=null&&r>0)return Math.min(r,fB);let n=Math.min(e*2**(t-1),fB);return n/2+Math.random()*(n/2)}function Zoe(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?Voe:zoe)).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 U0(L0(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}`,!Hoe.has(_.status))throw new Error(g);if(y>=a)break;let E=Zoe(_.headers["retry-after"]??null);await U0(L0(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 U0(L0(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 U0(L0(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:hB[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:hB[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"],Goe=new Set(mh),pc=[...mh],nO=new Set(pc),Zi="0x1",yh="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Woe(t){return t.map(e=>gh[e]??e).join(", ")}function q0(t){let e=new Set;if(t)for(let n of t){let i=j0(n);i&&e.add(i)}let r=mh.filter(n=>!e.has(n));pc=r.length>0?[...r]:[...mh],nO=new Set(pc),Zi=pc.includes("0x1")?"0x1":pc[0],yh=Woe(pc)}var Koe={"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=j0(t);return e&&nO.has(e)?e:null}function j0(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=Koe[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&&Goe.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 F0(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=j0(t);return e&&gh[e]?gh[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var Yoe={"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 mB(t,e){let r=j0(t),n=r?Yoe[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Joe={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function gB(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?Joe[e]??null:null}var Xoe={"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 yB(t){let e=_t(t);return e?Xoe[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 _B(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>nO.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:_B(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=_B(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=Qoe(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 Qoe(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();var eae="https://wallet-api.pantograph.app",tae="0x0000000000000000000000000000000000000000",wB={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},SB={"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 rae(t){return wB[t.toLowerCase()]||t}function bB(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 iO(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 B0(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 vB(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??eae).replace(/\/+$/,"")}tokensUrl(e,r){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),i=this.tokensUrl(r,n),o=await ve.get(i);if(!o.ok)return;let a=B0(o.data),s=new Map;for(let l of a)l.address&&s.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=s.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async 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?B0(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=B0(i.data),a=e.toLowerCase()===tae,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?iO(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=B0(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]=iO(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=bB({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(iO)}}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=SB[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=>vB(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=bB({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=>vB(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"}}}};var nae="https://nft.keyring.app",iae="https://nft.keyring.app",oae=.01,rt=5,lr=1e3,aae=25,sae="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",lae="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 cae(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 uae(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 oO(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??nae).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??iae).replace(/\/+$/,""),this.pantograph=new jr({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=mr(n),l="Unknown error";for(let c=1;c<=rt;c++)try{let u={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(u.token_addresses=i);let d=[],h=null;do{h&&(u.cursor=h);let g=cr(u),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await ve.get(y);if(!_.ok)throw new nt(_.status,Xe(_));let b=_.data,v=b?.data??b;v?.result?.length>0&&d.push(...v.result),h=v?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===sae?lae:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=oae)),{success:!0,data:m}}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 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<aae;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:cae(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:uae(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:oO(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:oO(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:oO(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)}};var vh=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(`
@@ -469,7 +469,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
469
469
  netApy
470
470
  historicalState { avgNetApy(options: $options) { x y } }
471
471
  }
472
- }`,Lh=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])}},Ry=class extends Lh{constructor(){super(...arguments);f(this,"type","spark");f(this,"balanceIsUnderlying",!1)}sizeCall(r){return gn(r.contract,pa,"totalAssets")}fetchApy(r,n,i){return mO(r,n,i)}},cO=class extends Ry{constructor(){super(...arguments);f(this,"type","spark")}liveRateCall(r){return gn(r.contract,Uh,"rateProvider")}followUpRateCall(r,n){let i=rr(n);return i===null?null:gn(i,od,"getAPR")}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ny(Math.expm1(Number(n)/H0))}},uO=class extends Ry{constructor(){super(...arguments);f(this,"type","spark-ethereum")}liveRateCall(r){return gn(r.contract,Uh,"vsr")}decodeLiveRate(r){let n=Gr(r);if(n===null||n<=0n)return null;let i=Number(n-IB)/H0;return i>-1?Ny(Math.expm1(Math.log1p(i)*OB)):null}},dO=class extends Lh{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,od,"getAPR")}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ny(Math.expm1(Number(n)/H0))}convertToAssetsCall(r){return gn(r.contract,od,"getConversionRate")}fetchApy(r,n,i){return mO(r,n,i)}};function qh(t,e,r,n){if(e<=0n||!Number.isInteger(r)||!Number.isInteger(n)||r<0||n<0)return null;let i=t*e/IB,o=n-r;return o===0?i:o>0?i*10n**BigInt(o):i/10n**BigInt(-o)}var pO=class extends Lh{constructor(){super(...arguments);f(this,"type","aave-v3");f(this,"balanceIsUnderlying",!0)}underlyingCall(r){return gn(r.token,Dh,"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 Ny(RB(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:Eae,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:Cae(s.data?.data?.reserve?.incentives)}}},hO=class extends Lh{constructor(){super(...arguments);f(this,"type","compound-v3");f(this,"balanceIsUnderlying",!0)}underlyingCall(r){return gn(r.contract,id,"baseToken")}sizeCall(r){return gn(r.token,Zt,"totalSupply")}liveRateCall(r){return gn(r.contract,id,"getUtilization")}followUpRateCall(r,n){let i=Gr(n);return i===null?null:gn(r.contract,id,"getSupplyRate",[i])}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ny(Number(n)/1e18*OB)}fetchApy(r,n,i){return mO(r,n,i)}},fO=class extends Ry{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:xae,variables:{address:r.contract,chainId:n.chainId,options:{startTimestamp:o-xB*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 mO(t,e,r){let n=`${r.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${t.token}?range=h&day=${xB}`,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 NB={"aave-v3":new pO,"compound-v3":new hO,spark:new cO,"spark-ethereum":new uO,"spark-l2-susds":new dO,"morpho-v2":new fO},Iae=NB.spark;function ad(t){return NB[t.type]??Iae}var Oae={"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 Oae[t]??null}var Rae={"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 Rae[t]??null}function mc(t,e){return Number(t)/10**e}function G0(t){return new Date(t).toISOString().slice(0,10)}var Nae=6e4,gO=new Map;async function My(t,e){let r=sl(e),n=r?parseInt(r,16):NaN;if(!r||!Number.isFinite(n))return[];let i=`${t}|${r}`,o=gO.get(i);if(o&&Date.now()-o.at<Nae)return o.markets;let a=Mae(t,r,n),s=a.then(l=>l.markets);return gO.set(i,{at:Date.now(),markets:s}),a.then(l=>{l.answered||gO.delete(i)}),s}async function W0(t,e){return(await My(t,e)).length>0}async function Mae(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=$ae(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 MB(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 $ae(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 yO(){return ii()}async function K0(t){let e=yO(),r=await Promise.all(e.map(n=>W0(t,n)));return e.filter((n,i)=>r[i])}async function Y0(t,e){let r=_t(e);return r?W0(t,r):!1}async function $B(t,e){let r=e.map(o=>_t(o)).filter(o=>!!o),n=[...new Set(r)],i=await Promise.all(n.map(o=>W0(t,o)));return n.filter((o,a)=>i[a])}p();p();var Dae={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function J0(t){let e=sl(t);return e?Dae[e]??null:null}function DB(t){return["susds","usds","rateProvider"].map(e=>({target:t,callData:gt({abi:lO,functionName:e})}))}var UB=3,Uae={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function _O(t){let e=sl(t),r=e?Uae[e]:void 0;return r?{target:r,callData:gt({abi:od,functionName:"getConversionRate"})}:null}function jh(t){return Z0(t)}var LB=5;async function qB(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=J0(t),o;try{ut("discovery: probing 5 accessors per token",{chain:t,tokens:n,psm:i}),o=await ni(t,[...n.flatMap(b=>b?Lae(b):[]),...i?DB(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-UB):[],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+LB);return d+=LB,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 qae(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 jae(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 Lae(t){return[{target:t,callData:gt({abi:Dh,functionName:"POOL"})},{target:t,callData:gt({abi:Dh,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:t,callData:gt({abi:id,functionName:"baseToken"})},{target:t,callData:gt({abi:pa,functionName:"asset"})},{target:t,callData:gt({abi:Uh,functionName:"vsr"})}]}async function qae(t,e){if(e.length===0)return new Set;try{let r=await ni(t,e.map(n=>({target:n,callData:gt({abi:sO,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,i)=>rr(r[i])!==null))}catch{return new Set}}async function jae(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 Fae=.01;function Bae(t){return t.reduce((e,r)=>r.conditions===null?e+r.apyPercent:e,0)}function zae(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&&zae(o,n);let a=o?Iy(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 qB(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 $B(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?Iy(n):null;return n&&i?this.describer.describe(n,i,r):[]}async positionsForChain(e,r){let n=Iy(e),i=await My(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<Fae?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Bae(l.rewards))/100}]})}};p();var bO=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Bh=class{constructor(e){f(this,"coinPoolBaseUrl",e)}async listChains(){return K0(this.coinPoolBaseUrl)}async isSupported(e){return Y0(this.coinPoolBaseUrl,e)}async getMarkets(e){let r=_t(e);return r?My(this.coinPoolBaseUrl,r):[]}async findMarket(e,r){let n=await this.getMarkets(e);return MB(n,r)}canSupply(e){return bO.includes(e.type)}async readReceiptToken(e,r){let n=ad(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 Vae={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Hae={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"},Zae={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Gae={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function X0(t){let e=tse(t.chain);return(e===null?null:Wae(t,e))??Z0(t.type)??ese(t,e)}function Wae(t,e){switch(t.type){case"morpho-v2":{let r=Vae[e];if(!r||!t.contract)return null;let n=`https://app.morpho.org/${r}/vault/${vO(t.contract)}`,i=Jae(t.name);return i?`${n}/${i}`:n}case"aave-v3":{let r=Hae[e],n=Kae(t);return!r||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${vO(n)}&marketName=${r}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let r=Zae[e],n=Qae(t);return!r||!n?null:`https://app.spark.fi/savings/${r}/${n}`}case"compound-v3":{let r=Gae[e],n=Xae(t);return!r||!n?null:`https://app.compound.finance/?market=${n}-${r}`}default:return null}}function Kae(t){let e=t.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Yae=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Jae(t){let e=t?.trim().toLowerCase()||"";return!e||Yae.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Xae(t){let e=t.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Qae(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 ese(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",vO(t.contract)),i.toString()}catch{return n}}function vO(t){let e=t.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function tse(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 rse=8;function nse(t,e,r){if(t.market.type!=="spark-l2-susds")return Gr(e);let n=Gr(e);return n===null||t.tokenDecimals===null?null:qh(t.rawBalance,n,t.tokenDecimals,r)}var Q0=class{constructor(e){f(this,"endpoints",e);f(this,"apyLimiter",new wO(rse));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=ose(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:X0({...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=ad(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=nse(s,a[o[l]],c);return u===null?mc(s.rawBalance,s.tokenDecimals??c):mc(u,c)})}async resolveAssets(e,r){let n={address:nd,decimals:NaN,symbol:null,logo:null},i=[],o=r.map(u=>{let d=ad(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=ad(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 ad(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:[]}}}},wO=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 ise(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 ose(t,e,r=[]){let{history:n,live:i}=ise(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:sse(n,o),...c}}var jB=1440*60*1e3,ase=jB/2;function sse(t,e){if(e===null)return null;let r=Date.now()-jB,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>ase?null:e-n.apyPercent}function FB(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 Q0(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 $y="{market}",VB=[{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}],tS=[{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}],HB="[[LIST]]",ZB=' 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.',GB=' 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 WB(t,e,r){let[n]=lse([t],e,r),[i]=t.canSupply?SO(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 lse(t,e,r){return KB(t,{labelTemplate:eS(e.detail_button_label),promptTemplate:eS(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${$y}`,...r===void 0?{}:{chainName:r}})}function SO(t,e,r){return KB([t],{labelTemplate:eS(e.supply_button_label),promptTemplate:eS(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${$y}`,promptFallback:`supply to ${$y}`,...r===void 0?{}:{chainName:r},max:1})}function KB(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:BB(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:BB(cse(e.promptTemplate),a,e.promptFallback)+use(o.contract,r)}))}return n}function cse(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 eS(t){return typeof t=="string"?t:""}function use(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 BB(t,e,r,n=!0){let o=t&&(!n||t.includes($y))?t:r;return dse(o).split($y).join(e).replace(/\s+/g," ").trim()}var zB="{chain}";function dse(t){if(!t.includes(zB))return t;let e=zB.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 rS=[{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"]}],TO=rS.map(t=>t.label),kO={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 YB(t){let e=typeof t=="string"?t.trim():"";if(!e)return{kind:"none"};let r=mse(e);if(!r)return{kind:"none"};let n=pse(r);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let i=fse(r);return i?{kind:"unsupported",label:i,requested:e}:{kind:"unknown",requested:e}}function pse(t){let e=rS.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=rS.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 hse(t)}function hse(t){let e=null,r=!1;for(let n of rS)for(let i of n.aliases){let o=JB(i);if(o===0||Math.abs(i.length-t.length)>o)continue;let a=XB(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 JB(t){return t.length<=4?0:t.length<=9?2:3}function fse(t){let e=kO[t];if(e)return e;if(t.length>=4){let i=new Set(Object.entries(kO).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(kO)){let a=JB(i);if(a===0||Math.abs(i.length-t.length)>a)continue;let s=XB(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 mse(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function XB(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:FB(t,e)}var Dn=2,gc=2;function nS(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 gse=["apy","score","size"],QB=3,e4=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: ${TO.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-${e4}. Default ${QB} \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},...VB,...tS]);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=YB(r.protocol);if(c.kind==="unsupported"||c.kind==="unknown")return this.unsupportedProtocol(c);let u=a?[a]:l,d=_se(r.sort),h=bse(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(yse[d]).slice(0,h),_=y.map(S=>WB({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:[...TO],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 ${HB} 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?ZB:""].filter(Boolean).join(" ")}},yse={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 _se(t){let e=typeof t=="string"?t.trim().toLowerCase():"";return gse.includes(e)?e:"apy"}function bse(t){let e=typeof t=="number"?t:Number(t);return!Number.isFinite(e)||e<1?QB:Math.min(Math.floor(e),e4)}p();p();function t4(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 iS(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},...tS]);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=iS(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?SO({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),...nS(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=t4(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 since yesterday 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?GB:""].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:vse(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),...nS(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 vse(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=iS(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=wse(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=Sse(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??X0(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 wse(t){let e=t?.asset;return!e?.address||e.address===nd||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Sse(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 oS="https://ipfs.pantograph.app/ipfs/",r4=/^(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?`${oS}${r[1]}`:r4.test(e)?`${oS}${e}`:null}function n4(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?`${oS}${r[1]}`:r4.test(e)?`${oS}${e}`:null}function i4(t){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(t)}function PO(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 kse(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 Tse(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)?kse(n):decodeURIComponent(n);return JSON.parse(i)}catch{try{return JSON.parse(n)}catch{return null}}}function o4(t){let e=t?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let r=Tse(e);return r?sd(PO(r)):null}p();var Pse=12,Ase=6e3;async function Ese(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 Cse(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 xse(t,e){let r=t?.trim();if(!r)return null;if(/^data:/i.test(r))return o4(r);let n=n4(r);if(!n)return null;if(i4(n))return n;let i=await Cse(n,e);if(i){let o=sd(PO(i));if(o)return o}return null}async function aS(t,e,r){if(e.length===0)return[];let n=r?.concurrency??Pse,i=r?.timeoutMs??Ase,o=await iB(t,e,r?.rpcUrl);return Ese(o,n,a=>xse(a,i))}var a4=100,Ise=100,Gh="{name}",s4="{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=Dse(r.contract_address),l=u4(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:a4});return{chain:u,rows:d.success?l4(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:Rse(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=Mse(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:a4,...a?{tokenAddresses:[a]}:{}});return{chain:g,rows:y.success?l4(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=>Ose(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=Nse(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 aS(o,s);a.forEach((c,u)=>{n[c]=l[u]??null})}))}catch{}return n}};function l4(t){return t.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Ose(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 Rse(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 Nse(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 Mse(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>=Ise)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",s=a?`show my ${Gh} NFTs on ${s4}`:`show my ${Gh} NFTs`,l=c4(n,{[Gh]:o.name,[s4]:a},s);a&&!l.includes(a)&&(l=`${l} (${a})`),i.push({label:$se(r,o.name,Gh),prompt:`${l} (${o.contractAddress})`})}return i}function c4(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 $se(t,e,r){return c4(t,{[Gh]:e},r)}function u4(t){if(typeof t!="string")return;let e=t.trim();return e||void 0}function Dse(t){let e=u4(t);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}p();p();var Use="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:Use,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 AO={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"},EO="amazon.com";function Lse(t){return t?t.trim().toLowerCase().split(/[-_]/)[0]:""}function CO(t){let e=Lse(t);return AO[e]??EO}function sS(t){return`https://${CO(t)}/s?k=NFC%20Tag`}p();function lS(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 qse=720*60*1e3,d4=new Map,p4=3;function jse(t){return[`A user in country "${t}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${p4} 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 Fse(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>=p4))break}return i}async function xO(t,e){let r=lS(t);if(!r||!e)return null;let n=d4.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:jse(r),timestamp:i}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=Fse(a.text);if(s.length)return d4.set(r,{links:s,expires:Date.now()+qse}),s}catch{}return null}async function Jh(t){let e=await xO(t.country,t.llm);return e&&e.length?e:[{label:"Amazon",url:sS(t.language)}]}function Bse(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(`
472
+ }`,Lh=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])}},Ry=class extends Lh{constructor(){super(...arguments);f(this,"type","spark");f(this,"balanceIsUnderlying",!1)}sizeCall(r){return gn(r.contract,pa,"totalAssets")}fetchApy(r,n,i){return mO(r,n,i)}},cO=class extends Ry{constructor(){super(...arguments);f(this,"type","spark")}liveRateCall(r){return gn(r.contract,Uh,"rateProvider")}followUpRateCall(r,n){let i=rr(n);return i===null?null:gn(i,od,"getAPR")}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ny(Math.expm1(Number(n)/H0))}},uO=class extends Ry{constructor(){super(...arguments);f(this,"type","spark-ethereum")}liveRateCall(r){return gn(r.contract,Uh,"vsr")}decodeLiveRate(r){let n=Gr(r);if(n===null||n<=0n)return null;let i=Number(n-IB)/H0;return i>-1?Ny(Math.expm1(Math.log1p(i)*OB)):null}},dO=class extends Lh{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,od,"getAPR")}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ny(Math.expm1(Number(n)/H0))}convertToAssetsCall(r){return gn(r.contract,od,"getConversionRate")}fetchApy(r,n,i){return mO(r,n,i)}};function qh(t,e,r,n){if(e<=0n||!Number.isInteger(r)||!Number.isInteger(n)||r<0||n<0)return null;let i=t*e/IB,o=n-r;return o===0?i:o>0?i*10n**BigInt(o):i/10n**BigInt(-o)}var pO=class extends Lh{constructor(){super(...arguments);f(this,"type","aave-v3");f(this,"balanceIsUnderlying",!0)}underlyingCall(r){return gn(r.token,Dh,"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 Ny(RB(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:Eae,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:Cae(s.data?.data?.reserve?.incentives)}}},hO=class extends Lh{constructor(){super(...arguments);f(this,"type","compound-v3");f(this,"balanceIsUnderlying",!0)}underlyingCall(r){return gn(r.contract,id,"baseToken")}sizeCall(r){return gn(r.token,Zt,"totalSupply")}liveRateCall(r){return gn(r.contract,id,"getUtilization")}followUpRateCall(r,n){let i=Gr(n);return i===null?null:gn(r.contract,id,"getSupplyRate",[i])}decodeLiveRate(r){let n=Gr(r);return n===null?null:Ny(Number(n)/1e18*OB)}fetchApy(r,n,i){return mO(r,n,i)}},fO=class extends Ry{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:xae,variables:{address:r.contract,chainId:n.chainId,options:{startTimestamp:o-xB*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 mO(t,e,r){let n=`${r.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${t.token}?range=h&day=${xB}`,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 NB={"aave-v3":new pO,"compound-v3":new hO,spark:new cO,"spark-ethereum":new uO,"spark-l2-susds":new dO,"morpho-v2":new fO},Iae=NB.spark;function ad(t){return NB[t.type]??Iae}var Oae={"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 Oae[t]??null}var Rae={"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 Rae[t]??null}function mc(t,e){return Number(t)/10**e}function G0(t){return new Date(t).toISOString().slice(0,10)}var Nae=6e4,gO=new Map;async function My(t,e){let r=sl(e),n=r?parseInt(r,16):NaN;if(!r||!Number.isFinite(n))return[];let i=`${t}|${r}`,o=gO.get(i);if(o&&Date.now()-o.at<Nae)return o.markets;let a=Mae(t,r,n),s=a.then(l=>l.markets);return gO.set(i,{at:Date.now(),markets:s}),a.then(l=>{l.answered||gO.delete(i)}),s}async function W0(t,e){return(await My(t,e)).length>0}async function Mae(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=$ae(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 MB(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 $ae(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 yO(){return ii()}async function K0(t){let e=yO(),r=await Promise.all(e.map(n=>W0(t,n)));return e.filter((n,i)=>r[i])}async function Y0(t,e){let r=_t(e);return r?W0(t,r):!1}async function $B(t,e){let r=e.map(o=>_t(o)).filter(o=>!!o),n=[...new Set(r)],i=await Promise.all(n.map(o=>W0(t,o)));return n.filter((o,a)=>i[a])}p();p();var Dae={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function J0(t){let e=sl(t);return e?Dae[e]??null:null}function DB(t){return["susds","usds","rateProvider"].map(e=>({target:t,callData:gt({abi:lO,functionName:e})}))}var UB=3,Uae={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function _O(t){let e=sl(t),r=e?Uae[e]:void 0;return r?{target:r,callData:gt({abi:od,functionName:"getConversionRate"})}:null}function jh(t){return Z0(t)}var LB=5;async function qB(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=J0(t),o;try{ut("discovery: probing 5 accessors per token",{chain:t,tokens:n,psm:i}),o=await ni(t,[...n.flatMap(b=>b?Lae(b):[]),...i?DB(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-UB):[],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+LB);return d+=LB,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 qae(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 jae(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 Lae(t){return[{target:t,callData:gt({abi:Dh,functionName:"POOL"})},{target:t,callData:gt({abi:Dh,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:t,callData:gt({abi:id,functionName:"baseToken"})},{target:t,callData:gt({abi:pa,functionName:"asset"})},{target:t,callData:gt({abi:Uh,functionName:"vsr"})}]}async function qae(t,e){if(e.length===0)return new Set;try{let r=await ni(t,e.map(n=>({target:n,callData:gt({abi:sO,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,i)=>rr(r[i])!==null))}catch{return new Set}}async function jae(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 Fae=.01;function Bae(t){return t.reduce((e,r)=>r.conditions===null?e+r.apyPercent:e,0)}function zae(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&&zae(o,n);let a=o?Iy(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 qB(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 $B(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?Iy(n):null;return n&&i?this.describer.describe(n,i,r):[]}async positionsForChain(e,r){let n=Iy(e),i=await My(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<Fae?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Bae(l.rewards))/100}]})}};p();var bO=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Bh=class{constructor(e){f(this,"coinPoolBaseUrl",e)}async listChains(){return K0(this.coinPoolBaseUrl)}async isSupported(e){return Y0(this.coinPoolBaseUrl,e)}async getMarkets(e){let r=_t(e);return r?My(this.coinPoolBaseUrl,r):[]}async findMarket(e,r){let n=await this.getMarkets(e);return MB(n,r)}canSupply(e){return bO.includes(e.type)}async readReceiptToken(e,r){let n=ad(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 Vae={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Hae={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"},Zae={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Gae={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function X0(t){let e=tse(t.chain);return(e===null?null:Wae(t,e))??Z0(t.type)??ese(t,e)}function Wae(t,e){switch(t.type){case"morpho-v2":{let r=Vae[e];if(!r||!t.contract)return null;let n=`https://app.morpho.org/${r}/vault/${vO(t.contract)}`,i=Jae(t.name);return i?`${n}/${i}`:n}case"aave-v3":{let r=Hae[e],n=Kae(t);return!r||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${vO(n)}&marketName=${r}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let r=Zae[e],n=Qae(t);return!r||!n?null:`https://app.spark.fi/savings/${r}/${n}`}case"compound-v3":{let r=Gae[e],n=Xae(t);return!r||!n?null:`https://app.compound.finance/?market=${n}-${r}`}default:return null}}function Kae(t){let e=t.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Yae=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Jae(t){let e=t?.trim().toLowerCase()||"";return!e||Yae.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Xae(t){let e=t.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Qae(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 ese(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",vO(t.contract)),i.toString()}catch{return n}}function vO(t){let e=t.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function tse(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 rse=8;function nse(t,e,r){if(t.market.type!=="spark-l2-susds")return Gr(e);let n=Gr(e);return n===null||t.tokenDecimals===null?null:qh(t.rawBalance,n,t.tokenDecimals,r)}var Q0=class{constructor(e){f(this,"endpoints",e);f(this,"apyLimiter",new wO(rse));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=ose(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:X0({...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=ad(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=nse(s,a[o[l]],c);return u===null?mc(s.rawBalance,s.tokenDecimals??c):mc(u,c)})}async resolveAssets(e,r){let n={address:nd,decimals:NaN,symbol:null,logo:null},i=[],o=r.map(u=>{let d=ad(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=ad(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 ad(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:[]}}}},wO=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 ise(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 ose(t,e,r=[]){let{history:n,live:i}=ise(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:sse(n,o),...c}}var jB=3600*1e3,ase=jB/2;function sse(t,e){if(e===null)return null;let r=Date.now()-jB,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>ase?null:e-n.apyPercent}function FB(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 Q0(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 $y="{market}",VB=[{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}],tS=[{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}],HB="[[LIST]]",ZB=' 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.',GB=' 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 WB(t,e,r){let[n]=lse([t],e,r),[i]=t.canSupply?SO(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 lse(t,e,r){return KB(t,{labelTemplate:eS(e.detail_button_label),promptTemplate:eS(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${$y}`,...r===void 0?{}:{chainName:r}})}function SO(t,e,r){return KB([t],{labelTemplate:eS(e.supply_button_label),promptTemplate:eS(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${$y}`,promptFallback:`supply to ${$y}`,...r===void 0?{}:{chainName:r},max:1})}function KB(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:BB(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:BB(cse(e.promptTemplate),a,e.promptFallback)+use(o.contract,r)}))}return n}function cse(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 eS(t){return typeof t=="string"?t:""}function use(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 BB(t,e,r,n=!0){let o=t&&(!n||t.includes($y))?t:r;return dse(o).split($y).join(e).replace(/\s+/g," ").trim()}var zB="{chain}";function dse(t){if(!t.includes(zB))return t;let e=zB.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 rS=[{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"]}],TO=rS.map(t=>t.label),kO={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 YB(t){let e=typeof t=="string"?t.trim():"";if(!e)return{kind:"none"};let r=mse(e);if(!r)return{kind:"none"};let n=pse(r);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let i=fse(r);return i?{kind:"unsupported",label:i,requested:e}:{kind:"unknown",requested:e}}function pse(t){let e=rS.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=rS.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 hse(t)}function hse(t){let e=null,r=!1;for(let n of rS)for(let i of n.aliases){let o=JB(i);if(o===0||Math.abs(i.length-t.length)>o)continue;let a=XB(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 JB(t){return t.length<=4?0:t.length<=9?2:3}function fse(t){let e=kO[t];if(e)return e;if(t.length>=4){let i=new Set(Object.entries(kO).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(kO)){let a=JB(i);if(a===0||Math.abs(i.length-t.length)>a)continue;let s=XB(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 mse(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function XB(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:FB(t,e)}var Dn=2,gc=2;function nS(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 gse=["apy","score","size"],QB=3,e4=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: ${TO.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-${e4}. Default ${QB} \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},...VB,...tS]);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=YB(r.protocol);if(c.kind==="unsupported"||c.kind==="unknown")return this.unsupportedProtocol(c);let u=a?[a]:l,d=_se(r.sort),h=bse(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(yse[d]).slice(0,h),_=y.map(S=>WB({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:[...TO],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 ${HB} 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?ZB:""].filter(Boolean).join(" ")}},yse={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 _se(t){let e=typeof t=="string"?t.trim().toLowerCase():"";return gse.includes(e)?e:"apy"}function bse(t){let e=typeof t=="number"?t:Number(t);return!Number.isFinite(e)||e<1?QB:Math.min(Math.floor(e),e4)}p();p();function t4(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 iS(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},...tS]);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=iS(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?SO({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),...nS(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=t4(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?GB:""].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:vse(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),...nS(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 vse(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=iS(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=wse(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=Sse(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??X0(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 wse(t){let e=t?.asset;return!e?.address||e.address===nd||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Sse(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 oS="https://ipfs.pantograph.app/ipfs/",r4=/^(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?`${oS}${r[1]}`:r4.test(e)?`${oS}${e}`:null}function n4(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?`${oS}${r[1]}`:r4.test(e)?`${oS}${e}`:null}function i4(t){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(t)}function PO(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 kse(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 Tse(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)?kse(n):decodeURIComponent(n);return JSON.parse(i)}catch{try{return JSON.parse(n)}catch{return null}}}function o4(t){let e=t?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let r=Tse(e);return r?sd(PO(r)):null}p();var Pse=12,Ase=6e3;async function Ese(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 Cse(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 xse(t,e){let r=t?.trim();if(!r)return null;if(/^data:/i.test(r))return o4(r);let n=n4(r);if(!n)return null;if(i4(n))return n;let i=await Cse(n,e);if(i){let o=sd(PO(i));if(o)return o}return null}async function aS(t,e,r){if(e.length===0)return[];let n=r?.concurrency??Pse,i=r?.timeoutMs??Ase,o=await iB(t,e,r?.rpcUrl);return Ese(o,n,a=>xse(a,i))}var a4=100,Ise=100,Gh="{name}",s4="{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=Dse(r.contract_address),l=u4(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:a4});return{chain:u,rows:d.success?l4(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:Rse(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=Mse(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:a4,...a?{tokenAddresses:[a]}:{}});return{chain:g,rows:y.success?l4(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=>Ose(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=Nse(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 aS(o,s);a.forEach((c,u)=>{n[c]=l[u]??null})}))}catch{}return n}};function l4(t){return t.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Ose(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 Rse(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 Nse(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 Mse(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>=Ise)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",s=a?`show my ${Gh} NFTs on ${s4}`:`show my ${Gh} NFTs`,l=c4(n,{[Gh]:o.name,[s4]:a},s);a&&!l.includes(a)&&(l=`${l} (${a})`),i.push({label:$se(r,o.name,Gh),prompt:`${l} (${o.contractAddress})`})}return i}function c4(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 $se(t,e,r){return c4(t,{[Gh]:e},r)}function u4(t){if(typeof t!="string")return;let e=t.trim();return e||void 0}function Dse(t){let e=u4(t);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}p();p();var Use="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:Use,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 AO={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"},EO="amazon.com";function Lse(t){return t?t.trim().toLowerCase().split(/[-_]/)[0]:""}function CO(t){let e=Lse(t);return AO[e]??EO}function sS(t){return`https://${CO(t)}/s?k=NFC%20Tag`}p();function lS(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 qse=720*60*1e3,d4=new Map,p4=3;function jse(t){return[`A user in country "${t}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${p4} 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 Fse(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>=p4))break}return i}async function xO(t,e){let r=lS(t);if(!r||!e)return null;let n=d4.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:jse(r),timestamp:i}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=Fse(a.text);if(s.length)return d4.set(r,{links:s,expires:Date.now()+qse}),s}catch{}return null}async function Jh(t){let e=await xO(t.country,t.llm);return e&&e.length?e:[{label:"Amazon",url:sS(t.language)}]}function Bse(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
473
  `)}var h4=["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
474
  `),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=Bse(o),s=o.length>1;return{reference:h4,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
475
  ${a}