keyring-agent-core 0.4.7 → 0.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +13 -9
- package/dist/index.js +2 -2
- package/dist/index.native.js +2 -2
- package/package.json +1 -1
package/dist/index.native.js
CHANGED
|
@@ -505,7 +505,7 @@ Caused by: `,XJ=Symbol("causeStack");function axe(e,t){let r=F.hasOwnProp(e,XJ)&
|
|
|
505
505
|
`);a=s===-1?"":o.slice(s+1)}if(!n.stack)n.stack=a;else if(a){let s=a.indexOf(`
|
|
506
506
|
`),l=s===-1?-1:a.indexOf(`
|
|
507
507
|
`,s+1),c=l===-1?a:a.slice(l+1),u=String(n.stack),d=axe(n,u),p=d===-1?u:u.slice(0,d),h=d===-1?"":u.slice(d);p.endsWith(c)||(n.stack=p+`
|
|
508
|
-
`+a+h)}}catch{}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=lu(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&eO.assertOptions(n,{silentJSONParsing:ko.transitional(ko.boolean),forcedJSONParsing:ko.transitional(ko.boolean),clarifyTimeoutError:ko.transitional(ko.boolean),legacyInterceptorReqResOrdering:ko.transitional(ko.boolean),advertiseZstdAcceptEncoding:ko.transitional(ko.boolean),validateStatusUndefinedResolves:ko.transitional(ko.boolean),encodeBasicAuthUsername:ko.transitional(ko.boolean)},!1),i!=null&&(F.isFunction(i)?r.paramsSerializer={serialize:i}:eO.assertOptions(i,{encode:ko.function,serialize:ko.function},!0)),r.allowAbsoluteUrls!==void 0||(F.hasOwnProp(this.defaults,"allowAbsoluteUrls")&&this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),eO.assertOptions(r,{baseUrl:ko.spelling("baseURL"),withXsrfToken:ko.spelling("withXSRFToken")},!0),r.method=(F.getSafeProp(r,"method")||F.getSafeProp(this.defaults,"method")||"get").toLowerCase();let a=F.getSafeProp(o,"common"),s=F.getSafeProp(o,r.method),l=o&&F.merge(AX(a)?a:void 0,AX(s)?s:void 0);o&&F.forEach(XB.concat("common"),_=>{AX(F.getSafeProp(o,_))&&delete o[_]}),r.headers=In.concat(l,o);let c=[],u=!0;this.interceptors.request.forEach(function(v){if(typeof v.runWhen=="function"&&v.runWhen(r)===!1)return;u=u&&v.synchronous;let S=r.transitional||pk;S&&S.legacyInterceptorReqResOrdering?c.unshift(v.fulfilled,v.rejected):c.push(v.fulfilled,v.rejected)});let d=[];this.interceptors.response.forEach(function(v){d.push(v.fulfilled,v.rejected)});let p,h=0,y;if(!u){let _=[QC.bind(this),void 0];for(_.unshift(...c),_.push(...d),y=_.length,p=Promise.resolve(r);h<y;)p=p.then(_[h++],_[h++]);return p}y=c.length;let b=r;for(;h<y;){let _=c[h++],v=c[h++];try{b=_?_(b):b}catch(S){if(!v){p=Promise.reject(S);break}try{let w=v.call(this,S);F.isThenable(w)&&(p=Promise.resolve(w).then(()=>QC.call(this,b)))}catch(w){p=Promise.reject(w)}break}}if(!p)try{p=QC.call(this,b)}catch(_){p=Promise.reject(_)}for(h=0,y=d.length;h<y;)p=p.then(d[h++],d[h++]);return p}getUri(t){t=lu(this.defaults,t);let r=JC(t.baseURL,t.url,t.allowAbsoluteUrls,t);return zC(r,t.params,t.paramsSerializer)}};F.forEach(["delete","get","head","options"],function(t){yk.prototype[t]=async function(r,n){return this.request(lu(n||{},{method:t,url:r,data:n&&F.hasOwnProp(n,"data")?n.data:void 0}))}});F.forEach(["post","put","patch","query"],function(t){function r(n){return async function(o,a,s){return this.request(lu(s||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}yk.prototype[t]=r(),t!=="query"&&(yk.prototype[t+"Form"]=r(!0))});var tO=yk;m();var PX=class e{constructor(t){if(typeof t!="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},t(function(o,a,s){n.reason||(n.reason=new xd(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new e(function(i){t=i}),cancel:t}}},zxe=PX;m();function EX(e){return function(r){return e.apply(null,r)}}m();function IX(e){return F.isObject(e)&&e.isAxiosError===!0}m();var oj={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,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent: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,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(oj).forEach(([e,t])=>{oj[t]===void 0&&(oj[t]=e)});var Hxe=oj;function Vxe(e){let t=new tO(e),r=UC(tO.prototype.request,t);return F.extend(r,tO.prototype,t,{allOwnKeys:!0}),F.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return Vxe(lu(e,i))},r}var Fi=Vxe(mk);Fi.Axios=tO;Fi.CanceledError=xd;Fi.CancelToken=zxe;Fi.isCancel=GC;Fi.VERSION=gk;Fi.toFormData=xg;Fi.AxiosError=Ke;Fi.Cancel=Fi.CanceledError;Fi.all=function(t){return Promise.all(t)};Fi.spread=EX;Fi.isAxiosError=IX;Fi.mergeConfig=lu;Fi.AxiosHeaders=In;Fi.formToJSON=e=>JB(F.isHTMLForm(e)?new FormData(e):e);Fi.getAdapter=nj.getAdapter;Fi.HttpStatusCode=Hxe;Fi.default=Fi;var aj=Fi;var{Axios:TRr,AxiosError:ARr,CanceledError:PRr,isCancel:ERr,CancelToken:IRr,VERSION:CRr,all:ORr,Cancel:RRr,isAxiosError:$Rr,spread:NRr,toFormData:DRr,AxiosHeaders:MRr,HttpStatusCode:LRr,formToJSON:URr,getAdapter:BRr,mergeConfig:jRr,create:qRr}=aj;var Zxe="0.4.
|
|
508
|
+
`+a+h)}}catch{}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=lu(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&eO.assertOptions(n,{silentJSONParsing:ko.transitional(ko.boolean),forcedJSONParsing:ko.transitional(ko.boolean),clarifyTimeoutError:ko.transitional(ko.boolean),legacyInterceptorReqResOrdering:ko.transitional(ko.boolean),advertiseZstdAcceptEncoding:ko.transitional(ko.boolean),validateStatusUndefinedResolves:ko.transitional(ko.boolean),encodeBasicAuthUsername:ko.transitional(ko.boolean)},!1),i!=null&&(F.isFunction(i)?r.paramsSerializer={serialize:i}:eO.assertOptions(i,{encode:ko.function,serialize:ko.function},!0)),r.allowAbsoluteUrls!==void 0||(F.hasOwnProp(this.defaults,"allowAbsoluteUrls")&&this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),eO.assertOptions(r,{baseUrl:ko.spelling("baseURL"),withXsrfToken:ko.spelling("withXSRFToken")},!0),r.method=(F.getSafeProp(r,"method")||F.getSafeProp(this.defaults,"method")||"get").toLowerCase();let a=F.getSafeProp(o,"common"),s=F.getSafeProp(o,r.method),l=o&&F.merge(AX(a)?a:void 0,AX(s)?s:void 0);o&&F.forEach(XB.concat("common"),_=>{AX(F.getSafeProp(o,_))&&delete o[_]}),r.headers=In.concat(l,o);let c=[],u=!0;this.interceptors.request.forEach(function(v){if(typeof v.runWhen=="function"&&v.runWhen(r)===!1)return;u=u&&v.synchronous;let S=r.transitional||pk;S&&S.legacyInterceptorReqResOrdering?c.unshift(v.fulfilled,v.rejected):c.push(v.fulfilled,v.rejected)});let d=[];this.interceptors.response.forEach(function(v){d.push(v.fulfilled,v.rejected)});let p,h=0,y;if(!u){let _=[QC.bind(this),void 0];for(_.unshift(...c),_.push(...d),y=_.length,p=Promise.resolve(r);h<y;)p=p.then(_[h++],_[h++]);return p}y=c.length;let b=r;for(;h<y;){let _=c[h++],v=c[h++];try{b=_?_(b):b}catch(S){if(!v){p=Promise.reject(S);break}try{let w=v.call(this,S);F.isThenable(w)&&(p=Promise.resolve(w).then(()=>QC.call(this,b)))}catch(w){p=Promise.reject(w)}break}}if(!p)try{p=QC.call(this,b)}catch(_){p=Promise.reject(_)}for(h=0,y=d.length;h<y;)p=p.then(d[h++],d[h++]);return p}getUri(t){t=lu(this.defaults,t);let r=JC(t.baseURL,t.url,t.allowAbsoluteUrls,t);return zC(r,t.params,t.paramsSerializer)}};F.forEach(["delete","get","head","options"],function(t){yk.prototype[t]=async function(r,n){return this.request(lu(n||{},{method:t,url:r,data:n&&F.hasOwnProp(n,"data")?n.data:void 0}))}});F.forEach(["post","put","patch","query"],function(t){function r(n){return async function(o,a,s){return this.request(lu(s||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}yk.prototype[t]=r(),t!=="query"&&(yk.prototype[t+"Form"]=r(!0))});var tO=yk;m();var PX=class e{constructor(t){if(typeof t!="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},t(function(o,a,s){n.reason||(n.reason=new xd(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new e(function(i){t=i}),cancel:t}}},zxe=PX;m();function EX(e){return function(r){return e.apply(null,r)}}m();function IX(e){return F.isObject(e)&&e.isAxiosError===!0}m();var oj={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,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent: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,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(oj).forEach(([e,t])=>{oj[t]===void 0&&(oj[t]=e)});var Hxe=oj;function Vxe(e){let t=new tO(e),r=UC(tO.prototype.request,t);return F.extend(r,tO.prototype,t,{allOwnKeys:!0}),F.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return Vxe(lu(e,i))},r}var Fi=Vxe(mk);Fi.Axios=tO;Fi.CanceledError=xd;Fi.CancelToken=zxe;Fi.isCancel=GC;Fi.VERSION=gk;Fi.toFormData=xg;Fi.AxiosError=Ke;Fi.Cancel=Fi.CanceledError;Fi.all=function(t){return Promise.all(t)};Fi.spread=EX;Fi.isAxiosError=IX;Fi.mergeConfig=lu;Fi.AxiosHeaders=In;Fi.formToJSON=e=>JB(F.isHTMLForm(e)?new FormData(e):e);Fi.getAdapter=nj.getAdapter;Fi.HttpStatusCode=Hxe;Fi.default=Fi;var aj=Fi;var{Axios:TRr,AxiosError:ARr,CanceledError:PRr,isCancel:ERr,CancelToken:IRr,VERSION:CRr,all:ORr,Cancel:RRr,isAxiosError:$Rr,spread:NRr,toFormData:DRr,AxiosHeaders:MRr,HttpStatusCode:LRr,formToJSON:URr,getAdapter:BRr,mergeConfig:jRr,create:qRr}=aj;var Zxe="0.4.8";var nft=`keyring-agent-core/${Zxe} (Keyring Chatbot Agent; +https://keyring.app)`,CX=null;function Gxe(e){CX=e}var ift=["payment-signature","x-payment"];function oft(e){return e?Object.keys(e).some(t=>ift.includes(t.toLowerCase())):!1}var RX;function rO(e){RX=e}function Wxe(){return RX}var aft=3e4,sft=typeof process<"u"&&process.versions?.node!=null,OX=class{constructor(t={}){g(this,"instance");this.instance=aj.create({baseURL:t.baseURL,timeout:t.timeout??aft,validateStatus:()=>!0,headers:{Accept:"application/json",...sft?{"Accept-Encoding":"gzip, deflate, br","User-Agent":t.userAgent??nft}:{},...t.headers}})}async request(t,r,n,i={}){let o=i.signal??RX,a=await this.instance.request({...i,signal:o,method:t,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&&CX&&!oft(i.headers)){let c=await CX(l,{url:r,method:String(t),body:n,headers:i.headers});if(c)return this.request(t,r,n,{...i,headers:{...i.headers,...c}})}return l}get(t,r){return this.request("GET",t,void 0,r)}post(t,r,n){return this.request("POST",t,r,n)}put(t,r,n){return this.request("PUT",t,r,n)}patch(t,r,n){return this.request("PATCH",t,r,n)}delete(t,r){return this.request("DELETE",t,void 0,r)}},Qe=new OX;function It(e){let{data:t,status:r,statusText:n}=e,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof t=="string")return t.trim()||i;if(t&&typeof t=="object"){let o=t,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}m();m();m();m();function lft(e){return e instanceof Or?e.details||e.shortMessage:e instanceof Error?e.message:typeof e=="string"?e:""}var Or=class extends Error{constructor(r,n={}){let i=n.details??lft(n.cause),o=n.metaMessages??[],a=[r||"An error occurred.",...o.length>0?["",...o]:[],...i?["",`Details: ${i}`]:[]].join(`
|
|
509
509
|
`);super(a,n.cause!==void 0?{cause:n.cause}:void 0);g(this,"name","BaseError");g(this,"shortMessage");g(this,"details");g(this,"metaMessages");this.shortMessage=r,this.details=i,this.metaMessages=o,n.name&&(this.name=n.name)}walk(r){return Kxe(this,r)}};function Kxe(e,t){if(t?.(e))return e;let r=e&&typeof e=="object"?e.cause:void 0;return r!=null?Kxe(r,t):t?null:e}var Pg=class extends Or{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."]});g(this,"name","AbiParameterTypeError")}},sj=class extends Or{constructor({expectedLength:r,givenLength:n}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${r}`,`Given length (values): ${n}`]});g(this,"name","AbiEncodingLengthMismatchError")}},lj=class extends Or{constructor({expectedLength:r,givenLength:n,type:i}){super(`ABI encoding array length mismatch for type ${i}.`,{metaMessages:[`Expected length: ${r}`,`Given length: ${n}`]});g(this,"name","AbiEncodingArrayLengthMismatchError")}},cu=class extends Or{constructor({type:r,value:n,reason:i}){super(`Invalid value for ABI type "${r}".`,{metaMessages:[`Value: ${Yxe(n)}`,`Reason: ${i}`]});g(this,"name","InvalidAbiValueError")}},cj=class extends Or{constructor({type:r,value:n,min:i,max:o}){super(`Number "${n}" is not in safe ${r} range.`,{metaMessages:[`Range: ${i} \u2026 ${o}`]});g(this,"name","IntegerOutOfRangeError")}},bk=class extends Or{constructor(r){super(`Address "${Yxe(r)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]});g(this,"name","InvalidAddressError")}};function Yxe(e){if(typeof e=="bigint")return e.toString();if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var uj=class extends Or{constructor({expectedSize:r,value:n}){super(`Size of bytes "${n}" does not match expected size of bytes${r}.`);g(this,"name","AbiEncodingBytesSizeMismatchError")}},Eg=class extends Or{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."]});g(this,"name","AbiDecodingZeroDataError")}},dj=class extends Or{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)`]});g(this,"name","AbiDecodingDataSizeTooSmallError");g(this,"data");g(this,"params");g(this,"size");this.data=r,this.params=n,this.size=i}},_k=class extends Or{constructor({position:r,length:n}){super(`Position ${r} is out of bounds (${n} bytes).`,{metaMessages:["The return data is truncated or not ABI-encoded."]});g(this,"name","AbiDecodingOutOfBoundsError")}},pj=class extends Or{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."]});g(this,"name","AbiItemNotFoundError")}},Ig=class extends Or{constructor(r,n){super(`Invalid ABI signature: "${r}".`,{metaMessages:n?[n]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']});g(this,"name","InvalidAbiSignatureError")}};m();var cft=/^0x[0-9a-fA-F]*$/;function F_(e,{strict:t=!0}={}){return typeof e!="string"?!1:t?cft.test(e):e.startsWith("0x")}function Td(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}function nO(e){return typeof e=="string"?Math.ceil(Td(e).length/2):e.length}function z_(e,t,r){let n=Td(e),i=(t??0)*2,o=r===void 0?n.length:r*2;return`0x${n.slice(i,o)}`}function fj(e){return`0x${e.map(Td).join("")}`}function H_(e){let t=new Uint8Array(e.reduce((n,i)=>n+i.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}function Cg(e){let t=Td(e),r=t.length%2?`0${t}`:t,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 Im(e){let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return`0x${t}`}function $X(e){return new TextEncoder().encode(e)}function NX(e){return new TextDecoder().decode(e)}function Ns(e,t={}){let{size:r,signed:n}=t,i=BigInt(e);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: ${e} overflows int${r*8}`)}let o=i.toString(16);if(!r)return`0x${o}`;if(o.length>r*2)throw new Error(`numberToHex: ${e} overflows ${r} bytes`);return`0x${o.padStart(r*2,"0")}`}function DX(e,t=32){if(e.length>t)throw new Error(`padLeft: ${e.length} bytes exceeds ${t}`);let r=new Uint8Array(t);return r.set(e,t-e.length),r}function MX(e,t=32){if(e.length>t)throw new Error(`padRight: ${e.length} bytes exceeds ${t}`);let r=new Uint8Array(t);return r.set(e),r}function V_(e){let t=1n<<256n,r=(e%t+t)%t;return Cg(r.toString(16).padStart(64,"0"))}function vk(e,{signed:t=!1}={}){let r=BigInt(Im(e));if(!t)return r;let n=BigInt(e.length*8);return r>=1n<<n-1n?r-(1n<<n):r}function uu(e,{signed:t=!1}={}){return Td(e)?vk(Cg(e),{signed:t}):0n}function mj(e,t={}){return Number(uu(e,t))}m();var Jxe=YS(iO());var uft=/^0x[0-9a-fA-F]{40}$/;function $t(e){return typeof e=="string"&&uft.test(e)}function wk(e){let t=Td(e).toLowerCase(),r=(0,Jxe.keccak_256)(t),n="";for(let i=0;i<t.length;i++)n+=parseInt(r[i],16)>=8?t[i].toUpperCase():t[i];return`0x${n}`}function LX(e){if(!$t(e))throw new Error(`Address "${e}" is invalid.`);return wk(e)}function UX(e,t){return $t(e)&&$t(t)&&e.toLowerCase()===t.toLowerCase()}m();var gj=YS(iO());function yj(e){return`0x${(0,gj.keccak_256)(e)}`}function Xxe(e){return`0x${(0,gj.keccak_256)(new TextEncoder().encode(e))}`}function Og(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function Rg(e){return e.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function oO(e){let t=Rg(e.type);return t==="tuple"||t.startsWith("tuple[")?`(${(e.components??[]).map(oO).join(",")})${t.slice(5)}`:t}function Sk(e){return`${e.name??""}(${(e.inputs??[]).map(oO).join(",")})`}function Cm(e){let t=typeof e=="string"?e:Sk(e);return`0x${(0,gj.keccak_256)(new TextEncoder().encode(t)).slice(0,8)}`}function BX(e){let t=typeof e=="string"?e:Sk(e);return Xxe(t)}function Qxe(e,t){let r=Rg(t.type),n=Og(r);if(n){let[i,o]=n;return!Array.isArray(e)||i!==null&&e.length!==i?!1:e.every(a=>Qxe(a,{...t,type:o}))}if(r==="tuple"){let i=t.components??[];return Array.isArray(e)?e.length===i.length:typeof e=="object"&&e!==null}return r==="address"?typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e):r==="bool"?typeof e=="boolean":r==="string"?typeof e=="string":r.startsWith("bytes")?typeof e=="string"||e instanceof Uint8Array:r.startsWith("uint")||r.startsWith("int")?typeof e=="number"||typeof e=="bigint"||typeof e=="string":!0}function $g({abi:e,name:t,args:r,type:n}){let i=n??"function",o=e.filter(s=>(s.type??"function")===i);if(t.startsWith("0x")&&t.length===10)return o.find(s=>Cm(s)===t.toLowerCase());if(t.includes("("))return o.find(s=>Sk(s)===t);let a=o.filter(s=>s.name===t);return a.length<=1||!r?a[0]:a.find(s=>{let l=s.inputs??[];return l.length===r.length&&l.every((c,u)=>Qxe(r[u],c))})??a[0]}function Z_(e){let t=$g(e);if(!t)throw new pj({name:e.name,type:e.type??"function"});return t}m();function eTe(e){let t=new Uint8Array(Math.ceil(e.length/32)*32);return t.set(e),{dynamic:!0,encoded:H_([V_(BigInt(e.length)),t])}}function tTe(e,t){let r=e.slice(t.length),n=r===""?256:Number(r);if(!Number.isInteger(n)||n<8||n>256||n%8!==0)throw new Pg(e);return n}function rTe(e,t){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new cu({type:t,value:e,reason:"expected an integer, got a fractional number"});return BigInt(e)}if(typeof e=="string"&&e.trim()!=="")try{return BigInt(e.trim())}catch{throw new cu({type:t,value:e,reason:"string is not a valid integer"})}throw new cu({type:t,value:e,reason:"expected a bigint, number or numeric string"})}function nTe(e,{bits:t,signed:r,type:n}){let i=r?(1n<<BigInt(t-1))-1n:(1n<<BigInt(t))-1n,o=r?-(1n<<BigInt(t-1)):0n;if(e<o||e>i)throw new cj({type:n,value:e,min:o,max:i})}function iTe(e,t){if(e instanceof Uint8Array)return e;if(typeof e=="string"){if(!F_(e))throw new cu({type:t,value:e,reason:"expected 0x-prefixed hex"});return Cg(e)}throw new cu({type:t,value:e,reason:"expected a hex string or Uint8Array"})}function jX(e,t){let r=Og(e.type);if(r){let[i,o]=r;if(!Array.isArray(t))throw new cu({type:e.type,value:t,reason:"expected an array"});return dft({...e,type:o},t,i,e.type)}if(e.type==="tuple")return pft(e,t);let n=Rg(e.type);if(n==="address"){if(!$t(t))throw new bk(t);return{dynamic:!1,encoded:DX(Cg(Td(t).toLowerCase()))}}if(n==="bool"){if(typeof t!="boolean")throw new cu({type:n,value:t,reason:"expected a boolean"});let i=new Uint8Array(32);return i[31]=t?1:0,{dynamic:!1,encoded:i}}if(/^uint\d*$/.test(n)){let i=rTe(t,n);return nTe(i,{bits:tTe(n,"uint"),signed:!1,type:n}),{dynamic:!1,encoded:V_(i)}}if(/^int\d*$/.test(n)){let i=rTe(t,n);return nTe(i,{bits:tTe(n,"int"),signed:!0,type:n}),i<0n&&(i+=1n<<256n),{dynamic:!1,encoded:V_(i)}}if(/^bytes\d+$/.test(n)){let i=Number(n.slice(5));if(i<1||i>32)throw new Pg(e.type);let o=iTe(t,n);if(o.length!==i)throw new uj({expectedSize:i,value:String(t)});return{dynamic:!1,encoded:MX(o)}}if(n==="bytes")return eTe(iTe(t,n));if(n==="string"){if(typeof t!="string"&&!(t instanceof Uint8Array))throw new cu({type:n,value:t,reason:"expected a string"});return eTe(typeof t=="string"?$X(t):t)}throw new Pg(e.type)}function qX(e){let t=0;for(let{dynamic:o,encoded:a}of e)t+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of e)o?(r.push(V_(BigInt(t+i))),n.push(a),i+=a.length):r.push(a);return H_([...r,...n])}function dft(e,t,r,n){let i=r===null;if(!i&&t.length!==r)throw new lj({expectedLength:r,givenLength:t.length,type:n});let o=!1,a=[];for(let s of t){let l=jX(e,s);l.dynamic&&(o=!0),a.push(l)}if(i||o){let s=qX(a);if(!i)return{dynamic:!0,encoded:s};let l=V_(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?H_([l,s]):l}}return{dynamic:!1,encoded:H_(a.map(s=>s.encoded))}}function pft(e,t){let r=e.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=jX(a,Array.isArray(t)?t[o]:t[a.name??""]);s.dynamic&&(n=!0),i.push(s)}return{dynamic:n,encoded:n?qX(i):H_(i.map(o=>o.encoded))}}function kk(e,t){if(e.length!==t.length)throw new sj({expectedLength:e.length,givenLength:t.length});return e.length===0?"0x":Im(qX(e.map((r,n)=>jX(r,t[n]))))}m();function sr({abi:e,functionName:t,args:r=[]}){let n=Z_({abi:e,name:t,args:r,type:"function"}),i=Cm(n),o=n.inputs??[];return o.length===0?i:fj([i,kk(o,r)])}function FX({abi:e,errorName:t,args:r=[]}){let n=Z_({abi:e,name:t,args:r,type:"error"}),i=n.inputs??[],o=Cm(n);return i.length===0?o:fj([o,kk(i,r)])}m();function fft(e){let t=e.replace(/^u?int/,"");return t?Number(t):256}function aO(e,t){if(t<0||t+32>e.length)throw new _k({position:t,length:e.length});return e.subarray(t,t+32)}function VX(e,t){let r=vk(aO(e,t));if(r>BigInt(e.length))throw new _k({position:Number(r),length:e.length});return Number(r)}function zX(e){let t=Og(e.type);if(t){let[n,i]=t;return n===null||zX({...e,type:i})}if(e.type==="tuple")return(e.components??[]).some(zX);let r=Rg(e.type);return r==="bytes"||r==="string"}function HX(e){let t=Og(e.type);if(t){let[r,n]=t;return r===null?32:r*HX({...e,type:n})}return e.type==="tuple"?(e.components??[]).reduce((r,n)=>r+HX(n),0):32}function ZX(e,t,r){let n=[],i=t;for(let o of r)zX(o)?(n.push(oTe(e,t+VX(e,i),o)),i+=32):(n.push(oTe(e,i,o)),i+=HX(o));return n}function mft(e,t,r,n){let i=n===null?VX(e,t):n,o=n===null?t+32:t;return ZX(e,o,new Array(i).fill(r))}function hft(e,t,r){let n=r.components??[],i=ZX(e,t,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 oTe(e,t,r){let n=Og(r.type);if(n){let[o,a]=n;return mft(e,t,{...r,type:a},o)}if(r.type==="tuple")return hft(e,t,r);let i=Rg(r.type);if(i==="address")return wk(Im(aO(e,t).subarray(12)));if(i==="bool")return vk(aO(e,t))!==0n;if(/^u?int\d*$/.test(i)){let o=i.startsWith("int"),a=vk(aO(e,t),{signed:o});return fft(i)>48?a:Number(a)}if(/^bytes\d+$/.test(i)){let o=Number(i.slice(5));return Im(aO(e,t).subarray(0,o))}if(i==="bytes"||i==="string"){let o=VX(e,t),a=t+32;if(a+o>e.length)throw new _k({position:a+o,length:e.length});let s=e.subarray(a,a+o);return i==="bytes"?Im(s):NX(s)}throw new Pg(r.type)}function Va(e,t){let r=typeof t=="string"?Cg(t):t;if(r.length===0){if(e.length>0)throw new Eg;return[]}if(r.length<32)throw new dj({data:typeof t=="string"?t:Im(t),params:e,size:r.length});return ZX(r,0,e)}m();function Ln(e){if(!e)return null;try{let[t]=Va([{type:"uint256"}],e);return t}catch{return null}}function Lr(e){if(!e)return null;try{let[t]=Va([{type:"address"}],e),r=t;return/^0x0{40}$/i.test(r)?null:r}catch{return null}}function xk(e){if(!e)return null;try{let[t]=Va([{type:"string"}],e),r=aTe(t);if(r)return r}catch{}try{let[t]=Va([{type:"bytes32"}],e);return _j(t)}catch{return null}}function Tk(e){return bj(Ln(e))}function bj(e){let t=typeof e=="bigint"?Number(e):typeof e=="number"?e:NaN;return Number.isFinite(t)&&t>=0&&t<=36?t:null}function _j(e){return typeof e!="string"||!e.startsWith("0x")?null:aTe(Buffer.from(e.slice(2),"hex").toString("utf8"))||null}function aTe(e){return e.replace(/[^\x20-\x7e]/g,"").trim()}m();function Ad({abi:e,functionName:t,args:r,data:n}){let o=Z_({abi:e,name:t,args:r,type:"function"}).outputs??[],a=Va(o,n);if(a.length!==0)return a.length===1?a[0]:a}function GX({abi:e,data:t}){let r=z_(t,0,4),n=Z_({abi:e,name:r,type:"function"}),i=n.inputs??[];return{functionName:n.name,args:i.length===0||nO(t)<=4?[]:Va(i,z_(t,4))}}m();var sTe={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},lTe={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},cTe={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 Ak({abi:e=[],data:t}){let r=z_(t,0,4);if(nO(t)<4)throw new Error(`Cannot decode error result: "${t}" is too short.`);let n=[...e,sTe,lTe],i=$g({abi:n,name:r,type:"error"})??n.find(a=>(a.type??"")==="error"&&Cm(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?Va(o,z_(t,4)):void 0}}function sO({abi:e,data:t}){if(!(!t||t==="0x"))try{let{errorName:r,args:n}=Ak({abi:e,data:t});if(r==="Error")return String(n?.[0]??"");if(r==="Panic"){let i=Number(n?.[0]??0);return cTe[i]??`Panic code ${i}.`}return!n||n.length===0?r:`${r}(${n.map(i=>String(i)).join(", ")})`}catch{return}}m();var gft=new Set(["pure","view","nonpayable","payable"]),yft=new Set(["external","public","internal","private","calldata","memory","storage"]);function KX(e,t){let r=0;for(let n=t;n<e.length;n++)if(e[n]==="(")r++;else if(e[n]===")"&&(r--,r===0))return n;throw new Ig(e,"Unbalanced parentheses.")}function dTe(e){let t=[],r=0,n="";for(let i of e){if(i==="("&&r++,i===")"&&r--,i===","&&r===0){t.push(n),n="";continue}n+=i}return n.trim()&&t.push(n),t.map(i=>i.trim()).filter(Boolean)}function bft(e){let t=e.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:t?.[1]??"",rest:(t?.[2]??"").trim()}}function uTe(e,t){let r=!1,n;for(let i of e)i==="indexed"?r=!0:yft.has(i)||(n=i);return{...t,...n?{name:n}:{},...r?{indexed:!0}:{}}}function YX(e){let t=e.trim();if(t.startsWith("(")){let i=KX(t,0),o=dTe(t.slice(1,i)).map(YX),{suffix:a,rest:s}=bft(t.slice(i+1).trim());return uTe(s.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:o})}let[r,...n]=t.split(/\s+/).filter(Boolean);if(!r)throw new Ig(e,"Missing parameter type.");return uTe(n,{type:r})}function cO(e){return dTe(e).map(YX)}function lO(e,t,r){let n=e.indexOf("(",t);if(n===-1)throw new Ig(r,"Missing parameter list.");let i=KX(e,n);return{name:e.slice(t,n).trim(),params:cO(e.slice(n+1,i)),rest:e.slice(i+1).trim()}}function WX(e,t){return e.split(/[\s()]+/).find(n=>gft.has(n))??t}function vj(e){let t=e.trim();if(t.startsWith("function ")){let{name:r,params:n,rest:i}=lO(t,9,e),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 Ig(e,"`returns` without a parameter list.");s=cO(i.slice(l+1,KX(i,l)))}return{type:"function",name:r,inputs:n,outputs:s,stateMutability:WX(a,"nonpayable")}}if(t.startsWith("event ")){let{name:r,params:n}=lO(t,6,e);return{type:"event",name:r,inputs:n}}if(t.startsWith("error ")){let{name:r,params:n}=lO(t,6,e);return{type:"error",name:r,inputs:n}}if(t.startsWith("constructor")){let{params:r,rest:n}=lO(t,11,e);return{type:"constructor",inputs:r,stateMutability:WX(n,"nonpayable")}}if(t.startsWith("fallback")){let{rest:r}=lO(t,8,e);return{type:"fallback",stateMutability:WX(r,"nonpayable")}}if(t.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new Ig(e,"Expected function, event, error, constructor, fallback or receive.")}function JX(e){return e.map(vj)}m();m();m();m();function Pd({blockNumber:e,blockTag:t="latest"}={}){return e!==void 0?Ns(e):t}function uO(e){let{account:t,to:r,data:n,value:i,gas:o,gasPrice:a,maxFeePerGas:s,maxPriorityFeePerGas:l,nonce:c}=e,u={};return t&&(u.from=t),r&&(u.to=r),n&&(u.data=n),i!==void 0&&(u.value=Ns(i)),o!==void 0&&(u.gas=Ns(o)),a!==void 0&&(u.gasPrice=Ns(a)),s!==void 0&&(u.maxFeePerGas=Ns(s)),l!==void 0&&(u.maxPriorityFeePerGas=Ns(l)),c!==void 0&&(u.nonce=Ns(c)),u}function XX(e){let t={};for(let[r,n]of Object.entries(e)){let i={};n.balance!==void 0&&(i.balance=Ns(n.balance)),n.nonce!==void 0&&(i.nonce=Ns(n.nonce)),n.code!==void 0&&(i.code=n.code),n.state&&(i.state=n.state),n.stateDiff&&(i.stateDiff=n.stateDiff),t[r]=i}return t}async function Pk(e){return uu(await e.request({method:"eth_blockNumber"}))}async function Ek(e){return mj(await e.request({method:"eth_chainId"}))}async function Ik(e,{address:t,...r}){return uu(await e.request({method:"eth_getBalance",params:[t,Pd(r)]}))}async function Ng(e,{address:t,...r}){let n=await e.request({method:"eth_getCode",params:[t,Pd(r)]});return!n||n==="0x"?void 0:n}async function Ck(e,{address:t,slot:r,...n}){return await e.request({method:"eth_getStorageAt",params:[t,r,Pd(n)]})??void 0}async function Ok(e,{address:t,...r}){return mj(await e.request({method:"eth_getTransactionCount",params:[t,Pd(r)]}))}async function Rk(e){return uu(await e.request({method:"eth_gasPrice"}))}async function wj(e){return uu(await e.request({method:"eth_maxPriorityFeePerGas"}))}async function $k(e,{blockNumber:t,blockTag:r,...n}){return uu(await e.request({method:"eth_estimateGas",params:[uO(n),Pd({blockNumber:t,blockTag:r})]}))}async function Nk(e,{includeTransactions:t=!1,...r}={}){let n=await e.request({method:"eth_getBlockByNumber",params:[Pd(r),t]});return n?{...n,blockNumber:n.number?uu(n.number):void 0,blockTimestamp:n.timestamp?uu(n.timestamp):void 0,baseFee:n.baseFeePerGas?uu(n.baseFeePerGas):void 0}:null}m();var ei="0xcA11bde05977b3631167028862bE2a173976CA11",pTe={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:ei,blockCreated:14353601}}},fTe={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:ei,blockCreated:4286263}}},mTe={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:ei}}},hTe={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:ei,blockCreated:25770160}}},gTe={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:ei,blockCreated:5022}}},yTe={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:ei,blockCreated:7654707}}},bTe={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:ei}}},_Te={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:ei}}},vTe={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:ei}}},wTe={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:ei}}},STe={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:ei}}},kTe={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:ei}}},G_=[pTe,fTe,mTe,hTe,gTe,yTe,bTe,_Te,vTe,wTe,STe,kTe];var xTe=new Map,QX=new Map;function _ft(e,t){return`${e??"unknown"}|${t.toLowerCase()}`}async function TTe(e,t=ei){let r=_ft(e.chain?.id??e.chain?.hexId,t),n=xTe.get(r);if(n!==void 0)return n;let i=QX.get(r);if(i)return i;let o=(async()=>{try{let s=await Ng(e,{address:t})!==void 0;return xTe.set(r,s),s}catch{return!0}finally{QX.delete(r)}})();return QX.set(r,o),o}async function W_(e,t,r=!1){return r||typeof e.batch?.multicall=="object"&&e.batch.multicall.assumeMulticall3?!0:TTe(e,t)}m();m();var du=[{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"}]}];m();var Er=[{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}]}],Dk=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];m();var Mk=[{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"}]}];m();var Sj=[{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"}]}];m();var Ed=[{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"}]}];m();m();var Lk=class extends Or{constructor(r){super(`Chain "${r}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]});g(this,"name","ChainNotFoundError")}},K_=class extends Or{constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]});g(this,"name","ClientChainNotConfiguredError")}},Dg=class extends Or{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."]});g(this,"name","ChainDoesNotSupportContractError")}};m();async function eQ(e,t,r){let n=new Array(e.length);if(e.length===0)return n;let i=0,o=Math.max(1,Math.min(t>0?t:e.length,e.length));async function a(){for(;;){let s=i++;if(s>=e.length)return;try{n[s]={status:"fulfilled",value:await r(e[s],s)}}catch(l){n[s]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:o},a)),n}m();m();function dO({blockNumber:e,chain:t,contract:r}){let n=t.contracts?.[r];if(!n)throw new Dg({chain:t.name,contract:r});if(e!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(e))throw new Dg({blockNumber:e,chain:t.name,contract:r});return n.address}m();var Uk=class extends Or{constructor({data:r,shortMessage:n="The contract call reverted."}){super(n);g(this,"name","RawContractError");g(this,"data");this.data=r}},tQ=class extends Or{constructor({abi:r,data:n,functionName:i}){let o=n?sO({abi:r,data:n}):void 0,a,s;if(n&&n!=="0x")try{let l=Ak({abi:r,data:n});a=l.errorName,s=l.args}catch{}super(o?`The contract function "${i??"call"}" reverted with the following reason:
|
|
510
510
|
${o}`:`The contract function "${i??"call"}" reverted.`,{metaMessages:n&&n!=="0x"?[`Revert data: ${n}`]:[]});g(this,"name","ContractFunctionRevertedError");g(this,"errorName");g(this,"errorArgs");g(this,"reason");g(this,"data");this.reason=o,this.errorName=a,this.errorArgs=s,this.data=n}},rQ=class extends Or{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."]});g(this,"name","ContractFunctionZeroDataError")}},nQ=class extends Or{constructor(r,{abi:n,address:i,args:o,functionName:a,sender:s}){let l=n&&a?$g({abi:n,name:a,args:o}):void 0,c=l?Sk(l):a,u=o&&o.length>0?` args: (${o.map(p=>vft(p)).join(", ")})`:void 0,d=l?.inputs?.length?`(${l.inputs.map(oO).join(", ")})`:"()";super(r instanceof Or?r.shortMessage:`An error occurred calling "${a??"contract"}".`,{cause:r,metaMessages:[...i?[`Contract: ${i}`]:[],...c?[`Function: ${c}${l?"":d}`]:[],...u?[u]:[],...s?[`Sender: ${s}`]:[]]});g(this,"name","ContractFunctionExecutionError");g(this,"abi");g(this,"address");g(this,"args");g(this,"functionName");this.abi=n,this.address=i,this.args=o,this.functionName=a}},pO=class extends Or{constructor(r,{to:n,data:i}){super(r instanceof Or?r.shortMessage:"The call failed.",{cause:r,metaMessages:[...n?[`To: ${n}`]:[],...i?[`Data: ${i}`]:[]]});g(this,"name","CallExecutionError")}};function vft(e){if(typeof e=="bigint")return e.toString();if(typeof e=="string")return e;try{return JSON.stringify(e,(t,r)=>typeof r=="bigint"?r.toString():r)}catch{return String(e)}}function kj(e){if(!e||typeof e!="object")return;let t=e,r=t.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 t.cause?kj(t.cause):void 0}function Bk(e,{abi:t,address:r,args:n,functionName:i,sender:o}){let a=kj(e),s=e instanceof Eg?new rQ({functionName:i}):a!==void 0?new tQ({abi:t,data:a,functionName:i}):e;return new nQ(s,{abi:t,address:r,args:n,functionName:i,sender:o})}m();var iQ=new Map;function fO({fn:e,id:t,shouldSplitBatch:r,wait:n=0}){let i=()=>iQ.get(t)??void 0,o=s=>iQ.set(t,s),a=async s=>{i()===s&&iQ.delete(t);try{let l=await e(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(h=>h.item),s]))a(d);else{d.push(u);return}let p=[u];o(p),setTimeout(()=>{a(p)},n)})}}}function wft(e){return!!(e.data&&e.to&&!e.account&&!e.value&&!e.gas&&!e.gasPrice&&!e.maxFeePerGas&&!e.maxPriorityFeePerGas&&e.nonce===void 0&&!e.stateOverride)}async function Sft(e,t){let{batchSize:r=1024,wait:n=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{blockNumber:i,blockTag:o="latest",data:a,to:s}=t;if(!e.chain)throw new K_;let l=dO({blockNumber:i,chain:e.chain,contract:"multicall3"});if(!await W_(e,l,!1))throw new Dg({chain:e.chain.name,contract:"multicall3"});let c=i!==void 0?Ns(i):o,{schedule:u}=fO({id:`${e.uid}.call.${c}`,wait:n,shouldSplitBatch:h=>h.reduce((y,b)=>y+(b.data.length-2)/2,0)>r,fn:async h=>{let y=sr({abi:du,functionName:"aggregate3",args:[h.map(_=>({allowFailure:!0,callData:_.data,target:_.to}))]}),b=await e.request({method:"eth_call",params:[{to:l,data:y},c]});return Ad({abi:du,functionName:"aggregate3",data:b})}}),{returnData:d,success:p}=await u({data:a,to:s});if(!p)throw new Uk({data:d});return d}async function Id(e,t){let{blockNumber:r,blockTag:n,stateOverride:i,skipBatch:o,...a}=t;if(e.batch?.multicall&&!o&&wft(t))try{let l=await Sft(e,{blockNumber:r,blockTag:n,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof K_||l instanceof Dg))throw new pO(l,{to:a.to,data:a.data})}let s=[uO(a),Pd({blockNumber:r,blockTag:n})];i&&s.push(XX(i));try{let l=await e.request({method:"eth_call",params:s});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new pO(l,{to:a.to,data:a.data})}}var oQ=8;function ATe(e,t){if(t!==void 0&&t>0)return t;let r=typeof e.batch?.multicall=="object"?e.batch.multicall.fallbackConcurrency:void 0;return r!==void 0&&r>0?r:oQ}function mO(e,t,r){if(t)return t;if(!e.chain)throw new K_;let n=e.chain.contracts?.multicall3;return n?r!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(r)?ei:n.address:ei}async function jk(e,t,r={}){let{concurrency:n,account:i,blockNumber:o,blockTag:a,stateOverride:s}=r;return(await eQ(t,ATe(e,n),async c=>{let{data:u}=await Id(e,{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})}m();async function Cd(e,t){let{abi:r,address:n,functionName:i,args:o,...a}=t;try{let s=sr({abi:r,functionName:i,args:o}),{data:l}=await Id(e,{...a,to:n,data:s});return Ad({abi:r,functionName:i,args:o,data:l??"0x"})}catch(s){throw Bk(s,{abi:r,address:n,args:o,functionName:i,sender:a.account})}}var kft=1024,xft=50;async function Mg(e,t){let{calls:r,account:n,blockNumber:i,blockTag:o,batchSize:a=kft,maxCalls:s=xft,multicallAddress:l,stateOverride:c,fallbackConcurrency:u}=t,d=r.map(()=>({success:!1,returnData:"0x"}));if(r.length===0)return d;let p=mO(e,l,i),h=[];if(r.forEach((v,S)=>{$t(v.target)&&F_(v.callData)&&h.push({index:S,call:v})}),h.length===0)return d;if(!await W_(e,p,l!==void 0))return(await jk(e,h.map(S=>S.call),{account:n,blockNumber:i,blockTag:o,stateOverride:c,concurrency:u})).forEach((S,w)=>{d[h[w].index]={success:S.success,returnData:S.returnData}}),d;let y=[],b;return h.forEach(({call:v,index:S})=>{let w=(v.callData.length-2)/2,k=a>0&&b!==void 0&&b.size+w>a,T=s>0&&b!==void 0&&b.calls.length>=s;(!b||(k||T)&&b.calls.length>0)&&(b={calls:[],indexes:[],size:0},y.push(b)),b.calls.push(v),b.indexes.push(S),b.size+=w}),(await Promise.allSettled(y.map(v=>Cd(e,{abi:du,address:p,functionName:"aggregate3",args:[v.calls.map(S=>({target:S.target,allowFailure:!0,callData:S.callData}))],account:n,blockNumber:i,blockTag:o,stateOverride:c})))).forEach((v,S)=>{v.status==="fulfilled"&&y[S].indexes.forEach((w,k)=>{let T=v.value[k];T&&(d[w]={success:!!T.success,returnData:T.returnData??"0x"})})}),d}m();m();var PTe="https://wallet-api.pantograph.app/keyring/chains_v6",Tft=6,Aft=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,ETe={},qk=null;function Pft(e){let t=Array.isArray(e.rpcs)?e.rpcs:[],r=typeof e.linkProvider=="string"?[e.linkProvider]:[],n=[];for(let i of[...r,...t]){if(typeof i!="string")continue;let o=i.trim();if(!(!o.startsWith("https://")||Aft.test(o))&&(n.includes(o)||n.push(o),n.length>=Tft))break}return n}function ITe(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t={};for(let[r,n]of Object.entries(e)){if(!n||typeof n!="object")continue;let i=n,o=Od(r)??(typeof i.chainId=="number"?Od(i.chainId):void 0);if(!o)continue;let a=Pft(i);a.length>0&&(t[o]=a)}return t}function CTe(e){ETe=e}function aQ(e){let t=Od(e);return t?ETe[t]??[]:[]}function sQ(){qk||xj()}function xj(e={}){let{url:t=PTe,force:r=!1,debug:n=!1}=e;return qk&&!r||(qk=(async()=>{try{let i=await Qe.get(t);if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=ITe(i.data),a=Object.keys(o).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return CTe(o),n&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${t}`),!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 qk=null,!1}})()),qk}var Eft=new Map(G_.map(e=>[e.hexId.toLowerCase(),e])),Ift=new Map(G_.map(e=>[e.id,e]));function Od(e){if(typeof e=="number")return Number.isFinite(e)&&e>=0?`0x${e.toString(16)}`:void 0;let t=e.trim().toLowerCase();if(t)return t.startsWith("0x")?/^0x[0-9a-f]+$/.test(t)?t:void 0:/^\d+$/.test(t)?`0x${Number(t).toString(16)}`:void 0}function xo(e){if(typeof e=="number")return Ift.get(e);let t=Od(e);return t?Eft.get(t):void 0}function Om(e){return xo(e)?.nativeCurrency}var sc=Object.fromEntries(G_.map(e=>[e.hexId,e.rpcUrls.default.http[0]]));function lQ(e){return xo(e)?.rpcUrls.default.http[0]}var cQ={};function Y_(e){let t={};if(e)for(let[r,n]of Object.entries(e)){if(typeof n!="string"||!n.trim())continue;let i=Od(r)??r.toLowerCase();t[i]=n.trim()}cQ=t}function J_(){return{...cQ}}function Rm(e){sQ();let t=Od(e),r=t?cQ[t]:void 0,n=aQ(e),i=xo(e)?.rpcUrls.default.http??[];return[...new Set([...r?[r]:[],...n,...i])]}function X_(e){return Rm(e)[0]}function uQ(e){let t=xo(e);if(!t)return;let r=Rm(e),n=t.rpcUrls.default.http;return r.length===0||r.length===n.length&&r.every((i,o)=>i===n[o])?t:{...t,rpcUrls:{default:{http:r}}}}m();m();m();var $m=class extends Or{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)}`]:[]]});g(this,"name","HttpRequestError");g(this,"status");g(this,"url");g(this,"body");g(this,"headers");this.status=o,this.url=a,this.body=r,this.headers=i}},Fk=class extends Or{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)}`]:[]]});g(this,"name","TimeoutError")}},zk=class extends Or{constructor({cause:r,url:n}){super("Could not reach the RPC endpoint.",{cause:r,metaMessages:[`URL: ${n}`]});g(this,"name","NetworkError")}},Tj=class extends Or{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.']});g(this,"name","UrlRequiredError")}},hO=class extends Or{constructor({cause:r,count:n}){super(`All ${n} fallback transports failed.`,{cause:r});g(this,"name","FallbackTransportError")}};m();m();var Hk=class extends Or{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}`]});g(this,"name","RpcRequestError");g(this,"code");g(this,"data");this.code=n.code,this.data=n.data}};function lc(e,t,r){var n;return n=class extends Hk{constructor(o){super({...o,shortMessage:r});g(this,"name",e)}},g(n,"code",t),n}var Cft=lc("ParseRpcError",-32700,"The node could not parse the JSON request."),Oft=lc("InvalidRequestRpcError",-32600,"The JSON request is not valid."),Rft=lc("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),$ft=lc("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),Nft=lc("InternalRpcError",-32603,"The node reported an internal error."),Dft=lc("InvalidInputRpcError",-32e3,"The RPC input is not valid."),Mft=lc("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Lft=lc("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),Uft=lc("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),Bft=lc("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),dQ=lc("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),jft=lc("UserRejectedRequestError",4001,"The user rejected the request."),qft=new Map([[-32700,Cft],[-32600,Oft],[-32601,Rft],[-32602,$ft],[-32603,Nft],[-32e3,Dft],[-32001,Mft],[-32002,Lft],[-32003,Uft],[-32004,Bft],[-32005,dQ],[4001,jft]]);function OTe(e){let t=qft.get(e.error.code);return t?new t(e):new Hk(e)}m();function RTe(e){return new Promise(t=>setTimeout(t,e))}async function pQ(e,{retryCount:t=2,delay:r=150,shouldRetry:n=()=>!0}={}){let i=0;for(;;)try{return await e()}catch(o){if(i++,i>t||!n({count:i,error:o}))throw o;let a=typeof r=="function"?r({count:i,error:o}):r*2**(i-1);a>0&&await RTe(a)}}function Aj(e){let t=e?.["retry-after"];if(!t)return;let r=Number(t);if(Number.isFinite(r))return r*1e3;let n=Date.parse(t);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}var Fft=new Set([408,413,429,500,502,503,504]),zft=new Set([401,402,403]);function Pj(e){return e instanceof Fk||e instanceof zk?!0:e instanceof $m?e.status?Fft.has(e.status)||e.status>=500:!0:e instanceof dQ?!0:e instanceof Hk?e.code===-32603:!1}function Ej(e){return e instanceof $m&&e.status&&zft.has(e.status)?!0:Pj(e)}function Ij(e,{retryCount:t=3,retryDelay:r=150,maxRetryAfterMs:n}={}){return function(o,a={}){return pQ(()=>e(o),{retryCount:a.retryCount??t,shouldRetry:({error:s})=>{if(n!==void 0&&s instanceof $m){let l=Aj(s.headers);if(l!==void 0&&l>n)return!1}return Pj(s)},delay:({count:s,error:l})=>{let c=l instanceof $m?Aj(l.headers):void 0;return c!==void 0?c:(a.retryDelay??r)*2**(s-1)}})}}m();function Lg({key:e,name:t,type:r,request:n,retryCount:i=3,retryDelay:o=150,maxRetryAfterMs:a,timeout:s=1e4},l){return{config:{key:e,name:t,type:r,request:n,retryCount:i,retryDelay:o,timeout:s},request:Ij(n,{retryCount:i,retryDelay:o,maxRetryAfterMs:a}),value:l}}m();m();var $Te=0;function NTe(){return $Te+=1,$Te}function Hft(e){let t=e?.code;if(t==="ECONNABORTED"||t==="ETIMEDOUT")return!0;let r=e?.message??"";return/timeout/i.test(r)}var Vk=class{constructor(t,{timeout:r=1e4,fetchOptions:n={}}={}){g(this,"url");g(this,"timeout");g(this,"fetchOptions");this.url=t,this.timeout=r,this.fetchOptions=n}async post(t){let r;try{r=await Qe.post(this.url,t,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(n){throw Hft(n)?new Fk({body:t,url:this.url,timeout:this.timeout}):new zk({cause:n,url:this.url})}if(!r.ok)throw new $m({body:t,details:It(r),headers:r.headers,status:r.status,url:this.url});return r.data}async request(t){let r={jsonrpc:"2.0",id:NTe(),...t};return await this.post(r)??{id:r.id}}async requestBatch(t){let r=t.map(o=>({jsonrpc:"2.0",id:NTe(),...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 DTe(e,t,r){if(e.error)throw OTe({body:t,error:e.error,url:r});return e.result}function pu(e,t={}){let{batch:r,fetchOptions:n,key:i="http",name:o="HTTP JSON-RPC",retryCount:a,retryDelay:s,maxRetryAfterMs:l,timeout:c}=t;return({chain:u,retryCount:d,retryDelay:p,timeout:h}={})=>{let{batchSize:y=1e3,wait:b=0}=typeof r=="object"?r:{},_=c??h??1e4,v=e??u?.rpcUrls.default.http[0];if(!v)throw new Tj;let S=new Vk(v,{timeout:_,fetchOptions:n});return Lg({key:i,name:o,type:"http",retryCount:a??d,retryDelay:s??p,maxRetryAfterMs:l,timeout:_,async request({method:w,params:k}){let T={method:w,params:k};if(r){let{schedule:O}=fO({id:`${v}:${y}:${b}`,wait:b,shouldSplitBatch:$=>$.length>y,fn:$=>S.requestBatch($)});return DTe(await O(T),T,v)}return DTe(await S.request(T),T,v)}},{url:v})}}var MTe=1e3;function gO(e){return yO(e.map((t,r)=>pu(t,{retryCount:1,...r<e.length-1?{maxRetryAfterMs:MTe}:{}})))}function yO(e,t={}){let{key:r="fallback",name:n="Fallback",retryCount:i=0,retryDelay:o,onTransportError:a}=t;return(s={})=>{let l=e.map(u=>u(s));if(l.length===0)throw new hO({count:0});return Lg({key:r,name:n,type:"fallback",request:async u=>{let d;for(let p=0;p<l.length;p++)try{return await l[p].request(u)}catch(h){if(d=h,a?.({error:h,index:p,method:u.method}),!Ej(h))throw h}throw new hO({cause:d,count:l.length})},retryCount:i,retryDelay:o,timeout:s.timeout},{transports:l})}}m();m();var Vft=1024;async function Zk(e,t){let{contracts:r,allowFailure:n=!0,account:i,blockNumber:o,blockTag:a,multicallAddress:s,stateOverride:l,fallbackConcurrency:c}=t,u=t.batchSize??(typeof e.batch?.multicall=="object"&&e.batch.multicall.batchSize||Vft),d=new Array(r.length);if(r.length===0)return n?d:[];let p=mO(e,s,o),h=[],y;r.forEach((v,S)=>{let{abi:w,address:k,functionName:T,args:O}=v,$;try{if(!$t(k))throw new bk(k);$=sr({abi:w,functionName:T,args:O})}catch(D){let q=Bk(D,{abi:w,address:k,args:O,functionName:T,sender:i});if(!n)throw q;d[S]={status:"failure",error:q};return}let I=($.length-2)/2;(!y||u>0&&y.size+I>u&&y.calls.length>0)&&(y={calls:[],indexes:[],size:0},h.push(y)),y.calls.push({target:k,allowFailure:!0,callData:$}),y.indexes.push(S),y.size+=I}),(await W_(e,p,s!==void 0)?await Promise.allSettled(h.map(v=>Cd(e,{abi:du,address:p,functionName:"aggregate3",args:[v.calls],account:i,blockNumber:o,blockTag:a,stateOverride:l}))):await(async()=>{let v=h.flatMap(w=>w.calls.map((k,T)=>({target:k.target,callData:k.callData,index:w.indexes[T]}))),S=await jk(e,v,{account:i,blockNumber:o,blockTag:a,stateOverride:l,concurrency:c});return h.length=0,S.map((w,k)=>(h.push({calls:[],indexes:[v[k].index],size:0}),w.success?{status:"fulfilled",value:[{success:!0,returnData:w.returnData}]}:{status:"rejected",reason:w.error}))})()).forEach((v,S)=>{let w=h[S];if(v.status==="rejected"){for(let k of w.indexes){let T=r[k],O=Bk(v.reason,{abi:T.abi,address:T.address,args:T.args,functionName:T.functionName,sender:i});if(!n)throw O;d[k]={status:"failure",error:O}}return}w.indexes.forEach((k,T)=>{let O=r[k],$=v.value[T];try{if(!$)throw new Error("Multicall returned fewer results than calls.");if(!$.success)throw new Uk({data:$.returnData});if(!$.returnData||$.returnData==="0x")throw new Eg;let I=Ad({abi:O.abi,functionName:O.functionName,args:O.args,data:$.returnData});d[k]={status:"success",result:I}}catch(I){let D=Bk(I,{abi:O.abi,address:O.address,args:O.args,functionName:O.functionName,sender:i});if(!n)throw D;d[k]={status:"failure",error:D}}})});for(let v=0;v<r.length;v++){if(d[v])continue;let S=new Error("Multicall returned no result for this call.");if(!n)throw S;d[v]={status:"failure",error:S}}return n?d:d.map(v=>v.result)}var Zft=0,Q_=class{constructor(t={}){g(this,"key");g(this,"name");g(this,"uid");g(this,"chain");g(this,"transport");g(this,"batch");g(this,"request");let{batch:r,key:n="public",name:i="Public Client",retryCount:o,retryDelay:a,timeout:s}=t;this.chain=Wft(t.chain),this.key=n,this.name=i,this.batch=r,this.uid=`${n}-${++Zft}-${Math.random().toString(36).slice(2,8)}`;let c=(t.transport??Gft(t.rpcUrl,this.chain))({chain:this.chain,retryCount:o,retryDelay:a,timeout:s});this.transport={...c.config,...c.value},this.request=c.request}call(t){return Id(this,t)}readContract(t){return Cd(this,t)}multicall(t){return Zk(this,t)}multicallRaw(t){return Mg(this,t)}getBlockNumber(){return Pk(this)}getChainId(){return Ek(this)}getBalance(t){return Ik(this,t)}getCode(t){return Ng(this,t)}getStorageAt(t){return Ck(this,t)}getTransactionCount(t){return Ok(this,t)}getGasPrice(){return Rk(this)}estimateMaxPriorityFeePerGas(){return wj(this)}estimateGas(t){return $k(this,t)}getBlock(t){return Nk(this,t)}rpc(t,r){return this.request({method:t,params:r})}extend(t){let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return Object.assign(r,t(r))}};function Gft(e,t){if(e)return pu(e);let r=t?.rpcUrls.default.http??[];return r.length>1?gO(r):pu(r[0])}function Wft(e){if(e===void 0)return;if(typeof e=="object")return e;let t=uQ(e);if(!t)throw new Lk(e);return t}function Ug(e={}){return new Q_(e)}var fQ=new Map;function Kft(e,t){return{id:parseInt(e,16),hexId:e,name:`Chain ${parseInt(e,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:t}},contracts:{multicall3:{address:ei}}}}function ti(e,t={}){let{batch:r=!0,pinRpcUrl:n=!1,fallbackConcurrency:i,assumeMulticall3:o}=t,a=Od(e),s=t.rpcUrl?.trim(),l=a?Rm(a):[],c=s?n?[s]:[...new Set([s,...l])]:l;if(c.length===0)throw new Lk(e);let u=`${a??e}|${c.join(",")}|${r?1:0}|${i??""}|${o?1:0}`,d=fQ.get(u);if(d)return d;let p=Ug({chain:a&&!xo(a)?Kft(a,c):a,transport:c.length===1?pu(c[0]):gO(c),batch:r?{multicall:{fallbackConcurrency:i,assumeMulticall3:o}}:void 0});return fQ.set(u,p),p}function Cj(){fQ.clear()}function hQ(e,t){try{return ti(e,{rpcUrl:t?.trim()||void 0})}catch{return null}}async function ro(e,t,r){let n=new Array(t.length).fill(null),i=t.length>0?hQ(e,r):null;if(!i)return n;let o=[];if(t.forEach((a,s)=>{!$t(a.target)||!F_(a.callData)||o.push({index:s,target:a.target,callData:a.callData})}),o.length===0)return n;try{(await Mg(i,{calls:o})).forEach((s,l)=>{s.success&&(n[o[l].index]=s.returnData)})}catch{}return n}function Oj(e){return e?.status==="success"?e.result:void 0}async function mQ(e,t){try{return await e.multicall({contracts:t})}catch{return[]}}async function Rd(e,t,r){let n=t.map(()=>({symbol:null,decimals:null})),i=t.length>0?hQ(e,r):null;if(!i)return n;let o=[];if(t.forEach((l,c)=>{$t(l)&&o.push({index:c,address:l})}),o.length===0)return n;let a=await mQ(i,o.flatMap(l=>[{address:l.address,abi:Er,functionName:"symbol"},{address:l.address,abi:Er,functionName:"decimals"}]));o.forEach((l,c)=>{let u=Oj(a[c*2]);typeof u=="string"&&u.trim()&&(n[l.index].symbol=u.trim()),n[l.index].decimals=bj(Oj(a[c*2+1]))});let s=o.filter(l=>n[l.index].symbol===null);if(s.length>0){let l=await mQ(i,s.map(c=>({address:c.address,abi:Dk,functionName:"symbol"})));s.forEach((c,u)=>{n[c.index].symbol=_j(Oj(l[u]))})}return n}async function LTe(e,t,r){let n=new Array(t.length).fill(null),i=t.length>0?hQ(e,r):null;if(!i)return n;let o=[];return t.forEach((s,l)=>{if($t(s.contract))try{o.push({index:l,address:s.contract,tokenId:BigInt(s.tokenId)})}catch{}}),o.length===0||(await mQ(i,o.map(s=>({address:s.address,abi:Mk,functionName:"tokenURI",args:[s.tokenId]})))).forEach((s,l)=>{let c=Oj(s);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(n[o[l].index]=u)}),n}m();function bO(e){return Gk(String(e))??"0"}function Gk(e){let t=e.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!t)return null;let r=t[1]==="-"?"-":"",n=t[2]??"",i=t[3]??"";if(n===""&&i==="")return null;let o=t[4]?parseInt(t[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 gQ(e){let t=Gk(e);if(t===null||t.startsWith("-"))return null;let[r,n=""]=t.split(".");return{mant:BigInt(r+n),frac:n.length}}function Wk(e,t){let r=e<0n,n=(r?-e:e).toString(),i;if(t===0)i=n;else{let o=n.padStart(t+1,"0"),a=o.length-t;i=`${o.slice(0,a)}.${o.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return r?`-${i}`:i}function Nm(e,t){let r=Gk(e);if(r===null||r.startsWith("-"))return null;let[n,i=""]=r.split("."),o=i.slice(0,t).padEnd(t,"0");try{let a=BigInt(n||"0")*10n**BigInt(t)+BigInt(o||"0");return a>0n?a:null}catch{return null}}function ev(e){if(typeof e=="number")return Number.isFinite(e)&&e>0?bO(e):null;if(typeof e!="string")return null;let t=e.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!t)return null;let r=Gk(t[0]);return r&&r!=="0"&&!r.startsWith("-")?r:null}function kl(e,t){let r=Gk(e);if(r===null||t<0)return e;let n=r.startsWith("-"),[i,o=""]=(n?r.slice(1):r).split(".");if(o.length<=t)return r;let a=t===0?i:`${i}.${o.slice(0,t)}`,s=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${s}`:s}function tv(e,t,r,n){let i=gQ(e);if(!i||r<=0n||n<0)return e;let o=i.mant*t*10n**BigInt(n)/(r*10n**BigInt(i.frac));return Wk(o,n)}function Bg(e,t){let r=gQ(e),n=gQ(t);if(!r||!n){let s=Number(e),l=Number(t);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 Yft={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"}]},Jft="payment-required",Xft="PAYMENT-SIGNATURE",Qft="X-PAYMENT",emt="payment-response",tmt="x-payment-response",rmt=600,nmt=300,imt={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 UTe(e){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let t=new TextEncoder().encode(e),r=Array.from(t,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(e,"utf8").toString("base64")}function jTe(e){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let t=globalThis.atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(e,"base64").toString("utf8")}function omt(){let e=new Uint8Array(32),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(e);else for(let r=0;r<32;r++)e[r]=Math.floor(Math.random()*256);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function qTe(e){let t=String(e);if(t.includes(":")){let[n,i]=t.split(":"),o=parseInt(i,10);if(n!=="eip155"||Number.isNaN(o))throw new Error(`Unsupported x402 network: ${e} (only EVM "eip155:*" is supported)`);return o}let r=imt[t.toLowerCase()];if(r===void 0)throw new Error(`Unsupported x402 network: ${e}`);return r}function FTe(e){if(!e.query||Object.keys(e.query).length===0)return e.url;let t=Object.entries(e.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return e.url.includes("?")?`${e.url}&${t}`:`${e.url}?${t}`}function Rj(e){let t=e.headers[Jft];if(t){let i=BTe(amt(t));return i&&Array.isArray(i.accepts)?{version:2,payload:i}:null}let r=e.data,n=r&&typeof r=="object"?r:BTe(r);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function BTe(e){if(typeof e!="string")return null;try{let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function amt(e){try{return jTe(e)}catch{return null}}function smt(e){let t=e.amount??e.maxAmountRequired;return typeof e.scheme!="string"||typeof e.network!="string"||t==null||typeof e.asset!="string"||typeof e.payTo!="string"?null:{scheme:e.scheme,network:e.network,amount:String(t),asset:e.asset,payTo:e.payTo,...typeof e.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:e.maxTimeoutSeconds}:{},...e.extra&&typeof e.extra=="object"?{extra:e.extra}:{},...typeof e.resource=="string"?{resource:e.resource}:{},...typeof e.description=="string"?{description:e.description}:{},...typeof e.mimeType=="string"?{mimeType:e.mimeType}:{},...e.outputSchema!=null?{outputSchema:e.outputSchema}:{}}}function lmt(e){let t=null;for(let r of e){let n=smt(r);if(n){if(n.scheme!=="exact"){t=`unsupported scheme "${n.scheme}"`;continue}try{return qTe(n.network),n}catch(i){t=i instanceof Error?i.message:String(i)}}}throw new Error(t?`No payable x402 requirement offered (${t}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function yQ(e,t,r,n){let i=Rj(e);if(!i)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:a}=i,s=lmt(a.accepts??[]);if(!r)throw new Error("No connected wallet address to build the payment from");let l=qTe(s.network),c=Math.floor(Date.now()/1e3),u={from:r,to:s.payTo,value:String(s.amount),validAfter:String(Math.max(0,c-rmt)),validBefore:String(c+(s.maxTimeoutSeconds??nmt)),nonce:omt()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:l,verifyingContract:s.asset},types:Yft,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:FTe(t),method:t.method??"GET",body:t.body,headers:t.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 cmt(e,t,r,n){let i=FTe(t),o=await e.request(t.method??"GET",i,t.body,{headers:t.headers});if(o.status===402)return{status:"payment_required",challenge:yQ(o,t,r,n)};if(!o.ok)throw new Error(It(o));return{status:"ok",data:o.data}}async function bQ(e,t,r){let{url:n,method:i,body:o,headers:a}=t.request,s=await e.request(i,n,o,{headers:{...a??{},..._Q(t,r)}});if(s.ok)return s.data;throw new Error(dmt(s)??It(s))}function umt(e){return Rj(e)!==null}function zTe(e){let t=HTe(e);return t?.errorReason?t.errorReason:Rj(e)?.payload.error??null}function dmt(e){let t=zTe(e);return t?`x402 payment rejected: ${t}`:null}var pmt={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 _Q(e,t){let{requirements:r,authorization:n}=e,i={signature:t,authorization:n};if(e.x402Version===1){let a={x402Version:1,scheme:r.scheme,network:r.network,payload:i};return{[Qft]:UTe(JSON.stringify(a))}}let o={x402Version:2,...e.resource!=null?{resource:e.resource}:{},accepted:fmt(r),payload:i,...e.extensions!=null?{extensions:e.extensions}:{}};return{[Xft]:UTe(JSON.stringify(o))}}function fmt(e){let{resource:t,description:r,mimeType:n,outputSchema:i,...o}=e;return o}function HTe(e){let t=e.headers[emt]??e.headers[tmt];if(!t)return null;try{return JSON.parse(jTe(t))}catch{return null}}function mmt(e,t){return e==null?t:pmt[e]??`Chain ${e}`}async function VTe(e){let t=e.requirements,n=e.resource?.description||t.description,i=e.chainId??null,o=null,a=null;if(i!=null){let[l]=await Rd("0x"+i.toString(16),[t.asset]);o=l?.symbol??null,a=l?.decimals??null}let s=String(t.amount);if(a!==null)try{s=Wk(BigInt(t.amount),a)}catch{}return{amount:s,asset:o||t.extra?.name||"USDC",amountRaw:String(t.amount),decimals:a,assetAddress:t.asset,network:i!=null?`eip155:${i}`:t.network,networkRaw:t.network,chainId:i,networkLabel:mmt(i,t.network),payTo:t.payTo,...n?{description:n}:{},resourceUrl:e.request.url}}function vQ(e){return async(t,r)=>{let n=e.getPayer(),i=e.getSigner();if(!n||!i)return null;let o;try{o=yQ(t,{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 VTe(o)})}catch{a=null}return a?_Q(o,a):null}}m();m();var jg=class extends Error{constructor(t="Aborted"){super(t),this.name="AbortError"}};function rv(e){if(!e||typeof e!="object")return!1;let t=e;return t.name==="AbortError"||t.name==="CanceledError"||t.code==="ERR_CANCELED"}function _O(e){if(e?.aborted)throw new jg}function wQ(e,t){if(!t)return{signal:e.signal,cleanup:()=>{}};if(t.aborted)return e.abort(),{signal:e.signal,cleanup:()=>{}};let r=()=>e.abort();return t.addEventListener("abort",r),{signal:e.signal,cleanup:()=>t.removeEventListener("abort",r)}}var ZTe={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},hmt="https://nft.keyring.app/api/gemini-stable",gmt="https://generativelanguage.googleapis.com",ymt=new Set([408,429,500,502,503,504]),GTe=3e4,$j=e=>new Promise(t=>setTimeout(t,e));function Nj(e,t,r){if(r!=null&&r>0)return Math.min(r,GTe);let n=Math.min(t*2**(e-1),GTe);return n/2+Math.random()*(n/2)}function bmt(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let r=Date.parse(e);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var zi=class{constructor(t){g(this,"model");g(this,"maxTokens");g(this,"temperature");g(this,"thinkingBudget");g(this,"baseUrl");g(this,"apiKey");g(this,"requestSignal");this.model=t.model??"gemini-2.5-flash",this.maxTokens=t.maxTokens??4096,this.temperature=t.temperature??.7,this.thinkingBudget=t.thinkingBudget===void 0?0:t.thinkingBudget,this.apiKey=t.apiKey?.trim()??"",this.baseUrl=(t.baseUrl??(this.apiKey?gmt:hmt)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(t){this.requestSignal=t}async chat(t,r,n){let{systemInstruction:i,contents:o}=this.toContents(t),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;_O(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let b of c){let _=b.parts.map(v=>v.functionCall?`fc:${v.functionCall.name}`:v.functionResponse?`fr:${v.functionResponse.name}`:`text:${(v.text??"").slice(0,40)}`).join(", ");console.log(` ${b.role}: [${_}]`)}}let u=n?.thinkingBudget===void 0?this.thinkingBudget:n.thinkingBudget,d={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let p={contents:c,generationConfig:d};i&&(p.systemInstruction=i),r?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(p.tools=[{googleSearch:{}}]);let h=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,y="Unknown error";for(let b=1;b<=a;b++){_O(l);let _;try{_=await Qe.post(h,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch($){if(rv($))throw $;if(y=$ instanceof Error?$.message:String($),b>=a)break;await $j(Nj(b,s));continue}if(!_.ok){let $=typeof _.data=="string"?_.data:JSON.stringify(_.data)||_.statusText;if(y=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${_.status}: ${$}`,!ymt.has(_.status))throw new Error(y);if(b>=a)break;let I=bmt(_.headers["retry-after"]??null);await $j(Nj(b,s,I));continue}if(_.data==null||typeof _.data!="object"){if(y=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,b>=a)break;await $j(Nj(b,s));continue}let v=_.data,S=v.candidates?.[0];if(!S)return{text:"",toolCalls:[]};let w="",k=[],T=S.content?.parts;if(!Array.isArray(T)||T.length===0){let $=S.finishReason;if(!($==="SAFETY"||$==="RECITATION")&&b<a){y=`Gemini returned an empty turn (finishReason=${$??"none"})`,await $j(Nj(b,s));continue}return{text:"",toolCalls:[]}}for(let $ of T)$.text&&(w+=$.text),$.functionCall&&k.push({toolName:$.functionCall.name,args:$.functionCall.args??{},callId:$.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let O=v.usageMetadata?{promptTokens:v.usageMetadata.promptTokenCount??0,completionTokens:v.usageMetadata.candidatesTokenCount??0,totalTokens:v.usageMetadata.totalTokenCount??0,thoughtsTokens:v.usageMetadata.thoughtsTokenCount??0,cachedTokens:v.usageMetadata.cachedContentTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:O,finishReason:S.finishReason}}throw new Error(y)}toContents(t){let r=[],n=[];for(let s of t){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(`
|
|
511
511
|
`)}]}:null,contents:o}}toFunctionDeclarations(t){return t.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:ZTe[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:ZTe[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}}})}};m();var Kk=class{constructor(){g(this,"tools",new Map)}register(t){if(this.tools.has(t.name))throw new Error(`Tool "${t.name}" is already registered`);this.tools.set(t.name,t)}unregister(t){return this.tools.delete(t)}get(t){return this.tools.get(t)}has(t){return this.tools.has(t)}getDefinitions(){return Array.from(this.tools.values()).map(t=>({name:t.name,description:t.description,parameters:t.parameters,category:t.category,kind:t.kind}))}getDefinitionsByCategory(t){return this.getDefinitions().filter(r=>r.category===t)}async execute(t,r,n){let i=this.tools.get(t);if(!i)return{toolName:t,callId:`err_${Date.now()}`,success:!1,error:`Tool "${t}" 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:t,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())}};m();m();m();m();m();var Yk=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],_mt=new Set(Yk),qg=[...Yk],SQ=new Set(qg),Ds="0x1",Xk="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function vmt(e){return e.map(t=>Jk[t]??t).join(", ")}function Dj(e){let t=new Set;if(e)for(let n of e){let i=Mj(n);i&&t.add(i)}let r=Yk.filter(n=>!t.has(n));qg=r.length>0?[...r]:[...Yk],SQ=new Set(qg),Ds=qg.includes("0x1")?"0x1":qg[0],Xk=vmt(qg)}var wmt={"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 or(e){let t=Mj(e);return t&&SQ.has(t)?t:null}function Mj(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase().replace(/\s+/g," ");if(!t)return null;let r=wmt[t];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(t)?n=t:/^[0-9]+$/.test(t)&&(n="0x"+Number(t).toString(16)),n&&_mt.has(n)?n:null}function Ms(e){return or(e)!==null}function Ls(){return[...qg]}var Fg=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Xk}.`);g(this,"requested",r);g(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},Dm=e=>typeof e=="string"&&e.trim()!=="";function Sn(e,t){if(Dm(e)){let r=or(e);if(r)return r;throw new Fg(e.trim())}if(Dm(t?.chain)){let r=or(t.chain);if(r)return r;throw new Fg(t.chain.trim())}return null}function Lj(e,t){return or(e)??or(t?.chain)??void 0}var Jk={"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 ye(e){let t=Mj(e);return t&&Jk[t]?Jk[t]:typeof e=="string"&&e.trim()?e.trim():"the requested chain"}var Smt={"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 WTe(e,t){let r=Mj(e),n=r?Smt[r]:void 0;return!n||typeof t!="string"||!/^0x[0-9a-fA-F]{64}$/.test(t.trim())?null:`${n}/tx/${t.trim()}`}var kmt={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function KTe(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t?kmt[t]??null:null}var xmt={"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 Uj(e){let t=or(e);return t?xmt[t]??null:null}function Bj(e,t){if(!Dm(e)||!Dm(t))return null;let r=or(e),n=or(t);return!r||!n||r===n?null:{from:r,to:n,fromLabel:Jk[r]??r,toLabel:Jk[n]??n}}function Qk(e){return`Hex chain ID of the ${e} \u2014 same ids as \`chain\` (e.g. "0xa" Optimism, "0x2105" Base). ONLY set this when the user names a chain FOR THIS SIDE SPECIFICALLY, i.e. they named a chain per token \u2014 "swap ETH on Optimism to ETH on Base", "buy USDC on Base using ETH on Arbitrum". When the user names ONE chain for the whole request (or none), leave this EMPTY and use \`chain\` instead. Never copy the same chain into both sides.`}function jj(e,t){return{error:"cross_chain_not_supported",_instructions:`The user asked to ${e} from ${t.fromLabel} to ${t.toLabel} \u2014 that is a CROSS-CHAIN (bridge) request, which is NOT supported: a ${e} happens entirely on ONE network. Tell them, in their language, that ${e}ping between two different networks isn't supported yet, and that they can ${e} between tokens that are both on ${t.fromLabel}, or both on ${t.toLabel} (switching their wallet's network first). Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var cc=`Hex chain ID \u2014 e.g. "0xa" Optimism, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0x38" BSC, "0x1" Ethereum, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Set this WHENEVER the user names a network anywhere in their request \u2014 "swap USDC on Optimism", "buy PEPE on Base", "\u0111\u1ED5i USDC tr\xEAn Optimism", "mua PEPE tr\xEAn Base" \u2014 by mapping that name to its hex id from the list above. Do this EVEN IF it differs from the wallet's currently connected chain: that is a normal request, and the wallet is asked to switch networks when the transaction is signed. NEVER substitute the connected chain for a network the user named, and never leave this empty just because the two differ. OMIT it only when the user names no network at all \u2014 the connected wallet chain is then used automatically.`;function YTe(e,t){let r=typeof e=="string"?e.trim():"",n=t&&t.length?t.filter(o=>SQ.has(o)):[];return(n.length?n:qg).map(o=>{let a=Jk[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function ex(e,t){return{actionButtons:YTe(t),_instructions:`The user wants to ${e} 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 Ci=class extends Error{constructor(r,n){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");g(this,"code","needs_chain_selection");g(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=YTe(r,n)}},vO=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");g(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function Un(e,t){if(Dm(e))return e.trim();if(Dm(t?.walletAddress))return t.walletAddress.trim();throw new vO}function To(e,t,r){if(Dm(e)){let n=or(e);if(n)return n;throw new Fg(e.trim())}if(Dm(t?.chain)){let n=or(t.chain);if(n)return n;throw new Fg(t.chain.trim())}if(Dm(t?.walletAddress))throw new Ci(typeof t?.query=="string"?t.query:void 0,r);return Ds}var Ce=class{constructor(){g(this,"category")}async execute(t,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(t,r),a=Tmt(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 Ci?{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 vO?{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 Tmt(e){if(!e||typeof e!="object")return{data:e};let t=e,r=t.actionButtons,n=Array.isArray(r)&&r.length>0?r:void 0,i=t.ui,o=i&&typeof i=="object"&&typeof i.component=="string"?i:void 0;if(!n&&!o)return{data:e};let{actionButtons:a,ui:s,...l}=t;return{data:l,...n?{actionButtons:n}:{},...o?{ui:o}:{}}}m();m();m();m();function JTe(e){if(!e)return;let t=e.yieldProtocolV2;if(t!=null)return t;let r=e.yieldProtocol;return r??(t===null||r===null?null:void 0)}function XTe(e){let t=e?.newConfig?.yieldInfo;if(t?.assetToken){let r=t.assetDecimals==null||t.assetDecimals===""?NaN:Number(t.assetDecimals);return{address:String(t.assetToken).toLowerCase(),...Number.isFinite(r)?{decimals:r}:{},fixedPrice:t.assetFixedPrice??null}}return e?.yieldAsset}function nv(e){let t=JTe(e),r=XTe(e);return t===void 0&&r===void 0?null:{yieldProtocol:t,yieldAsset:r}}var Amt="https://wallet-api.pantograph.app",Pmt="0x0000000000000000000000000000000000000000",rAe={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},nAe={"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 Emt(e){return rAe[e.toLowerCase()]||e}function QTe(e){let t=[];for(let[r,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let i of n)t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function kQ(e){let t=e,r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=t.price,o=i!=null?parseFloat(String(i)):NaN,a=typeof t.symbolOnchain=="string"?t.symbolOnchain.trim():"";return{...t,token_address:t.token_address??t.address??"",decimals:Number.isFinite(n)?n:0,...a?{symbol:a}:{},...Number.isFinite(o)?{usd_price:o}:{}}}function eAe(e){if(Array.isArray(e))return e;let t=e;return Array.isArray(t?.items)?t.items:Array.isArray(t?.data)?t.data:[]}function Za(e){if(e==null)return null;let t=typeof e=="number"?e:parseFloat(String(e));return Number.isFinite(t)?t:null}var qj=new WeakSet;function tAe(e,t){let r=typeof e.symbolOnchain=="string"?e.symbolOnchain.trim():"",n=e.decimals,i=typeof n=="number"?n:typeof n=="string"?parseInt(n,10):null,o=Za(e.price_change_percentage_24h)??Za(e.priceChange24h)??Za(e.usd_price_24hr_percent_change)??Za(e.price_change_24h)??Za(e.priceChange),a={chainId:t,tokenAddress:e.address??e.token_address??"",name:e.name??null,symbol:r||e.symbol||null,decimals:i!=null&&Number.isFinite(i)?i:null,logo:e.logoURI??e.icon_image??e.logo??null,usdPrice:Za(e.price)??Za(e.usd_price),marketCap:Za(e.market_cap)??Za(e.marketCap),totalVolume:{"24h":Za(e.total_volume)??Za(e.volume24h)},pricePercentChange:{"24h":o}};return r&&qj.add(a),a}var Imt=100;function Cmt(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}var Oi=class{constructor(t){g(this,"baseUrl");this.baseUrl=(t?.baseUrl??Amt).replace(/\/+$/,"")}tokensUrl(t,r){let n=parseInt(t,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async fetchTokensAll(t,r){let n=Cmt(r,Imt);return(await Promise.all(n.map(async o=>{try{let a=`${this.baseUrl}/keyrings/tokens/all/${t}?addresses=${encodeURIComponent(o.join(","))}`,s=await Qe.get(a);return s.ok?eAe(s.data):[]}catch{return[]}}))).flat()}async enrichTokenPrices(t,r){let n=new Map;if(t.length===0)return n;try{let i=t.map(s=>s.token_address),o=await this.fetchTokensAll(parseInt(r,16),i),a=new Map;for(let s of o)if(s.address){let l=s.address.toLowerCase(),c=typeof s.symbolOnchain=="string"?s.symbolOnchain.trim():"";a.set(l,{price:s.price!=null?parseFloat(String(s.price)):NaN,icon_image:s.icon_image,...c?{symbolOnchain:c}:{}});let u=nv(s);u&&n.set(l,u)}for(let s=0;s<t.length;s++){let l=a.get(t[s].token_address.toLowerCase());l&&(l.icon_image&&(t[s].logo=l.icon_image,t[s].thumbnail=l.icon_image),l.symbolOnchain&&(t[s].symbol=l.symbolOnchain),isNaN(l.price)||(t[s].usd_price=l.price,t[s].usd_value=parseFloat(t[s].balance_formatted||"0")*l.price))}}catch{}return n}async getYieldPricingTokens(t,r){let n=(r??[]).map(o=>String(o??"").trim()).filter(Boolean);if(n.length===0)return[];let i=typeof t=="number"?t:String(t).startsWith("0x")?parseInt(String(t),16):parseInt(String(t),10);if(!Number.isFinite(i))return[];try{return await this.fetchTokensAll(i,n)}catch{return[]}}async getTokenMetadata(t,r){try{let n=this.tokensUrl(r,t),i=await Qe.get(n);if(!i.ok)return null;let o=eAe(i.data),a=t.toLowerCase()===Pmt,s=o.find(l=>l.address?.toLowerCase()===t.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===t.toLowerCase()||a&&l.token_address==="");return s?kQ(s):null}catch{return null}}async getTokensMetadata(t,r){let n={};if(t.length===0)return n;try{let i=await this.fetchTokensAll(parseInt(r,16),t),o=new Set(t.map(a=>a.toLowerCase()));for(let a of i){let s=a.address?.toLowerCase()||a.token_address?.toLowerCase()||(a.address===""?"":null);s&&o.has(s)&&(n[s]=kQ(a))}}catch{}return n}async searchTokensByKey(t){let{key:r,chain:n}=t;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ds,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=QTe({chainId:o,key:r}),s=`${this.baseUrl}/token-list/all?${a}`,l=await Qe.get(s);if(!l.ok)throw new Error(It(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(kQ)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(t){let r=t?.chain||Ds,n=5,i=t?.limit&&t.limit>0?Math.floor(t.limit):void 0;try{let o=nAe[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(b=>l.value[b.toLowerCase()]).filter(b=>b!=null).map(b=>tAe(b,r)):[],d=new Set,p=[];for(let b of u){let _=b.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),p.push(b))}let h=[];for(let b of c){let _=b.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(b))}let y=i!=null?[...p,...h].slice(0,i):[...p,...h.slice(0,n)];return await this.enrichTrendingMarketData(y,r),{success:!0,data:y}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(t,r){let n=t.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null||!qj.has(o)));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()];if(!a)continue;let s=typeof a.symbolOnchain=="string"?a.symbolOnchain.trim():"";s&&!qj.has(o)&&(o.symbol=s,qj.add(o)),o.marketCap==null&&(o.marketCap=Za(a.market_cap)??Za(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":Za(a.total_volume)??Za(a.volume24h)})}}async fetchTopGainers(t,r,n="24h"){let i=parseInt(t,16),o=QTe({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 Qe.get(a);if(!c.ok)throw new Error(It(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=>tAe(l,t))}async getTopGainers(t){let r=t?.chain||Ds,n=t?.limit&&t.limit>0?Math.floor(t.limit):void 0,i=t?.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"}}}};m();m();m();m();function On(e,t,r,n=[]){return{target:e,callData:sr({abi:t,functionName:r,args:n})}}var iv=1e27,Fj=10n**27n,wO=31536e3,Omt=10;function uc(e){return Number.isFinite(e)&&e>=0&&e<=Omt?e:null}function xQ(e){return Math.expm1(e)}function dc(e,t){return Number(e)/10**t}function SO(e){return new Date(e).toISOString().slice(0,10)}m();m();m();m();m();m();m();async function zg(e,t,r){let n=`${r.lendingRatesBaseUrl}/lending-rates/${t.chainId}/${e.token}?range=h&day=${7}`,i=await Qe.get(n);if(!i.ok)throw new Error(It(i));return{samples:(Array.isArray(i.data)?i.data:i.data?.data||[]).filter(a=>a?.rate!==null&&a?.rate!==void 0).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.rate)})),current:null,rewards:[]}}var $d=class{underlyingCall(t){return On(t.contract,Ed,"asset")}liveRateCall(t,r){return null}followUpRateCall(t,r){return null}decodeSize(t,r){if(!Number.isInteger(r.decimals)||r.decimals<0)return null;let n=Ln(t);return n===null?null:dc(n,r.decimals)}decodeLiveRate(t){return null}convertToAssetsCall(t,r){return this.balanceIsUnderlying?null:On(t.contract,Ed,"convertToAssets",[r])}},Nd=class extends $d{constructor(){super(...arguments);g(this,"type","spark");g(this,"balanceIsUnderlying",!1)}sizeCall(r){return On(r.contract,Ed,"totalAssets")}fetchApy(r,n,i,o){return zg(r,n,i)}};m();m();m();var TQ=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}];m();var AQ=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]},{type:"function",name:"liquidity",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint128"}]},{type:"function",name:"tickSpacing",stateMutability:"view",inputs:[],outputs:[{name:"",type:"int24"}]},{type:"function",name:"fee",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint24"}]},{type:"function",name:"token0",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"token1",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];m();var Hj=[{type:"function",name:"getReserveData",stateMutability:"view",inputs:[{name:"asset",type:"address"}],outputs:[{name:"reserveData",type:"tuple",components:[{name:"configuration",type:"uint256"},{name:"liquidityIndex",type:"uint128"},{name:"currentLiquidityRate",type:"uint128"}]}]}],tx=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],PQ=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];m();var Mm=[{inputs:[],name:"getUtilization",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseToken",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"utilization",type:"uint256"}],name:"getSupplyRate",outputs:[{name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseTrackingSupplySpeed",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseIndexScale",outputs:[{name:"",type:"uint64"}],stateMutability:"pure",type:"function"}],EQ=[{inputs:[{name:"comet",type:"address"}],name:"rewardConfig",outputs:[{name:"token",type:"address"},{name:"rescaleFactor",type:"uint64"},{name:"shouldUpscale",type:"bool"}],stateMutability:"view",type:"function"}];m();var rx=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],Hg=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],IQ=[{inputs:[],name:"susds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];m();var CQ=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],OQ=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var Nmt=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|
|
@@ -546,7 +546,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
|
|
|
546
546
|
- Market Cap: <marketCap>
|
|
547
547
|
- Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
|
|
548
548
|
- 24h Volume: <totalVolume.24h>
|
|
549
|
-
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:i?ye(i):"all",timeFrame:a??null,count:u.length,tokens:u}}};m();m();m();function dx(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[r,n=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${r}.${(n+"00").slice(0,2)}`}function px(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<=0))return`($${dx(e)})`}var fx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-token-balances");g(this,"description",'Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ');g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n);if(o){let l=await this.service.getWalletTokenBalances({address:i,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return l.success?this.renderBalances(i,o,l.data?.result||[]):{error:l.error||"Failed to fetch token balances"}}let a=Ls(),s=await Promise.all(a.map(async l=>{let c=await this.service.getWalletTokenBalances({address:i,chain:l,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:l,tokens:c.success?c.data?.result||[]:[]}}));return this.renderBalancesByChain(i,s)}toTokenLine(r){let n=r.name||r.symbol||"Unknown",i=r.balance_formatted??"0",o=r.symbol||"",a=typeof r.usd_value=="number"?`$${dx(r.usd_value)}`:"$-";return`- ${n}: ${i} ${o} (${a})`.replace(/\s+/g," ").trim()}renderBalances(r,n,i){let o=i.reduce((a,s)=>a+(s.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:r,chain:n,totalUsdValue:`$${dx(o)}`,tokens:i.map(a=>this.toTokenLine(a))}}renderBalancesByChain(r,n){let i=n.map(a=>{let s=a.tokens.reduce((c,u)=>c+(u.usd_value||0),0),l=a.tokens.slice().sort((c,u)=>(u.usd_value||0)-(c.usd_value||0));return{chain:ye(a.chain),total:s,tokens:l}}).filter(a=>a.tokens.length>0).sort((a,s)=>s.total-a.total),o=i.reduce((a,s)=>a+s.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:r,chain:"all",totalUsdValue:`$${dx(o)}`,chains:i.map(a=>({chain:a.chain,totalUsdValue:`$${dx(a.total)}`,tokens:a.tokens.map(s=>this.toTokenLine(s))}))}}};m();var mx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-history");g(this,"description",`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=To(r.chain,n),a=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,s=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,l=typeof r.fromBlock=="number"?r.fromBlock:typeof r.fromBlock=="string"&&r.fromBlock?Number(r.fromBlock):void 0,c=typeof r.toBlock=="number"?r.toBlock:typeof r.toBlock=="string"&&r.toBlock?Number(r.toBlock):void 0,u=Number.isFinite(l)?l:void 0,d=Number.isFinite(c)?c:void 0,p=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,y=(typeof r.order=="string"?r.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",b=typeof r.includeInternalTransactions=="boolean"?r.includeInternalTransactions:void 0,_=typeof r.nftMetadata=="boolean"?r.nftMetadata:void 0,v=typeof r.limit=="number"?r.limit:typeof r.limit=="string"?Number(r.limit):void 0,S=Number.isFinite(v)&&v>0?v:10,w=await this.service.getWalletHistory({address:i,chain:o,limit:S,fromDate:a,toDate:s,fromBlock:u,toBlock:d,cursor:p,order:y,includeInternalTransactions:b,nftMetadata:_});if(!w.success)return{error:w.error||"Failed to fetch wallet history"};let T=(w.data?.result||[]).map(O=>{let $=WTe(o,O.hash);return $?{...O,explorerUrl:$}:O});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:i,chain:o||"default",pagination:{cursor:w.data?.cursor??null,hasMore:!!w.data?.cursor},transactionCount:T.length,transactions:T}}};m();function uht(e){if(e.value_decimal)return e.value_decimal;let t=parseInt(e.token_decimals??"18",10);if(isNaN(t)||t===0)return e.value;try{let r=BigInt(e.value),n=BigInt(10)**BigInt(t),i=r/n,a=(r%n).toString().padStart(t,"0").replace(/0+$/,"");return a?`${i}.${a}`:`${i}`}catch{return e.value}}var hx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-token-transfers");g(this,"description",`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=To(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):25,l=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,c=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,u=this.parseBlock(r.fromBlock),d=this.parseBlock(r.toBlock),p=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,y=(typeof r.order=="string"?r.order.toUpperCase():"")==="ASC"?"ASC":"DESC",b=typeof r.direction=="string"?r.direction.trim().toLowerCase():"all",_=b==="send"?"send":b==="receive"?"receive":"all",v=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,S=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(N=>typeof N=="string"&&!!N).map(N=>N.trim()):void 0,w,k;if(v){let N=await this.resolveContractAddressBySymbol(v,i,o);N&&(S=[N.address],w=N.symbol,k=N.name)}let T=await this.service.getWalletTokenTransfers({address:i,chain:o,contractAddresses:S,limit:s,fromDate:l,toDate:c,fromBlock:u,toBlock:d,cursor:p,order:y});if(!T.success)return{error:T.error||"Failed to fetch token transfers"};let O=i.toLowerCase(),I=(T.data?.result||[]).map(N=>{let G=N.from_address.toLowerCase()===O,U=G?"send":"receive",H=G?N.to_address:N.from_address,L=G?N.to_address_label??void 0:N.from_address_label??void 0,M=G?N.to_address_entity??void 0:N.from_address_entity??void 0;return{...N,direction:U,amount_formatted:uht(N),counterparty:H,counterparty_label:L,counterparty_entity:M}}),D=_==="all"?I:I.filter(N=>N.direction===_);if(v&&!S){let N=v.toLowerCase();D=D.filter(G=>(G.token_symbol??"").toLowerCase()===N)}let q=this.buildCounterparties(D);return{walletAddress:i,chain:o||"default",resolvedToken:w?{symbol:w,name:k,contractAddress:S?.[0]}:null,filters:{tokenSymbol:v||null,contractAddresses:S||null,direction:_,limit:s,order:y,fromDate:l||null,toDate:c||null,fromBlock:u??null,toBlock:d??null},pagination:{cursor:T.data?.cursor??null,pageSize:T.data?.page_size??s,page:T.data?.page??null,hasMore:!!T.data?.cursor},transferCount:D.length,transfers:D,counterparties:q}}async resolveContractAddressBySymbol(r,n,i){let o=r.toLowerCase(),a=await this.service.getWalletTokenBalances({address:n,chain:i});if(a.success&&a.data?.result?.length){let l=a.data.result.find(c=>(c.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}let s=await this.service.searchTokensByKey({key:r,chain:i});if(s.success&&s.data?.length){let c=s.data.find(u=>(u.symbol??"").toLowerCase()===o)??s.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name}}}buildCounterparties(r){let n=new Map,i=new Map;for(let a of r){let s=a.direction==="send"?n:i,l=a.counterparty.toLowerCase(),c=parseFloat(a.amount_formatted)||0,u=s.get(l);u?(u.total+=c,u.count+=1,!u.label&&a.counterparty_label&&(u.label=a.counterparty_label),!u.entity&&a.counterparty_entity&&(u.entity=a.counterparty_entity),a.block_timestamp<u.first&&(u.first=a.block_timestamp),a.block_timestamp>u.last&&(u.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,total:c,count:1,first:a.block_timestamp,last:a.block_timestamp})}let o=a=>Array.from(a.entries()).sort((s,l)=>l[1].count-s[1].count).map(([s,l])=>({address:s,label:l.label,entity:l.entity,total_amount:l.total.toFixed(6).replace(/\.?0+$/,""),tx_count:l.count,first_seen:l.first,last_seen:l.last}));return{sent:o(n),received:o(i)}}parseBlock(r){if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"&&r){let n=Number(r);return Number.isFinite(n)?n:void 0}}};m();var gx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-nft-transfers");g(this,"description",`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=To(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):25,l=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,c=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,u=this.parseBlock(r.fromBlock),d=this.parseBlock(r.toBlock),p=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,y=(typeof r.order=="string"?r.order.toUpperCase():"")==="ASC"?"ASC":"DESC",b=typeof r.includePrices=="boolean"?r.includePrices:void 0,_=typeof r.direction=="string"?r.direction.trim().toLowerCase():"all",v=_==="send"?"send":_==="receive"?"receive":"all",S=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(D=>typeof D=="string"&&!!D).map(D=>D.trim()):void 0,w=await this.service.getWalletNftTransfers({address:i,chain:o,contractAddresses:S,limit:s,fromDate:l,toDate:c,fromBlock:u,toBlock:d,cursor:p,order:y,includePrices:b});if(!w.success)return{error:w.error||"Failed to fetch NFT transfers"};let k=i.toLowerCase(),O=(w.data?.result||[]).map(D=>{let q=D.from_address.toLowerCase()===k,N=q?"send":"receive",G=q?D.to_address:D.from_address,U=q?D.to_address_label??void 0:D.from_address_label??void 0,H=q?D.to_address_entity??void 0:D.from_address_entity??void 0;return{...D,direction:N,counterparty:G,counterparty_label:U,counterparty_entity:H}}),$=v==="all"?O:O.filter(D=>D.direction===v),I=this.buildCounterparties($);return{walletAddress:i,chain:o||"default",filters:{contractAddresses:S||null,direction:v,limit:s,order:y,fromDate:l||null,toDate:c||null,fromBlock:u??null,toBlock:d??null,includePrices:b??null},pagination:{cursor:w.data?.cursor??null,pageSize:w.data?.page_size??s,page:w.data?.page??null,hasMore:!!w.data?.cursor},transferCount:$.length,transfers:$,counterparties:I}}buildCounterparties(r){let n=new Map,i=new Map;for(let a of r){let s=a.direction==="send"?n:i,l=a.counterparty.toLowerCase(),c=a.token_name??a.token_address,u=s.get(l);u?(u.tokenIds.add(a.token_id),u.collections.add(c),u.count+=1,!u.label&&a.counterparty_label&&(u.label=a.counterparty_label),!u.entity&&a.counterparty_entity&&(u.entity=a.counterparty_entity),a.block_timestamp<u.first&&(u.first=a.block_timestamp),a.block_timestamp>u.last&&(u.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,tokenIds:new Set([a.token_id]),collections:new Set([c]),count:1,first:a.block_timestamp,last:a.block_timestamp})}let o=a=>Array.from(a.entries()).sort((s,l)=>l[1].count-s[1].count).map(([s,l])=>({address:s,label:l.label,entity:l.entity,token_ids:Array.from(l.tokenIds),collections:Array.from(l.collections),tx_count:l.count,first_seen:l.first,last_seen:l.last}));return{sent:o(n),received:o(i)}}parseBlock(r){if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"&&r){let n=Number(r);return Number.isFinite(n)?n:void 0}}};m();var dht=["all","7","30","60","90"],yx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-pnl-summary");g(this,"description",`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=dht.includes(a)?a:void 0;if(o){let _=await this.service.getWalletPnlSummary({address:i,chain:o,days:s});return _.success?{walletAddress:i,chain:o,days:s??"all",summary:this.mapSummary(_.data)}:{error:_.error||"Failed to fetch wallet PnL summary"}}let c=(await Promise.all(Ls().map(async _=>{let v=await this.service.getWalletPnlSummary({address:i,chain:_,days:s});return{chain:_,data:v.success?v.data:void 0}}))).flatMap(_=>_.data&&_.data.total_count_of_trades>0?[{chain:_.chain,data:_.data}]:[]),u=c.map(_=>({chain:ye(_.chain),summary:this.mapSummary(_.data)})),d=c.reduce((_,v)=>_+Number(v.data.total_realized_profit_usd||0),0),p=c.reduce((_,v)=>_+Number(v.data.total_bought_volume_usd||0),0),h=c.reduce((_,v)=>_+Number(v.data.total_sold_volume_usd||0),0),y=c.reduce((_,v)=>_+Number(v.data.total_trade_volume||0),0),b={totalCountOfTrades:c.reduce((_,v)=>_+v.data.total_count_of_trades,0),totalTradeVolume:y,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:p>0?d/p*100:0,totalBuys:c.reduce((_,v)=>_+v.data.total_buys,0),totalSells:c.reduce((_,v)=>_+v.data.total_sells,0),totalBoughtVolumeUsd:p,totalSoldVolumeUsd:h};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:i,chain:"all",days:s??"all",summary:b,chains:u}}mapSummary(r){return{totalCountOfTrades:r.total_count_of_trades,totalTradeVolume:r.total_trade_volume,totalRealizedProfitUsd:r.total_realized_profit_usd,totalRealizedProfitPercentage:r.total_realized_profit_percentage,totalBuys:r.total_buys,totalSells:r.total_sells,totalBoughtVolumeUsd:r.total_bought_volume_usd,totalSoldVolumeUsd:r.total_sold_volume_usd}}};m();var pht=["all","7","30","60","90"],Yj=25,bx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-pnl");g(this,"description",`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${Yj}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${Yj}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${Yj}.`,required:!1,items:{type:"string"}}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=pht.includes(a)?a:void 0,l=Array.isArray(r.tokenSymbols)?r.tokenSymbols.filter(p=>typeof p=="string"&&!!p.trim()).map(p=>p.trim()):[],c=Array.isArray(r.tokenAddresses)?r.tokenAddresses.filter(p=>typeof p=="string"&&!!p.trim()).map(p=>p.trim()):[];if(o){let p=await this.fetchChainPnl(i,o,s,l,c);return p.ok?{walletAddress:i,chain:o,days:s??"all",filters:{tokenAddresses:p.tokenAddresses??null,resolvedSymbols:p.resolvedFromSymbols.length>0?p.resolvedFromSymbols:null,unresolvedSymbols:p.unresolvedSymbols.length>0?p.unresolvedSymbols:null},tokenCount:p.tokens.length,tokens:p.tokens}:{error:p.error||"Failed to fetch wallet PnL"}}let d=(await Promise.all(Ls().map(async p=>({chain:p,res:await this.fetchChainPnl(i,p,s,l,c)})))).filter(p=>p.res.ok&&p.res.tokens.length>0).map(p=>({chain:ye(p.chain),tokenCount:p.res.tokens.length,tokens:p.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:i,chain:"all",days:s??"all",filters:{requestedSymbols:l.length>0?l:null,requestedAddresses:c.length>0?c:null},tokenCount:d.reduce((p,h)=>p+h.tokenCount,0),chains:d}}async fetchChainPnl(r,n,i,o,a){let s=[],l=[];o.length>0&&(await Promise.all(o.map(h=>this.resolveContractAddress(h,n,r)))).forEach((h,y)=>{h?s.push({symbol:o[y],address:h.address}):l.push(o[y])});let c=fht([...s.map(p=>p.address),...a]).slice(0,Yj),u=c.length>0?c:void 0,d=await this.service.getWalletPnl({address:r,chain:n,days:i,tokenAddresses:u});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:u,resolvedFromSymbols:s,unresolvedSymbols:l}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(c=>(c.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};function fht(e){let t=new Set,r=[];for(let n of e){let i=n.toLowerCase();t.has(i)||(t.add(i),r.push(n))}return r}m();var mht=BigInt(2)**BigInt(255),_x=class extends Ce{constructor(r){super();g(this,"name","get-wallet-approvals");g(this,"description",`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=To(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):100,l=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,c=await this.service.getWalletApprovals({address:i,chain:o,limit:s,cursor:l});if(!c.success)return{error:c.error||"Failed to fetch wallet approvals"};let u=c.data,p=(u.result||[]).map(_=>hht(_)),h=0,y=0,b=[];for(let _ of p){_.isUnlimited&&(y+=1);let v=parseFloat(_.token.usdAtRisk??"");Number.isFinite(v)&&(h+=v);let S=_.token.possibleSpam||_.token.verifiedContract===!1,w=!_.spender.label&&!_.spender.entity;(S||_.isUnlimited&&w)&&b.push(_)}return{walletAddress:i,chain:o||"default",filters:{limit:s,cursor:l??null},pagination:{cursor:u.cursor??null,pageSize:u.page_size??s,page:u.page??null,hasMore:!!u.cursor},summary:{totalApprovals:p.length,unlimitedApprovals:y,totalUsdAtRisk:h,riskyApprovalCount:b.length},approvals:p,riskyApprovals:b}}};function hht(e){let t=ght(e.value);return{blockNumber:e.block_number,blockTimestamp:e.block_timestamp??null,transactionHash:e.transaction_hash??null,value:e.value,valueFormatted:e.value_formatted??null,isUnlimited:t,token:{address:e.token.address,addressLabel:e.token.address_label??null,name:e.token.name??null,symbol:e.token.symbol??null,logo:e.token.logo??null,possibleSpam:!!e.token.possible_spam,verifiedContract:e.token.verified_contract??null,currentBalance:e.token.current_balance??null,currentBalanceFormatted:e.token.current_balance_formatted??null,usdPrice:e.token.usd_price??null,usdAtRisk:e.token.usd_at_risk??null},spender:{address:e.spender.address,label:e.spender.address_label??null,entity:e.spender.entity??null,entityLogo:e.spender.entity_logo??null}}}function ght(e){if(!e)return!1;try{return BigInt(e)>=mht}catch{return!1}}m();var pAe=.01,vx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-defi-positions");g(this,"description",`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n);if(o){let l=await this.service.getWalletDefiPositions({address:i,chain:o});if(!l.success)return{error:l.error||"Failed to fetch wallet DeFi positions"};let c=(l.data||[]).filter(fAe);return{walletAddress:i,chain:o,positionCount:c.length,positions:c.map(mAe)}}let s=(await Promise.all(Ls().map(async l=>{let c=await this.service.getWalletDefiPositions({address:i,chain:l});return{chain:l,rows:c.success?(c.data||[]).filter(fAe):[]}}))).filter(l=>l.rows.length>0).map(l=>({chain:ye(l.chain),positionCount:l.rows.length,positions:l.rows.map(mAe)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:i,chain:"all",positionCount:s.reduce((l,c)=>l+c.positionCount,0),chains:s}}};function fAe(e){let t=e.position?.balance_usd,r=e.position?.total_unclaimed_usd_value;return typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=pAe?!0:typeof r=="number"&&r>=pAe}function mAe(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,accountHealthFactor:e.account_data?.health_factor??null,position:yht(e.position)}}function yht(e){return{label:e.label,address:e.address,balanceUsd:e.balance_usd,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,tokens:(e.tokens||[]).map(t=>({tokenType:t.token_type,name:t.name,symbol:t.symbol,contractAddress:t.contract_address,decimals:t.decimals,logo:t.logo,thumbnail:t.thumbnail,balance:t.balance,balanceFormatted:t.balance_formatted,usdPrice:t.usd_price,usdValue:t.usd_value})),details:e.position_details??null}}m();var wx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-defi-protocol-positions");g(this,"description",`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=r.protocol?.trim();if(!i)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=Un(r.address,n),a=Sn(r.chain,n);if(a){let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:a});return c.success?c.data?{walletAddress:o,chain:a,...this.protocolFields(c.data)}:{error:"No data returned for this protocol"}:{error:c.error||"Failed to fetch wallet DeFi protocol positions"}}let l=(await Promise.all(Ls().map(async c=>{let u=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:c});return{chain:c,data:u.success?u.data:void 0}}))).flatMap(c=>c.data&&(c.data.positions||[]).length>0?[{chain:ye(c.chain),data:c.data}]:[]).map(c=>({chain:c.chain,...this.protocolFields(c.data)})).sort((c,u)=>u.totalUsdValue-c.totalUsdValue);return{_instructions:`These ${i} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:i,totalUsdValue:l.reduce((c,u)=>c+u.totalUsdValue,0),chains:l}}protocolFields(r){return{protocolName:r.protocol_name,protocolId:r.protocol_id,protocolUrl:r.protocol_url,protocolLogo:r.protocol_logo,totalUsdValue:r.total_usd_value,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,accountHealthFactor:r.account_data?.health_factor??null,positionCount:(r.positions||[]).length,positions:(r.positions||[]).map(bht)}}};function bht(e){return{label:e.label,address:e.address,balanceUsd:e.balance_usd,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,tokens:(e.tokens||[]).map(t=>({tokenType:t.token_type,name:t.name,symbol:t.symbol,contractAddress:t.contract_address,decimals:t.decimals,logo:t.logo,thumbnail:t.thumbnail,balance:t.balance,balanceFormatted:t.balance_formatted,usdPrice:t.usd_price,usdValue:t.usd_value})),details:e.position_details??null}}m();function _ht(e){try{return(Number(BigInt(e))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return e}}var Sx=class extends Ce{constructor(r){super();g(this,"name","get-transaction-by-hash");g(this,"description",'Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.');g(this,"category","blockchain-data");g(this,"parameters",[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=r.transactionHash;if(!i)return{error:"Transaction hash is required."};let o=To(r.chain,n),a=await this.service.getTransactionByHash({transactionHash:i,chain:o});if(!a.success||!a.data)return{error:a.error||"Failed to fetch transaction"};let s=a.data,l=(s.logs??[]).filter(u=>!!u.decoded_event).map(u=>({contract:u.address,signature:u.decoded_event.signature,label:u.decoded_event.label,params:u.decoded_event.params})),c=s.logs.map(u=>({address:u.address,decodedEvent:u.decoded_event?{signature:u.decoded_event.signature,label:u.decoded_event.label,params:u.decoded_event.params}:null}));return{hash:s.hash,status:s.receipt_status==="1"?"success":s.receipt_status==="0"?"failed":"unknown",timestamp:s.block_timestamp,blockNumber:s.block_number,from:{address:s.from_address,label:s.from_address_label||null,entity:s.from_address_entity||null},to:s.to_address?{address:s.to_address,label:s.to_address_label||null,entity:s.to_address_entity||null}:null,valueEth:_ht(s.value||"0"),fee:s.transaction_fee,gasUsed:s.receipt_gas_used,gasPriceGwei:s.gas_price?(Number(s.gas_price)/1e9).toFixed(4):null,decodedCall:s.decoded_call?{signature:s.decoded_call.signature,label:s.decoded_call.label,params:s.decoded_call.params}:null,decodedEvents:l,contractCreated:s.receipt_contract_address||null,logs:c}}};m();m();m();m();m();var hAe=new Map;function vht(e){let t=hAe.get(e);if(t)return t;let r=Ug({rpcUrl:e});return hAe.set(e,r),r}async function gAe(e,t,r=[]){let n=await vht(e).rpc(t,r);if(n===void 0)throw new Error(`RPC ${t}: empty result`);return n}function yAe(e,t,r){return gAe(e,"eth_call",[{to:t,data:r},"latest"])}async function wht(e,t,r){let n=X_(e);if(!n)return null;try{return await yAe(n,t,r)}catch{return null}}m();m();m();function Yt(e,t){globalThis.__LENDING_DEBUG__!==!1&&(t===void 0?console.log(`[LEND] ${e}`):console.log(`[LEND] ${e}`,JSON.stringify(t,Sht)))}function Sht(e,t){return typeof t=="bigint"?`${t}n`:t}var kht=6e4,MQ=new Map;async function MO(e,t){let r=Lm(t),n=r?parseInt(r,16):NaN;if(!r||!Number.isFinite(n))return[];let i=`${e}|${r}`,o=MQ.get(i);if(o&&Date.now()-o.at<kht)return o.markets;let a=xht(e,r,n),s=a.then(l=>l.markets);return MQ.set(i,{at:Date.now(),markets:s}),a.then(l=>{l.answered||MQ.delete(i)}),s}async function Jj(e,t){return(await MO(e,t)).length>0}async function xht(e,t,r){try{let n=`${e}/supply/v2?chainId=${r}&limit=100&page=1`;Yt("catalog: GET",n);let i=await Qe.get(n);if(!i.ok){let a=i.status>=400&&i.status<500;return Yt(a?"catalog: chain not served":"catalog: FAILED",{chain:t,status:i.status,message:It(i)}),{markets:[],answered:a}}let o=(i.data?.data?.items||[]).flatMap(a=>{let s=Tht(a,t);return s?[s]:[]});return Yt("catalog: got markets",{chain:t,rawItems:i.data?.data?.items?.length??0,usable:o.length,tokens:o.map(a=>a.token)}),{markets:o,answered:!0}}catch(n){return Yt("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:t,message:n?.message}),{markets:[],answered:!1}}}function bAe(e,t){let r=t.trim().toLowerCase();if(!r)return[];if($t(r))return e.filter(i=>i.contract===r||i.token===r);let n=e.filter(i=>i.name.trim().toLowerCase()===r);return n.length>0?n:e.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 Tht(e,t){if(e?.isDeleted===!0)return null;let r=typeof e?.contract=="string"?e.contract.toLowerCase():"";if(!$t(r))return null;let n=typeof e?.token=="string"&&$t(e.token)?e.token.toLowerCase():r,i=Number(e?.rating?.balanceScore),o=e?.type?.trim()||"unknown";return{chain:t,name:e?.name?.trim()||"USDC lending market",protocol:e?.protocolId?.name?.trim()||"Unknown",protocolLabel:xl(o),protocolUrl:e?.protocolId?.domain?.trim()||null,type:o,contract:r,token:n,platformScore:Number.isFinite(i)?i:null}}function LQ(){return Ls()}async function Xj(e){let t=LQ(),r=await Promise.all(t.map(n=>Jj(e,n)));return t.filter((n,i)=>r[i])}async function Qj(e,t){let r=or(t);return r?Jj(e,r):!1}async function _Ae(e,t){let r=t.map(o=>or(o)).filter(o=>!!o),n=[...new Set(r)],i=await Promise.all(n.map(o=>Jj(e,o)));return n.filter((o,a)=>i[a])}m();function sv(e){return CO(e)}var vAe=6;async function wAe(e,t,r){let n=t.map(w=>$t(w)?w.toLowerCase():null);if(n.every(w=>w===null))return Yt("discovery: ABORT \u2014 no valid token address",{tokens:t}),t.map(()=>null);let i=Gj(e),o;try{Yt("discovery: probing 5 accessors per token",{chain:e,tokens:n,psm:i}),o=await ro(e,[...n.flatMap(w=>w?Aht(w):[]),...i?iAe(i):[]])}catch(w){return Yt("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:e,message:w?.message}),t.map(()=>null)}let a=i?o.slice(o.length-oAe):[],s=Lr(a[0])?.toLowerCase()??null,l=Lr(a[1]),c=Lr(a[2]),u=s&&l&&c?{susds:s,usds:l,oracle:c}:null;i&&Yt("discovery: PSM3 lookup",{psm:i,susds:s,usds:l,oracle:c});let d=0,p=n.map(w=>{if(!w)return null;let k=o.slice(d,d+vAe);return d+=vAe,Yt("discovery: probe answers",{token:w,"POOL()":Lr(k[0]),"UNDERLYING_ASSET_ADDRESS()":Lr(k[1]),"baseToken()":Lr(k[2]),"asset()":Lr(k[3]),"vsr()":Ln(k[4])?.toString()??null,"manager()":Lr(k[5])}),{token:w,slice:k}}),h=new Set;for(let w of p){if(!w)continue;let k=Lr(w.slice[0]);k&&Lr(w.slice[1])&&h.add(k.toLowerCase())}let y=await Pht(e,[...h]);h.size>0&&Yt("discovery: Aave pool authentication",{claimed:[...h],genuine:[...y]});let b=new Map;for(let w of p){if(!w||Lr(w.slice[0])&&Lr(w.slice[1])||Lr(w.slice[2])||!Lr(w.slice[3]))continue;let T=Lr(w.slice[5]);T&&b.set(w.token,T.toLowerCase())}let _=await Eht(e,b);b.size>0&&Yt("discovery: Maple manager authentication",{claimed:[...b.keys()],genuine:[..._]});let v=p.flatMap(w=>w?Lr(w.slice[0])&&Lr(w.slice[1])||Lr(w.slice[2])?[]:_.has(w.token)?[]:Lr(w.slice[3])?[w.token]:[]:[]),S=await Iht(e,[...new Set(v)],r);return v.length>0&&Yt("discovery: Morpho vault lookup",{asked:[...new Set(v)],recognised:[...S.keys()]}),p.map(w=>{if(!w)return null;let{token:k,slice:T}=w,O={chain:e,protocolUrl:null,token:k,platformScore:null};if(u&&k===u.susds)return Yt("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...O,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:xl("spark-l2-susds"),protocolUrl:sv("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let $=Lr(T[0]);if($&&Lr(T[1])){let I=y.has($.toLowerCase());return Yt("discovery: classified",{token:k,as:I?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:$}),I?{...O,name:"Aave v3",protocol:"AAVE",protocolLabel:xl("aave-v3"),protocolUrl:sv("aave-v3"),type:"aave-v3",contract:$}:null}if(Lr(T[2]))return Yt("discovery: classified",{token:k,as:"compound-v3"}),{...O,name:"Compound v3",protocol:"COMPOUND",protocolLabel:xl("compound-v3"),protocolUrl:sv("compound-v3"),type:"compound-v3",contract:k};if(Lr(T[3])){if(_.has(k))return Yt("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...O,name:"Maple",protocol:"MAPLE",protocolLabel:xl("maple"),protocolUrl:sv("maple"),type:"maple",contract:k};if(S.has(k)){Yt("discovery: classified",{token:k,as:"morpho-v2"});let q=S.get(k)||"Morpho V2";return{...O,name:q,protocol:"MORPHO",protocolLabel:xl("morpho-v2"),protocolUrl:sv("morpho-v2"),type:"morpho-v2",contract:k}}let D=Ln(T[4])!==null;return Yt("discovery: classified",{token:k,as:D?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),D?{...O,name:"Spark",protocol:"SPARK",protocolLabel:xl("spark-ethereum"),protocolUrl:sv("spark-ethereum"),type:"spark-ethereum",contract:k}:{...O,name:"Spark",protocol:"SPARK",protocolLabel:xl("spark"),protocolUrl:sv("spark"),type:"spark",contract:k}}return Yt("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function Aht(e){return[{target:e,callData:sr({abi:tx,functionName:"POOL"})},{target:e,callData:sr({abi:tx,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:e,callData:sr({abi:Mm,functionName:"baseToken"})},{target:e,callData:sr({abi:Ed,functionName:"asset"})},{target:e,callData:sr({abi:rx,functionName:"vsr"})},{target:e,callData:sr({abi:CQ,functionName:"manager"})}]}async function Pht(e,t){if(t.length===0)return new Set;try{let r=await ro(e,t.map(n=>({target:n,callData:sr({abi:PQ,functionName:"ADDRESSES_PROVIDER"})})));return new Set(t.filter((n,i)=>Lr(r[i])!==null))}catch{return new Set}}async function Eht(e,t){if(t.size===0)return new Set;let r=[...t.entries()];try{let n=await ro(e,r.map(([,i])=>({target:i,callData:sr({abi:OQ,functionName:"pool"})})));return new Set(r.filter(([i],o)=>Lr(n[o])?.toLowerCase()===i.toLowerCase()).map(([i])=>i))}catch{return new Set}}async function Iht(e,t,r){let n=parseInt(e,16);if(t.length===0||!Number.isFinite(n))return new Map;let i=await Promise.all(t.map(async o=>{try{let a=await Qe.post(r,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:o,c:n}}),s=a.ok?a.data?.data?.vaultV2ByAddress:null;return s?[o,s.name?.trim()||""]:null}catch{return null}}));return new Map(i.filter(o=>o!==null))}var Cht=.01;function Oht(e){return e.reduce((t,r)=>r.conditions===null?t+r.apyPercent:t,0)}function Rht(e,t){if(typeof t!="string"||!t.trim())return;let r=t.trim(),n=J_();n[e]!==r&&Y_({...n,[e]:r})}var kx=class{constructor(t,r,n){g(this,"coinPoolBaseUrl",t);g(this,"endpoints",r);g(this,"describer",n)}async describeReceiptTokens(t,r,n){let i=Date.now();Yt("describeReceiptTokens: START",{chain:t,tokens:r,hasRpcUrl:!!n});let o=Lm(t);o&&Rht(o,n);let a=o?OO(o):null,s=[...new Set(r.filter($t).map(p=>p.toLowerCase()))];if(Yt("describeReceiptTokens: chain resolved",{hex:o,hasChainInfo:!!a,wanted:s}),!o||!a||s.length===0)return Yt("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:o,hasChainInfo:!!a,wantedCount:s.length}),new Map;Yt("describeReceiptTokens: on-chain discovery for",s);let l=await wAe(o,s,this.endpoints.morphoApiUrl),u=[...new Map(s.flatMap((p,h)=>{let y=l[h];return Yt("describeReceiptTokens: discovery result",{token:p,found:!!y,protocol:y?.protocol,type:y?.type,contract:y?.contract}),y?[[p,y]]:[]})).entries()];if(u.length===0)return Yt("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-i}),new Map;Yt("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([p,h])=>({token:p,type:h.type,contract:h.contract}))});let d=await this.describer.describe(o,a,u.map(([,p])=>p));return Yt("describeReceiptTokens: DONE",{ms:Date.now()-i,overviews:d.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(d.map((p,h)=>[u[h][0],p]))}async findMarketByReceiptToken(t,r,n){if(Yt("findMarketByReceiptToken: called",{chain:t,receiptToken:r,hasRpcUrl:!!n}),!$t(r))return Yt("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:r}),null;let o=(await this.describeReceiptTokens(t,[r],n)).get(r.toLowerCase())??null;return Yt("findMarketByReceiptToken: returning",{found:!!o}),o}async getSupplyPositions(t){if(!$t(t.address))return[];let r=await _Ae(this.coinPoolBaseUrl,t.chains);return(await Promise.all(r.map(i=>this.positionsForChain(i,t.address)))).flat().sort((i,o)=>o.suppliedUsdc-i.suppliedUsdc||(o.avgApyPercent??0)-(i.avgApyPercent??0))}async describeResolvedMarkets(t,r){let n=Lm(t),i=n?OO(n):null;return n&&i?this.describer.describe(n,i,r):[]}async positionsForChain(t,r){let n=OO(t),i=await MO(this.coinPoolBaseUrl,t);if(!n||i.length===0)return[];let o=await this.describer.readBalances(t,r,i);if(o.length===0)return[];let a=await this.describer.describe(t,n,o.map(l=>l.market)),s=await this.describer.convertToUnderlying(t,o,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=s[c];return u<Cht?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Oht(l.rewards))/100}]})}};m();var UQ=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var xx=class{constructor(t){g(this,"coinPoolBaseUrl",t)}async listChains(){return Xj(this.coinPoolBaseUrl)}async isSupported(t){return Qj(this.coinPoolBaseUrl,t)}async getMarkets(t){let r=or(t);return r?MO(this.coinPoolBaseUrl,r):[]}async findMarket(t,r){let n=await this.getMarkets(t);return bAe(n,r)}canSupply(t){return UQ.includes(t.type)}async readReceiptToken(t,r){let n=Vg(r).balanceIsUnderlying;try{let i=await ro(t,[{target:r.token,callData:sr({abi:Er,functionName:"symbol"})},{target:r.token,callData:sr({abi:Er,functionName:"decimals"})}]);return{symbol:xk(i[0]),decimals:Tk(i[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};m();m();m();var kAe=6e5,e2=new Map;async function SAe(e){let t=e2.get(e);if(t&&Date.now()-t.at<kAe)return t.chains;let r=Lht(e);return e2.set(e,{at:Date.now(),chains:r}),r.then(n=>{n===null&&e2.delete(e)}),r}async function $ht(e){try{let t=e==="morpho"?await Nht():await Dht();return!t||t.size===0?(Yt(`protocolChains: ${e} returned no chains`),null):(Yt(`protocolChains: ${e} live on`,[...t].sort((r,n)=>r-n)),t)}catch(t){return Yt(`protocolChains: ${e} FAILED`,t instanceof Error?t.message:t),null}}async function Nht(){let e=await Qe.post("https://api.morpho.org/graphql",{query:"{ chains { id network } }"});if(!e.ok)return null;let t=e.data?.data?.chains;if(!Array.isArray(t))return null;let r=new Set;for(let n of t)typeof n?.id=="number"&&Number.isInteger(n.id)&&n.id>0&&(r.add(n.id),typeof n.network=="string"&&n.network.trim()&&xAe.set(n.id,n.network.trim()));return r}async function Dht(){let e=await Qe.get("https://v3-api.compound.xyz/market/all-networks/all-contracts/summary");if(!e.ok||!Array.isArray(e.data))return null;let t=new Set;for(let r of e.data)typeof r?.chain_id=="number"&&Number.isInteger(r.chain_id)&&r.chain_id>0&&t.add(r.chain_id);return t}var xAe=new Map;function TAe(e){return xAe.get(e)??null}var Mht=1500;async function AAe(){let e=Promise.all([SAe("morpho").catch(()=>null),SAe("compound").catch(()=>null)]),t,r=new Promise(n=>{t=setTimeout(n,Mht),t?.unref?.()});try{await Promise.race([e,r])}finally{t&&clearTimeout(t)}}function BQ(e){let t=e2.get(e);return!t||Date.now()-t.at>=kAe?null:PAe.get(t.chains)??null}var PAe=new WeakMap;function Lht(e){let t=$ht(e);return t.then(r=>{r&&PAe.set(t,r)}),t}var Uht={1:"ethereum",10:"opmainnet",130:"unichain",137:"polygon",143:"monad",480:"world-chain",988:"stable",999:"hyperevm",4217:"tempo",4663:"robinhood-chain",5042:"arc",8453:"base",42161:"arbitrum",747474:"katana"},Bht={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_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"},jht={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},qht={1:"mainnet",10:"op",130:"unichain",137:"polygon",2020:"ronin",5e3:"mantle",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function t2(e){let t=Qht(e.chain);return(t===null?null:Fht(e,t))??CO(e.type)??Xht(e,t)}function Fht(e,t){switch(e.type){case"morpho-v2":{let r=Uht[t]??Vht(t);if(!r||!e.contract)return null;let n=`https://app.morpho.org/${r}/vault/${jQ(e.contract)}`,i=Zht(e.name);return i?`${n}/${i}`:n}case"aave-v3":{let r=Bht[t],n=zht(e);return!r||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${jQ(n)}&marketName=${r}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let r=jht[t],n=Yht(e);return!r||!n?null:`https://app.spark.finance/savings/${r}/${n}`}case"compound-v3":{if(Ght(t))return null;let r=qht[t],n=Wht(e);return!r||!n?null:`https://app.compound.xyz/?market=${n}-${r}`}default:return null}}function zht(e){let t=e.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(t)?/^0x0+$/.test(t)?null:t:null}var Hht=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Vht(e){if(!BQ("morpho")?.has(e))return null;let r=TAe(e);return r&&r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Zht(e){let t=e?.trim().toLowerCase()||"";return!t||Hht.has(t)?null:t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Ght(e){let t=BQ("compound");return t!==null&&!t.has(e)}function Wht(e){let t=e.asset?.address?.trim().toLowerCase()||"",r=Kht[t];if(r)return r;let n=e.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(n)&&n.length<=12?n:null}var Kht={"0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"usdc.e","0xff970a61a04b1ca14834a43f5de4533ebddb5cc8":"usdc.e"};function Yht(e){let t=e.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(t))return t;let r=`${e.name||""} ${e.token||""}`.toLowerCase();for(let i of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(r.includes(i))return i;if(e.type==="spark-ethereum")return Jht[e.contract?.trim().toLowerCase()||""]??null;let n=e.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(n)||n.startsWith("s")?null:`s${n}`}var Jht={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function Xht(e,t){let r=e.protocolUrl?.trim();if(!r)return null;let n=/^https?:\/\//i.test(r)?r:`https://${r.replace(/^\/+/,"")}`;try{let i=new URL(n);return t!==null&&i.searchParams.set("chainId",String(t)),e.contract&&i.searchParams.set("contract",jQ(e.contract)),i.toString()}catch{return n}}function jQ(e){let t=e.trim().toLowerCase();return t.startsWith("0x")?t:`0x${t}`}function Qht(e){let t=e?.trim();if(!t)return null;let r=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(r)&&r>0?r:null}var egt=new Set(["spark","spark-ethereum"]),tgt=8;function rgt(e,t,r){if(e.market.type!=="spark-l2-susds")return Ln(t);let n=Ln(t);return n===null||e.tokenDecimals===null?null:ov(e.rawBalance,n,e.tokenDecimals,r)}var r2=class{constructor(t){g(this,"endpoints",t);g(this,"apyLimiter",new qQ(tgt));g(this,"pantograph",new Oi)}async describe(t,r,n){if(n.length===0)return[];Yt("describe: START",{chain:t,count:n.length,types:n.map(l=>l.type)});let{assets:i,shareSymbols:o}=await this.resolveAssets(t,n);Yt("describe: assets resolved",i);let[a,s]=await Promise.all([this.readMarketState(t,n,i),Promise.all(n.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,r,i[c])))),AAe()]);return Yt("describe: on-chain state",a),Yt("describe: APY fetched",s.map((l,c)=>({type:n[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),n.map((l,c)=>{let{totalSuppliedUsdc:u,liveApyFraction:d}=a[c],p=s[c].sizeOverride??u,h=igt(s[c].samples,d??s[c].current,s[c].rewards,s[c].avgOverride??null);return Yt("describe: summarised",{market:l.name,type:l.type,liveFrom:d!==null?"on-chain":s[c].current!==null?"api":"none",rawSamples:s[c].samples.length,historyPoints:h.history.length,currentApyPercent:h.currentApyPercent,avgApyPercent:h.avgApyPercent,apyChangePercent:h.apyChangePercent,totalSuppliedUsdc:p,asset:i[c]?.symbol}),{...l,protocolUrl:t2({...l,asset:i[c],shareSymbol:o[c]}),asset:i[c],totalSuppliedUsdc:p,avgApyPercent:h.avgApyPercent,currentApyPercent:h.currentApyPercent,baseApyPercent:h.baseApyPercent,rewardApyPercent:h.rewardApyPercent,rewards:h.rewards,apyChangePercent:h.apyChangePercent,apyHistory:h.history}})}async readBalances(t,r,n){let i=sr({abi:Er,functionName:"balanceOf",args:[r]}),o=sr({abi:Er,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:i},{target:l.token,callData:o}]),s=await ro(t,a);return n.flatMap((l,c)=>{let u=Ln(s[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Tk(s[c*2+1])}]})}async convertToUnderlying(t,r,n){let i=[],o=r.map(s=>{let l=Vg(s.market).convertToAssetsCall(s.market,s.rawBalance);return l?(i.push(l),i.length-1):-1}),a=await ro(t,i);return r.map((s,l)=>{let c=n[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(o[l]<0)return dc(s.rawBalance,c);let u=rgt(s,a[o[l]],c);return u===null?dc(s.rawBalance,s.tokenDecimals??c):dc(u,c)})}async resolveAssets(t,r){let n={address:av,decimals:NaN,symbol:null,logo:null},i=[],o=r.map(p=>{let h=Vg(p).underlyingCall(p);return h?(i.push(h),i.length-1):-1}),a;try{let p=i.length>0?await ro(t,i):[];a=o.map(h=>h<0?null:Lr(p[h]))}catch{a=r.map(()=>null)}a=a.map((p,h)=>p??r[h]?.assetAddress??null);let s=[...new Set(a.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,u]=await Promise.all([this.readAssetMetadata(t,s),this.fetchAssetLogos(t,s),this.readShareSymbols(t,r)]);return{assets:a.map(p=>{if(!p)return n;let h=p.toLowerCase(),y=l.get(h),b=c.get(h)??null;return y?.decimals!==null&&y?.decimals!==void 0?{address:p,decimals:y.decimals,symbol:y.symbol??null,logo:b}:{address:p,decimals:NaN,symbol:null,logo:b}}),shareSymbols:u}}async readShareSymbols(t,r){let n=sr({abi:Er,functionName:"symbol"}),i=[],o=r.map(a=>!egt.has(a.type)||!a.contract?-1:(i.push({target:a.contract,callData:n}),i.length-1));if(i.length===0)return r.map(()=>null);try{let a=await ro(t,i);return o.map(s=>s<0?null:xk(a[s]))}catch{return r.map(()=>null)}}async readAssetMetadata(t,r){let n=new Map;if(r.length===0)return n;let i=sr({abi:Er,functionName:"decimals"}),o=sr({abi:Er,functionName:"symbol"});try{let a=await ro(t,r.flatMap(s=>[{target:s,callData:i},{target:s,callData:o}]));r.forEach((s,l)=>{n.set(s,{decimals:Tk(a[l*2]),symbol:xk(a[l*2+1])})})}catch{}return n}async fetchAssetLogos(t,r){let n=new Map;if(r.length===0)return n;try{let i=await this.pantograph.getTokensMetadata(r,t);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 Yt("resolveAssets: logos",{chain:t,requested:r.length,found:n.size}),n}async readMarketState(t,r,n){let i=[],o=r.map((u,d)=>{let p=Vg(u),h=n[d],y={market:u,protocol:p,asset:h,size:i.length,rate:-1};i.push(p.sizeCall(u,h));let b=p.liveRateCall(u,h);return b&&(y.rate=i.length,i.push(b)),y}),a=await ro(t,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 ro(t,s):[];return o.map((u,d)=>{let p=u.rate<0?null:a[u.rate],h=l[d]>=0?c[l[d]]:p;return{totalSuppliedUsdc:u.protocol.decodeSize(a[u.size],u.asset),liveApyFraction:h===null?null:u.protocol.decodeLiveRate(h)}})}async fetchApy(t,r,n){try{Yt("fetchApy: requesting",{market:t.name,type:t.type,asset:n?.symbol});let i=await Vg(t).fetchApy(t,r,this.endpoints,n);return Yt("fetchApy: got",{market:t.name,samples:i.samples.length,current:i.current,avgOverride:i.avgOverride??null}),i}catch(i){return Yt("fetchApy: FAILED \u2014 market listed without APY",{market:t.name,type:t.type,message:i?.message}),{samples:[],current:null,rewards:[]}}}},qQ=class{constructor(t){g(this,"limit",t);g(this,"active",0);g(this,"waiting",[])}async run(t){this.active>=this.limit?await new Promise(r=>this.waiting.push(r)):this.active++;try{return await t()}finally{let r=this.waiting.shift();r?r():this.active--}}};function ngt(e,t){let r=SO(Date.now()),n=new Map,i=null;for(let s of e)!Number.isFinite(s.timeMs)||!Number.isFinite(s.fraction)||s.fraction<0||SO(s.timeMs)>r||((!i||s.timeMs>i.timeMs)&&(i=s),n.set(s.timeMs,s.fraction));let o=[...n.entries()].sort((s,l)=>s[0]-l[0]).map(([s,l])=>({date:new Date(s).toISOString(),apyPercent:l*100})),a=t??(i&&SO(i.timeMs)===r?i.fraction:null);return{history:o,live:a}}function igt(e,t,r=[],n=null){let{history:i,live:o}=ngt(e,t),a=o===null?null:o*100,s=r.map(h=>({apyPercent:h.fraction*100,tokenSymbol:h.tokenSymbol,conditions:h.conditions})),l=s.length===0?null:s.reduce((h,y)=>h+y.apyPercent,0),c=a===null?null:a+(l??0),u={baseApyPercent:a,rewardApyPercent:l,rewards:s},d=n!==null&&Number.isFinite(n)?n*100:null;if(i.length===0)return{history:i,avgApyPercent:d,currentApyPercent:c,apyChangePercent:null,...u};let p=i.reduce((h,y)=>h+y.apyPercent,0);return{history:i,avgApyPercent:d??p/i.length,currentApyPercent:c,apyChangePercent:agt(i,a),...u}}var EAe=3600*1e3,ogt=EAe/2;function agt(e,t){if(t===null)return null;let r=Date.now()-EAe,n=null,i=Number.POSITIVE_INFINITY;for(let o=e.length-1;o>=0;o--){let a=Math.abs(Date.parse(e[o].date)-r);if(a>i)break;i=a,n=e[o]}return!n||i>ogt?null:t-n.apyPercent}function IAe(e,t){if(!Number.isFinite(e))return e;let r=10**t,n=Number((e*r).toPrecision(15));return(e<0?-Math.floor(-n):Math.floor(n))/r+0}var fu=class{constructor(t={}){g(this,"read");g(this,"supply");let r=t.coinPoolBaseUrl||"https://api.coinpool.app",n={lendingRatesBaseUrl:t.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:t.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:t.morphoApiUrl||"https://api.morpho.org/graphql"},i=new r2(n);this.read=new kx(r,n,i),this.supply=new xx(r)}async listSupportedChains(){return this.supply.listChains()}async isSupported(t){return this.supply.isSupported(t)}async getMarkets(t){return this.supply.getMarkets(t)}async findMarket(t,r){return this.supply.findMarket(t,r)}canSupply(t){return this.supply.canSupply(t)}async readReceiptToken(t,r){return this.supply.readReceiptToken(t,r)}async describeReceiptTokens(t,r,n){return this.read.describeReceiptTokens(t,r,n)}async findMarketByReceiptToken(t,r,n){return this.read.findMarketByReceiptToken(t,r,n)}async describeResolvedMarkets(t,r){return this.read.describeResolvedMarkets(t,r)}async getMarketOverviews(t){return(await Promise.all(t.chains.map(async n=>this.read.describeResolvedMarkets(n,await this.getMarkets(n))))).flat().sort((n,i)=>(i.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(t){return this.read.getSupplyPositions(t)}};m();var LO="{market}",RAe=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],i2=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],pc="[[LIST]]",$Ae=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',NAe=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function DAe(e,t,r){let[n]=sgt([e],t,r),[i]=e.canSupply?FQ(e,t,r):[];return{name:e.name?.trim()||e.protocol,protocol:e.protocol,protocolUrl:e.protocolUrl,chain:r,apyPercent:e.apyPercent,detailPrompt:n?.prompt??"",detailLabel:n?.label??"",supplyPrompt:i?.prompt??"",supplyLabel:i?.label??""}}function sgt(e,t,r){return MAe(e,{labelTemplate:n2(t.detail_button_label),promptTemplate:n2(t.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${LO}`,...r===void 0?{}:{chainName:r}})}function FQ(e,t,r){return MAe([e],{labelTemplate:n2(t.supply_button_label),promptTemplate:n2(t.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${LO}`,promptFallback:`supply to ${LO}`,...r===void 0?{}:{chainName:r},max:1})}function MAe(e,t){let r=typeof t.chainName=="string"?t.chainName.trim():"",n=[],i=new Set;for(let o of e){if(t.max!==void 0&&n.length>=t.max)break;let a=o.name?.trim();!a||i.has(a.toLowerCase())||(i.add(a.toLowerCase()),n.push({label:CAe(t.labelTemplate,a,t.labelFallback,t.labelNamesMarket===!0),prompt:CAe(lgt(t.promptTemplate),a,t.promptFallback)+cgt(o.contract,r)}))}return n}function lgt(e){let[t,r]=[e[0],e[1]];return t===void 0||t===t.toLowerCase()||r!==void 0&&r!==r.toLowerCase()?e:t.toLowerCase()+e.slice(1)}function n2(e){return typeof e=="string"?e:""}function cgt(e,t){let r=e?.trim();if(!r||!/^0x[a-fA-F0-9]{40}$/.test(r))return"";let n=t?.trim();return n?` (market: ${r} - ${n})`:` (market: ${r})`}function CAe(e,t,r,n=!0){let o=e&&(!n||e.includes(LO))?e:r;return ugt(o).split(LO).join(t).replace(/\s+/g," ").trim()}var OAe="{chain}";function ugt(e){if(!e.includes(OAe))return e;let t=OAe.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${t}`,"g"),"").replace(new RegExp(`${t}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(t,"g"),"")}m();var o2=[{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"]}],HQ=o2.map(e=>e.label),zQ={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 LAe(e){let t=typeof e=="string"?e.trim():"";if(!t)return{kind:"none"};let r=mgt(t);if(!r)return{kind:"none"};let n=dgt(r);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let i=fgt(r);return i?{kind:"unsupported",label:i,requested:t}:{kind:"unknown",requested:t}}function dgt(e){let t=o2.filter(r=>r.aliases.includes(e));if(t.length===1)return t[0];if(t.length>1)return null;if(e.length>=3){let r=o2.filter(n=>n.aliases.some(i=>i.includes(e)||e.includes(i)));if(r.length===1)return r[0];if(r.length>1)return null}return pgt(e)}function pgt(e){let t=null,r=!1;for(let n of o2)for(let i of n.aliases){let o=UAe(i);if(o===0||Math.abs(i.length-e.length)>o)continue;let a=BAe(e,i,o);a>o||(!t||a<t.distance?(t={spec:n,distance:a},r=!1):a===t.distance&&n!==t.spec&&(r=!0))}return t&&!r?t.spec:null}function UAe(e){return e.length<=4?0:e.length<=9?2:3}function fgt(e){let t=zQ[e];if(t)return t;if(e.length>=4){let i=new Set(Object.entries(zQ).filter(([o])=>o.length>=4&&(o.includes(e)||e.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(zQ)){let a=UAe(i);if(a===0||Math.abs(i.length-e.length)>a)continue;let s=BAe(e,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 mgt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function BAe(e,t,r){if(e===t)return 0;if(!e.length)return t.length;if(!t.length)return e.length;let n=new Array(t.length+1),i=Array.from({length:t.length+1},(a,s)=>s),o=new Array(t.length+1);for(let a=1;a<=e.length;a++){o[0]=a;let s=o[0];for(let c=1;c<=t.length;c++){let u=i[c-1]+(e[a-1]===t[c-1]?0:1),d=Math.min(o[c-1]+1,i[c]+1,u);a>1&&c>1&&e[a-1]===t[c-2]&&e[a-2]===t[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[t.length]}m();function Ri(e,t){return e==null?null:IAe(e,t)}var Ga=2,Zg=2;function a2(e){let t=Ri(e.currentApyPercent,Ga),r=e.rewards.map(o=>({apyPercent:Ri(o.apyPercent,Ga)??0,tokenSymbol:o.tokenSymbol,conditions:o.conditions})),n=e.rewardApyPercent===null?null:r.reduce((o,a)=>o+Math.round(a.apyPercent*100),0)/100;if(n===null||t===null)return{currentApyPercent:t,rewardApyPercent:n,rewards:r,baseApyPercent:Ri(e.baseApyPercent,Ga)};let i=Math.round(t*100)-Math.round(n*100);return{currentApyPercent:t,rewardApyPercent:n,rewards:r,baseApyPercent:i/100}}var hgt=["apy","score","size"],jAe=3,qAe=40,Tx=class extends Ce{constructor(r){super();g(this,"name","get-lending-markets");g(this,"kind","ui");g(this,"description",'BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.');g(this,"category","blockchain-data");g(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: ${HQ.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-${qAe}. Default ${jAe} \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},...RAe,...i2]);g(this,"service");this.service=new fu(r)}async run(r,n){let i=Sn(r.chain,void 0),o=i?null:or(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 ${ye(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:ye(a),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:l.map(w=>ye(w))};let c=LAe(r.protocol);if(c.kind==="unsupported"||c.kind==="unknown")return this.unsupportedProtocol(c);let u=a?[a]:l,d=ygt(r.sort),p=bgt(r.limit),h=await this.service.getMarketOverviews({chains:u}),y=c.kind==="supported"?h.filter(w=>c.matches(w)):h;if(c.kind==="supported"&&y.length===0&&h.length>0)return{_instructions:`There are no ${c.label} lending markets on ${a?ye(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?ye(a):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(h.map(w=>w.protocol))]};let b=[...y].sort(ggt[d]).slice(0,p),_=b.map(w=>DAe({name:w.name,contract:w.contract,protocol:w.protocol,protocolUrl:w.protocolUrl,apyPercent:Ri(w.currentApyPercent,Ga),canSupply:this.service.supply.canSupply(w)},r,ye(w.chain))),S={component:"LendingMarketList",props:{chain:a?ye(a):"all",multiChain:new Set(_.map(w=>w.chain)).size>1,markets:_}};return{..._.length>0?{ui:S}:{},_instructions:this.instructions(b,d,_.length>0,c.kind==="supported"?c.label:null),chain:a?ye(a):"all",chainsQueried:u.map(w=>ye(w)),...c.kind==="supported"?{protocolFilter:c.label}:{},sortedBy:d,marketCount:_.length,totalMarketsAvailable:y.length,marketNames:_.map(w=>w.name)}}unsupportedProtocol(r){let n=r.kind==="unsupported",i=n?r.label:`"${r.requested}"`;return{_instructions:`The user asked about ${i}, which has no lending markets here. In their language: tell them plainly that ${i} is ${n?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${i} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:n?r.label:r.requested,protocolSupported:!1,supportedProtocols:[...HQ],marketCount:0,marketNames:[]}}instructions(r,n,i=!1,o=null){if(r.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let a={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[n];return[o?`These are the ${o} lending markets the user can supply to, ${a}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${a}.`,`Write your reply in TWO parts separated by a line containing exactly ${pc} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",n==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(r.map(s=>s.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${ye(r[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${a} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",i?$Ae:""].filter(Boolean).join(" ")}},ggt={apy:(e,t)=>(t.currentApyPercent??-1)-(e.currentApyPercent??-1),score:(e,t)=>(t.platformScore??-1)-(e.platformScore??-1),size:(e,t)=>(t.totalSuppliedUsdc??-1)-(e.totalSuppliedUsdc??-1)};function ygt(e){let t=typeof e=="string"?e.trim().toLowerCase():"";return hgt.includes(t)?t:"apy"}function bgt(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?jAe:Math.min(Math.floor(t),qAe)}m();m();function FAe(e){let{currentApyPercent:t,avgApyPercent:r,totalSuppliedUsdc:n,rewardApyPercent:i,baseApyPercent:o,platformScore:a}=e;return e.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:i!==null&&o!==null&&i>o*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:t!==null&&r!==null&&r>0&&t>r*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:n!==null&&n<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&n!==null&&n>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:n!==null&&n>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}m();function s2(e){let t=typeof e=="string"?e.trim():"",r=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(t);if(r)return r[1];let n=/0x[a-fA-F0-9]{40}/.exec(t);return n&&n[0]!==t?n[0]:t}var Ax=class extends Ce{constructor(r){super();g(this,"name","get-lending-market-detail");g(this,"category","blockchain-data");g(this,"description",'Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.');g(this,"parameters",[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...i2]);g(this,"service");this.service=new fu(r)}async run(r,n){let o=Sn(r.chain,void 0)??or(n?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let p=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:ye(o),chainsWithLendingMarkets:p.map(h=>ye(h)),_instructions:`There are no lending markets on ${ye(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let a=s2(r.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let s=await this.service.findMarket(o,a);if(s.length===0)return{error:"market_not_found",market:a,chain:ye(o),_instructions:`No lending market matching "${a}" exists on ${ye(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(s.length>1)return{error:"ambiguous_market",market:a,chain:ye(o),candidates:s.map(p=>({marketName:p.name,protocol:p.protocol})),_instructions:`"${a}" matches ${s.length} different markets on ${ye(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+a+`" and chain for ${ye(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let l=s[0],c=await this.describeOne(o,l);if(!c)return{error:"market_unavailable",marketName:l.name,chain:ye(o),_instructions:`${l.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let u=this.service.supply.canSupply(l),d=u?FQ({name:l.name,contract:l.contract},r,ye(o)):[];return{_instructions:this.instructions(c,d.length>0,u),...d.length>0?{actionButtons:d}:{},marketName:c.name,protocol:c.protocolLabel??c.protocol,protocolUrl:c.protocolUrl,chain:ye(c.chain),suppliedAssetSymbol:c.asset.symbol,totalSuppliedUsdc:Ri(c.totalSuppliedUsdc,Zg),...a2(c),avgApyPercent:Ri(c.avgApyPercent,Ga),apyChangePercent:Ri(c.apyChangePercent,Ga),platformScore:c.platformScore,supplySupported:u}}async describeOne(r,n){try{let[i]=await this.service.describeResolvedMarkets(r,[n]);return i??null}catch{return null}}instructions(r,n,i){let o=FAe(r);return[`This is the full picture of ONE lending market, ${r.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',i?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",n?NAe:""].filter(Boolean).join(" ")}};m();var Px=class extends Ce{constructor(r){super();g(this,"name","get-wallet-lending-positions");g(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.');g(this,"category","blockchain-data");g(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}]);g(this,"service");this.service=new fu(r)}async run(r,n){let i=Un(r.address,n);if(!$t(i))return{error:`"${i}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=Sn(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 ${ye(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:ye(o),positionCount:0,positions:[],chainsWithLendingMarkets:s.map(u=>ye(u))};let l=o?[o]:s,c=await this.service.getSupplyPositions({address:i,chains:l});return{_instructions:this.instructions(c),walletAddress:i,chain:o?ye(o):"all",chainsQueried:l.map(u=>ye(u)),positionCount:c.length,totals:_gt(c),positions:c.map(u=>({marketName:u.name,protocol:u.protocol,protocolUrl:u.protocolUrl,chain:ye(u.chain),suppliedUsdc:Ri(u.suppliedUsdc,Zg),suppliedAssetSymbol:u.asset.symbol,avgApyPercent:Ri(u.avgApyPercent,Ga),...a2(u),apyChangePercent:Ri(u.apyChangePercent,Ga),estimatedAnnualYieldUsdc:Ri(u.estimatedAnnualYieldUsdc,Zg),marketTotalSuppliedUsdc:Ri(u.totalSuppliedUsdc,Zg),apyHistory:u.apyHistory.map(d=>({...d,apyPercent:Ri(d.apyPercent,Ga)})),platformScore:u.platformScore}))}}instructions(r){return r.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(r.map(i=>i.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function _gt(e){if(new Set(e.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let n=e.reduce((a,s)=>a+s.suppliedUsdc,0),i=e.filter(a=>a.avgApyPercent!==null),o=i.reduce((a,s)=>a+s.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:e[0]?.asset.symbol??null,suppliedUsdc:Ri(n,Zg),estimatedAnnualYieldUsdc:Ri(e.reduce((a,s)=>a+(s.estimatedAnnualYieldUsdc??0),0),Zg),weightedAvgApyPercent:Ri(o>0?i.reduce((a,s)=>a+s.suppliedUsdc*s.avgApyPercent,0)/o:null,Ga)}}m();var Ex=class extends Ce{constructor(r){super();g(this,"name","open-supply-usdc-form");g(this,"kind","ui");g(this,"category","lending-action");g(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.');g(this,"parameters",[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}]);g(this,"service");g(this,"moralis");this.service=new fu(r),this.moralis=new mr(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=Sn(r.chain,void 0)??or(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 S=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:ye(a),chainsWithLendingMarkets:S.map(w=>ye(w)),_instructions:`There are no lending markets on ${ye(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=s2(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:ye(a),_instructions:`No lending market matching "${s}" exists on ${ye(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:ye(a),candidates:l.map(S=>({marketName:S.name,protocol:S.protocol})),_instructions:`"${s}" matches ${l.length} different markets on ${ye(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 ${ye(a)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let c=l[0];if(!this.service.supply.canSupply(c))return{error:"unsupported_protocol",marketName:c.name,protocol:c.protocol,_instructions:`Supplying to ${c.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let u=await this.describeOne(a,c),d=vgt(u);if(!d)return{error:"asset_unresolved",marketName:c.name,chain:ye(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[p,h]=await Promise.all([this.assetBalance(i,a,d.address),this.service.readReceiptToken(a,c)]);if(p&&Bg(p.amount,"0")<=0)return{error:"no_asset_balance",marketName:c.name,chain:ye(a),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${c.name} on ${ye(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 y=wgt(r.amount),b=y?kl(y,d.decimals):null;if(b&&p&&Bg(b,p.amount)>0)return{error:"insufficient_asset_balance",marketName:c.name,chain:ye(a),assetSymbol:d.symbol,requestedAmount:y,assetBalance:p.amount,_instructions:`The user wants to supply ${y} ${d.symbol} to ${c.name}, but they only hold ${p.amount} ${d.symbol} on ${ye(a)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${y} ${d.symbol} exceeds their balance of ${p.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:ye(a),walletAddress:i,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:u?.protocolUrl??t2(c),contract:c.contract,token:c.token,apyPercent:u?.currentApyPercent??u?.avgApyPercent??null,receiptToken:h},asset:d,...b?{prefillAmount:b}:{},...p?{spendable:p.amount}:{},...p?.usd?{spendableUsd:p.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:_},marketName:c.name,protocol:c.protocol,chain:ye(a),apyPercent:Ri(_.market.apyPercent,Ga),assetSymbol:d.symbol,assetBalance:p?.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 vgt(e){let t=e?.asset;return!t?.address||t.address===av||!Number.isFinite(t.decimals)?null:{address:t.address,symbol:t.symbol||"the market asset",decimals:t.decimals}}function wgt(e){let t=typeof e=="string"?e.trim():typeof e=="number"?String(e):"";return/^\d*\.?\d+$/.test(t)&&Number(t)>0?t:null}m();m();m();m();m();var Gg={GAMMA:"https://gamma-api.polymarket.com",DATA:"https://data-api.polymarket.com",BRIDGE:"https://bridge.polymarket.com",CLOB:"https://clob.polymarket.com",RELAYER:"https://relayer-v2.polymarket.com"},l2="/submit",c2={INTERVAL_MS:3e3,TIMEOUT_MS:9e4},ZQ="0xebd1cc31700311ef8259fc9337f7a04317bfee851a71bf628420669d75124374",Sgt=/^0x[0-9a-fA-F]{64}$/,VQ=ZQ;function GQ(e){let t=e?.trim();if(!t){VQ=ZQ;return}if(!Sgt.test(t))throw new Error(`Invalid Polymarket builder code: ${t}`);VQ=t.toLowerCase()}function Ix(){return VQ}var kgt=1e4,xgt="https://intercom.help/funxyz/en/articles/10732578-contact-us",UO="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Wg="https://polymarket.com",WQ="wss://ws-live-data.polymarket.com",Dd="0x89",BO="137",KQ="0xDCa4af75705dbB50f62437045afF9921947917d2",YQ="0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296",jO="0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",JQ="Trading setup approvals",Ao={DEPLOY:"deploy",ENABLE_TRADING:"enable_trading",APPROVE:"approve",DONE:"done"},u2={INTERVAL_MS:2e3,MAX_ATTEMPTS:30},qO=["USDC","USDC.E","USDT","USD\u20AE0","USDT0","DAI","USDE","AUSD","USDG"],lv={"1151111081099710":"svm",8253038:"btc",728126428:"tron",29780:null},mu="0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB",hu=6,fc={depositWalletFactory:"0x00000000000Fb5C9ADea0298D729A0CB3823Cc07",depositWalletImplementation:"0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB",safeFactory:"0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b",safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf",factoryBeaconSelector:"0x49493a4d"},Um={PREFIX:BigInt("0x61003d3d8160233d3973"),CONST1:"0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",CONST2:"0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",BEACON_PREFIX:BigInt("0x6100523d8160233d3973"),BEACON_CONST1:"0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",BEACON_CONST2:"0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",BEACON_CONST3:"0x60195155f3363d3d373d3d363d602036600436635c60da"},Kg=[{key:"politics",tagId:"2",label:"Politics",aliases:["politic","chinh tri","ch\xEDnh tr\u1ECB","\u653F\u6CBB","\uC815\uCE58"]},{key:"sports",tagId:"1",label:"Sports",aliases:["sport","the thao","th\u1EC3 thao","\u30B9\u30DD\u30FC\u30C4","\u4F53\u80B2","\uC2A4\uD3EC\uCE20"]},{key:"crypto",tagId:"21",label:"Crypto",aliases:["cryptocurrency","tien dien tu","ti\u1EC1n \u0111i\u1EC7n t\u1EED","tien ma hoa","ti\u1EC1n m\xE3 h\xF3a","\u6697\u53F7\u8CC7\u7523","\u52A0\u5BC6\u8D27\u5E01","\uC554\uD638\uD654\uD3D0"]},{key:"esports",tagId:"64",label:"Esports",aliases:["e-sports","the thao dien tu","th\u1EC3 thao \u0111i\u1EC7n t\u1EED","e\u30B9\u30DD\u30FC\u30C4","\u7535\u7ADE"]},{key:"iran",tagId:"78",label:"Iran",aliases:["\u30A4\u30E9\u30F3","\u4F0A\u6717","\uC774\uB780"]},{key:"finance",tagId:"120",label:"Finance",aliases:["tai chinh","t\xE0i ch\xEDnh","\u91D1\u878D","\uAE08\uC735"]},{key:"geopolitics",tagId:"100265",label:"Geopolitics",aliases:["dia chinh tri","\u0111\u1ECBa ch\xEDnh tr\u1ECB","\u5730\u653F\u5B66","\u5730\u7F18\u653F\u6CBB"]},{key:"tech",tagId:"1401",label:"Tech",aliases:["technology","cong nghe","c\xF4ng ngh\u1EC7","\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC","\u79D1\u6280","\uAE30\uC220"]},{key:"elections",tagId:"144",label:"Elections",aliases:["election","bau cu","b\u1EA7u c\u1EED","\u9078\u6319","\u9009\u4E3E","\uC120\uAC70"]},{key:"culture",tagId:"596",label:"Culture",aliases:["pop culture","pop-culture","entertainment","van hoa","v\u0103n h\xF3a","giai tri","gi\u1EA3i tr\xED","\u30A8\u30F3\u30BF\u30E1","\u5A31\u4E50"]},{key:"economy",tagId:"100328",label:"Economy",aliases:["economics","kinh te","kinh t\u1EBF","\u7D4C\u6E08","\u7ECF\u6D4E","\uACBD\uC81C"]},{key:"weather",tagId:"84",label:"Weather",aliases:["climate","thoi tiet","th\u1EDDi ti\u1EBFt","\u5929\u6C17","\u5929\u6C14"]},{key:"science",tagId:"74",label:"Science",aliases:["khoa hoc","khoa h\u1ECDc","\u79D1\u5B66","\uACFC\uD559"]},{key:"awards",tagId:"18",label:"Awards",aliases:["giai thuong","gi\u1EA3i th\u01B0\u1EDFng","\u8CDE","\u5956\u9879"]}],FO={trending:{order:"volume24hr",ascending:!1},new:{order:"startDate",ascending:!1},volume:{order:"volume",ascending:!1},liquidity:{order:"liquidity",ascending:!1},competitive:{order:"competitive",ascending:!1},ending_soon:{order:"endDate",ascending:!0}},XQ="102127",QQ="100639",eee="102169",tee=["TRADE","REDEEM","SPLIT","MERGE","CONVERSION","REWARD"],ree=.01,zO={MIN_BUY_USD:1,DEFAULT_SLIPPAGE:.05,SLIPPAGE_OPTIONS:[.02,.05,.1]},d2={POLL_MS:1e3,TIMEOUT_MS:2e4},Xo={STABLE_SYMBOLS:["USDC","USDT","USDT0","USD\u20AE0"],CHAIN_ORDER:["137","8453","42161","1","10","56"],LARGE_USD:5e4,ERROR:{INVALID_AMOUNT:"invalid_amount",BELOW_MINIMUM:"below_minimum",INSUFFICIENT_BALANCE:"insufficient_balance",CANCELLED:"cancelled",FAILED:"failed"}},cv={POSITIONS_READ_LIMIT:500,ERROR:{NOTHING_TO_CLAIM:"nothing_to_claim",CANCELLED:"cancelled",FAILED:"failed"}},Bm={ENTER_AMOUNT:"enter_amount",NO_LIQUIDITY:"no_liquidity",NOT_ENOUGH_LIQUIDITY:"not_enough_liquidity",BELOW_MINIMUM:"below_minimum",EXCEEDS_HOLDING:"exceeds_holding",TOO_SMALL:"too_small"},jn={REGION_RESTRICTED:"region_restricted",MARKET_CLOSED:"market_closed",NOT_FILLED:"not_filled",INSUFFICIENT_BALANCE:"insufficient_balance",NOT_ENOUGH_LIQUIDITY:"not_enough_liquidity",TRADING_PAUSED:"trading_paused",BELOW_MIN_SIZE:"below_min_size",CLOSE_ONLY:"close_only",ACCOUNT_BANNED:"account_banned",CANCELLED:"cancelled",FAILED:"failed"},HO={THROTTLE_MS:1e3,STALE_MS:3e4,FALLBACK_POLL_MS:5e3};m();function VAe(e){return`btc-updown-5m-${Math.floor(e/1e3/300)*300}`}var Tgt=e=>/^btc-updown-(5m|15m)-/.test((e.slug??"").toLowerCase()),gu={MAX:8,INDEX:2,PREGAME_MINUTES:720,VOLUME_FLOOR:15e4,MAX_PER_SERIES:2,GAME_MINUTES:180,PAIR_VOLUME:3e5,PROXIMITY_WEIGHT:10},ZAe={nfl:2160,cbb:1440,cwbb:1440},Agt={cwbb:1e5,"world-cup":25e3,wimbledon:25e3},Pgt={cwbb:3,"world-cup":6,wimbledon:4},Egt={nba:150,wnba:120,ufc:60,f1:120,cs2:90,"dota-2":90,"league-of-legends":60,valorant:60},Igt="world-cup";function nee(e){if(!e)return null;let t=e.trim().replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),r=Date.parse(t);return Number.isFinite(r)?r:null}function Cgt(e){return(e.seriesSlug||e.series?.[0]?.slug||(e.slug??"").split("-")[0]||"").toLowerCase().replace(/-\d{4}(-\d{2,4})?$/,"")}var Ogt=e=>(e.tags??[]).some(t=>["1","64"].includes(String(t?.id))||t?.slug==="sports"||t?.slug==="esports");function Rgt(e){let t=(e.markets??[]).find(r=>r.gameStartTime)?.gameStartTime;return nee(e.startTime)??nee(t)??nee(e.startDate)}var $gt=e=>{let t=Number(e.volume);return Number.isFinite(t)?t:0},zAe=e=>e.closed!==!0;function Ngt(e,t){if(e.parentEventId!=null||e.closed===!0||e.ended===!0||!Ogt(e))return null;let r=Cgt(e);if(!r)return null;let n=Rgt(e);if(n===null)return null;let i=$gt(e);if(i<(Agt[r]??gu.VOLUME_FLOOR))return null;let o=(n-t)/6e4,a=Egt[r]??gu.GAME_MINUTES,s=e.live===!0&&-o<=a+15+180+10;if(!s&&o<-30)return null;let l=ZAe[r]??gu.PREGAME_MINUTES;return!s&&!(o>=-5&&o<=l)?null:{row:e,league:r,volume:i,minutes:o,live:s}}function Dgt(e){let t=new Map;for(let n of e)t.set(n.league,[...t.get(n.league)??[],n]);let r=[];for(let[n,i]of t){let o=[...i].sort((u,d)=>d.volume-u.volume),a=Pgt[n]??gu.MAX_PER_SERIES,s=n===Igt,l=s?Math.min(o.length,a):1;if(!s&&o.length>=2){let[u,d]=o,p=u.volume>=gu.PAIR_VOLUME&&d.volume>=gu.PAIR_VOLUME,h=[u,d].filter(y=>y.live||y.minutes<=60).length>=2;(p||h)&&(l=Math.min(o.length,a))}let c=ZAe[n]??gu.PREGAME_MINUTES;for(let u of o.slice(0,l)){let d=Math.log1p(u.volume),p=Math.max(0,Math.min(1,(c-Math.max(0,u.minutes))/c));r.push({...u,worldCup:s,score:u.live?d:d+gu.PROXIMITY_WEIGHT*p})}}return r.sort((n,i)=>{if(n.worldCup!==i.worldCup)return n.worldCup?-1:1;let o=n.minutes<0,a=i.minutes<0;return o!==a?o?-1:1:i.score-n.score}).slice(0,gu.MAX).map(n=>n.row)}function HAe(e){let t=new Set;return e.filter(r=>{let n=String(r.id??"");return!n||t.has(n)?!1:(t.add(n),!0)})}function GAe(e,t){let r=e.btc5m&&zAe(e.btc5m)?e.btc5m:null,n=d=>HAe(d.filter(p=>zAe(p)&&!Tgt(p))),i=n(e.feed),o=n(e.featured);if(o.length>0){let d=new Set(o.map(h=>String(h.id))),p=new Set(o.map(h=>(h.series?.[0]?.slug??"").toLowerCase()).filter(Boolean));i=[...o,...i.filter(h=>!d.has(String(h.id))&&!p.has((h.series?.[0]?.slug??"").toLowerCase()))]}let a=i.slice(0,gu.INDEX),s=i.slice(gu.INDEX),l=new Set(a.map(d=>String(d.id))),c=HAe([...s,...n(e.sports)]).filter(d=>!l.has(String(d.id))).map(d=>Ngt(d,t)).filter(d=>d!==null),u=Dgt(c);if(u.length>0){let d=new Set(u.map(p=>String(p.id)));i=[...a,...u,...s.filter(p=>!d.has(String(p.id)))]}return r&&(i=[...i.slice(0,1),r,...i.slice(1)]),i}m();var Mgt=/^([a-z0-9]+)-updown-(5m|15m|4h)-(\d+)$/,Lgt={"5m":300,"15m":900,"4h":14400},Ugt={"5m":"fiveminute","15m":"fifteen","4h":"fourhour"},WAe=e=>new Date(e*1e3).toISOString().replace(".000Z","Z");function m2(e,t){let r=Mgt.exec((e??"").toLowerCase());if(!r)return null;let[,n,i,o]=r,a=Number(o),s=t?.cryptoMarketConfig;return{symbol:n.toUpperCase(),priceFeed:`${n}/usd`,duration:i,startTime:t?.eventStartTime||WAe(a),endTime:t?.endDate||WAe(a+Lgt[i]),twapSeconds:s?.twapEnabled===!0?Math.max(0,Number(s.twapLookbackSeconds)||0):0}}function JAe(e){return{symbol:e.symbol,eventStartTime:e.startTime,variant:Ugt[e.duration]??"hourly",endDate:e.endTime,...e.twapSeconds>0?{twapEnabled:"true",twapLookbackSeconds:String(e.twapSeconds)}:{}}}var Bgt="crypto_prices_chainlink",jgt=15e3,qgt=1e4,KAe=[1e3,2e3,5e3,1e4],jm=new Map,iee=new Map,qm=null,p2=null,Cx=null,f2=null,oee=0,aee=(e,t)=>JSON.stringify({action:e,subscriptions:t.map(r=>({topic:Bgt,type:"*",filters:JSON.stringify({symbol:r})}))});function Fgt(e,t){let r=iee.get(e);r&&r.timestamp>t.timestamp||(iee.set(e,t),jm.get(e)?.forEach(n=>n(t)))}function zgt(e){if(typeof e!="string"||!e.startsWith("{"))return;let t;try{t=JSON.parse(e)}catch{return}let r=t.payload??{},n=typeof r.symbol=="string"?r.symbol.toLowerCase():"";if(!n)return;let i=Array.isArray(r.data)?r.data:[r],o=i[i.length-1],a=Number(o?.value),s=Number(o?.timestamp);Number.isFinite(a)&&a>0&&Fgt(n,{value:a,timestamp:Number.isFinite(s)?s:Date.now()})}function Hgt(){p2&&clearInterval(p2),Cx&&clearTimeout(Cx),f2&&clearTimeout(f2),p2=Cx=f2=null}function XAe(){Hgt();let e=qm;if(qm=null,e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.close()}catch{}}}function YAe(){Cx&&clearTimeout(Cx),Cx=setTimeout(see,jgt)}function see(){if(XAe(),jm.size===0)return;let e=KAe[Math.min(oee,KAe.length-1)];oee+=1,f2=setTimeout(QAe,e)}function QAe(){if(qm||jm.size===0)return;let e=globalThis.WebSocket;if(!e)return;let t=new e(WQ);qm=t,t.onopen=()=>{t.send(aee("subscribe",[...jm.keys()])),p2=setInterval(()=>t.readyState===1&&t.send("ping"),qgt),YAe()},t.onmessage=r=>{oee=0,YAe(),zgt(r.data)},t.onclose=see,t.onerror=see}function ePe(e,t){let r=e.toLowerCase(),n=jm.get(r)??new Set,i=n.size===0;n.add(t),jm.set(r,n);let o=iee.get(r);return o&&t(o),qm?i&&qm.readyState===1&&qm.send(aee("subscribe",[r])):QAe(),()=>{let a=jm.get(r);!a?.delete(t)||a.size>0||(jm.delete(r),jm.size===0?XAe():qm?.readyState===1&&qm.send(aee("unsubscribe",[r])))}}m();var Vgt=.1;function ar(e,t){if(e==null||e==="")return t;let r=typeof e=="number"?e:Number.parseFloat(String(e));return Number.isFinite(r)?r:t}function h2(e){if(Array.isArray(e))return e;if(typeof e!="string"||e==="")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function VO(e){let t=String(e.version??"").trim().toLowerCase();return t===""||t==="v1"?"v1":t==="v2"?"v2":null}function ZO(e){let t=e.feeSchedule??null,r=e.feesEnabled===!0?ar(t?.rate,0):0,n=ar(t?.exponent,1);return{rate:r>0&&r<1?r:0,exponent:n>0?n:1}}function GO(e){return e.active!==!1&&e.archived!==!0&&e.closed!==!0&&e.acceptingOrders===!0&&e.enableOrderBook!==!1}function tPe(e,t){return h2(t==="v2"?e.positionIds:e.clobTokenIds).map(r=>String(r??"")).filter(Boolean)}function rPe(e,t){let r=h2(e.outcomes).map(i=>String(i)),n=tPe(e,t);return r.length>=2&&n.length===r.length?r.map((i,o)=>({label:i,tokenId:n[o]})):[]}function lee(e){let t=h2(e.outcomes).map(c=>String(c)),r=h2(e.outcomePrices).map(c=>ar(c,null)),n=VO(e);if(n===null)return null;let i=tPe(e,n);if(t.length<2||r.length!==t.length||i.length!==t.length||r.some(c=>c===null||c<0||c>1)||!e.id||!e.conditionId)return null;let o=(e.question??"").trim(),a=ar(e.bestBid,null),s=ar(e.bestAsk,null),l=ar(e.lastTradePrice,null);return{id:String(e.id),slug:e.slug??"",conditionId:e.conditionId,question:o,label:(e.groupItemTitle??"").trim()||o,outcomes:t.map((c,u)=>({label:c,chance:r[u]})),clobTokenIds:i,protocol:n,volume:ar(e.volumeNum??e.volume,0),volume24h:ar(e.volume24hr,0),liquidity:ar(e.liquidityNum??e.liquidity,0),endDate:e.endDate??null,open:GO(e),fee:ZO(e),priced:a!==null&&s!==null&&s-a<=Vgt+1e-9||l!==null&&l>0,negRisk:e.negRisk===!0,sportsMarketType:e.sportsMarketType??null,bestBid:a,bestAsk:s,oneDayPriceChange:ar(e.oneDayPriceChange,null),groupItemThreshold:ar(e.groupItemThreshold,null)}}function Zgt(e){let t=String(e.abbreviation??"").trim(),r=/^[a-z]{2,}\d+$/i.test(t)?t.replace(/\d+$/,""):t;return r?r.toUpperCase():null}function Ggt(e,t){if(e.sportsMarketType!=="moneyline"||t.length===0)return e;let r=new Map(t.map(n=>[_n(String(n.name??"")),Zgt(n)]));return{...e,outcomes:e.outcomes.map(n=>{let i=r.get(_n(n.label));return i?{...n,shortLabel:i}:n})}}function cee(e){return`${Wg}/event/${e}`}function g2(e){if(!e.id||!e.slug)return null;let t=e.negRisk===!0,r=Array.isArray(e.teams)?e.teams:[],n=(e.markets??[]).map(lee).filter(i=>i!==null).map(i=>Ggt({...i,negRisk:i.negRisk||t},r));return t?n.sort((i,o)=>o.outcomes[0].chance-i.outcomes[0].chance):n.every(i=>i.groupItemThreshold!==null)&&n.sort((i,o)=>(i.groupItemThreshold??0)-(o.groupItemThreshold??0)),{id:String(e.id),slug:e.slug,title:(e.title??"").trim(),description:(e.description??"").trim(),resolutionSource:(e.resolutionSource??"").trim(),image:e.image||e.icon||null,url:cee(e.slug),startDate:e.startDate??null,endDate:e.endDate??null,volume:ar(e.volume,0),volume24h:ar(e.volume24hr,0),liquidity:ar(e.liquidity,0),negRisk:t,ended:e.ended===!0,markets:n,upDown:m2(e.slug,e.markets?.[0])}}function uv(e){return e.markets.find(t=>t.sportsMarketType==="moneyline")}function y2(e,t=2){let r=e.markets.filter(l=>l.open);if(r.length===0)return null;let n=l=>l.priced?l.outcomes.slice(0,t):[],i=uv(e);return i?i.open?{kind:"binary",outcomes:n(i),openMarketCount:r.length}:null:e.markets.length===1?{kind:"binary",outcomes:n(r[0]),openMarketCount:1}:{kind:"multi",outcomes:[...r.filter(l=>l.priced)].sort((l,c)=>c.outcomes[0].chance-l.outcomes[0].chance).slice(0,t).map(l=>({label:l.label,chance:l.outcomes[0].chance})),openMarketCount:r.length}}function WO(e){let t=/polymarket\.com\/(?:[a-z]{2}(?:-[a-z]{2})?\/)?event\/([a-z0-9-]+)(?:\/([a-z0-9-]+))?/i.exec(e);return t?{eventSlug:t[1].toLowerCase(),...t[2]?{marketSlug:t[2].toLowerCase()}:{}}:null}function nPe(e){return`(prediction: ${e})`}function KO(e){let t=/\(prediction:\s*([a-z0-9-]+)\s*\)/i.exec(e);return t?t[1].toLowerCase():null}function _n(e){let t=e.toLowerCase().replace(/đ/g,"d");try{t=t.normalize("NFD").replace(/[̀-ͯ]/g,"")}catch{}return t.replace(/[\s!-/:-@[-`{-~]+/g," ").trim()}function b2(e){if(typeof e!="string"||!e.trim())return null;let t=_n(e);for(let r of Kg)if([r.key,r.label,...r.aliases].map(_n).includes(t))return r;for(let r of Kg)if([r.key,r.label,...r.aliases].map(_n).some(i=>i.length>=4&&(t.startsWith(i)||i.startsWith(t))))return r;return null}var rzr=Kg.map(e=>e.key);m();var Md=1e-9,dv=e=>Math.floor(e*100+Md)/100,iPe=e=>Math.ceil(e*100-Md)/100;function Yg(e,t){return!t||!(t.rate>0)||!(e>0)||!(e<1)?0:t.rate*(e*(1-e))**t.exponent}function oPe(e,t,r){return t>0?e/(1+Yg(t,r)/t):e}function aPe(e,t,r){let n=[...e].sort((a,s)=>a.price-s.price),i=t,o=0;for(let a of n){if(i<=Md)break;if(!(a.price>0))continue;let s=1+Yg(a.price,r)/a.price,l=a.price*a.size,c=l*s;c>=i?(o+=i/s,i=0):(o+=l,i-=c)}return{notional:o,filled:i<=Md}}function sPe(e,t,r){return Math.max(0,t-Ox(e,t,r).feeUsd)}function uee(e,t,r){if(!(e>0)||e>1||!(t>0))return{usd:0,shares:0};let n=t*Yg(e,r),i=Number.isFinite(n)?Math.round(n*1e4)/1e4:0;return{usd:i,shares:i/e}}function dee(e,t,r){let n=Ox(e,t,r),i=n.shares>0?t/n.shares:0,o=n.filled?uee(i,n.shares,r):{usd:0,shares:0},a=Math.max(0,n.shares-o.shares);return{shares:a,usd:t,feeUsd:o.usd,avgPrice:a>0?t/a:0,worstPrice:n.worstPrice,filled:n.filled}}function pee(e,t,r,n,i=0){if(!(t>0))return e;let o=Yg(t,n)*(1+i/100),s=Math.min(e,r)/t*o;return r<=e+s?Math.max(r-s,0):e}function Ox(e,t,r){let n=[...e].sort((c,u)=>c.price-u.price),i=t,o=0,a=0,s=n[0]?.price??0;for(let c of n){if(i<=Md)break;let u=c.price*c.size;s=c.price;let d=u>=i?i/c.price:c.size;o+=d,a+=d*Yg(c.price,r),i=u>=i?0:i-u}let l=t-i;return{shares:o,usd:l,feeUsd:a,avgPrice:o>0?l/o:0,worstPrice:s,filled:i<=Md}}function fee(e,t,r){let n=[...e].sort((c,u)=>u.price-c.price),i=t,o=0,a=0,s=n[0]?.price??0;for(let c of n){if(i<=Md)break;let u=Math.min(i,c.size);s=c.price,o+=u*c.price,a+=u*Yg(c.price,r),i-=u}let l=t-i;return{shares:l,usd:o-a,feeUsd:a,avgPrice:l>0?o/l:0,worstPrice:s,filled:i<=Md}}function mee(e,t,r){return e?t.side==="BUY"?t.usd>0?Ox(e.asks,t.usd,r):null:t.shares>0?fee(e.bids,t.shares,r):null:null}function _2(e,t,r,n=zO.DEFAULT_SLIPPAGE){if(!(t>0))return e;let i=Math.max(0,Math.round(-Math.log10(t))),o=Math.round(e/t),a=r==="BUY"?Math.min(Math.ceil(o*(1+n)-Md),Math.round(1/t)-1):Math.max(Math.floor(o*(1-n)+Md),1);return Number((a*t).toFixed(i))}function lPe(e,t,r,n=zO.DEFAULT_SLIPPAGE,i="v1",o){let a=mee(t,r,o);if(!a||!t)return{error:Bm.ENTER_AMOUNT,quote:null};if(a.shares<=0)return{error:Bm.NO_LIQUIDITY,quote:a};if(r.side==="BUY"){let u=dv(r.usd),d=_2(a.worstPrice,t.tickSize,"BUY",n),p=typeof r.cash=="number"&&r.cash>=0?r.cash:null,h=p===null?u:dv(pee(u,d,p,o)),y=dee(t.asks,u,o);return u<zO.MIN_BUY_USD?{error:Bm.BELOW_MINIMUM,quote:y}:!y.filled||!Ox(t.asks,h,o).filled?{error:Bm.NOT_ENOUGH_LIQUIDITY,quote:y}:{quote:y,order:{tokenId:e,protocol:i,side:"BUY",amount:u,notional:h,maxPrice:d,...p===null?{}:{maxSpend:p}}}}let s=a,l=r.heldShares;if(l!==void 0&&r.shares>l+1e-6)return{error:Bm.EXCEEDS_HOLDING,quote:s,maxShares:dv(l)};if(!s.filled)return{error:Bm.NOT_ENOUGH_LIQUIDITY,quote:s,maxShares:dv(s.shares)};let c=dv(l!==void 0?Math.min(r.shares,l):r.shares);return c<=0?{error:Bm.TOO_SMALL,quote:s}:{quote:s,order:{tokenId:e,protocol:i,side:"SELL",shares:c,minPrice:_2(s.worstPrice,t.tickSize,"SELL",n)}}}function cPe(e,t){let r=t==="BUY"?e?.asks[0]:e?.bids[0];return r?r.price:null}function pv(e,t){return e.filter(r=>Number.isFinite(r.price)&&Number.isFinite(r.size)&&r.size>0).sort((r,n)=>t==="bids"?n.price-r.price:r.price-n.price)}m();Yq();var Gre="0x0000000000000000000000000000000000000000",Jq=(e,t)=>!!e&&!!t&&e.toLowerCase()===t.toLowerCase();function mc(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)}function IR(){return ti(Dd)}var ER=e=>e.toLowerCase();function zOe(e){return Hi.encode([{type:"address"},{type:"bytes32"}],[ER(fc.depositWalletFactory),di.padLeft(ER(e),32)])}function nwt(e,t){let r=BigInt((t.length-2)/2),n=Um.PREFIX+(r<<BigInt(56));return Kr.keccak256(di.concat(di.fromNumber(n,{size:10}),ER(e),"0x6009",Um.CONST2,Um.CONST1,t))}function iwt(e,t){let r=BigInt((t.length-2)/2),n=Um.BEACON_PREFIX+(r<<BigInt(56));return Kr.keccak256(di.concat(di.fromNumber(n,{size:10}),ER(e),Um.BEACON_CONST3,Um.BEACON_CONST2,Um.BEACON_CONST1,t))}function Wre(e){let t=zOe(e);return Su.fromCreate2({from:fc.depositWalletFactory,salt:Kr.keccak256(t),bytecodeHash:nwt(fc.depositWalletImplementation,t)})}function Kre(e,t){let r=zOe(e);return Su.fromCreate2({from:fc.depositWalletFactory,salt:Kr.keccak256(r),bytecodeHash:iwt(t,r)})}function Yre(e){return Su.fromCreate2({from:fc.safeFactory,salt:Kr.keccak256(Hi.encode([{type:"address"}],[ER(e)])),bytecodeHash:fc.safeInitCodeHash})}var AR=null;function owt(e){return AR||(AR=awt(e),AR.catch(()=>{AR=null})),AR}async function awt(e){try{let{data:t}=await e.call({to:fc.depositWalletFactory,data:fc.factoryBeaconSelector});return t&&t.length>=66?`0x${t.slice(-40)}`:Gre}catch(t){if(kj(t)!==void 0)return Gre;throw t}}async function PR(e,t){return await e.getCode({address:t})!==void 0}async function Jre(e,t=IR()){let r=Wre(e),n=await owt(t);return Jq(n,Gre)||await PR(t,r)?r:Kre(e,n)}async function Xq(e,t,r=IR()){if(t&&Jq(t,e))return{address:e,owner:e,kind:"profile",deployed:await PR(r,e)};let n=await Jre(e,r),i=Yre(e),[o,a]=await Promise.all([PR(r,n),PR(r,i)]);if(t){if(Jq(t,i))return{address:i,owner:e,kind:"safe",deployed:a};if(Jq(t,n))return{address:n,owner:e,kind:"deposit-wallet",deployed:o};if(await PR(r,t))return{address:t,owner:e,kind:"profile",deployed:!0}}return o?{address:n,owner:e,kind:"deposit-wallet",deployed:!0}:a?{address:i,owner:e,kind:"safe",deployed:!0}:{address:n,owner:e,kind:"deposit-wallet",deployed:!1}}async function CR(e,t=IR()){return t.readContract({address:mu,abi:Er,functionName:"balanceOf",args:[e]})}var swt=[{type:"function",name:"balanceOfBatch",stateMutability:"view",inputs:[{name:"accounts",type:"address[]"},{name:"ids",type:"uint256[]"}],outputs:[{name:"",type:"uint256[]"}]}];async function Qq(e,t,r=IR()){if(t.length===0)return{};let n=await r.readContract({address:jO,abi:swt,functionName:"balanceOfBatch",args:[t.map(()=>e),t.map(o=>BigInt(o))]}),i={};return t.forEach((o,a)=>{i[o]=Number(n[a]??BigInt(0))/10**hu}),i}async function iT(e,t=IR()){return Number(await CR(e,t))/10**hu}var Xm=class extends Error{constructor(r,n){super(n);g(this,"status");this.name="PolymarketApiError",this.status=r}},OR=3e4,RR=1e4,lwt=60*6e4,cwt=64,HOe=100,VOe=1e3,uwt=new Set([429,500,502,503,504]),ZOe=2,dwt=3e3,pwt={active:"true",archived:"false",closed:"false",featured_order:"true",order:"featuredOrder",ascending:"true"},GOe={closed:"false",order:"volume",ascending:"false",limit:"50"},fwt=50,mwt=5e3,hwt="1",gwt="64",WOe=e=>new Promise(t=>setTimeout(t,e));function KOe(e,t){let r=t?Number(t)*1e3:NaN;return Number.isFinite(r)&&r>=0?Math.min(r,dwt):400*2**e}async function e4(e,t){try{return await e}catch(r){if(XOe(r))throw r;return t}}function XOe(e){let t=e?.name,r=e?.code;return t==="AbortError"||t==="CanceledError"||r==="ERR_CANCELED"}var Br=class{constructor(t={}){g(this,"gamma");g(this,"data");g(this,"bridge");g(this,"builderCode");g(this,"clob");g(this,"web");g(this,"cache",new Map);g(this,"accounts",new Map);this.gamma=(t.gammaBaseUrl??Gg.GAMMA).replace(/\/+$/,""),this.data=(t.dataBaseUrl??Gg.DATA).replace(/\/+$/,""),this.bridge=(t.bridgeBaseUrl??Gg.BRIDGE).replace(/\/+$/,""),this.builderCode=t.builderCode,this.clob=(t.clobBaseUrl??Gg.CLOB).replace(/\/+$/,""),this.web=(t.webBaseUrl??Wg).replace(/\/+$/,"")}async listEvents({sort:t,tagId:r,limit:n}){let{order:i,ascending:o}=FO[t],a={closed:"false",order:i,ascending:String(o),limit:String(Math.min(Math.max(1,n),HOe))};r&&(a.tag_id=r),t==="ending_soon"&&(a.end_date_min=new Date(Math.floor(Date.now()/6e4)*6e4).toISOString()),(t==="ending_soon"||t==="competitive")&&(a.exclude_tag_id=[XQ]),t==="new"&&!r&&(a.exclude_tag_id=[QQ,eee]);let s=this.eventRows(a);if(t!=="trending"||r)return t4(await s);let l=Date.now(),[c,u,d,p,h]=await Promise.all([s,e4(this.eventRows({...pwt,limit:String(fwt)}),[]),e4(this.eventRows({...GOe,tag_id:hwt}),[]),e4(this.eventRows({...GOe,tag_id:gwt}),[]),e4(this.eventRows({slug:VAe(l),limit:"1"}).then(y=>y[0]??null),null)]);return t4(GAe({feed:c,featured:u,sports:[...d,...p],btc5m:h},l))}async eventRows(t){let r=await this.getJson(`${this.gamma}/events/keyset`,t,OR);return Array.isArray(r.events)?r.events:[]}async getUpDownPrices(t){let r=await this.getJson(`${this.web}/api/crypto/crypto-price`,JAe(t),mwt),n=i=>{let o=ar(i,null);return o!==null&&o>0?o:null};return{openPrice:n(r?.openPrice),closePrice:n(r?.closePrice),completed:r?.completed===!0}}async searchEvents(t,r){let n=t.trim();if(!n)return[];let o=((await this.getJson(`${this.gamma}/public-search`,{q:n,events_status:"active",limit_per_type:String(Math.min(Math.max(1,r),50)),keep_closed_markets:"0"},OR)).events??[]).map(l=>l.id).filter(l=>typeof l=="string"&&!!l);if(o.length===0)return[];let a=await this.getJson(`${this.gamma}/events/keyset`,{id:o,limit:String(Math.min(o.length,HOe))},OR),s=new Map(t4(a.events).map(l=>[l.id,l]));return o.map(l=>s.get(l)).filter(l=>l!==void 0)}async getEventBySlug(t){let r=await this.getJson(`${this.gamma}/events/keyset`,{slug:t,limit:"1"},OR);return t4(r.events)[0]??null}async getMarketTradeInfo(t){if(!/^0x[0-9a-fA-F]{64}$/.test(t))return null;let n=(await this.getJson(`${this.gamma}/markets/keyset`,{condition_ids:t,limit:"1"},OR)).markets?.[0];if(!n)return null;let i=VO(n);return i===null?null:{conditionId:t,protocol:i,fee:ZO(n),negRisk:n.negRisk===!0,open:GO(n),outcomes:rPe(n,i),question:(n.question??"").trim(),label:(n.groupItemTitle??"").trim(),eventTitle:(n.events?.[0]?.title??"").trim()}}async getProfileWallet(t){try{let r=await this.getJson(`${this.gamma}/public-profile`,{address:t},RR);return typeof r.proxyWallet=="string"&&r.proxyWallet?r.proxyWallet:null}catch(r){if(r instanceof Xm&&r.status===404)return null;throw r}}async resolveAccount(t){let r=t.toLowerCase(),n=this.accounts.get(r);if(n&&(n.account.deployed||Date.now()-n.at<RR))return n.account;let i=await Xq(t,await this.getProfileWallet(t));return this.accounts.set(r,{account:i,at:Date.now()}),i}async getCash(t){return iT(t)}async getShares(t,r){return Qq(t,r)}async getPositionsValue(t){let r=await this.getJson(`${this.data}/v2/value`,{user:t},RR);return ar(r?.data?.value,0)}async getPositions(t,r,n={}){let i=await this.getJson(`${this.data}/v2/positions`,{user:t,status:"OPEN",filter_type:"TOKENS",filter_amount:String(ree),sort_by:"CURRENT_VALUE",sort_direction:"DESC",limit:String(Math.min(Math.max(1,r),VOe))},n.fresh?0:RR);return JOe(i).map(vwt)}async getActivity(t,r){let n=await this.getJson(`${this.data}/v2/activity`,{user:t,type:tee.join(","),sort_direction:"DESC",limit:String(Math.min(Math.max(1,r),VOe))},RR);return JOe(n).map(wwt)}async getBridgeAssets(){return((await this.getJson(`${this.bridge}/supported-assets`,{},lwt)).supportedAssets??[]).map(kwt).filter(r=>r!==null)}async getDepositAddresses(t){let n=(await this.requestJson("POST",`${this.bridge}/deposit`,{body:{address:t},headers:{"X-Builder-Code":this.builderCode??Ix()}})).address??{},i=typeof n.evm=="string"&&/^0x[0-9a-fA-F]{40}$/.test(n.evm)?n.evm:"";if(!i)throw new Xm(502,"Bridge returned no EVM deposit address");return{evm:i,svm:Yr(n.svm),btc:Yr(n.btc),tron:Yr(n.tron)}}async createWithdrawalAddresses(t){let n=(await this.requestJson("POST",`${this.bridge}/withdraw`,{body:{address:t.wallet,toChainId:t.toChainId,toTokenAddress:t.toTokenAddress,recipientAddr:t.recipient},headers:{"X-Builder-Code":this.builderCode??Ix()}})).address??{},i=typeof n.evm=="string"&&/^0x[0-9a-fA-F]{40}$/.test(n.evm)?n.evm:"";if(!i)throw new Xm(502,"Bridge returned no EVM withdrawal address");return{evm:i,svm:Yr(n.svm),btc:Yr(n.btc),tron:Yr(n.tron)}}async getBridgeQuote(t){let r=await this.requestJson("POST",`${this.bridge}/quote`,{body:t}),n=r.estFeeBreakdown??{},i=Yr(r.estToTokenBaseUnit);if(!/^\d+$/.test(i))throw new Xm(502,"Bridge returned no quote");return{estToTokenBaseUnit:i,estOutputUsd:ar(r.estOutputUsd,0),estInputUsd:ar(r.estInputUsd,0),estCheckoutTimeMs:ar(r.estCheckoutTimeMs,null),minReceived:ar(n.minReceived,null),totalImpactUsd:ar(n.totalImpactUsd,0),totalImpactPercent:ar(n.totalImpact,0),quoteId:Yr(r.quoteId)}}async getBridgeTransfers(t){return/^0x[0-9a-fA-F]{40}$/.test(t)?((await this.requestJson("GET",`${this.bridge}/status/${t}`)).transactions??[]).map(xwt).sort((n,i)=>(i.createdTimeMs??0)-(n.createdTimeMs??0)):[]}async getOrderBook(t,r){let n=await this.requestJson("GET",`${this.clob}/book?${YOe({token_id:t})}`,{signal:r});return ywt(t,n)}getJson(t,r,n){let i=YOe(r),o=i?`${t}?${i}`:t,a=this.cache.get(o);if(a&&Date.now()-a.at<a.ttl)return a.value;let s=this.requestJson("GET",o);if(s.catch(()=>{this.cache.get(o)?.value===s&&this.cache.delete(o)}),this.cache.size>=cwt){let l=this.cache.keys().next().value;l!==void 0&&this.cache.delete(l)}return this.cache.set(o,{at:Date.now(),ttl:n,value:s}),s}async requestJson(t,r,n={}){for(let i=0;;i++){let o;try{o=await Qe.request(t,r,n.body,{...n.signal?{signal:n.signal}:{},headers:{...n.body!==void 0?{"Content-Type":"application/json"}:{},...n.headers}})}catch(a){if(XOe(a)||i>=ZOe)throw a;await WOe(KOe(i));continue}if(o.ok)return o.data;if(!uwt.has(o.status)||i>=ZOe)throw new Xm(o.status,It(o));await WOe(KOe(i,o.headers["retry-after"]))}}};function YOe(e){let t=[];for(let[r,n]of Object.entries(e))for(let i of Array.isArray(n)?n:[n])t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);return t.join("&")}function t4(e){return(Array.isArray(e)?e:[]).map(g2).filter(t=>t!==null)}var Yr=e=>typeof e=="string"?e:"";function ywt(e,t){let r=n=>(n??[]).map(i=>({price:ar(i.price,NaN),size:ar(i.size,NaN)}));return{tokenId:e,bids:pv(r(t.bids),"bids"),asks:pv(r(t.asks),"asks"),tickSize:ar(t.tick_size,.01),minOrderSize:ar(t.min_order_size,0),negRisk:t.neg_risk===!0,lastTradePrice:ar(t.last_trade_price,null),updatedAt:Date.now()}}var JOe=e=>Array.isArray(e?.data)?e.data:[],bwt="1970-01-01",_wt=999;function vwt(e){let t=Yr(e.end_date),r=ar(e.outcome_index,0);return{title:Yr(e.title),outcome:Yr(e.outcome),eventSlug:Yr(e.event_slug),conditionId:Yr(e.condition_id),asset:Yr(e.token_id),outcomeIndex:r===_wt?0:r,oppositeOutcome:Yr(e.opposite_outcome),oppositeAsset:Yr(e.opposite_token_id),icon:Yr(e.icon)||null,shares:ar(e.current_size,0),avgPrice:ar(e.avg_price,0),curPrice:ar(e.current_price,0),initialValue:ar(e.entry_cost_usdc,0),currentValue:ar(e.current_value,0),cashPnl:ar(e.unrealized_pnl,0),percentPnl:ar(e.percent_pnl,0),redeemable:e.redeemable===!0,endDate:t&&t!==bwt?t:null}}function wwt(e){let t=Yr(e.side).toUpperCase();return{type:Yr(e.type).toUpperCase(),side:t==="BUY"||t==="SELL"?t:null,title:Yr(e.title),outcome:Yr(e.outcome),eventSlug:Yr(e.event_slug),shares:ar(e.size,0),usd:ar(e.usdc_size,0),price:ar(e.price,0),timestamp:ar(e.timestamp,0),transactionHash:Yr(e.transaction_hash)}}var Swt="0x0000000000000000000000000000000000000000";function kwt(e){let t=e.token??{},r=Yr(t.address).toLowerCase(),n=ar(t.decimals,NaN);return!e.chainId||!r||!Number.isInteger(n)?null:{chainId:String(e.chainId),chainName:Yr(e.chainName),symbol:Yr(t.symbol),name:Yr(t.name),address:r===UO?Swt:r,decimals:n,minUsd:ar(e.minCheckoutUsd,0)}}function xwt(e){return{fromChainId:String(e.fromChainId??""),fromTokenAddress:Yr(e.fromTokenAddress).toLowerCase(),fromAmountBaseUnit:String(e.fromAmountBaseUnit??"0"),toChainId:String(e.toChainId??""),status:Yr(e.status).toUpperCase(),txHash:Yr(e.txHash)||null,createdTimeMs:ar(e.createdTimeMs,null)}}m();m();m();bg();Sg();function Xre(e,t,r,n,i){let o=`${t}${r}${n}${i??""}`,a=ba(Rs,Awt(e),new TextEncoder().encode(o));return Pwt(a).replace(/\+/g,"-").replace(/\//g,"_")}function Hd(e){return typeof e?.authorize=="function"?e:Qre(e)}var Twt=["POLY_BUILDER_API_KEY","POLY_BUILDER_PASSPHRASE","POLY_BUILDER_SIGNATURE","POLY_BUILDER_TIMESTAMP"];function QOe(e){return{isBuilderKey:!0,supportGasless:!0,async authorize({method:t,path:r,body:n}){let i=typeof e.headers=="function"?await e.headers():e.headers,o=await fetch(e.url,{method:"POST",headers:{...i??{},"Content-Type":"application/json"},body:JSON.stringify({method:t,path:r,body:n}),credentials:e.credentials});if(!o.ok)throw new Error(`Remote builder signer rejected the request (${o.status})`);let a=await o.json(),s={};for(let l of Twt){let c=a?.[l];if(typeof c!="string"||!c)throw new Error(`Remote builder signer answered without ${l}`);s[l]=c}return s}}}function Qre(e){return{isBuilderKey:!0,supportGasless:!0,async authorize({method:t,path:r,body:n}){let i=Math.floor(Date.now()/1e3);return{POLY_BUILDER_API_KEY:e.key,POLY_BUILDER_PASSPHRASE:e.passphrase,POLY_BUILDER_SIGNATURE:Xre(e.secret,i,t,r,n),POLY_BUILDER_TIMESTAMP:String(i)}}}}function Awt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)n[i]=r.charCodeAt(i);return n}function Pwt(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}m();var Ewt=new Set(["STATE_CONFIRMED","STATE_FAILED","STATE_INVALID"]),Iwt=e=>new Promise(t=>setTimeout(t,e));async function eRe(e,t={}){let r=await fetch(`${Gg.RELAYER}${e}`,t),n=await r.text(),i;try{i=n?JSON.parse(n):null}catch{i=null}if(!r.ok){let o=i?.error||n||`HTTP ${r.status}`;throw new Error(`Relayer ${t.method??"GET"} ${e} failed (${r.status}): ${o}`)}return i}async function Cwt(e,t,r){let n=JSON.stringify({type:"WALLET-CREATE",from:e,to:fc.depositWalletFactory,metadata:"Deploy Deposit Wallet"}),i=await Hd(t).authorize({method:"POST",path:l2,body:n});return eRe(l2,{method:"POST",headers:{"Content-Type":"application/json",...i},body:n,signal:r})}async function Owt(e,t){let r=Date.now();for(;Date.now()-r<c2.TIMEOUT_MS;){let n=await eRe(`/transaction?id=${encodeURIComponent(e)}`,{signal:t}),i=Array.isArray(n)?n[0]:null;if(!i)throw new Error("Relayer transaction not found");if(Ewt.has(i.state))return i;if(t?.aborted)throw new Error("Cancelled");await Iwt(c2.INTERVAL_MS)}throw new Error("Deploy timed out")}async function r4(e,t,r){let n=await Cwt(e,t,r),i=await Owt(n.transactionID,r);if(i.state!=="STATE_CONFIRMED")throw new Error(`Deposit wallet deployment failed: ${i.error_msg||i.state}`);return{transactionHash:i.transactionHash,proxyAddress:i.proxyAddress,state:i.state}}m();var k5=null;function zBt(){let e=globalThis.URLSearchParams;typeof e!="function"||"size"in e.prototype||Object.defineProperty(e.prototype,"size",{configurable:!0,get(){let t=0;return this.forEach(()=>{t+=1}),t}})}function Hy(){return zBt(),k5??(k5=Promise.all([Promise.resolve().then(()=>(NHe(),$He)),Promise.resolve().then(()=>(MHe(),DHe))]).then(([e,t])=>({sdk:e,actions:t}))),k5.catch(()=>{k5=null}),k5}var LHe=20,HBt=5e3,VBt=5*6e4,x5=new Map;function ZBt(e){let t=x5.get(e);if(t)return t;let r=new AbortController,n=setTimeout(()=>r.abort(),HBt),i=Array.from({length:LHe},(a,s)=>({jsonrpc:"2.0",id:s+1,method:"eth_chainId",params:[]})),o=fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i),signal:r.signal}).then(async a=>{if(!a.ok)return!1;let s=await a.json();return Array.isArray(s)&&s.length===LHe&&s.every(l=>l&&typeof l=="object"&&"result"in l&&!("error"in l))}).catch(()=>!1).finally(()=>clearTimeout(n));return x5.set(e,o),o.then(a=>{a||setTimeout(()=>x5.get(e)===o&&x5.delete(e),VBt)}),o}function GBt(){let e=J_()[Dd],t=xo(Dd)?.rpcUrls.default.http??[];return[...new Set([...e?[e]:[],...t,...Rm(Dd)])]}async function UHe(){let e=GBt();for(let t of e)if(await ZBt(t))return t;return e[0]}async function g0(){let[{sdk:e},t]=await Promise.all([Hy(),UHe()]);return t?e.forkEnvironmentConfig({name:"production",rpc:t},e.production):e.production}var $fe=new Map,T5=async()=>{let e=await UHe(),t=e??"",r=$fe.get(t);return r||(r=Hy().then(({sdk:n})=>n.createPublicClient({environment:e?n.forkEnvironmentConfig({name:"production",rpc:e},n.production):n.production})),r.catch(()=>$fe.delete(t)),$fe.set(t,r)),r};m();function Vy(e){return{async getAddress(){return e.address},async signTypedData(t){let{EIP712Domain:r,...n}=t.types;return await e.signTypedData({...t,types:n})},async signMessage(t){if(!e.signMessage)throw new Error("Polymarket signer: signMessage is not supported by this wallet");return await e.signMessage(t)},async sendTransaction(){throw new Error("Polymarket signer: direct transactions are not supported \u2014 use the gasless relayer")}}}var jHe=(BigInt(1)<<BigInt(256))-BigInt(1),qHe=[{type:"function",name:"isApprovedForAll",stateMutability:"view",inputs:[{name:"account",type:"address"},{name:"operator",type:"address"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]}];async function A5(e){let t=await g0(),[r,n]=await Promise.all([T5().then(u=>u.fetchTradingApprovalsState({user:e})),WBt(e,t)]),i=new Set(KBt(t).map(u=>u.toLowerCase())),o=(r.missing?.erc20??[]).map(u=>({tokenAddress:u.tokenAddress,spenderAddress:u.spenderAddress})).filter(u=>!i.has(String(u.spenderAddress).toLowerCase())),a=(r.missing?.erc1155??[]).map(u=>({tokenAddress:u.tokenAddress,operatorAddress:u.operatorAddress})).filter(u=>!i.has(String(u.operatorAddress).toLowerCase())),s=(u,d)=>`${u.toLowerCase()}:${d.toLowerCase()}`,l=new Set(o.map(u=>s(u.tokenAddress,u.spenderAddress))),c=new Set(a.map(u=>s(u.tokenAddress,u.operatorAddress)));for(let u of n.erc20)l.has(s(u.tokenAddress,u.spenderAddress))||o.push(u);for(let u of n.erc1155)c.has(s(u.tokenAddress,u.operatorAddress))||a.push(u);return{isFullyApproved:o.length===0&&a.length===0,missing:{erc20:o,erc1155:a}}}async function WBt(e,t){let r=t?.contracts??{},n=(c,u)=>typeof c=="string"&&c?c:u,i=n(r.negRiskAdapter,YQ),o=n(r.collateralToken,mu),a=n(r.conditionalTokens,jO),[s,l]=await ti(Dd).multicall({contracts:[{address:o,abi:Er,functionName:"allowance",args:[e,i]},{address:a,abi:qHe,functionName:"isApprovedForAll",args:[e,i]}],allowFailure:!1});return{erc20:s<jHe/BigInt(2)?[{tokenAddress:o,spenderAddress:i}]:[],erc1155:l?[]:[{tokenAddress:a,operatorAddress:i}]}}function KBt(e){let t=e?.contracts?.perpsDepositContract;return[typeof t=="string"&&t?t:KQ]}async function wp(e,t=new Br){let r=await t.resolveAccount(e),n=r.deployed?await A5(r.address):null;return{account:r,approvals:n}}function FHe(e){return e.isDeployed?e.isTradingEnabled?e.isApproved?Ao.DONE:Ao.APPROVE:Ao.ENABLE_TRADING:Ao.DEPLOY}function Nfe(e){return[...e.erc20.map(t=>({to:t.tokenAddress,data:sr({abi:Er,functionName:"approve",args:[t.spenderAddress,jHe]})})),...e.erc1155.map(t=>({to:t.tokenAddress,data:sr({abi:qHe,functionName:"setApprovalForAll",args:[t.operatorAddress,!0]})}))]}var Ah=class extends Error{constructor(r,n,i){super(n);g(this,"step");this.name="PolymarketOnboardingError",this.step=r,i!==void 0&&(this.cause=i)}};async function zHe(e){let t=e.service??new Br,r=e.tracking??{intervalMs:u2.INTERVAL_MS,maxAttempts:u2.MAX_ATTEMPTS},n=Vy(e.signer),i=e.chain?.approvals??A5,o=b=>{YBt(e.signal,b),e.onStep?.(b)},a=await t.resolveAccount(e.signer.address);if(a.kind==="profile")throw new Ah(Ao.ENABLE_TRADING,"This address is a Polymarket account wallet, not a wallet that can sign for one.");let s=e.chain?.isDeployed??(async b=>await ti(Dd).getCode({address:b})!==void 0);a.deployed||(o(Ao.DEPLOY),await aP(Ao.DEPLOY,async()=>{await r4(e.signer.address,e.builder,e.signal),await BHe(()=>s(a.address),b=>b,r,e.signal)}),a={...a,deployed:!0});let{sdk:l,actions:c}=await Hy(),u=Hd(e.builder),d=await g0();o(Ao.ENABLE_TRADING);let p=await aP(Ao.ENABLE_TRADING,()=>l.createSecureClient({environment:d,signer:n,apiKey:u,wallet:a.address,...e.credentials?{credentials:{...e.credentials}}:{}})),h=cD(p);if(!h)throw new Ah(Ao.ENABLE_TRADING,"No CLOB credentials were issued.");await aP(Ao.ENABLE_TRADING,async()=>e.onCredentials?.(h));let y=await aP(Ao.APPROVE,()=>i(a.address));return y.isFullyApproved||(o(Ao.APPROVE),y=await aP(Ao.APPROVE,async()=>{let b=Nfe(y.missing),_=await c.prepareGaslessTransaction(p,{calls:b,metadata:JQ});return await(await JBt(_,n)).wait(),BHe(()=>i(a.address),S=>S.isFullyApproved,r,e.signal)})),await aP(Ao.APPROVE,()=>c.updateBalanceAllowance(p,{assetType:"COLLATERAL"})),o(Ao.DONE),{account:a,credentials:h,approvals:y}}function cD(e){let{key:t,secret:r,passphrase:n}=e?.credentials??{};return typeof t=="string"&&t&&typeof r=="string"&&r&&typeof n=="string"&&n?{key:t,secret:r,passphrase:n}:null}async function aP(e,t){try{return await t()}catch(r){if(r instanceof Ah)throw r;let n=r instanceof Error&&r.message?r.message:String(r);throw new Ah(e,n,r)}}function YBt(e,t){if(e?.aborted)throw new Ah(t,"Cancelled")}async function BHe(e,t,r,n){for(let i=1;;i++){let o=await e();if(t(o))return o;if(i>=r.maxAttempts)throw new Error("Not confirmed on-chain yet \u2014 please try again in a moment.");if(n?.aborted)throw new Error("Cancelled");await new Promise(a=>setTimeout(a,r.intervalMs))}}async function JBt(e,t){let r=await e.next();for(;!r.done;){let n=r.value;try{switch(n.kind){case"requestAddress":r=await e.next(await t.getAddress());break;case"signGaslessTypedData":r=await e.next(await t.signTypedData(n.payload));break;case"signGaslessMessage":r=await e.next(await t.signMessage(n.payload));break;default:throw new Error(`Unsupported gasless workflow request: ${String(n.kind)}`)}}catch(i){r=await e.throw(i)}}return r.value}m();var HHe=new Set(qO),XBt="0x0000000000000000000000000000000000000000";function Dfe(e){return e.filter(t=>/^\d+$/.test(t.chainId)&&Number(t.chainId)>0&&Number(t.chainId)<2**32&&t.address!==XBt&&/^0x[0-9a-f]{40}$/.test(t.address)&&HHe.has(t.symbol.toUpperCase()))}async function P5(e,t){let r=new Map;for(let i of Dfe(t)){let o=Number(i.chainId),a=r.get(o)??[];a.some(s=>s.address===i.address)||a.push(i),r.set(o,a)}return(await Promise.allSettled([...r.entries()].map(async([i,o])=>{let a=`0x${i.toString(16)}`,l=await ti(a).multicall({contracts:o.flatMap(c=>[{address:c.address,abi:Er,functionName:"balanceOf",args:[e]},{address:c.address,abi:Er,functionName:"decimals"}]),allowFailure:!0});return o.flatMap((c,u)=>{let d=l[2*u],p=l[2*u+1],h=d?.status==="success"&&typeof d.result=="bigint"?d.result:BigInt(0),y=p?.status==="success"&&(typeof p.result=="number"||typeof p.result=="bigint")?Number(p.result):NaN;return h<=BigInt(0)||!Number.isInteger(y)?[]:[{chainId:i,chainHex:a,chainName:ye(a)||c.symbol,tokenAddress:c.address,symbol:c.symbol,decimals:y,balance:Wk(h,y),minUsd:c.minUsd}]})}))).flatMap(i=>i.status==="fulfilled"?i.value:[]).sort((i,o)=>Number(o.balance)-Number(i.balance))}var QBt=e=>/^\d+$/.test(e)&&Number(e)>0&&Number(e)<2**32&&!(e in lv);function E5(e){let t=i=>{let o=Xo.CHAIN_ORDER.indexOf(i);return o===-1?Xo.CHAIN_ORDER.length:o},r=i=>{let o=qO.indexOf(i.toUpperCase());return o===-1?qO.length:o},n=new Set;return e.filter(i=>QBt(i.chainId)&&/^0x[0-9a-f]{40}$/.test(i.address)&&i.symbol).filter(i=>{let o=`${i.chainId}:${i.address}`;return n.has(o)?!1:(n.add(o),!0)}).map(i=>({chainId:i.chainId,chainName:i.chainName,symbol:i.symbol,tokenAddress:i.address,decimals:i.decimals,minUsd:i.minUsd,stable:HHe.has(i.symbol.toUpperCase())})).sort((i,o)=>t(i.chainId)-t(o.chainId)||i.chainName.localeCompare(o.chainName)||r(i.symbol)-r(o.symbol)||i.symbol.localeCompare(o.symbol))}async function uD(e,t=new Br){let r=Nm(String(e.amount??"").trim(),e.asset.decimals);if(r===null||r<=BigInt(0))throw new Error("Enter an amount");let n=await t.getBridgeQuote({fromAmountBaseUnit:r.toString(),fromChainId:e.asset.chainId,fromTokenAddress:e.asset.tokenAddress,recipientAddress:e.wallet,toChainId:BO,toTokenAddress:mu});return{estInputUsd:n.estInputUsd,estOutputUsd:n.estOutputUsd,priceImpactPercent:n.totalImpactPercent,totalFeeUsd:n.totalImpactUsd,minReceivedUsd:n.minReceived,estTimeMs:n.estCheckoutTimeMs}}var Mfe=100;async function VHe(e,t,r=new Br){let n=Math.max(Mfe,e.minUsd||0);if(e.stable)return uD({asset:e,amount:String(n),wallet:t},r);let i=await uD({asset:e,amount:"1",wallet:t},r);if(!(i.estInputUsd>0))return i;let o=(n/i.estInputUsd).toFixed(Math.min(e.decimals,8));return uD({asset:e,amount:o,wallet:t},r)}m();var Hl=e=>{let t=typeof e=="number"?e:Number.parseFloat(String(e??""));return Number.isFinite(t)?t:NaN},I5=e=>{let t=Hl(e);return Number.isFinite(t)?String(t):""};function ZHe(e,t){return pv([...e.entries()].map(([r,n])=>({price:Number(r),size:n})),t)}function ejt(e){return{bids:new Map(e.bids.map(t=>[I5(t.price),t.size])),asks:new Map(e.asks.map(t=>[I5(t.price),t.size])),tickSize:e.tickSize,minOrderSize:e.minOrderSize,negRisk:e.negRisk,lastTradePrice:e.lastTradePrice,updatedAt:e.updatedAt}}function tjt(e,t){return{tokenId:e,bids:ZHe(t.bids,"bids"),asks:ZHe(t.asks,"asks"),tickSize:t.tickSize,minOrderSize:t.minOrderSize,negRisk:t.negRisk,lastTradePrice:t.lastTradePrice,updatedAt:t.updatedAt}}function Lfe(e,t,r=Date.now()){let n=t?.payload??{};switch(t?.type){case"book":{let i=e.get(String(n.assetId));if(!i)return!1;let o=a=>[I5(a.price),Hl(a.size)];return i.bids=new Map((n.bids??[]).map(o).filter(([a,s])=>a&&s>0)),i.asks=new Map((n.asks??[]).map(o).filter(([a,s])=>a&&s>0)),Number.isFinite(Hl(n.tickSize))&&(i.tickSize=Hl(n.tickSize)),Number.isFinite(Hl(n.minOrderSize))&&(i.minOrderSize=Hl(n.minOrderSize)),typeof n.negRisk=="boolean"&&(i.negRisk=n.negRisk),Number.isFinite(Hl(n.lastTradePrice))&&(i.lastTradePrice=Hl(n.lastTradePrice)),i.updatedAt=r,!0}case"price_change":{let i=!1;for(let o of n.priceChanges??[]){let a=e.get(String(o.assetId)),s=I5(o.price);if(!a||!s)continue;let l=String(o.side).toUpperCase()==="BUY"?a.bids:a.asks,c=Hl(o.size);c>0?l.set(s,c):l.delete(s),a.updatedAt=r,i=!0}return i}case"last_trade_price":{let i=e.get(String(n.assetId));return!i||!Number.isFinite(Hl(n.price))?!1:(i.lastTradePrice=Hl(n.price),i.updatedAt=r,!0)}case"tick_size_change":{let i=e.get(String(n.assetId));return!i||!Number.isFinite(Hl(n.newTickSize))?!1:(i.tickSize=Hl(n.newTickSize),i.updatedAt=r,!0)}default:return!1}}function GHe(e,t){let r=[...new Set(e.filter(Boolean))],n=t.service??new Br,i=t.throttleMs??HO.THROTTLE_MS,o=t.staleMs??HO.STALE_MS,a=t.fallbackPollMs??HO.FALLBACK_POLL_MS,s=new Map,l=new AbortController,c=!1,u=null,d=null,p=Date.now(),h=0,y=null,b=null,_=null,v=I=>{u!==I&&(u=I,t.onStatus?.(I))},S=()=>{let I={};for(let[D,q]of s)I[D]=tjt(D,q);return I},w=()=>{c||(y&&clearTimeout(y),y=null,h=Date.now(),t.onUpdate(S()))},k=()=>{if(c||y)return;let I=i-(Date.now()-h);I<=0?w():y=setTimeout(w,I)},T=()=>(_??(_=Promise.all(r.map(async I=>{try{let D=await n.getOrderBook(I,l.signal);s.set(I,ejt(D))}catch(D){c||t.onError?.(D)}})).then(()=>(p=Date.now(),w(),S())).finally(()=>{_=null})),_),O=I=>new Promise(D=>{let q=setTimeout(D,I);l.signal.addEventListener("abort",()=>{clearTimeout(q),D()})}),$=async()=>{for(v("connecting"),await T();!c;){try{let I=await T5();if(c)break;if(d=await I.subscribe([{topic:"market",assetIds:r,customFeatureEnabled:!1}]),c){d.close();break}v("live");for await(let D of d){if(c)break;p=Date.now(),Lfe(s,D,p)&&k()}}catch(I){c||t.onError?.(I)}if(d=null,c)break;v("polling"),await T(),await O(a)}};return b=setInterval(()=>{!c&&Date.now()-p>o&&T()},Math.max(1e3,Math.floor(o/2))),$(),{refresh:T,stop(){c||(c=!0,l.abort(),y&&clearTimeout(y),b&&clearInterval(b),d?.close(),v("stopped"))}}}m();m();var rjt=(e,t)=>!!e&&!!t&&e.key===t.key&&e.secret===t.secret&&e.passphrase===t.passphrase;async function sP(e){let{sdk:t}=await Hy(),r=await t.createSecureClient({environment:await g0(),signer:Vy(e.signer),apiKey:Hd(e.builder),wallet:e.wallet,...e.credentials?{credentials:{...e.credentials}}:{}}),n=cD(r);return n&&!rjt(n,e.credentials)&&await e.onCredentials?.(n),r}function lP(e){let t=e??{},r=String(t.message??"");return t.name==="CancelledSigningError"||/user (rejected|denied)|cancel(l)?ed/i.test(r)&&!/order (was )?cancel/i.test(r)}var Zy=class extends Error{constructor(r,n,i){super(n);g(this,"code");this.name="PolymarketTradeError",this.code=r,i!==void 0&&(this.cause=i)}},njt=15e3,WHe={unmatched:jn.NOT_FILLED,fak_not_filled:jn.NOT_FILLED,fok_not_filled:jn.NOT_FILLED,insufficient_balance_or_allowance:jn.INSUFFICIENT_BALANCE,market_not_ready:jn.MARKET_CLOSED,post_only_mode:jn.TRADING_PAUSED},ijt=[[/not enough balance \/ allowance/i,jn.INSUFFICIENT_BALANCE],[/lower than the minimum/i,jn.BELOW_MIN_SIZE],[/closed only mode/i,jn.CLOSE_ONLY],[/address banned/i,jn.ACCOUNT_BANNED],[/no orders found to match|couldn't be fully filled|not filled/i,jn.NOT_FILLED],[/not yet ready to process|market (is )?(closed|not active|resolved)|orderbook .* does not exist/i,jn.MARKET_CLOSED],[/post-only mode|trading is (currently )?(paused|disabled)|cancel-only/i,jn.TRADING_PAUSED]],ojt=e=>/not enough balance \/ allowance/i.test(String(e?.message??""));function Bfe(e){if(e instanceof Zy)return e;let t=e??{},r=t.message||String(e),n=ijt.find(([o])=>o.test(r))?.[1],i=n===jn.CLOSE_ONLY||n===jn.ACCOUNT_BANNED?n:/restrict|region|geoblock|jurisdiction|not available in your/i.test(r)||t.status===403&&!t.restriction?jn.REGION_RESTRICTED:t.restriction?jn.TRADING_PAUSED:t.name==="InsufficientLiquidityError"?jn.NOT_ENOUGH_LIQUIDITY:lP(e)?jn.CANCELLED:(n??(t.code&&WHe[t.code]))||jn.FAILED;return new Zy(i,r,e)}var ajt=(e,t)=>!!e&&!!t&&e.key===t.key&&e.secret===t.secret&&e.passphrase===t.passphrase,Ufe=e=>{let t=Number.parseFloat(String(e??""));return Number.isFinite(t)?t:0};async function KHe(e){let{order:t}=e;try{let{sdk:r,actions:n}=await Hy(),i=await r.createSecureClient({environment:await g0(),signer:Vy(e.signer),apiKey:Hd(e.builder),wallet:e.wallet,...e.credentials?{credentials:{...e.credentials}}:{}}),o=cD(i);o&&!ajt(o,e.credentials)&&await e.onCredentials?.(o);let a=e.builderCode??Ix(),s=t.side==="BUY"?{assetId:t.tokenId,side:r.OrderSide.BUY,amount:t.notional&&t.notional>0?t.notional:t.amount,...t.maxSpend!==void 0&&t.maxSpend>0?{maxSpend:t.maxSpend}:{},maxPrice:t.maxPrice,builderCode:a,orderType:r.OrderType.FAK}:{assetId:t.tokenId,side:r.OrderSide.SELL,shares:t.shares,minPrice:t.minPrice,builderCode:a,orderType:r.OrderType.FAK},c=await(async()=>{try{return await i.placeMarketOrder(s)}catch(y){if(ojt(y))return{ok:!1,code:"insufficient_balance_or_allowance",error:y};throw y}})();if(!c.ok&&c.code==="insufficient_balance_or_allowance"&&(await n.updateBalanceAllowance(i,sjt(t)),c=await i.placeMarketOrder(s)),!c.ok)throw new Zy(WHe[c.code]??jn.FAILED,c.message||c.code||"Order rejected");if(String(c.status).toLowerCase()===C5.DELAYED)return await ljt(i,String(c.orderId),t,e.delayedTimeoutMs);let u=Ufe(c.makingAmount),d=Ufe(c.takingAmount),p=Array.isArray(c.transactionsHashes)?c.transactionsHashes:[],h=e.settlementTimeoutMs??njt;if(p.length===0&&h>0&&(c.tradeIds?.length??0)>0){let y;p=await Promise.race([n.waitForOrderFillSettlement(i,c).catch(()=>[]),new Promise(b=>{y=setTimeout(()=>b([]),h)})]).finally(()=>clearTimeout(y))}return{orderId:String(c.orderId),status:String(c.status),pending:!1,side:t.side,shares:t.side==="BUY"?d:u,usd:t.side==="BUY"?u:d,transactionHashes:p}}catch(r){throw Bfe(r)}}var C5={DELAYED:"delayed",LIVE:"live",MATCHED:"matched",UNMATCHED:"unmatched"};function sjt(e){return e.side==="BUY"?{assetType:"COLLATERAL"}:{assetType:e.protocol==="v2"?"CONDITIONAL-V2":"CONDITIONAL",assetId:e.tokenId}}async function ljt(e,t,r,n){let i=Date.now()+(n??d2.TIMEOUT_MS);for(;;){await new Promise(c=>setTimeout(c,d2.POLL_MS));let o=null;try{o=await e.fetchOrder({orderId:t})}catch{}let a=String(o?.status??"").toLowerCase(),s=Ufe(o?.sizeMatched),l=!!o&&!a.includes(C5.DELAYED);if(l&&s>0)return{orderId:t,status:C5.MATCHED,pending:!1,side:r.side,shares:s,usd:null,transactionHashes:[]};if(l)throw new Zy(jn.NOT_FILLED,`Delayed order ${t} ended unmatched (${a})`);if(Date.now()>=i)return{orderId:t,status:C5.DELAYED,pending:!0,side:r.side,shares:0,usd:null,transactionHashes:[]}}}m();var Ku=class extends Error{constructor(r,n,i){super(n);g(this,"code");this.name="PolymarketWithdrawError",this.code=r,i!==void 0&&(this.cause=i)}},YHe=/^0x[0-9a-fA-F]{40}$/,cjt="0x0000000000000000000000000000000000000000",JHe=e=>e.toLowerCase()===cjt?UO:e;function O5(e){let t=i=>{let o=Xo.CHAIN_ORDER.indexOf(i);return o===-1?Xo.CHAIN_ORDER.length:o},r=i=>{let o=Xo.STABLE_SYMBOLS.indexOf(i);return o===-1?Xo.STABLE_SYMBOLS.length:o},n=new Set;return e.filter(i=>!(i.chainId in lv)).filter(i=>YHe.test(i.address)&&i.address.toLowerCase()!==mu.toLowerCase()).filter(i=>{let o=`${i.chainId}:${i.address.toLowerCase()}`;return n.has(o)?!1:(n.add(o),!0)}).sort((i,o)=>t(i.chainId)-t(o.chainId)||i.chainName.localeCompare(o.chainName)||r(i.symbol.toUpperCase())-r(o.symbol.toUpperCase())||i.symbol.localeCompare(o.symbol)).map(i=>({chainId:i.chainId,chainName:i.chainName,tokenAddress:i.address,symbol:i.symbol,decimals:i.decimals,minUsd:i.minUsd}))}function R5(e,t){return typeof t=="number"&&t>0?e<BigInt(Math.round(t*10**hu)):!1}async function ujt(e,t){if(typeof e.minUsd=="number")return e.minUsd;let r=e.tokenAddress.toLowerCase();return(await t.getBridgeAssets()).find(i=>i.chainId===e.chainId&&i.address.toLowerCase()===r)?.minUsd??0}function XHe(e){return new Ku(Xo.ERROR.BELOW_MINIMUM,`Below the bridge minimum of $${e} for this destination`)}function $5(e){let t=String(e??"").trim(),r=/^(\d+)(?:\.(\d+))?$/.exec(t);if(!r)return null;let[,n,i=""]=r;if(i.length>hu)return null;let o=BigInt(n)*BigInt(10)**BigInt(hu)+BigInt(i.padEnd(hu,"0")||"0");return o>BigInt(0)?o:null}function jfe(e){let t=BigInt(10)**BigInt(hu),r=e/t,n=(e%t).toString().padStart(hu,"0").replace(/0+$/,"");return n?`${r}.${n}`:r.toString()}async function QHe(e,t=new Br){let r=$5(e.amount);if(r===null)throw new Ku(Xo.ERROR.INVALID_AMOUNT,"Enter an amount");let n=e.destination.minUsd;if(R5(r,n))throw XHe(n);let i=await t.getBridgeQuote({fromAmountBaseUnit:r.toString(),fromChainId:BO,fromTokenAddress:mu,recipientAddress:e.recipient,toChainId:e.destination.chainId,toTokenAddress:JHe(e.destination.tokenAddress)});return{estOutputBaseUnit:i.estToTokenBaseUnit,estOutputUsd:i.estOutputUsd,minReceivedUsd:i.minReceived,totalFeeUsd:i.totalImpactUsd,estTimeMs:i.estCheckoutTimeMs}}async function e3e(e){let t=e.service??new Br,r=$5(e.amount);if(r===null)throw new Ku(Xo.ERROR.INVALID_AMOUNT,"Enter an amount");if(!YHe.test(e.recipient))throw new Ku(Xo.ERROR.FAILED,`Invalid recipient ${e.recipient}`);try{let n=await ujt(e.destination,t);if(R5(r,n))throw XHe(n);let i=await CR(e.wallet);if(i<r)throw new Ku(Xo.ERROR.INSUFFICIENT_BALANCE,`Cash ${jfe(i)} is below ${e.amount}`);let o=await sP(e),a=await t.createWithdrawalAddresses({wallet:e.wallet,toChainId:e.destination.chainId,toTokenAddress:JHe(e.destination.tokenAddress),recipient:e.recipient}),l=await(await o.transferErc20({tokenAddress:mu,recipientAddress:a.evm,amount:r})).wait();return{bridgeAddress:a.evm,transactionHash:typeof l?.transactionHash=="string"?l.transactionHash:null,amountBaseUnit:r.toString()}}catch(n){throw qfe(n)}}function qfe(e){if(e instanceof Ku)return e;let t=e?.message||String(e),r=lP(e)?Xo.ERROR.CANCELLED:/insufficient|exceeds balance|not enough balance/i.test(t)?Xo.ERROR.INSUFFICIENT_BALANCE:Xo.ERROR.FAILED;return new Ku(r,t,e)}m();var Gy=class extends Error{constructor(r,n,i){super(n);g(this,"code");this.name="PolymarketRedeemError",this.code=r,i!==void 0&&(this.cause=i)}};async function t3e(e){let t=e.service??new Br;if(!/^0x[0-9a-fA-F]{64}$/.test(e.conditionId))throw new Gy(cv.ERROR.FAILED,`Invalid condition id ${e.conditionId}`);try{if((await t.getPositions(e.wallet,cv.POSITIONS_READ_LIMIT,{fresh:!0})).filter(s=>s.conditionId.toLowerCase()===e.conditionId.toLowerCase()&&s.redeemable&&s.shares>0).length===0)throw new Gy(cv.ERROR.NOTHING_TO_CLAIM,"Nothing left to redeem in this market");let a=await(await(await sP(e)).redeemPositions({conditionId:e.conditionId})).wait();return{transactionHash:typeof a?.transactionHash=="string"?a.transactionHash:null}}catch(r){if(r instanceof Gy)throw r;let n=r?.message||String(r);throw new Gy(lP(r)?cv.ERROR.CANCELLED:cv.ERROR.FAILED,n,r)}}m();m();var djt=6,pjt=.6,fjt=.1,mjt=200,hjt=8,y0=new Map;function r3e(e,t){let r=_n(e);if(r.length<hjt||!t)return;let n=y0.get(r)??new Set;n.add(t),y0.delete(r),y0.set(r,n),y0.size>mjt&&y0.delete(y0.keys().next().value)}function gjt(e,t){let r=_n(e),n=_n(t),i=null;for(let[o,a]of y0)(r===o||n!==""&&` ${n} `.includes(` ${o} `))&&(!i||o.length>i.title.length)&&(i={title:o,slugs:a});return i&&i.slugs.size===1?[...i.slugs][0]:null}async function N5(e,t,r){let n=KO(t)??WO(t)?.eventSlug??KO(r)??WO(r)?.eventSlug??gjt(t,r)??null;if(n){let c=await e.getEventBySlug(n);return c?{kind:"event",event:c}:{kind:"not_found",query:t||n}}if(!t)return{kind:"unnamed"};let i=(await e.searchEvents(t,djt)).filter(c=>c.markets.some(u=>u.open));if(i.length===0)return{kind:"not_found",query:t};let o=i.map(c=>({event:c,match:Ffe(t,c.title)})).sort((c,u)=>u.match.score-c.match.score),[a,s]=o;return i.length===1||a.match.exact||a.match.recall>=pjt&&(!s||a.match.score-s.match.score>=fjt)?{kind:"event",event:a.event}:{kind:"ambiguous",query:t,candidates:i}}function Ffe(e,t){let r=c=>_n(c).split(" ").filter(u=>u.length>1),n=r(e),i=r(t);if(n.length===0||i.length===0)return{recall:0,precision:0,score:0,exact:!1};let o=new Set(i),a=new Set(n),s=n.filter(c=>o.has(c)).length/n.length,l=i.filter(c=>a.has(c)).length/i.length;return{recall:s,precision:l,score:s*.7+l*.3,exact:n.join(" ")===i.join(" ")}}var D5="{market}",yjt=`Show me details of the prediction market ${D5}`,Wy=[{name:"detail_button_label",type:"string",description:`Label for the "Details" button rendered on EVERY event card, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it. Just the word "Details" translated: English "Details", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the event \u2014 the button sits on that event's own card. One or two words.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this prediction market in detail" request IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a card's button is tapped. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the event title. English: "Show me details of the prediction market {market}". Vietnamese: "Xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng d\u1EF1 \u0111o\xE1n {market}". Always include {market}.`,required:!1}],n3e=e=>typeof e=="string"?e.trim():"";function zfe(e){return n3e(e.detail_button_label).replace(D5,"").replace(/\s+/g," ").trim()}function Hfe(e,t,r){r3e(e,t);let n=n3e(r.detail_prompt_template);return(n.includes(D5)?n:yjt).split(D5).join(e).replace(/\s+/g," ").trim()}function bjt(e){return Math.round(e*1e3)/10}function Ph(e,t){let r=10**t;return Math.trunc(Number((e*r).toFixed(6)))/r}function Ky(e){return Ph(e,2)}function M5(e){return Ph(e,6)}function b0(e){return Math.round(e)}function Vfe(e){return e.map(t=>({label:t.label,chancePercent:bjt(t.chance),...t.shortLabel?{shortLabel:t.shortLabel}:{}}))}function cP(e,t){let r=y2(e);return r?{title:e.title,slug:e.slug,url:e.url,image:e.image,endDate:e.endDate,volumeUsd:b0(e.volume),volume24hUsd:b0(e.volume24h),kind:r.kind,outcomes:Vfe(r.outcomes),openMarketCount:r.openMarketCount,detailPrompt:Hfe(e.title,e.slug,t),detailLabel:zfe(t),upDown:e.upDown}:null}var Yy='A chance shown here is the PRICE traders currently pay for that outcome \u2014 the market-implied probability \u2014 never a forecast of yours: phrase it as "the market prices X at N%", never "X will win" or "X is likely". Do NOT give your own opinion or analysis of the underlying event (an election, a game, a policy decision), do NOT tell the user which side to buy or how much to stake, and never state a chance, price or volume the tool did not return. Prediction markets can lose the whole stake; this is information, not advice. Do NOT mention tool names.';var o3e=5,Zfe=20,_jt=3,a3e=Object.keys(FO),i3e={trending:"ordered as polymarket.com's homepage Trending view: its featured events, live or upcoming games and the live 5-minute Bitcoin market first, then by 24-hour trading volume",new:"ordered by creation date, newest first",volume:"ordered by all-time trading volume, largest first",liquidity:"ordered by liquidity, deepest first",competitive:"ordered by how close the odds are (the most contested first)",ending_soon:"ordered by end date, the soonest-ending first"},uP=class extends Ce{constructor(r){super();g(this,"name","get-prediction-markets");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'BROWSE or SEARCH Polymarket prediction markets \u2014 real-world questions people trade on (elections, sports games, crypto prices, economics, geopolitics, tech, weather\u2026). Returns event cards with the current market-implied odds of each, volume and end date, plus a "Details" button per event. Use for: "trending predictions", "hot Polymarket markets", "sports prediction markets", "d\u1EF1 \u0111o\xE1n v\u1EC1 crypto", "new markets", "markets ending soon", "most contested markets", "is there a market on <topic>?", "odds on the next Fed decision", "Polymarket odds for the election". Pass `query` when the user names a TOPIC or event (a person, team, coin, event); pass `category` when they name a broad section; pass neither for the general feed. Do NOT use for: ONE event in full (all its options, rules, deadline) \u2192 get-prediction-market-detail; the user\'s own positions \u2192 get-prediction-portfolio; their trade history \u2192 get-prediction-activity.');g(this,"parameters",[{name:"query",type:"string",description:`Search text when the user names a topic, event, person, team or coin ("bitcoin", "world cup", "Fed rates", "Lakers"). Write it in ENGLISH keywords \u2014 market titles are English \u2014 translating the user's words ("b\u1EA7u c\u1EED M\u1EF9" \u2192 "US election"). OMIT for a general or category feed.`,required:!1},{name:"category",type:"string",description:`Category to scope a feed to. One of: ${Kg.map(r=>r.key).join(", ")}. Pass the user's word as-is if unsure \u2014 it is matched for you, and an unknown one is reported back. OMIT when the user named none, and when \`query\` is set.`,required:!1},{name:"sort",type:"string",description:`Feed order: ${a3e.map(r=>`"${r}" (${i3e[r]})`).join(", ")}. Default "trending". Ignored when \`query\` is set (search results are ordered by relevance).`,required:!1},{name:"limit",type:"number",description:`How many events, 1-${Zfe}. Default ${o3e}. Raise only when the user asks for more.`,required:!1},...Wy]);g(this,"service");this.service=new Br(r)}async run(r){let n=typeof r.query=="string"?r.query.trim():"",i=wjt(r.limit),o=typeof r.category=="string"?r.category.trim():"",a=n?null:b2(o);if(!n&&o&&!a)return{requestedCategory:o,categoriesAvailable:Kg.map(h=>h.label),_instructions:`"${o}" is not a prediction-market category here. In the user's language, say so in one short sentence and name the categories in \`categoriesAvailable\`, offering to show one of them or to search a specific topic. Do NOT invent markets. Do NOT mention tool names.`};let s=vjt(r.sort),c=(n?await this.service.searchEvents(n,Math.min(Zfe*2,i*2+5)):await this.service.listEvents({sort:s,tagId:a?.tagId,limit:i*_jt})).map(h=>cP(h,r)).filter(h=>h!==null).slice(0,i);if(c.length===0)return{query:n||null,category:a?.label??null,eventCount:0,_instructions:(n?`No open prediction market matches "${n}" right now. `:"No open prediction markets could be loaded for this view right now. ")+"Say so briefly in the user's language and offer to show the trending markets or another topic. Do NOT invent markets or odds. Do NOT mention tool names."};let u={sort:n?"relevance":s,category:a?.label??null,query:n||null,events:c},d={component:"PredictionMarketList",props:u},p=n?`prediction markets matching "${n}", most relevant first`:`${a?`${a.label} `:""}prediction markets ${i3e[s]}`;return{ui:d,query:n||null,category:a?.label??null,sortedBy:u.sort,eventCount:c.length,eventTitles:c.map(h=>h.title),_instructions:[`These are ${p}. They are ALREADY RENDERED as cards below your reply, each with its title, the`,'current odds, volume, end date and a "Details" button. Do NOT write the list out: no numbered or',"bullet list, no per-event lines, no odds, no links, no mention of the buttons.",`Write your reply in TWO parts separated by a line containing exactly ${pc} and nothing`,"else \u2014 include that marker EXACTLY ONCE, on its own line; do not translate, style or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: ONE short sentence noting that the odds are live market prices that move","constantly and that this is information, not betting advice \u2014 in the user's language.",Yy].join(" ")}}};function vjt(e){let t=typeof e=="string"?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):"";return a3e.includes(t)?t:"trending"}function wjt(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?o3e:Math.min(Math.floor(t),Zfe)}m();m();function dP(e){return!e.open||e.clobTokenIds.length!==e.outcomes.length||e.clobTokenIds.length<2?null:{question:e.question,conditionId:e.conditionId,negRisk:e.negRisk,protocol:e.protocol,fee:e.fee,outcomes:e.outcomes.map((t,r)=>({label:t.label,tokenId:e.clobTokenIds[r],...t.shortLabel?{shortLabel:t.shortLabel}:{}}))}}function s3e(e,t,r){let n=e.markets.filter(c=>c.open&&dP(c));if(n.length===0)return null;if(r?.open&&dP(r)&&!t)return r;if(n.length===1)return n[0];if(!t)return null;let i=_n(t),o=n.find(c=>_n(c.label)===i||_n(c.question)===i);if(o)return o;let a=n.map(c=>({m:c,match:Ffe(t,c.label||c.question)})).sort((c,u)=>u.match.score-c.match.score),[s,l]=a;return s.match.recall>=.6&&(!l||s.match.score>l.match.score)?s.m:null}function l3e(e,t){if(!t)return-1;let r=_n(t),i={co:"yes",khong:"no"}[r]??r,o=e.outcomes.map(s=>_n(s.label)),a=o.indexOf(i);return a>=0?a:o.findIndex(s=>s.includes(i)||i.includes(s))}function L5(e){let t=typeof e=="string"?e.trim().replace(",","."):typeof e=="number"?String(e):"";return/^\d+(\.\d+)?$/.test(t)&&Number(t)>0?t:null}function U5(e){return typeof e=="string"&&/^(all|max|everything|het|tat ca|toan bo)$/.test(_n(e))}var Sjt=15,c3e=600,kjt=5,pP=class extends Ce{constructor(r){super();g(this,"name","get-prediction-market-detail");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'Show ONE prediction market (Polymarket event) in full: every open option with its current market-implied odds and 24 h change, volume, liquidity, end date and how it resolves. Use when the user singles out one event \u2014 "tell me more about the Fed October decision market", "odds of each candidate in the Brazil election", "how does this market resolve", a pasted polymarket.com link, or a tapped "Details" button (its message names the title of an event card already shown). Do NOT use for browsing many events or a topic in general \u2192 get-prediction-markets. Do NOT use when the user wants to buy, sell or bet (mua / b\xE1n / \u0111\u1EB7t c\u01B0\u1EE3c) \u2014 even with a hint \u2192 open-prediction-trade.');g(this,"parameters",[{name:"market",type:"string",description:'Which event. When the message names the title of an event card already shown (a "Details" tap), pass that title VERBATIM, untranslated. When it carries a "(prediction: <slug>)" hint, pass that hint VERBATIM (with the parentheses). When it carries a polymarket.com link, pass the link. Otherwise pass the event as the user named it, in ENGLISH keywords ("Fed decision October", "Brazil presidential election").',required:!0},...Wy]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=typeof r.market=="string"?r.market.trim():"",o=await N5(this.service,i,n?.query??"");switch(o.kind){case"event":return this.detail(o.event);case"ambiguous":return this.ambiguous(o.query,o.candidates,r);case"not_found":return this.notFound(o.query);default:return{_instructions:"No event was named. Ask the user, in their language, which prediction market they want to see. Do NOT mention tool names."}}}detail(r){let n=r.markets.filter(s=>s.open),i=Gfe(r),o=i.markets,a={component:"PredictionMarketDetail",props:i};return n.length===0?{ui:a,title:r.title,open:!1,resolvedOutcomes:Tjt(r),_instructions:"This prediction market is CLOSED \u2014 no longer open for trading. In the user's language, say so in one or two sentences; if `resolvedOutcomes` lists winners, state them as how the market resolved. "+Yy}:{ui:a,title:r.title,open:!0,endDate:r.endDate,volumeUsd:i.volumeUsd,mutuallyExclusive:r.negRisk,leadingOptions:o.filter(s=>s.outcomes.length>0).slice(0,kjt).map(s=>({option:s.label,outcomes:s.outcomes.map(l=>`${l.label} ${l.chancePercent}%`).join(" / ")})),openMarketCount:n.length,rules:u3e(r.description,c3e),_instructions:["The event is ALREADY RENDERED as a card below your reply, listing every open option with its odds,","volume, end date and rules. Write at most THREE short sentences: what the question is, the leading","option(s) from `leadingOptions` as market prices, and when it ends. Do NOT list every option and do NOT","repeat the rules unless the user asked how it resolves (then summarize `rules` in one sentence).",Yy].join(" ")}}ambiguous(r,n,i){let o=n.map(s=>cP(s,i)).filter(s=>s!==null);return o.length===0?this.notFound(r):{ui:{component:"PredictionMarketList",props:{sort:"relevance",category:null,query:r,events:o}},query:r,candidateCount:o.length,candidateTitles:o.map(s=>s.title),_instructions:[`"${r}" matches several prediction markets, so none was opened. They are ALREADY RENDERED as cards`,'below your reply, each with a "Details" button. Write your reply in TWO parts separated by a line',`containing exactly ${pc} (exactly once, on its own line): PART ONE \u2014 one short sentence`,"saying several markets match and asking which one they mean; PART TWO \u2014 leave it empty or one short","sentence. Do NOT list the markets in text.",Yy].join(" ")}}notFound(r){return{query:r,found:!1,_instructions:`No open prediction market matching "${r}" was found. Say so briefly in the user's language and offer to search a related topic or show the trending markets. Do NOT invent a market or odds. Do NOT mention tool names.`}}};function Gfe(e){let t=e.markets.filter(o=>o.open),r=uv(e),i=(r?r.open?[r]:[]:t.slice(0,Sjt)).map(xjt(e));return{title:e.title,slug:e.slug,url:e.url,image:e.image,description:u3e(e.description,c3e),resolutionSource:e.resolutionSource,endDate:e.endDate,volumeUsd:b0(e.volume),volume24hUsd:b0(e.volume24h),liquidityUsd:b0(e.liquidity),negRisk:e.negRisk,markets:i,hiddenMarketCount:Math.max(0,t.length-i.length)}}function xjt(e){let t=e.markets.length===1;return r=>({label:t?e.title:r.label,outcomes:r.priced?Vfe(r.outcomes):[],volumeUsd:b0(r.volume),oneDayChangePoints:r.priced&&r.oneDayPriceChange!==null?Math.round(r.oneDayPriceChange*1e3)/10:null,trade:dP(r)})}function Tjt(e){return e.markets.filter(t=>!t.open).map(t=>({market:t.label,winner:t.outcomes.find(r=>r.chance>=.999)?.label??""})).filter(t=>t.winner).slice(0,5)}function u3e(e,t){if(e.length<=t)return e;let r=e.slice(0,t),n=r.lastIndexOf(" ");return`${(n>t*.6?r.slice(0,n):r).trimEnd()}\u2026`}m();m();m();function Sp(e,t){return{component:"PredictionSetupCard",props:{signer:e.owner,wallet:e.address,walletKind:e.kind==="safe"?"safe":"deposit-wallet",deployed:e.deployed,approved:e.deployed?t?.isFullyApproved??!1:null}}}var Jy="This wallet has no Polymarket account yet, so there is nothing to show. A card to set one up is ALREADY RENDERED below your reply. In ONE short sentence in the user's language, say there is no Polymarket account yet and that they can create it with the card below. Do NOT invent positions, balances or steps, and do NOT mention tool names.";var B5={name:"address",type:"string",description:"EVM address (0x\u2026) to look up \u2014 the user's wallet or a Polymarket account wallet. Set it ONLY when the user wrote an address; otherwise OMIT it and the connected wallet is used.",required:!1};function d3e(e){return`${Wg}/profile/${e}`}function j5(e){return e?`${Wg}/event/${e}`:null}async function q5(e,t,r){let n=Un(t.address,r);if(!mc(n))return{ok:!1,result:{address:n,_instructions:`"${n}" is not a valid EVM address. Ask the user, in their language, for a valid 0x address. Do NOT mention tool names.`}};let i=await e.resolveAccount(n),o=!!r?.walletAddress&&r.walletAddress.toLowerCase()===n.toLowerCase();return!i.deployed&&o&&i.kind!=="profile"?{ok:!1,result:{ui:Sp(i,null),hasPolymarketAccount:!1,_instructions:Jy}}:i.deployed?{ok:!0,account:i}:{ok:!1,result:{address:n,hasPolymarketAccount:!1,_instructions:"This wallet has no Polymarket account yet \u2014 nothing has been deposited or traded on Polymarket from it. Tell the user so in one short sentence, in their language, and offer to show the trending prediction markets instead. Do NOT invent positions or balances. Do NOT mention tool names."}}}var p3e=10,f3e=30,Ajt=200,fP=class extends Ce{constructor(r){super();g(this,"name","get-prediction-portfolio");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",`The user's Polymarket holdings: cash available to trade, the value and profit/loss of every open position, and winnings ready to claim. Use for "my Polymarket positions", "my bets", "how much have I won/lost on Polymarket", "v\u1ECB th\u1EBF d\u1EF1 \u0111o\xE1n c\u1EE7a t\xF4i", "Polymarket balance". Works for the connected wallet or an address the user gives. Do NOT use for past trades \u2192 get-prediction-activity; for markets to browse \u2192 get-prediction-markets.`);g(this,"parameters",[B5,{name:"limit",type:"number",description:`How many positions to list, 1-${f3e}. Default ${p3e}.`,required:!1},...Wy]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=await q5(this.service,r,n);if(!i.ok)return i.result;let o=i.account.address,a=Ijt(r.limit),[s,l,c]=await Promise.all([this.service.getPositions(o,Ajt),this.service.getPositionsValue(o),this.service.getCash(o).catch(()=>null)]),u=s.filter(Pjt),d=u.filter(v=>v.redeemable),p=Ky(d.reduce((v,S)=>v+S.currentValue,0)),h=u.slice(0,a).map(v=>Ejt(v,r)),y={wallet:o,profileUrl:d3e(o),cashUsd:c===null?null:M5(c),positionsValueUsd:Ky(l),claimableUsd:p,positions:h,totalPositions:u.length},b={component:"PredictionPortfolio",props:y},_=Ky(u.reduce((v,S)=>v+S.cashPnl,0));return{ui:b,wallet:o,cashUsd:y.cashUsd,positionsValueUsd:y.positionsValueUsd,claimableUsd:p,openPositionCount:u.length-d.length,claimablePositionCount:d.length,unrealizedPnlUsd:_,positionsShown:h.length,positions:h.map(v=>({market:v.title,outcome:v.outcome,valueUsd:v.valueUsd,pnlUsd:v.pnlUsd})),_instructions:["The portfolio is ALREADY RENDERED as a card below your reply: cash, positions value, claimable winnings","and each position with its value and profit/loss. Write at most TWO short sentences in the user's","language: the headline numbers (cash, positions value, and claimable winnings if above 0) in USD exactly","as given, and \u2014 only if there are no positions \u2014 that the account currently holds none. End with a period,","never a colon. Do NOT list the positions in text (`positions` is there only so you never state anything","that is not in it). Never state a figure that is not in this result.",u.length===0?"":"Do NOT judge the positions or suggest selling, holding or buying anything.","Do NOT mention tool names."].filter(Boolean).join(" ")}}};function Pjt(e){return e.shares<=0?!1:!e.redeemable||e.currentValue>0}function Ejt(e,t){return{title:e.title,outcome:e.outcome,url:j5(e.eventSlug),icon:e.icon,shares:Ph(e.shares,2),avgPrice:Ph(e.avgPrice,4),curPrice:Ph(e.curPrice,4),valueUsd:Ky(e.currentValue),pnlUsd:Ky(e.cashPnl),pnlPercent:Math.round(e.percentPnl*10)/10,claimable:e.redeemable&&e.currentValue>0,endDate:e.endDate,detailPrompt:e.eventSlug?Hfe(e.title,e.eventSlug,t):"",detailLabel:zfe(t),tokenId:e.asset,conditionId:e.conditionId,outcomeIndex:e.outcomeIndex,oppositeOutcome:e.oppositeOutcome,oppositeTokenId:e.oppositeAsset}}function Ijt(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?p3e:Math.min(Math.floor(t),f3e)}m();var m3e=10,h3e=30,Cjt="https://polygonscan.com/tx/",mP=class extends Ce{constructor(r){super();g(this,"name","get-prediction-activity");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",`The user's recent Polymarket history: each buy and sell (outcome, shares, price, amount), claimed winnings and rewards, newest first. Use for "my Polymarket trades", "what did I bet on", "l\u1ECBch s\u1EED giao d\u1ECBch Polymarket", "my last prediction trades". Works for the connected wallet or an address the user gives. Do NOT use for current holdings \u2192 get-prediction-portfolio.`);g(this,"parameters",[B5,{name:"limit",type:"number",description:`How many entries, 1-${h3e}. Default ${m3e}.`,required:!1}]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=await q5(this.service,r,n);if(!i.ok)return i.result;let o=i.account.address,a=Ojt(r.limit),s=(await this.service.getActivity(o,a)).map(u=>({type:u.type,side:u.side,title:u.title,outcome:u.outcome,url:j5(u.eventSlug),shares:Ph(u.shares,2),usd:Ky(u.usd),price:Ph(u.price,4),timestamp:u.timestamp,txUrl:/^0x[0-9a-fA-F]{64}$/.test(u.transactionHash)?`${Cjt}${u.transactionHash}`:null}));return s.length===0?{wallet:o,entryCount:0,_instructions:"This Polymarket account has no trading history yet. Say so in one short sentence in the user's language. Do NOT invent trades. Do NOT mention tool names."}:{ui:{component:"PredictionActivity",props:{wallet:o,items:s},completeList:!0},wallet:o,entryCount:s.length,entries:s.map(u=>({type:u.type,side:u.side,market:u.title,outcome:u.outcome,usd:u.usd,date:u.timestamp>0?new Date(u.timestamp*1e3).toISOString().slice(0,10):null})),_instructions:["The history is ALREADY RENDERED as a list below your reply \u2014 every entry with its type, outcome, shares,",'price, amount and time \u2014 so a request to "show" or "list" the trades is ALREADY fully answered by it;',"writing the entries out again would show each one twice.",`Write your reply in TWO parts separated by a line containing exactly ${pc} (exactly once, on`,"its own line). PART ONE: ONE short sentence ending with a period (never a colon) saying this is their","recent Polymarket activity and how many entries are shown. PART TWO: EMPTY \u2014 write nothing at all after the","marker. No bullet or numbered list anywhere, no per-entry lines: `entries` is given ONLY so you never","state anything that is not in it. Do NOT judge the trades. Do NOT mention tool names."].join(" ")}}};function Ojt(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?m3e:Math.min(Math.floor(t),h3e)}m();var hP=class extends Ce{constructor(r){super();g(this,"name","open-prediction-setup");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",`Open the card that SETS UP the user's Polymarket account so they can trade prediction markets: one button that enables trading, creates their Polymarket wallet and grants the trading approvals \u2014 gasless, signed once from their own wallet. Use for "create a Polymarket account", "set up Polymarket", "enable trading on Polymarket", "t\u1EA1o t\xE0i kho\u1EA3n Polymarket", "k\xEDch ho\u1EA1t giao d\u1ECBch d\u1EF1 \u0111o\xE1n", or when the user wants to start betting / trading and has no account. Needs the connected wallet. Do NOT use to deposit funds \u2192 open-prediction-deposit.`);g(this,"parameters",[]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=n?.walletAddress?.trim();if(!i||!mc(i))return{error:"wallet_not_connected",_instructions:"Setting up a Polymarket account needs the user's own connected wallet, which signs for it. Ask them, in their language, to connect a wallet first. Do NOT mention tool names."};let{account:o,approvals:a}=await wp(i,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, not a wallet that can sign for one, so it cannot be set up here. Say so briefly in the user's language. Do NOT mention tool names."};let s=Sp(o,a),l=o.deployed&&a?.isFullyApproved===!0;return{ui:s,walletDeployed:o.deployed,approvalsComplete:a?.isFullyApproved??!1,_instructions:["The Polymarket account-setup card is ALREADY RENDERED below your reply; it runs the setup itself when the","user taps its button. Write ONE or TWO short sentences in the user's language:",l?"the wallet is already created and approved on-chain, so the card only needs to confirm trading access \u2014":"what the button does \u2014 enables trading, creates their Polymarket wallet and grants the approvals in one go,","with no gas fees, signed from their own wallet (an NFC card is tapped once).","Do NOT claim the account is set up, do NOT list technical steps or contract names, and do NOT mention tool","names."].join(" ")}}};m();var gP=class extends Ce{constructor(r){super();g(this,"name","open-prediction-deposit");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'Open the card that DEPOSITS funds into the user\'s Polymarket account (to trade prediction markets): send a stablecoin they hold (USDC, USDT, DAI\u2026 on Ethereum, Base, Polygon, Arbitrum, BSC\u2026) straight from their wallet, or get the EVM deposit address + QR code for another EVM wallet or exchange (EVM chains only). Use for "deposit to Polymarket", "fund my Polymarket", "n\u1EA1p ti\u1EC1n v\xE0o Polymarket", "top up my prediction account", "n\u1EA1p 50 USDC v\xE0o Polymarket". Needs the connected wallet; if the account is not set up yet the setup card is shown instead. Pass `amount` ONLY when the user named one.');g(this,"parameters",[{name:"amount",type:"string",description:`Amount to pre-fill, in the stablecoin's own units as a plain decimal ("50", "12.5"). ONLY when the user named an amount; never invent or convert one.`,required:!1}]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=n?.walletAddress?.trim();if(!i||!mc(i))return{error:"wallet_not_connected",_instructions:"Depositing into Polymarket needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let{account:o,approvals:a}=await wp(i,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, so deposits are made to it directly from another wallet. Say so briefly in the user's language. Do NOT mention tool names."};if(!o.deployed)return{ui:Sp(o,a),hasPolymarketAccount:!1,_instructions:Jy};let[s,l]=await Promise.all([this.service.getBridgeAssets(),this.service.getDepositAddresses(o.address)]),c=await P5(i,s),u=typeof r.amount=="string"&&/^\d+(\.\d+)?$/.test(r.amount.trim())?r.amount.trim():null,p={component:"PredictionDepositCard",props:{wallet:o.address,owner:i,depositAddress:l.evm,options:c,assets:E5(s),networks:Rjt(s,l),prefillAmount:u}},h=c.length>0?Math.min(...c.map(y=>y.minUsd)):null;return{ui:p,walletHasDepositableStablecoins:c.length>0,depositableFromWallet:c.slice(0,5).map(y=>`${y.symbol} on ${y.chainName}`),minimumDepositUsd:h,_instructions:["The deposit card is ALREADY RENDERED below your reply: it opens the deposit screen, which sends a stablecoin","from the user's wallet, or shows the EVM deposit address and QR code for another EVM wallet or exchange","(EVM chains only \u2014 Ethereum, Base, Polygon, Arbitrum, BNB Chain\u2026). Write ONE or TWO short sentences in the","user's language:",c.length>0?"they can deposit straight from their wallet with the card (pick a token and amount),":"their wallet holds no stablecoin the card can send, so they can deposit from another EVM wallet or exchange using the address and QR code,","funds arrive as cash in their Polymarket account after the bridge processes them (usually a few minutes),",h!==null?`and deposits below about $${h} may not be credited.`:"and very small deposits may not be credited.","Do NOT claim a deposit was made, do NOT repeat addresses, and do NOT mention tool names."].join(" ")}}};function Rjt(e,t){let r={evm:{chains:new Set,minUsd:1/0},svm:{chains:new Set,minUsd:1/0},btc:{chains:new Set,minUsd:1/0},tron:{chains:new Set,minUsd:1/0}};for(let n of e){let i=lv[n.chainId];if(i===null)continue;let o=r[i??"evm"];o.chains.add(n.chainName),o.minUsd=Math.min(o.minUsd,n.minUsd)}return Object.keys(r).filter(n=>t[n]&&r[n].chains.size>0).map(n=>({family:n,address:t[n],chains:[...r[n].chains].sort(),minUsd:Number.isFinite(r[n].minUsd)?r[n].minUsd:0}))}m();var $jt=100,yP=class extends Ce{constructor(r){super();g(this,"name","open-prediction-trade");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'Prepare a BUY or SELL of shares in a prediction market (Polymarket) for the user to review and confirm in the order drawer, which shows the live price. Use for "bet $10 on Yes", "buy Yes on the Fed market", "mua 20$ c\u1EEDa Lula", "sell my Real Madrid shares", "b\xE1n h\u1EBFt c\u1ED5 ph\u1EA7n Trump". Market orders only. Needs the connected wallet with a Polymarket account (otherwise the setup card is shown). Do NOT use to browse or see odds \u2192 get-prediction-markets / get-prediction-market-detail.');g(this,"parameters",[{name:"market",type:"string",description:'Which event. A "(prediction: <slug>)" hint, a polymarket.com link or the title of an event card already shown in the message \u2192 pass it VERBATIM. Otherwise the event as the user named it, in ENGLISH keywords ("Fed decision October").',required:!0},{name:"option",type:"string",description:'For an event with several options (candidates, price levels, dates): the one the user picked, as named ("Lula", "85,000", "No change"). Omit when the user did not name one.',required:!1},{name:"outcome",type:"string",description:'The side the user picked: "Yes", "No", or a team / name. Omit when not said.',required:!1},{name:"side",type:"string",description:'"buy" (bet on / mua) or "sell" (sell shares / b\xE1n).',required:!0},{name:"amount",type:"string",description:'ONLY when the user named it. BUY: USD to spend as a plain decimal ("10"). SELL: number of shares, or "all" to sell everything. Never invent or convert one.',required:!1},...Wy]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=n?.walletAddress?.trim();if(!i||!mc(i))return{error:"wallet_not_connected",_instructions:"Trading prediction markets needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let o=["sell","ban"].includes(_n(String(r.side??"")))?"SELL":"BUY",{account:a,approvals:s}=await wp(i,this.service);if(a.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, which cannot sign orders here. Say so briefly in the user's language. Do NOT mention tool names."};if(!a.deployed||s?.isFullyApproved!==!0)return{ui:Sp(a,s),hasPolymarketAccount:a.deployed,_instructions:a.deployed?"The Polymarket account is not fully set up for trading yet. A card that finishes the setup is ALREADY RENDERED below your reply. In ONE short sentence in the user's language, say the account needs to finish setup before trading. Do NOT mention tool names.":Jy};let l=typeof r.market=="string"?r.market.trim():"",c=await N5(this.service,l,n?.query??"");if(c.kind==="unnamed"||c.kind==="not_found")return{found:!1,_instructions:c.kind==="unnamed"?"No market was named. Ask the user, in their language, which prediction market they want to trade.":`No open prediction market matching "${c.query}" was found. Say so briefly in the user's language and offer to search a related topic. Do NOT invent a market. Do NOT mention tool names.`};if(c.kind==="ambiguous"){let T=c.candidates.map($=>cP($,r)).filter($=>!!$);return{ui:{component:"PredictionMarketList",props:{sort:"relevance",category:null,query:c.query,events:T}},candidateCount:T.length,_instructions:[`"${c.query}" matches several prediction markets, so no order was prepared. They are ALREADY`,"RENDERED as cards below. Write your reply in TWO parts separated by a line containing exactly",`${pc} (once, on its own line): PART ONE \u2014 one short sentence asking which market they`,"mean; PART TWO \u2014 empty. Do NOT list the markets in text."].join(" ")}}let u=c.event,d=typeof r.option=="string"?r.option.trim():"",p=s3e(u,d,uv(u)??null);if(!p){let T=Gfe(u),O=T.markets.some($=>$.trade);return{ui:{component:"PredictionMarketDetail",props:T},title:u.title,open:O,_instructions:O?"This event has several options and the order needs ONE. The event is ALREADY RENDERED below with a buy button on every option. In ONE short sentence in the user's language, ask them to pick the option on the card. Do NOT claim an order was placed. Do NOT mention tool names.":"This prediction market is closed \u2014 it can no longer be traded. Say so in one sentence in the user's language. Do NOT mention tool names."}}let h=dP(p),y=r.amount,b=o==="SELL"&&U5(y),_=l3e(p,typeof r.outcome=="string"?r.outcome:""),v=null;if(o==="SELL"){let T=(await this.service.getPositions(a.address,$jt)).filter($=>$.conditionId===p.conditionId&&$.shares>0&&!$.redeemable),O=(_>=0?T.find($=>$.outcomeIndex===_):void 0)??(T.length===1?T[0]:void 0);if(!O)return{holdsShares:!1,market:p.question,_instructions:T.length>1?"The user holds several outcomes of this market. Ask, in their language, which one to sell. Do NOT mention tool names.":"The user holds no shares of this market's chosen outcome, so there is nothing to sell. Say so in one sentence in the user's language. Do NOT mention tool names."};_=O.outcomeIndex,v=Math.floor(O.shares*100)/100}let S={eventTitle:u.title,eventSlug:u.slug,url:u.url,image:u.image,marketLabel:u.markets.length===1?u.title:p.label,market:h,outcomeIndex:Math.max(0,_),side:o,amount:b?null:L5(y),sellAll:b,signer:i,wallet:a.address,endDate:p.endDate??u.endDate},w={component:"PredictionTradeCard",props:S},k=h.outcomes[S.outcomeIndex].label;return{ui:w,side:o,market:p.question,outcome:k,outcomeWasNamed:_>=0,amount:S.amount,sellAll:b,heldShares:v,_instructions:["The order is ALREADY RENDERED below your reply as a card; it opens the order screen with the LIVE price,","where the user reviews and confirms (one signature / NFC tap). In ONE or TWO short sentences in the",`user's language, say what is prepared (${o==="BUY"?"buying":"selling"} "${k}" in`,`"${p.question}"${S.amount?`, ${o==="BUY"?`$${S.amount}`:`${S.amount} shares`}`:""}),`,_>=0?"":"that they can switch the outcome on the card,","and that they confirm it there. Do NOT claim the order is placed or filled, do NOT state a price (it is","live on the card), do NOT give betting advice, and do NOT mention tool names.",Yy].filter(Boolean).join(" ")}}};m();var bP=class extends Ce{constructor(r){super();g(this,"name","open-prediction-withdraw");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'Open the card that WITHDRAWS cash from the user\'s Polymarket account back to their own wallet, as USDC or USDT on the chain they choose (Polygon, Base, Arbitrum, Ethereum, Optimism, BNB Chain\u2026). Use for "withdraw from Polymarket", "cash out my Polymarket", "r\xFAt ti\u1EC1n kh\u1ECFi Polymarket", "r\xFAt 20 USDC v\u1EC1 v\xED", "withdraw everything to Base". Needs the connected wallet; if the account is not set up yet the setup card is shown instead. Pass `amount` ONLY when the user named one ("all" for everything), and `chain` / `token` ONLY when named. Selling a position first is open-prediction-trade, not this.');g(this,"parameters",[{name:"amount",type:"string",description:'USD amount to pre-fill as a plain decimal ("20", "12.5"), or "all" for the whole cash balance. ONLY when the user named one; never invent or convert one.',required:!1},{name:"chain",type:"string",description:'Destination chain the user named, in English ("Base", "Polygon", "Arbitrum", "Ethereum", "BNB Chain"). OMIT when not named \u2014 the card lets them pick.',required:!1},{name:"token",type:"string",description:'Destination token symbol the user named ("USDC", "USDT", "ETH", \u2026). OMIT when not named.',required:!1}]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=n?.walletAddress?.trim();if(!i||!mc(i))return{error:"wallet_not_connected",_instructions:"Withdrawing from Polymarket needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let{account:o,approvals:a}=await wp(i,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, which cannot sign a withdrawal here; withdrawals are made from the wallet that owns it. Say so briefly in the user's language. Do NOT mention tool names."};if(!o.deployed)return{ui:Sp(o,a),hasPolymarketAccount:!1,_instructions:Jy};let[s,l]=await Promise.all([this.service.getBridgeAssets(),iT(o.address).catch(()=>null)]),c=O5(s);if(c.length===0)return{error:"withdraw_unavailable",_instructions:"Withdrawals are not available right now (the bridge lists no destination). Say so briefly in the user's language and suggest trying again later. Do NOT mention tool names."};let u=l===null?null:M5(l);return{ui:{component:"PredictionWithdrawCard",props:{signer:i,wallet:o.address,recipient:i,cashUsd:u,destinations:c,defaultDestination:Njt(c,r.chain,r.token),prefillAmount:U5(r.amount)?"all":L5(r.amount)}},cashUsd:u,_instructions:["The withdraw card is ALREADY RENDERED below your reply: the user picks the chain and token, sees the","live quote (what arrives and the route cost) and confirms there; funds go to their own connected wallet.","Write ONE or TWO short sentences in the user's language:",u===null?"that they can withdraw their Polymarket cash with the card below.":u>0?`that they have $${u} cash available to withdraw with the card below.`:"that the account has no cash to withdraw right now \u2014 positions must be sold (or winnings claimed) first.","Do NOT claim a withdrawal was made or funds arrived, do NOT repeat addresses, and do NOT mention tool names."].join(" ")}}};function Njt(e,t,r){let n=typeof t=="string"?_n(t).replace(/\bchain\b|\bmainnet\b/g,"").trim():"",i=typeof r=="string"?_n(r):"";if(!n&&!i)return null;let o=u=>{if(!n)return!0;let d=_n(u.chainName);return d===n||d.startsWith(n)||n.startsWith(d.split(" ")[0])},a=u=>!i||_n(u.symbol).startsWith(i),s=e.findIndex(u=>!!i&&o(u)&&_n(u.symbol)===i);if(s>=0)return s;let l=e.findIndex(u=>o(u)&&a(u));if(l>=0)return l;let c=e.findIndex(o);return c>=0?c:null}m();m();m();var F5="https://ipfs.pantograph.app/ipfs/",g3e=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function _0(e){let t=e?.trim();if(!t)return null;if(/^(https?:\/\/|data:image\/)/i.test(t))return t;let r=t.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return r?`${F5}${r[1]}`:g3e.test(t)?`${F5}${t}`:null}function y3e(e){let t=e?.trim();if(!t)return null;if(/^https?:\/\//i.test(t))return t;let r=t.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return r?`${F5}${r[1]}`:g3e.test(t)?`${F5}${t}`:null}function b3e(e){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(e)}function Wfe(e){if(!e||typeof e!="object")return;let t=e,r=t.image??t.image_url??t.imageUrl;return typeof r=="string"&&r.trim()?r.trim():void 0}function Djt(e){if(typeof atob=="function"){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return new TextDecoder().decode(r)}if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Mjt(e){let t=e.match(/^data:application\/json([^,]*),(.*)$/is);if(!t)return null;let r=t[1]??"",n=t[2]??"";try{let i=/;base64/i.test(r)?Djt(n):decodeURIComponent(n);return JSON.parse(i)}catch{try{return JSON.parse(n)}catch{return null}}}function _3e(e){let t=e?.trim();if(!t||!/^data:/i.test(t))return null;if(/^data:image\//i.test(t))return t;let r=Mjt(t);return r?_0(Wfe(r)):null}m();var Ljt=12,Ujt=6e3;async function Bjt(e,t,r){let n=new Array(e.length),i=0,o=new Array(Math.max(1,Math.min(t,e.length))).fill(0).map(async()=>{for(;i<e.length;){let a=i++;n[a]=await r(e[a],a)}});return await Promise.all(o),n}async function jjt(e,t){try{let r=await Qe.get(e,{timeout:t});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 qjt(e,t){let r=e?.trim();if(!r)return null;if(/^data:/i.test(r))return _3e(r);let n=y3e(r);if(!n)return null;if(b3e(n))return n;let i=await jjt(n,t);if(i){let o=_0(Wfe(i));if(o)return o}return null}async function z5(e,t,r){if(t.length===0)return[];let n=r?.concurrency??Ljt,i=r?.timeoutMs??Ujt,o=await LTe(e,t,r?.rpcUrl);return Bjt(o,n,a=>qjt(a,i))}var v3e=100,Fjt=100,_P="{name}",w3e="{chain}",vP=class extends Ce{constructor(r){super();g(this,"name","get-wallet-nfts");g(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.`);g(this,"category","nft");g(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}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n),a=o?[o]:Ls(),s=Wjt(r.contract_address),l=x3e(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:v3e});return{chain:u,rows:d.success?S3e(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:Hjt(d),contractAddress:d.token_address,chain:ye(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=Zjt(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 y=>{let b=await this.service.getWalletNFTs({address:n,chain:y,limit:v3e,...a?{tokenAddresses:[a]}:{}});return{chain:y,rows:b.success?S3e(b.data?.result??[]):[],ok:b.success}}));if(o&&!l[0].ok)return{error:"Failed to fetch wallet NFTs"};let c=l.flatMap(y=>y.rows.filter(b=>zjt(b,{contract:a,collectionName:s})).map(b=>({chain:y.chain,row:b})));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),p=c.map(({chain:y,row:b},_)=>{let v=Vjt(b);return{name:v.name,tokenId:v.tokenId,contractAddress:v.contractAddress,image:d[_]??v.image,chain:ye(y)}});return{ui:{component:"WalletNftList",props:{walletAddress:n,collectionName:u,nfts:p}},_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 z5(o,s);a.forEach((c,u)=>{n[c]=l[u]??null})}))}catch{}return n}};function S3e(e){return e.filter(t=>(t.contract_type||"").toUpperCase()==="ERC721")}function zjt(e,t){if(t.contract)return e.token_address.toLowerCase()===t.contract.toLowerCase();if(t.collectionName){let r=t.collectionName.toLowerCase();return(e.name??"").toLowerCase().includes(r)}return!1}function Hjt(e){let t=e.name?.trim();if(t)return t;let r=e.token_address??"";return r.length>10?`${r.slice(0,6)}\u2026${r.slice(-4)}`:r}function Vjt(e){return{name:e.normalized_metadata?.name||e.name||`#${e.token_id}`,tokenId:e.token_id,contractAddress:e.token_address,image:_0(e.normalized_metadata?.image||e.media?.original_media_url)}}function Zjt(e,t){let r=typeof t.pick_button_label=="string"?t.pick_button_label:"",n=typeof t.pick_prompt_template=="string"?t.pick_prompt_template:"",i=[];for(let o of e){if(i.length>=Fjt)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",s=a?`show my ${_P} NFTs on ${w3e}`:`show my ${_P} NFTs`,l=k3e(n,{[_P]:o.name,[w3e]:a},s);a&&!l.includes(a)&&(l=`${l} (${a})`),i.push({label:Gjt(r,o.name,_P),prompt:`${l} (${o.contractAddress})`})}return i}function k3e(e,t,r){let n=e&&e.includes(_P)?e:r;for(let[i,o]of Object.entries(t))n=n.split(i).join(o);return n.replace(/\s+/g," ").trim()}function Gjt(e,t,r){return k3e(e,{[_P]:t},r)}function x3e(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}function Wjt(e){let t=x3e(e);return t&&/^0x[a-fA-F0-9]{40}$/.test(t)?t:void 0}m();m();var Kjt="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.",kp=class extends Ce{constructor(r){super();g(this,"kind","data");g(this,"category","nft");g(this,"llm");this.llm=new zi(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:Kjt,timestamp:n},{role:"user",content:r,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var wP=class extends kp{constructor(){super(...arguments);g(this,"name","get-nft-contract-info");g(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`.');g(this,"parameters",kp.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."`));g(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.")}};m();var SP=class extends kp{constructor(){super(...arguments);g(this,"name","get-nft-metadata");g(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`.');g(this,"parameters",kp.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."`));g(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.")}};m();m();m();m();var Kfe={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"},Yfe="amazon.com";function Yjt(e){return e?e.trim().toLowerCase().split(/[-_]/)[0]:""}function Jfe(e){let t=Yjt(e);return Kfe[t]??Yfe}function H5(e){return`https://${Jfe(e)}/s?k=NFC%20Tag`}m();function V5(e){if(!e)return"";let t=e.trim().toUpperCase().split(/[-_]/),r=t.length>1?t[t.length-1]:t[0];return/^[A-Z]{2}$/.test(r)?r:""}var Jjt=720*60*1e3,T3e=new Map,A3e=3;function Xjt(e){return[`A user in country "${e}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${A3e} 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 Qjt(e){if(!e)return[];let t=e.indexOf("["),r=e.lastIndexOf("]");if(t===-1||r===-1||r<=t)return[];let n;try{n=JSON.parse(e.slice(t,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>=A3e))break}return i}async function Xfe(e,t){let r=V5(e);if(!r||!t)return null;let n=T3e.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:Xjt(r),timestamp:i}];try{let a=await t.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=Qjt(a.text);if(s.length)return T3e.set(r,{links:s,expires:Date.now()+Jjt}),s}catch{}return null}async function kP(e){let t=await Xfe(e.country,e.llm);return t&&t.length?t:[{label:"Amazon",url:H5(e.language)}]}function e2t(e){return e.length<=1?e.length===1?`[${e[0].label}](${e[0].url})`:"":e.map((t,r)=>`${r+1}. [${t.label}](${t.url})`).join(`
|
|
549
|
+
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:i?ye(i):"all",timeFrame:a??null,count:u.length,tokens:u}}};m();m();m();function dx(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[r,n=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${r}.${(n+"00").slice(0,2)}`}function px(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<=0))return`($${dx(e)})`}var fx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-token-balances");g(this,"description",'Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ');g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n);if(o){let l=await this.service.getWalletTokenBalances({address:i,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return l.success?this.renderBalances(i,o,l.data?.result||[]):{error:l.error||"Failed to fetch token balances"}}let a=Ls(),s=await Promise.all(a.map(async l=>{let c=await this.service.getWalletTokenBalances({address:i,chain:l,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:l,tokens:c.success?c.data?.result||[]:[]}}));return this.renderBalancesByChain(i,s)}toTokenLine(r){let n=r.name||r.symbol||"Unknown",i=r.balance_formatted??"0",o=r.symbol||"",a=typeof r.usd_value=="number"?`$${dx(r.usd_value)}`:"$-";return`- ${n}: ${i} ${o} (${a})`.replace(/\s+/g," ").trim()}renderBalances(r,n,i){let o=i.reduce((a,s)=>a+(s.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:r,chain:n,totalUsdValue:`$${dx(o)}`,tokens:i.map(a=>this.toTokenLine(a))}}renderBalancesByChain(r,n){let i=n.map(a=>{let s=a.tokens.reduce((c,u)=>c+(u.usd_value||0),0),l=a.tokens.slice().sort((c,u)=>(u.usd_value||0)-(c.usd_value||0));return{chain:ye(a.chain),total:s,tokens:l}}).filter(a=>a.tokens.length>0).sort((a,s)=>s.total-a.total),o=i.reduce((a,s)=>a+s.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:r,chain:"all",totalUsdValue:`$${dx(o)}`,chains:i.map(a=>({chain:a.chain,totalUsdValue:`$${dx(a.total)}`,tokens:a.tokens.map(s=>this.toTokenLine(s))}))}}};m();var mx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-history");g(this,"description",`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=To(r.chain,n),a=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,s=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,l=typeof r.fromBlock=="number"?r.fromBlock:typeof r.fromBlock=="string"&&r.fromBlock?Number(r.fromBlock):void 0,c=typeof r.toBlock=="number"?r.toBlock:typeof r.toBlock=="string"&&r.toBlock?Number(r.toBlock):void 0,u=Number.isFinite(l)?l:void 0,d=Number.isFinite(c)?c:void 0,p=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,y=(typeof r.order=="string"?r.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",b=typeof r.includeInternalTransactions=="boolean"?r.includeInternalTransactions:void 0,_=typeof r.nftMetadata=="boolean"?r.nftMetadata:void 0,v=typeof r.limit=="number"?r.limit:typeof r.limit=="string"?Number(r.limit):void 0,S=Number.isFinite(v)&&v>0?v:10,w=await this.service.getWalletHistory({address:i,chain:o,limit:S,fromDate:a,toDate:s,fromBlock:u,toBlock:d,cursor:p,order:y,includeInternalTransactions:b,nftMetadata:_});if(!w.success)return{error:w.error||"Failed to fetch wallet history"};let T=(w.data?.result||[]).map(O=>{let $=WTe(o,O.hash);return $?{...O,explorerUrl:$}:O});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:i,chain:o||"default",pagination:{cursor:w.data?.cursor??null,hasMore:!!w.data?.cursor},transactionCount:T.length,transactions:T}}};m();function uht(e){if(e.value_decimal)return e.value_decimal;let t=parseInt(e.token_decimals??"18",10);if(isNaN(t)||t===0)return e.value;try{let r=BigInt(e.value),n=BigInt(10)**BigInt(t),i=r/n,a=(r%n).toString().padStart(t,"0").replace(/0+$/,"");return a?`${i}.${a}`:`${i}`}catch{return e.value}}var hx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-token-transfers");g(this,"description",`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=To(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):25,l=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,c=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,u=this.parseBlock(r.fromBlock),d=this.parseBlock(r.toBlock),p=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,y=(typeof r.order=="string"?r.order.toUpperCase():"")==="ASC"?"ASC":"DESC",b=typeof r.direction=="string"?r.direction.trim().toLowerCase():"all",_=b==="send"?"send":b==="receive"?"receive":"all",v=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,S=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(N=>typeof N=="string"&&!!N).map(N=>N.trim()):void 0,w,k;if(v){let N=await this.resolveContractAddressBySymbol(v,i,o);N&&(S=[N.address],w=N.symbol,k=N.name)}let T=await this.service.getWalletTokenTransfers({address:i,chain:o,contractAddresses:S,limit:s,fromDate:l,toDate:c,fromBlock:u,toBlock:d,cursor:p,order:y});if(!T.success)return{error:T.error||"Failed to fetch token transfers"};let O=i.toLowerCase(),I=(T.data?.result||[]).map(N=>{let G=N.from_address.toLowerCase()===O,U=G?"send":"receive",H=G?N.to_address:N.from_address,L=G?N.to_address_label??void 0:N.from_address_label??void 0,M=G?N.to_address_entity??void 0:N.from_address_entity??void 0;return{...N,direction:U,amount_formatted:uht(N),counterparty:H,counterparty_label:L,counterparty_entity:M}}),D=_==="all"?I:I.filter(N=>N.direction===_);if(v&&!S){let N=v.toLowerCase();D=D.filter(G=>(G.token_symbol??"").toLowerCase()===N)}let q=this.buildCounterparties(D);return{walletAddress:i,chain:o||"default",resolvedToken:w?{symbol:w,name:k,contractAddress:S?.[0]}:null,filters:{tokenSymbol:v||null,contractAddresses:S||null,direction:_,limit:s,order:y,fromDate:l||null,toDate:c||null,fromBlock:u??null,toBlock:d??null},pagination:{cursor:T.data?.cursor??null,pageSize:T.data?.page_size??s,page:T.data?.page??null,hasMore:!!T.data?.cursor},transferCount:D.length,transfers:D,counterparties:q}}async resolveContractAddressBySymbol(r,n,i){let o=r.toLowerCase(),a=await this.service.getWalletTokenBalances({address:n,chain:i});if(a.success&&a.data?.result?.length){let l=a.data.result.find(c=>(c.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}let s=await this.service.searchTokensByKey({key:r,chain:i});if(s.success&&s.data?.length){let c=s.data.find(u=>(u.symbol??"").toLowerCase()===o)??s.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name}}}buildCounterparties(r){let n=new Map,i=new Map;for(let a of r){let s=a.direction==="send"?n:i,l=a.counterparty.toLowerCase(),c=parseFloat(a.amount_formatted)||0,u=s.get(l);u?(u.total+=c,u.count+=1,!u.label&&a.counterparty_label&&(u.label=a.counterparty_label),!u.entity&&a.counterparty_entity&&(u.entity=a.counterparty_entity),a.block_timestamp<u.first&&(u.first=a.block_timestamp),a.block_timestamp>u.last&&(u.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,total:c,count:1,first:a.block_timestamp,last:a.block_timestamp})}let o=a=>Array.from(a.entries()).sort((s,l)=>l[1].count-s[1].count).map(([s,l])=>({address:s,label:l.label,entity:l.entity,total_amount:l.total.toFixed(6).replace(/\.?0+$/,""),tx_count:l.count,first_seen:l.first,last_seen:l.last}));return{sent:o(n),received:o(i)}}parseBlock(r){if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"&&r){let n=Number(r);return Number.isFinite(n)?n:void 0}}};m();var gx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-nft-transfers");g(this,"description",`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=To(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):25,l=typeof r.fromDate=="string"&&r.fromDate?r.fromDate:void 0,c=typeof r.toDate=="string"&&r.toDate?r.toDate:void 0,u=this.parseBlock(r.fromBlock),d=this.parseBlock(r.toBlock),p=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,y=(typeof r.order=="string"?r.order.toUpperCase():"")==="ASC"?"ASC":"DESC",b=typeof r.includePrices=="boolean"?r.includePrices:void 0,_=typeof r.direction=="string"?r.direction.trim().toLowerCase():"all",v=_==="send"?"send":_==="receive"?"receive":"all",S=Array.isArray(r.contractAddresses)?r.contractAddresses.filter(D=>typeof D=="string"&&!!D).map(D=>D.trim()):void 0,w=await this.service.getWalletNftTransfers({address:i,chain:o,contractAddresses:S,limit:s,fromDate:l,toDate:c,fromBlock:u,toBlock:d,cursor:p,order:y,includePrices:b});if(!w.success)return{error:w.error||"Failed to fetch NFT transfers"};let k=i.toLowerCase(),O=(w.data?.result||[]).map(D=>{let q=D.from_address.toLowerCase()===k,N=q?"send":"receive",G=q?D.to_address:D.from_address,U=q?D.to_address_label??void 0:D.from_address_label??void 0,H=q?D.to_address_entity??void 0:D.from_address_entity??void 0;return{...D,direction:N,counterparty:G,counterparty_label:U,counterparty_entity:H}}),$=v==="all"?O:O.filter(D=>D.direction===v),I=this.buildCounterparties($);return{walletAddress:i,chain:o||"default",filters:{contractAddresses:S||null,direction:v,limit:s,order:y,fromDate:l||null,toDate:c||null,fromBlock:u??null,toBlock:d??null,includePrices:b??null},pagination:{cursor:w.data?.cursor??null,pageSize:w.data?.page_size??s,page:w.data?.page??null,hasMore:!!w.data?.cursor},transferCount:$.length,transfers:$,counterparties:I}}buildCounterparties(r){let n=new Map,i=new Map;for(let a of r){let s=a.direction==="send"?n:i,l=a.counterparty.toLowerCase(),c=a.token_name??a.token_address,u=s.get(l);u?(u.tokenIds.add(a.token_id),u.collections.add(c),u.count+=1,!u.label&&a.counterparty_label&&(u.label=a.counterparty_label),!u.entity&&a.counterparty_entity&&(u.entity=a.counterparty_entity),a.block_timestamp<u.first&&(u.first=a.block_timestamp),a.block_timestamp>u.last&&(u.last=a.block_timestamp)):s.set(l,{label:a.counterparty_label,entity:a.counterparty_entity,tokenIds:new Set([a.token_id]),collections:new Set([c]),count:1,first:a.block_timestamp,last:a.block_timestamp})}let o=a=>Array.from(a.entries()).sort((s,l)=>l[1].count-s[1].count).map(([s,l])=>({address:s,label:l.label,entity:l.entity,token_ids:Array.from(l.tokenIds),collections:Array.from(l.collections),tx_count:l.count,first_seen:l.first,last_seen:l.last}));return{sent:o(n),received:o(i)}}parseBlock(r){if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"&&r){let n=Number(r);return Number.isFinite(n)?n:void 0}}};m();var dht=["all","7","30","60","90"],yx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-pnl-summary");g(this,"description",`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=dht.includes(a)?a:void 0;if(o){let _=await this.service.getWalletPnlSummary({address:i,chain:o,days:s});return _.success?{walletAddress:i,chain:o,days:s??"all",summary:this.mapSummary(_.data)}:{error:_.error||"Failed to fetch wallet PnL summary"}}let c=(await Promise.all(Ls().map(async _=>{let v=await this.service.getWalletPnlSummary({address:i,chain:_,days:s});return{chain:_,data:v.success?v.data:void 0}}))).flatMap(_=>_.data&&_.data.total_count_of_trades>0?[{chain:_.chain,data:_.data}]:[]),u=c.map(_=>({chain:ye(_.chain),summary:this.mapSummary(_.data)})),d=c.reduce((_,v)=>_+Number(v.data.total_realized_profit_usd||0),0),p=c.reduce((_,v)=>_+Number(v.data.total_bought_volume_usd||0),0),h=c.reduce((_,v)=>_+Number(v.data.total_sold_volume_usd||0),0),y=c.reduce((_,v)=>_+Number(v.data.total_trade_volume||0),0),b={totalCountOfTrades:c.reduce((_,v)=>_+v.data.total_count_of_trades,0),totalTradeVolume:y,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:p>0?d/p*100:0,totalBuys:c.reduce((_,v)=>_+v.data.total_buys,0),totalSells:c.reduce((_,v)=>_+v.data.total_sells,0),totalBoughtVolumeUsd:p,totalSoldVolumeUsd:h};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:i,chain:"all",days:s??"all",summary:b,chains:u}}mapSummary(r){return{totalCountOfTrades:r.total_count_of_trades,totalTradeVolume:r.total_trade_volume,totalRealizedProfitUsd:r.total_realized_profit_usd,totalRealizedProfitPercentage:r.total_realized_profit_percentage,totalBuys:r.total_buys,totalSells:r.total_sells,totalBoughtVolumeUsd:r.total_bought_volume_usd,totalSoldVolumeUsd:r.total_sold_volume_usd}}};m();var pht=["all","7","30","60","90"],Yj=25,bx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-pnl");g(this,"description",`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${Yj}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${Yj}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${Yj}.`,required:!1,items:{type:"string"}}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n),a=typeof r.days=="string"?r.days.trim().toLowerCase():"",s=pht.includes(a)?a:void 0,l=Array.isArray(r.tokenSymbols)?r.tokenSymbols.filter(p=>typeof p=="string"&&!!p.trim()).map(p=>p.trim()):[],c=Array.isArray(r.tokenAddresses)?r.tokenAddresses.filter(p=>typeof p=="string"&&!!p.trim()).map(p=>p.trim()):[];if(o){let p=await this.fetchChainPnl(i,o,s,l,c);return p.ok?{walletAddress:i,chain:o,days:s??"all",filters:{tokenAddresses:p.tokenAddresses??null,resolvedSymbols:p.resolvedFromSymbols.length>0?p.resolvedFromSymbols:null,unresolvedSymbols:p.unresolvedSymbols.length>0?p.unresolvedSymbols:null},tokenCount:p.tokens.length,tokens:p.tokens}:{error:p.error||"Failed to fetch wallet PnL"}}let d=(await Promise.all(Ls().map(async p=>({chain:p,res:await this.fetchChainPnl(i,p,s,l,c)})))).filter(p=>p.res.ok&&p.res.tokens.length>0).map(p=>({chain:ye(p.chain),tokenCount:p.res.tokens.length,tokens:p.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:i,chain:"all",days:s??"all",filters:{requestedSymbols:l.length>0?l:null,requestedAddresses:c.length>0?c:null},tokenCount:d.reduce((p,h)=>p+h.tokenCount,0),chains:d}}async fetchChainPnl(r,n,i,o,a){let s=[],l=[];o.length>0&&(await Promise.all(o.map(h=>this.resolveContractAddress(h,n,r)))).forEach((h,y)=>{h?s.push({symbol:o[y],address:h.address}):l.push(o[y])});let c=fht([...s.map(p=>p.address),...a]).slice(0,Yj),u=c.length>0?c:void 0,d=await this.service.getWalletPnl({address:r,chain:n,days:i,tokenAddresses:u});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:u,resolvedFromSymbols:s,unresolvedSymbols:l}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(c=>(c.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};function fht(e){let t=new Set,r=[];for(let n of e){let i=n.toLowerCase();t.has(i)||(t.add(i),r.push(n))}return r}m();var mht=BigInt(2)**BigInt(255),_x=class extends Ce{constructor(r){super();g(this,"name","get-wallet-approvals");g(this,"description",`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=To(r.chain,n),a=typeof r.limit=="number"?r.limit:Number(r.limit),s=Number.isFinite(a)&&a>0?Math.min(100,Math.floor(a)):100,l=typeof r.cursor=="string"&&r.cursor?r.cursor:void 0,c=await this.service.getWalletApprovals({address:i,chain:o,limit:s,cursor:l});if(!c.success)return{error:c.error||"Failed to fetch wallet approvals"};let u=c.data,p=(u.result||[]).map(_=>hht(_)),h=0,y=0,b=[];for(let _ of p){_.isUnlimited&&(y+=1);let v=parseFloat(_.token.usdAtRisk??"");Number.isFinite(v)&&(h+=v);let S=_.token.possibleSpam||_.token.verifiedContract===!1,w=!_.spender.label&&!_.spender.entity;(S||_.isUnlimited&&w)&&b.push(_)}return{walletAddress:i,chain:o||"default",filters:{limit:s,cursor:l??null},pagination:{cursor:u.cursor??null,pageSize:u.page_size??s,page:u.page??null,hasMore:!!u.cursor},summary:{totalApprovals:p.length,unlimitedApprovals:y,totalUsdAtRisk:h,riskyApprovalCount:b.length},approvals:p,riskyApprovals:b}}};function hht(e){let t=ght(e.value);return{blockNumber:e.block_number,blockTimestamp:e.block_timestamp??null,transactionHash:e.transaction_hash??null,value:e.value,valueFormatted:e.value_formatted??null,isUnlimited:t,token:{address:e.token.address,addressLabel:e.token.address_label??null,name:e.token.name??null,symbol:e.token.symbol??null,logo:e.token.logo??null,possibleSpam:!!e.token.possible_spam,verifiedContract:e.token.verified_contract??null,currentBalance:e.token.current_balance??null,currentBalanceFormatted:e.token.current_balance_formatted??null,usdPrice:e.token.usd_price??null,usdAtRisk:e.token.usd_at_risk??null},spender:{address:e.spender.address,label:e.spender.address_label??null,entity:e.spender.entity??null,entityLogo:e.spender.entity_logo??null}}}function ght(e){if(!e)return!1;try{return BigInt(e)>=mht}catch{return!1}}m();var pAe=.01,vx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-defi-positions");g(this,"description",`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n);if(o){let l=await this.service.getWalletDefiPositions({address:i,chain:o});if(!l.success)return{error:l.error||"Failed to fetch wallet DeFi positions"};let c=(l.data||[]).filter(fAe);return{walletAddress:i,chain:o,positionCount:c.length,positions:c.map(mAe)}}let s=(await Promise.all(Ls().map(async l=>{let c=await this.service.getWalletDefiPositions({address:i,chain:l});return{chain:l,rows:c.success?(c.data||[]).filter(fAe):[]}}))).filter(l=>l.rows.length>0).map(l=>({chain:ye(l.chain),positionCount:l.rows.length,positions:l.rows.map(mAe)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:i,chain:"all",positionCount:s.reduce((l,c)=>l+c.positionCount,0),chains:s}}};function fAe(e){let t=e.position?.balance_usd,r=e.position?.total_unclaimed_usd_value;return typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=pAe?!0:typeof r=="number"&&r>=pAe}function mAe(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,accountHealthFactor:e.account_data?.health_factor??null,position:yht(e.position)}}function yht(e){return{label:e.label,address:e.address,balanceUsd:e.balance_usd,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,tokens:(e.tokens||[]).map(t=>({tokenType:t.token_type,name:t.name,symbol:t.symbol,contractAddress:t.contract_address,decimals:t.decimals,logo:t.logo,thumbnail:t.thumbnail,balance:t.balance,balanceFormatted:t.balance_formatted,usdPrice:t.usd_price,usdValue:t.usd_value})),details:e.position_details??null}}m();var wx=class extends Ce{constructor(r){super();g(this,"name","get-wallet-defi-protocol-positions");g(this,"description",`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`);g(this,"category","blockchain-data");g(this,"parameters",[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=r.protocol?.trim();if(!i)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=Un(r.address,n),a=Sn(r.chain,n);if(a){let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:a});return c.success?c.data?{walletAddress:o,chain:a,...this.protocolFields(c.data)}:{error:"No data returned for this protocol"}:{error:c.error||"Failed to fetch wallet DeFi protocol positions"}}let l=(await Promise.all(Ls().map(async c=>{let u=await this.service.getWalletDefiProtocolPositions({address:o,protocol:i,chain:c});return{chain:c,data:u.success?u.data:void 0}}))).flatMap(c=>c.data&&(c.data.positions||[]).length>0?[{chain:ye(c.chain),data:c.data}]:[]).map(c=>({chain:c.chain,...this.protocolFields(c.data)})).sort((c,u)=>u.totalUsdValue-c.totalUsdValue);return{_instructions:`These ${i} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:i,totalUsdValue:l.reduce((c,u)=>c+u.totalUsdValue,0),chains:l}}protocolFields(r){return{protocolName:r.protocol_name,protocolId:r.protocol_id,protocolUrl:r.protocol_url,protocolLogo:r.protocol_logo,totalUsdValue:r.total_usd_value,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,accountHealthFactor:r.account_data?.health_factor??null,positionCount:(r.positions||[]).length,positions:(r.positions||[]).map(bht)}}};function bht(e){return{label:e.label,address:e.address,balanceUsd:e.balance_usd,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,tokens:(e.tokens||[]).map(t=>({tokenType:t.token_type,name:t.name,symbol:t.symbol,contractAddress:t.contract_address,decimals:t.decimals,logo:t.logo,thumbnail:t.thumbnail,balance:t.balance,balanceFormatted:t.balance_formatted,usdPrice:t.usd_price,usdValue:t.usd_value})),details:e.position_details??null}}m();function _ht(e){try{return(Number(BigInt(e))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return e}}var Sx=class extends Ce{constructor(r){super();g(this,"name","get-transaction-by-hash");g(this,"description",'Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.');g(this,"category","blockchain-data");g(this,"parameters",[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=r.transactionHash;if(!i)return{error:"Transaction hash is required."};let o=To(r.chain,n),a=await this.service.getTransactionByHash({transactionHash:i,chain:o});if(!a.success||!a.data)return{error:a.error||"Failed to fetch transaction"};let s=a.data,l=(s.logs??[]).filter(u=>!!u.decoded_event).map(u=>({contract:u.address,signature:u.decoded_event.signature,label:u.decoded_event.label,params:u.decoded_event.params})),c=s.logs.map(u=>({address:u.address,decodedEvent:u.decoded_event?{signature:u.decoded_event.signature,label:u.decoded_event.label,params:u.decoded_event.params}:null}));return{hash:s.hash,status:s.receipt_status==="1"?"success":s.receipt_status==="0"?"failed":"unknown",timestamp:s.block_timestamp,blockNumber:s.block_number,from:{address:s.from_address,label:s.from_address_label||null,entity:s.from_address_entity||null},to:s.to_address?{address:s.to_address,label:s.to_address_label||null,entity:s.to_address_entity||null}:null,valueEth:_ht(s.value||"0"),fee:s.transaction_fee,gasUsed:s.receipt_gas_used,gasPriceGwei:s.gas_price?(Number(s.gas_price)/1e9).toFixed(4):null,decodedCall:s.decoded_call?{signature:s.decoded_call.signature,label:s.decoded_call.label,params:s.decoded_call.params}:null,decodedEvents:l,contractCreated:s.receipt_contract_address||null,logs:c}}};m();m();m();m();m();var hAe=new Map;function vht(e){let t=hAe.get(e);if(t)return t;let r=Ug({rpcUrl:e});return hAe.set(e,r),r}async function gAe(e,t,r=[]){let n=await vht(e).rpc(t,r);if(n===void 0)throw new Error(`RPC ${t}: empty result`);return n}function yAe(e,t,r){return gAe(e,"eth_call",[{to:t,data:r},"latest"])}async function wht(e,t,r){let n=X_(e);if(!n)return null;try{return await yAe(n,t,r)}catch{return null}}m();m();m();function Yt(e,t){globalThis.__LENDING_DEBUG__!==!1&&(t===void 0?console.log(`[LEND] ${e}`):console.log(`[LEND] ${e}`,JSON.stringify(t,Sht)))}function Sht(e,t){return typeof t=="bigint"?`${t}n`:t}var kht=6e4,MQ=new Map;async function MO(e,t){let r=Lm(t),n=r?parseInt(r,16):NaN;if(!r||!Number.isFinite(n))return[];let i=`${e}|${r}`,o=MQ.get(i);if(o&&Date.now()-o.at<kht)return o.markets;let a=xht(e,r,n),s=a.then(l=>l.markets);return MQ.set(i,{at:Date.now(),markets:s}),a.then(l=>{l.answered||MQ.delete(i)}),s}async function Jj(e,t){return(await MO(e,t)).length>0}async function xht(e,t,r){try{let n=`${e}/supply/v2?chainId=${r}&limit=100&page=1`;Yt("catalog: GET",n);let i=await Qe.get(n);if(!i.ok){let a=i.status>=400&&i.status<500;return Yt(a?"catalog: chain not served":"catalog: FAILED",{chain:t,status:i.status,message:It(i)}),{markets:[],answered:a}}let o=(i.data?.data?.items||[]).flatMap(a=>{let s=Tht(a,t);return s?[s]:[]});return Yt("catalog: got markets",{chain:t,rawItems:i.data?.data?.items?.length??0,usable:o.length,tokens:o.map(a=>a.token)}),{markets:o,answered:!0}}catch(n){return Yt("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:t,message:n?.message}),{markets:[],answered:!1}}}function bAe(e,t){let r=t.trim().toLowerCase();if(!r)return[];if($t(r))return e.filter(i=>i.contract===r||i.token===r);let n=e.filter(i=>i.name.trim().toLowerCase()===r);return n.length>0?n:e.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 Tht(e,t){if(e?.isDeleted===!0)return null;let r=typeof e?.contract=="string"?e.contract.toLowerCase():"";if(!$t(r))return null;let n=typeof e?.token=="string"&&$t(e.token)?e.token.toLowerCase():r,i=Number(e?.rating?.balanceScore),o=e?.type?.trim()||"unknown";return{chain:t,name:e?.name?.trim()||"USDC lending market",protocol:e?.protocolId?.name?.trim()||"Unknown",protocolLabel:xl(o),protocolUrl:e?.protocolId?.domain?.trim()||null,type:o,contract:r,token:n,platformScore:Number.isFinite(i)?i:null}}function LQ(){return Ls()}async function Xj(e){let t=LQ(),r=await Promise.all(t.map(n=>Jj(e,n)));return t.filter((n,i)=>r[i])}async function Qj(e,t){let r=or(t);return r?Jj(e,r):!1}async function _Ae(e,t){let r=t.map(o=>or(o)).filter(o=>!!o),n=[...new Set(r)],i=await Promise.all(n.map(o=>Jj(e,o)));return n.filter((o,a)=>i[a])}m();function sv(e){return CO(e)}var vAe=6;async function wAe(e,t,r){let n=t.map(w=>$t(w)?w.toLowerCase():null);if(n.every(w=>w===null))return Yt("discovery: ABORT \u2014 no valid token address",{tokens:t}),t.map(()=>null);let i=Gj(e),o;try{Yt("discovery: probing 5 accessors per token",{chain:e,tokens:n,psm:i}),o=await ro(e,[...n.flatMap(w=>w?Aht(w):[]),...i?iAe(i):[]])}catch(w){return Yt("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:e,message:w?.message}),t.map(()=>null)}let a=i?o.slice(o.length-oAe):[],s=Lr(a[0])?.toLowerCase()??null,l=Lr(a[1]),c=Lr(a[2]),u=s&&l&&c?{susds:s,usds:l,oracle:c}:null;i&&Yt("discovery: PSM3 lookup",{psm:i,susds:s,usds:l,oracle:c});let d=0,p=n.map(w=>{if(!w)return null;let k=o.slice(d,d+vAe);return d+=vAe,Yt("discovery: probe answers",{token:w,"POOL()":Lr(k[0]),"UNDERLYING_ASSET_ADDRESS()":Lr(k[1]),"baseToken()":Lr(k[2]),"asset()":Lr(k[3]),"vsr()":Ln(k[4])?.toString()??null,"manager()":Lr(k[5])}),{token:w,slice:k}}),h=new Set;for(let w of p){if(!w)continue;let k=Lr(w.slice[0]);k&&Lr(w.slice[1])&&h.add(k.toLowerCase())}let y=await Pht(e,[...h]);h.size>0&&Yt("discovery: Aave pool authentication",{claimed:[...h],genuine:[...y]});let b=new Map;for(let w of p){if(!w||Lr(w.slice[0])&&Lr(w.slice[1])||Lr(w.slice[2])||!Lr(w.slice[3]))continue;let T=Lr(w.slice[5]);T&&b.set(w.token,T.toLowerCase())}let _=await Eht(e,b);b.size>0&&Yt("discovery: Maple manager authentication",{claimed:[...b.keys()],genuine:[..._]});let v=p.flatMap(w=>w?Lr(w.slice[0])&&Lr(w.slice[1])||Lr(w.slice[2])?[]:_.has(w.token)?[]:Lr(w.slice[3])?[w.token]:[]:[]),S=await Iht(e,[...new Set(v)],r);return v.length>0&&Yt("discovery: Morpho vault lookup",{asked:[...new Set(v)],recognised:[...S.keys()]}),p.map(w=>{if(!w)return null;let{token:k,slice:T}=w,O={chain:e,protocolUrl:null,token:k,platformScore:null};if(u&&k===u.susds)return Yt("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...O,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:xl("spark-l2-susds"),protocolUrl:sv("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let $=Lr(T[0]);if($&&Lr(T[1])){let I=y.has($.toLowerCase());return Yt("discovery: classified",{token:k,as:I?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:$}),I?{...O,name:"Aave v3",protocol:"AAVE",protocolLabel:xl("aave-v3"),protocolUrl:sv("aave-v3"),type:"aave-v3",contract:$}:null}if(Lr(T[2]))return Yt("discovery: classified",{token:k,as:"compound-v3"}),{...O,name:"Compound v3",protocol:"COMPOUND",protocolLabel:xl("compound-v3"),protocolUrl:sv("compound-v3"),type:"compound-v3",contract:k};if(Lr(T[3])){if(_.has(k))return Yt("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...O,name:"Maple",protocol:"MAPLE",protocolLabel:xl("maple"),protocolUrl:sv("maple"),type:"maple",contract:k};if(S.has(k)){Yt("discovery: classified",{token:k,as:"morpho-v2"});let q=S.get(k)||"Morpho V2";return{...O,name:q,protocol:"MORPHO",protocolLabel:xl("morpho-v2"),protocolUrl:sv("morpho-v2"),type:"morpho-v2",contract:k}}let D=Ln(T[4])!==null;return Yt("discovery: classified",{token:k,as:D?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),D?{...O,name:"Spark",protocol:"SPARK",protocolLabel:xl("spark-ethereum"),protocolUrl:sv("spark-ethereum"),type:"spark-ethereum",contract:k}:{...O,name:"Spark",protocol:"SPARK",protocolLabel:xl("spark"),protocolUrl:sv("spark"),type:"spark",contract:k}}return Yt("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function Aht(e){return[{target:e,callData:sr({abi:tx,functionName:"POOL"})},{target:e,callData:sr({abi:tx,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:e,callData:sr({abi:Mm,functionName:"baseToken"})},{target:e,callData:sr({abi:Ed,functionName:"asset"})},{target:e,callData:sr({abi:rx,functionName:"vsr"})},{target:e,callData:sr({abi:CQ,functionName:"manager"})}]}async function Pht(e,t){if(t.length===0)return new Set;try{let r=await ro(e,t.map(n=>({target:n,callData:sr({abi:PQ,functionName:"ADDRESSES_PROVIDER"})})));return new Set(t.filter((n,i)=>Lr(r[i])!==null))}catch{return new Set}}async function Eht(e,t){if(t.size===0)return new Set;let r=[...t.entries()];try{let n=await ro(e,r.map(([,i])=>({target:i,callData:sr({abi:OQ,functionName:"pool"})})));return new Set(r.filter(([i],o)=>Lr(n[o])?.toLowerCase()===i.toLowerCase()).map(([i])=>i))}catch{return new Set}}async function Iht(e,t,r){let n=parseInt(e,16);if(t.length===0||!Number.isFinite(n))return new Map;let i=await Promise.all(t.map(async o=>{try{let a=await Qe.post(r,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:o,c:n}}),s=a.ok?a.data?.data?.vaultV2ByAddress:null;return s?[o,s.name?.trim()||""]:null}catch{return null}}));return new Map(i.filter(o=>o!==null))}var Cht=.01;function Oht(e){return e.reduce((t,r)=>r.conditions===null?t+r.apyPercent:t,0)}function Rht(e,t){if(typeof t!="string"||!t.trim())return;let r=t.trim(),n=J_();n[e]!==r&&Y_({...n,[e]:r})}var kx=class{constructor(t,r,n){g(this,"coinPoolBaseUrl",t);g(this,"endpoints",r);g(this,"describer",n)}async describeReceiptTokens(t,r,n){let i=Date.now();Yt("describeReceiptTokens: START",{chain:t,tokens:r,hasRpcUrl:!!n});let o=Lm(t);o&&Rht(o,n);let a=o?OO(o):null,s=[...new Set(r.filter($t).map(p=>p.toLowerCase()))];if(Yt("describeReceiptTokens: chain resolved",{hex:o,hasChainInfo:!!a,wanted:s}),!o||!a||s.length===0)return Yt("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:o,hasChainInfo:!!a,wantedCount:s.length}),new Map;Yt("describeReceiptTokens: on-chain discovery for",s);let l=await wAe(o,s,this.endpoints.morphoApiUrl),u=[...new Map(s.flatMap((p,h)=>{let y=l[h];return Yt("describeReceiptTokens: discovery result",{token:p,found:!!y,protocol:y?.protocol,type:y?.type,contract:y?.contract}),y?[[p,y]]:[]})).entries()];if(u.length===0)return Yt("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-i}),new Map;Yt("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([p,h])=>({token:p,type:h.type,contract:h.contract}))});let d=await this.describer.describe(o,a,u.map(([,p])=>p));return Yt("describeReceiptTokens: DONE",{ms:Date.now()-i,overviews:d.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(d.map((p,h)=>[u[h][0],p]))}async findMarketByReceiptToken(t,r,n){if(Yt("findMarketByReceiptToken: called",{chain:t,receiptToken:r,hasRpcUrl:!!n}),!$t(r))return Yt("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:r}),null;let o=(await this.describeReceiptTokens(t,[r],n)).get(r.toLowerCase())??null;return Yt("findMarketByReceiptToken: returning",{found:!!o}),o}async getSupplyPositions(t){if(!$t(t.address))return[];let r=await _Ae(this.coinPoolBaseUrl,t.chains);return(await Promise.all(r.map(i=>this.positionsForChain(i,t.address)))).flat().sort((i,o)=>o.suppliedUsdc-i.suppliedUsdc||(o.avgApyPercent??0)-(i.avgApyPercent??0))}async describeResolvedMarkets(t,r){let n=Lm(t),i=n?OO(n):null;return n&&i?this.describer.describe(n,i,r):[]}async positionsForChain(t,r){let n=OO(t),i=await MO(this.coinPoolBaseUrl,t);if(!n||i.length===0)return[];let o=await this.describer.readBalances(t,r,i);if(o.length===0)return[];let a=await this.describer.describe(t,n,o.map(l=>l.market)),s=await this.describer.convertToUnderlying(t,o,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=s[c];return u<Cht?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Oht(l.rewards))/100}]})}};m();var UQ=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var xx=class{constructor(t){g(this,"coinPoolBaseUrl",t)}async listChains(){return Xj(this.coinPoolBaseUrl)}async isSupported(t){return Qj(this.coinPoolBaseUrl,t)}async getMarkets(t){let r=or(t);return r?MO(this.coinPoolBaseUrl,r):[]}async findMarket(t,r){let n=await this.getMarkets(t);return bAe(n,r)}canSupply(t){return UQ.includes(t.type)}async readReceiptToken(t,r){let n=Vg(r).balanceIsUnderlying;try{let i=await ro(t,[{target:r.token,callData:sr({abi:Er,functionName:"symbol"})},{target:r.token,callData:sr({abi:Er,functionName:"decimals"})}]);return{symbol:xk(i[0]),decimals:Tk(i[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};m();m();m();var kAe=6e5,e2=new Map;async function SAe(e){let t=e2.get(e);if(t&&Date.now()-t.at<kAe)return t.chains;let r=Lht(e);return e2.set(e,{at:Date.now(),chains:r}),r.then(n=>{n===null&&e2.delete(e)}),r}async function $ht(e){try{let t=e==="morpho"?await Nht():await Dht();return!t||t.size===0?(Yt(`protocolChains: ${e} returned no chains`),null):(Yt(`protocolChains: ${e} live on`,[...t].sort((r,n)=>r-n)),t)}catch(t){return Yt(`protocolChains: ${e} FAILED`,t instanceof Error?t.message:t),null}}async function Nht(){let e=await Qe.post("https://api.morpho.org/graphql",{query:"{ chains { id network } }"});if(!e.ok)return null;let t=e.data?.data?.chains;if(!Array.isArray(t))return null;let r=new Set;for(let n of t)typeof n?.id=="number"&&Number.isInteger(n.id)&&n.id>0&&(r.add(n.id),typeof n.network=="string"&&n.network.trim()&&xAe.set(n.id,n.network.trim()));return r}async function Dht(){let e=await Qe.get("https://v3-api.compound.xyz/market/all-networks/all-contracts/summary");if(!e.ok||!Array.isArray(e.data))return null;let t=new Set;for(let r of e.data)typeof r?.chain_id=="number"&&Number.isInteger(r.chain_id)&&r.chain_id>0&&t.add(r.chain_id);return t}var xAe=new Map;function TAe(e){return xAe.get(e)??null}var Mht=1500;async function AAe(){let e=Promise.all([SAe("morpho").catch(()=>null),SAe("compound").catch(()=>null)]),t,r=new Promise(n=>{t=setTimeout(n,Mht),t?.unref?.()});try{await Promise.race([e,r])}finally{t&&clearTimeout(t)}}function BQ(e){let t=e2.get(e);return!t||Date.now()-t.at>=kAe?null:PAe.get(t.chains)??null}var PAe=new WeakMap;function Lht(e){let t=$ht(e);return t.then(r=>{r&&PAe.set(t,r)}),t}var Uht={1:"ethereum",10:"opmainnet",130:"unichain",137:"polygon",143:"monad",480:"world-chain",988:"stable",999:"hyperevm",4217:"tempo",4663:"robinhood-chain",5042:"arc",8453:"base",42161:"arbitrum",747474:"katana"},Bht={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_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"},jht={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},qht={1:"mainnet",10:"op",130:"unichain",137:"polygon",2020:"ronin",5e3:"mantle",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function t2(e){let t=Qht(e.chain);return(t===null?null:Fht(e,t))??CO(e.type)??Xht(e,t)}function Fht(e,t){switch(e.type){case"morpho-v2":{let r=Uht[t]??Vht(t);if(!r||!e.contract)return null;let n=`https://app.morpho.org/${r}/vault/${jQ(e.contract)}`,i=Zht(e.name);return i?`${n}/${i}`:n}case"aave-v3":{let r=Bht[t],n=zht(e);return!r||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${jQ(n)}&marketName=${r}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let r=jht[t],n=Yht(e);return!r||!n?null:`https://app.spark.finance/savings/${r}/${n}`}case"compound-v3":{if(Ght(t))return null;let r=qht[t],n=Wht(e);return!r||!n?null:`https://app.compound.xyz/?market=${n}-${r}`}default:return null}}function zht(e){let t=e.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(t)?/^0x0+$/.test(t)?null:t:null}var Hht=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Vht(e){if(!BQ("morpho")?.has(e))return null;let r=TAe(e);return r&&r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Zht(e){let t=e?.trim().toLowerCase()||"";return!t||Hht.has(t)?null:t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Ght(e){let t=BQ("compound");return t!==null&&!t.has(e)}function Wht(e){let t=e.asset?.address?.trim().toLowerCase()||"",r=Kht[t];if(r)return r;let n=e.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(n)&&n.length<=12?n:null}var Kht={"0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"usdc.e","0xff970a61a04b1ca14834a43f5de4533ebddb5cc8":"usdc.e"};function Yht(e){let t=e.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(t))return t;let r=`${e.name||""} ${e.token||""}`.toLowerCase();for(let i of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(r.includes(i))return i;if(e.type==="spark-ethereum")return Jht[e.contract?.trim().toLowerCase()||""]??null;let n=e.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(n)||n.startsWith("s")?null:`s${n}`}var Jht={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function Xht(e,t){let r=e.protocolUrl?.trim();if(!r)return null;let n=/^https?:\/\//i.test(r)?r:`https://${r.replace(/^\/+/,"")}`;try{let i=new URL(n);return t!==null&&i.searchParams.set("chainId",String(t)),e.contract&&i.searchParams.set("contract",jQ(e.contract)),i.toString()}catch{return n}}function jQ(e){let t=e.trim().toLowerCase();return t.startsWith("0x")?t:`0x${t}`}function Qht(e){let t=e?.trim();if(!t)return null;let r=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(r)&&r>0?r:null}var egt=new Set(["spark","spark-ethereum"]),tgt=8;function rgt(e,t,r){if(e.market.type!=="spark-l2-susds")return Ln(t);let n=Ln(t);return n===null||e.tokenDecimals===null?null:ov(e.rawBalance,n,e.tokenDecimals,r)}var r2=class{constructor(t){g(this,"endpoints",t);g(this,"apyLimiter",new qQ(tgt));g(this,"pantograph",new Oi)}async describe(t,r,n){if(n.length===0)return[];Yt("describe: START",{chain:t,count:n.length,types:n.map(l=>l.type)});let{assets:i,shareSymbols:o}=await this.resolveAssets(t,n);Yt("describe: assets resolved",i);let[a,s]=await Promise.all([this.readMarketState(t,n,i),Promise.all(n.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,r,i[c])))),AAe()]);return Yt("describe: on-chain state",a),Yt("describe: APY fetched",s.map((l,c)=>({type:n[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),n.map((l,c)=>{let{totalSuppliedUsdc:u,liveApyFraction:d}=a[c],p=s[c].sizeOverride??u,h=igt(s[c].samples,d??s[c].current,s[c].rewards,s[c].avgOverride??null);return Yt("describe: summarised",{market:l.name,type:l.type,liveFrom:d!==null?"on-chain":s[c].current!==null?"api":"none",rawSamples:s[c].samples.length,historyPoints:h.history.length,currentApyPercent:h.currentApyPercent,avgApyPercent:h.avgApyPercent,apyChangePercent:h.apyChangePercent,totalSuppliedUsdc:p,asset:i[c]?.symbol}),{...l,protocolUrl:t2({...l,asset:i[c],shareSymbol:o[c]}),asset:i[c],totalSuppliedUsdc:p,avgApyPercent:h.avgApyPercent,currentApyPercent:h.currentApyPercent,baseApyPercent:h.baseApyPercent,rewardApyPercent:h.rewardApyPercent,rewards:h.rewards,apyChangePercent:h.apyChangePercent,apyHistory:h.history}})}async readBalances(t,r,n){let i=sr({abi:Er,functionName:"balanceOf",args:[r]}),o=sr({abi:Er,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:i},{target:l.token,callData:o}]),s=await ro(t,a);return n.flatMap((l,c)=>{let u=Ln(s[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Tk(s[c*2+1])}]})}async convertToUnderlying(t,r,n){let i=[],o=r.map(s=>{let l=Vg(s.market).convertToAssetsCall(s.market,s.rawBalance);return l?(i.push(l),i.length-1):-1}),a=await ro(t,i);return r.map((s,l)=>{let c=n[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(o[l]<0)return dc(s.rawBalance,c);let u=rgt(s,a[o[l]],c);return u===null?dc(s.rawBalance,s.tokenDecimals??c):dc(u,c)})}async resolveAssets(t,r){let n={address:av,decimals:NaN,symbol:null,logo:null},i=[],o=r.map(p=>{let h=Vg(p).underlyingCall(p);return h?(i.push(h),i.length-1):-1}),a;try{let p=i.length>0?await ro(t,i):[];a=o.map(h=>h<0?null:Lr(p[h]))}catch{a=r.map(()=>null)}a=a.map((p,h)=>p??r[h]?.assetAddress??null);let s=[...new Set(a.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,u]=await Promise.all([this.readAssetMetadata(t,s),this.fetchAssetLogos(t,s),this.readShareSymbols(t,r)]);return{assets:a.map(p=>{if(!p)return n;let h=p.toLowerCase(),y=l.get(h),b=c.get(h)??null;return y?.decimals!==null&&y?.decimals!==void 0?{address:p,decimals:y.decimals,symbol:y.symbol??null,logo:b}:{address:p,decimals:NaN,symbol:null,logo:b}}),shareSymbols:u}}async readShareSymbols(t,r){let n=sr({abi:Er,functionName:"symbol"}),i=[],o=r.map(a=>!egt.has(a.type)||!a.contract?-1:(i.push({target:a.contract,callData:n}),i.length-1));if(i.length===0)return r.map(()=>null);try{let a=await ro(t,i);return o.map(s=>s<0?null:xk(a[s]))}catch{return r.map(()=>null)}}async readAssetMetadata(t,r){let n=new Map;if(r.length===0)return n;let i=sr({abi:Er,functionName:"decimals"}),o=sr({abi:Er,functionName:"symbol"});try{let a=await ro(t,r.flatMap(s=>[{target:s,callData:i},{target:s,callData:o}]));r.forEach((s,l)=>{n.set(s,{decimals:Tk(a[l*2]),symbol:xk(a[l*2+1])})})}catch{}return n}async fetchAssetLogos(t,r){let n=new Map;if(r.length===0)return n;try{let i=await this.pantograph.getTokensMetadata(r,t);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 Yt("resolveAssets: logos",{chain:t,requested:r.length,found:n.size}),n}async readMarketState(t,r,n){let i=[],o=r.map((u,d)=>{let p=Vg(u),h=n[d],y={market:u,protocol:p,asset:h,size:i.length,rate:-1};i.push(p.sizeCall(u,h));let b=p.liveRateCall(u,h);return b&&(y.rate=i.length,i.push(b)),y}),a=await ro(t,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 ro(t,s):[];return o.map((u,d)=>{let p=u.rate<0?null:a[u.rate],h=l[d]>=0?c[l[d]]:p;return{totalSuppliedUsdc:u.protocol.decodeSize(a[u.size],u.asset),liveApyFraction:h===null?null:u.protocol.decodeLiveRate(h)}})}async fetchApy(t,r,n){try{Yt("fetchApy: requesting",{market:t.name,type:t.type,asset:n?.symbol});let i=await Vg(t).fetchApy(t,r,this.endpoints,n);return Yt("fetchApy: got",{market:t.name,samples:i.samples.length,current:i.current,avgOverride:i.avgOverride??null}),i}catch(i){return Yt("fetchApy: FAILED \u2014 market listed without APY",{market:t.name,type:t.type,message:i?.message}),{samples:[],current:null,rewards:[]}}}},qQ=class{constructor(t){g(this,"limit",t);g(this,"active",0);g(this,"waiting",[])}async run(t){this.active>=this.limit?await new Promise(r=>this.waiting.push(r)):this.active++;try{return await t()}finally{let r=this.waiting.shift();r?r():this.active--}}};function ngt(e,t){let r=SO(Date.now()),n=new Map,i=null;for(let s of e)!Number.isFinite(s.timeMs)||!Number.isFinite(s.fraction)||s.fraction<0||SO(s.timeMs)>r||((!i||s.timeMs>i.timeMs)&&(i=s),n.set(s.timeMs,s.fraction));let o=[...n.entries()].sort((s,l)=>s[0]-l[0]).map(([s,l])=>({date:new Date(s).toISOString(),apyPercent:l*100})),a=t??(i&&SO(i.timeMs)===r?i.fraction:null);return{history:o,live:a}}function igt(e,t,r=[],n=null){let{history:i,live:o}=ngt(e,t),a=o===null?null:o*100,s=r.map(h=>({apyPercent:h.fraction*100,tokenSymbol:h.tokenSymbol,conditions:h.conditions})),l=s.length===0?null:s.reduce((h,y)=>h+y.apyPercent,0),c=a===null?null:a+(l??0),u={baseApyPercent:a,rewardApyPercent:l,rewards:s},d=n!==null&&Number.isFinite(n)?n*100:null;if(i.length===0)return{history:i,avgApyPercent:d,currentApyPercent:c,apyChangePercent:null,...u};let p=i.reduce((h,y)=>h+y.apyPercent,0);return{history:i,avgApyPercent:d??p/i.length,currentApyPercent:c,apyChangePercent:agt(i,a),...u}}var EAe=3600*1e3,ogt=EAe/2;function agt(e,t){if(t===null)return null;let r=Date.now()-EAe,n=null,i=Number.POSITIVE_INFINITY;for(let o=e.length-1;o>=0;o--){let a=Math.abs(Date.parse(e[o].date)-r);if(a>i)break;i=a,n=e[o]}return!n||i>ogt?null:t-n.apyPercent}function IAe(e,t){if(!Number.isFinite(e))return e;let r=10**t,n=Number((e*r).toPrecision(15));return(e<0?-Math.floor(-n):Math.floor(n))/r+0}var fu=class{constructor(t={}){g(this,"read");g(this,"supply");let r=t.coinPoolBaseUrl||"https://api.coinpool.app",n={lendingRatesBaseUrl:t.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:t.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:t.morphoApiUrl||"https://api.morpho.org/graphql"},i=new r2(n);this.read=new kx(r,n,i),this.supply=new xx(r)}async listSupportedChains(){return this.supply.listChains()}async isSupported(t){return this.supply.isSupported(t)}async getMarkets(t){return this.supply.getMarkets(t)}async findMarket(t,r){return this.supply.findMarket(t,r)}canSupply(t){return this.supply.canSupply(t)}async readReceiptToken(t,r){return this.supply.readReceiptToken(t,r)}async describeReceiptTokens(t,r,n){return this.read.describeReceiptTokens(t,r,n)}async findMarketByReceiptToken(t,r,n){return this.read.findMarketByReceiptToken(t,r,n)}async describeResolvedMarkets(t,r){return this.read.describeResolvedMarkets(t,r)}async getMarketOverviews(t){return(await Promise.all(t.chains.map(async n=>this.read.describeResolvedMarkets(n,await this.getMarkets(n))))).flat().sort((n,i)=>(i.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(t){return this.read.getSupplyPositions(t)}};m();var LO="{market}",RAe=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],i2=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],pc="[[LIST]]",$Ae=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',NAe=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function DAe(e,t,r){let[n]=sgt([e],t,r),[i]=e.canSupply?FQ(e,t,r):[];return{name:e.name?.trim()||e.protocol,protocol:e.protocol,protocolUrl:e.protocolUrl,chain:r,apyPercent:e.apyPercent,detailPrompt:n?.prompt??"",detailLabel:n?.label??"",supplyPrompt:i?.prompt??"",supplyLabel:i?.label??""}}function sgt(e,t,r){return MAe(e,{labelTemplate:n2(t.detail_button_label),promptTemplate:n2(t.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${LO}`,...r===void 0?{}:{chainName:r}})}function FQ(e,t,r){return MAe([e],{labelTemplate:n2(t.supply_button_label),promptTemplate:n2(t.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${LO}`,promptFallback:`supply to ${LO}`,...r===void 0?{}:{chainName:r},max:1})}function MAe(e,t){let r=typeof t.chainName=="string"?t.chainName.trim():"",n=[],i=new Set;for(let o of e){if(t.max!==void 0&&n.length>=t.max)break;let a=o.name?.trim();!a||i.has(a.toLowerCase())||(i.add(a.toLowerCase()),n.push({label:CAe(t.labelTemplate,a,t.labelFallback,t.labelNamesMarket===!0),prompt:CAe(lgt(t.promptTemplate),a,t.promptFallback)+cgt(o.contract,r)}))}return n}function lgt(e){let[t,r]=[e[0],e[1]];return t===void 0||t===t.toLowerCase()||r!==void 0&&r!==r.toLowerCase()?e:t.toLowerCase()+e.slice(1)}function n2(e){return typeof e=="string"?e:""}function cgt(e,t){let r=e?.trim();if(!r||!/^0x[a-fA-F0-9]{40}$/.test(r))return"";let n=t?.trim();return n?` (market: ${r} - ${n})`:` (market: ${r})`}function CAe(e,t,r,n=!0){let o=e&&(!n||e.includes(LO))?e:r;return ugt(o).split(LO).join(t).replace(/\s+/g," ").trim()}var OAe="{chain}";function ugt(e){if(!e.includes(OAe))return e;let t=OAe.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${t}`,"g"),"").replace(new RegExp(`${t}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(t,"g"),"")}m();var o2=[{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"]}],HQ=o2.map(e=>e.label),zQ={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 LAe(e){let t=typeof e=="string"?e.trim():"";if(!t)return{kind:"none"};let r=mgt(t);if(!r)return{kind:"none"};let n=dgt(r);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let i=fgt(r);return i?{kind:"unsupported",label:i,requested:t}:{kind:"unknown",requested:t}}function dgt(e){let t=o2.filter(r=>r.aliases.includes(e));if(t.length===1)return t[0];if(t.length>1)return null;if(e.length>=3){let r=o2.filter(n=>n.aliases.some(i=>i.includes(e)||e.includes(i)));if(r.length===1)return r[0];if(r.length>1)return null}return pgt(e)}function pgt(e){let t=null,r=!1;for(let n of o2)for(let i of n.aliases){let o=UAe(i);if(o===0||Math.abs(i.length-e.length)>o)continue;let a=BAe(e,i,o);a>o||(!t||a<t.distance?(t={spec:n,distance:a},r=!1):a===t.distance&&n!==t.spec&&(r=!0))}return t&&!r?t.spec:null}function UAe(e){return e.length<=4?0:e.length<=9?2:3}function fgt(e){let t=zQ[e];if(t)return t;if(e.length>=4){let i=new Set(Object.entries(zQ).filter(([o])=>o.length>=4&&(o.includes(e)||e.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(zQ)){let a=UAe(i);if(a===0||Math.abs(i.length-e.length)>a)continue;let s=BAe(e,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 mgt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function BAe(e,t,r){if(e===t)return 0;if(!e.length)return t.length;if(!t.length)return e.length;let n=new Array(t.length+1),i=Array.from({length:t.length+1},(a,s)=>s),o=new Array(t.length+1);for(let a=1;a<=e.length;a++){o[0]=a;let s=o[0];for(let c=1;c<=t.length;c++){let u=i[c-1]+(e[a-1]===t[c-1]?0:1),d=Math.min(o[c-1]+1,i[c]+1,u);a>1&&c>1&&e[a-1]===t[c-2]&&e[a-2]===t[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[t.length]}m();function Ri(e,t){return e==null?null:IAe(e,t)}var Ga=2,Zg=2;function a2(e){let t=Ri(e.currentApyPercent,Ga),r=e.rewards.map(o=>({apyPercent:Ri(o.apyPercent,Ga)??0,tokenSymbol:o.tokenSymbol,conditions:o.conditions})),n=e.rewardApyPercent===null?null:r.reduce((o,a)=>o+Math.round(a.apyPercent*100),0)/100;if(n===null||t===null)return{currentApyPercent:t,rewardApyPercent:n,rewards:r,baseApyPercent:Ri(e.baseApyPercent,Ga)};let i=Math.round(t*100)-Math.round(n*100);return{currentApyPercent:t,rewardApyPercent:n,rewards:r,baseApyPercent:i/100}}var hgt=["apy","score","size"],jAe=3,qAe=40,Tx=class extends Ce{constructor(r){super();g(this,"name","get-lending-markets");g(this,"kind","ui");g(this,"description",'BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.');g(this,"category","blockchain-data");g(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: ${HQ.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-${qAe}. Default ${jAe} \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},...RAe,...i2]);g(this,"service");this.service=new fu(r)}async run(r,n){let i=Sn(r.chain,void 0),o=i?null:or(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 ${ye(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:ye(a),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:l.map(w=>ye(w))};let c=LAe(r.protocol);if(c.kind==="unsupported"||c.kind==="unknown")return this.unsupportedProtocol(c);let u=a?[a]:l,d=ygt(r.sort),p=bgt(r.limit),h=await this.service.getMarketOverviews({chains:u}),y=c.kind==="supported"?h.filter(w=>c.matches(w)):h;if(c.kind==="supported"&&y.length===0&&h.length>0)return{_instructions:`There are no ${c.label} lending markets on ${a?ye(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?ye(a):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(h.map(w=>w.protocol))]};let b=[...y].sort(ggt[d]).slice(0,p),_=b.map(w=>DAe({name:w.name,contract:w.contract,protocol:w.protocol,protocolUrl:w.protocolUrl,apyPercent:Ri(w.currentApyPercent,Ga),canSupply:this.service.supply.canSupply(w)},r,ye(w.chain))),S={component:"LendingMarketList",props:{chain:a?ye(a):"all",multiChain:new Set(_.map(w=>w.chain)).size>1,markets:_}};return{..._.length>0?{ui:S}:{},_instructions:this.instructions(b,d,_.length>0,c.kind==="supported"?c.label:null),chain:a?ye(a):"all",chainsQueried:u.map(w=>ye(w)),...c.kind==="supported"?{protocolFilter:c.label}:{},sortedBy:d,marketCount:_.length,totalMarketsAvailable:y.length,marketNames:_.map(w=>w.name)}}unsupportedProtocol(r){let n=r.kind==="unsupported",i=n?r.label:`"${r.requested}"`;return{_instructions:`The user asked about ${i}, which has no lending markets here. In their language: tell them plainly that ${i} is ${n?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${i} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:n?r.label:r.requested,protocolSupported:!1,supportedProtocols:[...HQ],marketCount:0,marketNames:[]}}instructions(r,n,i=!1,o=null){if(r.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let a={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[n];return[o?`These are the ${o} lending markets the user can supply to, ${a}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${a}.`,`Write your reply in TWO parts separated by a line containing exactly ${pc} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",n==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(r.map(s=>s.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${ye(r[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${a} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",i?$Ae:""].filter(Boolean).join(" ")}},ggt={apy:(e,t)=>(t.currentApyPercent??-1)-(e.currentApyPercent??-1),score:(e,t)=>(t.platformScore??-1)-(e.platformScore??-1),size:(e,t)=>(t.totalSuppliedUsdc??-1)-(e.totalSuppliedUsdc??-1)};function ygt(e){let t=typeof e=="string"?e.trim().toLowerCase():"";return hgt.includes(t)?t:"apy"}function bgt(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?jAe:Math.min(Math.floor(t),qAe)}m();m();function FAe(e){let{currentApyPercent:t,avgApyPercent:r,totalSuppliedUsdc:n,rewardApyPercent:i,baseApyPercent:o,platformScore:a}=e;return e.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:i!==null&&o!==null&&i>o*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:t!==null&&r!==null&&r>0&&t>r*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:n!==null&&n<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&n!==null&&n>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:n!==null&&n>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}m();function s2(e){let t=typeof e=="string"?e.trim():"",r=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(t);if(r)return r[1];let n=/0x[a-fA-F0-9]{40}/.exec(t);return n&&n[0]!==t?n[0]:t}var Ax=class extends Ce{constructor(r){super();g(this,"name","get-lending-market-detail");g(this,"category","blockchain-data");g(this,"description",'Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.');g(this,"parameters",[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...i2]);g(this,"service");this.service=new fu(r)}async run(r,n){let o=Sn(r.chain,void 0)??or(n?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let p=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:ye(o),chainsWithLendingMarkets:p.map(h=>ye(h)),_instructions:`There are no lending markets on ${ye(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let a=s2(r.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let s=await this.service.findMarket(o,a);if(s.length===0)return{error:"market_not_found",market:a,chain:ye(o),_instructions:`No lending market matching "${a}" exists on ${ye(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(s.length>1)return{error:"ambiguous_market",market:a,chain:ye(o),candidates:s.map(p=>({marketName:p.name,protocol:p.protocol})),_instructions:`"${a}" matches ${s.length} different markets on ${ye(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+a+`" and chain for ${ye(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let l=s[0],c=await this.describeOne(o,l);if(!c)return{error:"market_unavailable",marketName:l.name,chain:ye(o),_instructions:`${l.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let u=this.service.supply.canSupply(l),d=u?FQ({name:l.name,contract:l.contract},r,ye(o)):[];return{_instructions:this.instructions(c,d.length>0,u),...d.length>0?{actionButtons:d}:{},marketName:c.name,protocol:c.protocolLabel??c.protocol,protocolUrl:c.protocolUrl,chain:ye(c.chain),suppliedAssetSymbol:c.asset.symbol,totalSuppliedUsdc:Ri(c.totalSuppliedUsdc,Zg),...a2(c),avgApyPercent:Ri(c.avgApyPercent,Ga),apyChangePercent:Ri(c.apyChangePercent,Ga),platformScore:c.platformScore,supplySupported:u}}async describeOne(r,n){try{let[i]=await this.service.describeResolvedMarkets(r,[n]);return i??null}catch{return null}}instructions(r,n,i){let o=FAe(r);return[`This is the full picture of ONE lending market, ${r.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',i?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",n?NAe:""].filter(Boolean).join(" ")}};m();var Px=class extends Ce{constructor(r){super();g(this,"name","get-wallet-lending-positions");g(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.');g(this,"category","blockchain-data");g(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}]);g(this,"service");this.service=new fu(r)}async run(r,n){let i=Un(r.address,n);if(!$t(i))return{error:`"${i}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=Sn(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 ${ye(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:ye(o),positionCount:0,positions:[],chainsWithLendingMarkets:s.map(u=>ye(u))};let l=o?[o]:s,c=await this.service.getSupplyPositions({address:i,chains:l});return{_instructions:this.instructions(c),walletAddress:i,chain:o?ye(o):"all",chainsQueried:l.map(u=>ye(u)),positionCount:c.length,totals:_gt(c),positions:c.map(u=>({marketName:u.name,protocol:u.protocol,protocolUrl:u.protocolUrl,chain:ye(u.chain),suppliedUsdc:Ri(u.suppliedUsdc,Zg),suppliedAssetSymbol:u.asset.symbol,avgApyPercent:Ri(u.avgApyPercent,Ga),...a2(u),apyChangePercent:Ri(u.apyChangePercent,Ga),estimatedAnnualYieldUsdc:Ri(u.estimatedAnnualYieldUsdc,Zg),marketTotalSuppliedUsdc:Ri(u.totalSuppliedUsdc,Zg),apyHistory:u.apyHistory.map(d=>({...d,apyPercent:Ri(d.apyPercent,Ga)})),platformScore:u.platformScore}))}}instructions(r){return r.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(r.map(i=>i.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function _gt(e){if(new Set(e.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let n=e.reduce((a,s)=>a+s.suppliedUsdc,0),i=e.filter(a=>a.avgApyPercent!==null),o=i.reduce((a,s)=>a+s.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:e[0]?.asset.symbol??null,suppliedUsdc:Ri(n,Zg),estimatedAnnualYieldUsdc:Ri(e.reduce((a,s)=>a+(s.estimatedAnnualYieldUsdc??0),0),Zg),weightedAvgApyPercent:Ri(o>0?i.reduce((a,s)=>a+s.suppliedUsdc*s.avgApyPercent,0)/o:null,Ga)}}m();var Ex=class extends Ce{constructor(r){super();g(this,"name","open-supply-usdc-form");g(this,"kind","ui");g(this,"category","lending-action");g(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.');g(this,"parameters",[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}]);g(this,"service");g(this,"moralis");this.service=new fu(r),this.moralis=new mr(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=Sn(r.chain,void 0)??or(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 S=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:ye(a),chainsWithLendingMarkets:S.map(w=>ye(w)),_instructions:`There are no lending markets on ${ye(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=s2(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:ye(a),_instructions:`No lending market matching "${s}" exists on ${ye(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:ye(a),candidates:l.map(S=>({marketName:S.name,protocol:S.protocol})),_instructions:`"${s}" matches ${l.length} different markets on ${ye(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 ${ye(a)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let c=l[0];if(!this.service.supply.canSupply(c))return{error:"unsupported_protocol",marketName:c.name,protocol:c.protocol,_instructions:`Supplying to ${c.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let u=await this.describeOne(a,c),d=vgt(u);if(!d)return{error:"asset_unresolved",marketName:c.name,chain:ye(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[p,h]=await Promise.all([this.assetBalance(i,a,d.address),this.service.readReceiptToken(a,c)]);if(p&&Bg(p.amount,"0")<=0)return{error:"no_asset_balance",marketName:c.name,chain:ye(a),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${c.name} on ${ye(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 y=wgt(r.amount),b=y?kl(y,d.decimals):null;if(b&&p&&Bg(b,p.amount)>0)return{error:"insufficient_asset_balance",marketName:c.name,chain:ye(a),assetSymbol:d.symbol,requestedAmount:y,assetBalance:p.amount,_instructions:`The user wants to supply ${y} ${d.symbol} to ${c.name}, but they only hold ${p.amount} ${d.symbol} on ${ye(a)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${y} ${d.symbol} exceeds their balance of ${p.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:ye(a),walletAddress:i,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:u?.protocolUrl??t2(c),contract:c.contract,token:c.token,apyPercent:u?.currentApyPercent??u?.avgApyPercent??null,receiptToken:h},asset:d,...b?{prefillAmount:b}:{},...p?{spendable:p.amount}:{},...p?.usd?{spendableUsd:p.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:_},marketName:c.name,protocol:c.protocol,chain:ye(a),apyPercent:Ri(_.market.apyPercent,Ga),assetSymbol:d.symbol,assetBalance:p?.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 vgt(e){let t=e?.asset;return!t?.address||t.address===av||!Number.isFinite(t.decimals)?null:{address:t.address,symbol:t.symbol||"the market asset",decimals:t.decimals}}function wgt(e){let t=typeof e=="string"?e.trim():typeof e=="number"?String(e):"";return/^\d*\.?\d+$/.test(t)&&Number(t)>0?t:null}m();m();m();m();m();var Gg={GAMMA:"https://gamma-api.polymarket.com",DATA:"https://data-api.polymarket.com",BRIDGE:"https://bridge.polymarket.com",CLOB:"https://clob.polymarket.com",RELAYER:"https://relayer-v2.polymarket.com"},l2="/submit",c2={INTERVAL_MS:3e3,TIMEOUT_MS:9e4},ZQ="0xebd1cc31700311ef8259fc9337f7a04317bfee851a71bf628420669d75124374",Sgt=/^0x[0-9a-fA-F]{64}$/,VQ=ZQ;function GQ(e){let t=e?.trim();if(!t){VQ=ZQ;return}if(!Sgt.test(t))throw new Error(`Invalid Polymarket builder code: ${t}`);VQ=t.toLowerCase()}function Ix(){return VQ}var kgt=1e4,xgt="https://intercom.help/funxyz/en/articles/10732578-contact-us",UO="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Wg="https://polymarket.com",WQ="wss://ws-live-data.polymarket.com",Dd="0x89",BO="137",KQ="0xDCa4af75705dbB50f62437045afF9921947917d2",YQ="0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296",jO="0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",JQ="Trading setup approvals",Ao={DEPLOY:"deploy",ENABLE_TRADING:"enable_trading",APPROVE:"approve",DONE:"done"},u2={INTERVAL_MS:2e3,MAX_ATTEMPTS:30},qO=["USDC","USDC.E","USDT","USD\u20AE0","USDT0","DAI","USDE","AUSD","USDG"],lv={"1151111081099710":"svm",8253038:"btc",728126428:"tron",29780:null},mu="0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB",hu=6,fc={depositWalletFactory:"0x00000000000Fb5C9ADea0298D729A0CB3823Cc07",depositWalletImplementation:"0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB",safeFactory:"0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b",safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf",factoryBeaconSelector:"0x49493a4d"},Um={PREFIX:BigInt("0x61003d3d8160233d3973"),CONST1:"0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",CONST2:"0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",BEACON_PREFIX:BigInt("0x6100523d8160233d3973"),BEACON_CONST1:"0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",BEACON_CONST2:"0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",BEACON_CONST3:"0x60195155f3363d3d373d3d363d602036600436635c60da"},Kg=[{key:"politics",tagId:"2",label:"Politics",aliases:["politic","chinh tri","ch\xEDnh tr\u1ECB","\u653F\u6CBB","\uC815\uCE58"]},{key:"sports",tagId:"1",label:"Sports",aliases:["sport","the thao","th\u1EC3 thao","\u30B9\u30DD\u30FC\u30C4","\u4F53\u80B2","\uC2A4\uD3EC\uCE20"]},{key:"crypto",tagId:"21",label:"Crypto",aliases:["cryptocurrency","tien dien tu","ti\u1EC1n \u0111i\u1EC7n t\u1EED","tien ma hoa","ti\u1EC1n m\xE3 h\xF3a","\u6697\u53F7\u8CC7\u7523","\u52A0\u5BC6\u8D27\u5E01","\uC554\uD638\uD654\uD3D0"]},{key:"esports",tagId:"64",label:"Esports",aliases:["e-sports","the thao dien tu","th\u1EC3 thao \u0111i\u1EC7n t\u1EED","e\u30B9\u30DD\u30FC\u30C4","\u7535\u7ADE"]},{key:"iran",tagId:"78",label:"Iran",aliases:["\u30A4\u30E9\u30F3","\u4F0A\u6717","\uC774\uB780"]},{key:"finance",tagId:"120",label:"Finance",aliases:["tai chinh","t\xE0i ch\xEDnh","\u91D1\u878D","\uAE08\uC735"]},{key:"geopolitics",tagId:"100265",label:"Geopolitics",aliases:["dia chinh tri","\u0111\u1ECBa ch\xEDnh tr\u1ECB","\u5730\u653F\u5B66","\u5730\u7F18\u653F\u6CBB"]},{key:"tech",tagId:"1401",label:"Tech",aliases:["technology","cong nghe","c\xF4ng ngh\u1EC7","\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC","\u79D1\u6280","\uAE30\uC220"]},{key:"elections",tagId:"144",label:"Elections",aliases:["election","bau cu","b\u1EA7u c\u1EED","\u9078\u6319","\u9009\u4E3E","\uC120\uAC70"]},{key:"culture",tagId:"596",label:"Culture",aliases:["pop culture","pop-culture","entertainment","van hoa","v\u0103n h\xF3a","giai tri","gi\u1EA3i tr\xED","\u30A8\u30F3\u30BF\u30E1","\u5A31\u4E50"]},{key:"economy",tagId:"100328",label:"Economy",aliases:["economics","kinh te","kinh t\u1EBF","\u7D4C\u6E08","\u7ECF\u6D4E","\uACBD\uC81C"]},{key:"weather",tagId:"84",label:"Weather",aliases:["climate","thoi tiet","th\u1EDDi ti\u1EBFt","\u5929\u6C17","\u5929\u6C14"]},{key:"science",tagId:"74",label:"Science",aliases:["khoa hoc","khoa h\u1ECDc","\u79D1\u5B66","\uACFC\uD559"]},{key:"awards",tagId:"18",label:"Awards",aliases:["giai thuong","gi\u1EA3i th\u01B0\u1EDFng","\u8CDE","\u5956\u9879"]}],FO={trending:{order:"volume24hr",ascending:!1},new:{order:"startDate",ascending:!1},volume:{order:"volume",ascending:!1},liquidity:{order:"liquidity",ascending:!1},competitive:{order:"competitive",ascending:!1},ending_soon:{order:"endDate",ascending:!0}},XQ="102127",QQ="100639",eee="102169",tee=["TRADE","REDEEM","SPLIT","MERGE","CONVERSION","REWARD"],ree=.01,zO={MIN_BUY_USD:1,DEFAULT_SLIPPAGE:.05,SLIPPAGE_OPTIONS:[.02,.05,.1]},d2={POLL_MS:1e3,TIMEOUT_MS:2e4},Xo={STABLE_SYMBOLS:["USDC","USDT","USDT0","USD\u20AE0"],CHAIN_ORDER:["137","8453","42161","1","10","56"],LARGE_USD:5e4,ERROR:{INVALID_AMOUNT:"invalid_amount",BELOW_MINIMUM:"below_minimum",INSUFFICIENT_BALANCE:"insufficient_balance",CANCELLED:"cancelled",FAILED:"failed"}},cv={POSITIONS_READ_LIMIT:500,ERROR:{NOTHING_TO_CLAIM:"nothing_to_claim",CANCELLED:"cancelled",FAILED:"failed"}},Bm={ENTER_AMOUNT:"enter_amount",NO_LIQUIDITY:"no_liquidity",NOT_ENOUGH_LIQUIDITY:"not_enough_liquidity",BELOW_MINIMUM:"below_minimum",EXCEEDS_HOLDING:"exceeds_holding",TOO_SMALL:"too_small"},jn={REGION_RESTRICTED:"region_restricted",MARKET_CLOSED:"market_closed",NOT_FILLED:"not_filled",INSUFFICIENT_BALANCE:"insufficient_balance",NOT_ENOUGH_LIQUIDITY:"not_enough_liquidity",TRADING_PAUSED:"trading_paused",BELOW_MIN_SIZE:"below_min_size",CLOSE_ONLY:"close_only",ACCOUNT_BANNED:"account_banned",CANCELLED:"cancelled",FAILED:"failed"},HO={THROTTLE_MS:1e3,STALE_MS:3e4,FALLBACK_POLL_MS:5e3};m();function VAe(e){return`btc-updown-5m-${Math.floor(e/1e3/300)*300}`}var Tgt=e=>/^btc-updown-(5m|15m)-/.test((e.slug??"").toLowerCase()),gu={MAX:8,INDEX:2,PREGAME_MINUTES:720,VOLUME_FLOOR:15e4,MAX_PER_SERIES:2,GAME_MINUTES:180,PAIR_VOLUME:3e5,PROXIMITY_WEIGHT:10},ZAe={nfl:2160,cbb:1440,cwbb:1440},Agt={cwbb:1e5,"world-cup":25e3,wimbledon:25e3},Pgt={cwbb:3,"world-cup":6,wimbledon:4},Egt={nba:150,wnba:120,ufc:60,f1:120,cs2:90,"dota-2":90,"league-of-legends":60,valorant:60},Igt="world-cup";function nee(e){if(!e)return null;let t=e.trim().replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),r=Date.parse(t);return Number.isFinite(r)?r:null}function Cgt(e){return(e.seriesSlug||e.series?.[0]?.slug||(e.slug??"").split("-")[0]||"").toLowerCase().replace(/-\d{4}(-\d{2,4})?$/,"")}var Ogt=e=>(e.tags??[]).some(t=>["1","64"].includes(String(t?.id))||t?.slug==="sports"||t?.slug==="esports");function Rgt(e){let t=(e.markets??[]).find(r=>r.gameStartTime)?.gameStartTime;return nee(e.startTime)??nee(t)??nee(e.startDate)}var $gt=e=>{let t=Number(e.volume);return Number.isFinite(t)?t:0},zAe=e=>e.closed!==!0;function Ngt(e,t){if(e.parentEventId!=null||e.closed===!0||e.ended===!0||!Ogt(e))return null;let r=Cgt(e);if(!r)return null;let n=Rgt(e);if(n===null)return null;let i=$gt(e);if(i<(Agt[r]??gu.VOLUME_FLOOR))return null;let o=(n-t)/6e4,a=Egt[r]??gu.GAME_MINUTES,s=e.live===!0&&-o<=a+15+180+10;if(!s&&o<-30)return null;let l=ZAe[r]??gu.PREGAME_MINUTES;return!s&&!(o>=-5&&o<=l)?null:{row:e,league:r,volume:i,minutes:o,live:s}}function Dgt(e){let t=new Map;for(let n of e)t.set(n.league,[...t.get(n.league)??[],n]);let r=[];for(let[n,i]of t){let o=[...i].sort((u,d)=>d.volume-u.volume),a=Pgt[n]??gu.MAX_PER_SERIES,s=n===Igt,l=s?Math.min(o.length,a):1;if(!s&&o.length>=2){let[u,d]=o,p=u.volume>=gu.PAIR_VOLUME&&d.volume>=gu.PAIR_VOLUME,h=[u,d].filter(y=>y.live||y.minutes<=60).length>=2;(p||h)&&(l=Math.min(o.length,a))}let c=ZAe[n]??gu.PREGAME_MINUTES;for(let u of o.slice(0,l)){let d=Math.log1p(u.volume),p=Math.max(0,Math.min(1,(c-Math.max(0,u.minutes))/c));r.push({...u,worldCup:s,score:u.live?d:d+gu.PROXIMITY_WEIGHT*p})}}return r.sort((n,i)=>{if(n.worldCup!==i.worldCup)return n.worldCup?-1:1;let o=n.minutes<0,a=i.minutes<0;return o!==a?o?-1:1:i.score-n.score}).slice(0,gu.MAX).map(n=>n.row)}function HAe(e){let t=new Set;return e.filter(r=>{let n=String(r.id??"");return!n||t.has(n)?!1:(t.add(n),!0)})}function GAe(e,t){let r=e.btc5m&&zAe(e.btc5m)?e.btc5m:null,n=d=>HAe(d.filter(p=>zAe(p)&&!Tgt(p))),i=n(e.feed),o=n(e.featured);if(o.length>0){let d=new Set(o.map(h=>String(h.id))),p=new Set(o.map(h=>(h.series?.[0]?.slug??"").toLowerCase()).filter(Boolean));i=[...o,...i.filter(h=>!d.has(String(h.id))&&!p.has((h.series?.[0]?.slug??"").toLowerCase()))]}let a=i.slice(0,gu.INDEX),s=i.slice(gu.INDEX),l=new Set(a.map(d=>String(d.id))),c=HAe([...s,...n(e.sports)]).filter(d=>!l.has(String(d.id))).map(d=>Ngt(d,t)).filter(d=>d!==null),u=Dgt(c);if(u.length>0){let d=new Set(u.map(p=>String(p.id)));i=[...a,...u,...s.filter(p=>!d.has(String(p.id)))]}return r&&(i=[...i.slice(0,1),r,...i.slice(1)]),i}m();var Mgt=/^([a-z0-9]+)-updown-(5m|15m|4h)-(\d+)$/,Lgt={"5m":300,"15m":900,"4h":14400},Ugt={"5m":"fiveminute","15m":"fifteen","4h":"fourhour"},WAe=e=>new Date(e*1e3).toISOString().replace(".000Z","Z");function m2(e,t){let r=Mgt.exec((e??"").toLowerCase());if(!r)return null;let[,n,i,o]=r,a=Number(o),s=t?.cryptoMarketConfig;return{symbol:n.toUpperCase(),priceFeed:`${n}/usd`,duration:i,startTime:t?.eventStartTime||WAe(a),endTime:t?.endDate||WAe(a+Lgt[i]),twapSeconds:s?.twapEnabled===!0?Math.max(0,Number(s.twapLookbackSeconds)||0):0}}function JAe(e){return{symbol:e.symbol,eventStartTime:e.startTime,variant:Ugt[e.duration]??"hourly",endDate:e.endTime,...e.twapSeconds>0?{twapEnabled:"true",twapLookbackSeconds:String(e.twapSeconds)}:{}}}var Bgt="crypto_prices_chainlink",jgt=15e3,qgt=1e4,KAe=[1e3,2e3,5e3,1e4],jm=new Map,iee=new Map,qm=null,p2=null,Cx=null,f2=null,oee=0,aee=(e,t)=>JSON.stringify({action:e,subscriptions:t.map(r=>({topic:Bgt,type:"*",filters:JSON.stringify({symbol:r})}))});function Fgt(e,t){let r=iee.get(e);r&&r.timestamp>t.timestamp||(iee.set(e,t),jm.get(e)?.forEach(n=>n(t)))}function zgt(e){if(typeof e!="string"||!e.startsWith("{"))return;let t;try{t=JSON.parse(e)}catch{return}let r=t.payload??{},n=typeof r.symbol=="string"?r.symbol.toLowerCase():"";if(!n)return;let i=Array.isArray(r.data)?r.data:[r],o=i[i.length-1],a=Number(o?.value),s=Number(o?.timestamp);Number.isFinite(a)&&a>0&&Fgt(n,{value:a,timestamp:Number.isFinite(s)?s:Date.now()})}function Hgt(){p2&&clearInterval(p2),Cx&&clearTimeout(Cx),f2&&clearTimeout(f2),p2=Cx=f2=null}function XAe(){Hgt();let e=qm;if(qm=null,e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.close()}catch{}}}function YAe(){Cx&&clearTimeout(Cx),Cx=setTimeout(see,jgt)}function see(){if(XAe(),jm.size===0)return;let e=KAe[Math.min(oee,KAe.length-1)];oee+=1,f2=setTimeout(QAe,e)}function QAe(){if(qm||jm.size===0)return;let e=globalThis.WebSocket;if(!e)return;let t=new e(WQ);qm=t,t.onopen=()=>{t.send(aee("subscribe",[...jm.keys()])),p2=setInterval(()=>t.readyState===1&&t.send("ping"),qgt),YAe()},t.onmessage=r=>{oee=0,YAe(),zgt(r.data)},t.onclose=see,t.onerror=see}function ePe(e,t){let r=e.toLowerCase(),n=jm.get(r)??new Set,i=n.size===0;n.add(t),jm.set(r,n);let o=iee.get(r);return o&&t(o),qm?i&&qm.readyState===1&&qm.send(aee("subscribe",[r])):QAe(),()=>{let a=jm.get(r);!a?.delete(t)||a.size>0||(jm.delete(r),jm.size===0?XAe():qm?.readyState===1&&qm.send(aee("unsubscribe",[r])))}}m();var Vgt=.1;function ar(e,t){if(e==null||e==="")return t;let r=typeof e=="number"?e:Number.parseFloat(String(e));return Number.isFinite(r)?r:t}function h2(e){if(Array.isArray(e))return e;if(typeof e!="string"||e==="")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function VO(e){let t=String(e.version??"").trim().toLowerCase();return t===""||t==="v1"?"v1":t==="v2"?"v2":null}function ZO(e){let t=e.feeSchedule??null,r=e.feesEnabled===!0?ar(t?.rate,0):0,n=ar(t?.exponent,1);return{rate:r>0&&r<1?r:0,exponent:n>0?n:1}}function GO(e){return e.active!==!1&&e.archived!==!0&&e.closed!==!0&&e.acceptingOrders===!0&&e.enableOrderBook!==!1}function tPe(e,t){return h2(t==="v2"?e.positionIds:e.clobTokenIds).map(r=>String(r??"")).filter(Boolean)}function rPe(e,t){let r=h2(e.outcomes).map(i=>String(i)),n=tPe(e,t);return r.length>=2&&n.length===r.length?r.map((i,o)=>({label:i,tokenId:n[o]})):[]}function lee(e){let t=h2(e.outcomes).map(c=>String(c)),r=h2(e.outcomePrices).map(c=>ar(c,null)),n=VO(e);if(n===null)return null;let i=tPe(e,n);if(t.length<2||r.length!==t.length||i.length!==t.length||r.some(c=>c===null||c<0||c>1)||!e.id||!e.conditionId)return null;let o=(e.question??"").trim(),a=ar(e.bestBid,null),s=ar(e.bestAsk,null),l=ar(e.lastTradePrice,null);return{id:String(e.id),slug:e.slug??"",conditionId:e.conditionId,question:o,label:(e.groupItemTitle??"").trim()||o,outcomes:t.map((c,u)=>({label:c,chance:r[u]})),clobTokenIds:i,protocol:n,volume:ar(e.volumeNum??e.volume,0),volume24h:ar(e.volume24hr,0),liquidity:ar(e.liquidityNum??e.liquidity,0),endDate:e.endDate??null,open:GO(e),fee:ZO(e),priced:a!==null&&s!==null&&s-a<=Vgt+1e-9||l!==null&&l>0,negRisk:e.negRisk===!0,sportsMarketType:e.sportsMarketType??null,bestBid:a,bestAsk:s,oneDayPriceChange:ar(e.oneDayPriceChange,null),groupItemThreshold:ar(e.groupItemThreshold,null)}}function Zgt(e){let t=String(e.abbreviation??"").trim(),r=/^[a-z]{2,}\d+$/i.test(t)?t.replace(/\d+$/,""):t;return r?r.toUpperCase():null}function Ggt(e,t){if(e.sportsMarketType!=="moneyline"||t.length===0)return e;let r=new Map(t.map(n=>[_n(String(n.name??"")),Zgt(n)]));return{...e,outcomes:e.outcomes.map(n=>{let i=r.get(_n(n.label));return i?{...n,shortLabel:i}:n})}}function cee(e){return`${Wg}/event/${e}`}function g2(e){if(!e.id||!e.slug)return null;let t=e.negRisk===!0,r=Array.isArray(e.teams)?e.teams:[],n=(e.markets??[]).map(lee).filter(i=>i!==null).map(i=>Ggt({...i,negRisk:i.negRisk||t},r));return t?n.sort((i,o)=>o.outcomes[0].chance-i.outcomes[0].chance):n.every(i=>i.groupItemThreshold!==null)&&n.sort((i,o)=>(i.groupItemThreshold??0)-(o.groupItemThreshold??0)),{id:String(e.id),slug:e.slug,title:(e.title??"").trim(),description:(e.description??"").trim(),resolutionSource:(e.resolutionSource??"").trim(),image:e.image||e.icon||null,url:cee(e.slug),startDate:e.startDate??null,endDate:e.endDate??null,volume:ar(e.volume,0),volume24h:ar(e.volume24hr,0),liquidity:ar(e.liquidity,0),negRisk:t,ended:e.ended===!0,markets:n,upDown:m2(e.slug,e.markets?.[0])}}function uv(e){return e.markets.find(t=>t.sportsMarketType==="moneyline")}function y2(e,t=2){let r=e.markets.filter(l=>l.open);if(r.length===0)return null;let n=l=>l.priced?l.outcomes.slice(0,t):[],i=uv(e);return i?i.open?{kind:"binary",outcomes:n(i),openMarketCount:r.length}:null:e.markets.length===1?{kind:"binary",outcomes:n(r[0]),openMarketCount:1}:{kind:"multi",outcomes:[...r.filter(l=>l.priced)].sort((l,c)=>c.outcomes[0].chance-l.outcomes[0].chance).slice(0,t).map(l=>({label:l.label,chance:l.outcomes[0].chance})),openMarketCount:r.length}}function WO(e){let t=/polymarket\.com\/(?:[a-z]{2}(?:-[a-z]{2})?\/)?event\/([a-z0-9-]+)(?:\/([a-z0-9-]+))?/i.exec(e);return t?{eventSlug:t[1].toLowerCase(),...t[2]?{marketSlug:t[2].toLowerCase()}:{}}:null}function nPe(e){return`(prediction: ${e})`}function KO(e){let t=/\(prediction:\s*([a-z0-9-]+)\s*\)/i.exec(e);return t?t[1].toLowerCase():null}function _n(e){let t=e.toLowerCase().replace(/đ/g,"d");try{t=t.normalize("NFD").replace(/[̀-ͯ]/g,"")}catch{}return t.replace(/[\s!-/:-@[-`{-~]+/g," ").trim()}function b2(e){if(typeof e!="string"||!e.trim())return null;let t=_n(e);for(let r of Kg)if([r.key,r.label,...r.aliases].map(_n).includes(t))return r;for(let r of Kg)if([r.key,r.label,...r.aliases].map(_n).some(i=>i.length>=4&&(t.startsWith(i)||i.startsWith(t))))return r;return null}var rzr=Kg.map(e=>e.key);m();var Md=1e-9,dv=e=>Math.floor(e*100+Md)/100,iPe=e=>Math.ceil(e*100-Md)/100;function Yg(e,t){return!t||!(t.rate>0)||!(e>0)||!(e<1)?0:t.rate*(e*(1-e))**t.exponent}function oPe(e,t,r){return t>0?e/(1+Yg(t,r)/t):e}function aPe(e,t,r){let n=[...e].sort((a,s)=>a.price-s.price),i=t,o=0;for(let a of n){if(i<=Md)break;if(!(a.price>0))continue;let s=1+Yg(a.price,r)/a.price,l=a.price*a.size,c=l*s;c>=i?(o+=i/s,i=0):(o+=l,i-=c)}return{notional:o,filled:i<=Md}}function sPe(e,t,r){return Math.max(0,t-Ox(e,t,r).feeUsd)}function uee(e,t,r){if(!(e>0)||e>1||!(t>0))return{usd:0,shares:0};let n=t*Yg(e,r),i=Number.isFinite(n)?Math.round(n*1e4)/1e4:0;return{usd:i,shares:i/e}}function dee(e,t,r){let n=Ox(e,t,r),i=n.shares>0?t/n.shares:0,o=n.filled?uee(i,n.shares,r):{usd:0,shares:0},a=Math.max(0,n.shares-o.shares);return{shares:a,usd:t,feeUsd:o.usd,avgPrice:a>0?t/a:0,worstPrice:n.worstPrice,filled:n.filled}}function pee(e,t,r,n,i=0){if(!(t>0))return e;let o=Yg(t,n)*(1+i/100),s=Math.min(e,r)/t*o;return r<=e+s?Math.max(r-s,0):e}function Ox(e,t,r){let n=[...e].sort((c,u)=>c.price-u.price),i=t,o=0,a=0,s=n[0]?.price??0;for(let c of n){if(i<=Md)break;let u=c.price*c.size;s=c.price;let d=u>=i?i/c.price:c.size;o+=d,a+=d*Yg(c.price,r),i=u>=i?0:i-u}let l=t-i;return{shares:o,usd:l,feeUsd:a,avgPrice:o>0?l/o:0,worstPrice:s,filled:i<=Md}}function fee(e,t,r){let n=[...e].sort((c,u)=>u.price-c.price),i=t,o=0,a=0,s=n[0]?.price??0;for(let c of n){if(i<=Md)break;let u=Math.min(i,c.size);s=c.price,o+=u*c.price,a+=u*Yg(c.price,r),i-=u}let l=t-i;return{shares:l,usd:o-a,feeUsd:a,avgPrice:l>0?o/l:0,worstPrice:s,filled:i<=Md}}function mee(e,t,r){return e?t.side==="BUY"?t.usd>0?Ox(e.asks,t.usd,r):null:t.shares>0?fee(e.bids,t.shares,r):null:null}function _2(e,t,r,n=zO.DEFAULT_SLIPPAGE){if(!(t>0))return e;let i=Math.max(0,Math.round(-Math.log10(t))),o=Math.round(e/t),a=r==="BUY"?Math.min(Math.ceil(o*(1+n)-Md),Math.round(1/t)-1):Math.max(Math.floor(o*(1-n)+Md),1);return Number((a*t).toFixed(i))}function lPe(e,t,r,n=zO.DEFAULT_SLIPPAGE,i="v1",o){let a=mee(t,r,o);if(!a||!t)return{error:Bm.ENTER_AMOUNT,quote:null};if(a.shares<=0)return{error:Bm.NO_LIQUIDITY,quote:a};if(r.side==="BUY"){let u=dv(r.usd),d=_2(a.worstPrice,t.tickSize,"BUY",n),p=typeof r.cash=="number"&&r.cash>=0?r.cash:null,h=p===null?u:dv(pee(u,d,p,o)),y=dee(t.asks,u,o);return u<zO.MIN_BUY_USD?{error:Bm.BELOW_MINIMUM,quote:y}:!y.filled||!Ox(t.asks,h,o).filled?{error:Bm.NOT_ENOUGH_LIQUIDITY,quote:y}:{quote:y,order:{tokenId:e,protocol:i,side:"BUY",amount:u,notional:h,maxPrice:d,...p===null?{}:{maxSpend:p}}}}let s=a,l=r.heldShares;if(l!==void 0&&r.shares>l+1e-6)return{error:Bm.EXCEEDS_HOLDING,quote:s,maxShares:dv(l)};if(!s.filled)return{error:Bm.NOT_ENOUGH_LIQUIDITY,quote:s,maxShares:dv(s.shares)};let c=dv(l!==void 0?Math.min(r.shares,l):r.shares);return c<=0?{error:Bm.TOO_SMALL,quote:s}:{quote:s,order:{tokenId:e,protocol:i,side:"SELL",shares:c,minPrice:_2(s.worstPrice,t.tickSize,"SELL",n)}}}function cPe(e,t){let r=t==="BUY"?e?.asks[0]:e?.bids[0];return r?r.price:null}function pv(e,t){return e.filter(r=>Number.isFinite(r.price)&&Number.isFinite(r.size)&&r.size>0).sort((r,n)=>t==="bids"?n.price-r.price:r.price-n.price)}m();Yq();var Gre="0x0000000000000000000000000000000000000000",Jq=(e,t)=>!!e&&!!t&&e.toLowerCase()===t.toLowerCase();function mc(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)}function IR(){return ti(Dd)}var ER=e=>e.toLowerCase();function zOe(e){return Hi.encode([{type:"address"},{type:"bytes32"}],[ER(fc.depositWalletFactory),di.padLeft(ER(e),32)])}function nwt(e,t){let r=BigInt((t.length-2)/2),n=Um.PREFIX+(r<<BigInt(56));return Kr.keccak256(di.concat(di.fromNumber(n,{size:10}),ER(e),"0x6009",Um.CONST2,Um.CONST1,t))}function iwt(e,t){let r=BigInt((t.length-2)/2),n=Um.BEACON_PREFIX+(r<<BigInt(56));return Kr.keccak256(di.concat(di.fromNumber(n,{size:10}),ER(e),Um.BEACON_CONST3,Um.BEACON_CONST2,Um.BEACON_CONST1,t))}function Wre(e){let t=zOe(e);return Su.fromCreate2({from:fc.depositWalletFactory,salt:Kr.keccak256(t),bytecodeHash:nwt(fc.depositWalletImplementation,t)})}function Kre(e,t){let r=zOe(e);return Su.fromCreate2({from:fc.depositWalletFactory,salt:Kr.keccak256(r),bytecodeHash:iwt(t,r)})}function Yre(e){return Su.fromCreate2({from:fc.safeFactory,salt:Kr.keccak256(Hi.encode([{type:"address"}],[ER(e)])),bytecodeHash:fc.safeInitCodeHash})}var AR=null;function owt(e){return AR||(AR=awt(e),AR.catch(()=>{AR=null})),AR}async function awt(e){try{let{data:t}=await e.call({to:fc.depositWalletFactory,data:fc.factoryBeaconSelector});return t&&t.length>=66?`0x${t.slice(-40)}`:Gre}catch(t){if(kj(t)!==void 0)return Gre;throw t}}async function PR(e,t){return await e.getCode({address:t})!==void 0}async function Jre(e,t=IR()){let r=Wre(e),n=await owt(t);return Jq(n,Gre)||await PR(t,r)?r:Kre(e,n)}async function Xq(e,t,r=IR()){if(t&&Jq(t,e))return{address:e,owner:e,kind:"profile",deployed:await PR(r,e)};let n=await Jre(e,r),i=Yre(e),[o,a]=await Promise.all([PR(r,n),PR(r,i)]);if(t){if(Jq(t,i))return{address:i,owner:e,kind:"safe",deployed:a};if(Jq(t,n))return{address:n,owner:e,kind:"deposit-wallet",deployed:o};if(await PR(r,t))return{address:t,owner:e,kind:"profile",deployed:!0}}return o?{address:n,owner:e,kind:"deposit-wallet",deployed:!0}:a?{address:i,owner:e,kind:"safe",deployed:!0}:{address:n,owner:e,kind:"deposit-wallet",deployed:!1}}async function CR(e,t=IR()){return t.readContract({address:mu,abi:Er,functionName:"balanceOf",args:[e]})}var swt=[{type:"function",name:"balanceOfBatch",stateMutability:"view",inputs:[{name:"accounts",type:"address[]"},{name:"ids",type:"uint256[]"}],outputs:[{name:"",type:"uint256[]"}]}];async function Qq(e,t,r=IR()){if(t.length===0)return{};let n=await r.readContract({address:jO,abi:swt,functionName:"balanceOfBatch",args:[t.map(()=>e),t.map(o=>BigInt(o))]}),i={};return t.forEach((o,a)=>{i[o]=Number(n[a]??BigInt(0))/10**hu}),i}async function iT(e,t=IR()){return Number(await CR(e,t))/10**hu}var Xm=class extends Error{constructor(r,n){super(n);g(this,"status");this.name="PolymarketApiError",this.status=r}},OR=3e4,RR=1e4,lwt=60*6e4,cwt=64,HOe=100,VOe=1e3,uwt=new Set([429,500,502,503,504]),ZOe=2,dwt=3e3,pwt={active:"true",archived:"false",closed:"false",featured_order:"true",order:"featuredOrder",ascending:"true"},GOe={closed:"false",order:"volume",ascending:"false",limit:"50"},fwt=50,mwt=5e3,hwt="1",gwt="64",WOe=e=>new Promise(t=>setTimeout(t,e));function KOe(e,t){let r=t?Number(t)*1e3:NaN;return Number.isFinite(r)&&r>=0?Math.min(r,dwt):400*2**e}async function e4(e,t){try{return await e}catch(r){if(XOe(r))throw r;return t}}function XOe(e){let t=e?.name,r=e?.code;return t==="AbortError"||t==="CanceledError"||r==="ERR_CANCELED"}var Br=class{constructor(t={}){g(this,"gamma");g(this,"data");g(this,"bridge");g(this,"builderCode");g(this,"clob");g(this,"web");g(this,"cache",new Map);g(this,"accounts",new Map);this.gamma=(t.gammaBaseUrl??Gg.GAMMA).replace(/\/+$/,""),this.data=(t.dataBaseUrl??Gg.DATA).replace(/\/+$/,""),this.bridge=(t.bridgeBaseUrl??Gg.BRIDGE).replace(/\/+$/,""),this.builderCode=t.builderCode,this.clob=(t.clobBaseUrl??Gg.CLOB).replace(/\/+$/,""),this.web=(t.webBaseUrl??Wg).replace(/\/+$/,"")}async listEvents({sort:t,tagId:r,limit:n}){let{order:i,ascending:o}=FO[t],a={closed:"false",order:i,ascending:String(o),limit:String(Math.min(Math.max(1,n),HOe))};r&&(a.tag_id=r),t==="ending_soon"&&(a.end_date_min=new Date(Math.floor(Date.now()/6e4)*6e4).toISOString()),(t==="ending_soon"||t==="competitive")&&(a.exclude_tag_id=[XQ]),t==="new"&&!r&&(a.exclude_tag_id=[QQ,eee]);let s=this.eventRows(a);if(t!=="trending"||r)return t4(await s);let l=Date.now(),[c,u,d,p,h]=await Promise.all([s,e4(this.eventRows({...pwt,limit:String(fwt)}),[]),e4(this.eventRows({...GOe,tag_id:hwt}),[]),e4(this.eventRows({...GOe,tag_id:gwt}),[]),e4(this.eventRows({slug:VAe(l),limit:"1"}).then(y=>y[0]??null),null)]);return t4(GAe({feed:c,featured:u,sports:[...d,...p],btc5m:h},l))}async eventRows(t){let r=await this.getJson(`${this.gamma}/events/keyset`,t,OR);return Array.isArray(r.events)?r.events:[]}async getUpDownPrices(t){let r=await this.getJson(`${this.web}/api/crypto/crypto-price`,JAe(t),mwt),n=i=>{let o=ar(i,null);return o!==null&&o>0?o:null};return{openPrice:n(r?.openPrice),closePrice:n(r?.closePrice),completed:r?.completed===!0}}async searchEvents(t,r){let n=t.trim();if(!n)return[];let o=((await this.getJson(`${this.gamma}/public-search`,{q:n,events_status:"active",limit_per_type:String(Math.min(Math.max(1,r),50)),keep_closed_markets:"0"},OR)).events??[]).map(l=>l.id).filter(l=>typeof l=="string"&&!!l);if(o.length===0)return[];let a=await this.getJson(`${this.gamma}/events/keyset`,{id:o,limit:String(Math.min(o.length,HOe))},OR),s=new Map(t4(a.events).map(l=>[l.id,l]));return o.map(l=>s.get(l)).filter(l=>l!==void 0)}async getEventBySlug(t){let r=await this.getJson(`${this.gamma}/events/keyset`,{slug:t,limit:"1"},OR);return t4(r.events)[0]??null}async getMarketTradeInfo(t){if(!/^0x[0-9a-fA-F]{64}$/.test(t))return null;let n=(await this.getJson(`${this.gamma}/markets/keyset`,{condition_ids:t,limit:"1"},OR)).markets?.[0];if(!n)return null;let i=VO(n);return i===null?null:{conditionId:t,protocol:i,fee:ZO(n),negRisk:n.negRisk===!0,open:GO(n),outcomes:rPe(n,i),question:(n.question??"").trim(),label:(n.groupItemTitle??"").trim(),eventTitle:(n.events?.[0]?.title??"").trim()}}async getProfileWallet(t){try{let r=await this.getJson(`${this.gamma}/public-profile`,{address:t},RR);return typeof r.proxyWallet=="string"&&r.proxyWallet?r.proxyWallet:null}catch(r){if(r instanceof Xm&&r.status===404)return null;throw r}}async resolveAccount(t){let r=t.toLowerCase(),n=this.accounts.get(r);if(n&&(n.account.deployed||Date.now()-n.at<RR))return n.account;let i=await Xq(t,await this.getProfileWallet(t));return this.accounts.set(r,{account:i,at:Date.now()}),i}async getCash(t){return iT(t)}async getShares(t,r){return Qq(t,r)}async getPositionsValue(t){let r=await this.getJson(`${this.data}/v2/value`,{user:t},RR);return ar(r?.data?.value,0)}async getPositions(t,r,n={}){let i=await this.getJson(`${this.data}/v2/positions`,{user:t,status:"OPEN",filter_type:"TOKENS",filter_amount:String(ree),sort_by:"CURRENT_VALUE",sort_direction:"DESC",limit:String(Math.min(Math.max(1,r),VOe))},n.fresh?0:RR);return JOe(i).map(vwt)}async getActivity(t,r){let n=await this.getJson(`${this.data}/v2/activity`,{user:t,type:tee.join(","),sort_direction:"DESC",limit:String(Math.min(Math.max(1,r),VOe))},RR);return JOe(n).map(wwt)}async getBridgeAssets(){return((await this.getJson(`${this.bridge}/supported-assets`,{},lwt)).supportedAssets??[]).map(kwt).filter(r=>r!==null)}async getDepositAddresses(t){let n=(await this.requestJson("POST",`${this.bridge}/deposit`,{body:{address:t},headers:{"X-Builder-Code":this.builderCode??Ix()}})).address??{},i=typeof n.evm=="string"&&/^0x[0-9a-fA-F]{40}$/.test(n.evm)?n.evm:"";if(!i)throw new Xm(502,"Bridge returned no EVM deposit address");return{evm:i,svm:Yr(n.svm),btc:Yr(n.btc),tron:Yr(n.tron)}}async createWithdrawalAddresses(t){let n=(await this.requestJson("POST",`${this.bridge}/withdraw`,{body:{address:t.wallet,toChainId:t.toChainId,toTokenAddress:t.toTokenAddress,recipientAddr:t.recipient},headers:{"X-Builder-Code":this.builderCode??Ix()}})).address??{},i=typeof n.evm=="string"&&/^0x[0-9a-fA-F]{40}$/.test(n.evm)?n.evm:"";if(!i)throw new Xm(502,"Bridge returned no EVM withdrawal address");return{evm:i,svm:Yr(n.svm),btc:Yr(n.btc),tron:Yr(n.tron)}}async getBridgeQuote(t){let r=await this.requestJson("POST",`${this.bridge}/quote`,{body:t}),n=r.estFeeBreakdown??{},i=Yr(r.estToTokenBaseUnit);if(!/^\d+$/.test(i))throw new Xm(502,"Bridge returned no quote");return{estToTokenBaseUnit:i,estOutputUsd:ar(r.estOutputUsd,0),estInputUsd:ar(r.estInputUsd,0),estCheckoutTimeMs:ar(r.estCheckoutTimeMs,null),minReceived:ar(n.minReceived,null),totalImpactUsd:ar(n.totalImpactUsd,0),totalImpactPercent:ar(n.totalImpact,0),quoteId:Yr(r.quoteId)}}async getBridgeTransfers(t){return/^0x[0-9a-fA-F]{40}$/.test(t)?((await this.requestJson("GET",`${this.bridge}/status/${t}`)).transactions??[]).map(xwt).sort((n,i)=>(i.createdTimeMs??0)-(n.createdTimeMs??0)):[]}async getOrderBook(t,r){let n=await this.requestJson("GET",`${this.clob}/book?${YOe({token_id:t})}`,{signal:r});return ywt(t,n)}getJson(t,r,n){let i=YOe(r),o=i?`${t}?${i}`:t,a=this.cache.get(o);if(a&&Date.now()-a.at<a.ttl)return a.value;let s=this.requestJson("GET",o);if(s.catch(()=>{this.cache.get(o)?.value===s&&this.cache.delete(o)}),this.cache.size>=cwt){let l=this.cache.keys().next().value;l!==void 0&&this.cache.delete(l)}return this.cache.set(o,{at:Date.now(),ttl:n,value:s}),s}async requestJson(t,r,n={}){for(let i=0;;i++){let o;try{o=await Qe.request(t,r,n.body,{...n.signal?{signal:n.signal}:{},headers:{...n.body!==void 0?{"Content-Type":"application/json"}:{},...n.headers}})}catch(a){if(XOe(a)||i>=ZOe)throw a;await WOe(KOe(i));continue}if(o.ok)return o.data;if(!uwt.has(o.status)||i>=ZOe)throw new Xm(o.status,It(o));await WOe(KOe(i,o.headers["retry-after"]))}}};function YOe(e){let t=[];for(let[r,n]of Object.entries(e))for(let i of Array.isArray(n)?n:[n])t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);return t.join("&")}function t4(e){return(Array.isArray(e)?e:[]).map(g2).filter(t=>t!==null)}var Yr=e=>typeof e=="string"?e:"";function ywt(e,t){let r=n=>(n??[]).map(i=>({price:ar(i.price,NaN),size:ar(i.size,NaN)}));return{tokenId:e,bids:pv(r(t.bids),"bids"),asks:pv(r(t.asks),"asks"),tickSize:ar(t.tick_size,.01),minOrderSize:ar(t.min_order_size,0),negRisk:t.neg_risk===!0,lastTradePrice:ar(t.last_trade_price,null),updatedAt:Date.now()}}var JOe=e=>Array.isArray(e?.data)?e.data:[],bwt="1970-01-01",_wt=999;function vwt(e){let t=Yr(e.end_date),r=ar(e.outcome_index,0);return{title:Yr(e.title),outcome:Yr(e.outcome),eventSlug:Yr(e.event_slug),conditionId:Yr(e.condition_id),asset:Yr(e.token_id),outcomeIndex:r===_wt?0:r,oppositeOutcome:Yr(e.opposite_outcome),oppositeAsset:Yr(e.opposite_token_id),icon:Yr(e.icon)||null,shares:ar(e.current_size,0),avgPrice:ar(e.avg_price,0),curPrice:ar(e.current_price,0),initialValue:ar(e.entry_cost_usdc,0),currentValue:ar(e.current_value,0),cashPnl:ar(e.unrealized_pnl,0),percentPnl:ar(e.percent_pnl,0),redeemable:e.redeemable===!0,endDate:t&&t!==bwt?t:null}}function wwt(e){let t=Yr(e.side).toUpperCase();return{type:Yr(e.type).toUpperCase(),side:t==="BUY"||t==="SELL"?t:null,title:Yr(e.title),outcome:Yr(e.outcome),eventSlug:Yr(e.event_slug),shares:ar(e.size,0),usd:ar(e.usdc_size,0),price:ar(e.price,0),timestamp:ar(e.timestamp,0),transactionHash:Yr(e.transaction_hash)}}var Swt="0x0000000000000000000000000000000000000000";function kwt(e){let t=e.token??{},r=Yr(t.address).toLowerCase(),n=ar(t.decimals,NaN);return!e.chainId||!r||!Number.isInteger(n)?null:{chainId:String(e.chainId),chainName:Yr(e.chainName),symbol:Yr(t.symbol),name:Yr(t.name),address:r===UO?Swt:r,decimals:n,minUsd:ar(e.minCheckoutUsd,0)}}function xwt(e){return{fromChainId:String(e.fromChainId??""),fromTokenAddress:Yr(e.fromTokenAddress).toLowerCase(),fromAmountBaseUnit:String(e.fromAmountBaseUnit??"0"),toChainId:String(e.toChainId??""),status:Yr(e.status).toUpperCase(),txHash:Yr(e.txHash)||null,createdTimeMs:ar(e.createdTimeMs,null)}}m();m();m();bg();Sg();function Xre(e,t,r,n,i){let o=`${t}${r}${n}${i??""}`,a=ba(Rs,Awt(e),new TextEncoder().encode(o));return Pwt(a).replace(/\+/g,"-").replace(/\//g,"_")}function Hd(e){return typeof e?.authorize=="function"?e:Qre(e)}var Twt=["POLY_BUILDER_API_KEY","POLY_BUILDER_PASSPHRASE","POLY_BUILDER_SIGNATURE","POLY_BUILDER_TIMESTAMP"];function QOe(e){return{isBuilderKey:!0,supportGasless:!0,async authorize({method:t,path:r,body:n}){let i=typeof e.headers=="function"?await e.headers():e.headers,o=await fetch(e.url,{method:"POST",headers:{...i??{},"Content-Type":"application/json"},body:JSON.stringify({method:t,path:r,body:n}),credentials:e.credentials});if(!o.ok)throw new Error(`Remote builder signer rejected the request (${o.status})`);let a=await o.json(),s={};for(let l of Twt){let c=a?.[l];if(typeof c!="string"||!c)throw new Error(`Remote builder signer answered without ${l}`);s[l]=c}return s}}}function Qre(e){return{isBuilderKey:!0,supportGasless:!0,async authorize({method:t,path:r,body:n}){let i=Math.floor(Date.now()/1e3);return{POLY_BUILDER_API_KEY:e.key,POLY_BUILDER_PASSPHRASE:e.passphrase,POLY_BUILDER_SIGNATURE:Xre(e.secret,i,t,r,n),POLY_BUILDER_TIMESTAMP:String(i)}}}}function Awt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)n[i]=r.charCodeAt(i);return n}function Pwt(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}m();var Ewt=new Set(["STATE_CONFIRMED","STATE_FAILED","STATE_INVALID"]),Iwt=e=>new Promise(t=>setTimeout(t,e));async function eRe(e,t={}){let r=await fetch(`${Gg.RELAYER}${e}`,t),n=await r.text(),i;try{i=n?JSON.parse(n):null}catch{i=null}if(!r.ok){let o=i?.error||n||`HTTP ${r.status}`;throw new Error(`Relayer ${t.method??"GET"} ${e} failed (${r.status}): ${o}`)}return i}async function Cwt(e,t,r){let n=JSON.stringify({type:"WALLET-CREATE",from:e,to:fc.depositWalletFactory,metadata:"Deploy Deposit Wallet"}),i=await Hd(t).authorize({method:"POST",path:l2,body:n});return eRe(l2,{method:"POST",headers:{"Content-Type":"application/json",...i},body:n,signal:r})}async function Owt(e,t){let r=Date.now();for(;Date.now()-r<c2.TIMEOUT_MS;){let n=await eRe(`/transaction?id=${encodeURIComponent(e)}`,{signal:t}),i=Array.isArray(n)?n[0]:null;if(!i)throw new Error("Relayer transaction not found");if(Ewt.has(i.state))return i;if(t?.aborted)throw new Error("Cancelled");await Iwt(c2.INTERVAL_MS)}throw new Error("Deploy timed out")}async function r4(e,t,r){let n=await Cwt(e,t,r),i=await Owt(n.transactionID,r);if(i.state!=="STATE_CONFIRMED")throw new Error(`Deposit wallet deployment failed: ${i.error_msg||i.state}`);return{transactionHash:i.transactionHash,proxyAddress:i.proxyAddress,state:i.state}}m();var k5=null;function zBt(){let e=globalThis.URLSearchParams;typeof e!="function"||"size"in e.prototype||Object.defineProperty(e.prototype,"size",{configurable:!0,get(){let t=0;return this.forEach(()=>{t+=1}),t}})}function Hy(){return zBt(),k5??(k5=Promise.all([Promise.resolve().then(()=>(NHe(),$He)),Promise.resolve().then(()=>(MHe(),DHe))]).then(([e,t])=>({sdk:e,actions:t}))),k5.catch(()=>{k5=null}),k5}var LHe=20,HBt=5e3,VBt=5*6e4,x5=new Map;function ZBt(e){let t=x5.get(e);if(t)return t;let r=new AbortController,n=setTimeout(()=>r.abort(),HBt),i=Array.from({length:LHe},(a,s)=>({jsonrpc:"2.0",id:s+1,method:"eth_chainId",params:[]})),o=fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i),signal:r.signal}).then(async a=>{if(!a.ok)return!1;let s=await a.json();return Array.isArray(s)&&s.length===LHe&&s.every(l=>l&&typeof l=="object"&&"result"in l&&!("error"in l))}).catch(()=>!1).finally(()=>clearTimeout(n));return x5.set(e,o),o.then(a=>{a||setTimeout(()=>x5.get(e)===o&&x5.delete(e),VBt)}),o}function GBt(){let e=J_()[Dd],t=xo(Dd)?.rpcUrls.default.http??[];return[...new Set([...e?[e]:[],...t,...Rm(Dd)])]}async function UHe(){let e=GBt();for(let t of e)if(await ZBt(t))return t;return e[0]}async function g0(){let[{sdk:e},t]=await Promise.all([Hy(),UHe()]);return t?e.forkEnvironmentConfig({name:"production",rpc:t},e.production):e.production}var $fe=new Map,T5=async()=>{let e=await UHe(),t=e??"",r=$fe.get(t);return r||(r=Hy().then(({sdk:n})=>n.createPublicClient({environment:e?n.forkEnvironmentConfig({name:"production",rpc:e},n.production):n.production})),r.catch(()=>$fe.delete(t)),$fe.set(t,r)),r};m();function Vy(e){return{async getAddress(){return e.address},async signTypedData(t){let{EIP712Domain:r,...n}=t.types;return await e.signTypedData({...t,types:n})},async signMessage(t){if(!e.signMessage)throw new Error("Polymarket signer: signMessage is not supported by this wallet");return await e.signMessage(t)},async sendTransaction(){throw new Error("Polymarket signer: direct transactions are not supported \u2014 use the gasless relayer")}}}var jHe=(BigInt(1)<<BigInt(256))-BigInt(1),qHe=[{type:"function",name:"isApprovedForAll",stateMutability:"view",inputs:[{name:"account",type:"address"},{name:"operator",type:"address"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]}];async function A5(e){let t=await g0(),[r,n]=await Promise.all([T5().then(u=>u.fetchTradingApprovalsState({user:e})),WBt(e,t)]),i=new Set(KBt(t).map(u=>u.toLowerCase())),o=(r.missing?.erc20??[]).map(u=>({tokenAddress:u.tokenAddress,spenderAddress:u.spenderAddress})).filter(u=>!i.has(String(u.spenderAddress).toLowerCase())),a=(r.missing?.erc1155??[]).map(u=>({tokenAddress:u.tokenAddress,operatorAddress:u.operatorAddress})).filter(u=>!i.has(String(u.operatorAddress).toLowerCase())),s=(u,d)=>`${u.toLowerCase()}:${d.toLowerCase()}`,l=new Set(o.map(u=>s(u.tokenAddress,u.spenderAddress))),c=new Set(a.map(u=>s(u.tokenAddress,u.operatorAddress)));for(let u of n.erc20)l.has(s(u.tokenAddress,u.spenderAddress))||o.push(u);for(let u of n.erc1155)c.has(s(u.tokenAddress,u.operatorAddress))||a.push(u);return{isFullyApproved:o.length===0&&a.length===0,missing:{erc20:o,erc1155:a}}}async function WBt(e,t){let r=t?.contracts??{},n=(c,u)=>typeof c=="string"&&c?c:u,i=n(r.negRiskAdapter,YQ),o=n(r.collateralToken,mu),a=n(r.conditionalTokens,jO),[s,l]=await ti(Dd).multicall({contracts:[{address:o,abi:Er,functionName:"allowance",args:[e,i]},{address:a,abi:qHe,functionName:"isApprovedForAll",args:[e,i]}],allowFailure:!1});return{erc20:s<jHe?[{tokenAddress:o,spenderAddress:i}]:[],erc1155:l?[]:[{tokenAddress:a,operatorAddress:i}]}}function KBt(e){let t=e?.contracts?.perpsDepositContract;return[typeof t=="string"&&t?t:KQ]}async function wp(e,t=new Br){let r=await t.resolveAccount(e),n=r.deployed?await A5(r.address):null;return{account:r,approvals:n}}function FHe(e){return e.isDeployed?e.isTradingEnabled?e.isApproved?Ao.DONE:Ao.APPROVE:Ao.ENABLE_TRADING:Ao.DEPLOY}function Nfe(e){return[...e.erc20.map(t=>({to:t.tokenAddress,data:sr({abi:Er,functionName:"approve",args:[t.spenderAddress,jHe]})})),...e.erc1155.map(t=>({to:t.tokenAddress,data:sr({abi:qHe,functionName:"setApprovalForAll",args:[t.operatorAddress,!0]})}))]}var Ah=class extends Error{constructor(r,n,i){super(n);g(this,"step");this.name="PolymarketOnboardingError",this.step=r,i!==void 0&&(this.cause=i)}};async function zHe(e){let t=e.service??new Br,r=e.tracking??{intervalMs:u2.INTERVAL_MS,maxAttempts:u2.MAX_ATTEMPTS},n=Vy(e.signer),i=e.chain?.approvals??A5,o=b=>{YBt(e.signal,b),e.onStep?.(b)},a=await t.resolveAccount(e.signer.address);if(a.kind==="profile")throw new Ah(Ao.ENABLE_TRADING,"This address is a Polymarket account wallet, not a wallet that can sign for one.");let s=e.chain?.isDeployed??(async b=>await ti(Dd).getCode({address:b})!==void 0);a.deployed||(o(Ao.DEPLOY),await aP(Ao.DEPLOY,async()=>{await r4(e.signer.address,e.builder,e.signal),await BHe(()=>s(a.address),b=>b,r,e.signal)}),a={...a,deployed:!0});let{sdk:l,actions:c}=await Hy(),u=Hd(e.builder),d=await g0();o(Ao.ENABLE_TRADING);let p=await aP(Ao.ENABLE_TRADING,()=>l.createSecureClient({environment:d,signer:n,apiKey:u,wallet:a.address,...e.credentials?{credentials:{...e.credentials}}:{}})),h=cD(p);if(!h)throw new Ah(Ao.ENABLE_TRADING,"No CLOB credentials were issued.");await aP(Ao.ENABLE_TRADING,async()=>e.onCredentials?.(h));let y=await aP(Ao.APPROVE,()=>i(a.address));return y.isFullyApproved||(o(Ao.APPROVE),y=await aP(Ao.APPROVE,async()=>{let b=Nfe(y.missing),_=await c.prepareGaslessTransaction(p,{calls:b,metadata:JQ});return await(await JBt(_,n)).wait(),BHe(()=>i(a.address),S=>S.isFullyApproved,r,e.signal)})),await aP(Ao.APPROVE,()=>c.updateBalanceAllowance(p,{assetType:"COLLATERAL"})),o(Ao.DONE),{account:a,credentials:h,approvals:y}}function cD(e){let{key:t,secret:r,passphrase:n}=e?.credentials??{};return typeof t=="string"&&t&&typeof r=="string"&&r&&typeof n=="string"&&n?{key:t,secret:r,passphrase:n}:null}async function aP(e,t){try{return await t()}catch(r){if(r instanceof Ah)throw r;let n=r instanceof Error&&r.message?r.message:String(r);throw new Ah(e,n,r)}}function YBt(e,t){if(e?.aborted)throw new Ah(t,"Cancelled")}async function BHe(e,t,r,n){for(let i=1;;i++){let o=await e();if(t(o))return o;if(i>=r.maxAttempts)throw new Error("Not confirmed on-chain yet \u2014 please try again in a moment.");if(n?.aborted)throw new Error("Cancelled");await new Promise(a=>setTimeout(a,r.intervalMs))}}async function JBt(e,t){let r=await e.next();for(;!r.done;){let n=r.value;try{switch(n.kind){case"requestAddress":r=await e.next(await t.getAddress());break;case"signGaslessTypedData":r=await e.next(await t.signTypedData(n.payload));break;case"signGaslessMessage":r=await e.next(await t.signMessage(n.payload));break;default:throw new Error(`Unsupported gasless workflow request: ${String(n.kind)}`)}}catch(i){r=await e.throw(i)}}return r.value}m();var HHe=new Set(qO),XBt="0x0000000000000000000000000000000000000000";function Dfe(e){return e.filter(t=>/^\d+$/.test(t.chainId)&&Number(t.chainId)>0&&Number(t.chainId)<2**32&&t.address!==XBt&&/^0x[0-9a-f]{40}$/.test(t.address)&&HHe.has(t.symbol.toUpperCase()))}async function P5(e,t){let r=new Map;for(let i of Dfe(t)){let o=Number(i.chainId),a=r.get(o)??[];a.some(s=>s.address===i.address)||a.push(i),r.set(o,a)}return(await Promise.allSettled([...r.entries()].map(async([i,o])=>{let a=`0x${i.toString(16)}`,l=await ti(a).multicall({contracts:o.flatMap(c=>[{address:c.address,abi:Er,functionName:"balanceOf",args:[e]},{address:c.address,abi:Er,functionName:"decimals"}]),allowFailure:!0});return o.flatMap((c,u)=>{let d=l[2*u],p=l[2*u+1],h=d?.status==="success"&&typeof d.result=="bigint"?d.result:BigInt(0),y=p?.status==="success"&&(typeof p.result=="number"||typeof p.result=="bigint")?Number(p.result):NaN;return h<=BigInt(0)||!Number.isInteger(y)?[]:[{chainId:i,chainHex:a,chainName:ye(a)||c.symbol,tokenAddress:c.address,symbol:c.symbol,decimals:y,balance:Wk(h,y),minUsd:c.minUsd}]})}))).flatMap(i=>i.status==="fulfilled"?i.value:[]).sort((i,o)=>Number(o.balance)-Number(i.balance))}var QBt=e=>/^\d+$/.test(e)&&Number(e)>0&&Number(e)<2**32&&!(e in lv);function E5(e){let t=i=>{let o=Xo.CHAIN_ORDER.indexOf(i);return o===-1?Xo.CHAIN_ORDER.length:o},r=i=>{let o=qO.indexOf(i.toUpperCase());return o===-1?qO.length:o},n=new Set;return e.filter(i=>QBt(i.chainId)&&/^0x[0-9a-f]{40}$/.test(i.address)&&i.symbol).filter(i=>{let o=`${i.chainId}:${i.address}`;return n.has(o)?!1:(n.add(o),!0)}).map(i=>({chainId:i.chainId,chainName:i.chainName,symbol:i.symbol,tokenAddress:i.address,decimals:i.decimals,minUsd:i.minUsd,stable:HHe.has(i.symbol.toUpperCase())})).sort((i,o)=>t(i.chainId)-t(o.chainId)||i.chainName.localeCompare(o.chainName)||r(i.symbol)-r(o.symbol)||i.symbol.localeCompare(o.symbol))}async function uD(e,t=new Br){let r=Nm(String(e.amount??"").trim(),e.asset.decimals);if(r===null||r<=BigInt(0))throw new Error("Enter an amount");let n=await t.getBridgeQuote({fromAmountBaseUnit:r.toString(),fromChainId:e.asset.chainId,fromTokenAddress:e.asset.tokenAddress,recipientAddress:e.wallet,toChainId:BO,toTokenAddress:mu});return{estInputUsd:n.estInputUsd,estOutputUsd:n.estOutputUsd,priceImpactPercent:n.totalImpactPercent,totalFeeUsd:n.totalImpactUsd,minReceivedUsd:n.minReceived,estTimeMs:n.estCheckoutTimeMs}}var Mfe=100;async function VHe(e,t,r=new Br){let n=Math.max(Mfe,e.minUsd||0);if(e.stable)return uD({asset:e,amount:String(n),wallet:t},r);let i=await uD({asset:e,amount:"1",wallet:t},r);if(!(i.estInputUsd>0))return i;let o=(n/i.estInputUsd).toFixed(Math.min(e.decimals,8));return uD({asset:e,amount:o,wallet:t},r)}m();var Hl=e=>{let t=typeof e=="number"?e:Number.parseFloat(String(e??""));return Number.isFinite(t)?t:NaN},I5=e=>{let t=Hl(e);return Number.isFinite(t)?String(t):""};function ZHe(e,t){return pv([...e.entries()].map(([r,n])=>({price:Number(r),size:n})),t)}function ejt(e){return{bids:new Map(e.bids.map(t=>[I5(t.price),t.size])),asks:new Map(e.asks.map(t=>[I5(t.price),t.size])),tickSize:e.tickSize,minOrderSize:e.minOrderSize,negRisk:e.negRisk,lastTradePrice:e.lastTradePrice,updatedAt:e.updatedAt}}function tjt(e,t){return{tokenId:e,bids:ZHe(t.bids,"bids"),asks:ZHe(t.asks,"asks"),tickSize:t.tickSize,minOrderSize:t.minOrderSize,negRisk:t.negRisk,lastTradePrice:t.lastTradePrice,updatedAt:t.updatedAt}}function Lfe(e,t,r=Date.now()){let n=t?.payload??{};switch(t?.type){case"book":{let i=e.get(String(n.assetId));if(!i)return!1;let o=a=>[I5(a.price),Hl(a.size)];return i.bids=new Map((n.bids??[]).map(o).filter(([a,s])=>a&&s>0)),i.asks=new Map((n.asks??[]).map(o).filter(([a,s])=>a&&s>0)),Number.isFinite(Hl(n.tickSize))&&(i.tickSize=Hl(n.tickSize)),Number.isFinite(Hl(n.minOrderSize))&&(i.minOrderSize=Hl(n.minOrderSize)),typeof n.negRisk=="boolean"&&(i.negRisk=n.negRisk),Number.isFinite(Hl(n.lastTradePrice))&&(i.lastTradePrice=Hl(n.lastTradePrice)),i.updatedAt=r,!0}case"price_change":{let i=!1;for(let o of n.priceChanges??[]){let a=e.get(String(o.assetId)),s=I5(o.price);if(!a||!s)continue;let l=String(o.side).toUpperCase()==="BUY"?a.bids:a.asks,c=Hl(o.size);c>0?l.set(s,c):l.delete(s),a.updatedAt=r,i=!0}return i}case"last_trade_price":{let i=e.get(String(n.assetId));return!i||!Number.isFinite(Hl(n.price))?!1:(i.lastTradePrice=Hl(n.price),i.updatedAt=r,!0)}case"tick_size_change":{let i=e.get(String(n.assetId));return!i||!Number.isFinite(Hl(n.newTickSize))?!1:(i.tickSize=Hl(n.newTickSize),i.updatedAt=r,!0)}default:return!1}}function GHe(e,t){let r=[...new Set(e.filter(Boolean))],n=t.service??new Br,i=t.throttleMs??HO.THROTTLE_MS,o=t.staleMs??HO.STALE_MS,a=t.fallbackPollMs??HO.FALLBACK_POLL_MS,s=new Map,l=new AbortController,c=!1,u=null,d=null,p=Date.now(),h=0,y=null,b=null,_=null,v=I=>{u!==I&&(u=I,t.onStatus?.(I))},S=()=>{let I={};for(let[D,q]of s)I[D]=tjt(D,q);return I},w=()=>{c||(y&&clearTimeout(y),y=null,h=Date.now(),t.onUpdate(S()))},k=()=>{if(c||y)return;let I=i-(Date.now()-h);I<=0?w():y=setTimeout(w,I)},T=()=>(_??(_=Promise.all(r.map(async I=>{try{let D=await n.getOrderBook(I,l.signal);s.set(I,ejt(D))}catch(D){c||t.onError?.(D)}})).then(()=>(p=Date.now(),w(),S())).finally(()=>{_=null})),_),O=I=>new Promise(D=>{let q=setTimeout(D,I);l.signal.addEventListener("abort",()=>{clearTimeout(q),D()})}),$=async()=>{for(v("connecting"),await T();!c;){try{let I=await T5();if(c)break;if(d=await I.subscribe([{topic:"market",assetIds:r,customFeatureEnabled:!1}]),c){d.close();break}v("live");for await(let D of d){if(c)break;p=Date.now(),Lfe(s,D,p)&&k()}}catch(I){c||t.onError?.(I)}if(d=null,c)break;v("polling"),await T(),await O(a)}};return b=setInterval(()=>{!c&&Date.now()-p>o&&T()},Math.max(1e3,Math.floor(o/2))),$(),{refresh:T,stop(){c||(c=!0,l.abort(),y&&clearTimeout(y),b&&clearInterval(b),d?.close(),v("stopped"))}}}m();m();var rjt=(e,t)=>!!e&&!!t&&e.key===t.key&&e.secret===t.secret&&e.passphrase===t.passphrase;async function sP(e){let{sdk:t}=await Hy(),r=await t.createSecureClient({environment:await g0(),signer:Vy(e.signer),apiKey:Hd(e.builder),wallet:e.wallet,...e.credentials?{credentials:{...e.credentials}}:{}}),n=cD(r);return n&&!rjt(n,e.credentials)&&await e.onCredentials?.(n),r}function lP(e){let t=e??{},r=String(t.message??"");return t.name==="CancelledSigningError"||/user (rejected|denied)|cancel(l)?ed/i.test(r)&&!/order (was )?cancel/i.test(r)}var Zy=class extends Error{constructor(r,n,i){super(n);g(this,"code");this.name="PolymarketTradeError",this.code=r,i!==void 0&&(this.cause=i)}},njt=15e3,WHe={unmatched:jn.NOT_FILLED,fak_not_filled:jn.NOT_FILLED,fok_not_filled:jn.NOT_FILLED,insufficient_balance_or_allowance:jn.INSUFFICIENT_BALANCE,market_not_ready:jn.MARKET_CLOSED,post_only_mode:jn.TRADING_PAUSED},ijt=[[/not enough balance \/ allowance/i,jn.INSUFFICIENT_BALANCE],[/lower than the minimum/i,jn.BELOW_MIN_SIZE],[/closed only mode/i,jn.CLOSE_ONLY],[/address banned/i,jn.ACCOUNT_BANNED],[/no orders found to match|couldn't be fully filled|not filled/i,jn.NOT_FILLED],[/not yet ready to process|market (is )?(closed|not active|resolved)|orderbook .* does not exist/i,jn.MARKET_CLOSED],[/post-only mode|trading is (currently )?(paused|disabled)|cancel-only/i,jn.TRADING_PAUSED]],ojt=e=>/not enough balance \/ allowance/i.test(String(e?.message??""));function Bfe(e){if(e instanceof Zy)return e;let t=e??{},r=t.message||String(e),n=ijt.find(([o])=>o.test(r))?.[1],i=n===jn.CLOSE_ONLY||n===jn.ACCOUNT_BANNED?n:/restrict|region|geoblock|jurisdiction|not available in your/i.test(r)||t.status===403&&!t.restriction?jn.REGION_RESTRICTED:t.restriction?jn.TRADING_PAUSED:t.name==="InsufficientLiquidityError"?jn.NOT_ENOUGH_LIQUIDITY:lP(e)?jn.CANCELLED:(n??(t.code&&WHe[t.code]))||jn.FAILED;return new Zy(i,r,e)}var ajt=(e,t)=>!!e&&!!t&&e.key===t.key&&e.secret===t.secret&&e.passphrase===t.passphrase,Ufe=e=>{let t=Number.parseFloat(String(e??""));return Number.isFinite(t)?t:0};async function KHe(e){let{order:t}=e;try{let{sdk:r,actions:n}=await Hy(),i=await r.createSecureClient({environment:await g0(),signer:Vy(e.signer),apiKey:Hd(e.builder),wallet:e.wallet,...e.credentials?{credentials:{...e.credentials}}:{}}),o=cD(i);o&&!ajt(o,e.credentials)&&await e.onCredentials?.(o);let a=e.builderCode??Ix(),s=t.side==="BUY"?{assetId:t.tokenId,side:r.OrderSide.BUY,amount:t.notional&&t.notional>0?t.notional:t.amount,...t.maxSpend!==void 0&&t.maxSpend>0?{maxSpend:t.maxSpend}:{},maxPrice:t.maxPrice,builderCode:a,orderType:r.OrderType.FAK}:{assetId:t.tokenId,side:r.OrderSide.SELL,shares:t.shares,minPrice:t.minPrice,builderCode:a,orderType:r.OrderType.FAK},c=await(async()=>{try{return await i.placeMarketOrder(s)}catch(y){if(ojt(y))return{ok:!1,code:"insufficient_balance_or_allowance",error:y};throw y}})();if(!c.ok&&c.code==="insufficient_balance_or_allowance"&&(await n.updateBalanceAllowance(i,sjt(t)),c=await i.placeMarketOrder(s)),!c.ok)throw new Zy(WHe[c.code]??jn.FAILED,c.message||c.code||"Order rejected");if(String(c.status).toLowerCase()===C5.DELAYED)return await ljt(i,String(c.orderId),t,e.delayedTimeoutMs);let u=Ufe(c.makingAmount),d=Ufe(c.takingAmount),p=Array.isArray(c.transactionsHashes)?c.transactionsHashes:[],h=e.settlementTimeoutMs??njt;if(p.length===0&&h>0&&(c.tradeIds?.length??0)>0){let y;p=await Promise.race([n.waitForOrderFillSettlement(i,c).catch(()=>[]),new Promise(b=>{y=setTimeout(()=>b([]),h)})]).finally(()=>clearTimeout(y))}return{orderId:String(c.orderId),status:String(c.status),pending:!1,side:t.side,shares:t.side==="BUY"?d:u,usd:t.side==="BUY"?u:d,transactionHashes:p}}catch(r){throw Bfe(r)}}var C5={DELAYED:"delayed",LIVE:"live",MATCHED:"matched",UNMATCHED:"unmatched"};function sjt(e){return e.side==="BUY"?{assetType:"COLLATERAL"}:{assetType:e.protocol==="v2"?"CONDITIONAL-V2":"CONDITIONAL",assetId:e.tokenId}}async function ljt(e,t,r,n){let i=Date.now()+(n??d2.TIMEOUT_MS);for(;;){await new Promise(c=>setTimeout(c,d2.POLL_MS));let o=null;try{o=await e.fetchOrder({orderId:t})}catch{}let a=String(o?.status??"").toLowerCase(),s=Ufe(o?.sizeMatched),l=!!o&&!a.includes(C5.DELAYED);if(l&&s>0)return{orderId:t,status:C5.MATCHED,pending:!1,side:r.side,shares:s,usd:null,transactionHashes:[]};if(l)throw new Zy(jn.NOT_FILLED,`Delayed order ${t} ended unmatched (${a})`);if(Date.now()>=i)return{orderId:t,status:C5.DELAYED,pending:!0,side:r.side,shares:0,usd:null,transactionHashes:[]}}}m();var Ku=class extends Error{constructor(r,n,i){super(n);g(this,"code");this.name="PolymarketWithdrawError",this.code=r,i!==void 0&&(this.cause=i)}},YHe=/^0x[0-9a-fA-F]{40}$/,cjt="0x0000000000000000000000000000000000000000",JHe=e=>e.toLowerCase()===cjt?UO:e;function O5(e){let t=i=>{let o=Xo.CHAIN_ORDER.indexOf(i);return o===-1?Xo.CHAIN_ORDER.length:o},r=i=>{let o=Xo.STABLE_SYMBOLS.indexOf(i);return o===-1?Xo.STABLE_SYMBOLS.length:o},n=new Set;return e.filter(i=>!(i.chainId in lv)).filter(i=>YHe.test(i.address)&&i.address.toLowerCase()!==mu.toLowerCase()).filter(i=>{let o=`${i.chainId}:${i.address.toLowerCase()}`;return n.has(o)?!1:(n.add(o),!0)}).sort((i,o)=>t(i.chainId)-t(o.chainId)||i.chainName.localeCompare(o.chainName)||r(i.symbol.toUpperCase())-r(o.symbol.toUpperCase())||i.symbol.localeCompare(o.symbol)).map(i=>({chainId:i.chainId,chainName:i.chainName,tokenAddress:i.address,symbol:i.symbol,decimals:i.decimals,minUsd:i.minUsd}))}function R5(e,t){return typeof t=="number"&&t>0?e<BigInt(Math.round(t*10**hu)):!1}async function ujt(e,t){if(typeof e.minUsd=="number")return e.minUsd;let r=e.tokenAddress.toLowerCase();return(await t.getBridgeAssets()).find(i=>i.chainId===e.chainId&&i.address.toLowerCase()===r)?.minUsd??0}function XHe(e){return new Ku(Xo.ERROR.BELOW_MINIMUM,`Below the bridge minimum of $${e} for this destination`)}function $5(e){let t=String(e??"").trim(),r=/^(\d+)(?:\.(\d+))?$/.exec(t);if(!r)return null;let[,n,i=""]=r;if(i.length>hu)return null;let o=BigInt(n)*BigInt(10)**BigInt(hu)+BigInt(i.padEnd(hu,"0")||"0");return o>BigInt(0)?o:null}function jfe(e){let t=BigInt(10)**BigInt(hu),r=e/t,n=(e%t).toString().padStart(hu,"0").replace(/0+$/,"");return n?`${r}.${n}`:r.toString()}async function QHe(e,t=new Br){let r=$5(e.amount);if(r===null)throw new Ku(Xo.ERROR.INVALID_AMOUNT,"Enter an amount");let n=e.destination.minUsd;if(R5(r,n))throw XHe(n);let i=await t.getBridgeQuote({fromAmountBaseUnit:r.toString(),fromChainId:BO,fromTokenAddress:mu,recipientAddress:e.recipient,toChainId:e.destination.chainId,toTokenAddress:JHe(e.destination.tokenAddress)});return{estOutputBaseUnit:i.estToTokenBaseUnit,estOutputUsd:i.estOutputUsd,minReceivedUsd:i.minReceived,totalFeeUsd:i.totalImpactUsd,estTimeMs:i.estCheckoutTimeMs}}async function e3e(e){let t=e.service??new Br,r=$5(e.amount);if(r===null)throw new Ku(Xo.ERROR.INVALID_AMOUNT,"Enter an amount");if(!YHe.test(e.recipient))throw new Ku(Xo.ERROR.FAILED,`Invalid recipient ${e.recipient}`);try{let n=await ujt(e.destination,t);if(R5(r,n))throw XHe(n);let i=await CR(e.wallet);if(i<r)throw new Ku(Xo.ERROR.INSUFFICIENT_BALANCE,`Cash ${jfe(i)} is below ${e.amount}`);let o=await sP(e),a=await t.createWithdrawalAddresses({wallet:e.wallet,toChainId:e.destination.chainId,toTokenAddress:JHe(e.destination.tokenAddress),recipient:e.recipient}),l=await(await o.transferErc20({tokenAddress:mu,recipientAddress:a.evm,amount:r})).wait();return{bridgeAddress:a.evm,transactionHash:typeof l?.transactionHash=="string"?l.transactionHash:null,amountBaseUnit:r.toString()}}catch(n){throw qfe(n)}}function qfe(e){if(e instanceof Ku)return e;let t=e?.message||String(e),r=lP(e)?Xo.ERROR.CANCELLED:/insufficient|exceeds balance|not enough balance/i.test(t)?Xo.ERROR.INSUFFICIENT_BALANCE:Xo.ERROR.FAILED;return new Ku(r,t,e)}m();var Gy=class extends Error{constructor(r,n,i){super(n);g(this,"code");this.name="PolymarketRedeemError",this.code=r,i!==void 0&&(this.cause=i)}};async function t3e(e){let t=e.service??new Br;if(!/^0x[0-9a-fA-F]{64}$/.test(e.conditionId))throw new Gy(cv.ERROR.FAILED,`Invalid condition id ${e.conditionId}`);try{if((await t.getPositions(e.wallet,cv.POSITIONS_READ_LIMIT,{fresh:!0})).filter(s=>s.conditionId.toLowerCase()===e.conditionId.toLowerCase()&&s.redeemable&&s.shares>0).length===0)throw new Gy(cv.ERROR.NOTHING_TO_CLAIM,"Nothing left to redeem in this market");let a=await(await(await sP(e)).redeemPositions({conditionId:e.conditionId})).wait();return{transactionHash:typeof a?.transactionHash=="string"?a.transactionHash:null}}catch(r){if(r instanceof Gy)throw r;let n=r?.message||String(r);throw new Gy(lP(r)?cv.ERROR.CANCELLED:cv.ERROR.FAILED,n,r)}}m();m();var djt=6,pjt=.6,fjt=.1,mjt=200,hjt=8,y0=new Map;function r3e(e,t){let r=_n(e);if(r.length<hjt||!t)return;let n=y0.get(r)??new Set;n.add(t),y0.delete(r),y0.set(r,n),y0.size>mjt&&y0.delete(y0.keys().next().value)}function gjt(e,t){let r=_n(e),n=_n(t),i=null;for(let[o,a]of y0)(r===o||n!==""&&` ${n} `.includes(` ${o} `))&&(!i||o.length>i.title.length)&&(i={title:o,slugs:a});return i&&i.slugs.size===1?[...i.slugs][0]:null}async function N5(e,t,r){let n=KO(t)??WO(t)?.eventSlug??KO(r)??WO(r)?.eventSlug??gjt(t,r)??null;if(n){let c=await e.getEventBySlug(n);return c?{kind:"event",event:c}:{kind:"not_found",query:t||n}}if(!t)return{kind:"unnamed"};let i=(await e.searchEvents(t,djt)).filter(c=>c.markets.some(u=>u.open));if(i.length===0)return{kind:"not_found",query:t};let o=i.map(c=>({event:c,match:Ffe(t,c.title)})).sort((c,u)=>u.match.score-c.match.score),[a,s]=o;return i.length===1||a.match.exact||a.match.recall>=pjt&&(!s||a.match.score-s.match.score>=fjt)?{kind:"event",event:a.event}:{kind:"ambiguous",query:t,candidates:i}}function Ffe(e,t){let r=c=>_n(c).split(" ").filter(u=>u.length>1),n=r(e),i=r(t);if(n.length===0||i.length===0)return{recall:0,precision:0,score:0,exact:!1};let o=new Set(i),a=new Set(n),s=n.filter(c=>o.has(c)).length/n.length,l=i.filter(c=>a.has(c)).length/i.length;return{recall:s,precision:l,score:s*.7+l*.3,exact:n.join(" ")===i.join(" ")}}var D5="{market}",yjt=`Show me details of the prediction market ${D5}`,Wy=[{name:"detail_button_label",type:"string",description:`Label for the "Details" button rendered on EVERY event card, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it. Just the word "Details" translated: English "Details", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the event \u2014 the button sits on that event's own card. One or two words.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this prediction market in detail" request IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a card's button is tapped. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the event title. English: "Show me details of the prediction market {market}". Vietnamese: "Xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng d\u1EF1 \u0111o\xE1n {market}". Always include {market}.`,required:!1}],n3e=e=>typeof e=="string"?e.trim():"";function zfe(e){return n3e(e.detail_button_label).replace(D5,"").replace(/\s+/g," ").trim()}function Hfe(e,t,r){r3e(e,t);let n=n3e(r.detail_prompt_template);return(n.includes(D5)?n:yjt).split(D5).join(e).replace(/\s+/g," ").trim()}function bjt(e){return Math.round(e*1e3)/10}function Ph(e,t){let r=10**t;return Math.trunc(Number((e*r).toFixed(6)))/r}function Ky(e){return Ph(e,2)}function M5(e){return Ph(e,6)}function b0(e){return Math.round(e)}function Vfe(e){return e.map(t=>({label:t.label,chancePercent:bjt(t.chance),...t.shortLabel?{shortLabel:t.shortLabel}:{}}))}function cP(e,t){let r=y2(e);return r?{title:e.title,slug:e.slug,url:e.url,image:e.image,endDate:e.endDate,volumeUsd:b0(e.volume),volume24hUsd:b0(e.volume24h),kind:r.kind,outcomes:Vfe(r.outcomes),openMarketCount:r.openMarketCount,detailPrompt:Hfe(e.title,e.slug,t),detailLabel:zfe(t),upDown:e.upDown}:null}var Yy='A chance shown here is the PRICE traders currently pay for that outcome \u2014 the market-implied probability \u2014 never a forecast of yours: phrase it as "the market prices X at N%", never "X will win" or "X is likely". Do NOT give your own opinion or analysis of the underlying event (an election, a game, a policy decision), do NOT tell the user which side to buy or how much to stake, and never state a chance, price or volume the tool did not return. Prediction markets can lose the whole stake; this is information, not advice. Do NOT mention tool names.';var o3e=5,Zfe=20,_jt=3,a3e=Object.keys(FO),i3e={trending:"ordered as polymarket.com's homepage Trending view: its featured events, live or upcoming games and the live 5-minute Bitcoin market first, then by 24-hour trading volume",new:"ordered by creation date, newest first",volume:"ordered by all-time trading volume, largest first",liquidity:"ordered by liquidity, deepest first",competitive:"ordered by how close the odds are (the most contested first)",ending_soon:"ordered by end date, the soonest-ending first"},uP=class extends Ce{constructor(r){super();g(this,"name","get-prediction-markets");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'BROWSE or SEARCH Polymarket prediction markets \u2014 real-world questions people trade on (elections, sports games, crypto prices, economics, geopolitics, tech, weather\u2026). Returns event cards with the current market-implied odds of each, volume and end date, plus a "Details" button per event. Use for: "trending predictions", "hot Polymarket markets", "sports prediction markets", "d\u1EF1 \u0111o\xE1n v\u1EC1 crypto", "new markets", "markets ending soon", "most contested markets", "is there a market on <topic>?", "odds on the next Fed decision", "Polymarket odds for the election". Pass `query` when the user names a TOPIC or event (a person, team, coin, event); pass `category` when they name a broad section; pass neither for the general feed. Do NOT use for: ONE event in full (all its options, rules, deadline) \u2192 get-prediction-market-detail; the user\'s own positions \u2192 get-prediction-portfolio; their trade history \u2192 get-prediction-activity.');g(this,"parameters",[{name:"query",type:"string",description:`Search text when the user names a topic, event, person, team or coin ("bitcoin", "world cup", "Fed rates", "Lakers"). Write it in ENGLISH keywords \u2014 market titles are English \u2014 translating the user's words ("b\u1EA7u c\u1EED M\u1EF9" \u2192 "US election"). OMIT for a general or category feed.`,required:!1},{name:"category",type:"string",description:`Category to scope a feed to. One of: ${Kg.map(r=>r.key).join(", ")}. Pass the user's word as-is if unsure \u2014 it is matched for you, and an unknown one is reported back. OMIT when the user named none, and when \`query\` is set.`,required:!1},{name:"sort",type:"string",description:`Feed order: ${a3e.map(r=>`"${r}" (${i3e[r]})`).join(", ")}. Default "trending". Ignored when \`query\` is set (search results are ordered by relevance).`,required:!1},{name:"limit",type:"number",description:`How many events, 1-${Zfe}. Default ${o3e}. Raise only when the user asks for more.`,required:!1},...Wy]);g(this,"service");this.service=new Br(r)}async run(r){let n=typeof r.query=="string"?r.query.trim():"",i=wjt(r.limit),o=typeof r.category=="string"?r.category.trim():"",a=n?null:b2(o);if(!n&&o&&!a)return{requestedCategory:o,categoriesAvailable:Kg.map(h=>h.label),_instructions:`"${o}" is not a prediction-market category here. In the user's language, say so in one short sentence and name the categories in \`categoriesAvailable\`, offering to show one of them or to search a specific topic. Do NOT invent markets. Do NOT mention tool names.`};let s=vjt(r.sort),c=(n?await this.service.searchEvents(n,Math.min(Zfe*2,i*2+5)):await this.service.listEvents({sort:s,tagId:a?.tagId,limit:i*_jt})).map(h=>cP(h,r)).filter(h=>h!==null).slice(0,i);if(c.length===0)return{query:n||null,category:a?.label??null,eventCount:0,_instructions:(n?`No open prediction market matches "${n}" right now. `:"No open prediction markets could be loaded for this view right now. ")+"Say so briefly in the user's language and offer to show the trending markets or another topic. Do NOT invent markets or odds. Do NOT mention tool names."};let u={sort:n?"relevance":s,category:a?.label??null,query:n||null,events:c},d={component:"PredictionMarketList",props:u},p=n?`prediction markets matching "${n}", most relevant first`:`${a?`${a.label} `:""}prediction markets ${i3e[s]}`;return{ui:d,query:n||null,category:a?.label??null,sortedBy:u.sort,eventCount:c.length,eventTitles:c.map(h=>h.title),_instructions:[`These are ${p}. They are ALREADY RENDERED as cards below your reply, each with its title, the`,'current odds, volume, end date and a "Details" button. Do NOT write the list out: no numbered or',"bullet list, no per-event lines, no odds, no links, no mention of the buttons.",`Write your reply in TWO parts separated by a line containing exactly ${pc} and nothing`,"else \u2014 include that marker EXACTLY ONCE, on its own line; do not translate, style or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: ONE short sentence noting that the odds are live market prices that move","constantly and that this is information, not betting advice \u2014 in the user's language.",Yy].join(" ")}}};function vjt(e){let t=typeof e=="string"?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):"";return a3e.includes(t)?t:"trending"}function wjt(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?o3e:Math.min(Math.floor(t),Zfe)}m();m();function dP(e){return!e.open||e.clobTokenIds.length!==e.outcomes.length||e.clobTokenIds.length<2?null:{question:e.question,conditionId:e.conditionId,negRisk:e.negRisk,protocol:e.protocol,fee:e.fee,outcomes:e.outcomes.map((t,r)=>({label:t.label,tokenId:e.clobTokenIds[r],...t.shortLabel?{shortLabel:t.shortLabel}:{}}))}}function s3e(e,t,r){let n=e.markets.filter(c=>c.open&&dP(c));if(n.length===0)return null;if(r?.open&&dP(r)&&!t)return r;if(n.length===1)return n[0];if(!t)return null;let i=_n(t),o=n.find(c=>_n(c.label)===i||_n(c.question)===i);if(o)return o;let a=n.map(c=>({m:c,match:Ffe(t,c.label||c.question)})).sort((c,u)=>u.match.score-c.match.score),[s,l]=a;return s.match.recall>=.6&&(!l||s.match.score>l.match.score)?s.m:null}function l3e(e,t){if(!t)return-1;let r=_n(t),i={co:"yes",khong:"no"}[r]??r,o=e.outcomes.map(s=>_n(s.label)),a=o.indexOf(i);return a>=0?a:o.findIndex(s=>s.includes(i)||i.includes(s))}function L5(e){let t=typeof e=="string"?e.trim().replace(",","."):typeof e=="number"?String(e):"";return/^\d+(\.\d+)?$/.test(t)&&Number(t)>0?t:null}function U5(e){return typeof e=="string"&&/^(all|max|everything|het|tat ca|toan bo)$/.test(_n(e))}var Sjt=15,c3e=600,kjt=5,pP=class extends Ce{constructor(r){super();g(this,"name","get-prediction-market-detail");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'Show ONE prediction market (Polymarket event) in full: every open option with its current market-implied odds and 24 h change, volume, liquidity, end date and how it resolves. Use when the user singles out one event \u2014 "tell me more about the Fed October decision market", "odds of each candidate in the Brazil election", "how does this market resolve", a pasted polymarket.com link, or a tapped "Details" button (its message names the title of an event card already shown). Do NOT use for browsing many events or a topic in general \u2192 get-prediction-markets. Do NOT use when the user wants to buy, sell or bet (mua / b\xE1n / \u0111\u1EB7t c\u01B0\u1EE3c) \u2014 even with a hint \u2192 open-prediction-trade.');g(this,"parameters",[{name:"market",type:"string",description:'Which event. When the message names the title of an event card already shown (a "Details" tap), pass that title VERBATIM, untranslated. When it carries a "(prediction: <slug>)" hint, pass that hint VERBATIM (with the parentheses). When it carries a polymarket.com link, pass the link. Otherwise pass the event as the user named it, in ENGLISH keywords ("Fed decision October", "Brazil presidential election").',required:!0},...Wy]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=typeof r.market=="string"?r.market.trim():"",o=await N5(this.service,i,n?.query??"");switch(o.kind){case"event":return this.detail(o.event);case"ambiguous":return this.ambiguous(o.query,o.candidates,r);case"not_found":return this.notFound(o.query);default:return{_instructions:"No event was named. Ask the user, in their language, which prediction market they want to see. Do NOT mention tool names."}}}detail(r){let n=r.markets.filter(s=>s.open),i=Gfe(r),o=i.markets,a={component:"PredictionMarketDetail",props:i};return n.length===0?{ui:a,title:r.title,open:!1,resolvedOutcomes:Tjt(r),_instructions:"This prediction market is CLOSED \u2014 no longer open for trading. In the user's language, say so in one or two sentences; if `resolvedOutcomes` lists winners, state them as how the market resolved. "+Yy}:{ui:a,title:r.title,open:!0,endDate:r.endDate,volumeUsd:i.volumeUsd,mutuallyExclusive:r.negRisk,leadingOptions:o.filter(s=>s.outcomes.length>0).slice(0,kjt).map(s=>({option:s.label,outcomes:s.outcomes.map(l=>`${l.label} ${l.chancePercent}%`).join(" / ")})),openMarketCount:n.length,rules:u3e(r.description,c3e),_instructions:["The event is ALREADY RENDERED as a card below your reply, listing every open option with its odds,","volume, end date and rules. Write at most THREE short sentences: what the question is, the leading","option(s) from `leadingOptions` as market prices, and when it ends. Do NOT list every option and do NOT","repeat the rules unless the user asked how it resolves (then summarize `rules` in one sentence).",Yy].join(" ")}}ambiguous(r,n,i){let o=n.map(s=>cP(s,i)).filter(s=>s!==null);return o.length===0?this.notFound(r):{ui:{component:"PredictionMarketList",props:{sort:"relevance",category:null,query:r,events:o}},query:r,candidateCount:o.length,candidateTitles:o.map(s=>s.title),_instructions:[`"${r}" matches several prediction markets, so none was opened. They are ALREADY RENDERED as cards`,'below your reply, each with a "Details" button. Write your reply in TWO parts separated by a line',`containing exactly ${pc} (exactly once, on its own line): PART ONE \u2014 one short sentence`,"saying several markets match and asking which one they mean; PART TWO \u2014 leave it empty or one short","sentence. Do NOT list the markets in text.",Yy].join(" ")}}notFound(r){return{query:r,found:!1,_instructions:`No open prediction market matching "${r}" was found. Say so briefly in the user's language and offer to search a related topic or show the trending markets. Do NOT invent a market or odds. Do NOT mention tool names.`}}};function Gfe(e){let t=e.markets.filter(o=>o.open),r=uv(e),i=(r?r.open?[r]:[]:t.slice(0,Sjt)).map(xjt(e));return{title:e.title,slug:e.slug,url:e.url,image:e.image,description:u3e(e.description,c3e),resolutionSource:e.resolutionSource,endDate:e.endDate,volumeUsd:b0(e.volume),volume24hUsd:b0(e.volume24h),liquidityUsd:b0(e.liquidity),negRisk:e.negRisk,markets:i,hiddenMarketCount:Math.max(0,t.length-i.length)}}function xjt(e){let t=e.markets.length===1;return r=>({label:t?e.title:r.label,outcomes:r.priced?Vfe(r.outcomes):[],volumeUsd:b0(r.volume),oneDayChangePoints:r.priced&&r.oneDayPriceChange!==null?Math.round(r.oneDayPriceChange*1e3)/10:null,trade:dP(r)})}function Tjt(e){return e.markets.filter(t=>!t.open).map(t=>({market:t.label,winner:t.outcomes.find(r=>r.chance>=.999)?.label??""})).filter(t=>t.winner).slice(0,5)}function u3e(e,t){if(e.length<=t)return e;let r=e.slice(0,t),n=r.lastIndexOf(" ");return`${(n>t*.6?r.slice(0,n):r).trimEnd()}\u2026`}m();m();m();function Sp(e,t){return{component:"PredictionSetupCard",props:{signer:e.owner,wallet:e.address,walletKind:e.kind==="safe"?"safe":"deposit-wallet",deployed:e.deployed,approved:e.deployed?t?.isFullyApproved??!1:null}}}var Jy="This wallet has no Polymarket account yet, so there is nothing to show. A card to set one up is ALREADY RENDERED below your reply. In ONE short sentence in the user's language, say there is no Polymarket account yet and that they can create it with the card below. Do NOT invent positions, balances or steps, and do NOT mention tool names.";var B5={name:"address",type:"string",description:"EVM address (0x\u2026) to look up \u2014 the user's wallet or a Polymarket account wallet. Set it ONLY when the user wrote an address; otherwise OMIT it and the connected wallet is used.",required:!1};function d3e(e){return`${Wg}/profile/${e}`}function j5(e){return e?`${Wg}/event/${e}`:null}async function q5(e,t,r){let n=Un(t.address,r);if(!mc(n))return{ok:!1,result:{address:n,_instructions:`"${n}" is not a valid EVM address. Ask the user, in their language, for a valid 0x address. Do NOT mention tool names.`}};let i=await e.resolveAccount(n),o=!!r?.walletAddress&&r.walletAddress.toLowerCase()===n.toLowerCase();return!i.deployed&&o&&i.kind!=="profile"?{ok:!1,result:{ui:Sp(i,null),hasPolymarketAccount:!1,_instructions:Jy}}:i.deployed?{ok:!0,account:i}:{ok:!1,result:{address:n,hasPolymarketAccount:!1,_instructions:"This wallet has no Polymarket account yet \u2014 nothing has been deposited or traded on Polymarket from it. Tell the user so in one short sentence, in their language, and offer to show the trending prediction markets instead. Do NOT invent positions or balances. Do NOT mention tool names."}}}var p3e=10,f3e=30,Ajt=200,fP=class extends Ce{constructor(r){super();g(this,"name","get-prediction-portfolio");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",`The user's Polymarket holdings: cash available to trade, the value and profit/loss of every open position, and winnings ready to claim. Use for "my Polymarket positions", "my bets", "how much have I won/lost on Polymarket", "v\u1ECB th\u1EBF d\u1EF1 \u0111o\xE1n c\u1EE7a t\xF4i", "Polymarket balance". Works for the connected wallet or an address the user gives. Do NOT use for past trades \u2192 get-prediction-activity; for markets to browse \u2192 get-prediction-markets.`);g(this,"parameters",[B5,{name:"limit",type:"number",description:`How many positions to list, 1-${f3e}. Default ${p3e}.`,required:!1},...Wy]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=await q5(this.service,r,n);if(!i.ok)return i.result;let o=i.account.address,a=Ijt(r.limit),[s,l,c]=await Promise.all([this.service.getPositions(o,Ajt),this.service.getPositionsValue(o),this.service.getCash(o).catch(()=>null)]),u=s.filter(Pjt),d=u.filter(v=>v.redeemable),p=Ky(d.reduce((v,S)=>v+S.currentValue,0)),h=u.slice(0,a).map(v=>Ejt(v,r)),y={wallet:o,profileUrl:d3e(o),cashUsd:c===null?null:M5(c),positionsValueUsd:Ky(l),claimableUsd:p,positions:h,totalPositions:u.length},b={component:"PredictionPortfolio",props:y},_=Ky(u.reduce((v,S)=>v+S.cashPnl,0));return{ui:b,wallet:o,cashUsd:y.cashUsd,positionsValueUsd:y.positionsValueUsd,claimableUsd:p,openPositionCount:u.length-d.length,claimablePositionCount:d.length,unrealizedPnlUsd:_,positionsShown:h.length,positions:h.map(v=>({market:v.title,outcome:v.outcome,valueUsd:v.valueUsd,pnlUsd:v.pnlUsd})),_instructions:["The portfolio is ALREADY RENDERED as a card below your reply: cash, positions value, claimable winnings","and each position with its value and profit/loss. Write at most TWO short sentences in the user's","language: the headline numbers (cash, positions value, and claimable winnings if above 0) in USD exactly","as given, and \u2014 only if there are no positions \u2014 that the account currently holds none. End with a period,","never a colon. Do NOT list the positions in text (`positions` is there only so you never state anything","that is not in it). Never state a figure that is not in this result.",u.length===0?"":"Do NOT judge the positions or suggest selling, holding or buying anything.","Do NOT mention tool names."].filter(Boolean).join(" ")}}};function Pjt(e){return e.shares<=0?!1:!e.redeemable||e.currentValue>0}function Ejt(e,t){return{title:e.title,outcome:e.outcome,url:j5(e.eventSlug),icon:e.icon,shares:Ph(e.shares,2),avgPrice:Ph(e.avgPrice,4),curPrice:Ph(e.curPrice,4),valueUsd:Ky(e.currentValue),pnlUsd:Ky(e.cashPnl),pnlPercent:Math.round(e.percentPnl*10)/10,claimable:e.redeemable&&e.currentValue>0,endDate:e.endDate,detailPrompt:e.eventSlug?Hfe(e.title,e.eventSlug,t):"",detailLabel:zfe(t),tokenId:e.asset,conditionId:e.conditionId,outcomeIndex:e.outcomeIndex,oppositeOutcome:e.oppositeOutcome,oppositeTokenId:e.oppositeAsset}}function Ijt(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?p3e:Math.min(Math.floor(t),f3e)}m();var m3e=10,h3e=30,Cjt="https://polygonscan.com/tx/",mP=class extends Ce{constructor(r){super();g(this,"name","get-prediction-activity");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",`The user's recent Polymarket history: each buy and sell (outcome, shares, price, amount), claimed winnings and rewards, newest first. Use for "my Polymarket trades", "what did I bet on", "l\u1ECBch s\u1EED giao d\u1ECBch Polymarket", "my last prediction trades". Works for the connected wallet or an address the user gives. Do NOT use for current holdings \u2192 get-prediction-portfolio.`);g(this,"parameters",[B5,{name:"limit",type:"number",description:`How many entries, 1-${h3e}. Default ${m3e}.`,required:!1}]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=await q5(this.service,r,n);if(!i.ok)return i.result;let o=i.account.address,a=Ojt(r.limit),s=(await this.service.getActivity(o,a)).map(u=>({type:u.type,side:u.side,title:u.title,outcome:u.outcome,url:j5(u.eventSlug),shares:Ph(u.shares,2),usd:Ky(u.usd),price:Ph(u.price,4),timestamp:u.timestamp,txUrl:/^0x[0-9a-fA-F]{64}$/.test(u.transactionHash)?`${Cjt}${u.transactionHash}`:null}));return s.length===0?{wallet:o,entryCount:0,_instructions:"This Polymarket account has no trading history yet. Say so in one short sentence in the user's language. Do NOT invent trades. Do NOT mention tool names."}:{ui:{component:"PredictionActivity",props:{wallet:o,items:s},completeList:!0},wallet:o,entryCount:s.length,entries:s.map(u=>({type:u.type,side:u.side,market:u.title,outcome:u.outcome,usd:u.usd,date:u.timestamp>0?new Date(u.timestamp*1e3).toISOString().slice(0,10):null})),_instructions:["The history is ALREADY RENDERED as a list below your reply \u2014 every entry with its type, outcome, shares,",'price, amount and time \u2014 so a request to "show" or "list" the trades is ALREADY fully answered by it;',"writing the entries out again would show each one twice.",`Write your reply in TWO parts separated by a line containing exactly ${pc} (exactly once, on`,"its own line). PART ONE: ONE short sentence ending with a period (never a colon) saying this is their","recent Polymarket activity and how many entries are shown. PART TWO: EMPTY \u2014 write nothing at all after the","marker. No bullet or numbered list anywhere, no per-entry lines: `entries` is given ONLY so you never","state anything that is not in it. Do NOT judge the trades. Do NOT mention tool names."].join(" ")}}};function Ojt(e){let t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<1?m3e:Math.min(Math.floor(t),h3e)}m();var hP=class extends Ce{constructor(r){super();g(this,"name","open-prediction-setup");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",`Open the card that SETS UP the user's Polymarket account so they can trade prediction markets: one button that enables trading, creates their Polymarket wallet and grants the trading approvals \u2014 gasless, signed once from their own wallet. Use for "create a Polymarket account", "set up Polymarket", "enable trading on Polymarket", "t\u1EA1o t\xE0i kho\u1EA3n Polymarket", "k\xEDch ho\u1EA1t giao d\u1ECBch d\u1EF1 \u0111o\xE1n", or when the user wants to start betting / trading and has no account. Needs the connected wallet. Do NOT use to deposit funds \u2192 open-prediction-deposit.`);g(this,"parameters",[]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=n?.walletAddress?.trim();if(!i||!mc(i))return{error:"wallet_not_connected",_instructions:"Setting up a Polymarket account needs the user's own connected wallet, which signs for it. Ask them, in their language, to connect a wallet first. Do NOT mention tool names."};let{account:o,approvals:a}=await wp(i,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, not a wallet that can sign for one, so it cannot be set up here. Say so briefly in the user's language. Do NOT mention tool names."};let s=Sp(o,a),l=o.deployed&&a?.isFullyApproved===!0;return{ui:s,walletDeployed:o.deployed,approvalsComplete:a?.isFullyApproved??!1,_instructions:["The Polymarket account-setup card is ALREADY RENDERED below your reply; it runs the setup itself when the","user taps its button. Write ONE or TWO short sentences in the user's language:",l?"the wallet is already created and approved on-chain, so the card only needs to confirm trading access \u2014":"what the button does \u2014 enables trading, creates their Polymarket wallet and grants the approvals in one go,","with no gas fees, signed from their own wallet (an NFC card is tapped once).","Do NOT claim the account is set up, do NOT list technical steps or contract names, and do NOT mention tool","names."].join(" ")}}};m();var gP=class extends Ce{constructor(r){super();g(this,"name","open-prediction-deposit");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'Open the card that DEPOSITS funds into the user\'s Polymarket account (to trade prediction markets): send a stablecoin they hold (USDC, USDT, DAI\u2026 on Ethereum, Base, Polygon, Arbitrum, BSC\u2026) straight from their wallet, or get the EVM deposit address + QR code for another EVM wallet or exchange (EVM chains only). Use for "deposit to Polymarket", "fund my Polymarket", "n\u1EA1p ti\u1EC1n v\xE0o Polymarket", "top up my prediction account", "n\u1EA1p 50 USDC v\xE0o Polymarket". Needs the connected wallet; if the account is not set up yet the setup card is shown instead. Pass `amount` ONLY when the user named one.');g(this,"parameters",[{name:"amount",type:"string",description:`Amount to pre-fill, in the stablecoin's own units as a plain decimal ("50", "12.5"). ONLY when the user named an amount; never invent or convert one.`,required:!1}]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=n?.walletAddress?.trim();if(!i||!mc(i))return{error:"wallet_not_connected",_instructions:"Depositing into Polymarket needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let{account:o,approvals:a}=await wp(i,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, so deposits are made to it directly from another wallet. Say so briefly in the user's language. Do NOT mention tool names."};if(!o.deployed)return{ui:Sp(o,a),hasPolymarketAccount:!1,_instructions:Jy};let[s,l]=await Promise.all([this.service.getBridgeAssets(),this.service.getDepositAddresses(o.address)]),c=await P5(i,s),u=typeof r.amount=="string"&&/^\d+(\.\d+)?$/.test(r.amount.trim())?r.amount.trim():null,p={component:"PredictionDepositCard",props:{wallet:o.address,owner:i,depositAddress:l.evm,options:c,assets:E5(s),networks:Rjt(s,l),prefillAmount:u}},h=c.length>0?Math.min(...c.map(y=>y.minUsd)):null;return{ui:p,walletHasDepositableStablecoins:c.length>0,depositableFromWallet:c.slice(0,5).map(y=>`${y.symbol} on ${y.chainName}`),minimumDepositUsd:h,_instructions:["The deposit card is ALREADY RENDERED below your reply: it opens the deposit screen, which sends a stablecoin","from the user's wallet, or shows the EVM deposit address and QR code for another EVM wallet or exchange","(EVM chains only \u2014 Ethereum, Base, Polygon, Arbitrum, BNB Chain\u2026). Write ONE or TWO short sentences in the","user's language:",c.length>0?"they can deposit straight from their wallet with the card (pick a token and amount),":"their wallet holds no stablecoin the card can send, so they can deposit from another EVM wallet or exchange using the address and QR code,","funds arrive as cash in their Polymarket account after the bridge processes them (usually a few minutes),",h!==null?`and deposits below about $${h} may not be credited.`:"and very small deposits may not be credited.","Do NOT claim a deposit was made, do NOT repeat addresses, and do NOT mention tool names."].join(" ")}}};function Rjt(e,t){let r={evm:{chains:new Set,minUsd:1/0},svm:{chains:new Set,minUsd:1/0},btc:{chains:new Set,minUsd:1/0},tron:{chains:new Set,minUsd:1/0}};for(let n of e){let i=lv[n.chainId];if(i===null)continue;let o=r[i??"evm"];o.chains.add(n.chainName),o.minUsd=Math.min(o.minUsd,n.minUsd)}return Object.keys(r).filter(n=>t[n]&&r[n].chains.size>0).map(n=>({family:n,address:t[n],chains:[...r[n].chains].sort(),minUsd:Number.isFinite(r[n].minUsd)?r[n].minUsd:0}))}m();var $jt=100,yP=class extends Ce{constructor(r){super();g(this,"name","open-prediction-trade");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'Prepare a BUY or SELL of shares in a prediction market (Polymarket) for the user to review and confirm in the order drawer, which shows the live price. Use for "bet $10 on Yes", "buy Yes on the Fed market", "mua 20$ c\u1EEDa Lula", "sell my Real Madrid shares", "b\xE1n h\u1EBFt c\u1ED5 ph\u1EA7n Trump". Market orders only. Needs the connected wallet with a Polymarket account (otherwise the setup card is shown). Do NOT use to browse or see odds \u2192 get-prediction-markets / get-prediction-market-detail.');g(this,"parameters",[{name:"market",type:"string",description:'Which event. A "(prediction: <slug>)" hint, a polymarket.com link or the title of an event card already shown in the message \u2192 pass it VERBATIM. Otherwise the event as the user named it, in ENGLISH keywords ("Fed decision October").',required:!0},{name:"option",type:"string",description:'For an event with several options (candidates, price levels, dates): the one the user picked, as named ("Lula", "85,000", "No change"). Omit when the user did not name one.',required:!1},{name:"outcome",type:"string",description:'The side the user picked: "Yes", "No", or a team / name. Omit when not said.',required:!1},{name:"side",type:"string",description:'"buy" (bet on / mua) or "sell" (sell shares / b\xE1n).',required:!0},{name:"amount",type:"string",description:'ONLY when the user named it. BUY: USD to spend as a plain decimal ("10"). SELL: number of shares, or "all" to sell everything. Never invent or convert one.',required:!1},...Wy]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=n?.walletAddress?.trim();if(!i||!mc(i))return{error:"wallet_not_connected",_instructions:"Trading prediction markets needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let o=["sell","ban"].includes(_n(String(r.side??"")))?"SELL":"BUY",{account:a,approvals:s}=await wp(i,this.service);if(a.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, which cannot sign orders here. Say so briefly in the user's language. Do NOT mention tool names."};if(!a.deployed||s?.isFullyApproved!==!0)return{ui:Sp(a,s),hasPolymarketAccount:a.deployed,_instructions:a.deployed?"The Polymarket account is not fully set up for trading yet. A card that finishes the setup is ALREADY RENDERED below your reply. In ONE short sentence in the user's language, say the account needs to finish setup before trading. Do NOT mention tool names.":Jy};let l=typeof r.market=="string"?r.market.trim():"",c=await N5(this.service,l,n?.query??"");if(c.kind==="unnamed"||c.kind==="not_found")return{found:!1,_instructions:c.kind==="unnamed"?"No market was named. Ask the user, in their language, which prediction market they want to trade.":`No open prediction market matching "${c.query}" was found. Say so briefly in the user's language and offer to search a related topic. Do NOT invent a market. Do NOT mention tool names.`};if(c.kind==="ambiguous"){let T=c.candidates.map($=>cP($,r)).filter($=>!!$);return{ui:{component:"PredictionMarketList",props:{sort:"relevance",category:null,query:c.query,events:T}},candidateCount:T.length,_instructions:[`"${c.query}" matches several prediction markets, so no order was prepared. They are ALREADY`,"RENDERED as cards below. Write your reply in TWO parts separated by a line containing exactly",`${pc} (once, on its own line): PART ONE \u2014 one short sentence asking which market they`,"mean; PART TWO \u2014 empty. Do NOT list the markets in text."].join(" ")}}let u=c.event,d=typeof r.option=="string"?r.option.trim():"",p=s3e(u,d,uv(u)??null);if(!p){let T=Gfe(u),O=T.markets.some($=>$.trade);return{ui:{component:"PredictionMarketDetail",props:T},title:u.title,open:O,_instructions:O?"This event has several options and the order needs ONE. The event is ALREADY RENDERED below with a buy button on every option. In ONE short sentence in the user's language, ask them to pick the option on the card. Do NOT claim an order was placed. Do NOT mention tool names.":"This prediction market is closed \u2014 it can no longer be traded. Say so in one sentence in the user's language. Do NOT mention tool names."}}let h=dP(p),y=r.amount,b=o==="SELL"&&U5(y),_=l3e(p,typeof r.outcome=="string"?r.outcome:""),v=null;if(o==="SELL"){let T=(await this.service.getPositions(a.address,$jt)).filter($=>$.conditionId===p.conditionId&&$.shares>0&&!$.redeemable),O=(_>=0?T.find($=>$.outcomeIndex===_):void 0)??(T.length===1?T[0]:void 0);if(!O)return{holdsShares:!1,market:p.question,_instructions:T.length>1?"The user holds several outcomes of this market. Ask, in their language, which one to sell. Do NOT mention tool names.":"The user holds no shares of this market's chosen outcome, so there is nothing to sell. Say so in one sentence in the user's language. Do NOT mention tool names."};_=O.outcomeIndex,v=Math.floor(O.shares*100)/100}let S={eventTitle:u.title,eventSlug:u.slug,url:u.url,image:u.image,marketLabel:u.markets.length===1?u.title:p.label,market:h,outcomeIndex:Math.max(0,_),side:o,amount:b?null:L5(y),sellAll:b,signer:i,wallet:a.address,endDate:p.endDate??u.endDate},w={component:"PredictionTradeCard",props:S},k=h.outcomes[S.outcomeIndex].label;return{ui:w,side:o,market:p.question,outcome:k,outcomeWasNamed:_>=0,amount:S.amount,sellAll:b,heldShares:v,_instructions:["The order is ALREADY RENDERED below your reply as a card; it opens the order screen with the LIVE price,","where the user reviews and confirms (one signature / NFC tap). In ONE or TWO short sentences in the",`user's language, say what is prepared (${o==="BUY"?"buying":"selling"} "${k}" in`,`"${p.question}"${S.amount?`, ${o==="BUY"?`$${S.amount}`:`${S.amount} shares`}`:""}),`,_>=0?"":"that they can switch the outcome on the card,","and that they confirm it there. Do NOT claim the order is placed or filled, do NOT state a price (it is","live on the card), do NOT give betting advice, and do NOT mention tool names.",Yy].filter(Boolean).join(" ")}}};m();var bP=class extends Ce{constructor(r){super();g(this,"name","open-prediction-withdraw");g(this,"kind","ui");g(this,"category","prediction");g(this,"description",'Open the card that WITHDRAWS cash from the user\'s Polymarket account back to their own wallet, as USDC or USDT on the chain they choose (Polygon, Base, Arbitrum, Ethereum, Optimism, BNB Chain\u2026). Use for "withdraw from Polymarket", "cash out my Polymarket", "r\xFAt ti\u1EC1n kh\u1ECFi Polymarket", "r\xFAt 20 USDC v\u1EC1 v\xED", "withdraw everything to Base". Needs the connected wallet; if the account is not set up yet the setup card is shown instead. Pass `amount` ONLY when the user named one ("all" for everything), and `chain` / `token` ONLY when named. Selling a position first is open-prediction-trade, not this.');g(this,"parameters",[{name:"amount",type:"string",description:'USD amount to pre-fill as a plain decimal ("20", "12.5"), or "all" for the whole cash balance. ONLY when the user named one; never invent or convert one.',required:!1},{name:"chain",type:"string",description:'Destination chain the user named, in English ("Base", "Polygon", "Arbitrum", "Ethereum", "BNB Chain"). OMIT when not named \u2014 the card lets them pick.',required:!1},{name:"token",type:"string",description:'Destination token symbol the user named ("USDC", "USDT", "ETH", \u2026). OMIT when not named.',required:!1}]);g(this,"service");this.service=new Br(r)}async run(r,n){let i=n?.walletAddress?.trim();if(!i||!mc(i))return{error:"wallet_not_connected",_instructions:"Withdrawing from Polymarket needs the user's connected wallet. Ask them, in their language, to connect one first. Do NOT mention tool names."};let{account:o,approvals:a}=await wp(i,this.service);if(o.kind==="profile")return{error:"unsupported_account",_instructions:"The connected address is itself a Polymarket account wallet, which cannot sign a withdrawal here; withdrawals are made from the wallet that owns it. Say so briefly in the user's language. Do NOT mention tool names."};if(!o.deployed)return{ui:Sp(o,a),hasPolymarketAccount:!1,_instructions:Jy};let[s,l]=await Promise.all([this.service.getBridgeAssets(),iT(o.address).catch(()=>null)]),c=O5(s);if(c.length===0)return{error:"withdraw_unavailable",_instructions:"Withdrawals are not available right now (the bridge lists no destination). Say so briefly in the user's language and suggest trying again later. Do NOT mention tool names."};let u=l===null?null:M5(l);return{ui:{component:"PredictionWithdrawCard",props:{signer:i,wallet:o.address,recipient:i,cashUsd:u,destinations:c,defaultDestination:Njt(c,r.chain,r.token),prefillAmount:U5(r.amount)?"all":L5(r.amount)}},cashUsd:u,_instructions:["The withdraw card is ALREADY RENDERED below your reply: the user picks the chain and token, sees the","live quote (what arrives and the route cost) and confirms there; funds go to their own connected wallet.","Write ONE or TWO short sentences in the user's language:",u===null?"that they can withdraw their Polymarket cash with the card below.":u>0?`that they have $${u} cash available to withdraw with the card below.`:"that the account has no cash to withdraw right now \u2014 positions must be sold (or winnings claimed) first.","Do NOT claim a withdrawal was made or funds arrived, do NOT repeat addresses, and do NOT mention tool names."].join(" ")}}};function Njt(e,t,r){let n=typeof t=="string"?_n(t).replace(/\bchain\b|\bmainnet\b/g,"").trim():"",i=typeof r=="string"?_n(r):"";if(!n&&!i)return null;let o=u=>{if(!n)return!0;let d=_n(u.chainName);return d===n||d.startsWith(n)||n.startsWith(d.split(" ")[0])},a=u=>!i||_n(u.symbol).startsWith(i),s=e.findIndex(u=>!!i&&o(u)&&_n(u.symbol)===i);if(s>=0)return s;let l=e.findIndex(u=>o(u)&&a(u));if(l>=0)return l;let c=e.findIndex(o);return c>=0?c:null}m();m();m();var F5="https://ipfs.pantograph.app/ipfs/",g3e=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function _0(e){let t=e?.trim();if(!t)return null;if(/^(https?:\/\/|data:image\/)/i.test(t))return t;let r=t.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return r?`${F5}${r[1]}`:g3e.test(t)?`${F5}${t}`:null}function y3e(e){let t=e?.trim();if(!t)return null;if(/^https?:\/\//i.test(t))return t;let r=t.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return r?`${F5}${r[1]}`:g3e.test(t)?`${F5}${t}`:null}function b3e(e){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(e)}function Wfe(e){if(!e||typeof e!="object")return;let t=e,r=t.image??t.image_url??t.imageUrl;return typeof r=="string"&&r.trim()?r.trim():void 0}function Djt(e){if(typeof atob=="function"){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return new TextDecoder().decode(r)}if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Mjt(e){let t=e.match(/^data:application\/json([^,]*),(.*)$/is);if(!t)return null;let r=t[1]??"",n=t[2]??"";try{let i=/;base64/i.test(r)?Djt(n):decodeURIComponent(n);return JSON.parse(i)}catch{try{return JSON.parse(n)}catch{return null}}}function _3e(e){let t=e?.trim();if(!t||!/^data:/i.test(t))return null;if(/^data:image\//i.test(t))return t;let r=Mjt(t);return r?_0(Wfe(r)):null}m();var Ljt=12,Ujt=6e3;async function Bjt(e,t,r){let n=new Array(e.length),i=0,o=new Array(Math.max(1,Math.min(t,e.length))).fill(0).map(async()=>{for(;i<e.length;){let a=i++;n[a]=await r(e[a],a)}});return await Promise.all(o),n}async function jjt(e,t){try{let r=await Qe.get(e,{timeout:t});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 qjt(e,t){let r=e?.trim();if(!r)return null;if(/^data:/i.test(r))return _3e(r);let n=y3e(r);if(!n)return null;if(b3e(n))return n;let i=await jjt(n,t);if(i){let o=_0(Wfe(i));if(o)return o}return null}async function z5(e,t,r){if(t.length===0)return[];let n=r?.concurrency??Ljt,i=r?.timeoutMs??Ujt,o=await LTe(e,t,r?.rpcUrl);return Bjt(o,n,a=>qjt(a,i))}var v3e=100,Fjt=100,_P="{name}",w3e="{chain}",vP=class extends Ce{constructor(r){super();g(this,"name","get-wallet-nfts");g(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.`);g(this,"category","nft");g(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}]);g(this,"service");this.service=new mr(r)}async run(r,n){let i=Un(r.address,n),o=Sn(r.chain,n),a=o?[o]:Ls(),s=Wjt(r.contract_address),l=x3e(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:v3e});return{chain:u,rows:d.success?S3e(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:Hjt(d),contractAddress:d.token_address,chain:ye(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=Zjt(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 y=>{let b=await this.service.getWalletNFTs({address:n,chain:y,limit:v3e,...a?{tokenAddresses:[a]}:{}});return{chain:y,rows:b.success?S3e(b.data?.result??[]):[],ok:b.success}}));if(o&&!l[0].ok)return{error:"Failed to fetch wallet NFTs"};let c=l.flatMap(y=>y.rows.filter(b=>zjt(b,{contract:a,collectionName:s})).map(b=>({chain:y.chain,row:b})));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),p=c.map(({chain:y,row:b},_)=>{let v=Vjt(b);return{name:v.name,tokenId:v.tokenId,contractAddress:v.contractAddress,image:d[_]??v.image,chain:ye(y)}});return{ui:{component:"WalletNftList",props:{walletAddress:n,collectionName:u,nfts:p}},_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 z5(o,s);a.forEach((c,u)=>{n[c]=l[u]??null})}))}catch{}return n}};function S3e(e){return e.filter(t=>(t.contract_type||"").toUpperCase()==="ERC721")}function zjt(e,t){if(t.contract)return e.token_address.toLowerCase()===t.contract.toLowerCase();if(t.collectionName){let r=t.collectionName.toLowerCase();return(e.name??"").toLowerCase().includes(r)}return!1}function Hjt(e){let t=e.name?.trim();if(t)return t;let r=e.token_address??"";return r.length>10?`${r.slice(0,6)}\u2026${r.slice(-4)}`:r}function Vjt(e){return{name:e.normalized_metadata?.name||e.name||`#${e.token_id}`,tokenId:e.token_id,contractAddress:e.token_address,image:_0(e.normalized_metadata?.image||e.media?.original_media_url)}}function Zjt(e,t){let r=typeof t.pick_button_label=="string"?t.pick_button_label:"",n=typeof t.pick_prompt_template=="string"?t.pick_prompt_template:"",i=[];for(let o of e){if(i.length>=Fjt)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",s=a?`show my ${_P} NFTs on ${w3e}`:`show my ${_P} NFTs`,l=k3e(n,{[_P]:o.name,[w3e]:a},s);a&&!l.includes(a)&&(l=`${l} (${a})`),i.push({label:Gjt(r,o.name,_P),prompt:`${l} (${o.contractAddress})`})}return i}function k3e(e,t,r){let n=e&&e.includes(_P)?e:r;for(let[i,o]of Object.entries(t))n=n.split(i).join(o);return n.replace(/\s+/g," ").trim()}function Gjt(e,t,r){return k3e(e,{[_P]:t},r)}function x3e(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}function Wjt(e){let t=x3e(e);return t&&/^0x[a-fA-F0-9]{40}$/.test(t)?t:void 0}m();m();var Kjt="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.",kp=class extends Ce{constructor(r){super();g(this,"kind","data");g(this,"category","nft");g(this,"llm");this.llm=new zi(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:Kjt,timestamp:n},{role:"user",content:r,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var wP=class extends kp{constructor(){super(...arguments);g(this,"name","get-nft-contract-info");g(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`.');g(this,"parameters",kp.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."`));g(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.")}};m();var SP=class extends kp{constructor(){super(...arguments);g(this,"name","get-nft-metadata");g(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`.');g(this,"parameters",kp.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."`));g(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.")}};m();m();m();m();var Kfe={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"},Yfe="amazon.com";function Yjt(e){return e?e.trim().toLowerCase().split(/[-_]/)[0]:""}function Jfe(e){let t=Yjt(e);return Kfe[t]??Yfe}function H5(e){return`https://${Jfe(e)}/s?k=NFC%20Tag`}m();function V5(e){if(!e)return"";let t=e.trim().toUpperCase().split(/[-_]/),r=t.length>1?t[t.length-1]:t[0];return/^[A-Z]{2}$/.test(r)?r:""}var Jjt=720*60*1e3,T3e=new Map,A3e=3;function Xjt(e){return[`A user in country "${e}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${A3e} 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 Qjt(e){if(!e)return[];let t=e.indexOf("["),r=e.lastIndexOf("]");if(t===-1||r===-1||r<=t)return[];let n;try{n=JSON.parse(e.slice(t,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>=A3e))break}return i}async function Xfe(e,t){let r=V5(e);if(!r||!t)return null;let n=T3e.get(r);if(n&&n.expires>Date.now())return n.links;let i=Date.now(),o=[{role:"user",content:Xjt(r),timestamp:i}];try{let a=await t.chat(o,void 0,{googleSearch:!0,maxRetries:1}),s=Qjt(a.text);if(s.length)return T3e.set(r,{links:s,expires:Date.now()+Jjt}),s}catch{}return null}async function kP(e){let t=await Xfe(e.country,e.llm);return t&&t.length?t:[{label:"Amazon",url:H5(e.language)}]}function e2t(e){return e.length<=1?e.length===1?`[${e[0].label}](${e[0].url})`:"":e.map((t,r)=>`${r+1}. [${t.label}](${t.url})`).join(`
|
|
550
550
|
`)}var P3e=["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(`
|
|
551
551
|
`),xP=class extends Ce{constructor(r){super();g(this,"kind","data");g(this,"name","nfc-info");g(this,"category","nfc");g(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.');g(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}]);g(this,"llm");r&&(this.llm=new zi(r))}async run(r,n){let i=typeof r.language=="string"&&r.language.trim()?r.language.trim():void 0,o=await kP({country:n?.country,language:i,llm:this.llm}),a=e2t(o),s=o.length>1;return{reference:P3e,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)):
|
|
552
552
|
${a}
|