keyring-agent-core 0.2.56 → 0.2.58

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=Ao(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&sy.assertOptions(n,{silentJSONParsing:Fi.transitional(Fi.boolean),forcedJSONParsing:Fi.transitional(Fi.boolean),clarifyTimeoutError:Fi.transitional(Fi.boolean),legacyInterceptorReqResOrdering:Fi.transitional(Fi.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:sy.assertOptions(i,{encode:Fi.function,serialize:Fi.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),sy.assertOptions(r,{baseUrl:Fi.spelling("baseURL"),withXsrfToken:Fi.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=Sr.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||Ip;_&&_.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,f;if(!l){let g=[c0.bind(this),void 0];for(g.unshift(...s),g.push(...c),f=g.length,u=Promise.resolve(r);d<f;)u=u.then(g[d++],g[d++]);return u}f=s.length;let m=r;for(;d<f;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{u=c0.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,f=c.length;d<f;)u=u.then(c[d++],c[d++]);return u}getUri(e){e=Ao(this.defaults,e);let r=ay(e.baseURL,e.url,e.allowAbsoluteUrls);return ry(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){Mp.prototype[e]=function(r,n){return this.request(Ao(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(Ao(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Mp.prototype[e]=r(),e!=="query"&&(Mp.prototype[e+"Form"]=r(!0))});var ly=Mp;p();var Xx=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 oa(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}}},nF=Xx;p();function Qx(t){return function(r){return t.apply(null,r)}}p();function eI(t){return j.isObject(t)&&t.isAxiosError===!0}p();var tI={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(tI).forEach(([t,e])=>{tI[e]=t});var iF=tI;function oF(t){let e=new ly(t),r=Jg(ly.prototype.request,e);return j.extend(r,ly.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return oF(Ao(t,i))},r}var Or=oF(Rp);Or.Axios=ly;Or.CanceledError=oa;Or.CancelToken=nF;Or.isCancel=iy;Or.VERSION=$p;Or.toFormData=Gl;Or.AxiosError=De;Or.Cancel=Or.CanceledError;Or.all=function(e){return Promise.all(e)};Or.spread=Qx;Or.isAxiosError=eI;Or.mergeConfig=Ao;Or.AxiosHeaders=Sr;Or.formToJSON=t=>o0(j.isHTMLForm(t)?new FormData(t):t);Or.getAdapter=l0.getAdapter;Or.HttpStatusCode=iF;Or.default=Or;var d0=Or;var{Axios:SWe,AxiosError:TWe,CanceledError:kWe,isCancel:PWe,CancelToken:AWe,VERSION:CWe,all:EWe,Cancel:xWe,isAxiosError:IWe,spread:OWe,toFormData:RWe,AxiosHeaders:NWe,HttpStatusCode:$We,formToJSON:MWe,getAdapter:DWe,mergeConfig:UWe,create:LWe}=d0;var aF="0.2.56";var mie=`keyring-agent-core/${aF} (Keyring Chatbot Agent; +https://keyring.app)`,rI=null;function sF(t){rI=t}var gie=["payment-signature","x-payment"];function yie(t){return t?Object.keys(t).some(e=>gie.includes(e.toLowerCase())):!1}var lF;function cy(t){lF=t}var _ie=3e4,bie=typeof process<"u"&&process.versions?.node!=null,nI=class{constructor(e={}){h(this,"instance");this.instance=d0.create({baseURL:e.baseURL,timeout:e.timeout??_ie,validateStatus:()=>!0,headers:{Accept:"application/json",...bie?{"User-Agent":e.userAgent??mie}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??lF,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&&rI&&!yie(i.headers)){let c=await rI(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 nI;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 vie(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??vie(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=Ao(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&sy.assertOptions(n,{silentJSONParsing:Fi.transitional(Fi.boolean),forcedJSONParsing:Fi.transitional(Fi.boolean),clarifyTimeoutError:Fi.transitional(Fi.boolean),legacyInterceptorReqResOrdering:Fi.transitional(Fi.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:sy.assertOptions(i,{encode:Fi.function,serialize:Fi.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),sy.assertOptions(r,{baseUrl:Fi.spelling("baseURL"),withXsrfToken:Fi.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=Sr.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||Ip;_&&_.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,f;if(!l){let g=[c0.bind(this),void 0];for(g.unshift(...s),g.push(...c),f=g.length,u=Promise.resolve(r);d<f;)u=u.then(g[d++],g[d++]);return u}f=s.length;let m=r;for(;d<f;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{u=c0.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,f=c.length;d<f;)u=u.then(c[d++],c[d++]);return u}getUri(e){e=Ao(this.defaults,e);let r=ay(e.baseURL,e.url,e.allowAbsoluteUrls);return ry(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){Mp.prototype[e]=function(r,n){return this.request(Ao(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(Ao(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Mp.prototype[e]=r(),e!=="query"&&(Mp.prototype[e+"Form"]=r(!0))});var ly=Mp;p();var Xx=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 oa(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}}},nF=Xx;p();function Qx(t){return function(r){return t.apply(null,r)}}p();function eI(t){return j.isObject(t)&&t.isAxiosError===!0}p();var tI={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(tI).forEach(([t,e])=>{tI[e]=t});var iF=tI;function oF(t){let e=new ly(t),r=Jg(ly.prototype.request,e);return j.extend(r,ly.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return oF(Ao(t,i))},r}var Or=oF(Rp);Or.Axios=ly;Or.CanceledError=oa;Or.CancelToken=nF;Or.isCancel=iy;Or.VERSION=$p;Or.toFormData=Gl;Or.AxiosError=De;Or.Cancel=Or.CanceledError;Or.all=function(e){return Promise.all(e)};Or.spread=Qx;Or.isAxiosError=eI;Or.mergeConfig=Ao;Or.AxiosHeaders=Sr;Or.formToJSON=t=>o0(j.isHTMLForm(t)?new FormData(t):t);Or.getAdapter=l0.getAdapter;Or.HttpStatusCode=iF;Or.default=Or;var d0=Or;var{Axios:SWe,AxiosError:TWe,CanceledError:kWe,isCancel:PWe,CancelToken:AWe,VERSION:CWe,all:EWe,Cancel:xWe,isAxiosError:IWe,spread:OWe,toFormData:RWe,AxiosHeaders:NWe,HttpStatusCode:$We,formToJSON:MWe,getAdapter:DWe,mergeConfig:UWe,create:LWe}=d0;var aF="0.2.58";var mie=`keyring-agent-core/${aF} (Keyring Chatbot Agent; +https://keyring.app)`,rI=null;function sF(t){rI=t}var gie=["payment-signature","x-payment"];function yie(t){return t?Object.keys(t).some(e=>gie.includes(e.toLowerCase())):!1}var lF;function cy(t){lF=t}var _ie=3e4,bie=typeof process<"u"&&process.versions?.node!=null,nI=class{constructor(e={}){h(this,"instance");this.instance=d0.create({baseURL:e.baseURL,timeout:e.timeout??_ie,validateStatus:()=>!0,headers:{Accept:"application/json",...bie?{"User-Agent":e.userAgent??mie}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??lF,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&&rI&&!yie(i.headers)){let c=await rI(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 nI;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 vie(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??vie(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);h(this,"name","BaseError");h(this,"shortMessage");h(this,"details");h(this,"metaMessages");this.shortMessage=r,this.details=i,this.metaMessages=o,n.name&&(this.name=n.name)}walk(r){return cF(this,r)}};function cF(t,e){if(e?.(t))return t;let r=t&&typeof t=="object"?t.cause:void 0;return r!=null?cF(r,e):e?null:t}var Wl=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."]});h(this,"name","AbiParameterTypeError")}},p0=class extends yt{constructor({expectedLength:r,givenLength:n}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${r}`,`Given length (values): ${n}`]});h(this,"name","AbiEncodingLengthMismatchError")}},f0=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}`]});h(this,"name","AbiEncodingArrayLengthMismatchError")}},Co=class extends yt{constructor({type:r,value:n,reason:i}){super(`Invalid value for ABI type "${r}".`,{metaMessages:[`Value: ${uF(n)}`,`Reason: ${i}`]});h(this,"name","InvalidAbiValueError")}},h0=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}`]});h(this,"name","IntegerOutOfRangeError")}},Dp=class extends yt{constructor(r){super(`Address "${uF(r)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]});h(this,"name","InvalidAddressError")}};function uF(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 m0=class extends yt{constructor({expectedSize:r,value:n}){super(`Size of bytes "${n}" does not match expected size of bytes${r}.`);h(this,"name","AbiEncodingBytesSizeMismatchError")}},Kl=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."]});h(this,"name","AbiDecodingZeroDataError")}},g0=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)`]});h(this,"name","AbiDecodingDataSizeTooSmallError");h(this,"data");h(this,"params");h(this,"size");this.data=r,this.params=n,this.size=i}},Up=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."]});h(this,"name","AbiDecodingOutOfBoundsError")}},y0=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."]});h(this,"name","AbiItemNotFoundError")}},Yl=class extends yt{constructor(r,n){super(`Invalid ABI signature: "${r}".`,{metaMessages:n?[n]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']});h(this,"name","InvalidAbiSignatureError")}};p();var wie=/^0x[0-9a-fA-F]*$/;function Fu(t,{strict:e=!0}={}){return typeof t!="string"?!1:e?wie.test(t):t.startsWith("0x")}function aa(t){return t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t}function uy(t){return typeof t=="string"?Math.ceil(aa(t).length/2):t.length}function Bu(t,e,r){let n=aa(t),i=(e??0)*2,o=r===void 0?n.length:r*2;return`0x${n.slice(i,o)}`}function _0(t){return`0x${t.map(aa).join("")}`}function zu(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 Jl(t){let e=aa(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 tl(t){let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return`0x${e}`}function iI(t){return new TextEncoder().encode(t)}function oI(t){return new TextDecoder().decode(t)}function Qn(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 aI(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 sI(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 Vu(t){let e=1n<<256n,r=(t%e+e)%e;return Jl(r.toString(16).padStart(64,"0"))}function Lp(t,{signed:e=!1}={}){let r=BigInt(tl(t));if(!e)return r;let n=BigInt(t.length*8);return r>=1n<<n-1n?r-(1n<<n):r}function Eo(t,{signed:e=!1}={}){return aa(t)?Lp(Jl(t),{signed:e}):0n}function b0(t,e={}){return Number(Eo(t,e))}p();var dF=Lg(dy());var Sie=/^0x[0-9a-fA-F]{40}$/;function Ve(t){return typeof t=="string"&&Sie.test(t)}function qp(t){let e=aa(t).toLowerCase(),r=(0,dF.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 lI(t){if(!Ve(t))throw new Error(`Address "${t}" is invalid.`);return qp(t)}function cI(t,e){return Ve(t)&&Ve(e)&&t.toLowerCase()===e.toLowerCase()}p();var uI=Lg(dy());function pF(t){return`0x${(0,uI.keccak_256)(new TextEncoder().encode(t))}`}function Xl(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Ql(t){return t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function py(t){let e=Ql(t.type);return e==="tuple"||e.startsWith("tuple[")?`(${(t.components??[]).map(py).join(",")})${e.slice(5)}`:e}function jp(t){return`${t.name??""}(${(t.inputs??[]).map(py).join(",")})`}function rl(t){let e=typeof t=="string"?t:jp(t);return`0x${(0,uI.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function dI(t){let e=typeof t=="string"?t:jp(t);return pF(e)}function fF(t,e){let r=Ql(e.type),n=Xl(r);if(n){let[i,o]=n;return!Array.isArray(t)||i!==null&&t.length!==i?!1:t.every(a=>fF(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 ec({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=>rl(s)===e.toLowerCase());if(e.includes("("))return o.find(s=>jp(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)=>fF(r[u],c))})??a[0]}function Hu(t){let e=ec(t);if(!e)throw new y0({name:t.name,type:t.type??"function"});return e}p();function hF(t){let e=new Uint8Array(Math.ceil(t.length/32)*32);return e.set(t),{dynamic:!0,encoded:zu([Vu(BigInt(t.length)),e])}}function mF(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 Wl(t);return n}function gF(t,e){if(typeof t=="bigint")return t;if(typeof t=="number"){if(!Number.isInteger(t))throw new Co({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 Co({type:e,value:t,reason:"string is not a valid integer"})}throw new Co({type:e,value:t,reason:"expected a bigint, number or numeric string"})}function yF(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 h0({type:n,value:t,min:o,max:i})}function _F(t,e){if(t instanceof Uint8Array)return t;if(typeof t=="string"){if(!Fu(t))throw new Co({type:e,value:t,reason:"expected 0x-prefixed hex"});return Jl(t)}throw new Co({type:e,value:t,reason:"expected a hex string or Uint8Array"})}function pI(t,e){let r=Xl(t.type);if(r){let[i,o]=r;if(!Array.isArray(e))throw new Co({type:t.type,value:e,reason:"expected an array"});return Tie({...t,type:o},e,i,t.type)}if(t.type==="tuple")return kie(t,e);let n=Ql(t.type);if(n==="address"){if(!Ve(e))throw new Dp(e);return{dynamic:!1,encoded:aI(Jl(aa(e).toLowerCase()))}}if(n==="bool"){if(typeof e!="boolean")throw new Co({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=gF(e,n);return yF(i,{bits:mF(n,"uint"),signed:!1,type:n}),{dynamic:!1,encoded:Vu(i)}}if(/^int\d*$/.test(n)){let i=gF(e,n);return yF(i,{bits:mF(n,"int"),signed:!0,type:n}),i<0n&&(i+=1n<<256n),{dynamic:!1,encoded:Vu(i)}}if(/^bytes\d+$/.test(n)){let i=Number(n.slice(5));if(i<1||i>32)throw new Wl(t.type);let o=_F(e,n);if(o.length!==i)throw new m0({expectedSize:i,value:String(e)});return{dynamic:!1,encoded:sI(o)}}if(n==="bytes")return hF(_F(e,n));if(n==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new Co({type:n,value:e,reason:"expected a string"});return hF(typeof e=="string"?iI(e):e)}throw new Wl(t.type)}function fI(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(Vu(BigInt(e+i))),n.push(a),i+=a.length):r.push(a);return zu([...r,...n])}function Tie(t,e,r,n){let i=r===null;if(!i&&e.length!==r)throw new f0({expectedLength:r,givenLength:e.length,type:n});let o=!1,a=[];for(let s of e){let l=pI(t,s);l.dynamic&&(o=!0),a.push(l)}if(i||o){let s=fI(a);if(!i)return{dynamic:!0,encoded:s};let l=Vu(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?zu([l,s]):l}}return{dynamic:!1,encoded:zu(a.map(s=>s.encoded))}}function kie(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=pI(a,Array.isArray(e)?e[o]:e[a.name??""]);s.dynamic&&(n=!0),i.push(s)}return{dynamic:n,encoded:n?fI(i):zu(i.map(o=>o.encoded))}}function Fp(t,e){if(t.length!==e.length)throw new p0({expectedLength:t.length,givenLength:e.length});return t.length===0?"0x":tl(fI(t.map((r,n)=>pI(r,e[n]))))}p();function gt({abi:t,functionName:e,args:r=[]}){let n=Hu({abi:t,name:e,args:r,type:"function"}),i=rl(n),o=n.inputs??[];return o.length===0?i:_0([i,Fp(o,r)])}function hI({abi:t,errorName:e,args:r=[]}){let n=Hu({abi:t,name:e,args:r,type:"error"}),i=n.inputs??[],o=rl(n);return i.length===0?o:_0([o,Fp(i,r)])}p();function Pie(t){let e=t.replace(/^u?int/,"");return e?Number(e):256}function fy(t,e){if(e<0||e+32>t.length)throw new Up({position:e,length:t.length});return t.subarray(e,e+32)}function yI(t,e){let r=Lp(fy(t,e));if(r>BigInt(t.length))throw new Up({position:Number(r),length:t.length});return Number(r)}function mI(t){let e=Xl(t.type);if(e){let[n,i]=e;return n===null||mI({...t,type:i})}if(t.type==="tuple")return(t.components??[]).some(mI);let r=Ql(t.type);return r==="bytes"||r==="string"}function gI(t){let e=Xl(t.type);if(e){let[r,n]=e;return r===null?32:r*gI({...t,type:n})}return t.type==="tuple"?(t.components??[]).reduce((r,n)=>r+gI(n),0):32}function _I(t,e,r){let n=[],i=e;for(let o of r)mI(o)?(n.push(bF(t,e+yI(t,i),o)),i+=32):(n.push(bF(t,i,o)),i+=gI(o));return n}function Aie(t,e,r,n){let i=n===null?yI(t,e):n,o=n===null?e+32:e;return _I(t,o,new Array(i).fill(r))}function Cie(t,e,r){let n=r.components??[],i=_I(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 bF(t,e,r){let n=Xl(r.type);if(n){let[o,a]=n;return Aie(t,e,{...r,type:a},o)}if(r.type==="tuple")return Cie(t,e,r);let i=Ql(r.type);if(i==="address")return qp(tl(fy(t,e).subarray(12)));if(i==="bool")return Lp(fy(t,e))!==0n;if(/^u?int\d*$/.test(i)){let o=i.startsWith("int"),a=Lp(fy(t,e),{signed:o});return Pie(i)>48?a:Number(a)}if(/^bytes\d+$/.test(i)){let o=Number(i.slice(5));return tl(fy(t,e).subarray(0,o))}if(i==="bytes"||i==="string"){let o=yI(t,e),a=e+32;if(a+o>t.length)throw new Up({position:a+o,length:t.length});let s=t.subarray(a,a+o);return i==="bytes"?tl(s):oI(s)}throw new Wl(r.type)}function Nn(t,e){let r=typeof e=="string"?Jl(e):e;if(r.length===0){if(t.length>0)throw new Kl;return[]}if(r.length<32)throw new g0({data:typeof e=="string"?e:tl(e),params:t,size:r.length});return _I(r,0,t)}p();function Zr(t){if(!t)return null;try{let[e]=Nn([{type:"uint256"}],t);return e}catch{return null}}function rr(t){if(!t)return null;try{let[e]=Nn([{type:"address"}],t),r=e;return/^0x0{40}$/i.test(r)?null:r}catch{return null}}function hy(t){if(!t)return null;try{let[e]=Nn([{type:"string"}],t),r=vF(e);if(r)return r}catch{}try{let[e]=Nn([{type:"bytes32"}],t);return S0(e)}catch{return null}}function Bp(t){return w0(Zr(t))}function w0(t){let e=typeof t=="bigint"?Number(t):typeof t=="number"?t:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function S0(t){return typeof t!="string"||!t.startsWith("0x")?null:vF(Buffer.from(t.slice(2),"hex").toString("utf8"))||null}function vF(t){return t.replace(/[^\x20-\x7e]/g,"").trim()}p();function sa({abi:t,functionName:e,args:r,data:n}){let o=Hu({abi:t,name:e,args:r,type:"function"}).outputs??[],a=Nn(o,n);if(a.length!==0)return a.length===1?a[0]:a}function bI({abi:t,data:e}){let r=Bu(e,0,4),n=Hu({abi:t,name:r,type:"function"}),i=n.inputs??[];return{functionName:n.name,args:i.length===0||uy(e)<=4?[]:Nn(i,Bu(e,4))}}p();var wF={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},SF={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},TF={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 zp({abi:t=[],data:e}){let r=Bu(e,0,4);if(uy(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let n=[...t,wF,SF],i=ec({abi:n,name:r,type:"error"})??n.find(a=>(a.type??"")==="error"&&rl(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?Nn(o,Bu(e,4)):void 0}}function my({abi:t,data:e}){if(!(!e||e==="0x"))try{let{errorName:r,args:n}=zp({abi:t,data:e});if(r==="Error")return String(n?.[0]??"");if(r==="Panic"){let i=Number(n?.[0]??0);return TF[i]??`Panic code ${i}.`}return!n||n.length===0?r:`${r}(${n.map(i=>String(i)).join(", ")})`}catch{return}}p();var Eie=new Set(["pure","view","nonpayable","payable"]),xie=new Set(["external","public","internal","private","calldata","memory","storage"]);function wI(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 Yl(t,"Unbalanced parentheses.")}function PF(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 Iie(t){let e=t.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function kF(t,e){let r=!1,n;for(let i of t)i==="indexed"?r=!0:xie.has(i)||(n=i);return{...e,...n?{name:n}:{},...r?{indexed:!0}:{}}}function SI(t){let e=t.trim();if(e.startsWith("(")){let i=wI(e,0),o=PF(e.slice(1,i)).map(SI),{suffix:a,rest:s}=Iie(e.slice(i+1).trim());return kF(s.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:o})}let[r,...n]=e.split(/\s+/).filter(Boolean);if(!r)throw new Yl(t,"Missing parameter type.");return kF(n,{type:r})}function yy(t){return PF(t).map(SI)}function gy(t,e,r){let n=t.indexOf("(",e);if(n===-1)throw new Yl(r,"Missing parameter list.");let i=wI(t,n);return{name:t.slice(e,n).trim(),params:yy(t.slice(n+1,i)),rest:t.slice(i+1).trim()}}function vI(t,e){return t.split(/[\s()]+/).find(n=>Eie.has(n))??e}function T0(t){let e=t.trim();if(e.startsWith("function ")){let{name:r,params:n,rest:i}=gy(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 Yl(t,"`returns` without a parameter list.");s=yy(i.slice(l+1,wI(i,l)))}return{type:"function",name:r,inputs:n,outputs:s,stateMutability:vI(a,"nonpayable")}}if(e.startsWith("event ")){let{name:r,params:n}=gy(e,6,t);return{type:"event",name:r,inputs:n}}if(e.startsWith("error ")){let{name:r,params:n}=gy(e,6,t);return{type:"error",name:r,inputs:n}}if(e.startsWith("constructor")){let{params:r,rest:n}=gy(e,11,t);return{type:"constructor",inputs:r,stateMutability:vI(n,"nonpayable")}}if(e.startsWith("fallback")){let{rest:r}=gy(e,8,t);return{type:"fallback",stateMutability:vI(r,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new Yl(t,"Expected function, event, error, constructor, fallback or receive.")}function TI(t){return t.map(T0)}p();p();p();p();function la({blockNumber:t,blockTag:e="latest"}={}){return t!==void 0?Qn(t):e}function _y(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=Qn(i)),o!==void 0&&(u.gas=Qn(o)),a!==void 0&&(u.gasPrice=Qn(a)),s!==void 0&&(u.maxFeePerGas=Qn(s)),l!==void 0&&(u.maxPriorityFeePerGas=Qn(l)),c!==void 0&&(u.nonce=Qn(c)),u}function kI(t){let e={};for(let[r,n]of Object.entries(t)){let i={};n.balance!==void 0&&(i.balance=Qn(n.balance)),n.nonce!==void 0&&(i.nonce=Qn(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 Vp(t){return Eo(await t.request({method:"eth_blockNumber"}))}async function Hp(t){return b0(await t.request({method:"eth_chainId"}))}async function Zp(t,{address:e,...r}){return Eo(await t.request({method:"eth_getBalance",params:[e,la(r)]}))}async function tc(t,{address:e,...r}){let n=await t.request({method:"eth_getCode",params:[e,la(r)]});return!n||n==="0x"?void 0:n}async function Gp(t,{address:e,slot:r,...n}){return await t.request({method:"eth_getStorageAt",params:[e,r,la(n)]})??void 0}async function Wp(t,{address:e,...r}){return b0(await t.request({method:"eth_getTransactionCount",params:[e,la(r)]}))}async function Kp(t){return Eo(await t.request({method:"eth_gasPrice"}))}async function k0(t){return Eo(await t.request({method:"eth_maxPriorityFeePerGas"}))}async function Yp(t,{blockNumber:e,blockTag:r,...n}){return Eo(await t.request({method:"eth_estimateGas",params:[_y(n),la({blockNumber:e,blockTag:r})]}))}async function Jp(t,{includeTransactions:e=!1,...r}={}){let n=await t.request({method:"eth_getBlockByNumber",params:[la(r),e]});return n?{...n,blockNumber:n.number?Eo(n.number):void 0,blockTimestamp:n.timestamp?Eo(n.timestamp):void 0,baseFee:n.baseFeePerGas?Eo(n.baseFeePerGas):void 0}:null}p();var sr="0xcA11bde05977b3631167028862bE2a173976CA11",AF={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}}},CF={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}}},EF={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}}},xF={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}}},IF={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}}},OF={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}}},RF={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}}},NF={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}}},$F={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}}},MF={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}}},DF={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}}},UF={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:sr}}},Zu=[AF,CF,EF,xF,IF,OF,RF,NF,$F,MF,DF,UF];var LF=new Map,PI=new Map;function Oie(t,e){return`${t??"unknown"}|${e.toLowerCase()}`}async function qF(t,e=sr){let r=Oie(t.chain?.id??t.chain?.hexId,e),n=LF.get(r);if(n!==void 0)return n;let i=PI.get(r);if(i)return i;let o=(async()=>{try{let s=await tc(t,{address:e})!==void 0;return LF.set(r,s),s}catch{return!0}finally{PI.delete(r)}})();return PI.set(r,o),o}async function Gu(t,e,r=!1){return r||typeof t.batch?.multicall=="object"&&t.batch.multicall.assumeMulticall3?!0:qF(t,e)}p();p();var xo=[{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}]}],Xp=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];p();var Qp=[{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 P0=[{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 ca=[{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 ef=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`."]});h(this,"name","ChainNotFoundError")}},Wu=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."]});h(this,"name","ClientChainNotConfiguredError")}},rc=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."]});h(this,"name","ChainDoesNotSupportContractError")}};p();async function AI(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 by({blockNumber:t,chain:e,contract:r}){let n=e.contracts?.[r];if(!n)throw new rc({chain:e.name,contract:r});if(t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(t))throw new rc({blockNumber:t,chain:e.name,contract:r});return n.address}p();var tf=class extends yt{constructor({data:r,shortMessage:n="The contract call reverted."}){super(n);h(this,"name","RawContractError");h(this,"data");this.data=r}},CI=class extends yt{constructor({abi:r,data:n,functionName:i}){let o=n?my({abi:r,data:n}):void 0,a,s;if(n&&n!=="0x")try{let l=zp({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}`]:[]});h(this,"name","ContractFunctionRevertedError");h(this,"errorName");h(this,"errorArgs");h(this,"reason");h(this,"data");this.reason=o,this.errorName=a,this.errorArgs=s,this.data=n}},EI=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."]});h(this,"name","ContractFunctionZeroDataError")}},xI=class extends yt{constructor(r,{abi:n,address:i,args:o,functionName:a,sender:s}){let l=n&&a?ec({abi:n,name:a,args:o}):void 0,c=l?jp(l):a,u=o&&o.length>0?` args: (${o.map(f=>Rie(f)).join(", ")})`:void 0,d=l?.inputs?.length?`(${l.inputs.map(py).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}`]:[]]});h(this,"name","ContractFunctionExecutionError");h(this,"abi");h(this,"address");h(this,"args");h(this,"functionName");this.abi=n,this.address=i,this.args=o,this.functionName=a}},vy=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}`]:[]]});h(this,"name","CallExecutionError")}};function Rie(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 jF(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?jF(e.cause):void 0}function rf(t,{abi:e,address:r,args:n,functionName:i,sender:o}){let a=jF(t),s=t instanceof Kl?new EI({functionName:i}):a!==void 0?new CI({abi:e,data:a,functionName:i}):t;return new xI(s,{abi:e,address:r,args:n,functionName:i,sender:o})}p();var II=new Map;function wy({fn:t,id:e,shouldSplitBatch:r,wait:n=0}){let i=()=>II.get(e)??void 0,o=s=>II.set(e,s),a=async s=>{i()===s&&II.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 f=[u];o(f),setTimeout(()=>{a(f)},n)})}}}function Nie(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 $ie(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 Wu;let l=by({blockNumber:i,chain:t.chain,contract:"multicall3"});if(!await Gu(t,l,!1))throw new rc({chain:t.chain.name,contract:"multicall3"});let c=i!==void 0?Qn(i):o,{schedule:u}=wy({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:xo,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 sa({abi:xo,functionName:"aggregate3",data:y})}}),{returnData:d,success:f}=await u({data:a,to:s});if(!f)throw new tf({data:d});return d}async function ua(t,e){let{blockNumber:r,blockTag:n,stateOverride:i,skipBatch:o,...a}=e;if(t.batch?.multicall&&!o&&Nie(e))try{let l=await $ie(t,{blockNumber:r,blockTag:n,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof Wu||l instanceof rc))throw new vy(l,{to:a.to,data:a.data})}let s=[_y(a),la({blockNumber:r,blockTag:n})];i&&s.push(kI(i));try{let l=await t.request({method:"eth_call",params:s});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new vy(l,{to:a.to,data:a.data})}}var OI=8;function FF(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:OI}function Sy(t,e,r){if(e)return e;if(!t.chain)throw new Wu;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 nf(t,e,r={}){let{concurrency:n,account:i,blockNumber:o,blockTag:a,stateOverride:s}=r;return(await AI(e,FF(t,n),async c=>{let{data:u}=await ua(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 da(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 ua(t,{...a,to:n,data:s});return sa({abi:r,functionName:i,args:o,data:l??"0x"})}catch(s){throw rf(s,{abi:r,address:n,args:o,functionName:i,sender:a.account})}}var Mie=1024,Die=50;async function nc(t,e){let{calls:r,account:n,blockNumber:i,blockTag:o,batchSize:a=Mie,maxCalls:s=Die,multicallAddress:l,stateOverride:c,fallbackConcurrency:u}=e,d=r.map(()=>({success:!1,returnData:"0x"}));if(r.length===0)return d;let f=Sy(t,l,i),m=[];if(r.forEach((b,v)=>{Ve(b.target)&&Fu(b.callData)&&m.push({index:v,call:b})}),m.length===0)return d;if(!await Gu(t,f,l!==void 0))return(await nf(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,k=a>0&&y!==void 0&&y.size+S>a,E=s>0&&y!==void 0&&y.calls.length>=s;(!y||(k||E)&&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=>da(t,{abi:xo,address:f,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,k)=>{let E=b.value[k];E&&(d[S]={success:!!E.success,returnData:E.returnData??"0x"})})}),d}p();p();var BF="https://wallet-api.pantograph.app/keyring/chains_v6",Uie=6,Lie=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,zF={},of=null;function qie(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://")||Lie.test(o))&&(n.includes(o)||n.push(o),n.length>=Uie))break}return n}function VF(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=pa(r)??(typeof i.chainId=="number"?pa(i.chainId):void 0);if(!o)continue;let a=qie(i);a.length>0&&(e[o]=a)}return e}function HF(t){zF=t}function RI(t){let e=pa(t);return e?zF[e]??[]:[]}function NI(){of||A0()}function A0(t={}){let{url:e=BF,force:r=!1,debug:n=!1}=t;return of&&!r||(of=(async()=>{try{let i=await ve.get(e);if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=VF(i.data),a=Object.keys(o).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return HF(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 of=null,!1}})()),of}var jie=new Map(Zu.map(t=>[t.hexId.toLowerCase(),t])),Fie=new Map(Zu.map(t=>[t.id,t]));function pa(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 nl(t){if(typeof t=="number")return Fie.get(t);let e=pa(t);return e?jie.get(e):void 0}var Bi=Object.fromEntries(Zu.map(t=>[t.hexId,t.rpcUrls.default.http[0]]));function $I(t){return nl(t)?.rpcUrls.default.http[0]}var MI={};function Ku(t){let e={};if(t)for(let[r,n]of Object.entries(t)){if(typeof n!="string"||!n.trim())continue;let i=pa(r)??r.toLowerCase();e[i]=n.trim()}MI=e}function Ty(){return{...MI}}function Yu(t){NI();let e=pa(t),r=e?MI[e]:void 0,n=RI(t),i=nl(t)?.rpcUrls.default.http??[];return[...new Set([...r?[r]:[],...n,...i])]}function Ju(t){return Yu(t)[0]}function DI(t){let e=nl(t);if(!e)return;let r=Yu(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 ic=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)}`]:[]]});h(this,"name","HttpRequestError");h(this,"status");h(this,"url");h(this,"body");h(this,"headers");this.status=o,this.url=a,this.body=r,this.headers=i}},af=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)}`]:[]]});h(this,"name","TimeoutError")}},sf=class extends yt{constructor({cause:r,url:n}){super("Could not reach the RPC endpoint.",{cause:r,metaMessages:[`URL: ${n}`]});h(this,"name","NetworkError")}},C0=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.']});h(this,"name","UrlRequiredError")}},ky=class extends yt{constructor({cause:r,count:n}){super(`All ${n} fallback transports failed.`,{cause:r});h(this,"name","FallbackTransportError")}};p();p();var lf=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}`]});h(this,"name","RpcRequestError");h(this,"code");h(this,"data");this.code=n.code,this.data=n.data}};function zi(t,e,r){var n;return n=class extends lf{constructor(o){super({...o,shortMessage:r});h(this,"name",t)}},h(n,"code",e),n}var Bie=zi("ParseRpcError",-32700,"The node could not parse the JSON request."),zie=zi("InvalidRequestRpcError",-32600,"The JSON request is not valid."),Vie=zi("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),Hie=zi("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),Zie=zi("InternalRpcError",-32603,"The node reported an internal error."),Gie=zi("InvalidInputRpcError",-32e3,"The RPC input is not valid."),Wie=zi("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Kie=zi("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),Yie=zi("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),Jie=zi("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),UI=zi("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),Xie=zi("UserRejectedRequestError",4001,"The user rejected the request."),Qie=new Map([[-32700,Bie],[-32600,zie],[-32601,Vie],[-32602,Hie],[-32603,Zie],[-32e3,Gie],[-32001,Wie],[-32002,Kie],[-32003,Yie],[-32004,Jie],[-32005,UI],[4001,Xie]]);function ZF(t){let e=Qie.get(t.error.code);return e?new e(t):new lf(t)}p();function GF(t){return new Promise(e=>setTimeout(e,t))}async function LI(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 GF(a)}}function qI(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 eoe=new Set([408,413,429,500,502,503,504]),toe=new Set([401,402,403]);function E0(t){return t instanceof af||t instanceof sf?!0:t instanceof ic?t.status?eoe.has(t.status)||t.status>=500:!0:t instanceof UI?!0:t instanceof lf?t.code===-32603:!1}function x0(t){return t instanceof ic&&t.status&&toe.has(t.status)?!0:E0(t)}function I0(t,{retryCount:e=3,retryDelay:r=150}={}){return function(i,o={}){return LI(()=>t(i),{retryCount:o.retryCount??e,shouldRetry:({error:a})=>E0(a),delay:({count:a,error:s})=>{let l=s instanceof ic?qI(s.headers):void 0;return l!==void 0?l:(o.retryDelay??r)*2**(a-1)}})}}p();function oc({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:I0(n,{retryCount:i,retryDelay:o}),value:s}}function ac(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 ky({count:0});return oc({key:r,name:n,type:"fallback",request:async u=>{let d;for(let f=0;f<l.length;f++)try{return await l[f].request(u)}catch(m){if(d=m,a?.({error:m,index:f,method:u.method}),!x0(m))throw m}throw new ky({cause:d,count:l.length})},retryCount:i,retryDelay:o,timeout:s.timeout},{transports:l})}}p();p();var WF=0;function KF(){return WF+=1,WF}function roe(t){let e=t?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let r=t?.message??"";return/timeout/i.test(r)}var cf=class{constructor(e,{timeout:r=1e4,fetchOptions:n={}}={}){h(this,"url");h(this,"timeout");h(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 roe(n)?new af({body:e,url:this.url,timeout:this.timeout}):new sf({cause:n,url:this.url})}if(!r.ok)throw new ic({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:KF(),...e};return await this.post(r)??{id:r.id}}async requestBatch(e){let r=e.map(o=>({jsonrpc:"2.0",id:KF(),...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 YF(t,e,r){if(t.error)throw ZF({body:e,error:t.error,url:r});return t.result}function Io(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:f}={})=>{let{batchSize:m=1e3,wait:g=0}=typeof r=="object"?r:{},y=l??f??1e4,_=t??c?.rpcUrls.default.http[0];if(!_)throw new C0;let b=new cf(_,{timeout:y,fetchOptions:n});return oc({key:i,name:o,type:"http",retryCount:a??u,retryDelay:s??d,timeout:y,async request({method:v,params:S}){let k={method:v,params:S};if(r){let{schedule:E}=wy({id:`${_}:${m}:${g}`,wait:g,shouldSplitBatch:I=>I.length>m,fn:I=>b.requestBatch(I)});return YF(await E(k),k,_)}return YF(await b.request(k),k,_)}},{url:_})}}p();p();var noe=1024;async function uf(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||noe),d=new Array(r.length);if(r.length===0)return n?d:[];let f=Sy(t,s,o),m=[],g;r.forEach((b,v)=>{let{abi:S,address:k,functionName:E,args:I}=b,R;try{if(!Ve(k))throw new Dp(k);R=gt({abi:S,functionName:E,args:I})}catch(U){let D=rf(U,{abi:S,address:k,args:I,functionName:E,sender:i});if(!n)throw D;d[v]={status:"failure",error:D};return}let C=(R.length-2)/2;(!g||u>0&&g.size+C>u&&g.calls.length>0)&&(g={calls:[],indexes:[],size:0},m.push(g)),g.calls.push({target:k,allowFailure:!0,callData:R}),g.indexes.push(v),g.size+=C}),(await Gu(t,f,s!==void 0)?await Promise.allSettled(m.map(b=>da(t,{abi:xo,address:f,functionName:"aggregate3",args:[b.calls],account:i,blockNumber:o,blockTag:a,stateOverride:l}))):await(async()=>{let b=m.flatMap(S=>S.calls.map((k,E)=>({target:k.target,callData:k.callData,index:S.indexes[E]}))),v=await nf(t,b,{account:i,blockNumber:o,blockTag:a,stateOverride:l,concurrency:c});return m.length=0,v.map((S,k)=>(m.push({calls:[],indexes:[b[k].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 k of S.indexes){let E=r[k],I=rf(b.reason,{abi:E.abi,address:E.address,args:E.args,functionName:E.functionName,sender:i});if(!n)throw I;d[k]={status:"failure",error:I}}return}S.indexes.forEach((k,E)=>{let I=r[k],R=b.value[E];try{if(!R)throw new Error("Multicall returned fewer results than calls.");if(!R.success)throw new tf({data:R.returnData});if(!R.returnData||R.returnData==="0x")throw new Kl;let C=sa({abi:I.abi,functionName:I.functionName,args:I.args,data:R.returnData});d[k]={status:"success",result:C}}catch(C){let U=rf(C,{abi:I.abi,address:I.address,args:I.args,functionName:I.functionName,sender:i});if(!n)throw U;d[k]={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 ioe=0,Xu=class{constructor(e={}){h(this,"key");h(this,"name");h(this,"uid");h(this,"chain");h(this,"transport");h(this,"batch");h(this,"request");let{batch:r,key:n="public",name:i="Public Client",retryCount:o,retryDelay:a,timeout:s}=e;this.chain=aoe(e.chain),this.key=n,this.name=i,this.batch=r,this.uid=`${n}-${++ioe}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??ooe(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 ua(this,e)}readContract(e){return da(this,e)}multicall(e){return uf(this,e)}multicallRaw(e){return nc(this,e)}getBlockNumber(){return Vp(this)}getChainId(){return Hp(this)}getBalance(e){return Zp(this,e)}getCode(e){return tc(this,e)}getStorageAt(e){return Gp(this,e)}getTransactionCount(e){return Wp(this,e)}getGasPrice(){return Kp(this)}estimateMaxPriorityFeePerGas(){return k0(this)}estimateGas(e){return Yp(this,e)}getBlock(e){return Jp(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 ooe(t,e){if(t)return Io(t);let r=e?.rpcUrls.default.http??[];return r.length>1?ac(r.map(n=>Io(n,{retryCount:1}))):Io(r[0])}function aoe(t){if(t===void 0)return;if(typeof t=="object")return t;let e=DI(t);if(!e)throw new ef(t);return e}function sc(t={}){return new Xu(t)}var jI=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 ei(t,e={}){let{batch:r=!0,pinRpcUrl:n=!1,fallbackConcurrency:i,assumeMulticall3:o}=e,a=pa(t),s=e.rpcUrl?.trim(),l=a?Yu(a):[],c=s?n?[s]:[...new Set([s,...l])]:l;if(c.length===0)throw new ef(t);let u=`${a??t}|${c.join(",")}|${r?1:0}|${i??""}|${o?1:0}`,d=jI.get(u);if(d)return d;let f=sc({chain:a&&!nl(a)?soe(a,c):a,transport:c.length===1?Io(c[0]):ac(c.map(m=>Io(m,{retryCount:1}))),batch:r?{multicall:{fallbackConcurrency:i,assumeMulticall3:o}}:void 0});return jI.set(u,f),f}function O0(){jI.clear()}function BI(t,e){try{return ei(t,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function ti(t,e,r){let n=new Array(e.length).fill(null),i=e.length>0?BI(t,r):null;if(!i)return n;let o=[];if(e.forEach((a,s)=>{!Ve(a.target)||!Fu(a.callData)||o.push({index:s,target:a.target,callData:a.callData})}),o.length===0)return n;try{(await nc(i,{calls:o})).forEach((s,l)=>{s.success&&(n[o[l].index]=s.returnData)})}catch{}return n}function R0(t){return t?.status==="success"?t.result:void 0}async function FI(t,e){try{return await t.multicall({contracts:e})}catch{return[]}}async function JF(t,e,r){let n=e.map(()=>({symbol:null,decimals:null})),i=e.length>0?BI(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 FI(i,o.flatMap(l=>[{address:l.address,abi:Zt,functionName:"symbol"},{address:l.address,abi:Zt,functionName:"decimals"}]));o.forEach((l,c)=>{let u=R0(a[c*2]);typeof u=="string"&&u.trim()&&(n[l.index].symbol=u.trim()),n[l.index].decimals=w0(R0(a[c*2+1]))});let s=o.filter(l=>n[l.index].symbol===null);if(s.length>0){let l=await FI(i,s.map(c=>({address:c.address,abi:Xp,functionName:"symbol"})));s.forEach((c,u)=>{n[c.index].symbol=S0(R0(l[u]))})}return n}async function XF(t,e,r){let n=new Array(e.length).fill(null),i=e.length>0?BI(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 FI(i,o.map(s=>({address:s.address,abi:Qp,functionName:"tokenURI",args:[s.tokenId]})))).forEach((s,l)=>{let c=R0(s);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(n[o[l].index]=u)}),n}p();function loe(t){return N0(String(t))??"0"}function N0(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 zI(t){let e=N0(t);if(e===null||e.startsWith("-"))return null;let[r,n=""]=e.split(".");return{mant:BigInt(r+n),frac:n.length}}function VI(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 df(t){if(typeof t=="number")return Number.isFinite(t)&&t>0?loe(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=N0(e[0]);return r&&r!=="0"&&!r.startsWith("-")?r:null}function lc(t,e){let r=N0(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 pf(t,e,r,n){let i=zI(t);if(!i||r<=0n||n<0)return t;let o=i.mant*e*10n**BigInt(n)/(r*10n**BigInt(i.frac));return VI(o,n)}function Qu(t,e){let r=zI(t),n=zI(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 coe={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"}]},uoe="payment-required",doe="PAYMENT-SIGNATURE",poe="X-PAYMENT",foe="payment-response",hoe="x-payment-response",moe=600,goe=300,yoe={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 QF(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 tB(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 _oe(){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 rB(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=yoe[e.toLowerCase()];if(r===void 0)throw new Error(`Unsupported x402 network: ${t}`);return r}function nB(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 $0(t){let e=t.headers[uoe];if(e){let i=eB(boe(e));return i&&Array.isArray(i.accepts)?{version:2,payload:i}:null}let r=t.data,n=r&&typeof r=="object"?r:eB(r);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function eB(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}function boe(t){try{return tB(t)}catch{return null}}function voe(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 woe(t){let e=null;for(let r of t){let n=voe(r);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return rB(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 HI(t,e,r,n){let i=$0(t);if(!i)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:a}=i,s=woe(a.accepts??[]);if(!r)throw new Error("No connected wallet address to build the payment from");let l=rB(s.network),c=Math.floor(Date.now()/1e3),u={from:r,to:s.payTo,value:String(s.amount),validAfter:String(Math.max(0,c-moe)),validBefore:String(c+(s.maxTimeoutSeconds??goe)),nonce:_oe()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:l,verifyingContract:s.asset},types:coe,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:nB(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 Soe(t,e,r,n){let i=nB(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:HI(o,e,r,n)};if(!o.ok)throw new Error(Xe(o));return{status:"ok",data:o.data}}async function ZI(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...GI(e,r)}});if(s.ok)return s.data;throw new Error(koe(s)??Xe(s))}function Toe(t){return $0(t)!==null}function iB(t){let e=oB(t);return e?.errorReason?e.errorReason:$0(t)?.payload.error??null}function koe(t){let e=iB(t);return e?`x402 payment rejected: ${e}`:null}var Poe={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 GI(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{[poe]:QF(JSON.stringify(a))}}let o={x402Version:2,...t.resource!=null?{resource:t.resource}:{},accepted:Aoe(r),payload:i,...t.extensions!=null?{extensions:t.extensions}:{}};return{[doe]:QF(JSON.stringify(o))}}function Aoe(t){let{resource:e,description:r,mimeType:n,outputSchema:i,...o}=t;return o}function oB(t){let e=t.headers[foe]??t.headers[hoe];if(!e)return null;try{return JSON.parse(tB(e))}catch{return null}}function Coe(t,e){return t==null?e:Poe[t]??`Chain ${t}`}async function aB(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 JF("0x"+i.toString(16),[e.asset]);o=l?.symbol??null,a=l?.decimals??null}let s=String(e.amount);if(a!==null)try{s=VI(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:Coe(i,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:t.request.url}}function WI(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=HI(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 aB(o)})}catch{a=null}return a?GI(o,a):null}}p();p();var cc=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function ed(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Py(t){if(t?.aborted)throw new cc}function KI(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 sB={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},Eoe="https://nft.keyring.app/api/gemini-stable",xoe="https://generativelanguage.googleapis.com",Ioe=new Set([408,429,500,502,503,504]),lB=3e4,M0=t=>new Promise(e=>setTimeout(e,t));function D0(t,e,r){if(r!=null&&r>0)return Math.min(r,lB);let n=Math.min(e*2**(t-1),lB);return n/2+Math.random()*(n/2)}function Ooe(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 Rr=class{constructor(e){h(this,"model");h(this,"maxTokens");h(this,"temperature");h(this,"baseUrl");h(this,"apiKey");h(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?xoe:Eoe)).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;Py(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 f={contents:c,generationConfig:d};i&&(f.systemInstruction=i),r?.length?(f.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(f.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(f.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,g="Unknown error";for(let y=1;y<=a;y++){Py(l);let _;try{_=await ve.post(m,f,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(R){if(ed(R))throw R;if(g=R instanceof Error?R.message:String(R),y>=a)break;await M0(D0(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}`,!Ioe.has(_.status))throw new Error(g);if(y>=a)break;let C=Ooe(_.headers["retry-after"]??null);await M0(D0(y,s,C));continue}if(_.data==null||typeof _.data!="object"){if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,y>=a)break;await M0(D0(y,s));continue}let b=_.data,v=b.candidates?.[0];if(!v)return{text:"",toolCalls:[]};let S="",k=[],E=v.content?.parts;if(!Array.isArray(E)||E.length===0){let R=v.finishReason;if(!(R==="SAFETY"||R==="RECITATION")&&y<a){g=`Gemini returned an empty turn (finishReason=${R??"none"})`,await M0(D0(y,s));continue}return{text:"",toolCalls:[]}}for(let R of E)R.text&&(S+=R.text),R.functionCall&&k.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:k,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:sB[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:sB[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 ff=class{constructor(){h(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 hf=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Roe=new Set(hf),uc=[...hf],YI=new Set(uc),Vi="0x1",gf="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Noe(t){return t.map(e=>mf[e]??e).join(", ")}function U0(t){let e=new Set;if(t)for(let n of t){let i=L0(n);i&&e.add(i)}let r=hf.filter(n=>!e.has(n));uc=r.length>0?[...r]:[...hf],YI=new Set(uc),Vi=uc.includes("0x1")?"0x1":uc[0],gf=Noe(uc)}var $oe={"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 kt(t){let e=L0(t);return e&&YI.has(e)?e:null}function L0(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=$oe[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&&Roe.has(n)?n:null}function Oo(t){return kt(t)!==null}function ri(){return[...uc]}var pc=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${gf}.`);h(this,"requested",r);h(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},dc=t=>typeof t=="string"&&t.trim()!=="";function Nr(t,e){if(dc(t)){let r=kt(t);if(r)return r;throw new pc(t.trim())}if(dc(e?.chain)){let r=kt(e.chain);if(r)return r;throw new pc(e.chain.trim())}return null}function q0(t,e){return kt(t)??kt(e?.chain)??void 0}var mf={"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 te(t){let e=L0(t);return e&&mf[e]?mf[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var Moe={"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 cB(t,e){let r=L0(t),n=r?Moe[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Doe={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function uB(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?Doe[e]??null:null}var Uoe={"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 dB(t){let e=kt(t);return e?Uoe[e]??null:null}function yf(t,e){if(!dc(t))return null;let r=kt(t),n=kt(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:mf[r]??r,connectedLabel:mf[n]??n}}function pB(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>YI.has(o)):[];return(n.length?n:uc).map(o=>{let a=mf[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function _f(t,e){return{actionButtons:pB(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.");h(this,"code","needs_chain_selection");h(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=pB(r,n)}},Ay=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");h(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function fr(t,e){if(dc(t))return t.trim();if(dc(e?.walletAddress))return e.walletAddress.trim();throw new Ay}function Gr(t,e,r){if(dc(t)){let n=kt(t);if(n)return n;throw new pc(t.trim())}if(dc(e?.chain)){let n=kt(e.chain);if(n)return n;throw new pc(e.chain.trim())}if(dc(e?.walletAddress))throw new Tr(typeof e?.query=="string"?e.query:void 0,r);return Vi}var ae=class{constructor(){h(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=Loe(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 Ay?{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 Loe(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 qoe="https://wallet-api.pantograph.app",joe="0x0000000000000000000000000000000000000000",mB={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},gB={"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 Foe(t){return mB[t.toLowerCase()]||t}function fB(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 JI(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 j0(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 hB(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 qr=class{constructor(e){h(this,"baseUrl");this.baseUrl=(e?.baseUrl??qoe).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=j0(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?j0(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=j0(i.data),a=e.toLowerCase()===joe,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?JI(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=j0(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]=JI(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||Vi,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=fB({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(JI)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Vi,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=gB[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=>hB(y,r)):[],d=new Set,f=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),f.push(y))}let m=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...f,...m].slice(0,i):[...f,...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=fB({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=>hB(l,e))}async getTopGainers(e){let r=e?.chain||Vi,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 Boe="https://nft.keyring.app",zoe="https://nft.keyring.app",Voe=.01,rt=5,lr=1e3,Hoe=25,Zoe="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Goe="0x0000000000000000000000000000000000000000",nt=class extends Error{constructor(r,n){super(n);h(this,"status",r);this.name="MoralisHttpError"}};function hr(t){return t||Vi}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 Woe(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 Koe(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 XI(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){h(this,"baseUrl");h(this,"v1BaseUrl");h(this,"pantograph");this.baseUrl=(e?.baseUrl??Boe).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??zoe).replace(/\/+$/,""),this.pantograph=new qr({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=hr(n),l="Unknown error";for(let 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=[],f=null;do{f&&(u.cursor=f);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),f=v?.cursor??null}while(f);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()===Zoe?Goe:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=Voe)),{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=hr(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 f=l.value.data;u=(Array.isArray(f)?f:Array.isArray(f?.data)?f.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 f=c.value.data;d=f?.data??f}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=hr(n),d=[],f=a,m,g;for(let y=0;y<Hoe;y++){let _=await this.fetchWalletNftsPage({address:r,moralisChain:u,limit:i,excludeSpam:o,cursor:f,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:k,page_size:E}=b;if(Array.isArray(v)&&d.push(...v),m=k,g=E,f=typeof S=="string"&&S.trim()?S:void 0,!f)break}return{success:!0,data:{result:d,cursor:f,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 f={chain:n,format:c,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(f.cursor=a),l&&(f.include_prices=!0),s&&s.length>0&&(f.token_addresses=s);let m=cr(f),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(f){if(u=f instanceof Error?f.message:"Unknown error",f instanceof nt&&f.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=hr(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),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/collections?${d}`,m=await ve.get(f);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=hr(i),u="Unknown error";for(let d=1;d<=rt;d++)try{let f={chain:c,format:o,normalizeMetadata:a,media_items:s};l&&(f.include=l);let m=cr(f),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(f){if(u=f instanceof Error?f.message:"Unknown error",f instanceof nt&&f.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=hr(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:f}=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=hr(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),f!=null&&(b.nft_metadata=f);let v=cr(b),S=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${v}`,k=await ve.get(S);if(!k.ok)throw new nt(k.status,Xe(k));let E=k.data;return{success:!0,data:E?.data??E}}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 f=hr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=rt;y++)try{let _={chain:f,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 k=S.data;return{success:!0,data:k?.data??k}}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:f,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=hr(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),f!=null&&(v.include_prices=f);let S=cr(v),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${S}`,E=await ve.get(k);if(!E.ok)throw new nt(E.status,Xe(E));let I=E.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=hr(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=hr(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 f=d.data;return{success:!0,data:f?.data??f}}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=hr(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}`,f=await ve.get(d);if(!f.ok)throw new nt(f.status,Xe(f));let m=f.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=hr(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=hr(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}`,f=await ve.get(d);if(!f.ok)throw new nt(f.status,Xe(f));let m=f.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=hr(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:Woe(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=hr(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:Koe(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=hr(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=hr(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=hr(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=hr(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:XI(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=hr(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 f=d.data,m=f?.data??f;return{success:!0,data:XI(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=hr(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 f=d.data,m=f?.data??f;return{success:!0,data:XI(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 bf=class extends ae{constructor(r){super();h(this,"name","get-token-info");h(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');h(this,"category","blockchain-data");h(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}]);h(this,"service");h(this,"llm");this.service=new ct(r),this.llm=new Rr(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=Gr(r.chain,n)}catch(l){if(l instanceof pc)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(`
@@ -461,7 +461,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
461
461
  netApyExcludingRewards
462
462
  historicalState { avgNetApy(options: $options) { x y } }
463
463
  }
464
- }`,Uf=class{underlyingCall(e){return mn(e.contract,ca,"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=Zr(e);return n===null?null:fc(n,r.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,r){return this.balanceIsUnderlying?null:mn(e.contract,ca,"convertToAssets",[r])}},xy=class extends Uf{constructor(){super(...arguments);h(this,"type","spark");h(this,"balanceIsUnderlying",!1)}sizeCall(r){return mn(r.contract,ca,"totalAssets")}fetchApy(r,n,i){return cO(r,n,i)}},rO=class extends xy{constructor(){super(...arguments);h(this,"type","spark")}liveRateCall(r){return mn(r.contract,Df,"rateProvider")}followUpRateCall(r,n){let i=rr(n);return i===null?null:mn(i,nd,"getAPR")}decodeLiveRate(r){let n=Zr(r);return n===null?null:Iy(Math.expm1(Number(n)/z0))}},nO=class extends xy{constructor(){super(...arguments);h(this,"type","spark-ethereum")}liveRateCall(r){return mn(r.contract,Df,"vsr")}decodeLiveRate(r){let n=Zr(r);if(n===null)return null;let i=Number(n)/z0;return i>0?Iy(Math.expm1(Math.log(i)*TB)):null}},iO=class extends Uf{constructor(){super(...arguments);h(this,"type","spark-l2-susds");h(this,"balanceIsUnderlying",!1)}underlyingCall(){return null}sizeCall(r){return mn(r.token,Zt,"totalSupply")}liveRateCall(r){return mn(r.contract,nd,"getAPR")}decodeLiveRate(r){let n=Zr(r);return n===null?null:Iy(Math.expm1(Number(n)/z0))}convertToAssetsCall(r){return mn(r.contract,nd,"getConversionRate")}fetchApy(r,n,i){return cO(r,n,i)}};function Lf(t,e,r,n){if(e<=0n||!Number.isInteger(r)||!Number.isInteger(n)||r<0||n<0)return null;let i=t*e/dae,o=n-r;return o===0?i:o>0?i*10n**BigInt(o):i/10n**BigInt(-o)}var oO=class extends Uf{constructor(){super(...arguments);h(this,"type","aave-v3");h(this,"balanceIsUnderlying",!0)}underlyingCall(r){return mn(r.token,Mf,"UNDERLYING_ASSET_ADDRESS")}sizeCall(r){return mn(r.token,Zt,"totalSupply")}liveRateCall(r,n){return mn(r.contract,B0,"getReserveData",[n.address])}decodeLiveRate(r){if(!r)return null;let n;try{let[i]=Nn(B0[0].outputs,r);n=i.currentLiquidityRate}catch{return null}return Iy(Number(n)/z0)}async fetchApy(r,n,i,o){let a=await ve.post(i.aaveApiUrl,{operationName:"SupplyAPYHistory",query:fae,variables:{request:{chainId:n.chainId,market:r.contract,underlyingToken:o.address,window:"LAST_WEEK"}}});if(!a.ok)throw new Error(Xe(a));return{samples:(a.data?.data?.value||[]).map(s=>({timeMs:Date.parse(s?.date??""),fraction:Number(s?.avgRate?.value)})),current:null}}},aO=class extends Uf{constructor(){super(...arguments);h(this,"type","compound-v3");h(this,"balanceIsUnderlying",!0)}underlyingCall(r){return mn(r.contract,rd,"baseToken")}sizeCall(r){return mn(r.token,Zt,"totalSupply")}liveRateCall(r){return mn(r.contract,rd,"getUtilization")}followUpRateCall(r,n){let i=Zr(n);return i===null?null:mn(r.contract,rd,"getSupplyRate",[i])}decodeLiveRate(r){let n=Zr(r);return n===null?null:Iy(Number(n)/1e18*TB)}fetchApy(r,n,i){return cO(r,n,i)}},sO=class extends xy{constructor(){super(...arguments);h(this,"type","morpho-v2")}async fetchApy(r,n,i){let o=_ae(Date.now()),a=await ve.post(i.morphoApiUrl,{operationName:"VaultV2ByAddress",query:hae,variables:{address:r.contract,chainId:n.chainId,options:{startTimestamp:Math.floor(o/1e3)-(lO-1)*86400,endTimestamp:Math.floor(o/1e3)-86400}}});if(!a.ok)throw new Error(Xe(a));let s=a.data?.data?.vaultV2ByAddress,l=Number(s?.netApyExcludingRewards);return{samples:(s?.historicalState?.avgNetApy||[]).map(c=>({timeMs:Number(c?.x)*1e3,fraction:Number(c?.y)})),current:Number.isFinite(l)?l:null}}};async function cO(t,e,r){let n=`${r.coinPoolBaseUrl}/supply/rates/history?chainId=${e.chainId}&token=${t.token}`,i=await ve.get(n);if(!i.ok)throw new Error(Xe(i));return{samples:(i.data?.data||[]).map(o=>({timeMs:Date.parse(o?.date??""),fraction:Number(o?.rate)})),current:null}}var kB={"aave-v3":new oO,"compound-v3":new aO,spark:new rO,"spark-ethereum":new nO,"spark-l2-susds":new iO,"morpho-v2":new sO},mae=kB.spark;function id(t){return kB[t.type]??mae}var gae={"aave-v3":"Aave V3","compound-v3":"Compound V3",spark:"Spark","spark-ethereum":"Spark","spark-l2-susds":"Spark","morpho-v2":"Morpho V2"};function Ro(t){return gae[t]??null}var yae={"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 V0(t){return yae[t]??null}function fc(t,e){return Number(t)/10**e}function Oy(t){return new Date(t).toISOString().slice(0,10)}function _ae(t){return Date.parse(`${Oy(t)}T00:00:00.000Z`)}var bae=6e4,uO=new Map;async function Ry(t,e){let r=il(e),n=r?parseInt(r,16):NaN;if(!r||!Number.isFinite(n))return[];let i=`${t}|${r}`,o=uO.get(i);if(o&&Date.now()-o.at<bae)return o.markets;let a=vae(t,r,n),s=a.then(l=>l.markets);return uO.set(i,{at:Date.now(),markets:s}),a.then(l=>{l.answered||uO.delete(i)}),s}async function H0(t,e){return(await Ry(t,e)).length>0}async function vae(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=wae(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 PB(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 wae(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:Ro(o),protocolUrl:t?.protocolId?.domain?.trim()||null,type:o,contract:r,token:n,platformScore:Number.isFinite(i)?i:null}}function dO(){return ri()}async function Z0(t){let e=dO(),r=await Promise.all(e.map(n=>H0(t,n)));return e.filter((n,i)=>r[i])}async function G0(t,e){let r=kt(e);return r?H0(t,r):!1}async function AB(t,e){let r=e.map(o=>kt(o)).filter(o=>!!o),n=[...new Set(r)],i=await Promise.all(n.map(o=>H0(t,o)));return n.filter((o,a)=>i[a])}p();p();var Sae={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function W0(t){let e=il(t);return e?Sae[e]??null:null}function CB(t){return["susds","usds","rateProvider"].map(e=>({target:t,callData:gt({abi:tO,functionName:e})}))}var EB=3,Tae={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function pO(t){let e=il(t),r=e?Tae[e]:void 0;return r?{target:r,callData:gt({abi:nd,functionName:"getConversionRate"})}:null}function qf(t){return V0(t)}var xB=5;async function IB(t,e,r){let n=e.map(b=>Ve(b)?b.toLowerCase():null);if(n.every(b=>b===null))return ut("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let i=W0(t),o;try{ut("discovery: probing 5 accessors per token",{chain:t,tokens:n,psm:i}),o=await ti(t,[...n.flatMap(b=>b?kae(b):[]),...i?CB(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-EB):[],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,f=n.map(b=>{if(!b)return null;let v=o.slice(d,d+xB);return d+=xB,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()":Zr(v[4])?.toString()??null}),{token:b,slice:v}}),m=new Set;for(let b of f){if(!b)continue;let v=rr(b.slice[0]);v&&rr(b.slice[1])&&m.add(v.toLowerCase())}let g=await Pae(t,[...m]);m.size>0&&ut("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let y=f.flatMap(b=>b?rr(b.slice[0])&&rr(b.slice[1])||rr(b.slice[2])?[]:rr(b.slice[3])?[b.token]:[]:[]),_=await Aae(t,[...new Set(y)],r);return y.length>0&&ut("discovery: Morpho vault lookup",{asked:[...new Set(y)],recognised:[..._.keys()]}),f.map(b=>{if(!b)return null;let{token:v,slice:S}=b,k={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}),{...k,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Ro("spark-l2-susds"),protocolUrl:qf("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let E=rr(S[0]);if(E&&rr(S[1])){let I=g.has(E.toLowerCase());return ut("discovery: classified",{token:v,as:I?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:E}),I?{...k,name:"Aave v3",protocol:"AAVE",protocolLabel:Ro("aave-v3"),protocolUrl:qf("aave-v3"),type:"aave-v3",contract:E}:null}if(rr(S[2]))return ut("discovery: classified",{token:v,as:"compound-v3"}),{...k,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Ro("compound-v3"),protocolUrl:qf("compound-v3"),type:"compound-v3",contract:v};if(rr(S[3])){if(_.has(v)){ut("discovery: classified",{token:v,as:"morpho-v2"});let C=_.get(v)||"Morpho V2";return{...k,name:C,protocol:"MORPHO",protocolLabel:Ro("morpho-v2"),protocolUrl:qf("morpho-v2"),type:"morpho-v2",contract:v}}let R=Zr(S[4])!==null;return ut("discovery: classified",{token:v,as:R?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),R?{...k,name:"Spark",protocol:"SPARK",protocolLabel:Ro("spark-ethereum"),protocolUrl:qf("spark-ethereum"),type:"spark-ethereum",contract:v}:{...k,name:"Spark",protocol:"SPARK",protocolLabel:Ro("spark"),protocolUrl:qf("spark"),type:"spark",contract:v}}return ut("discovery: classified",{token:v,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function kae(t){return[{target:t,callData:gt({abi:Mf,functionName:"POOL"})},{target:t,callData:gt({abi:Mf,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:t,callData:gt({abi:rd,functionName:"baseToken"})},{target:t,callData:gt({abi:ca,functionName:"asset"})},{target:t,callData:gt({abi:Df,functionName:"vsr"})}]}async function Pae(t,e){if(e.length===0)return new Set;try{let r=await ti(t,e.map(n=>({target:n,callData:gt({abi:eO,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,i)=>rr(r[i])!==null))}catch{return new Set}}async function Aae(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))}p();p();var Cae={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Eae={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"},xae={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Iae={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function K0(t){let e=Lae(t.chain);return(e===null?null:Oae(t,e))??V0(t.type)??Uae(t,e)}function Oae(t,e){switch(t.type){case"morpho-v2":{let r=Cae[e];if(!r||!t.contract)return null;let n=`https://app.morpho.org/${r}/vault/${fO(t.contract)}`,i=$ae(t.name);return i?`${n}/${i}`:n}case"aave-v3":{let r=Eae[e],n=Rae(t);return!r||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${fO(n)}&marketName=${r}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let r=xae[e],n=Dae(t);return!r||!n?null:`https://app.spark.fi/savings/${r}/${n}`}case"compound-v3":{let r=Iae[e],n=Mae(t);return!r||!n?null:`https://app.compound.finance/?market=${n}-${r}`}default:return null}}function Rae(t){let e=t.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Nae=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function $ae(t){let e=t?.trim().toLowerCase()||"";return!e||Nae.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Mae(t){let e=t.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Dae(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 Uae(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",fO(t.contract)),i.toString()}catch{return n}}function fO(t){let e=t.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function Lae(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 qae=8;function jae(t,e,r){if(t.market.type!=="spark-l2-susds")return Zr(e);let n=Zr(e);return n===null||t.tokenDecimals===null?null:Lf(t.rawBalance,n,t.tokenDecimals,r)}var Y0=class{constructor(e){h(this,"endpoints",e);h(this,"apyLimiter",new hO(qae));h(this,"pantograph",new qr)}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=Fae(a[l].samples,u??a[l].current);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:K0({...s,asset:i[l]}),asset:i[l],totalSuppliedUsdc:c===null?null:hc(c,2),avgApyPercent:d.avgApyPercent,currentApyPercent:d.currentApyPercent,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 ti(e,a);return n.flatMap((l,c)=>{let u=Zr(s[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Bp(s[c*2+1])}]})}async convertToUnderlying(e,r,n){let i=[],o=r.map(s=>{let l=id(s.market).convertToAssetsCall(s.market,s.rawBalance);return l?(i.push(l),i.length-1):-1}),a=await ti(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 fc(s.rawBalance,c);let u=jae(s,a[o[l]],c);return u===null?fc(s.rawBalance,s.tokenDecimals??c):fc(u,c)})}async resolveAssets(e,r){let n={address:td,decimals:NaN,symbol:null,logo:null},i=[],o=r.map(u=>{let d=id(u).underlyingCall(u);return d?(i.push(d),i.length-1):-1}),a;try{let u=i.length>0?await ti(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(),f=l.get(d),m=c.get(d)??null;return f?.decimals!==null&&f?.decimals!==void 0?{address:u,decimals:f.decimals,symbol:f.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 ti(e,r.flatMap(s=>[{target:s,callData:i},{target:s,callData:o}]));r.forEach((s,l)=>{n.set(s,{decimals:Bp(a[l*2]),symbol:hy(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 f=id(u),m=n[d],g={market:u,protocol:f,asset:m,size:i.length,rate:-1};i.push(f.sizeCall(u,m));let y=f.liveRateCall(u,m);return y&&(g.rate=i.length,i.push(y)),g}),a=await ti(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 ti(e,s):[];return o.map((u,d)=>{let f=u.rate<0?null:a[u.rate],m=l[d]>=0?c[l[d]]:f;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 id(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}}}},hO=class{constructor(e){h(this,"limit",e);h(this,"active",0);h(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 Fae(t,e){let r=Oy(Date.now()),n=new Map,i=null;for(let u of t){if(!Number.isFinite(u.timeMs)||!Number.isFinite(u.fraction)||u.fraction<0||((!i||u.timeMs>i.timeMs)&&(i=u),!Bae(u.timeMs)))continue;let d=Oy(u.timeMs);d>=r||n.set(d,u.fraction)}let o=[...n.entries()].sort((u,d)=>u[0]<d[0]?-1:1).slice(-lO).map(([u,d])=>({date:u,apyPercent:hc(d*100,2)})),a=e??(i&&Oy(i.timeMs)===r?i.fraction:null),s=a===null?null:hc(a*100,2);if(s!==null&&o.push({date:r,apyPercent:s}),o.length===0)return{history:o,avgApyPercent:null,currentApyPercent:null,apyChangePercent:null};let l=o.reduce((u,d)=>u+d.apyPercent,0),c=o[o.length-1].apyPercent;return{history:o,avgApyPercent:hc(l/o.length,2),currentApyPercent:s,apyChangePercent:o.length>=2?hc(c-o[o.length-2].apyPercent,2):null}}function hc(t,e){let r=10**e;return Math.round(t*r)/r}function Bae(t){let e=new Date(t);return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0}var zae=.01;function Vae(t,e){if(typeof e!="string"||!e.trim())return;let r=e.trim(),n=Ty();n[t]!==r&&Ku({...n,[t]:r})}var jf=class{constructor(e,r,n){h(this,"coinPoolBaseUrl",e);h(this,"endpoints",r);h(this,"describer",n)}async describeReceiptTokens(e,r,n){let i=Date.now();ut("describeReceiptTokens: START",{chain:e,tokens:r,hasRpcUrl:!!n});let o=il(e);o&&Vae(o,n);let a=o?Cy(o):null,s=[...new Set(r.filter(Ve).map(f=>f.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 IB(o,s,this.endpoints.morphoApiUrl),u=[...new Map(s.flatMap((f,m)=>{let g=l[m];return ut("describeReceiptTokens: discovery result",{token:f,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[f,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(([f,m])=>({token:f,type:m.type,contract:m.contract}))});let d=await this.describer.describe(o,a,u.map(([,f])=>f));return ut("describeReceiptTokens: DONE",{ms:Date.now()-i,overviews:d.map(f=>({name:f.name,protocol:f.protocol,asset:f.asset?.symbol,assetDecimals:f.asset?.decimals,currentApyPercent:f.currentApyPercent,avgApyPercent:f.avgApyPercent,apyChangePercent:f.apyChangePercent,totalSuppliedUsdc:f.totalSuppliedUsdc,apyHistoryPoints:f.apyHistory?.length??0}))}),new Map(d.map((f,m)=>[u[m][0],f]))}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 AB(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=il(e),i=n?Cy(n):null;return n&&i?this.describer.describe(n,i,r):[]}async positionsForChain(e,r){let n=Cy(e),i=await Ry(this.coinPoolBaseUrl,e);if(!n||i.length===0)return[];let o=await this.describer.readBalances(e,r,i);if(o.length===0)return[];let a=await this.describer.describe(e,n,o.map(l=>l.market)),s=await this.describer.convertToUnderlying(e,o,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=s[c];return u<zae?[]:[{...l,suppliedUsdc:hc(u,6),estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:hc(u*l.avgApyPercent/100,2)}]})}};p();var mO=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Ff=class{constructor(e){h(this,"coinPoolBaseUrl",e)}async listChains(){return Z0(this.coinPoolBaseUrl)}async isSupported(e){return G0(this.coinPoolBaseUrl,e)}async getMarkets(e){let r=kt(e);return r?Ry(this.coinPoolBaseUrl,r):[]}async findMarket(e,r){let n=await this.getMarkets(e);return PB(n,r)}canSupply(e){return mO.includes(e.type)}async readReceiptToken(e,r){let n=id(r).balanceIsUnderlying;try{let i=await ti(e,[{target:r.token,callData:gt({abi:Zt,functionName:"symbol"})},{target:r.token,callData:gt({abi:Zt,functionName:"decimals"})}]);return{symbol:hy(i[0]),decimals:Bp(i[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};var ol=class{constructor(e={}){h(this,"read");h(this,"supply");let r=e.coinPoolBaseUrl||"https://api.coinpool.app",n={coinPoolBaseUrl:r,aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},i=new Y0(n);this.read=new jf(r,n,i),this.supply=new Ff(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 Ny="{market}",RB="{chain}";var NB=[{name:"supply_button_label",type:"string",description:`Label template for the per-market "Supply" 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. Use the exact placeholder "{market}" (do not translate the braces); it is replaced per market with its name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply USDC" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use BOTH exact placeholders (do not translate the braces): "{market}" is replaced with the market name, "{chain}" with the chain name it lives on. Write the connecting words around {chain} in the user's language \u2014 that is why it is a placeholder and not appended for you. English example: "supply USDC to {market} on {chain}". Vietnamese example: "n\u1EA1p USDC v\xE0o {market} tr\xEAn {chain}". Always include BOTH {market} and {chain}. Do NOT write a chain name or a contract address literally \u2014 the exact market identifier is appended automatically.`,required:!1}],$B=' A clickable "Supply" button is shown below your reply for each market automatically \u2014 do NOT list, number, or repeat those buttons in your text, and do NOT tell the user to tap one; just deliver the list and your suggestion.';function MB(t,e,r){return Hae(t,typeof e.supply_button_label=="string"?e.supply_button_label:"",typeof e.supply_prompt_template=="string"?e.supply_prompt_template:"",r)}function Hae(t,e,r,n){let i=typeof n=="string"?n.trim():"",o=[],a=new Set;for(let s of t){if(o.length>=10)break;let l=s.name?.trim();!l||a.has(l.toLowerCase())||(a.add(l.toLowerCase()),o.push({label:OB(e,l,"",`Supply ${Ny}`),prompt:OB(r,l,i,Zae(i))+Gae(s.contract)}))}return o}function Zae(t){return t?`supply USDC to ${Ny} on ${RB}`:`supply USDC to ${Ny}`}function Gae(t){let e=t?.trim();return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?` (market: ${e})`:""}function OB(t,e,r,n){return(t&&t.includes(Ny)?t:n).split(Ny).join(e).split(RB).join(r).replace(/\s+/g," ").trim()}p();var J0=[{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"]}],yO=J0.map(t=>t.label),gO={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 DB(t){let e=typeof t=="string"?t.trim():"";if(!e)return{kind:"none"};let r=Jae(e);if(!r)return{kind:"none"};let n=Wae(r);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let i=Yae(r);return i?{kind:"unsupported",label:i,requested:e}:{kind:"unknown",requested:e}}function Wae(t){let e=J0.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=J0.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 Kae(t)}function Kae(t){let e=null,r=!1;for(let n of J0)for(let i of n.aliases){let o=UB(i);if(o===0||Math.abs(i.length-t.length)>o)continue;let a=LB(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 UB(t){return t.length<=4?0:t.length<=9?2:3}function Yae(t){let e=gO[t];if(e)return e;if(t.length>=4){let i=new Set(Object.entries(gO).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(gO)){let a=UB(i);if(a===0||Math.abs(i.length-t.length)>a)continue;let s=LB(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 Jae(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function LB(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]}var Qae=["apy","score","size"],qB=5,jB=40,Bf=class extends ae{constructor(r){super();h(this,"name","get-lending-markets");h(this,"description",'List the LENDING / SUPPLY markets available to deposit into and earn yield on: protocol (Aave v3, Compound v3, Spark, Morpho vaults), market name, chain, total supplied to that market, the live supply APY plus the average over the last week and its daily change, and a 0\u201310 platform score. Ranked by the live protocol APY by default, and filterable to ONE protocol via `protocol`. 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. Each market states its own asset in `suppliedAssetSymbol`, which is usually USDC but need not be. Do NOT use for: what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.');h(this,"category","blockchain-data");h(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: ${yO.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-${jB}. 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},...NB]);h(this,"service");this.service=new ol(r)}async run(r,n){let i=await this.service.listSupportedChains(),o=Nr(r.chain,void 0),a=o?null:kt(n?.chain),s=o??a;if(s&&!i.includes(s))return{_instructions:`There are no lending markets on ${te(s)}`+(a?", 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:te(s),connectedChainHasNoMarkets:a!==null,marketCount:0,markets:[],chainsWithLendingMarkets:i.map(_=>te(_))};let l=DB(r.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,u=tse(r.sort),d=rse(r.limit),f=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?f.filter(_=>l.matches(_)):f;if(l.kind==="supported"&&m.length===0&&f.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?te(s):"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 ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?te(s):"all",marketCount:0,markets:[],protocolsAvailable:[...new Set(f.map(_=>_.protocol))]};let g=[...m].sort(ese[u]).slice(0,d),y=g.slice(0,10).flatMap(_=>MB([{name:_.name,contract:_.contract}],r,te(_.chain)));return{_instructions:this.instructions(g,u,y.length>0,l.kind==="supported"?l.label:null),...y.length>0?{actionButtons:y}:{},chain:s?te(s):"all",chainsQueried:c.map(_=>te(_)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:u,marketCount:g.length,totalMarketsAvailable:m.length,markets:g.map(_=>({marketName:_.name,protocol:_.protocol,protocolUrl:_.protocolUrl,chain:te(_.chain),avgApyPercent:_.avgApyPercent,avgApyDays:_.apyHistory.length,currentApyPercent:_.currentApyPercent,apyChangePercent:_.apyChangePercent,totalSuppliedUsdc:_.totalSuppliedUsdc,suppliedAssetSymbol:_.asset.symbol,platformScore:_.platformScore}))}}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:[...yO],marketCount:0,markets:[]}}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 present it as such, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${a}.`,"Present them as a NUMBERED list. Each entry starts with `marketName` as a markdown link to that","market's `protocolUrl` in bold \u2014 **[marketName](protocolUrl)** \u2014 so the name opens that market's page on","the protocol.","When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it.",'Under each name put exactly three bullet points, in this order: "Total supplied" = `totalSuppliedUsdc`,','"Protocol APY" = `currentApyPercent` (the live rate), and "Avg APY" = `avgApyPercent` labelled as the',"average over the last `avgApyDays` days. Do NOT add other bullets.","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 \u2014 mention it only when the user","asks which market is safest. A null APY means that rate was unavailable \u2014 say so rather than showing 0.",new Set(r.map(s=>s.chain)).size>1?"The markets span several chains \u2014 put each one's `chain` on the title line, after the linked name, so the user knows where it lives.":"All markets are on one chain \u2014 state the chain name once before the list, not per market.","Close with one short sentence naming the best option for the ranking used and why.","This is information, NOT financial advice \u2014 say so briefly.","Do NOT mention tool names.",i?$B:""].filter(Boolean).join(" ")}},ese={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 tse(t){let e=typeof t=="string"?t.trim().toLowerCase():"";return Qae.includes(e)?e:"apy"}function rse(t){let e=typeof t=="number"?t:Number(t);return!Number.isFinite(e)||e<1?qB:Math.min(Math.floor(e),jB)}p();var zf=class extends ae{constructor(r){super();h(this,"name","get-wallet-lending-positions");h(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.');h(this,"category","blockchain-data");h(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}]);h(this,"service");this.service=new ol(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=Nr(r.chain,n),a=await this.service.listSupportedChains();if(o&&!a.includes(o))return{_instructions:`There are no lending markets on ${te(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:te(o),positionCount:0,positions:[],chainsWithLendingMarkets:a.map(c=>te(c))};let s=o?[o]:a,l=await this.service.getSupplyPositions({address:i,chains:s});return{_instructions:this.instructions(l),walletAddress:i,chain:o?te(o):"all",chainsQueried:s.map(c=>te(c)),positionCount:l.length,totals:nse(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:te(c.chain),suppliedUsdc:c.suppliedUsdc,suppliedAssetSymbol:c.asset.symbol,avgApyPercent:c.avgApyPercent,currentApyPercent:c.currentApyPercent,apyChangePercent:c.apyChangePercent,estimatedAnnualYieldUsdc:c.estimatedAnnualYieldUsdc,marketTotalSuppliedUsdc:c.totalSuppliedUsdc,apyHistory:c.apyHistory,platformScore:c.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 daily 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).","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 nse(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:_O(n,6),estimatedAnnualYieldUsdc:_O(t.reduce((a,s)=>a+(s.estimatedAnnualYieldUsdc??0),0),2),weightedAvgApyPercent:o>0?_O(i.reduce((a,s)=>a+s.suppliedUsdc*s.avgApyPercent,0)/o,2):null}}function _O(t,e){let r=10**e;return Math.round(t*r)/r}p();var Vf=class extends ae{constructor(r){super();h(this,"name","open-supply-usdc-form");h(this,"kind","ui");h(this,"category","lending-action");h(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.');h(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)" hint, pass THAT address verbatim as this argument and ignore the market name in the sentence \u2014 the address identifies the exact market they picked, while a name may match several vaults of the same protocol.`,required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the user names; whether it carries markets is checked at call time. Set it ONLY when the user names a chain; 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}]);h(this,"service");h(this,"moralis");this.service=new ol(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=Nr(r.chain,void 0)??kt(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."};let s=await this.service.listSupportedChains();if(!s.includes(a))return{error:"unsupported_chain",chain:te(a),chainsWithLendingMarkets:s.map(S=>te(S)),_instructions:`There are no lending markets on ${te(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 l=ose(r.market);if(!l)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 c=await this.service.findMarket(a,l);if(c.length===0)return{error:"market_not_found",market:l,chain:te(a),_instructions:`No lending market matching "${l}" exists on ${te(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(c.length>1)return{error:"ambiguous_market",market:l,chain:te(a),candidates:c.map(S=>({marketName:S.name,protocol:S.protocol})),_instructions:`"${l}" matches ${c.length} different markets on ${te(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="`+l+`" and chain for ${te(a)}, plus the localized supply-button templates \u2014 that shows the user each market with its APY, size and score, each with its own Supply button to tap. Write no message of your own before that call.`};let u=c[0];if(!this.service.supply.canSupply(u))return{error:"unsupported_protocol",marketName:u.name,protocol:u.protocol,_instructions:`Supplying to ${u.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 d=await this.describeOne(a,u),f=ise(d);if(!f)return{error:"asset_unresolved",marketName:u.name,chain:te(a),_instructions:`The asset ${u.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[m,g]=await Promise.all([this.assetBalance(i,a,f.address),this.service.readReceiptToken(a,u)]);if(m&&Qu(m.amount,"0")<=0)return{error:"no_asset_balance",marketName:u.name,chain:te(a),assetSymbol:f.symbol,assetBalance:"0",_instructions:`The user has no ${f.symbol} available to supply to ${u.name} on ${te(a)}. In the user's language, tell them plainly that they have no ${f.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 y=ase(r.amount),_=y?lc(y,f.decimals):null;if(_&&m&&Qu(_,m.amount)>0)return{error:"insufficient_asset_balance",marketName:u.name,chain:te(a),assetSymbol:f.symbol,requestedAmount:y,assetBalance:m.amount,_instructions:`The user wants to supply ${y} ${f.symbol} to ${u.name}, but they only hold ${m.amount} ${f.symbol} on ${te(a)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${y} ${f.symbol} exceeds their balance of ${m.amount} ${f.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 b={action:"supply_usdc",chainId:a,chainName:te(a),walletAddress:i,market:{name:u.name,type:u.type,protocol:u.protocol,protocolUrl:d?.protocolUrl??K0(u),contract:u.contract,token:u.token,apyPercent:d?.currentApyPercent??d?.avgApyPercent??null,receiptToken:g},asset:f,..._?{prefillAmount:_}:{},...m?{spendable:m.amount}:{},...m?.usd?{spendableUsd:m.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:b},marketName:u.name,protocol:u.protocol,chain:te(a),apyPercent:b.market.apyPercent,assetSymbol:f.symbol,assetBalance:m?.amount??null,_instructions:this.instructions(u,f.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 ise(t){let e=t?.asset;return!e?.address||e.address===td||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function ose(t){let e=typeof t=="string"?t.trim():"",r=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})\s*[\])]/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}function ase(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 X0="https://ipfs.pantograph.app/ipfs/",FB=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function od(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?`${X0}${r[1]}`:FB.test(e)?`${X0}${e}`:null}function BB(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?`${X0}${r[1]}`:FB.test(e)?`${X0}${e}`:null}function zB(t){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(t)}function bO(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 sse(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 lse(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)?sse(n):decodeURIComponent(n);return JSON.parse(i)}catch{try{return JSON.parse(n)}catch{return null}}}function VB(t){let e=t?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let r=lse(e);return r?od(bO(r)):null}p();var cse=12,use=6e3;async function dse(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 pse(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 fse(t,e){let r=t?.trim();if(!r)return null;if(/^data:/i.test(r))return VB(r);let n=BB(r);if(!n)return null;if(zB(n))return n;let i=await pse(n,e);if(i){let o=od(bO(i));if(o)return o}return null}async function Q0(t,e,r){if(e.length===0)return[];let n=r?.concurrency??cse,i=r?.timeoutMs??use,o=await XF(t,e,r?.rpcUrl);return dse(o,n,a=>fse(a,i))}var HB=100,hse=100,Hf="{name}",ZB="{chain}",Zf=class extends ae{constructor(r){super();h(this,"name","get-wallet-nfts");h(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.`);h(this,"category","nft");h(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}]);h(this,"service");this.service=new ct(r)}async run(r,n){let i=fr(r.address,n),o=Nr(r.chain,n),a=o?[o]:ri(),s=vse(r.contract_address),l=KB(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:HB});return{chain:u,rows:d.success?GB(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:gse(d),contractAddress:d.token_address,chain:te(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=_se(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:HB,...a?{tokenAddresses:[a]}:{}});return{chain:g,rows:y.success?GB(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=>mse(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),f=c.map(({chain:g,row:y},_)=>{let b=yse(y);return{name:b.name,tokenId:b.tokenId,contractAddress:b.contractAddress,image:d[_]??b.image,chain:te(g)}});return{ui:{component:"WalletNftList",props:{walletAddress:n,collectionName:u,nfts:f}},_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 Q0(o,s);a.forEach((c,u)=>{n[c]=l[u]??null})}))}catch{}return n}};function GB(t){return t.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function mse(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 gse(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 yse(t){return{name:t.normalized_metadata?.name||t.name||`#${t.token_id}`,tokenId:t.token_id,contractAddress:t.token_address,image:od(t.normalized_metadata?.image||t.media?.original_media_url)}}function _se(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>=hse)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",s=a?`show my ${Hf} NFTs on ${ZB}`:`show my ${Hf} NFTs`,l=WB(n,{[Hf]:o.name,[ZB]:a},s);a&&!l.includes(a)&&(l=`${l} (${a})`),i.push({label:bse(r,o.name,Hf),prompt:`${l} (${o.contractAddress})`})}return i}function WB(t,e,r){let n=t&&t.includes(Hf)?t:r;for(let[i,o]of Object.entries(e))n=n.split(i).join(o);return n.replace(/\s+/g," ").trim()}function bse(t,e,r){return WB(t,{[Hf]:e},r)}function KB(t){if(typeof t!="string")return;let e=t.trim();return e||void 0}function vse(t){let e=KB(t);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}p();p();var wse="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.",fa=class extends ae{constructor(r){super();h(this,"kind","data");h(this,"category","nft");h(this,"llm");this.llm=new Rr(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:wse,timestamp:n},{role:"user",content:r,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Gf=class extends fa{constructor(){super(...arguments);h(this,"name","get-nft-contract-info");h(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`.');h(this,"parameters",fa.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."`));h(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 Wf=class extends fa{constructor(){super(...arguments);h(this,"name","get-nft-metadata");h(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`.');h(this,"parameters",fa.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."`));h(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 vO={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"},wO="amazon.com";function Sse(t){return t?t.trim().toLowerCase().split(/[-_]/)[0]:""}function SO(t){let e=Sse(t);return vO[e]??wO}function eS(t){return`https://${SO(t)}/s?k=NFC%20Tag`}p();function tS(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 Tse=720*60*1e3,YB=new Map,JB=3;function kse(t){return[`A user in country "${t}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${JB} 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 Pse(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>=JB))break}return i}async function TO(t,e){let r=tS(t);if(!r||!e)return null;let n=YB.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:kse(r),timestamp:i}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=Pse(a.text);if(s.length)return YB.set(r,{links:s,expires:Date.now()+Tse}),s}catch{}return null}async function Kf(t){let e=await TO(t.country,t.llm);return e&&e.length?e:[{label:"Amazon",url:eS(t.language)}]}function Ase(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(`
464
+ }`,Uf=class{underlyingCall(e){return mn(e.contract,ca,"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=Zr(e);return n===null?null:fc(n,r.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,r){return this.balanceIsUnderlying?null:mn(e.contract,ca,"convertToAssets",[r])}},xy=class extends Uf{constructor(){super(...arguments);h(this,"type","spark");h(this,"balanceIsUnderlying",!1)}sizeCall(r){return mn(r.contract,ca,"totalAssets")}fetchApy(r,n,i){return cO(r,n,i)}},rO=class extends xy{constructor(){super(...arguments);h(this,"type","spark")}liveRateCall(r){return mn(r.contract,Df,"rateProvider")}followUpRateCall(r,n){let i=rr(n);return i===null?null:mn(i,nd,"getAPR")}decodeLiveRate(r){let n=Zr(r);return n===null?null:Iy(Math.expm1(Number(n)/z0))}},nO=class extends xy{constructor(){super(...arguments);h(this,"type","spark-ethereum")}liveRateCall(r){return mn(r.contract,Df,"vsr")}decodeLiveRate(r){let n=Zr(r);if(n===null)return null;let i=Number(n)/z0;return i>0?Iy(Math.expm1(Math.log(i)*TB)):null}},iO=class extends Uf{constructor(){super(...arguments);h(this,"type","spark-l2-susds");h(this,"balanceIsUnderlying",!1)}underlyingCall(){return null}sizeCall(r){return mn(r.token,Zt,"totalSupply")}liveRateCall(r){return mn(r.contract,nd,"getAPR")}decodeLiveRate(r){let n=Zr(r);return n===null?null:Iy(Math.expm1(Number(n)/z0))}convertToAssetsCall(r){return mn(r.contract,nd,"getConversionRate")}fetchApy(r,n,i){return cO(r,n,i)}};function Lf(t,e,r,n){if(e<=0n||!Number.isInteger(r)||!Number.isInteger(n)||r<0||n<0)return null;let i=t*e/dae,o=n-r;return o===0?i:o>0?i*10n**BigInt(o):i/10n**BigInt(-o)}var oO=class extends Uf{constructor(){super(...arguments);h(this,"type","aave-v3");h(this,"balanceIsUnderlying",!0)}underlyingCall(r){return mn(r.token,Mf,"UNDERLYING_ASSET_ADDRESS")}sizeCall(r){return mn(r.token,Zt,"totalSupply")}liveRateCall(r,n){return mn(r.contract,B0,"getReserveData",[n.address])}decodeLiveRate(r){if(!r)return null;let n;try{let[i]=Nn(B0[0].outputs,r);n=i.currentLiquidityRate}catch{return null}return Iy(Number(n)/z0)}async fetchApy(r,n,i,o){let a=await ve.post(i.aaveApiUrl,{operationName:"SupplyAPYHistory",query:fae,variables:{request:{chainId:n.chainId,market:r.contract,underlyingToken:o.address,window:"LAST_WEEK"}}});if(!a.ok)throw new Error(Xe(a));return{samples:(a.data?.data?.value||[]).map(s=>({timeMs:Date.parse(s?.date??""),fraction:Number(s?.avgRate?.value)})),current:null}}},aO=class extends Uf{constructor(){super(...arguments);h(this,"type","compound-v3");h(this,"balanceIsUnderlying",!0)}underlyingCall(r){return mn(r.contract,rd,"baseToken")}sizeCall(r){return mn(r.token,Zt,"totalSupply")}liveRateCall(r){return mn(r.contract,rd,"getUtilization")}followUpRateCall(r,n){let i=Zr(n);return i===null?null:mn(r.contract,rd,"getSupplyRate",[i])}decodeLiveRate(r){let n=Zr(r);return n===null?null:Iy(Number(n)/1e18*TB)}fetchApy(r,n,i){return cO(r,n,i)}},sO=class extends xy{constructor(){super(...arguments);h(this,"type","morpho-v2")}async fetchApy(r,n,i){let o=_ae(Date.now()),a=await ve.post(i.morphoApiUrl,{operationName:"VaultV2ByAddress",query:hae,variables:{address:r.contract,chainId:n.chainId,options:{startTimestamp:Math.floor(o/1e3)-(lO-1)*86400,endTimestamp:Math.floor(o/1e3)-86400}}});if(!a.ok)throw new Error(Xe(a));let s=a.data?.data?.vaultV2ByAddress,l=Number(s?.netApyExcludingRewards);return{samples:(s?.historicalState?.avgNetApy||[]).map(c=>({timeMs:Number(c?.x)*1e3,fraction:Number(c?.y)})),current:Number.isFinite(l)?l:null}}};async function cO(t,e,r){let n=`${r.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${t.token}`,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}}var kB={"aave-v3":new oO,"compound-v3":new aO,spark:new rO,"spark-ethereum":new nO,"spark-l2-susds":new iO,"morpho-v2":new sO},mae=kB.spark;function id(t){return kB[t.type]??mae}var gae={"aave-v3":"Aave V3","compound-v3":"Compound V3",spark:"Spark","spark-ethereum":"Spark","spark-l2-susds":"Spark","morpho-v2":"Morpho V2"};function Ro(t){return gae[t]??null}var yae={"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 V0(t){return yae[t]??null}function fc(t,e){return Number(t)/10**e}function Oy(t){return new Date(t).toISOString().slice(0,10)}function _ae(t){return Date.parse(`${Oy(t)}T00:00:00.000Z`)}var bae=6e4,uO=new Map;async function Ry(t,e){let r=il(e),n=r?parseInt(r,16):NaN;if(!r||!Number.isFinite(n))return[];let i=`${t}|${r}`,o=uO.get(i);if(o&&Date.now()-o.at<bae)return o.markets;let a=vae(t,r,n),s=a.then(l=>l.markets);return uO.set(i,{at:Date.now(),markets:s}),a.then(l=>{l.answered||uO.delete(i)}),s}async function H0(t,e){return(await Ry(t,e)).length>0}async function vae(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=wae(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 PB(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 wae(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:Ro(o),protocolUrl:t?.protocolId?.domain?.trim()||null,type:o,contract:r,token:n,platformScore:Number.isFinite(i)?i:null}}function dO(){return ri()}async function Z0(t){let e=dO(),r=await Promise.all(e.map(n=>H0(t,n)));return e.filter((n,i)=>r[i])}async function G0(t,e){let r=kt(e);return r?H0(t,r):!1}async function AB(t,e){let r=e.map(o=>kt(o)).filter(o=>!!o),n=[...new Set(r)],i=await Promise.all(n.map(o=>H0(t,o)));return n.filter((o,a)=>i[a])}p();p();var Sae={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function W0(t){let e=il(t);return e?Sae[e]??null:null}function CB(t){return["susds","usds","rateProvider"].map(e=>({target:t,callData:gt({abi:tO,functionName:e})}))}var EB=3,Tae={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function pO(t){let e=il(t),r=e?Tae[e]:void 0;return r?{target:r,callData:gt({abi:nd,functionName:"getConversionRate"})}:null}function qf(t){return V0(t)}var xB=5;async function IB(t,e,r){let n=e.map(b=>Ve(b)?b.toLowerCase():null);if(n.every(b=>b===null))return ut("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let i=W0(t),o;try{ut("discovery: probing 5 accessors per token",{chain:t,tokens:n,psm:i}),o=await ti(t,[...n.flatMap(b=>b?kae(b):[]),...i?CB(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-EB):[],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,f=n.map(b=>{if(!b)return null;let v=o.slice(d,d+xB);return d+=xB,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()":Zr(v[4])?.toString()??null}),{token:b,slice:v}}),m=new Set;for(let b of f){if(!b)continue;let v=rr(b.slice[0]);v&&rr(b.slice[1])&&m.add(v.toLowerCase())}let g=await Pae(t,[...m]);m.size>0&&ut("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let y=f.flatMap(b=>b?rr(b.slice[0])&&rr(b.slice[1])||rr(b.slice[2])?[]:rr(b.slice[3])?[b.token]:[]:[]),_=await Aae(t,[...new Set(y)],r);return y.length>0&&ut("discovery: Morpho vault lookup",{asked:[...new Set(y)],recognised:[..._.keys()]}),f.map(b=>{if(!b)return null;let{token:v,slice:S}=b,k={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}),{...k,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Ro("spark-l2-susds"),protocolUrl:qf("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let E=rr(S[0]);if(E&&rr(S[1])){let I=g.has(E.toLowerCase());return ut("discovery: classified",{token:v,as:I?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:E}),I?{...k,name:"Aave v3",protocol:"AAVE",protocolLabel:Ro("aave-v3"),protocolUrl:qf("aave-v3"),type:"aave-v3",contract:E}:null}if(rr(S[2]))return ut("discovery: classified",{token:v,as:"compound-v3"}),{...k,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Ro("compound-v3"),protocolUrl:qf("compound-v3"),type:"compound-v3",contract:v};if(rr(S[3])){if(_.has(v)){ut("discovery: classified",{token:v,as:"morpho-v2"});let C=_.get(v)||"Morpho V2";return{...k,name:C,protocol:"MORPHO",protocolLabel:Ro("morpho-v2"),protocolUrl:qf("morpho-v2"),type:"morpho-v2",contract:v}}let R=Zr(S[4])!==null;return ut("discovery: classified",{token:v,as:R?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),R?{...k,name:"Spark",protocol:"SPARK",protocolLabel:Ro("spark-ethereum"),protocolUrl:qf("spark-ethereum"),type:"spark-ethereum",contract:v}:{...k,name:"Spark",protocol:"SPARK",protocolLabel:Ro("spark"),protocolUrl:qf("spark"),type:"spark",contract:v}}return ut("discovery: classified",{token:v,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function kae(t){return[{target:t,callData:gt({abi:Mf,functionName:"POOL"})},{target:t,callData:gt({abi:Mf,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:t,callData:gt({abi:rd,functionName:"baseToken"})},{target:t,callData:gt({abi:ca,functionName:"asset"})},{target:t,callData:gt({abi:Df,functionName:"vsr"})}]}async function Pae(t,e){if(e.length===0)return new Set;try{let r=await ti(t,e.map(n=>({target:n,callData:gt({abi:eO,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,i)=>rr(r[i])!==null))}catch{return new Set}}async function Aae(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))}p();p();var Cae={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Eae={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"},xae={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Iae={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function K0(t){let e=Lae(t.chain);return(e===null?null:Oae(t,e))??V0(t.type)??Uae(t,e)}function Oae(t,e){switch(t.type){case"morpho-v2":{let r=Cae[e];if(!r||!t.contract)return null;let n=`https://app.morpho.org/${r}/vault/${fO(t.contract)}`,i=$ae(t.name);return i?`${n}/${i}`:n}case"aave-v3":{let r=Eae[e],n=Rae(t);return!r||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${fO(n)}&marketName=${r}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let r=xae[e],n=Dae(t);return!r||!n?null:`https://app.spark.fi/savings/${r}/${n}`}case"compound-v3":{let r=Iae[e],n=Mae(t);return!r||!n?null:`https://app.compound.finance/?market=${n}-${r}`}default:return null}}function Rae(t){let e=t.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Nae=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function $ae(t){let e=t?.trim().toLowerCase()||"";return!e||Nae.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Mae(t){let e=t.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Dae(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 Uae(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",fO(t.contract)),i.toString()}catch{return n}}function fO(t){let e=t.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function Lae(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 qae=8;function jae(t,e,r){if(t.market.type!=="spark-l2-susds")return Zr(e);let n=Zr(e);return n===null||t.tokenDecimals===null?null:Lf(t.rawBalance,n,t.tokenDecimals,r)}var Y0=class{constructor(e){h(this,"endpoints",e);h(this,"apyLimiter",new hO(qae));h(this,"pantograph",new qr)}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=Fae(a[l].samples,u??a[l].current);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:K0({...s,asset:i[l]}),asset:i[l],totalSuppliedUsdc:c===null?null:hc(c,2),avgApyPercent:d.avgApyPercent,currentApyPercent:d.currentApyPercent,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 ti(e,a);return n.flatMap((l,c)=>{let u=Zr(s[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Bp(s[c*2+1])}]})}async convertToUnderlying(e,r,n){let i=[],o=r.map(s=>{let l=id(s.market).convertToAssetsCall(s.market,s.rawBalance);return l?(i.push(l),i.length-1):-1}),a=await ti(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 fc(s.rawBalance,c);let u=jae(s,a[o[l]],c);return u===null?fc(s.rawBalance,s.tokenDecimals??c):fc(u,c)})}async resolveAssets(e,r){let n={address:td,decimals:NaN,symbol:null,logo:null},i=[],o=r.map(u=>{let d=id(u).underlyingCall(u);return d?(i.push(d),i.length-1):-1}),a;try{let u=i.length>0?await ti(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(),f=l.get(d),m=c.get(d)??null;return f?.decimals!==null&&f?.decimals!==void 0?{address:u,decimals:f.decimals,symbol:f.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 ti(e,r.flatMap(s=>[{target:s,callData:i},{target:s,callData:o}]));r.forEach((s,l)=>{n.set(s,{decimals:Bp(a[l*2]),symbol:hy(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 f=id(u),m=n[d],g={market:u,protocol:f,asset:m,size:i.length,rate:-1};i.push(f.sizeCall(u,m));let y=f.liveRateCall(u,m);return y&&(g.rate=i.length,i.push(y)),g}),a=await ti(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 ti(e,s):[];return o.map((u,d)=>{let f=u.rate<0?null:a[u.rate],m=l[d]>=0?c[l[d]]:f;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 id(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}}}},hO=class{constructor(e){h(this,"limit",e);h(this,"active",0);h(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 Fae(t,e){let r=Oy(Date.now()),n=new Map,i=null;for(let u of t){if(!Number.isFinite(u.timeMs)||!Number.isFinite(u.fraction)||u.fraction<0||((!i||u.timeMs>i.timeMs)&&(i=u),!Bae(u.timeMs)))continue;let d=Oy(u.timeMs);d>=r||n.set(d,u.fraction)}let o=[...n.entries()].sort((u,d)=>u[0]<d[0]?-1:1).slice(-lO).map(([u,d])=>({date:u,apyPercent:hc(d*100,2)})),a=e??(i&&Oy(i.timeMs)===r?i.fraction:null),s=a===null?null:hc(a*100,2);if(s!==null&&o.push({date:r,apyPercent:s}),o.length===0)return{history:o,avgApyPercent:null,currentApyPercent:null,apyChangePercent:null};let l=o.reduce((u,d)=>u+d.apyPercent,0),c=o[o.length-1].apyPercent;return{history:o,avgApyPercent:hc(l/o.length,2),currentApyPercent:s,apyChangePercent:o.length>=2?hc(c-o[o.length-2].apyPercent,2):null}}function hc(t,e){let r=10**e;return Math.round(t*r)/r}function Bae(t){let e=new Date(t);return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0}var zae=.01;function Vae(t,e){if(typeof e!="string"||!e.trim())return;let r=e.trim(),n=Ty();n[t]!==r&&Ku({...n,[t]:r})}var jf=class{constructor(e,r,n){h(this,"coinPoolBaseUrl",e);h(this,"endpoints",r);h(this,"describer",n)}async describeReceiptTokens(e,r,n){let i=Date.now();ut("describeReceiptTokens: START",{chain:e,tokens:r,hasRpcUrl:!!n});let o=il(e);o&&Vae(o,n);let a=o?Cy(o):null,s=[...new Set(r.filter(Ve).map(f=>f.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 IB(o,s,this.endpoints.morphoApiUrl),u=[...new Map(s.flatMap((f,m)=>{let g=l[m];return ut("describeReceiptTokens: discovery result",{token:f,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[f,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(([f,m])=>({token:f,type:m.type,contract:m.contract}))});let d=await this.describer.describe(o,a,u.map(([,f])=>f));return ut("describeReceiptTokens: DONE",{ms:Date.now()-i,overviews:d.map(f=>({name:f.name,protocol:f.protocol,asset:f.asset?.symbol,assetDecimals:f.asset?.decimals,currentApyPercent:f.currentApyPercent,avgApyPercent:f.avgApyPercent,apyChangePercent:f.apyChangePercent,totalSuppliedUsdc:f.totalSuppliedUsdc,apyHistoryPoints:f.apyHistory?.length??0}))}),new Map(d.map((f,m)=>[u[m][0],f]))}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 AB(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=il(e),i=n?Cy(n):null;return n&&i?this.describer.describe(n,i,r):[]}async positionsForChain(e,r){let n=Cy(e),i=await Ry(this.coinPoolBaseUrl,e);if(!n||i.length===0)return[];let o=await this.describer.readBalances(e,r,i);if(o.length===0)return[];let a=await this.describer.describe(e,n,o.map(l=>l.market)),s=await this.describer.convertToUnderlying(e,o,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=s[c];return u<zae?[]:[{...l,suppliedUsdc:hc(u,6),estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:hc(u*l.avgApyPercent/100,2)}]})}};p();var mO=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Ff=class{constructor(e){h(this,"coinPoolBaseUrl",e)}async listChains(){return Z0(this.coinPoolBaseUrl)}async isSupported(e){return G0(this.coinPoolBaseUrl,e)}async getMarkets(e){let r=kt(e);return r?Ry(this.coinPoolBaseUrl,r):[]}async findMarket(e,r){let n=await this.getMarkets(e);return PB(n,r)}canSupply(e){return mO.includes(e.type)}async readReceiptToken(e,r){let n=id(r).balanceIsUnderlying;try{let i=await ti(e,[{target:r.token,callData:gt({abi:Zt,functionName:"symbol"})},{target:r.token,callData:gt({abi:Zt,functionName:"decimals"})}]);return{symbol:hy(i[0]),decimals:Bp(i[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};var ol=class{constructor(e={}){h(this,"read");h(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 Y0(n);this.read=new jf(r,n,i),this.supply=new Ff(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 Ny="{market}",RB="{chain}";var NB=[{name:"supply_button_label",type:"string",description:`Label template for the per-market "Supply" 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. Use the exact placeholder "{market}" (do not translate the braces); it is replaced per market with its name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply USDC" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use BOTH exact placeholders (do not translate the braces): "{market}" is replaced with the market name, "{chain}" with the chain name it lives on. Write the connecting words around {chain} in the user's language \u2014 that is why it is a placeholder and not appended for you. English example: "supply USDC to {market} on {chain}". Vietnamese example: "n\u1EA1p USDC v\xE0o {market} tr\xEAn {chain}". Always include BOTH {market} and {chain}. Do NOT write a chain name or a contract address literally \u2014 the exact market identifier is appended automatically.`,required:!1}],$B=' A clickable "Supply" button is shown below your reply for each market automatically \u2014 do NOT list, number, or repeat those buttons in your text, and do NOT tell the user to tap one; just deliver the list and your suggestion.';function MB(t,e,r){return Hae(t,typeof e.supply_button_label=="string"?e.supply_button_label:"",typeof e.supply_prompt_template=="string"?e.supply_prompt_template:"",r)}function Hae(t,e,r,n){let i=typeof n=="string"?n.trim():"",o=[],a=new Set;for(let s of t){if(o.length>=10)break;let l=s.name?.trim();!l||a.has(l.toLowerCase())||(a.add(l.toLowerCase()),o.push({label:OB(e,l,"",`Supply ${Ny}`),prompt:OB(r,l,i,Zae(i))+Gae(s.contract)}))}return o}function Zae(t){return t?`supply USDC to ${Ny} on ${RB}`:`supply USDC to ${Ny}`}function Gae(t){let e=t?.trim();return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?` (market: ${e})`:""}function OB(t,e,r,n){return(t&&t.includes(Ny)?t:n).split(Ny).join(e).split(RB).join(r).replace(/\s+/g," ").trim()}p();var J0=[{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"]}],yO=J0.map(t=>t.label),gO={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 DB(t){let e=typeof t=="string"?t.trim():"";if(!e)return{kind:"none"};let r=Jae(e);if(!r)return{kind:"none"};let n=Wae(r);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let i=Yae(r);return i?{kind:"unsupported",label:i,requested:e}:{kind:"unknown",requested:e}}function Wae(t){let e=J0.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=J0.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 Kae(t)}function Kae(t){let e=null,r=!1;for(let n of J0)for(let i of n.aliases){let o=UB(i);if(o===0||Math.abs(i.length-t.length)>o)continue;let a=LB(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 UB(t){return t.length<=4?0:t.length<=9?2:3}function Yae(t){let e=gO[t];if(e)return e;if(t.length>=4){let i=new Set(Object.entries(gO).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(gO)){let a=UB(i);if(a===0||Math.abs(i.length-t.length)>a)continue;let s=LB(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 Jae(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function LB(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]}var Qae=["apy","score","size"],qB=5,jB=40,Bf=class extends ae{constructor(r){super();h(this,"name","get-lending-markets");h(this,"description",'List the LENDING / SUPPLY markets available to deposit into and earn yield on: protocol (Aave v3, Compound v3, Spark, Morpho vaults), market name, chain, total supplied to that market, the live supply APY plus the average over the last week and its daily change, and a 0\u201310 platform score. Ranked by the live protocol APY by default, and filterable to ONE protocol via `protocol`. 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. Each market states its own asset in `suppliedAssetSymbol`, which is usually USDC but need not be. Do NOT use for: what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.');h(this,"category","blockchain-data");h(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: ${yO.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-${jB}. 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},...NB]);h(this,"service");this.service=new ol(r)}async run(r,n){let i=Nr(r.chain,void 0),o=i?null:kt(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 ${te(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:te(a),connectedChainHasNoMarkets:o!==null,marketCount:0,markets:[],chainsWithLendingMarkets:l.map(b=>te(b))};let c=DB(r.protocol);if(c.kind==="unsupported"||c.kind==="unknown")return this.unsupportedProtocol(c);let u=a?[a]:l,d=tse(r.sort),f=rse(r.limit),m=await this.service.getMarketOverviews({chains:u}),g=c.kind==="supported"?m.filter(b=>c.matches(b)):m;if(c.kind==="supported"&&g.length===0&&m.length>0)return{_instructions:`There are no ${c.label} lending markets on ${a?te(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?te(a):"all",marketCount:0,markets:[],protocolsAvailable:[...new Set(m.map(b=>b.protocol))]};let y=[...g].sort(ese[d]).slice(0,f),_=y.slice(0,10).flatMap(b=>MB([{name:b.name,contract:b.contract}],r,te(b.chain)));return{_instructions:this.instructions(y,d,_.length>0,c.kind==="supported"?c.label:null),..._.length>0?{actionButtons:_}:{},chain:a?te(a):"all",chainsQueried:u.map(b=>te(b)),...c.kind==="supported"?{protocolFilter:c.label}:{},sortedBy:d,marketCount:y.length,totalMarketsAvailable:g.length,markets:y.map(b=>({marketName:b.name,protocol:b.protocol,protocolUrl:b.protocolUrl,chain:te(b.chain),avgApyPercent:b.avgApyPercent,avgApyDays:b.apyHistory.length,currentApyPercent:b.currentApyPercent,apyChangePercent:b.apyChangePercent,totalSuppliedUsdc:b.totalSuppliedUsdc,suppliedAssetSymbol:b.asset.symbol,platformScore:b.platformScore}))}}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:[...yO],marketCount:0,markets:[]}}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 present it as such, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${a}.`,"Present them as a NUMBERED list. Each entry starts with `marketName` as a markdown link to that","market's `protocolUrl` in bold \u2014 **[marketName](protocolUrl)** \u2014 so the name opens that market's page on","the protocol.","When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it.",'Under each name put exactly three bullet points, in this order: "Total supplied" = `totalSuppliedUsdc`,','"Protocol APY" = `currentApyPercent` (the live rate), and "Avg APY" = `avgApyPercent` labelled as the',"average over the last `avgApyDays` days. Do NOT add other bullets.","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 \u2014 mention it only when the user","asks which market is safest. A null APY means that rate was unavailable \u2014 say so rather than showing 0.",new Set(r.map(s=>s.chain)).size>1?"The markets span several chains \u2014 put each one's `chain` on the title line, after the linked name, so the user knows where it lives.":"All markets are on one chain \u2014 state the chain name once before the list, not per market.","Close with one short sentence naming the best option for the ranking used and why.","This is information, NOT financial advice \u2014 say so briefly.","Do NOT mention tool names.",i?$B:""].filter(Boolean).join(" ")}},ese={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 tse(t){let e=typeof t=="string"?t.trim().toLowerCase():"";return Qae.includes(e)?e:"apy"}function rse(t){let e=typeof t=="number"?t:Number(t);return!Number.isFinite(e)||e<1?qB:Math.min(Math.floor(e),jB)}p();var zf=class extends ae{constructor(r){super();h(this,"name","get-wallet-lending-positions");h(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.');h(this,"category","blockchain-data");h(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}]);h(this,"service");this.service=new ol(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=Nr(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 ${te(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:te(o),positionCount:0,positions:[],chainsWithLendingMarkets:s.map(u=>te(u))};let l=o?[o]:s,c=await this.service.getSupplyPositions({address:i,chains:l});return{_instructions:this.instructions(c),walletAddress:i,chain:o?te(o):"all",chainsQueried:l.map(u=>te(u)),positionCount:c.length,totals:nse(c),positions:c.map(u=>({marketName:u.name,protocol:u.protocol,protocolUrl:u.protocolUrl,chain:te(u.chain),suppliedUsdc:u.suppliedUsdc,suppliedAssetSymbol:u.asset.symbol,avgApyPercent:u.avgApyPercent,currentApyPercent:u.currentApyPercent,apyChangePercent:u.apyChangePercent,estimatedAnnualYieldUsdc:u.estimatedAnnualYieldUsdc,marketTotalSuppliedUsdc:u.totalSuppliedUsdc,apyHistory:u.apyHistory,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 daily 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).","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 nse(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:_O(n,6),estimatedAnnualYieldUsdc:_O(t.reduce((a,s)=>a+(s.estimatedAnnualYieldUsdc??0),0),2),weightedAvgApyPercent:o>0?_O(i.reduce((a,s)=>a+s.suppliedUsdc*s.avgApyPercent,0)/o,2):null}}function _O(t,e){let r=10**e;return Math.round(t*r)/r}p();var Vf=class extends ae{constructor(r){super();h(this,"name","open-supply-usdc-form");h(this,"kind","ui");h(this,"category","lending-action");h(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.');h(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)" hint, pass THAT address verbatim as this argument and ignore the market name in the sentence \u2014 the address identifies the exact market they picked, while a name may match several vaults of the same protocol.`,required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the user names; whether it carries markets is checked at call time. Set it ONLY when the user names a chain; 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}]);h(this,"service");h(this,"moralis");this.service=new ol(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=Nr(r.chain,void 0)??kt(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:te(a),chainsWithLendingMarkets:v.map(S=>te(S)),_instructions:`There are no lending markets on ${te(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=ose(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:te(a),_instructions:`No lending market matching "${s}" exists on ${te(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:te(a),candidates:l.map(v=>({marketName:v.name,protocol:v.protocol})),_instructions:`"${s}" matches ${l.length} different markets on ${te(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 ${te(a)}, plus the localized supply-button templates \u2014 that shows the user each market with its APY, size and score, each with its own Supply button to tap. 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=ise(u);if(!d)return{error:"asset_unresolved",marketName:c.name,chain:te(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[f,m]=await Promise.all([this.assetBalance(i,a,d.address),this.service.readReceiptToken(a,c)]);if(f&&Qu(f.amount,"0")<=0)return{error:"no_asset_balance",marketName:c.name,chain:te(a),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${c.name} on ${te(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=ase(r.amount),y=g?lc(g,d.decimals):null;if(y&&f&&Qu(y,f.amount)>0)return{error:"insufficient_asset_balance",marketName:c.name,chain:te(a),assetSymbol:d.symbol,requestedAmount:g,assetBalance:f.amount,_instructions:`The user wants to supply ${g} ${d.symbol} to ${c.name}, but they only hold ${f.amount} ${d.symbol} on ${te(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 ${f.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:te(a),walletAddress:i,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:u?.protocolUrl??K0(c),contract:c.contract,token:c.token,apyPercent:u?.currentApyPercent??u?.avgApyPercent??null,receiptToken:m},asset:d,...y?{prefillAmount:y}:{},...f?{spendable:f.amount}:{},...f?.usd?{spendableUsd:f.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:_},marketName:c.name,protocol:c.protocol,chain:te(a),apyPercent:_.market.apyPercent,assetSymbol:d.symbol,assetBalance:f?.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 ise(t){let e=t?.asset;return!e?.address||e.address===td||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function ose(t){let e=typeof t=="string"?t.trim():"",r=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})\s*[\])]/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}function ase(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 X0="https://ipfs.pantograph.app/ipfs/",FB=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function od(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?`${X0}${r[1]}`:FB.test(e)?`${X0}${e}`:null}function BB(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?`${X0}${r[1]}`:FB.test(e)?`${X0}${e}`:null}function zB(t){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(t)}function bO(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 sse(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 lse(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)?sse(n):decodeURIComponent(n);return JSON.parse(i)}catch{try{return JSON.parse(n)}catch{return null}}}function VB(t){let e=t?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let r=lse(e);return r?od(bO(r)):null}p();var cse=12,use=6e3;async function dse(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 pse(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 fse(t,e){let r=t?.trim();if(!r)return null;if(/^data:/i.test(r))return VB(r);let n=BB(r);if(!n)return null;if(zB(n))return n;let i=await pse(n,e);if(i){let o=od(bO(i));if(o)return o}return null}async function Q0(t,e,r){if(e.length===0)return[];let n=r?.concurrency??cse,i=r?.timeoutMs??use,o=await XF(t,e,r?.rpcUrl);return dse(o,n,a=>fse(a,i))}var HB=100,hse=100,Hf="{name}",ZB="{chain}",Zf=class extends ae{constructor(r){super();h(this,"name","get-wallet-nfts");h(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.`);h(this,"category","nft");h(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}]);h(this,"service");this.service=new ct(r)}async run(r,n){let i=fr(r.address,n),o=Nr(r.chain,n),a=o?[o]:ri(),s=vse(r.contract_address),l=KB(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:HB});return{chain:u,rows:d.success?GB(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:gse(d),contractAddress:d.token_address,chain:te(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=_se(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:HB,...a?{tokenAddresses:[a]}:{}});return{chain:g,rows:y.success?GB(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=>mse(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),f=c.map(({chain:g,row:y},_)=>{let b=yse(y);return{name:b.name,tokenId:b.tokenId,contractAddress:b.contractAddress,image:d[_]??b.image,chain:te(g)}});return{ui:{component:"WalletNftList",props:{walletAddress:n,collectionName:u,nfts:f}},_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 Q0(o,s);a.forEach((c,u)=>{n[c]=l[u]??null})}))}catch{}return n}};function GB(t){return t.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function mse(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 gse(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 yse(t){return{name:t.normalized_metadata?.name||t.name||`#${t.token_id}`,tokenId:t.token_id,contractAddress:t.token_address,image:od(t.normalized_metadata?.image||t.media?.original_media_url)}}function _se(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>=hse)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",s=a?`show my ${Hf} NFTs on ${ZB}`:`show my ${Hf} NFTs`,l=WB(n,{[Hf]:o.name,[ZB]:a},s);a&&!l.includes(a)&&(l=`${l} (${a})`),i.push({label:bse(r,o.name,Hf),prompt:`${l} (${o.contractAddress})`})}return i}function WB(t,e,r){let n=t&&t.includes(Hf)?t:r;for(let[i,o]of Object.entries(e))n=n.split(i).join(o);return n.replace(/\s+/g," ").trim()}function bse(t,e,r){return WB(t,{[Hf]:e},r)}function KB(t){if(typeof t!="string")return;let e=t.trim();return e||void 0}function vse(t){let e=KB(t);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}p();p();var wse="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.",fa=class extends ae{constructor(r){super();h(this,"kind","data");h(this,"category","nft");h(this,"llm");this.llm=new Rr(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:wse,timestamp:n},{role:"user",content:r,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Gf=class extends fa{constructor(){super(...arguments);h(this,"name","get-nft-contract-info");h(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`.');h(this,"parameters",fa.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."`));h(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 Wf=class extends fa{constructor(){super(...arguments);h(this,"name","get-nft-metadata");h(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`.');h(this,"parameters",fa.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."`));h(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 vO={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"},wO="amazon.com";function Sse(t){return t?t.trim().toLowerCase().split(/[-_]/)[0]:""}function SO(t){let e=Sse(t);return vO[e]??wO}function eS(t){return`https://${SO(t)}/s?k=NFC%20Tag`}p();function tS(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 Tse=720*60*1e3,YB=new Map,JB=3;function kse(t){return[`A user in country "${t}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${JB} 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 Pse(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>=JB))break}return i}async function TO(t,e){let r=tS(t);if(!r||!e)return null;let n=YB.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:kse(r),timestamp:i}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=Pse(a.text);if(s.length)return YB.set(r,{links:s,expires:Date.now()+Tse}),s}catch{}return null}async function Kf(t){let e=await TO(t.country,t.llm);return e&&e.length?e:[{label:"Amazon",url:eS(t.language)}]}function Ase(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(`
465
465
  `)}var XB=["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(`
466
466
  `),Yf=class extends ae{constructor(r){super();h(this,"kind","data");h(this,"name","nfc-info");h(this,"category","nfc");h(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.');h(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}]);h(this,"llm");r&&(this.llm=new Rr(r))}async run(r,n){let i=typeof r.language=="string"&&r.language.trim()?r.language.trim():void 0,o=await Kf({country:n?.country,language:i,llm:this.llm}),a=Ase(o),s=o.length>1;return{reference:XB,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)):
467
467
  ${a}