keyring-agent-core 0.2.45 → 0.2.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -437,7 +437,7 @@ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}
437
437
  `);return a===-1?"":i.stack.slice(a+1)})();try{if(!n.stack)n.stack=o;else if(o){let a=o.indexOf(`
438
438
  `),s=a===-1?-1:o.indexOf(`
439
439
  `,a+1),l=s===-1?"":o.slice(s+1);String(n.stack).endsWith(l)||(n.stack+=`
440
- `+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=ho(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&ym.assertOptions(n,{silentJSONParsing:Ii.transitional(Ii.boolean),forcedJSONParsing:Ii.transitional(Ii.boolean),clarifyTimeoutError:Ii.transitional(Ii.boolean),legacyInterceptorReqResOrdering:Ii.transitional(Ii.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:ym.assertOptions(i,{encode:Ii.function,serialize:Ii.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),ym.assertOptions(r,{baseUrl:Ii.spelling("baseURL"),withXsrfToken:Ii.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&j.merge(o.common,o[r.method]);o&&j.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=mr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||wd;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let u,d=0,f;if(!l){let g=[nv.bind(this),void 0];for(g.unshift(...s),g.push(...c),f=g.length,u=Promise.resolve(r);d<f;)u=u.then(g[d++],g[d++]);return u}f=s.length;let m=r;for(;d<f;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{u=nv.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,f=c.length;d<f;)u=u.then(c[d++],c[d++]);return u}getUri(e){e=ho(this.defaults,e);let r=gm(e.baseURL,e.url,e.allowAbsoluteUrls);return pm(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){Ed.prototype[e]=function(r,n){return this.request(ho(n||{},{method:e,url:r,data:(n||{}).data}))}});j.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(ho(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Ed.prototype[e]=r(),e!=="query"&&(Ed.prototype[e+"Form"]=r(!0))});var _m=Ed;p();var yA=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new Fo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},SU=yA;p();function _A(t){return function(r){return t.apply(null,r)}}p();function bA(t){return j.isObject(t)&&t.isAxiosError===!0}p();var vA={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(vA).forEach(([t,e])=>{vA[e]=t});var TU=vA;function kU(t){let e=new _m(t),r=sm(_m.prototype.request,e);return j.extend(r,_m.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return kU(ho(t,i))},r}var kr=kU(Td);kr.Axios=_m;kr.CanceledError=Fo;kr.CancelToken=SU;kr.isCancel=hm;kr.VERSION=Pd;kr.toFormData=bl;kr.AxiosError=De;kr.Cancel=kr.CanceledError;kr.all=function(e){return Promise.all(e)};kr.spread=_A;kr.isAxiosError=bA;kr.mergeConfig=ho;kr.AxiosHeaders=mr;kr.formToJSON=t=>Qb(j.isHTMLForm(t)?new FormData(t):t);kr.getAdapter=rv.getAdapter;kr.HttpStatusCode=TU;kr.default=kr;var ov=kr;var{Axios:g3e,AxiosError:y3e,CanceledError:_3e,isCancel:b3e,CancelToken:v3e,VERSION:w3e,all:S3e,Cancel:T3e,isAxiosError:k3e,spread:P3e,toFormData:E3e,AxiosHeaders:A3e,HttpStatusCode:C3e,formToJSON:x3e,getAdapter:I3e,mergeConfig:O3e,create:R3e}=ov;var PU="0.2.45";var RQ=`keyring-agent-core/${PU} (Keyring Chatbot Agent; +https://keyring.app)`,wA=null;function EU(t){wA=t}var NQ=["payment-signature","x-payment"];function $Q(t){return t?Object.keys(t).some(e=>NQ.includes(e.toLowerCase())):!1}var AU;function bm(t){AU=t}var MQ=3e4,DQ=typeof process<"u"&&process.versions?.node!=null,SA=class{constructor(e={}){h(this,"instance");this.instance=ov.create({baseURL:e.baseURL,timeout:e.timeout??MQ,validateStatus:()=>!0,headers:{Accept:"application/json",...DQ?{"User-Agent":e.userAgent??RQ}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??AU,a=await this.instance.request({...i,signal:o,method:e,url:r,data:n}),s={};for(let[c,u]of Object.entries(a.headers??{}))u!=null&&(s[c.toLowerCase()]=String(u));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:s};if(l.status===402&&wA&&!$Q(i.headers)){let c=await wA(l,{url:r,method:String(e),body:n,headers:i.headers});if(c)return this.request(e,r,n,{...i,headers:{...i.headers,...c}})}return l}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},Oe=new SA;function rt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}p();p();var CU=mb(sv());function Bt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function UQ(t){return new Uint8Array(CU.keccak256.arrayBuffer(t))}function vm(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function xU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function IU(t){return new TextEncoder().encode(t)}function Yc(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function qQ(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function LQ(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function OU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return vm(e)}function wm(t){return OU(BigInt(t))}function RU(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function NU(t){let e=RU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(NU).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function jQ(t){let e=(t.inputs??[]).map(NU).join(",");return`${t.name??""}(${e})`}function TA(t,e){let r=zQ(t.type);if(r){let[i,o]=r;return FQ({...t,type:o},e,i)}if(t.type==="tuple")return BQ(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:qQ(vm(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=RU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:wm(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:OU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?vm(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:LQ(o)}}if(n==="bytes"){let i=typeof e=="string"?vm(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Yc(wm(i.length),a)}}if(n==="string"){let i=typeof e=="string"?IU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Yc(wm(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function kA(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(wm(e+i)),n.push(a),i+=a.length):r.push(a);return Yc(...r,...n)}function FQ(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=TA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=kA(o);if(n){let s=wm(o.length);return{dynamic:!0,encoded:o.length>0?Yc(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:Yc(...o.map(a=>a.encoded))}}function BQ(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=TA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?kA(i):Yc(...i.map(o=>o.encoded))}}function zQ(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function PA(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>TA(i,e[o])),n=kA(r);return xU(n)}function Ad({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=jQ(n),o=UQ(IU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):vm(PA(a,r).slice(2));return xU(Yc(o,s))}p();var EA=mb(sv()),$U=2n**96n;function qr(t,e=8){return!Number.isFinite(t)||t===0?t:Number(t.toPrecision(e))}function MU(t,e,r){let n=t*t,i=$U*$U,o=n*10n**18n/i;return Number(o)/1e18*Math.pow(10,e-r)}function mo(t,e,r){return Math.pow(1.0001,t)*Math.pow(10,e-r)}function Jc(t,e,r){if(t<=0)throw new Error("priceToTick: price must be > 0");let n=t/Math.pow(10,e-r),i=Math.log(n)/Math.log(1.0001),o=Math.round(i);return Math.abs(i-o)<.001?o:Math.floor(i)}function xd(t,e,r){let n={minPrice:t,maxPrice:e,inverted:!1};if(!Number.isFinite(t)||!Number.isFinite(e)||!Number.isFinite(r)||t<=0||e<=0||r<=0||t>=e)return n;let i={minPrice:1/e,maxPrice:1/t,inverted:!0},o=c=>r>=c.minPrice&&r<=c.maxPrice,a=o(n),s=o(i);if(a&&!s)return n;if(s&&!a)return i;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/r));return l(i)<l(n)?i:n}function Bo(t,e,r="nearest"){let n=Math.abs(t-Math.round(t))<1e-6?Math.round(t):t,i=(n%e+e)%e;if(i===0)return n;let o=n-i,a=o+e;return r==="down"?o:r==="up"?a:n-o<a-n?o:a}var vl=-887272,Cd=887272;function zo(t){return t<vl?vl:t>Cd?Cd:t}var VQ=/^0x[0-9a-f]+$/i;function Lr(t){return t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t}function lv(t){let e=Lr(t).toLowerCase();if(e.length>64)throw new Error(`pad32: input too long (${e.length})`);return e.padStart(64,"0")}function cv(t){if(!VQ.test(t)||Lr(t).length!==40)throw new Error(`encodeAddress: invalid address ${t}`);return lv(t.toLowerCase())}function fi(t,e=256){let r=typeof t=="bigint"?t:BigInt(t);if(r<0n)throw new Error("encodeUint: negative");let n=r.toString(16);if(n.length>e/4)throw new Error(`encodeUint: overflow ${e}`);return lv(n)}function AA(t){let e=typeof t=="bigint"?t:BigInt(t);if(e>=0n)return lv(e.toString(16));let r=1n<<256n;return lv((r+e).toString(16))}function DU(t){return"0x"+(0,EA.keccak_256)(ZQ(t))}function ZQ(t){let e=Lr(t),r=new Uint8Array(e.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(e.substring(n*2,n*2+2),16);return r}function zn(t){return"0x"+(0,EA.keccak_256)(new TextEncoder().encode(t)).slice(0,8)}function Sm(t,e){let r=t.substring(e,e+64);return r?BigInt("0x"+r):0n}function CA(t,e){let r=t.substring(e,e+64),n=BigInt("0x"+r),i=1n<<256n,o=1n<<23n;return n>=1n<<255n?Number(n-i):(n<o,Number(n))}function xA(t,e){return"0x"+t.substring(e+24,e+64).toLowerCase()}p();var Oi={"0x1":"https://ethereum-rpc.publicnode.com","0xa":"https://mainnet.optimism.io","0x38":"https://bsc-dataseed.binance.org","0x89":"https://polygon-bor-rpc.publicnode.com","0x2105":"https://mainnet.base.org","0xa4b1":"https://arb1.arbitrum.io/rpc","0xa86a":"https://avalanche-c-chain-rpc.publicnode.com","0xe708":"https://rpc.linea.build","0x64":"https://gnosis-rpc.publicnode.com","0x3e7":"https://rpc.hyperliquid.xyz/evm","0x1388":"https://rpc.mantle.xyz","0x8f":"https://rpc.monad.xyz"};function HQ(t){return Oi[t.toLowerCase()]}var UU={};function IA(t){let e={};if(t)for(let[r,n]of Object.entries(t))typeof n=="string"&&n.trim()&&(e[r.toLowerCase()]=n.trim());UU=e}function xs(t){let e=t.toLowerCase();return UU[e]??Oi[e]}async function Is(t,e,r){for(let i=0;i<=5;i++){let o=await Oe.post(t,{jsonrpc:"2.0",id:Date.now(),method:e,params:r},{headers:{"Content-Type":"application/json"}});if(o.status===429&&i<5){await new Promise(s=>setTimeout(s,2**i*500));continue}if(!o.ok)throw new Error(`RPC ${e}: ${rt(o)}`);let a=o.data;if(a.error)throw new Error(`RPC ${e}: ${a.error.message}`);if(a.result===void 0)throw new Error(`RPC ${e}: empty result`);return a.result}throw new Error(`RPC ${e}: exceeded max retries (429)`)}function Tm(t,e,r){return Is(t,"eth_call",[{to:e,data:r},"latest"])}async function OA(t,e,r){let n=xs(t);if(!n)return null;try{return await Tm(n,e,r)}catch{return null}}var GQ="0xcA11bde05977b3631167028862bE2a173976CA11",WQ={};function qU(t){return WQ[t.toLowerCase()]??GQ}var KQ=zn("aggregate3((address,bool,bytes)[])"),YQ=[{type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],JQ=zn("tokenURI(uint256)"),XQ=zn("symbol()"),QQ=zn("decimals()"),uv=50,LU=/^0x[0-9a-fA-F]{40}$/;function Os(t,e){return t.slice(e*2,e*2+64)}function Rs(t){return t?Number(BigInt("0x"+t)):0}function eee(t){try{return JQ+fi(BigInt(t))}catch{return null}}function jU(t){let e=PA(YQ,[t]);return KQ+Lr(e)}function FU(t,e){let r=Lr(t);if(r.length<64)return[];let n=Rs(Os(r,0)),i=Rs(Os(r,n)),o=Math.min(i,e),a=n+32,s=[];for(let l=0;l<o;l++){let c=a+Rs(Os(r,a+l*32)),u=Rs(Os(r,c))===1,d=c+Rs(Os(r,c+32)),f=Rs(Os(r,d)),m=r.slice((d+32)*2,(d+32)*2+f*2);s.push({success:u,returnData:"0x"+m})}return s}function BU(t){let e=Lr(t);if(e.length<128)return null;let r=Rs(Os(e,0)),n=Rs(Os(e,r));if(n<=0)return null;let i=e.slice((r+32)*2,(r+32)*2+n*2);if(i.length<n*2)return null;let o=new Uint8Array(n);for(let s=0;s<n;s++)o[s]=parseInt(i.slice(s*2,s*2+2),16);return new TextDecoder().decode(o).replace(/\0+$/,"").trim()||null}function tee(t){let e=BU(t);if(e)return e;let r=Lr(t);if(r.length!==64)return null;let n=[];for(let o=0;o<32;o++){let a=parseInt(r.slice(o*2,o*2+2),16);if(a===0)break;n.push(a)}return new TextDecoder().decode(new Uint8Array(n)).trim()||null}function ree(t){let e=Lr(t);if(e.length<64)return null;let r=Rs(Os(e,0));return Number.isFinite(r)&&r>=0&&r<=36?r:null}async function zU(t,e,r){let n=e.map(()=>({symbol:null,decimals:null})),i=r?.trim()||xs(t);if(!i||e.length===0)return n;let o=qU(t),a=[];e.forEach((l,c)=>{LU.test(l)&&(a.push({index:c,field:"symbol",call:{target:l,allowFailure:!0,callData:XQ}}),a.push({index:c,field:"decimals",call:{target:l,allowFailure:!0,callData:QQ}}))});let s=[];for(let l=0;l<a.length;l+=uv)s.push(a.slice(l,l+uv));return await Promise.all(s.map(async l=>{try{let c=await Tm(i,o,jU(l.map(d=>d.call)));FU(c,l.length).forEach((d,f)=>{if(!d.success)return;let m=l[f];m.field==="symbol"?n[m.index].symbol=tee(d.returnData):n[m.index].decimals=ree(d.returnData)})}catch{}})),n}async function VU(t,e,r){let n=new Array(e.length).fill(null),i=r?.trim()||xs(t);if(!i||e.length===0)return n;let o=qU(t),a=[];e.forEach((l,c)=>{if(!LU.test(l.contract))return;let u=eee(l.tokenId);u!==null&&a.push({index:c,call:{target:l.contract,allowFailure:!0,callData:u}})});let s=[];for(let l=0;l<a.length;l+=uv)s.push(a.slice(l,l+uv));return await Promise.all(s.map(async l=>{try{let c=await Tm(i,o,jU(l.map(d=>d.call)));FU(c,l.length).forEach((d,f)=>{d.success&&(n[l[f].index]=BU(d.returnData))})}catch{}})),n}p();function nee(t){return dv(String(t))??"0"}function dv(t){let e=t.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let r=e[1]==="-"?"-":"",n=e[2]??"",i=e[3]??"";if(n===""&&i==="")return null;let o=e[4]?parseInt(e[4],10):0,a=n+i,s=n.length+o,l;return s<=0?l=`0.${"0".repeat(-s)}${a}`:s>=a.length?l=a+"0".repeat(s-a.length):l=`${a.slice(0,s)}.${a.slice(s)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":r+l}function RA(t){let e=dv(t);if(e===null||e.startsWith("-"))return null;let[r,n=""]=e.split(".");return{mant:BigInt(r+n),frac:n.length}}function NA(t,e){let r=t<0n,n=(r?-t:t).toString(),i;if(e===0)i=n;else{let o=n.padStart(e+1,"0"),a=o.length-e;i=`${o.slice(0,a)}.${o.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return r?`-${i}`:i}function Id(t){if(typeof t=="number")return Number.isFinite(t)&&t>0?nee(t):null;if(typeof t!="string")return null;let e=t.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let r=dv(e[0]);return r&&r!=="0"&&!r.startsWith("-")?r:null}function Od(t,e){let r=dv(t);if(r===null||e<0)return t;let n=r.startsWith("-"),[i,o=""]=(n?r.slice(1):r).split(".");if(o.length<=e)return r;let a=e===0?i:`${i}.${o.slice(0,e)}`,s=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${s}`:s}function Rd(t,e,r,n){let i=RA(t);if(!i||r<=0n||n<0)return t;let o=i.mant*e*10n**BigInt(n)/(r*10n**BigInt(i.frac));return NA(o,n)}function pv(t,e){let r=RA(t),n=RA(e);if(!r||!n){let s=Number(t),l=Number(e);return s<l?-1:s>l?1:0}let i=Math.max(r.frac,n.frac),o=r.mant*10n**BigInt(i-r.frac),a=n.mant*10n**BigInt(i-n.frac);return o<a?-1:o>a?1:0}var iee={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"}]},oee="payment-required",aee="PAYMENT-SIGNATURE",see="X-PAYMENT",lee="payment-response",cee="x-payment-response",uee=600,dee=300,pee={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 ZU(t){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(t,"utf8").toString("base64")}function GU(t){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(t,"base64").toString("utf8")}function fee(){let t=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<32;r++)t[r]=Math.floor(Math.random()*256);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function WU(t){let e=String(t);if(e.includes(":")){let[n,i]=e.split(":"),o=parseInt(i,10);if(n!=="eip155"||Number.isNaN(o))throw new Error(`Unsupported x402 network: ${t} (only EVM "eip155:*" is supported)`);return o}let r=pee[e.toLowerCase()];if(r===void 0)throw new Error(`Unsupported x402 network: ${t}`);return r}function KU(t){if(!t.query||Object.keys(t.query).length===0)return t.url;let e=Object.entries(t.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return t.url.includes("?")?`${t.url}&${e}`:`${t.url}?${e}`}function fv(t){let e=t.headers[oee];if(e){let i=HU(hee(e));return i&&Array.isArray(i.accepts)?{version:2,payload:i}:null}let r=t.data,n=r&&typeof r=="object"?r:HU(r);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function HU(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}function hee(t){try{return GU(t)}catch{return null}}function mee(t){let e=t.amount??t.maxAmountRequired;return typeof t.scheme!="string"||typeof t.network!="string"||e==null||typeof t.asset!="string"||typeof t.payTo!="string"?null:{scheme:t.scheme,network:t.network,amount:String(e),asset:t.asset,payTo:t.payTo,...typeof t.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:t.maxTimeoutSeconds}:{},...t.extra&&typeof t.extra=="object"?{extra:t.extra}:{},...typeof t.resource=="string"?{resource:t.resource}:{},...typeof t.description=="string"?{description:t.description}:{},...typeof t.mimeType=="string"?{mimeType:t.mimeType}:{},...t.outputSchema!=null?{outputSchema:t.outputSchema}:{}}}function gee(t){let e=null;for(let r of t){let n=mee(r);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return WU(n.network),n}catch(i){e=i instanceof Error?i.message:String(i)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function $A(t,e,r,n){let i=fv(t);if(!i)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:a}=i,s=gee(a.accepts??[]);if(!r)throw new Error("No connected wallet address to build the payment from");let l=WU(s.network),c=Math.floor(Date.now()/1e3),u={from:r,to:s.payTo,value:String(s.amount),validAfter:String(Math.max(0,c-uee)),validBefore:String(c+(s.maxTimeoutSeconds??dee)),nonce:fee()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:l,verifyingContract:s.asset},types:iee,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:KU(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:o,requirements:s,authorization:u,typedData:d,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...n?{userQuery:n}:{}}}async function yee(t,e,r,n){let i=KU(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:$A(o,e,r,n)};if(!o.ok)throw new Error(rt(o));return{status:"ok",data:o.data}}async function MA(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...DA(e,r)}});if(s.ok)return s.data;throw new Error(bee(s)??rt(s))}function _ee(t){return fv(t)!==null}function YU(t){let e=JU(t);return e?.errorReason?e.errorReason:fv(t)?.payload.error??null}function bee(t){let e=YU(t);return e?`x402 payment rejected: ${e}`:null}var vee={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 DA(t,e){let{requirements:r,authorization:n}=t,i={signature:e,authorization:n};if(t.x402Version===1){let a={x402Version:1,scheme:r.scheme,network:r.network,payload:i};return{[see]:ZU(JSON.stringify(a))}}let o={x402Version:2,...t.resource!=null?{resource:t.resource}:{},accepted:wee(r),payload:i,...t.extensions!=null?{extensions:t.extensions}:{}};return{[aee]:ZU(JSON.stringify(o))}}function wee(t){let{resource:e,description:r,mimeType:n,outputSchema:i,...o}=t;return o}function JU(t){let e=t.headers[lee]??t.headers[cee];if(!e)return null;try{return JSON.parse(GU(e))}catch{return null}}function See(t,e){return t==null?e:vee[t]??`Chain ${t}`}async function XU(t){let e=t.requirements,n=t.resource?.description||e.description,i=t.chainId??null,o=null,a=null;if(i!=null){let[l]=await zU("0x"+i.toString(16),[e.asset]);o=l?.symbol??null,a=l?.decimals??null}let s=String(e.amount);if(a!==null)try{s=NA(BigInt(e.amount),a)}catch{}return{amount:s,asset:o||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:i!=null?`eip155:${i}`:e.network,networkRaw:e.network,chainId:i,networkLabel:See(i,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:t.request.url}}function UA(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=$A(e,{url:r.url,method:r.method,body:r.body,headers:r.headers},n)}catch{return null}let a;try{a=await i({typedData:o.typedData,display:await XU(o)})}catch{a=null}return a?DA(o,a):null}}p();p();var wl=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Xc(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function km(t){if(t?.aborted)throw new wl}function qA(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var QU={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},Tee="https://nft.keyring.app/api/gemini-stable",kee="https://generativelanguage.googleapis.com",Pee=new Set([408,429,500,502,503,504]),eq=3e4,hv=t=>new Promise(e=>setTimeout(e,t));function mv(t,e,r){if(r!=null&&r>0)return Math.min(r,eq);let n=Math.min(e*2**(t-1),eq);return n/2+Math.random()*(n/2)}function Eee(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pr=class{constructor(e){h(this,"model");h(this,"maxTokens");h(this,"temperature");h(this,"baseUrl");h(this,"apiKey");h(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?kee:Tee)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;km(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let y of c){let _=y.parts.map(b=>b.functionCall?`fc:${b.functionCall.name}`:b.functionResponse?`fr:${b.functionResponse.name}`:`text:${(b.text??"").slice(0,40)}`).join(", ");console.log(` ${y.role}: [${_}]`)}}let u=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),d={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let f={contents:c,generationConfig:d};i&&(f.systemInstruction=i),r?.length?(f.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(f.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(f.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,g="Unknown error";for(let y=1;y<=a;y++){km(l);let _;try{_=await Oe.post(m,f,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(M){if(Xc(M))throw M;if(g=M instanceof Error?M.message:String(M),y>=a)break;await hv(mv(y,s));continue}if(!_.ok){let M=typeof _.data=="string"?_.data:JSON.stringify(_.data)||_.statusText;if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${_.status}: ${M}`,!Pee.has(_.status))throw new Error(g);if(y>=a)break;let A=Eee(_.headers["retry-after"]??null);await hv(mv(y,s,A));continue}if(_.data==null||typeof _.data!="object"){if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,y>=a)break;await hv(mv(y,s));continue}let b=_.data,w=b.candidates?.[0];if(!w)return{text:"",toolCalls:[]};let T="",E=[],C=w.content?.parts;if(!Array.isArray(C)||C.length===0){let M=w.finishReason;if(!(M==="SAFETY"||M==="RECITATION")&&y<a){g=`Gemini returned an empty turn (finishReason=${M??"none"})`,await hv(mv(y,s));continue}return{text:"",toolCalls:[]}}for(let M of C)M.text&&(T+=M.text),M.functionCall&&E.push({toolName:M.functionCall.name,args:M.functionCall.args??{},callId:M.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let N=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0}:void 0;return{text:T,toolCalls:E,usage:N}}throw new Error(g)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],c=s.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!c&&!u?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],c=o[o.length-1];l.role==="function"&&!c?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
440
+ `+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=ho(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&ym.assertOptions(n,{silentJSONParsing:Ii.transitional(Ii.boolean),forcedJSONParsing:Ii.transitional(Ii.boolean),clarifyTimeoutError:Ii.transitional(Ii.boolean),legacyInterceptorReqResOrdering:Ii.transitional(Ii.boolean)},!1),i!=null&&(j.isFunction(i)?r.paramsSerializer={serialize:i}:ym.assertOptions(i,{encode:Ii.function,serialize:Ii.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),ym.assertOptions(r,{baseUrl:Ii.spelling("baseURL"),withXsrfToken:Ii.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&j.merge(o.common,o[r.method]);o&&j.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=mr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||wd;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let u,d=0,f;if(!l){let g=[nv.bind(this),void 0];for(g.unshift(...s),g.push(...c),f=g.length,u=Promise.resolve(r);d<f;)u=u.then(g[d++],g[d++]);return u}f=s.length;let m=r;for(;d<f;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{u=nv.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,f=c.length;d<f;)u=u.then(c[d++],c[d++]);return u}getUri(e){e=ho(this.defaults,e);let r=gm(e.baseURL,e.url,e.allowAbsoluteUrls);return pm(r,e.params,e.paramsSerializer)}};j.forEach(["delete","get","head","options"],function(e){Ed.prototype[e]=function(r,n){return this.request(ho(n||{},{method:e,url:r,data:(n||{}).data}))}});j.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(ho(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Ed.prototype[e]=r(),e!=="query"&&(Ed.prototype[e+"Form"]=r(!0))});var _m=Ed;p();var yA=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new Fo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},SU=yA;p();function _A(t){return function(r){return t.apply(null,r)}}p();function bA(t){return j.isObject(t)&&t.isAxiosError===!0}p();var vA={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(vA).forEach(([t,e])=>{vA[e]=t});var TU=vA;function kU(t){let e=new _m(t),r=sm(_m.prototype.request,e);return j.extend(r,_m.prototype,e,{allOwnKeys:!0}),j.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return kU(ho(t,i))},r}var kr=kU(Td);kr.Axios=_m;kr.CanceledError=Fo;kr.CancelToken=SU;kr.isCancel=hm;kr.VERSION=Pd;kr.toFormData=bl;kr.AxiosError=De;kr.Cancel=kr.CanceledError;kr.all=function(e){return Promise.all(e)};kr.spread=_A;kr.isAxiosError=bA;kr.mergeConfig=ho;kr.AxiosHeaders=mr;kr.formToJSON=t=>Qb(j.isHTMLForm(t)?new FormData(t):t);kr.getAdapter=rv.getAdapter;kr.HttpStatusCode=TU;kr.default=kr;var ov=kr;var{Axios:g3e,AxiosError:y3e,CanceledError:_3e,isCancel:b3e,CancelToken:v3e,VERSION:w3e,all:S3e,Cancel:T3e,isAxiosError:k3e,spread:P3e,toFormData:E3e,AxiosHeaders:A3e,HttpStatusCode:C3e,formToJSON:x3e,getAdapter:I3e,mergeConfig:O3e,create:R3e}=ov;var PU="0.2.46";var RQ=`keyring-agent-core/${PU} (Keyring Chatbot Agent; +https://keyring.app)`,wA=null;function EU(t){wA=t}var NQ=["payment-signature","x-payment"];function $Q(t){return t?Object.keys(t).some(e=>NQ.includes(e.toLowerCase())):!1}var AU;function bm(t){AU=t}var MQ=3e4,DQ=typeof process<"u"&&process.versions?.node!=null,SA=class{constructor(e={}){h(this,"instance");this.instance=ov.create({baseURL:e.baseURL,timeout:e.timeout??MQ,validateStatus:()=>!0,headers:{Accept:"application/json",...DQ?{"User-Agent":e.userAgent??RQ}:{},...e.headers}})}async request(e,r,n,i={}){let o=i.signal??AU,a=await this.instance.request({...i,signal:o,method:e,url:r,data:n}),s={};for(let[c,u]of Object.entries(a.headers??{}))u!=null&&(s[c.toLowerCase()]=String(u));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:s};if(l.status===402&&wA&&!$Q(i.headers)){let c=await wA(l,{url:r,method:String(e),body:n,headers:i.headers});if(c)return this.request(e,r,n,{...i,headers:{...i.headers,...c}})}return l}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},Oe=new SA;function rt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}p();p();var CU=mb(sv());function Bt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function UQ(t){return new Uint8Array(CU.keccak256.arrayBuffer(t))}function vm(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function xU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function IU(t){return new TextEncoder().encode(t)}function Yc(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function qQ(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function LQ(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function OU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return vm(e)}function wm(t){return OU(BigInt(t))}function RU(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function NU(t){let e=RU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(NU).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function jQ(t){let e=(t.inputs??[]).map(NU).join(",");return`${t.name??""}(${e})`}function TA(t,e){let r=zQ(t.type);if(r){let[i,o]=r;return FQ({...t,type:o},e,i)}if(t.type==="tuple")return BQ(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:qQ(vm(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=RU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:wm(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:OU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?vm(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:LQ(o)}}if(n==="bytes"){let i=typeof e=="string"?vm(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Yc(wm(i.length),a)}}if(n==="string"){let i=typeof e=="string"?IU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:Yc(wm(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function kA(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(wm(e+i)),n.push(a),i+=a.length):r.push(a);return Yc(...r,...n)}function FQ(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=TA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=kA(o);if(n){let s=wm(o.length);return{dynamic:!0,encoded:o.length>0?Yc(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:Yc(...o.map(a=>a.encoded))}}function BQ(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=TA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?kA(i):Yc(...i.map(o=>o.encoded))}}function zQ(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function PA(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>TA(i,e[o])),n=kA(r);return xU(n)}function Ad({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=jQ(n),o=UQ(IU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):vm(PA(a,r).slice(2));return xU(Yc(o,s))}p();var EA=mb(sv()),$U=2n**96n;function qr(t,e=8){return!Number.isFinite(t)||t===0?t:Number(t.toPrecision(e))}function MU(t,e,r){let n=t*t,i=$U*$U,o=n*10n**18n/i;return Number(o)/1e18*Math.pow(10,e-r)}function mo(t,e,r){return Math.pow(1.0001,t)*Math.pow(10,e-r)}function Jc(t,e,r){if(t<=0)throw new Error("priceToTick: price must be > 0");let n=t/Math.pow(10,e-r),i=Math.log(n)/Math.log(1.0001),o=Math.round(i);return Math.abs(i-o)<.001?o:Math.floor(i)}function xd(t,e,r){let n={minPrice:t,maxPrice:e,inverted:!1};if(!Number.isFinite(t)||!Number.isFinite(e)||!Number.isFinite(r)||t<=0||e<=0||r<=0||t>=e)return n;let i={minPrice:1/e,maxPrice:1/t,inverted:!0},o=c=>r>=c.minPrice&&r<=c.maxPrice,a=o(n),s=o(i);if(a&&!s)return n;if(s&&!a)return i;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/r));return l(i)<l(n)?i:n}function Bo(t,e,r="nearest"){let n=Math.abs(t-Math.round(t))<1e-6?Math.round(t):t,i=(n%e+e)%e;if(i===0)return n;let o=n-i,a=o+e;return r==="down"?o:r==="up"?a:n-o<a-n?o:a}var vl=-887272,Cd=887272;function zo(t){return t<vl?vl:t>Cd?Cd:t}var VQ=/^0x[0-9a-f]+$/i;function Lr(t){return t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t}function lv(t){let e=Lr(t).toLowerCase();if(e.length>64)throw new Error(`pad32: input too long (${e.length})`);return e.padStart(64,"0")}function cv(t){if(!VQ.test(t)||Lr(t).length!==40)throw new Error(`encodeAddress: invalid address ${t}`);return lv(t.toLowerCase())}function fi(t,e=256){let r=typeof t=="bigint"?t:BigInt(t);if(r<0n)throw new Error("encodeUint: negative");let n=r.toString(16);if(n.length>e/4)throw new Error(`encodeUint: overflow ${e}`);return lv(n)}function AA(t){let e=typeof t=="bigint"?t:BigInt(t);if(e>=0n)return lv(e.toString(16));let r=1n<<256n;return lv((r+e).toString(16))}function DU(t){return"0x"+(0,EA.keccak_256)(ZQ(t))}function ZQ(t){let e=Lr(t),r=new Uint8Array(e.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(e.substring(n*2,n*2+2),16);return r}function zn(t){return"0x"+(0,EA.keccak_256)(new TextEncoder().encode(t)).slice(0,8)}function Sm(t,e){let r=t.substring(e,e+64);return r?BigInt("0x"+r):0n}function CA(t,e){let r=t.substring(e,e+64),n=BigInt("0x"+r),i=1n<<256n,o=1n<<23n;return n>=1n<<255n?Number(n-i):(n<o,Number(n))}function xA(t,e){return"0x"+t.substring(e+24,e+64).toLowerCase()}p();var Oi={"0x1":"https://ethereum-rpc.publicnode.com","0xa":"https://mainnet.optimism.io","0x38":"https://bsc-dataseed.binance.org","0x89":"https://polygon-bor-rpc.publicnode.com","0x2105":"https://mainnet.base.org","0xa4b1":"https://arb1.arbitrum.io/rpc","0xa86a":"https://avalanche-c-chain-rpc.publicnode.com","0xe708":"https://rpc.linea.build","0x64":"https://gnosis-rpc.publicnode.com","0x3e7":"https://rpc.hyperliquid.xyz/evm","0x1388":"https://rpc.mantle.xyz","0x8f":"https://rpc.monad.xyz"};function HQ(t){return Oi[t.toLowerCase()]}var UU={};function IA(t){let e={};if(t)for(let[r,n]of Object.entries(t))typeof n=="string"&&n.trim()&&(e[r.toLowerCase()]=n.trim());UU=e}function xs(t){let e=t.toLowerCase();return UU[e]??Oi[e]}async function Is(t,e,r){for(let i=0;i<=5;i++){let o=await Oe.post(t,{jsonrpc:"2.0",id:Date.now(),method:e,params:r},{headers:{"Content-Type":"application/json"}});if(o.status===429&&i<5){await new Promise(s=>setTimeout(s,2**i*500));continue}if(!o.ok)throw new Error(`RPC ${e}: ${rt(o)}`);let a=o.data;if(a.error)throw new Error(`RPC ${e}: ${a.error.message}`);if(a.result===void 0)throw new Error(`RPC ${e}: empty result`);return a.result}throw new Error(`RPC ${e}: exceeded max retries (429)`)}function Tm(t,e,r){return Is(t,"eth_call",[{to:e,data:r},"latest"])}async function OA(t,e,r){let n=xs(t);if(!n)return null;try{return await Tm(n,e,r)}catch{return null}}var GQ="0xcA11bde05977b3631167028862bE2a173976CA11",WQ={};function qU(t){return WQ[t.toLowerCase()]??GQ}var KQ=zn("aggregate3((address,bool,bytes)[])"),YQ=[{type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],JQ=zn("tokenURI(uint256)"),XQ=zn("symbol()"),QQ=zn("decimals()"),uv=50,LU=/^0x[0-9a-fA-F]{40}$/;function Os(t,e){return t.slice(e*2,e*2+64)}function Rs(t){return t?Number(BigInt("0x"+t)):0}function eee(t){try{return JQ+fi(BigInt(t))}catch{return null}}function jU(t){let e=PA(YQ,[t]);return KQ+Lr(e)}function FU(t,e){let r=Lr(t);if(r.length<64)return[];let n=Rs(Os(r,0)),i=Rs(Os(r,n)),o=Math.min(i,e),a=n+32,s=[];for(let l=0;l<o;l++){let c=a+Rs(Os(r,a+l*32)),u=Rs(Os(r,c))===1,d=c+Rs(Os(r,c+32)),f=Rs(Os(r,d)),m=r.slice((d+32)*2,(d+32)*2+f*2);s.push({success:u,returnData:"0x"+m})}return s}function BU(t){let e=Lr(t);if(e.length<128)return null;let r=Rs(Os(e,0)),n=Rs(Os(e,r));if(n<=0)return null;let i=e.slice((r+32)*2,(r+32)*2+n*2);if(i.length<n*2)return null;let o=new Uint8Array(n);for(let s=0;s<n;s++)o[s]=parseInt(i.slice(s*2,s*2+2),16);return new TextDecoder().decode(o).replace(/\0+$/,"").trim()||null}function tee(t){let e=BU(t);if(e)return e;let r=Lr(t);if(r.length!==64)return null;let n=[];for(let o=0;o<32;o++){let a=parseInt(r.slice(o*2,o*2+2),16);if(a===0)break;n.push(a)}return new TextDecoder().decode(new Uint8Array(n)).trim()||null}function ree(t){let e=Lr(t);if(e.length<64)return null;let r=Rs(Os(e,0));return Number.isFinite(r)&&r>=0&&r<=36?r:null}async function zU(t,e,r){let n=e.map(()=>({symbol:null,decimals:null})),i=r?.trim()||xs(t);if(!i||e.length===0)return n;let o=qU(t),a=[];e.forEach((l,c)=>{LU.test(l)&&(a.push({index:c,field:"symbol",call:{target:l,allowFailure:!0,callData:XQ}}),a.push({index:c,field:"decimals",call:{target:l,allowFailure:!0,callData:QQ}}))});let s=[];for(let l=0;l<a.length;l+=uv)s.push(a.slice(l,l+uv));return await Promise.all(s.map(async l=>{try{let c=await Tm(i,o,jU(l.map(d=>d.call)));FU(c,l.length).forEach((d,f)=>{if(!d.success)return;let m=l[f];m.field==="symbol"?n[m.index].symbol=tee(d.returnData):n[m.index].decimals=ree(d.returnData)})}catch{}})),n}async function VU(t,e,r){let n=new Array(e.length).fill(null),i=r?.trim()||xs(t);if(!i||e.length===0)return n;let o=qU(t),a=[];e.forEach((l,c)=>{if(!LU.test(l.contract))return;let u=eee(l.tokenId);u!==null&&a.push({index:c,call:{target:l.contract,allowFailure:!0,callData:u}})});let s=[];for(let l=0;l<a.length;l+=uv)s.push(a.slice(l,l+uv));return await Promise.all(s.map(async l=>{try{let c=await Tm(i,o,jU(l.map(d=>d.call)));FU(c,l.length).forEach((d,f)=>{d.success&&(n[l[f].index]=BU(d.returnData))})}catch{}})),n}p();function nee(t){return dv(String(t))??"0"}function dv(t){let e=t.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let r=e[1]==="-"?"-":"",n=e[2]??"",i=e[3]??"";if(n===""&&i==="")return null;let o=e[4]?parseInt(e[4],10):0,a=n+i,s=n.length+o,l;return s<=0?l=`0.${"0".repeat(-s)}${a}`:s>=a.length?l=a+"0".repeat(s-a.length):l=`${a.slice(0,s)}.${a.slice(s)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":r+l}function RA(t){let e=dv(t);if(e===null||e.startsWith("-"))return null;let[r,n=""]=e.split(".");return{mant:BigInt(r+n),frac:n.length}}function NA(t,e){let r=t<0n,n=(r?-t:t).toString(),i;if(e===0)i=n;else{let o=n.padStart(e+1,"0"),a=o.length-e;i=`${o.slice(0,a)}.${o.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return r?`-${i}`:i}function Id(t){if(typeof t=="number")return Number.isFinite(t)&&t>0?nee(t):null;if(typeof t!="string")return null;let e=t.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let r=dv(e[0]);return r&&r!=="0"&&!r.startsWith("-")?r:null}function Od(t,e){let r=dv(t);if(r===null||e<0)return t;let n=r.startsWith("-"),[i,o=""]=(n?r.slice(1):r).split(".");if(o.length<=e)return r;let a=e===0?i:`${i}.${o.slice(0,e)}`,s=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${s}`:s}function Rd(t,e,r,n){let i=RA(t);if(!i||r<=0n||n<0)return t;let o=i.mant*e*10n**BigInt(n)/(r*10n**BigInt(i.frac));return NA(o,n)}function pv(t,e){let r=RA(t),n=RA(e);if(!r||!n){let s=Number(t),l=Number(e);return s<l?-1:s>l?1:0}let i=Math.max(r.frac,n.frac),o=r.mant*10n**BigInt(i-r.frac),a=n.mant*10n**BigInt(i-n.frac);return o<a?-1:o>a?1:0}var iee={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"}]},oee="payment-required",aee="PAYMENT-SIGNATURE",see="X-PAYMENT",lee="payment-response",cee="x-payment-response",uee=600,dee=300,pee={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 ZU(t){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(r)}return Buffer.from(t,"utf8").toString("base64")}function GU(t){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}return Buffer.from(t,"base64").toString("utf8")}function fee(){let t=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<32;r++)t[r]=Math.floor(Math.random()*256);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function WU(t){let e=String(t);if(e.includes(":")){let[n,i]=e.split(":"),o=parseInt(i,10);if(n!=="eip155"||Number.isNaN(o))throw new Error(`Unsupported x402 network: ${t} (only EVM "eip155:*" is supported)`);return o}let r=pee[e.toLowerCase()];if(r===void 0)throw new Error(`Unsupported x402 network: ${t}`);return r}function KU(t){if(!t.query||Object.keys(t.query).length===0)return t.url;let e=Object.entries(t.query).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&");return t.url.includes("?")?`${t.url}&${e}`:`${t.url}?${e}`}function fv(t){let e=t.headers[oee];if(e){let i=HU(hee(e));return i&&Array.isArray(i.accepts)?{version:2,payload:i}:null}let r=t.data,n=r&&typeof r=="object"?r:HU(r);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function HU(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}function hee(t){try{return GU(t)}catch{return null}}function mee(t){let e=t.amount??t.maxAmountRequired;return typeof t.scheme!="string"||typeof t.network!="string"||e==null||typeof t.asset!="string"||typeof t.payTo!="string"?null:{scheme:t.scheme,network:t.network,amount:String(e),asset:t.asset,payTo:t.payTo,...typeof t.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:t.maxTimeoutSeconds}:{},...t.extra&&typeof t.extra=="object"?{extra:t.extra}:{},...typeof t.resource=="string"?{resource:t.resource}:{},...typeof t.description=="string"?{description:t.description}:{},...typeof t.mimeType=="string"?{mimeType:t.mimeType}:{},...t.outputSchema!=null?{outputSchema:t.outputSchema}:{}}}function gee(t){let e=null;for(let r of t){let n=mee(r);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return WU(n.network),n}catch(i){e=i instanceof Error?i.message:String(i)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function $A(t,e,r,n){let i=fv(t);if(!i)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:a}=i,s=gee(a.accepts??[]);if(!r)throw new Error("No connected wallet address to build the payment from");let l=WU(s.network),c=Math.floor(Date.now()/1e3),u={from:r,to:s.payTo,value:String(s.amount),validAfter:String(Math.max(0,c-uee)),validBefore:String(c+(s.maxTimeoutSeconds??dee)),nonce:fee()},d={domain:{name:s.extra?.name,version:s.extra?.version,chainId:l,verifyingContract:s.asset},types:iee,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:KU(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:o,requirements:s,authorization:u,typedData:d,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...n?{userQuery:n}:{}}}async function yee(t,e,r,n){let i=KU(e),o=await t.request(e.method??"GET",i,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:$A(o,e,r,n)};if(!o.ok)throw new Error(rt(o));return{status:"ok",data:o.data}}async function MA(t,e,r){let{url:n,method:i,body:o,headers:a}=e.request,s=await t.request(i,n,o,{headers:{...a??{},...DA(e,r)}});if(s.ok)return s.data;throw new Error(bee(s)??rt(s))}function _ee(t){return fv(t)!==null}function YU(t){let e=JU(t);return e?.errorReason?e.errorReason:fv(t)?.payload.error??null}function bee(t){let e=YU(t);return e?`x402 payment rejected: ${e}`:null}var vee={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 DA(t,e){let{requirements:r,authorization:n}=t,i={signature:e,authorization:n};if(t.x402Version===1){let a={x402Version:1,scheme:r.scheme,network:r.network,payload:i};return{[see]:ZU(JSON.stringify(a))}}let o={x402Version:2,...t.resource!=null?{resource:t.resource}:{},accepted:wee(r),payload:i,...t.extensions!=null?{extensions:t.extensions}:{}};return{[aee]:ZU(JSON.stringify(o))}}function wee(t){let{resource:e,description:r,mimeType:n,outputSchema:i,...o}=t;return o}function JU(t){let e=t.headers[lee]??t.headers[cee];if(!e)return null;try{return JSON.parse(GU(e))}catch{return null}}function See(t,e){return t==null?e:vee[t]??`Chain ${t}`}async function XU(t){let e=t.requirements,n=t.resource?.description||e.description,i=t.chainId??null,o=null,a=null;if(i!=null){let[l]=await zU("0x"+i.toString(16),[e.asset]);o=l?.symbol??null,a=l?.decimals??null}let s=String(e.amount);if(a!==null)try{s=NA(BigInt(e.amount),a)}catch{}return{amount:s,asset:o||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:i!=null?`eip155:${i}`:e.network,networkRaw:e.network,chainId:i,networkLabel:See(i,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:t.request.url}}function UA(t){return async(e,r)=>{let n=t.getPayer(),i=t.getSigner();if(!n||!i)return null;let o;try{o=$A(e,{url:r.url,method:r.method,body:r.body,headers:r.headers},n)}catch{return null}let a;try{a=await i({typedData:o.typedData,display:await XU(o)})}catch{a=null}return a?DA(o,a):null}}p();p();var wl=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Xc(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function km(t){if(t?.aborted)throw new wl}function qA(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var QU={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},Tee="https://nft.keyring.app/api/gemini-stable",kee="https://generativelanguage.googleapis.com",Pee=new Set([408,429,500,502,503,504]),eq=3e4,hv=t=>new Promise(e=>setTimeout(e,t));function mv(t,e,r){if(r!=null&&r>0)return Math.min(r,eq);let n=Math.min(e*2**(t-1),eq);return n/2+Math.random()*(n/2)}function Eee(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pr=class{constructor(e){h(this,"model");h(this,"maxTokens");h(this,"temperature");h(this,"baseUrl");h(this,"apiKey");h(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?kee:Tee)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;km(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let y of c){let _=y.parts.map(b=>b.functionCall?`fc:${b.functionCall.name}`:b.functionResponse?`fr:${b.functionResponse.name}`:`text:${(b.text??"").slice(0,40)}`).join(", ");console.log(` ${y.role}: [${_}]`)}}let u=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),d={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let f={contents:c,generationConfig:d};i&&(f.systemInstruction=i),r?.length?(f.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(f.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(f.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,g="Unknown error";for(let y=1;y<=a;y++){km(l);let _;try{_=await Oe.post(m,f,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(M){if(Xc(M))throw M;if(g=M instanceof Error?M.message:String(M),y>=a)break;await hv(mv(y,s));continue}if(!_.ok){let M=typeof _.data=="string"?_.data:JSON.stringify(_.data)||_.statusText;if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${_.status}: ${M}`,!Pee.has(_.status))throw new Error(g);if(y>=a)break;let A=Eee(_.headers["retry-after"]??null);await hv(mv(y,s,A));continue}if(_.data==null||typeof _.data!="object"){if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,y>=a)break;await hv(mv(y,s));continue}let b=_.data,w=b.candidates?.[0];if(!w)return{text:"",toolCalls:[]};let T="",E=[],C=w.content?.parts;if(!Array.isArray(C)||C.length===0){let M=w.finishReason;if(!(M==="SAFETY"||M==="RECITATION")&&y<a){g=`Gemini returned an empty turn (finishReason=${M??"none"})`,await hv(mv(y,s));continue}return{text:"",toolCalls:[]}}for(let M of C)M.text&&(T+=M.text),M.functionCall&&E.push({toolName:M.functionCall.name,args:M.functionCall.args??{},callId:M.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let N=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0}:void 0;return{text:T,toolCalls:E,usage:N}}throw new Error(g)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],c=s.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!c&&!u?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],c=o[o.length-1];l.role==="function"&&!c?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
441
441
  `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:QU[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:QU[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&i.push(o.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};p();var Nd=class{constructor(){h(this,"tools",new Map)}register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await i.execute(r,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};p();p();p();p();p();var $d=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Aee=new Set($d),Sl=[...$d],LA=new Set(Sl),Ri="0x1",Dd="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Cee(t){return t.map(e=>Md[e]??e).join(", ")}function gv(t){let e=new Set;if(t)for(let n of t){let i=yv(n);i&&e.add(i)}let r=$d.filter(n=>!e.has(n));Sl=r.length>0?[...r]:[...$d],LA=new Set(Sl),Ri=Sl.includes("0x1")?"0x1":Sl[0],Dd=Cee(Sl)}var xee={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function tr(t){let e=yv(t);return e&&LA.has(e)?e:null}function yv(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=xee[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&Aee.has(n)?n:null}function go(t){return tr(t)!==null}function Vn(){return[...Sl]}var kl=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Dd}.`);h(this,"requested",r);h(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},Tl=t=>typeof t=="string"&&t.trim()!=="";function sn(t,e){if(Tl(t)){let r=tr(t);if(r)return r;throw new kl(t.trim())}if(Tl(e?.chain)){let r=tr(e.chain);if(r)return r;throw new kl(e.chain.trim())}return null}function _v(t,e){return tr(t)??tr(e?.chain)??void 0}var Md={"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 ve(t){let e=yv(t);return e&&Md[e]?Md[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var Iee={"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 tq(t,e){let r=yv(t),n=r?Iee[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Oee={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function rq(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?Oee[e]??null:null}var Ree={"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 nq(t){let e=tr(t);return e?Ree[e]??null:null}function Ud(t,e){if(!Tl(t))return null;let r=tr(t),n=tr(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:Md[r]??r,connectedLabel:Md[n]??n}}function iq(t,e){let r=typeof t=="string"?t.trim():"",n=e&&e.length?e.filter(o=>LA.has(o)):[];return(n.length?n:Sl).map(o=>{let a=Md[o]??o;return{label:a,prompt:r?`${r} (${a})`:a}})}function qd(t,e){return{actionButtons:iq(e),_instructions:`The user wants to ${t} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var gr=class extends Error{constructor(r,n){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");h(this,"code","needs_chain_selection");h(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=iq(r,n)}},Pm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");h(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function sr(t,e){if(Tl(t))return t.trim();if(Tl(e?.walletAddress))return e.walletAddress.trim();throw new Pm}function jr(t,e,r){if(Tl(t)){let n=tr(t);if(n)return n;throw new kl(t.trim())}if(Tl(e?.chain)){let n=tr(e.chain);if(n)return n;throw new kl(e.chain.trim())}if(Tl(e?.walletAddress))throw new gr(typeof e?.query=="string"?e.query:void 0,r);return Ri}var se=class{constructor(){h(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=Nee(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 gr?{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 Pm?{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 Nee(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons,n=Array.isArray(r)&&r.length>0?r:void 0,i=e.ui,o=i&&typeof i=="object"&&typeof i.component=="string"?i:void 0;if(!n&&!o)return{data:t};let{actionButtons:a,ui:s,...l}=e;return{data:l,...n?{actionButtons:n}:{},...o?{ui:o}:{}}}p();p();var $ee="https://wallet-api.pantograph.app",Mee="0x0000000000000000000000000000000000000000",sq={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},lq={"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 Dee(t){return sq[t.toLowerCase()]||t}function oq(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function jA(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,o=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function FA(t){if(Array.isArray(t))return t;let e=t;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function kn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function aq(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=kn(t.price_change_percentage_24h)??kn(t.priceChange24h)??kn(t.usd_price_24hr_percent_change)??kn(t.price_change_24h)??kn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:kn(t.price)??kn(t.usd_price),marketCap:kn(t.market_cap)??kn(t.marketCap),totalVolume:{"24h":kn(t.total_volume)??kn(t.volume24h)},pricePercentChange:{"24h":i}}}var Pn=class{constructor(e){h(this,"baseUrl");this.baseUrl=(e?.baseUrl??$ee).replace(/\/+$/,"")}tokensUrl(e,r){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(r)}`}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),i=this.tokensUrl(r,n),o=await Oe.get(i);if(!o.ok)return;let a=FA(o.data),s=new Map;for(let l of a)l.address&&s.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=s.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getTokenMetadata(e,r){try{let n=this.tokensUrl(r,e),i=await Oe.get(n);if(!i.ok)return null;let o=FA(i.data),a=e.toLowerCase()===Mee,s=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return s?jA(s):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=this.tokensUrl(r,e.join(",")),o=await Oe.get(i);if(!o.ok)return n;let a=FA(o.data),s=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&s.has(c)&&(n[c]=jA(l))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ri,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=oq({chainId:o,key:r}),s=`${this.baseUrl}/token-list/all?${a}`,l=await Oe.get(s);if(!l.ok)throw new Error(rt(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(jA)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ri,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=lq[r.toLowerCase()]??[],a=i!=null?i+o.length:n+o.length,[s,l]=await Promise.allSettled([this.fetchTopGainers(r,a),o.length>0?this.getTokensMetadata(o,r):Promise.resolve({})]),c=s.status==="fulfilled"?s.value:[],u=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>aq(y,r)):[],d=new Set,f=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),f.push(y))}let m=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...f,...m].slice(0,i):[...f,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=kn(a.market_cap)??kn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":kn(a.total_volume)??kn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=parseInt(e,16),o=oq({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 Oe.get(a);if(!c.ok)throw new Error(rt(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=>aq(l,e))}async getTopGainers(e){let r=e?.chain||Ri,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var Uee="https://nft.keyring.app",qee="https://nft.keyring.app",Lee=.01,et=5,rr=1e3,jee=25,Fee="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Bee="0x0000000000000000000000000000000000000000",tt=class extends Error{constructor(r,n){super(n);h(this,"status",r);this.name="MoralisHttpError"}};function lr(t){return t||Ri}function nr(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ir(t){return new Promise(e=>setTimeout(e,t))}function zee(t){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!t||typeof t!="object")return e;let r=t;if("active_protocols"in r||"total_usd_value"in r){let i=r;return{...e,...i,protocols:i.protocols||[]}}let n=r.result;return!n||typeof n!="object"?e:{active_protocols:n.activeProtocols??0,total_positions:n.totalPositions??0,total_usd_value:n.totalUsd??0,total_unclaimed_usd_value:n.totalUnclaimedUsd??0,protocols:(n.protocols||[]).map(i=>({protocol_id:i.protocolId,protocol_name:i.protocolName,protocol_url:i.protocolUrl??"",protocol_logo:i.protocolLogo??"",positions:i.positionCount??0,total_usd_value:i.totalUsd??0,total_unclaimed_usd_value:i.totalUnclaimedUsd??0,account_health_factor:i.accountHealthFactor??null}))}}function Vee(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function BA(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var lt=class{constructor(e){h(this,"baseUrl");h(this,"v1BaseUrl");h(this,"pantograph");this.baseUrl=(e?.baseUrl??Uee).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??qee).replace(/\/+$/,""),this.pantograph=new Pn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=lr(n),l="Unknown error";for(let c=1;c<=et;c++)try{let u={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(u.token_addresses=i);let d=[],f=null;do{f&&(u.cursor=f);let g=nr(u),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await Oe.get(y);if(!_.ok)throw new tt(_.status,rt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),f=w?.cursor??null}while(f);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===Fee?Bee:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=Lee)),{success:!0,data:m}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;c<et&&await ir(rr)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=lr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=et;s++)try{let[l,c]=await Promise.allSettled([Oe.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${nr({chain:i,addresses:[r]})}`),Oe.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${nr({chain:i,include:"percent_change"})}`)]),u=null;if(l.status==="fulfilled"&&l.value.ok){let f=l.value.data;u=(Array.isArray(f)?f:Array.isArray(f?.data)?f.data:[])[0]??null}if(!u){o="Token metadata not found",s<et&&await ir(rr);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let f=c.value.data;d=f?.data??f}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ir(rr)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=100,excludeSpam:o=!1,cursor:a,tokenAddresses:s,includePrices:l,format:c="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let u=lr(n),d=[],f=a,m,g;for(let y=0;y<jee;y++){let _=await this.fetchWalletNftsPage({address:r,moralisChain:u,limit:i,excludeSpam:o,cursor:f,tokenAddresses:s,includePrices:l,format:c});if(!_.success){if(d.length===0)return _;break}let b=_.data;if(!b)break;let{result:w,cursor:T,page:E,page_size:C}=b;if(Array.isArray(w)&&d.push(...w),m=E,g=C,f=typeof T=="string"&&T.trim()?T:void 0,!f)break}return{success:!0,data:{result:d,cursor:f,page:m,page_size:g}}}async fetchWalletNftsPage(e){let{address:r,moralisChain:n,limit:i,excludeSpam:o,cursor:a,tokenAddresses:s,includePrices:l,format:c}=e,u="Unknown error";for(let d=1;d<=et;d++)try{let f={chain:n,format:c,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(f.cursor=a),l&&(f.include_prices=!0),s&&s.length>0&&(f.token_addresses=s);let m=nr(f),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${m}`,y=await Oe.get(g);if(!y.ok)throw new tt(y.status,rt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(f){if(u=f instanceof Error?f.message:"Unknown error",f instanceof tt&&f.status===400)break;d<et&&await ir(rr)}return{success:!1,error:u}}async getWalletNftCollections(e){let{address:r,chain:n,limit:i=100,excludeSpam:o=!0,cursor:a}=e;if(!r)return{success:!1,error:"Address is required"};let s=lr(n),l="Unknown error";for(let c=1;c<=et;c++)try{let u={chain:s,limit:i,exclude_spam:o};a&&(u.cursor=a);let d=nr(u),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/collections?${d}`,m=await Oe.get(f);if(!m.ok)throw new tt(m.status,rt(m));let g=m.data;return{success:!0,data:g?.data??g}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof tt&&u.status===400)break;c<et&&await ir(rr)}return{success:!1,error:l}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!Bt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=lr(i),u="Unknown error";for(let d=1;d<=et;d++)try{let f={chain:c,format:o,normalizeMetadata:a,media_items:s};l&&(f.include=l);let m=nr(f),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await Oe.get(g);if(!y.ok)throw new tt(y.status,rt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(f){if(u=f instanceof Error?f.message:"Unknown error",f instanceof tt&&f.status===400)break;d<et&&await ir(rr)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=lr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=nr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,c=await Oe.get(l);if(!c.ok)throw new tt(c.status,rt(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ir(rr)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:f}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=lr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=et;_++)try{let b={chain:m,limit:g,order:u};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),c&&(b.cursor=c),d!=null&&(b.include_internal_transactions=d),f!=null&&(b.nft_metadata=f);let w=nr(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await Oe.get(T);if(!E.ok)throw new tt(E.status,rt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof tt&&b.status===400)break;_<et&&await ir(rr)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:c,cursor:u,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let f=lr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=et;y++)try{let _={chain:f,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),c!=null&&(_.to_block=c),u&&(_.cursor=u),i?.length&&(_.contract_addresses=i);let b=nr(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await Oe.get(w);if(!T.ok)throw new tt(T.status,rt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof tt&&_.status===400)break;y<et&&await ir(rr)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:c,cursor:u,order:d="DESC",includePrices:f,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=lr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=et;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),c!=null&&(w.to_block=c),u&&(w.cursor=u),i?.length&&(w.contract_addresses=i),f!=null&&(w.include_prices=f);let T=nr(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await Oe.get(E);if(!C.ok)throw new tt(C.status,rt(C));let N=C.data;return{success:!0,data:N?.data??N}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof tt&&w.status===400)break;b<et&&await ir(rr)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Bt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=lr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=nr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,c=await Oe.get(l);if(!c.ok)throw new tt(c.status,rt(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ir(rr)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=lr(n),a="Unknown error";for(let s=1;s<=et;s++)try{let l={chain:o};i&&(l.days=i);let c=nr(l),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${c}`,d=await Oe.get(u);if(!d.ok)throw new tt(d.status,rt(d));let f=d.data;return{success:!0,data:f?.data??f}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ir(rr)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=lr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let c={chain:a};i&&(c.days=i),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=nr(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${u}`,f=await Oe.get(d);if(!f.ok)throw new tt(f.status,rt(f));let m=f.data;return{success:!0,data:m?.data??m}}catch(c){if(s=c instanceof Error?c.message:"Unknown error",c instanceof tt&&c.status===400)break;l<et&&await ir(rr)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=lr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=nr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,c=await Oe.get(l);if(!c.ok)throw new tt(c.status,rt(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ir(rr)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=lr(n),s="Unknown error";for(let l=1;l<=et;l++)try{let c={chain:a};i!=null&&(c.limit=i),o&&(c.cursor=o);let u=nr(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${u}`,f=await Oe.get(d);if(!f.ok)throw new tt(f.status,rt(f));let m=f.data;return{success:!0,data:m?.data??m}}catch(c){if(s=c instanceof Error?c.message:"Unknown error",c instanceof tt&&c.status===400)break;l<et&&await ir(rr)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=lr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=nr({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,c=await Oe.get(l);if(!c.ok)throw new tt(c.status,rt(c));let u=c.data,d=u?.data??u;return{success:!0,data:zee(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ir(rr)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=lr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=nr({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,c=await Oe.get(l);if(!c.ok)throw new tt(c.status,rt(c));let u=c.data,d=u?.data??u;return{success:!0,data:Vee(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ir(rr)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!Bt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=lr(i),a="Unknown error";for(let s=1;s<=et;s++)try{let l=nr({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,u=await Oe.get(c);if(!u.ok)throw new tt(u.status,rt(u));let m=u.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ir(rr)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=lr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=nr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,c=await Oe.get(l);if(!c.ok)throw new tt(c.status,rt(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ir(rr)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Bt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=lr(n),o="Unknown error";for(let a=1;a<=et;a++)try{let s=nr({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,c=await Oe.get(l);if(!c.ok)throw new tt(c.status,rt(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof tt&&s.status===400)break;a<et&&await ir(rr)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=et;o++)try{let a={};r&&(a.chain=lr(r)),n!=null&&(a.limit=n);let s=nr(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,c=await Oe.get(l);if(!c.ok)throw new tt(c.status,rt(c));let u=c.data,d=u?.data??u;return{success:!0,data:BA(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof tt&&a.status===400)break;o<et&&await ir(rr)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=lr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let c=nr(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await Oe.get(u);if(!d.ok)throw new tt(d.status,rt(d));let f=d.data,m=f?.data??f;return{success:!0,data:BA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ir(rr)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=et;s++)try{let l={};r&&(l.chain=lr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let c=nr(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await Oe.get(u);if(!d.ok)throw new tt(d.status,rt(d));let f=d.data,m=f?.data??f;return{success:!0,data:BA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof tt&&l.status===400)break;s<et&&await ir(rr)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Ld=class extends se{constructor(r){super();h(this,"name","get-token-info");h(this,"description",'Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad');h(this,"category","blockchain-data");h(this,"parameters",[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}]);h(this,"service");h(this,"llm");this.service=new lt(r),this.llm=new Pr(r?.llm??{})}async run(r,n){let i=r.keyword||"",o=r.prompt||"",a=n?.walletAddress||void 0;if(!i)return{error:"Missing required parameter: keyword"};let s;try{s=jr(r.chain,n)}catch(l){if(l instanceof kl)return await this.researchTokenChainAgnostic(i,o,a);throw l}return await this.searchToken(i,s,o,a)}async researchTokenChainAgnostic(r,n,i){let o=[i?`User's connected wallet address: ${i}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
442
442
  `),a=n?await this.askGeminiWithSearch(n,o):null;return{_instructions:'The token info comes from web research only (the user is on a chain this app does not support on-chain). Present a clear summary of the token using the research: what it is, current USD price and 24h change, market data, recent news and the catalyst behind any price move, and a brief, clearly-hedged sense of market direction (no financial advice). Do NOT add a labelled "AI Analysis" heading and do NOT mention that the analysis came from AI \u2014 write it as a normal token summary. If a field is unknown, omit it. Do NOT mention chains, tools, or that anything is unsupported; just answer the question.',keyword:r,token:null,userHoldsToken:!1,research:a}}async searchToken(r,n,i,o){let a=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
443
443
  `),[s,l,c]=await Promise.all([this.service.searchTokensByKey({key:r,chain:n}),o?this.findTokenInWallet(o,n,r):Promise.resolve(null),i?this.askGeminiWithSearch(i,a):Promise.resolve(null)]),u=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],d=r.toLowerCase(),f=b=>b.symbol?.toLowerCase()===d||b.token_address?.toLowerCase()===d,m=[...u].sort((b,w)=>(f(b)?0:1)-(f(w)?0:1)),g=null,y=m[0];if(y?.token_address){let b=await this.service.getTokenMetadata({address:y.token_address,chain:n});b.success&&b.data&&(g=b.data)}return!g&&y&&(g={...y}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:n,userHoldsToken:!!l,walletBalance:l,token:g,...u.length>1?{searchResults:m.slice(0,10)}:{},research:c}}async askGeminiWithSearch(r,n){let i=Date.now();try{return(await this.llm.chat([...n?[{role:"system",content:n,timestamp:i}]:[],{role:"user",content:r,timestamp:i}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(r,n,i){if(!i)return null;let o=await this.service.getWalletTokenBalances({address:r,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1});if(!o.success||!o.data?.result)return null;let a=i.toLowerCase(),s=o.data.result.find(l=>l.token_address.toLowerCase()===a||l.symbol?.toLowerCase()===a||l.name?.toLowerCase().includes(a));return s||null}};p();var jd=class extends se{constructor(r){super();h(this,"name","get-token-holders");h(this,"description",'Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ');h(this,"category","blockchain-data");h(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);h(this,"service");this.service=new lt(r)}async run(r,n){let i=jr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let l,c;if(a){let f=await this.resolveContractAddress(a,i,o);if(!f)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?ve(i):"the selected chain"}. Try passing contractAddress directly.`};s=f.address,l=f.symbol,c=f.name}let u=await this.service.getTokenHolders({address:s,chain:i});if(!u.success)return{error:u.error||"Failed to fetch token holder stats"};let d=u.data;return{token:{symbol:l??a??null,name:c??null,contractAddress:s,chain:i||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(c=>(c.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Fd=class extends se{constructor(r){super();h(this,"name","get-token-analytics");h(this,"description",`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`);h(this,"category","blockchain-data");h(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);h(this,"service");this.service=new lt(r)}async run(r,n){let i=jr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,c;if(a){let f=await this.resolveContractAddress(a,i,o);if(!f)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?ve(i):"the selected chain"}. Try passing contractAddress directly.`};s=f.address,l=f.symbol,c=f.name}let u=await this.service.getTokenAnalytics({address:s,chain:i});if(!u.success)return{error:u.error||"Failed to fetch token analytics"};let d=u.data??{};return{token:{symbol:l??a??null,name:c??null,contractAddress:s,chain:i||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(c=>(c.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Bd=class extends se{constructor(r){super();h(this,"name","get-token-score");h(this,"description",`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`);h(this,"category","blockchain-data");h(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);h(this,"service");this.service=new lt(r)}async run(r,n){let i=jr(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,c;if(a){let m=await this.resolveContractAddress(a,i,o);if(!m)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?ve(i):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,l=m.symbol,c=m.name}let u=await this.service.getTokenScore({address:s,chain:i});if(!u.success)return{error:u.error||"Failed to fetch token score"};let d=u.data??{},f=d.metrics??{};return{token:{symbol:l??a??null,name:c??null,contractAddress:s,chain:i||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:f.usdPrice??null,liquidityUsd:f.liquidityUsd??null,volumeUsd:f.volumeUsd??null,transactions:f.transactions??null,supply:f.supply??null}}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(c=>(c.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var zd=class extends se{constructor(r){super();h(this,"name","get-trending-tokens");h(this,"description",'List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad, and more.');h(this,"category","blockchain-data");h(this,"parameters",[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1}]);h(this,"service");this.service=new Pn({baseUrl:r?.pantographUrl})}async run(r,n){let i=_v(r.chain,n),o=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.floor(r.limit):void 0,a=await this.service.getTrendingTokens({chain:i,limit:o});if(!a.success)return{error:a.error||"Failed to fetch trending tokens"};let s=a.data??[];return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
@@ -623,7 +623,7 @@ ${xq}`,dp={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
623
623
  Source: Uniswap ExploreStats (live 24h data). Supports: `+Hn());h(this,"category","blockchain-data");h(this,"parameters",[{name:"token0Symbol",type:"string",description:'Symbol of one of the pool tokens (e.g. "USDC"). Pair order does not matter.',required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 if omitted, the tool auto-picks the highest-volume pool containing token0Symbol.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "ETH/USDC 0.3%" \u2192 feeTier=3000). NEVER guess or infer one. When the user has not mentioned a fee tier and the pair has multiple fee tiers, OMIT it \u2014 the tool then returns candidates.',required:!1},{name:"depositUsd",type:"number",description:"USD amount to deposit. Optional \u2014 defaults to 1000 and the response is marked as a per-$1000 example.",required:!1},{name:"chain",type:"string",description:Ni,required:!1}]);h(this,"service");this.service=new Zn(r)}async run(r,n){let i=await Gn($i(),r.chain,n);if(!i.ok)return i.result;let o=i.chain,a=typeof r.token0Symbol=="string"?r.token0Symbol.trim():"",s=typeof r.token1Symbol=="string"?r.token1Symbol.trim():"",l=typeof r.feeTier=="number"&&Number.isFinite(r.feeTier)?Math.floor(r.feeTier):void 0,c=typeof r.depositUsd=="number"&&Number.isFinite(r.depositUsd)&&r.depositUsd>0,u=c?r.depositUsd:kre;if(!a)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let d=s?`${a} ${s}`:a,f=await this.service.searchPools({query:d,chain:o,page:1,size:50,protocolVersion:"V3"});if(!f.success)return{error:f.error||"Pool search failed"};let m=f.data??[],g=this.filterPools(m,a,s,l);if(g.length===0)return{error:`No V3 pool found for ${this.describeQuery(a,s,l)} on ${ve(o)}. Verify the token symbols with the user.`};let y=this.rankByVolume(g);if(s&&l==null&&new Set(y.map(F=>F.feeTier).filter(F=>typeof F=="number")).size>1){let F=this.dedupeByFeeTier(y).slice(0,5);return{_instructions:"The pair has multiple fee tiers. Present them as a short numbered list (fee tier %, 24h volume). Ask which fee tier the user wants, then re-call with the same token symbols + chosen feeTier. If the user already mentioned a deposit amount, pass it along as depositUsd. Do NOT mention tool names. Format numbers human-readably (e.g. $12.5M, 0.05%).",reason:`${a}/${s} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:F.map(G=>({pair:G.token0?.symbol&&G.token1?.symbol?`${G.token0.symbol}/${G.token1.symbol}`:void 0,feeTierBps:G.feeTier,feeTierPercent:typeof G.feeTier=="number"?G.feeTier/1e4:void 0,volume24hUsd:G.volumeUsd24hr,address:G.id}))}}let _=y[0];if(!_.id||!Pre.test(_.id))return{error:"Resolved pool has no valid address."};let b=await this.service.getV3PoolDetail({address:_.id,chain:o});if(!b.success||!b.data)return{error:b.error||"Failed to fetch pool detail."};let w=b.data,T=w.totalLiquidity?.value,E=w.volume24h?.value,C=w.feeTier,N=typeof C=="number"?C/1e4:void 0,M=typeof E=="number"&&typeof N=="number"?E*N/100:void 0,A=typeof M=="number"&&typeof T=="number"&&T>0?M/T*Vq:void 0,U=typeof E=="number"&&typeof T=="number"&&T>0?E/T:void 0,D={address:w.address,pair:w.token0?.symbol&&w.token1?.symbol?`${w.token0.symbol}/${w.token1.symbol}`:void 0,feeTierBps:C,feeTierPercent:N,tvlUsd:T,volume24hUsd:E,fees24hUsd:M,volumeToTvlRatio:U,aprPercent:typeof A=="number"?A*100:void 0,chain:o,token0:w.token0?{symbol:w.token0.symbol}:void 0,token1:w.token1?{symbol:w.token1.symbol}:void 0},x=s?void 0:`User only provided ${a}; auto-picked the highest-volume V3 pool containing it.`;if(A==null)return{_instructions:"Pool APR could not be computed (TVL or volume data unavailable). Inform the user briefly and show TVL/volume if present. Do NOT mention tool names.",pool:D,autoPickedReason:x,aprUnavailableReason:T?"Volume data unavailable":"TVL is zero or unavailable"};let O=Ere(u,A);return{_instructions:hi+"Present the yield estimate naturally in the user's language. "+(c?"Lead with: pool (pair + fee %), chain, APR %. Then show projected earnings for the user's deposit \u2014 daily, weekly, monthly, yearly. ":'IMPORTANT: depositUsd was NOT specified by the user \u2014 the result is a per-$1000 EXAMPLE. Lead with: pool (pair + fee %), chain, APR %. Then say "for every $1000 deposited you would earn approximately:" and list daily / weekly / monthly / yearly. End with a short note that the user can multiply these numbers by (their deposit / 1000) for a custom amount. ')+(x?'Mention briefly that you picked the highest-volume pool for this token (do NOT say "auto-picked"). ':"")+"After the numbers, add a SHORT expert read of whether this pool is actually worth the deposit. "+mi+gi+ln+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:D,estimate:O,depositMode:c?"user-specified":"default-1000-example",autoPickedReason:x,disclaimer:"Fee yield is based on the pool's 24h volume snapshot and assumes full-range liquidity. Actual returns vary with price movement, volume changes, and impermanent loss."}}filterPools(r,n,i,o){let a=n.toLowerCase(),s=i?i.toLowerCase():"";return r.filter(l=>{if(o!=null&&l.feeTier!==o)return!1;let c=(l.token0?.symbol??"").toLowerCase(),u=(l.token1?.symbol??"").toLowerCase();return s?this.sym(c,a)&&this.sym(u,s)||this.sym(c,s)&&this.sym(u,a):this.sym(c,a)||this.sym(u,a)})}sym(r,n){return!r||!n?!1:r.includes(n)||n.includes(r)}rankByVolume(r){return[...r].sort((n,i)=>(i.volumeUsd24hr??0)-(n.volumeUsd24hr??0))}dedupeByFeeTier(r){let n=new Set,i=[];for(let o of r)typeof o.feeTier=="number"&&(n.has(o.feeTier)||(n.add(o.feeTier),i.push(o)));return i}describeQuery(r,n,i){let o=n?`${r}/${n}`:r;return i!=null?`${o} at ${i} bps`:o}};p();var kp=class extends se{constructor(r){super();h(this,"name","get-pool-price-ranges");h(this,"description",'List CoinPool concentrated-liquidity price-range candidates for a token pair on a given EVM chain. Each entry shows: pair, fee tier, min/max price range, current price, and the APR earned WITHIN that range (strictly per-range \u2014 NOT the overall pool APR). Use ONLY for questions about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use get-pool-detail or search-pools for that. Source: CoinPool. Supports: '+Hn()+".");h(this,"category","blockchain-data");h(this,"parameters",[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:Ni,required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}]);h(this,"service");this.service=new Cl(r)}async run(r,n){let i=(Array.isArray(r.tokens)?r.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase());if(i.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=await Gn($i(),r.chain,n);if(!o.ok)return o.result;let a=o.chain,s=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.min(Math.floor(r.limit),30):10,l=await this.service.getPairs({chain:a,tokens:i});if(l.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and offer the pool's overall stats instead (via get-pool-detail).",tokens:i,chain:a,pairs:[],count:0};let c=[...l].sort((u,d)=>(d.apr??-1/0)-(u.apr??-1/0)).slice(0,s);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+ln+"Do NOT mention tool or API names.",tokens:i,chain:a,count:c.length,pairs:c}}};p();var Zq="https://coinpool.app/my-liquidity",Pp=class extends se{constructor(){super(...arguments);h(this,"name","manage-liquidity-redirect");h(this,"description",'Use when the user wants to MANAGE an EXISTING liquidity position rather than open a new one \u2014 specifically: collecting / claiming earned fees or rewards ("collect earnings", "claim my fees", "thu ph\xED", "r\xFAt l\xE3i"), or closing / removing / withdrawing a position ("close the pair", "close my position", "remove liquidity", "withdraw liquidity", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "\u0111\xF3ng c\u1EB7p"). This tool does NOT perform the action \u2014 it returns a link to the CoinPool management page where the user does it themselves. Do NOT use this for ADDING liquidity (use the add-liquidity form) or for pool data/analysis questions.');h(this,"category","pool-action");h(this,"parameters",[{name:"action",type:"string",description:'What the user wants to do \u2014 one of: "collect" (collect/claim earned fees) or "close" (close/remove the position). Optional \u2014 used only to tailor the wording. Omit if unclear.',required:!1}])}async run(r){let n=r.action==="collect"||r.action==="close"?r.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${n==="collect"?"collect their earned fees":n==="close"?"close / remove their position":"manage their existing position (collect earnings or close the pair)"}, they need to visit the CoinPool management page and do it there. Give them the link as plain text: ${Zq} \u2014 write the URL exactly, do NOT shorten it or wrap it in markdown. Keep it short and friendly. Do NOT mention tool names.`,url:Zq,action:n}}};p();p();var Are=["tvl","volume","apr","fee","liquidity"],Ep=class extends se{constructor(r){super();h(this,"name","subgraph-search-pools");h(this,"description",'Search Uniswap V3 liquidity pools via The Graph subgraphs by token symbol(s) on one or more chains. Use for: "find ETH/USDC pools on Base", "show OP pools", "stablecoin pools on Arbitrum", "best USDC pool". Returns pools with pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched), and liquidity rank. When exactly two tokens are given, also returns CoinPool concentrated-liquidity price-range candidates (per-range APR) for that pair. Supports TVL/APR/fee filters and sort by tvl, volume, apr, fee, or liquidity. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).');h(this,"category","blockchain-data");h(this,"parameters",[{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols to match. 0 tokens = top pools by chosen sort. 1 token = pools containing it. 2 tokens = pools with that exact pair (both orderings tried). Wrapped variants (WETH\u2194ETH, WBTC\u2194BTC) auto-handled.",required:!1,default:[]},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"sortBy",type:"string",description:'Sort key: "tvl" (default), "volume", "apr", "fee" (low-to-high), or "liquidity".',required:!1,default:"tvl"},{name:"minTVL",type:"number",description:"Minimum TVL in USD.",required:!1},{name:"maxTVL",type:"number",description:"Maximum TVL in USD.",required:!1},{name:"minAPR",type:"number",description:"Minimum APR percentage (e.g. 5 for 5%).",required:!1},{name:"maxAPR",type:"number",description:"Maximum APR percentage.",required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100, 500, 3000, or 10000.",required:!1},{name:"limit",type:"number",description:"Max pools to return after sort/filter. Default 5, max 20.",required:!1,default:5}]);h(this,"service");this.service=new Fr(r)}async run(r,n){let i=(Array.isArray(r.tokens)?r.tokens:[]).filter(y=>typeof y=="string"&&y.trim().length>0).map(y=>y.trim().toUpperCase()),o=(Array.isArray(r.chains)?r.chains:[]).filter(y=>typeof y=="string"&&y.trim().length>0),a=o.filter(y=>!this.service.isSupported(y)),s=o.filter(y=>this.service.isSupported(y)).map(y=>this.service.resolveChain(y));if(s.length===0&&!this.service.isSupported(n?.chain)&&n?.walletAddress)throw new gr(typeof n?.query=="string"?n.query:void 0);let l=s.length>0?s:this.service.isSupported(n?.chain)?[this.service.resolveChain(n?.chain)]:["0x1"],c=typeof r.sortBy=="string"&&Are.includes(r.sortBy)?r.sortBy:"tvl",u={minTVL:typeof r.minTVL=="number"?r.minTVL:void 0,maxTVL:typeof r.maxTVL=="number"?r.maxTVL:void 0,minAPR:typeof r.minAPR=="number"?r.minAPR:void 0,maxAPR:typeof r.maxAPR=="number"?r.maxAPR:void 0,feeTier:typeof r.feeTier=="number"?r.feeTier:void 0},d=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.min(Math.floor(r.limit),20):5;if(o.length>0&&s.length===0)return{_instructions:"The user requested chains we do not support via The Graph subgraph. Politely list the unsupported chains and the supported chains. Do not show any pool data.",unsupportedChains:a.map(ve),supportedChains:this.service.listSupportedChains().map(ve),pools:[],count:0};let m=(await Promise.allSettled(l.map(y=>this.service.searchPools({tokens:i,chain:y,sortBy:c,filters:u})))).flatMap(y=>y.status==="fulfilled"?y.value:[]);c==="apr"?m.sort((y,_)=>(_.apr??0)-(y.apr??0)):c==="tvl"?m.sort((y,_)=>_.tvl-y.tvl):c==="volume"?m.sort((y,_)=>_.volume24hUsd-y.volume24hUsd):c==="fee"&&m.sort((y,_)=>y.feeTierBps-_.feeTierBps),m=m.slice(0,d);let g=[];return i.length===2&&(g=(await Promise.allSettled(l.map(_=>this.service.getCoinPoolPairs({chain:_,tokens:i})))).flatMap((_,b)=>_.status==="fulfilled"?_.value.map(w=>({...w,chain:ve(l[b])})):[]),g.sort((_,b)=>(b.apr??-1/0)-(_.apr??-1/0)),g=g.slice(0,d)),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). Then list the pools with: pair (e.g. USDC/WETH), fee tier (%), TVL (USD), volume past day (USD), APR (%). Format USD human-readably ($12.5M, $450K). Mention chain and sort metric briefly. If a pool has no APR (null), skip the APR field rather than showing zero. For EACH pool, render the provided uniswapUrl as a clickable markdown link \u2014 e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)". Never omit this link. Do not invent URLs. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: the APR in coinPoolPairs is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the list, add a brief, natural read on the pools \u2014 conversational, like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4CA} Evaluation"); vary your wording each time and only mention what actually stands out in THIS data. Reason ONLY from the numbers shown \u2014 never invent figures. Touch on, as it fits: which pool looks strongest and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; a high volume-to-TVL ratio signals an active, fee-generating pool); whether the fee tier fits the pair (0.05% for stable/correlated, 0.30% for typical volatile, 1% for exotic/low-liquidity); any pool to be cautious about (thin TVL/volume, or an eye-catching APR that is likely volatile/unsustainable rather than a sure thing); and the key risks in a line (APR is variable, high APR usually means higher risk, impermanent loss for LPs on volatile pairs). Keep it short and human \u2014 a sentence or two or a couple of light bullets. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, no stock disclaimer). If unsupportedChains is non-empty, mention them once at the end.',tokens:i,chains:l.map(ve),unsupportedChains:a.map(ve),sortBy:c,filters:u,count:m.length,pools:m.map(y=>this.formatPool(y)),coinPoolPairs:g}}formatPool(r){return{pair:r.pair,poolAddress:r.poolAddress,chain:r.chain,feeTierBps:r.feeTierBps,feeTierPercent:r.feeTierPercent,tvlUsd:r.tvl,volumePastDayUsd:r.volume24hUsd,fees24hUsd:r.fees24hUsd,apr:r.apr,token0:r.token0,token1:r.token1,uniswapUrl:yi(r)}}};function yi(t){return`https://app.uniswap.org/explore/pools/${Im[t.chain]||t.chain}/${t.poolAddress}`}var Im={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};p();var Ap=class extends se{constructor(r){super();h(this,"name","subgraph-trending-pools");h(this,"description",'List Uniswap V3 pools with the highest volume past day on one or more chains via The Graph subgraphs. Use for: "what are trending pools?", "most active pools", "hot pools right now", "pools with biggest volume today". Returns pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched) for each. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).');h(this,"category","blockchain-data");h(this,"parameters",[{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"limit",type:"number",description:"Max pools to return. Default 5, max 20.",required:!1,default:5}]);h(this,"service");this.service=new Fr(r)}async run(r,n){let i=(Array.isArray(r.chains)?r.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=i.filter(d=>!this.service.isSupported(d)),a=i.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(i.length>0&&a.length===0)return{_instructions:"User requested unsupported chains. Politely list them and the supported chains; do not show pool data.",unsupportedChains:o,supportedChains:this.service.listSupportedChains(),pools:[],count:0};if(a.length===0&&!this.service.isSupported(n?.chain)&&n?.walletAddress)throw new gr(typeof n?.query=="string"?n.query:void 0);let s=a.length>0?a:this.service.isSupported(n?.chain)?[this.service.resolveChain(n?.chain)]:["0x1"],l=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.min(Math.floor(r.limit),20):5,u=(await Promise.allSettled(s.map(d=>this.service.getTrendingPools({chain:d})))).flatMap(d=>d.status==="fulfilled"?d.value:[]);return u.sort((d,f)=>f.volume24hUsd-d.volume24hUsd),u=u.slice(0,l),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). List pools ranked by volume past day. For each: pair, fee %, volume past day, TVL, APR (skip if null). For EACH pool render the provided uniswapUrl as a clickable markdown link (e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)"). Never omit it. Do not invent URLs.',chains:s,unsupportedChains:o,count:u.length,pools:u.map(d=>({pair:d.pair,poolAddress:d.poolAddress,chain:d.chain,feeTierBps:d.feeTierBps,feeTierPercent:d.feeTierPercent,tvlUsd:d.tvl,volumePastDayUsd:d.volume24hUsd,fees24hUsd:d.fees24hUsd,apr:d.apr,token0:d.token0,token1:d.token1,uniswapUrl:yi(d)}))}}};p();var Cp=class extends se{constructor(r){super();h(this,"name","subgraph-pool-by-address");h(this,"description",'Fetch full pool detail AND an evaluation for a specific Uniswap V3 pool by its on-chain address via The Graph subgraphs. Returns Uniswap fundamentals (pair, fee tier, TVL, volume past day + fees, APR, token addresses) enriched with CoinPool concentrated-liquidity price-range candidates (per-range APR + min/max/current price), then a genuine assessment of the pool. Use whenever the user pastes a 0x pool address \u2014 both for plain detail ("tell me about pool 0xabc\u2026", "details of this pool 0x\u2026") and for an opinion ("\u0111\xE1nh gi\xE1 pool 0x\u2026", "rate/evaluate this pool 0x\u2026", "is pool 0x\u2026 good?", "pool n\xE0y c\xF3 t\u1ED1t kh\xF4ng").');h(this,"category","blockchain-data");h(this,"parameters",[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1}]);h(this,"service");this.service=new Fr(r)}async run(r,n){let i=typeof r.poolAddress=="string"?r.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(i))return{error:"This only supports Uniswap V3 pools. Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address)."};let o=typeof r.chain=="string"&&r.chain.trim();if(!o&&!n?.chain&&n?.walletAddress)throw new gr(typeof n?.query=="string"?n.query:void 0);let a=o?r.chain.trim():n?.chain||"0x1";if(!this.service.isSupported(a))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[a],supportedChains:this.service.listSupportedChains()};let s=this.service.resolveChain(a),[l,c]=await Promise.all([this.service.getPoolByAddress({poolAddress:i,chain:s}),this.service.getCoinPoolByAddress({chain:s,poolAddress:i}).catch(()=>[])]);return l?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(c.length>0?" enriched with CoinPool range data,":"")+'" (translate naturally; keep "Subgraph" and "CoinPool" as-is). First show the pool snapshot: pair, fee tier (%), TVL, volume past day, 24h fees, APR (skip if null), and the pool address. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: a range APR is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Then give a genuine evaluation of THIS pool \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading; vary the wording each time and only cover what is actually relevant to this pool and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: liquidity depth & activity (higher TVL + volume past day = deeper liquidity, more fees, less slippage; thin TVL/volume is a red flag); fee-tier fit (0.05% suits stable/correlated pairs, 0.30% typical volatile pairs, 1% exotic/low-liquidity ones \u2014 flag a mismatch); whether the APR looks attractive vs. how sustainable it is (fee-driven and steady vs. thin-TVL spikes that can vanish); if coinPoolPairs is present, which price range makes sense \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Close with a short, natural overall take (e.g. solid / decent-with-caveats / risky) and a brief nudge that it is informational, not financial advice \u2014 phrase it differently each time, do not paste a stock disclaimer. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs. Do NOT mention tool names, UI, or forms.',chain:s,coinPoolPairs:c,pool:{pair:l.pair,poolAddress:l.poolAddress,chain:l.chain,feeTierBps:l.feeTierBps,feeTierPercent:l.feeTierPercent,tvlUsd:l.tvl,volumePastDayUsd:l.volume24hUsd,fees24hUsd:l.fees24hUsd,apr:l.apr,token0:l.token0,token1:l.token1,uniswapUrl:yi(l)}}:{error:`No pool found at ${i} on ${ve(s)}.`}}};p();var xp=class extends se{constructor(r){super();h(this,"name","subgraph-pool-by-position-id");h(this,"description",'Return the pool underlying a Uniswap V3 NFT position id. Use when the user wants the pool stats for a numeric id WITHOUT the deposit/withdraw/fee history (e.g. "which pool is position 962961 in?", "show the pool of id 12345"). For full position history use subgraph-position-detail instead.');h(this,"category","blockchain-data");h(this,"parameters",[{name:"positionId",type:"string",description:"Numeric Uniswap V3 NFT position id as a string.",required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}]);h(this,"service");this.service=new Fr(r)}async run(r,n){let i=typeof r.positionId=="string"?r.positionId.trim():"";if(!/^\d+$/.test(i))return{error:"positionId must be a numeric string."};let o=(Array.isArray(r.chains)?r.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),a=o.filter(d=>!this.service.isSupported(d)),s=o.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(o.length>0&&s.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:a,supportedChains:this.service.listSupportedChains()};if(s.length===0&&!this.service.isSupported(n?.chain)&&n?.walletAddress)throw new gr(typeof n?.query=="string"?n.query:void 0);let l=s.length>0?s:this.service.isSupported(n?.chain)?[this.service.resolveChain(n?.chain)]:["0x1"],u=(await Promise.allSettled(l.map(d=>this.service.getPoolByPositionId({positionId:i,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);return u?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pool of that position: pair, fee %, TVL, volume past day, APR. Mention the position id. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs.',positionId:i,pool:{pair:u.pair,poolAddress:u.poolAddress,chain:u.chain,feeTierBps:u.feeTierBps,feeTierPercent:u.feeTierPercent,tvlUsd:u.tvl,volumePastDayUsd:u.volume24hUsd,fees24hUsd:u.fees24hUsd,apr:u.apr,token0:u.token0,token1:u.token1,uniswapUrl:yi(u)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:i,chains:l,found:!1}}};p();var Ip=class extends se{constructor(r){super();h(this,"name","subgraph-position-detail");h(this,"description",`Look up a Uniswap V3 liquidity position by its numeric NFT id (e.g. 962961) on one or more chains via The Graph subgraphs. Returns the position (deposited/withdrawn token amounts, collected fees, liquidity) AND its underlying pool (pair, fee tier, TVL, volume past day, APR). Use when the user names a numeric id with phrases like: "position 12345", "pool id 962961", "tell me about position 962961". Does NOT support the user's wallet-wide LP list \u2014 only a specific id.`);h(this,"category","blockchain-data");h(this,"parameters",[{name:"positionId",type:"string",description:'Numeric Uniswap V3 NFT position id as a string (e.g. "962961").',required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}]);h(this,"service");this.service=new Fr(r)}async run(r,n){let i=typeof r.positionId=="string"?r.positionId.trim():"";if(!/^\d+$/.test(i))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let o=(Array.isArray(r.chains)?r.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),a=o.filter(f=>!this.service.isSupported(f)),s=o.filter(f=>this.service.isSupported(f)).map(f=>this.service.resolveChain(f));if(o.length>0&&s.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:a,supportedChains:this.service.listSupportedChains()};if(s.length===0&&!this.service.isSupported(n?.chain)&&n?.walletAddress)throw new gr(typeof n?.query=="string"?n.query:void 0);let l=s.length>0?s:this.service.isSupported(n?.chain)?[this.service.resolveChain(n?.chain)]:["0x1"],u=(await Promise.allSettled(l.map(f=>this.service.getPositionDetail({positionId:i,chain:f})))).map(f=>f.status==="fulfilled"?f.value:null).find(f=>f!=null);if(!u)return{_instructions:"No position with this id was found on the chosen chains. Suggest the user double-check the id or specify another chain.",positionId:i,chains:l,found:!1};let d=Im[u.position.chain]||u.position.chain;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pair, chain, fee tier (%), deposited/withdrawn/collected fees for each token, plus pool stats (TVL, volume past day, APR). End the response with TWO clickable markdown links from the data: position.uniswapPositionUrl as "[View position on Uniswap](uniswapPositionUrl)" and pool.uniswapUrl as "[View pool on Uniswap](uniswapUrl)". Never omit them. Do not invent URLs.',positionId:i,position:{...u.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${d}/${u.position.positionId}`},pool:{...u.pool,uniswapUrl:yi(u.pool)}}}};p();var Op=class extends se{constructor(r){super();h(this,"name","subgraph-coinpool-pairs");h(this,"description",'List CoinPool concentrated-liquidity price-range candidates for a token pair on a chain. Each entry shows: pair, fee tier, min/max price range, current price, and APR within that range (NOT the overall pool APR \u2014 strictly per-range). Use ONLY for queries about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use subgraph-search-pools for that.');h(this,"category","blockchain-data");h(this,"parameters",[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}]);h(this,"service");this.service=new Fr(r)}async run(r,n){let i=(Array.isArray(r.tokens)?r.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase());if(i.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=typeof r.chain=="string"&&r.chain.trim();if(!o&&!n?.chain&&n?.walletAddress)throw new gr(typeof n?.query=="string"?n.query:void 0);let a=o?r.chain.trim():n?.chain||"0x1";if(!this.service.isSupported(a))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[a],supportedChains:this.service.listSupportedChains()};let s=this.service.resolveChain(a),l=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.min(Math.floor(r.limit),30):10,c=await this.service.getCoinPoolPairs({chain:s,tokens:i});if(c.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and suggest using general pool data instead (via subgraph-search-pools).",tokens:i,chain:s,pairs:[],count:0};let u=[...c].sort((d,f)=>(f.apr??-1/0)-(d.apr??-1/0)).slice(0,l);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:i,chain:s,count:u.length,pairs:u}}};p();var Rp=class extends se{constructor(r){super();h(this,"name","subgraph-add-pool");h(this,"description",'Open the ADD-LIQUIDITY / ADD-POOL flow for Uniswap V3 via The Graph subgraphs. Use for ANY "provide / add liquidity", "add LP", "add pool", "create pool", "create pair", "farm/deposit into a pool" intent (natural-language verbs in any language map here: "th\xEAm thanh kho\u1EA3n", "th\xEAm pool", "t\u1EA1o pool"). It RESOLVES the pool the user means \u2014 by 0x pool address, or by one/two token symbols (with optional fee tier) \u2014 like the detail/search tools, then points the user to the add-liquidity website. When two token symbols are given, it also surfaces CoinPool concentrated-liquidity price-range candidates (per-range APR) to help pick a range. Pass `poolAddress` when the user gives a 0x pool address; otherwise pass `tokens` (1 or 2 symbols) and optional `feeTier`. Leave both blank when the user named no pool/token \u2014 the tool returns the chain\'s top pools to choose from. It does NOT build a transaction; it surfaces the add-liquidity link.');h(this,"category","blockchain-data");h(this,"parameters",[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars). Pass when the user gives a concrete pool address; otherwise leave blank and pass `tokens`.",required:!1},{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols of the pair to add liquidity to. 1 token = pools containing it; 2 tokens = that exact pair (both orderings tried). Leave EMPTY when the user named no token \u2014 the tool returns top pools to choose from.",required:!1,default:[]},{name:"feeTier",type:"number",description:"Optional fee tier in basis points (100, 500, 3000, or 10000) to disambiguate the pool.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"howTo",type:"boolean",description:'Set TRUE when the user asks HOW to add liquidity / how to create a pool or pair / how it works ("how to add pool", "how to add pair", "how do I add liquidity", "c\xE1ch th\xEAm thanh kho\u1EA3n", "l\xE0m sao \u0111\u1EC3 add pool/pair") rather than naming a specific pool to add to ("pool" and "pair" are equivalent here). Returns the general steps + the add-liquidity website link, without needing a pool, token, or connected chain. Leave false/omit for a concrete add-liquidity request.',required:!1}]);h(this,"service");h(this,"linkAddLiquidity");this.service=new Fr(r),this.linkAddLiquidity=r?.linkAddLiquidity?.trim()||void 0}async run(r,n){if(r.howTo===!0){let f=this.linkAddLiquidity??null,m=typeof r.chain=="string"&&r.chain.trim()||n?.chain||"0x1",g="",y=[];if(this.service.isSupported(m)){g=this.service.resolveChain(m);try{y=(await this.service.searchPools({tokens:[],chain:g,sortBy:"tvl"})).slice(0,5)}catch{y=[]}}return{_instructions:`The user is asking HOW to add liquidity / create a pool \u2014 a how-to question, not a request about a specific pool. Reply in the user's language, in THIS exact order:
624
624
  1) A clear, easy-to-follow step-by-step guide (numbered steps) on how adding liquidity works. Generate the steps yourself from how Uniswap V3 add-liquidity actually works \u2014 keep each step short; do not pad with filler.
625
625
  `+(y.length>0?'2) A few popular pools (from the provided list) as examples to add liquidity to \u2014 show fee tier %, TVL, APR (skip APR if null). For EACH pool, make it a clickable Uniswap link using its `uniswapUrl`: wrap the pair as a markdown link, e.g. "[USDC/WETH](uniswapUrl)", or append "[View on Uniswap](uniswapUrl)". Use the uniswapUrl verbatim; never invent one. Make clear these are just examples for reference, not recommendations.\n':"")+(y.length>0?"3) ":"2) ")+this.linkInstruction(f)+`
626
- Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:g||void 0,addLiquidityLink:f,count:y.length,pools:y.map(_=>this.formatPool(_))}}let i=typeof r.poolAddress=="string"?r.poolAddress.trim():"",o=(Array.isArray(r.tokens)?r.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),a=typeof r.feeTier=="number"&&Number.isFinite(r.feeTier)?Math.floor(r.feeTier):void 0,s=typeof r.chain=="string"&&r.chain.trim();if(!s&&!n?.chain&&n?.walletAddress)throw new gr(typeof n?.query=="string"?n.query:void 0);let l=s?r.chain.trim():n?.chain||"0x1";if(!this.service.isSupported(l))return{_instructions:"The requested chain is not supported by the Subgraph pool service. Tell the user, in their language, that add-liquidity is not available on that network and list the supported chains briefly. Do NOT mention tool names.",unsupportedChains:[ve(l)],supportedChains:this.service.listSupportedChains().map(ve)};let c=this.service.resolveChain(l);if(i){if(!/^0x[a-fA-F0-9]{40}$/.test(i))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let f=await this.service.getPoolByAddress({poolAddress:i,chain:c});return f?this.poolsResult([f],c,!0):{error:`No pool found at ${i} on ${ve(c)}.`}}if(o.length>0){let f=await this.service.searchPools({tokens:o,chain:c,sortBy:"tvl",filters:{feeTier:a}});if(f.length===0)return{error:`No Uniswap V3 pool found for ${o.join("/")}${a!=null?` at ${a}bps`:""} on ${ve(c)}. Ask the user to check the token symbols, or try a different pair.`};let m=o.length===2?await this.fetchCoinPoolPairs(c,o):[];return this.poolsResult(f.slice(0,8),c,!0,m)}let u=await this.service.searchPools({tokens:[],chain:c,sortBy:"tvl"}),d=this.linkAddLiquidity??null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity but has not named a pool yet. Briefly list these top pools (pair, fee tier %, TVL, APR \u2014 skip APR if null) as suggestions, render each `uniswapUrl` as a clickable markdown link, then ask the user which token pair (or pool) they want to add liquidity to. '+this.linkInstruction(d)+"Do NOT mention tool names, UI, or forms.",chain:c,needsSelection:!0,addLiquidityLink:d,count:u.length,pools:u.slice(0,6).map(f=>this.formatPool(f))}}async fetchCoinPoolPairs(r,n){try{return[...await this.service.getCoinPoolPairs({chain:r,tokens:n})].sort((o,a)=>(a.apr??-1/0)-(o.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(r){return r?`ALWAYS finish by inviting the user to add liquidity on the website, as ONE short sentence that shows the FULL link in plain view \u2014 display the entire URL verbatim (${r}) as the visible link text, do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${r}](${r}). For example: "You can add liquidity here: [${r}](${r})". Use the URL verbatim; never invent one, and never use a pool's uniswapUrl here. `:"No add-liquidity website is configured, so do not show or invent any link. "}poolsResult(r,n,i,o=[]){let a=i?this.linkAddLiquidity??null:null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity. Show the resolved pool(s): pair (e.g. USDC/WETH), fee tier (%), TVL, volume past day, APR (skip if null), and the pool address. For EACH pool, render the provided `uniswapUrl` as a clickable markdown link. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)", to help the user choose a range when adding liquidity. CRITICAL: that APR is for the SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the data, give a genuine, conversational recommendation \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4A1} Recommendation"); vary your wording naturally each time and only cover what is actually relevant to THIS pair and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: which pool/fee tier looks best and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; fee-tier fit: 0.05% for stable/correlated pairs, 0.30% for typical volatile pairs, 1% for exotic/low-liquidity ones); which price range makes sense (from coinPoolPairs if present) \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; anything worth avoiding (thin TVL/volume, ranges far from current price, chasing the top APR blindly); and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Keep it short and human \u2014 a sentence or two or a couple of light bullets, tailored to whether the pair is stable or volatile. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, do not paste a stock disclaimer). '+(a?`Then, at the VERY END, write ONE short, friendly sentence in the user's language inviting them to add liquidity, showing the FULL add-liquidity link in plain view: display the entire URL verbatim as the visible link text \u2014 do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${a}](${a}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${a}](${a})." Use the addLiquidityLink verbatim; never invent a URL, and never use a pool's uniswapUrl here.`:"Do NOT invent or show any add-liquidity link (none is configured). Just present the pool(s).")+" Do NOT mention tool names, UI, forms, or that a transaction is built elsewhere.",chain:n,addLiquidityLink:a,count:r.length,pools:r.map(l=>this.formatPool(l)),coinPoolPairs:o}}formatPool(r){return{pair:r.pair,poolAddress:r.poolAddress,chain:r.chain,feeTierBps:r.feeTierBps,feeTierPercent:r.feeTierPercent,tvlUsd:r.tvl,volumePastDayUsd:r.volume24hUsd,fees24hUsd:r.fees24hUsd,apr:r.apr,token0:r.token0,token1:r.token1,uniswapUrl:yi(r)}}};p();p();p();function Ho(t){if(typeof t=="number")return Number.isFinite(t)&&t>0?{kind:"token",value:t,raw:String(t)}:null;if(typeof t!="string")return null;let e=t.trim();if(!e)return null;if(/^(?:max(?:imum)?|all|everything|tất\s*cả|toàn\s*bộ)$/i.test(e))return{kind:"percent",percent:100,raw:e};let r=e.match(/^%?\s*([0-9]*\.?[0-9]+)\s*%$|^%\s*([0-9]*\.?[0-9]+)$/);if(r){let o=parseFloat(r[1]??r[2]);return Number.isFinite(o)&&o>0?{kind:"percent",percent:o,raw:e}:null}let n=e.match(/^\$\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*\$$|^(?:usd)\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*usd$/i);if(n){let o=parseFloat(n[1]??n[2]??n[3]??n[4]);return Number.isFinite(o)&&o>0?{kind:"usd",usd:o,raw:e}:null}let i=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(i){let o=parseFloat(i[1]);return Number.isFinite(o)&&o>0?{kind:"token",value:o,raw:e}:null}return null}function Hq(t,e){switch(t.kind){case"token":return{ok:!0,amount:t.value};case"percent":return e.balance===void 0||!Number.isFinite(e.balance)||e.balance<=0?{ok:!1,reason:"no_balance"}:{ok:!0,amount:e.balance*t.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:t.usd/e.usdPrice}}}p();var Cre={send:30000n,swap:1000000n},xre={"0x1":["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"],"0xa":["https://optimism-rpc.publicnode.com","https://optimism.drpc.org"],"0x38":["https://bsc-rpc.publicnode.com","https://bsc.drpc.org"],"0x89":["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"],"0x2105":["https://base-rpc.publicnode.com","https://base.drpc.org"],"0xa4b1":["https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"],"0xa86a":["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"],"0xe708":["https://linea-rpc.publicnode.com","https://linea.drpc.org"],"0x64":["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"],"0x3e7":["https://rpc.hyperliquid.xyz/evm"],"0x1388":["https://mantle-rpc.publicnode.com","https://rpc.mantle.xyz"],"0x8f":["https://rpc.monad.xyz"]};async function Ire(t){let e=t.toLowerCase(),n=[xs(t),...xre[e]??[]].filter(i=>!!i);for(let i of n)try{let o=await Is(i,"eth_gasPrice",[]),a=BigInt(o);if(a>0n)return a}catch{}return 0n}async function Np(t,e){let r=await Ire(t);return r<=0n?0n:Cre[e]*r}function $p(t,e,r){if(e<=0n)return t;let n=Br(r)?.native.decimals;if(n===void 0)return t;let i=Number(e)/10**n;return!Number.isFinite(i)||i<=0?t:Math.max(0,t-i)}var Mi=class extends se{constructor(r){super();h(this,"kind","ui");h(this,"category","wallet-action");h(this,"userInputFields",[]);h(this,"moralis");r!==void 0&&(this.moralis=new lt(r))}buildUI(r){let n={action:this.actionType,chainId:r.chainId,chainName:ve(r.chainId),walletAddress:r.walletAddress,parameters:r.parameters};return{component:this.component,props:n}}async resolveContractAddress(r,n,i){if(!this.moralis||!r)return;let o=r.trim().toLowerCase(),a=Bt(r.trim()),s=c=>a?(c.token_address??"").toLowerCase()===o:(c.symbol??"").toLowerCase()===o;if(i){let c=await this.moralis.getWalletTokenBalances({address:i,chain:n});if(c.success&&c.data?.result?.length){let u=c.data.result.find(s);if(u)return{address:u.token_address,symbol:u.symbol,name:u.name,decimals:typeof u.decimals=="number"?u.decimals:void 0}}}let l=await this.moralis.searchTokensByKey({key:r,chain:n});if(l.success&&l.data?.length){let u=l.data.find(s)??l.data[0];if(u?.token_address)return{address:u.token_address,symbol:u.symbol,name:u.name,decimals:typeof u.decimals=="number"?u.decimals:void 0}}}parseDecimals(r){if(typeof r=="number"&&Number.isInteger(r)&&r>=0)return r;if(typeof r=="string"&&r.trim()){let n=parseInt(r,10);if(Number.isInteger(n)&&n>=0)return n}}async resolveTokenRef(r){let{contractArg:n,symbolArg:i,decimalsArg:o,chain:a,walletAddress:s}=r,l=this.parseDecimals(o),c=typeof i=="string"&&i.trim()?i.trim():void 0,u=this.normaliseAddress(n),d=typeof n=="string"&&n.trim()?n.trim():void 0,f=u??c??d;if(!f)return{token:void 0};let m=await this.resolveContractAddress(f,a,s);return m?{token:{address:m.address,symbol:c??m.symbol,name:m.name,decimals:l??m.decimals}}:u?{token:{address:u,symbol:c,decimals:l}}:{error:"token_not_found",key:f}}requireWallet(r){let n=r?.walletAddress;return n?{ok:!0,address:n}:{ok:!1,payload:{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before submitting the action. Do NOT render the form."}}}requireChain(r,n){return sn(r.chain,n)}normaliseAddress(r){if(typeof r!="string")return null;let n=r.trim();return Bt(n)?n:null}normaliseAmount(r){if(typeof r=="number"&&Number.isFinite(r)&&r>0)return String(r);if(typeof r!="string")return null;let n=r.trim();if(!n)return null;let i=parseFloat(n);return Number.isFinite(i)&&i>0?n:null}async resolveAmountInput(r){let{rawAmount:n,tokenAddress:i,chain:o,walletAddress:a,gasKind:s}=r,l=Ho(n);if(!l)return null;let c=r.symbol??"the token",u=i.toLowerCase()==="native",d=!!s&&u&&!!o;if(l.kind==="token")return{amount:this.toPlainDecimal(l.value)};let f=await this.readTokenBalanceAndPrice(i,o,a),m=f?.balance;d&&f?.balance!==void 0&&(m=await this.computeNativeSpendable(o,s,f.balance));let g=Hq(l,{balance:m,usdPrice:f?.usdPrice});return g.ok?{amount:this.toPlainDecimal(g.amount)}:g.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${c} balance to work out ${l.raw} right now. Tell them, in their language, that the balance couldn't be fetched at the moment and ask them to enter an exact ${c} amount instead. Do NOT invent a balance or amount. Do NOT mention tool names, UI, or forms.`}:{error:"amount_price_unavailable",_instructions:`Could not get a USD price for ${c} to work out ${l.raw} right now. Tell them, in their language, that the price couldn't be fetched at the moment and ask them to enter an exact ${c} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(r,n,i){let o=await Np(r,n);return $p(i,o,r)}async resolveNativeSpendableFormatted(r,n,i){if(!(!r||!n))try{let o=await this.readTokenBalanceAndPrice("native",r,n);if(o?.balance===void 0)return;let a=await this.computeNativeSpendable(r,i,o.balance);return this.toPlainDecimal(a)}catch{return}}async readTokenBalanceAndPrice(r,n,i){if(!this.moralis||!i)return;let o=await this.moralis.getWalletTokenBalances({address:i,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),a=o.success?o.data?.result??[]:[],s=r.toLowerCase()==="native",l=r.toLowerCase(),c=a.find(d=>s?d.native_token===!0:(d.token_address??"").toLowerCase()===l);if(!c)return;let u=c.balance_formatted!=null?Number(c.balance_formatted):void 0;return{balance:Number.isFinite(u)?u:void 0,usdPrice:typeof c.usd_price=="number"&&c.usd_price>0?c.usd_price:void 0,balanceFormatted:c.balance_formatted,symbol:c.symbol}}cleanAmountString(r){if(!/e/i.test(r))return r;let n=Number(r);return Number.isFinite(n)?this.toPlainDecimal(n):r}toPlainDecimal(r){let n=String(r);if(!/e/i.test(n))return n;let i=r<0,[o,a]=Math.abs(r).toString().split("e"),s=Number(a),[l,c=""]=o.split("."),u=l+c,d;if(s>=0){let f=l.length+s;d=f>=u.length?u.padEnd(f,"0"):`${u.slice(0,f)}.${u.slice(f)}`}else d=`0.${"0".repeat(-s-l.length)}${u}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),i?`-${d}`:d}async execute(r,n){let i=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let a=await this.run(r,n),s={toolName:this.name,callId:i,success:!0,data:a,duration:Date.now()-o};return a&&typeof a=="object"&&a.ui&&(s.ui=a.ui),a&&Array.isArray(a.actionButtons)&&a.actionButtons.length>0&&(s.actionButtons=a.actionButtons),s}catch(a){return{toolName:this.name,callId:i,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}async run(r,n){let i=this.requireWallet(n);if(!i.ok)return i.payload;let o=Ud(r.chain,n);if(o){let b=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${b} on ${o.requestedLabel}, but their wallet is connected to ${o.connectedLabel}. Tell them, in their language, that to ${b} on ${o.requestedLabel} they must first switch their wallet's network to ${o.requestedLabel}, or they can ${b} on ${o.connectedLabel} (their current network) instead. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}let a=this.requireChain(r,n);if(!a){let b=typeof n?.query=="string"?n.query:void 0;return qd(this.actionType.replace(/_/g," "),b)}let s=await this.buildParameters(r,n);if(s&&typeof s=="object"&&"error"in s&&typeof s.error=="string"||s&&typeof s=="object"&&"actionButtons"in s&&Array.isArray(s.actionButtons)||s&&typeof s=="object"&&"ui"in s&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string")return s;let l=s,c=this.buildUI({parameters:l,chainId:a,walletAddress:i.address}),u=b=>{let w=l[b];return w!=null&&w!==""},d=this.userInputFields.filter(b=>!(Array.isArray(b.key)?b.key:[b.key]).some(u)).map(b=>b.label),f=this.userInputFields.map(b=>{let T=(Array.isArray(b.key)?b.key:[b.key]).find(u);return T?`${b.label}: ${l[T]}`:null}).filter(b=>b!=null),m=this.actionType.replace(/_/g," "),g='NEVER invent, guess, or insert a placeholder (e.g. "[recipient address]") for any detail the user has not actually provided \u2014 only state values listed as already provided. Do NOT mention tool names, UI, or forms.',y="The user completes this themselves and it is submitted right away \u2014 do NOT ask them to reply to confirm, do NOT say you will send it for them, and do NOT announce the result. This turn ends after your message.",_=d.length>0?`The ${m} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${d.join(", ")}. `+(f.length>0?`Already provided: ${f.join("; ")}. `:"")+`${y} ${g}`:`The ${m} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${m}. `+(f.length>0?`Details provided: ${f.join("; ")}. `:"")+`${y} ${g}`;return{ui:c,action:this.actionType,chainId:a,parameters:l,_instructions:_}}};p();var Mp=class extends Mi{constructor(r){super(r);h(this,"name","open-send-native-form");h(this,"actionType","send_native");h(this,"component","SendNativeForm");h(this,"userInputFields",[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}]);h(this,"description",`Open the SEND NATIVE form for the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026). Use for ANY native-send intent: "send eth", "send 0.1 ETH", "transfer 1 BNB to vitalik.eth", "g\u1EEDi ETH". Call EVEN IF the user did not name an amount or recipient \u2014 the form prompts for them. Do NOT use for ERC-20 tokens \u2014 use open-send-token-form instead.`);h(this,"parameters",[{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. Defaults to connected chain.',required:!1},{name:"native_symbol",type:"string",description:'The native coin the user named to send, VERBATIM (e.g. "ETH", "BNB", "MATIC", "AVAX"). ALWAYS set this when the user names the coin ("send bnb" \u2192 native_symbol="BNB"); leave blank only when they say just "send" with no coin. A coin that belongs to one specific chain (BNB\u2192BSC, MATIC/POL\u2192Polygon, AVAX\u2192Avalanche, XDAI\u2192Gnosis, HYPE\u2192HyperEVM, MNT\u2192Mantle, MON\u2192Monad) selects that chain, so the tool can detect when the wallet is connected elsewhere.',required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Amount of native coin to send. Accepted forms: a plain amount ("0.1"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become the literal "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself (and for the native coin always leaves enough to cover the network fee). Omit when unknown.',required:!1}])}async run(r,n){if(r.chain==null||r.chain===""){let i=rq(r.native_symbol);if(i)return super.run({...r,chain:i},n)}return super.run(r,n)}async buildParameters(r,n){let i={},o=this.requireChain(r,n)??void 0,a=n?.walletAddress??void 0,s=await this.readTokenBalanceAndPrice("native",o,a);if(!s||s.balance==null||s.balance<=0){let u=s?.symbol||"the native coin";return{error:"no_native_balance",_instructions:`The user wants to send ${u} but their wallet holds 0 ${u} on this chain. Tell them, in their language, that they do not have any ${u} to send and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}if(r.to_address!=null){let u=this.normaliseAddress(r.to_address);u?i.to_address=u:typeof r.to_address=="string"&&r.to_address.trim()&&(i.to_address=r.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:r.amount,tokenAddress:"native",symbol:"the native coin",chain:o,walletAddress:a,gasKind:"send"});if(l&&"error"in l)return l;l&&(i.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(o,a,"send");return c!==void 0&&(i.spendable=c),i}};p();var Dp=class extends Mi{constructor(r){super(r);h(this,"name","open-send-token-form");h(this,"actionType","send_token");h(this,"component","SendTokenForm");h(this,"userInputFields",[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}]);h(this,"description",`Open the SEND TOKEN (ERC-20) form. Use for ANY ERC-20 send/transfer intent: "send token", "send USDC", "transfer 50 DAI to 0x\u2026", "g\u1EEDi 10 USDT". Call this tool EVEN IF the user did not name a token, amount, or recipient \u2014 the tool handles missing token via a picker, the form prompts for the rest. Do NOT use for the chain's native coin (ETH/BNB/MATIC/AVAX) \u2014 use open-send-native-form instead.`);h(this,"parameters",[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol \u2014 the tool will look up the address.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). ALWAYS set this whenever the user names a token to send ("send usdc" \u2192 token_symbol="USDC"); only leave it blank when the user names NO token at all ("send token"), so the tool can show a wallet picker. Used to auto-resolve the contract address and to display the symbol in the form. (Pass either this or contract_address.)',required:!1},{name:"decimals",type:"number",description:"Token decimals (e.g. 6 for USDC, 18 for most ERC-20s). Optional.",required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown.",required:!1},{name:"amount",type:"string",description:'Amount of the token to send. Accepted forms: a plain amount ("100"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself. Omit when unknown.',required:!1},{name:"send_prompt_template",type:"string",description:`A short imperative "send" command IN THE USER'S LANGUAGE, used as the label/command when the user has not yet picked which token to send (token-picker buttons). Write it in the SAME language the user is using right now. Use these exact placeholders (do not translate the braces): "{symbol}" for the token, "{amount}" for the amount, "{to}" for the recipient address, "{chain}" for the chain name. Put the localized verb, the "to" preposition, and the "on <chain>" preposition directly in the text. English example: "send {amount} {symbol} to {to} on {chain}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to} tr\xEAn {chain}". Japanese example: "{chain} \u3067 {to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to}/{chain} too \u2014 the tool removes any whose value is unknown.`,required:!0}])}async buildParameters(r,n){let i=this.normaliseAddress(r.contract_address)!=null,o=typeof r.token_symbol=="string"&&r.token_symbol.trim().length>0;if(!i&&!o&&this.moralis){let d=this.requireChain(r,n)??void 0,f=n?.walletAddress;if(f){let m=await this.moralis.getWalletTokenBalances({address:f,chain:d,excludeSpam:!1,excludeUnverifiedContracts:!1}),y=(m.success?m.data?.result??[]:[]).filter(C=>C.symbol&&(C.native_token||C.token_address)).sort((C,N)=>(N.usd_value??0)-(C.usd_value??0)).slice(0,8);if(y.length===0)return{error:"no_token_holdings",_instructions:"The wallet does not hold any sendable tokens on this chain. Tell the user they have nothing to send and suggest they top up first. Do NOT open the form."};let _=r.to_address!=null?this.normaliseAddress(r.to_address):null,b=this.normaliseAmount(r.amount),w=typeof r.send_prompt_template=="string"?r.send_prompt_template:"",T=d?ve(d):null;return{actionButtons:y.map(C=>{let N=C.symbol,M=C.balance_formatted?this.cleanAmountString(C.balance_formatted):"",A=C.name?C.name:"",U=C.usd_value?`($${C.usd_value.toFixed(2)})`:"";return{label:`${A}:${M} ${N} ${U}`.trim(),prompt:this.buildSendPrompt(w,N,b,_,T)}}),_instructions:"Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n g\u1EEDi token.' / 'You want to send a token.'), then ask them to choose which token from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n g\u1EEDi.' / 'Please choose the token you want to send.'). Do NOT list the tokens in text \u2014 the options already show them. Do NOT mention tool names, UI, or forms."}}}let a=this.requireChain(r,n)??void 0,s=n?.walletAddress??void 0,l=await this.findOwnedTokenForSend(r,a,s);if(l&&"error"in l)return l;let c=l?.token,u={};if(c?.address&&(u.contract_address=c.address),c?.symbol&&(u.token_symbol=c.symbol),c?.decimals!==void 0&&(u.decimals=String(c.decimals)),l?.spendable!==void 0&&(u.spendable=l.spendable),r.to_address!=null){let d=this.normaliseAddress(r.to_address);d?u.to_address=d:typeof r.to_address=="string"&&r.to_address.trim()&&(u.to_address=r.to_address.trim())}if(c?.address){let d=await this.resolveAmountInput({rawAmount:r.amount,tokenAddress:c.address,symbol:c.symbol,chain:a,walletAddress:s});if(d&&"error"in d)return d;d&&(u.amount=d.amount)}else{let d=this.normaliseAmount(r.amount);d&&(u.amount=d)}return u}async findOwnedTokenForSend(r,n,i){let o=this.normaliseAddress(r.contract_address),a=typeof r.token_symbol=="string"&&r.token_symbol.trim()?r.token_symbol.trim():void 0,s=o??a;if(!this.moralis||!i||!s){let g=await this.resolveTokenRef({contractArg:r.contract_address,symbolArg:r.token_symbol,decimalsArg:r.decimals,chain:n,walletAddress:i});return"error"in g?{error:"token_not_found",symbol:g.key,_instructions:`Could not resolve token "${g.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:g.token}}let l=s.toLowerCase(),c=o!=null,u=await this.moralis.getWalletTokenBalances({address:i,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),f=(u.success?u.data?.result??[]:[]).find(g=>c?(g.token_address??"").toLowerCase()===l:(g.symbol??"").toLowerCase()===l);if(f&&f.balance&&!/^0*$/.test(f.balance.trim())){let g=this.parseDecimals(r.decimals);return{token:{address:f.token_address,symbol:f.symbol??a,name:f.name,decimals:g??(typeof f.decimals=="number"?f.decimals:void 0)},spendable:f.balance_formatted?this.cleanAmountString(f.balance_formatted):void 0}}let m=f?.symbol??a??s;return{error:"no_balance",symbol:m,_instructions:`The user does not hold any ${m} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${m} to send, and suggest they top up or pick another token. Do NOT open a form. Do NOT mention tool names, UI, or forms.`}}buildSendPrompt(r,n,i,o,a){let l=(r&&r.includes("{symbol}")?r:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,n).replace(/\{amount\}/g,i??"");return l=this.fillOrDropPhrase(l,"{to}",o),l=this.fillOrDropPhrase(l,"{chain}",a),l.replace(/\s+/g," ").trim()}fillOrDropPhrase(r,n,i){if(i)return r.split(n).join(i);let o=n.replace(/[{}]/g,"\\$&");return r.replace(new RegExp(`\\s*\\S+\\s*${o}`,"g"),"").replace(new RegExp(`${o}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(o,"g"),"")}};p();var Up=class extends Mi{constructor(r){super(r);h(this,"name","open-approve-token-form");h(this,"actionType","approve_token");h(this,"component","ApproveTokenForm");h(this,"userInputFields",[{key:"spender_address",label:"the spender address to approve"}]);h(this,"description",'Open the APPROVE TOKEN form so the user can grant a spender allowance on an ERC-20 token. Use when the user says "approve USDC for Uniswap", "c\u1EA5p quy\u1EC1n 100 USDT cho 0x\u2026", "revoke approval". Pass `contract_address` when you have it; otherwise pass `token_symbol` (e.g. "USDC") and the tool auto-resolves the contract. Always pass `spender_address` (the contract being approved). Pass `amount` for a specific allowance; omit for unlimited (max uint256). For approving 0 to revoke, pass amount="0".');h(this,"parameters",[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). Required when contract_address is not given. Used to auto-resolve the contract.',required:!1},{name:"decimals",type:"number",description:"Token decimals.",required:!1},{name:"spender_address",type:"string",description:"EVM address of the spender contract being approved (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Human-readable allowance amount. Omit for UNLIMITED (max uint256). Pass "0" to revoke.',required:!1}])}async buildParameters(r,n){let i=this.requireChain(r,n)??void 0,o=await this.resolveTokenRef({contractArg:r.contract_address,symbolArg:r.token_symbol,decimalsArg:r.decimals,chain:i,walletAddress:n?.walletAddress??void 0});if("error"in o)return{error:"token_not_found",symbol:o.key,_instructions:`Could not resolve token "${o.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let a=o.token,s=this.normaliseAddress(r.spender_address),l={};if(a?.address&&(l.contract_address=a.address),s&&(l.spender_address=s),a?.symbol&&(l.token_symbol=a.symbol),a?.decimals!==void 0&&(l.decimals=String(a.decimals)),typeof r.amount=="string"&&r.amount.trim()){let c=r.amount.trim(),u=parseFloat(c);Number.isFinite(u)&&u>=0&&(l.amount=c)}else typeof r.amount=="number"&&Number.isFinite(r.amount)&&r.amount>=0&&(l.amount=String(r.amount));return l}};p();var qp=class extends se{constructor(r,n){super();h(this,"name","open-buy-token-form");h(this,"kind","action");h(this,"category","wallet-action");h(this,"moralis");h(this,"pantograph");h(this,"debug");h(this,"description",'Open the BUY TOKEN flow for ANY buy/purchase intent. Handles both cases: (a) the user NAMED a token \u2014 "buy PEPE", "mua DOGE", "buy 100 USDC with ETH": pass `token_symbol` (the destination); if you also know the pay token, fill `pay_with_symbol` (or `pay_with_address`), else leave pay_with_* blank and the tool returns a wallet picker. (b) the user did NOT name a token \u2014 "buy a trending token", "mua token trending", "buy something pumping", "buy hot tokens", "mua token t\u0103ng m\u1EA1nh": leave `token_symbol` blank and the tool returns buttons of the chain\'s current trending tokens so the user picks one. Amount: `buy_amount` = destination to RECEIVE; `pay_with_amount` = payment to SPEND. Never both.');h(this,"parameters",[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"token_symbol",type:"string",description:'Symbol of the token the user wants to BUY (e.g. "PEPE"). Leave EMPTY when the user did not name a token (e.g. "buy a trending token") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"contract_address",type:"string",description:`Destination token address (0x\u2026), or "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from token_symbol.`,required:!1},{name:"buy_amount",type:"string",description:`Quantity of the DESTINATION token (the one being bought) the user wants to RECEIVE. Set this when the amount sits next to the token being bought: "buy 5 PEPE", "mua 5 PEPE", "buy 0.02 PCM with USDC" \u2192 buy_amount = the number next to PEPE/PCM. May also be a USD value when the user sizes the buy in dollars ("buy $5 of PEPE" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$" to a token quantity). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with pay_with_amount \u2014 set at most ONE of the two.`,required:!1},{name:"pay_with_symbol",type:"string",description:'Symbol of the payment token (e.g. "USDC", "ETH"). Set ONLY when the user actually named a token to pay with. Leave EMPTY when they did not \u2014 do NOT default to the native coin / ETH; the tool then returns a picker of the tokens the wallet holds.',required:!1},{name:"pay_with_address",type:"string",description:`Address of the payment token (0x\u2026), OR "native" for the chain's native coin. Set ONLY when the user named the payment token. Leave EMPTY when they did not \u2014 do NOT invent an address or default to native.`,required:!1},{name:"pay_with_amount",type:"string",description:'Quantity of the PAYMENT token (the one being spent) the user wants to SPEND. Set this when the amount sits next to the payment token: "buy PEPE with 10 USDC", "mua PEPE b\u1EB1ng 10 USDC", "spend 0.5 ETH on DOGE" \u2192 pay_with_amount = the number next to USDC/ETH. May also be a PERCENT of the pay-token balance ("buy USDC with 50% USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("buy USDC with 5$ USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set pay_with_symbol to the payment token ("ETH" in "buy USDC with max ETH"). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with buy_amount \u2014 set at most ONE of the two.',required:!1},{name:"limit",type:"number",description:"Only used when no token is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the trending-token picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_with_prompt_template",type:"string",description:`A short "buy X with Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the pay-token picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{token}" = token being bought, "{pay}" = payment token, "{buy_amount}" = quantity of the BOUGHT token (place it next to {token}), "{pay_amount}" = quantity of the PAYMENT token (place it next to {pay}). Put the localized verb and the "with" preposition directly in the text. English example: "buy {buy_amount} {token} with {pay_amount} {pay}". Vietnamese example: "mua {buy_amount} {token} b\u1EB1ng {pay_amount} {pay}". Japanese example: "{pay_amount} {pay} \u3067 {buy_amount} {token} \u8CFC\u5165". Always include {token} and {pay}. Include both {buy_amount} and {pay_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount).`,required:!0}]);r!==void 0&&(this.moralis=new lt(r),this.pantograph=new Pn({baseUrl:r.pantographUrl})),this.debug=n?.debug??!1}dbg(r,n){this.debug&&(n===void 0?console.log(`[BuyTokenTool] ${r}`):console.log(`[BuyTokenTool] ${r}`,JSON.stringify(n)))}async execute(r,n){let i=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let a=await this.run(r,n),s={toolName:this.name,callId:i,success:!0,data:a,duration:Date.now()-o};return a&&typeof a=="object"&&a.ui&&(s.ui=a.ui),a&&Array.isArray(a.actionButtons)&&a.actionButtons.length>0&&(s.actionButtons=a.actionButtons),s}catch(a){return{toolName:this.name,callId:i,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}async run(r,n){if(!n?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let o=Ud(r.chain,n);if(o)return{error:"wrong_chain",_instructions:`The user asked to buy on ${o.requestedLabel}, but their wallet is connected to ${o.connectedLabel}. Tell them, in their language, that to buy on ${o.requestedLabel} they must first switch their wallet's network to ${o.requestedLabel}, or they can buy on ${o.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(r,n)){let s=typeof n?.query=="string"?n.query:void 0;return qd("buy",s)}return this.buildResult(r,n)}async buildResult(r,n){this.correctAmountSide(r,n),this.dropUnmentionedPayToken(r,n),this.dropInventedAmounts(r,n);let i=typeof r.token_symbol=="string"?r.token_symbol.trim():"",o=typeof r.contract_address=="string"?r.contract_address.trim():"",a=this.requireChain(r,n)??void 0,s=n?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:r,chain:a,walletAddress:s,hasMoralis:!!this.moralis}),!i&&!o)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(r,n);let l=await this.resolveSide(r.contract_address,i,a,s,"dest"),c=l.address,u=l.symbol??i,d=l.decimals,f=await this.resolveSide(r.pay_with_address,r.pay_with_symbol,a,s,"pay"),m=f.address,g=f.symbol,y=f.decimals,_=await this.resolveBuyAmountSpec(r.buy_amount,c,a,u),b=m?await this.resolvePayAmountSpec(r.pay_with_amount,m,a,s,g,y??(m==="native"?18:void 0)):this.normaliseAmount(r.pay_with_amount),w=Ho(r.pay_with_amount),T=!!w&&w.kind!=="token",E=null;if(this.dbg("resolved sides",{dest:{destContract:c,destSymbol:u,destDecimals:d},pay:{payAddr:m,paySymbol:g,payDecimals:y},buyAmount:_,payAmount:b}),!c)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${u||o}" to buy on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!m&&this.moralis&&n?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:r,userContext:n,destSymbol:u,destContract:c,buyAmount:_,payAmount:b});if(!m)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${u}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(_&&!b){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:_,destSymbol:u,paySymbol:g});let C=await this.derivePayAmountFromBuy({chain:a,buyAmount:_,destContract:c,destSymbol:u,payAddr:m,paySymbol:g});if(!C)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${g??"of the payment token"} equals ${_} ${u} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${g??"of the payment token"} they want to spend instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};b=C,E=_,T=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:b,derivedFromBuy:E})}if(this.moralis&&n?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:m,paySymbol:g,payAmount:b});let C=await this.checkPayBalance({args:r,userContext:n,chain:a,destSymbol:u,destContract:c,payAddr:m,paySymbol:g,payAmount:b,buyAmount:_,derivedFromBuy:E,amountSizedToBalance:T});if(C)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:C.error,hasButtons:Array.isArray(C.actionButtons)}),C;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!_&&!b&&this.moralis&&n?.walletAddress){this.dbg("Branch 1.5: building amount picker");let C=await this.buildAmountPicker({userContext:n,chain:a,destSymbol:u,payAddr:m,paySymbol:g,buyWithTemplate:typeof r.buy_with_prompt_template=="string"?r.buy_with_prompt_template:""});if(C)return this.dbg("\u2192 Branch 1.5: amount picker returned"),C;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(b&&(y!==void 0||m==="native")){this.dbg("Branch 1.75: building confirm tx");let C=await this.buildConfirmTx({userContext:n,chain:a,destContract:c,destSymbol:u,destDecimals:d,payAddr:m,paySymbol:g,payDecimals:y,payAmount:b});return C&&"ui"in C?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),C):C&&"quoteError"in C?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:C.quoteError}),{error:"quote_failed",quoteError:C.quoteError,_instructions:`Could not quote buying ${u} with ${g??"the selected token"}. The swap provider reported: "${C.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to buy ${u} with ${g??"the selected token"} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs pay amount"),{error:"needs_pay_amount",_instructions:`Ask the user, in their language, how much ${g??"of the payment token"} they want to spend to buy ${u}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(r){if(typeof r!="string")return null;let n=r.trim();return Bt(n)?n:null}normaliseAmount(r){if(typeof r=="number"&&Number.isFinite(r)&&r>0)return String(r);if(typeof r!="string")return null;let n=r.trim();if(!n)return null;let i=n.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!i)return null;let o=parseFloat(i[1]);return Number.isFinite(o)&&o>0?i[1]:null}correctAmountSide(r,n){let i=typeof n?.query=="string"?n.query:"",o=typeof r.token_symbol=="string"?r.token_symbol.trim():"",a=typeof r.pay_with_symbol=="string"?r.pay_with_symbol.trim():"";if(!i||!o||!a)return;let s=typeof r.buy_amount=="string"?r.buy_amount.trim():"",l=typeof r.pay_with_amount=="string"?r.pay_with_amount.trim():"",c=s.length>0,u=l.length>0;if(c===u)return;let d=c?s:l,f=d.match(/[0-9]*\.?[0-9]+/)?.[0];if(!f)return;let m=this.nearestSymbolSide(i,f,o,a);m&&(m==="pay"&&c?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:d,buySym:o,paySym:a}),r.pay_with_amount=d,r.buy_amount=""):m==="buy"&&u&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:d,buySym:o,paySym:a}),r.buy_amount=d,r.pay_with_amount=""))}dropUnmentionedPayToken(r,n){let i=typeof n?.query=="string"?n.query:"";if(!i)return;let o=typeof r.token_symbol=="string"?r.token_symbol.trim():"";if(!o)return;let a=typeof r.pay_with_symbol=="string"?r.pay_with_symbol.trim():"",s=typeof r.pay_with_address=="string"?r.pay_with_address.trim():"";if(!a&&!s)return;let l=i.toLowerCase(),c=a.toLowerCase(),u=s.toLowerCase(),d=c==="native"||u==="native",f=[];if(a&&c!=="native"&&f.push(c),u&&u!=="native"&&f.push(u),d){f.push("native");let g=this.requireChain(r,n)??void 0,y=g?Br(g)?.native.symbol:void 0;y&&f.push(y.toLowerCase())}f.some(g=>Bt(g)?l.includes(g):this.indexOfToken(l,g)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:a,payAddr:s,buySym:o}),r.pay_with_symbol="",r.pay_with_address="")}dropInventedAmounts(r,n){let i=typeof n?.query=="string"?n.query:"";if(!i)return;let o=(i.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),a=s=>{let l=typeof r[s]=="string"?r[s].trim():"";if(!l)return;let c=l.match(/[0-9]*\.?[0-9]+/)?.[0];if(c===void 0)return;let u=parseFloat(c);Number.isFinite(u)&&(o.some(d=>d===u)||(this.dbg(`dropInventedAmounts: clearing invented ${s}`,{val:l}),r[s]=""))};a("buy_amount"),a("pay_with_amount")}nearestSymbolSide(r,n,i,o){let a=r.toLowerCase(),s=a.indexOf(n.toLowerCase()),l=this.indexOfToken(a,i.toLowerCase()),c=this.indexOfToken(a,o.toLowerCase());if(s<0||l<0||c<0)return null;let u=(m,g)=>Math.max(0,m-(s+n.length),s-(m+g)),d=u(l,i.length),f=u(c,o.length);return f===d?null:f<d?"pay":"buy"}indexOfToken(r,n){if(!n)return-1;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=r.match(new RegExp(`(?:^|[^a-z0-9])(${i})(?:[^a-z0-9]|$)`));return o&&o.index!==void 0?o.index+o[0].indexOf(o[1]):-1}requireChain(r,n){let i=typeof r.chain=="string"&&r.chain.trim()?r.chain.trim():null;return i||(typeof n?.chain=="string"&&n.chain.trim()?n.chain.trim():null)}async resolveContractAddress(r,n,i){if(!this.moralis||!r)return;let o=r.trim().toLowerCase(),a=Bt(r.trim()),s=c=>a?(c.token_address??"").toLowerCase()===o:(c.symbol??"").toLowerCase()===o;if(i){let c=await this.moralis.getWalletTokenBalances({address:i,chain:n});if(c.success&&c.data?.result?.length){let u=c.data.result.find(s);if(u)return{address:u.token_address,symbol:u.symbol,name:u.name,decimals:typeof u.decimals=="number"?u.decimals:void 0}}}let l=await this.moralis.searchTokensByKey({key:r,chain:n});if(l.success&&l.data?.length){let u=l.data.find(s)??l.data[0];if(u?.token_address)return{address:u.token_address,symbol:u.symbol,name:u.name,decimals:typeof u.decimals=="number"?u.decimals:void 0}}}async resolveSide(r,n,i,o,a="side"){let s=typeof r=="string"?r.trim():"",l=typeof n=="string"?n.trim():"";if(s.toLowerCase()==="native"||l.toLowerCase()==="native")return{address:"native",symbol:l||void 0};let c=this.normaliseAddress(r),u=l||void 0,d=g=>g.toLowerCase()===zt?"native":g,f=c??u??(s||void 0);if(!f)return this.dbg(`resolveSide:${a}`,{refStr:s,symbolStr:l,chain:i,resolved:"none"}),{address:null,symbol:u};let m=await this.resolveContractAddress(f,i,o);return this.dbg(`resolveSide:${a}`,{refStr:s,symbolStr:l,chain:i,key:f,lookup:m}),m?{address:d(m.address),symbol:u??m.symbol,decimals:m.decimals}:c?{address:d(c),symbol:u}:{address:null,symbol:u}}async buildConfirmTx(r){let{userContext:n,chain:i,destContract:o,destSymbol:a,destDecimals:s,payAddr:l,paySymbol:c,payDecimals:u,payAmount:d}=r,f=n?.walletAddress;if(!f||!i||!o)return null;let m=Br(i),g=Number.parseInt(i,16);if(!m||!Number.isFinite(g))return null;let y=l==="native",_=y?m.native.decimals??18:u;if(_===void 0)return null;let b=this.toRawAmount(d,_);if(!b)return null;let w=y?zt:l,T=o==="native"?zt:o,E;try{E=await(await Zo.getServiceByProvider("debridge")).getQuote({srcChainId:g,srcTokenAddress:w,srcTokenAmount:b,dstChainId:g,dstTokenAddress:T,recipientAddress:f,senderAddress:f,slippage:"auto",isCrossChain:!1})}catch(L){return{quoteError:L instanceof Error?L.message:String(L)}}if(!E.success)return this.dbg("buildConfirmTx: quote failed",{error:E.error,errorMessage:E.errorMessage}),{quoteError:this.extractQuoteError(E)};if(!E.tx)return{quoteError:"No route available for this swap."};let C=E.tx;if(!C.to||typeof C.data!="string")return null;let N={chainId:i,to:C.to,data:C.data,value:C.value??"0",from:f},M=this.extractOutRaw(E),A=M&&s!==void 0?this.trimAmount(Number(M)/10**s):void 0,U;y||(U=await this.buildApproveTx({chain:i,walletAddress:f,payAddr:l,payDec:_,rawAmount:b,quote:E}));let x={component:"BuyTokenConfirmTx",props:{chain:{hexId:i,name:m.name},payToken:{address:y?"native":l,symbol:c,decimals:_,amount:d,rawAmount:b},buyToken:{address:o,symbol:a,decimals:s,amount:A,rawAmount:M},estimatedOut:A,estimatedOutRaw:M,provider:E.provider,swapTx:N,approveTx:U}},O=A?` They will receive about ${A} ${a}.`:"";return{ui:x,_instructions:`The purchase of ${a} with ${d} ${c??"the selected token"} is ready for the user to confirm.${O} Briefly tell the user, in their language, the amount they are spending and the estimated amount they will receive, and ask them to review and confirm to complete the purchase. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (buying) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async derivePayAmountFromBuy(r){let{chain:n,buyAmount:i,destContract:o,payAddr:a}=r,[s,l]=await Promise.all([this.getUsdPrice(o,n),this.getUsdPrice(a,n)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:s,payPrice:l}),!s||!l)return null;let c=Number(i);if(!Number.isFinite(c)||c<=0)return null;let u=1.02,d=c*s/l;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*u)}async getUsdPrice(r,n){if(!this.moralis)return null;let i=r==="native"?zt:r,o=await this.moralis.getTokenMetadata({address:i,chain:n}),a=o.success?o.data?.usd_price:void 0;return typeof a=="number"&&Number.isFinite(a)&&a>0?a:null}async resolvePayAmountSpec(r,n,i,o,a,s){let l=Ho(r);if(!l)return null;let c=d=>s===void 0?d:Od(d,s);if(l.kind==="token")return c(Id(r)??this.toPlainDecimal(l.value));if(l.kind==="percent"){if(!o)return null;let d=await this.readPayBalance(o,n,i);if(this.dbg("resolvePayAmountSpec: percent",{percent:l.percent,paySymbol:a,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let f=d.decimals??s??18;return l.percent>=100?this.cleanAmountString(d.balanceFormatted):Rd(d.balanceFormatted,BigInt(Math.round(l.percent*1e6)),100000000n,f)}let u=await this.getUsdPrice(n,i);return this.dbg("resolvePayAmountSpec: usd",{usd:l.usd,paySymbol:a,price:u}),u?c(this.trimAmount(l.usd/u)):null}async resolveBuyAmountSpec(r,n,i,o){let a=Ho(r);if(!a)return null;if(a.kind==="token")return Id(r)??this.toPlainDecimal(a.value);if(a.kind==="percent"||!n)return null;let s=await this.getUsdPrice(n,i);return this.dbg("resolveBuyAmountSpec: usd",{usd:a.usd,destSymbol:o,price:s}),s?this.trimAmount(a.usd/s):null}async buildApproveTx(r){let{chain:n,walletAddress:i,payAddr:o,payDec:a,rawAmount:s,quote:l}=r;try{let u=await(await Zo.getServiceByProvider("debridge")).checkApproval({chain:n,userAddress:i,tokenAddress:o,amount:s,tokenDecimals:a,quoteData:l});if(!u.isNeeded)return;let d=u.approvalData??{};if(d.to&&typeof d.data=="string")return{chainId:n,to:d.to,data:d.data,value:d.value??"0",from:i};let f=u.contractAddress;if(!f)return;let m=Ad({abi:Nv,functionName:"approve",args:[f,BigInt(s)]});return{chainId:n,to:o,data:m,value:"0",from:i}}catch{return}}toRawAmount(r,n){let i=r.trim();if(!/^\d*\.?\d+$/.test(i))return null;let[o,a=""]=i.split("."),s=a.slice(0,n).padEnd(n,"0");try{let l=BigInt(o||"0")*10n**BigInt(n)+BigInt(s||"0");return l<=0n?null:l.toString()}catch{return null}}extractQuoteError(r){if(r.errorMessage&&r.errorMessage.trim())return r.errorMessage.trim();let n=o=>{if(typeof o=="string"&&o.trim())return o.trim();if(o&&typeof o=="object"){let a=o;for(let s of[a.message,a.errorMessage,a.error])if(typeof s=="string"&&s.trim())return s.trim()}},i=r.raw??{};return n(r.error)??n(i.errorMessage)??n(i.error)??"The swap could not be quoted right now."}extractOutRaw(r){let n=r.raw??{},i=n.tokenOut?.amount??n.tokenOut?.minAmount??n.details?.currencyOut?.amount??n.details?.currencyOut?.minimumAmount??n.estimation?.dstChainTokenOut?.recommendedAmount??n.estimation?.dstChainTokenOut?.amount;return i&&/^\d+$/.test(i)?i:void 0}async buildPayWithPicker(r){let{args:n,userContext:i,destSymbol:o,destContract:a}=r,s=this.requireChain(n,i)??void 0,l=this.moralis,c=i.walletAddress,u=await l.getWalletTokenBalances({address:c,chain:s,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=u.success?u.data?.result??[]:[],f=a?.toLowerCase(),m=o.trim().toLowerCase(),g=d.filter(T=>!T.symbol||m&&T.symbol.toLowerCase()===m?!1:T.native_token?f!=="native":!(!T.token_address||f&&T.token_address.toLowerCase()===f)).sort((T,E)=>(E.usd_value??0)-(T.usd_value??0)).slice(0,8);if(g.length===0)return{error:"no_pay_token_holdings",_instructions:"The wallet has no tokens that can pay for this purchase on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let y=r.buyAmount??this.normaliseAmount(n.buy_amount),_=r.payAmount??this.normaliseAmount(n.pay_with_amount),b=typeof n.buy_with_prompt_template=="string"?n.buy_with_prompt_template:"";return{actionButtons:g.map(T=>{let E=T.symbol,C=T.name?.trim()||E,N=T.balance_formatted?`${this.cleanAmountString(T.balance_formatted)} `:"",M=typeof T.usd_value=="number"&&T.usd_value>0?` ($${T.usd_value.toFixed(2)})`:"",A=`${C}: ${N}${E}${M}`,U=y?this.buildBuyWithPrompt(b,o,E,y,null):this.buildBuyWithPrompt(b,o,E,null,_);return{label:A,prompt:U}}),_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n mua ${o}.' / 'You want to buy ${o}.'), then ask them to choose which token they want to spend to buy ${o} from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua.' / 'Please choose the token to spend.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async checkPayBalance(r){let{args:n,userContext:i,chain:o,destSymbol:a,destContract:s,payAddr:l,payAmount:c,buyAmount:u,derivedFromBuy:d}=r,f=i.walletAddress,m=await this.readPayBalance(f,l,o),g=r.paySymbol??m?.symbol??"the selected token";if(!m){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:g});let T=await this.buildPayWithPicker({args:n,userContext:i,destSymbol:a,destContract:s,buyAmount:u,payAmount:c});return"actionButtons"in T?{error:"no_pay_balance",actionButtons:T.actionButtons,_instructions:`The user wanted to spend ${g} to buy ${a}, but their wallet holds no ${g} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${g} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${g} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to pay with (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua ${a} t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to pay with from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:T}if(!c||r.amountSizedToBalance)return null;let y=m.decimals!==void 0?Od(c,m.decimals):c;if(pv(y,m.balanceFormatted)<=0)return null;let _=this.cleanAmountString(m.balanceFormatted),b=this.percentSpendButtons({balanceFormatted:m.balanceFormatted,balanceNum:m.balanceNum,decimals:m.decimals,paySymbol:g,destSymbol:a,buyWithTemplate:typeof n.buy_with_prompt_template=="string"?n.buy_with_prompt_template:""}),w=d?`Buying ${d} ${a} needs about ${c} ${g}, but they only have ${_} ${g} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them that buying ${d} ${a} would cost about ${c} ${g}, which is more than their balance of ${_} ${g}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${c} ${g} to buy ${a}, but they only have ${_} ${g} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${c} ${g} exceeds their balance of ${_} ${g}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:b,_instructions:w+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readPayBalance(r,n,i){if(!this.moralis)return null;let o=await this.moralis.getWalletTokenBalances({address:r,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1}),a=o.success?o.data?.result??[]:[];this.dbg("readPayBalance",{payAddr:n,chain:i,ok:o.success,count:a.length,held:a.map(u=>({sym:u.symbol,addr:u.token_address,bal:u.balance_formatted}))});let s=n.toLowerCase(),l=a.find(u=>s==="native"?u.native_token===!0:u.token_address?.toLowerCase()===s);if(!l?.balance_formatted)return this.dbg("readPayBalance: pay token NOT held \u2192 null",{payAddr:n}),null;let c=Number(l.balance_formatted);if(!Number.isFinite(c)||c<=0)return this.dbg("readPayBalance: zero/invalid balance \u2192 null",{payAddr:n,balance:l.balance_formatted}),null;if(s==="native"&&i){let u=await Np(i,"swap"),d=$p(c,u,i);if(this.dbg("readPayBalance: native spendable",{balanceNum:c,spendable:d}),d<=0)return this.dbg("readPayBalance: native spendable \u2264 0 \u2192 null",{balanceNum:c}),null;let f=this.trimAmount(d),m=typeof l.decimals=="number"?l.decimals:18;return{balanceFormatted:f,balanceNum:d,symbol:l.symbol,decimals:m}}return this.dbg("readPayBalance: held",{payAddr:n,balance:l.balance_formatted,symbol:l.symbol}),{balanceFormatted:l.balance_formatted,balanceNum:c,symbol:l.symbol,decimals:typeof l.decimals=="number"?l.decimals:void 0}}percentSpendButtons(r){let{balanceFormatted:n,decimals:i,paySymbol:o,destSymbol:a,buyWithTemplate:s}=r,l=i??18;return[25,50,75,100].map(u=>{let d=Rd(this.cleanAmountString(n),BigInt(u),100n,l);return{label:`${u}%`,prompt:this.buildBuyWithPrompt(s,a,o,null,d)}})}async buildAmountPicker(r){let{userContext:n,chain:i,destSymbol:o,payAddr:a,buyWithTemplate:s}=r,l=n.walletAddress,c=await this.readPayBalance(l,a,i),u=r.paySymbol??c?.symbol;if(!c||!u)return null;let d=this.percentSpendButtons({balanceFormatted:c.balanceFormatted,balanceNum:c.balanceNum,decimals:c.decimals,paySymbol:u,destSymbol:o,buyWithTemplate:s}),f=this.cleanAmountString(c.balanceFormatted);return{actionButtons:d,_instructions:`The user's spendable balance is ${f} ${u}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${u} balance (e.g., 'B\u1EA1n mu\u1ED1n mua ${o} b\u1EB1ng ${u}, hi\u1EC7n c\xF3 ${f} ${u} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to buy ${o} with ${u}; you have ${f} ${u} available.'), then ask how much they want to spend and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(r){return Number.isFinite(r)?this.toPlainDecimal(parseFloat(r.toPrecision(8))):"0"}toPlainDecimal(r){let n=String(r);if(!/e/i.test(n))return n;let i=r<0,[o,a]=Math.abs(r).toString().split("e"),s=Number(a),[l,c=""]=o.split("."),u=l+c,d;if(s>=0){let f=l.length+s;d=f>=u.length?u.padEnd(f,"0"):`${u.slice(0,f)}.${u.slice(f)}`}else d=`0.${"0".repeat(-s-l.length)}${u}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),i?`-${d}`:d}cleanAmountString(r){if(!/e/i.test(r))return r;let n=Number(r);return Number.isFinite(n)?this.toPlainDecimal(n):r}buildBuyPrompt(r,n){return(r&&r.includes("{token}")?r:"buy {token}").replace(/\{token\}/g,n).replace(/\s+/g," ").trim()}buildBuyWithPrompt(r,n,i,o,a){return(r&&r.includes("{token}")&&r.includes("{pay}")?r:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,n).replace(/\{pay\}/g,i).replace(/\{buy_amount\}/g,o??"").replace(/\{pay_amount\}/g,a??"").replace(/\s+/g," ").trim()}async buildTrendingPicker(r,n){if(!this.pantograph)return{error:"trending_unavailable",_instructions:"Trending tokens are unavailable in this build (service not configured). Tell the user briefly and ask them to name a token to buy."};let i=this.requireChain(r,n)??void 0,o=typeof r.limit=="number"&&Number.isFinite(r.limit)?Math.floor(r.limit):6,a=Math.max(1,Math.min(10,o)),s=await this.pantograph.getTrendingTokens({chain:i,limit:a}),l=s.success?s.data??[]:[];if(l.length===0)return{error:"no_trending_tokens",_instructions:"No trending tokens are available for this chain right now. Tell the user briefly and suggest they name a token directly."};let c=l.filter(g=>g.symbol),u=typeof r.buy_prompt_template=="string"?r.buy_prompt_template:"",d=c.map(g=>{let y=g.symbol;return{label:y,prompt:this.buildBuyPrompt(u,y)}}),m=c.map((g,y)=>{let _=g.name?.trim()||g.symbol,b=g.symbol,w=typeof g.usdPrice=="number"&&g.usdPrice>0?`$${this.formatPrice(g.usdPrice)}`:"N/A",T=g.pricePercentChange?.["24h"],E=typeof T=="number"&&Number.isFinite(T)?` (${T>0?"+":T<0?"-":""}${this.formatPercent(Math.abs(T))}%)`:"";return`${y+1}. ${_} (${b}) \u2014 ${w}${E}`}).join(`
626
+ Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:g||void 0,addLiquidityLink:f,count:y.length,pools:y.map(_=>this.formatPool(_))}}let i=typeof r.poolAddress=="string"?r.poolAddress.trim():"",o=(Array.isArray(r.tokens)?r.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),a=typeof r.feeTier=="number"&&Number.isFinite(r.feeTier)?Math.floor(r.feeTier):void 0,s=typeof r.chain=="string"&&r.chain.trim();if(!s&&!n?.chain&&n?.walletAddress)throw new gr(typeof n?.query=="string"?n.query:void 0);let l=s?r.chain.trim():n?.chain||"0x1";if(!this.service.isSupported(l))return{_instructions:"The requested chain is not supported by the Subgraph pool service. Tell the user, in their language, that add-liquidity is not available on that network and list the supported chains briefly. Do NOT mention tool names.",unsupportedChains:[ve(l)],supportedChains:this.service.listSupportedChains().map(ve)};let c=this.service.resolveChain(l);if(i){if(!/^0x[a-fA-F0-9]{40}$/.test(i))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let f=await this.service.getPoolByAddress({poolAddress:i,chain:c});return f?this.poolsResult([f],c,!0):{error:`No pool found at ${i} on ${ve(c)}.`}}if(o.length>0){let f=await this.service.searchPools({tokens:o,chain:c,sortBy:"tvl",filters:{feeTier:a}});if(f.length===0)return{error:`No Uniswap V3 pool found for ${o.join("/")}${a!=null?` at ${a}bps`:""} on ${ve(c)}. Ask the user to check the token symbols, or try a different pair.`};let m=o.length===2?await this.fetchCoinPoolPairs(c,o):[];return this.poolsResult(f.slice(0,8),c,!0,m)}let u=await this.service.searchPools({tokens:[],chain:c,sortBy:"tvl"}),d=this.linkAddLiquidity??null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity but has not named a pool yet. Briefly list these top pools (pair, fee tier %, TVL, APR \u2014 skip APR if null) as suggestions, render each `uniswapUrl` as a clickable markdown link, then ask the user which token pair (or pool) they want to add liquidity to. '+this.linkInstruction(d)+"Do NOT mention tool names, UI, or forms.",chain:c,needsSelection:!0,addLiquidityLink:d,count:u.length,pools:u.slice(0,6).map(f=>this.formatPool(f))}}async fetchCoinPoolPairs(r,n){try{return[...await this.service.getCoinPoolPairs({chain:r,tokens:n})].sort((o,a)=>(a.apr??-1/0)-(o.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(r){return r?`ALWAYS finish by inviting the user to add liquidity on the website, as ONE short sentence that shows the FULL link in plain view \u2014 display the entire URL verbatim (${r}) as the visible link text, do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${r}](${r}). For example: "You can add liquidity here: [${r}](${r})". Use the URL verbatim; never invent one, and never use a pool's uniswapUrl here. `:"No add-liquidity website is configured, so do not show or invent any link. "}poolsResult(r,n,i,o=[]){let a=i?this.linkAddLiquidity??null:null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity. Show the resolved pool(s): pair (e.g. USDC/WETH), fee tier (%), TVL, volume past day, APR (skip if null), and the pool address. For EACH pool, render the provided `uniswapUrl` as a clickable markdown link. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)", to help the user choose a range when adding liquidity. CRITICAL: that APR is for the SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the data, give a genuine, conversational recommendation \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4A1} Recommendation"); vary your wording naturally each time and only cover what is actually relevant to THIS pair and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: which pool/fee tier looks best and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; fee-tier fit: 0.05% for stable/correlated pairs, 0.30% for typical volatile pairs, 1% for exotic/low-liquidity ones); which price range makes sense (from coinPoolPairs if present) \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; anything worth avoiding (thin TVL/volume, ranges far from current price, chasing the top APR blindly); and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Keep it short and human \u2014 a sentence or two or a couple of light bullets, tailored to whether the pair is stable or volatile. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, do not paste a stock disclaimer). '+(a?`Then, at the VERY END, write ONE short, friendly sentence in the user's language inviting them to add liquidity, showing the FULL add-liquidity link in plain view: display the entire URL verbatim as the visible link text \u2014 do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${a}](${a}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${a}](${a})." Use the addLiquidityLink verbatim; never invent a URL, and never use a pool's uniswapUrl here.`:"Do NOT invent or show any add-liquidity link (none is configured). Just present the pool(s).")+" Do NOT mention tool names, UI, forms, or that a transaction is built elsewhere.",chain:n,addLiquidityLink:a,count:r.length,pools:r.map(l=>this.formatPool(l)),coinPoolPairs:o}}formatPool(r){return{pair:r.pair,poolAddress:r.poolAddress,chain:r.chain,feeTierBps:r.feeTierBps,feeTierPercent:r.feeTierPercent,tvlUsd:r.tvl,volumePastDayUsd:r.volume24hUsd,fees24hUsd:r.fees24hUsd,apr:r.apr,token0:r.token0,token1:r.token1,uniswapUrl:yi(r)}}};p();p();p();function Ho(t){if(typeof t=="number")return Number.isFinite(t)&&t>0?{kind:"token",value:t,raw:String(t)}:null;if(typeof t!="string")return null;let e=t.trim();if(!e)return null;if(/^(?:max(?:imum)?|all|everything|tất\s*cả|toàn\s*bộ)$/i.test(e))return{kind:"percent",percent:100,raw:e};let r=e.match(/^%?\s*([0-9]*\.?[0-9]+)\s*%$|^%\s*([0-9]*\.?[0-9]+)$/);if(r){let o=parseFloat(r[1]??r[2]);return Number.isFinite(o)&&o>0?{kind:"percent",percent:o,raw:e}:null}let n=e.match(/^\$\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*\$$|^(?:usd)\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*usd$/i);if(n){let o=parseFloat(n[1]??n[2]??n[3]??n[4]);return Number.isFinite(o)&&o>0?{kind:"usd",usd:o,raw:e}:null}let i=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(i){let o=parseFloat(i[1]);return Number.isFinite(o)&&o>0?{kind:"token",value:o,raw:e}:null}return null}function Hq(t,e){switch(t.kind){case"token":return{ok:!0,amount:t.value};case"percent":return e.balance===void 0||!Number.isFinite(e.balance)||e.balance<=0?{ok:!1,reason:"no_balance"}:{ok:!0,amount:e.balance*t.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:t.usd/e.usdPrice}}}p();var Cre={send:30000n,swap:1000000n},xre={"0x1":["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"],"0xa":["https://optimism-rpc.publicnode.com","https://optimism.drpc.org"],"0x38":["https://bsc-rpc.publicnode.com","https://bsc.drpc.org"],"0x89":["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"],"0x2105":["https://base-rpc.publicnode.com","https://base.drpc.org"],"0xa4b1":["https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"],"0xa86a":["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"],"0xe708":["https://linea-rpc.publicnode.com","https://linea.drpc.org"],"0x64":["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"],"0x3e7":["https://rpc.hyperliquid.xyz/evm"],"0x1388":["https://mantle-rpc.publicnode.com","https://rpc.mantle.xyz"],"0x8f":["https://rpc.monad.xyz"]};async function Ire(t){let e=t.toLowerCase(),n=[xs(t),...xre[e]??[]].filter(i=>!!i);for(let i of n)try{let o=await Is(i,"eth_gasPrice",[]),a=BigInt(o);if(a>0n)return a}catch{}return 0n}async function Np(t,e){let r=await Ire(t);return r<=0n?0n:Cre[e]*r}function $p(t,e,r){if(e<=0n)return t;let n=Br(r)?.native.decimals;if(n===void 0)return t;let i=Number(e)/10**n;return!Number.isFinite(i)||i<=0?t:Math.max(0,t-i)}var Mi=class extends se{constructor(r){super();h(this,"kind","ui");h(this,"category","wallet-action");h(this,"userInputFields",[]);h(this,"moralis");r!==void 0&&(this.moralis=new lt(r))}buildUI(r){let n={action:this.actionType,chainId:r.chainId,chainName:ve(r.chainId),walletAddress:r.walletAddress,parameters:r.parameters};return{component:this.component,props:n}}async resolveContractAddress(r,n,i){if(!this.moralis||!r)return;let o=r.trim().toLowerCase(),a=Bt(r.trim()),s=c=>a?(c.token_address??"").toLowerCase()===o:(c.symbol??"").toLowerCase()===o;if(i){let c=await this.moralis.getWalletTokenBalances({address:i,chain:n});if(c.success&&c.data?.result?.length){let u=c.data.result.find(s);if(u)return{address:u.token_address,symbol:u.symbol,name:u.name,decimals:typeof u.decimals=="number"?u.decimals:void 0}}}let l=await this.moralis.searchTokensByKey({key:r,chain:n});if(l.success&&l.data?.length){let u=l.data.find(s)??l.data[0];if(u?.token_address)return{address:u.token_address,symbol:u.symbol,name:u.name,decimals:typeof u.decimals=="number"?u.decimals:void 0}}}parseDecimals(r){if(typeof r=="number"&&Number.isInteger(r)&&r>=0)return r;if(typeof r=="string"&&r.trim()){let n=parseInt(r,10);if(Number.isInteger(n)&&n>=0)return n}}async resolveTokenRef(r){let{contractArg:n,symbolArg:i,decimalsArg:o,chain:a,walletAddress:s}=r,l=this.parseDecimals(o),c=typeof i=="string"&&i.trim()?i.trim():void 0,u=this.normaliseAddress(n),d=typeof n=="string"&&n.trim()?n.trim():void 0,f=u??c??d;if(!f)return{token:void 0};let m=await this.resolveContractAddress(f,a,s);return m?{token:{address:m.address,symbol:c??m.symbol,name:m.name,decimals:l??m.decimals}}:u?{token:{address:u,symbol:c,decimals:l}}:{error:"token_not_found",key:f}}requireWallet(r){let n=r?.walletAddress;return n?{ok:!0,address:n}:{ok:!1,payload:{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before submitting the action. Do NOT render the form."}}}requireChain(r,n){return sn(r.chain,n)}normaliseAddress(r){if(typeof r!="string")return null;let n=r.trim();return Bt(n)?n:null}normaliseAmount(r){if(typeof r=="number"&&Number.isFinite(r)&&r>0)return String(r);if(typeof r!="string")return null;let n=r.trim();if(!n)return null;let i=parseFloat(n);return Number.isFinite(i)&&i>0?n:null}async resolveAmountInput(r){let{rawAmount:n,tokenAddress:i,chain:o,walletAddress:a,gasKind:s}=r,l=Ho(n);if(!l)return null;let c=r.symbol??"the token",u=i.toLowerCase()==="native",d=!!s&&u&&!!o;if(l.kind==="token")return{amount:this.toPlainDecimal(l.value)};let f=await this.readTokenBalanceAndPrice(i,o,a),m=f?.balance;d&&f?.balance!==void 0&&(m=await this.computeNativeSpendable(o,s,f.balance));let g=Hq(l,{balance:m,usdPrice:f?.usdPrice});return g.ok?{amount:this.toPlainDecimal(g.amount)}:g.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${c} balance to work out ${l.raw} right now. Tell them, in their language, that the balance couldn't be fetched at the moment and ask them to enter an exact ${c} amount instead. Do NOT invent a balance or amount. Do NOT mention tool names, UI, or forms.`}:{error:"amount_price_unavailable",_instructions:`Could not get a USD price for ${c} to work out ${l.raw} right now. Tell them, in their language, that the price couldn't be fetched at the moment and ask them to enter an exact ${c} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(r,n,i){let o=await Np(r,n);return $p(i,o,r)}async resolveNativeSpendableFormatted(r,n,i){if(!(!r||!n))try{let o=await this.readTokenBalanceAndPrice("native",r,n);if(o?.balance===void 0)return;let a=await this.computeNativeSpendable(r,i,o.balance);return this.toPlainDecimal(a)}catch{return}}async readTokenBalanceAndPrice(r,n,i){if(!this.moralis||!i)return;let o=await this.moralis.getWalletTokenBalances({address:i,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),a=o.success?o.data?.result??[]:[],s=r.toLowerCase()==="native",l=r.toLowerCase(),c=a.find(d=>s?d.native_token===!0:(d.token_address??"").toLowerCase()===l);if(!c)return;let u=c.balance_formatted!=null?Number(c.balance_formatted):void 0;return{balance:Number.isFinite(u)?u:void 0,usdPrice:typeof c.usd_price=="number"&&c.usd_price>0?c.usd_price:void 0,balanceFormatted:c.balance_formatted,symbol:c.symbol}}cleanAmountString(r){if(!/e/i.test(r))return r;let n=Number(r);return Number.isFinite(n)?this.toPlainDecimal(n):r}toPlainDecimal(r){let n=String(r);if(!/e/i.test(n))return n;let i=r<0,[o,a]=Math.abs(r).toString().split("e"),s=Number(a),[l,c=""]=o.split("."),u=l+c,d;if(s>=0){let f=l.length+s;d=f>=u.length?u.padEnd(f,"0"):`${u.slice(0,f)}.${u.slice(f)}`}else d=`0.${"0".repeat(-s-l.length)}${u}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),i?`-${d}`:d}async execute(r,n){let i=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let a=await this.run(r,n),s={toolName:this.name,callId:i,success:!0,data:a,duration:Date.now()-o};return a&&typeof a=="object"&&a.ui&&(s.ui=a.ui),a&&Array.isArray(a.actionButtons)&&a.actionButtons.length>0&&(s.actionButtons=a.actionButtons),s}catch(a){return{toolName:this.name,callId:i,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}async run(r,n){let i=this.requireWallet(n);if(!i.ok)return i.payload;let o=Ud(r.chain,n);if(o){let b=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${b} on ${o.requestedLabel}, but their wallet is connected to ${o.connectedLabel}. Tell them, in their language, that to ${b} on ${o.requestedLabel} they must first switch their wallet's network to ${o.requestedLabel}, or they can ${b} on ${o.connectedLabel} (their current network) instead. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}let a=this.requireChain(r,n);if(!a){let b=typeof n?.query=="string"?n.query:void 0;return qd(this.actionType.replace(/_/g," "),b)}let s=await this.buildParameters(r,n);if(s&&typeof s=="object"&&"error"in s&&typeof s.error=="string"||s&&typeof s=="object"&&"actionButtons"in s&&Array.isArray(s.actionButtons)||s&&typeof s=="object"&&"ui"in s&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string")return s;let l=s,c=this.buildUI({parameters:l,chainId:a,walletAddress:i.address}),u=b=>{let w=l[b];return w!=null&&w!==""},d=this.userInputFields.filter(b=>!(Array.isArray(b.key)?b.key:[b.key]).some(u)).map(b=>b.label),f=this.userInputFields.map(b=>{let T=(Array.isArray(b.key)?b.key:[b.key]).find(u);return T?`${b.label}: ${l[T]}`:null}).filter(b=>b!=null),m=this.actionType.replace(/_/g," "),g='NEVER invent, guess, or insert a placeholder (e.g. "[recipient address]") for any detail the user has not actually provided \u2014 only state values listed as already provided. Do NOT mention tool names, UI, or forms.',y="The user completes this themselves and it is submitted right away \u2014 do NOT ask them to reply to confirm, do NOT say you will send it for them, and do NOT announce the result. This turn ends after your message.",_=d.length>0?`The ${m} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${d.join(", ")}. `+(f.length>0?`Already provided: ${f.join("; ")}. `:"")+`${y} ${g}`:`The ${m} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${m}. `+(f.length>0?`Details provided: ${f.join("; ")}. `:"")+`${y} ${g}`;return{ui:c,action:this.actionType,chainId:a,parameters:l,_instructions:_}}};p();var Mp=class extends Mi{constructor(r){super(r);h(this,"name","open-send-native-form");h(this,"actionType","send_native");h(this,"component","SendNativeForm");h(this,"userInputFields",[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}]);h(this,"description",`Open the SEND NATIVE form for the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026). Use for ANY native-send intent: "send eth", "send 0.1 ETH", "transfer 1 BNB to vitalik.eth", "g\u1EEDi ETH". Call EVEN IF the user did not name an amount or recipient \u2014 the form prompts for them. Do NOT use for ERC-20 tokens \u2014 use open-send-token-form instead.`);h(this,"parameters",[{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. Defaults to connected chain.',required:!1},{name:"native_symbol",type:"string",description:'The native coin the user named to send, VERBATIM (e.g. "ETH", "BNB", "MATIC", "AVAX"). ALWAYS set this when the user names the coin ("send bnb" \u2192 native_symbol="BNB"); leave blank only when they say just "send" with no coin. A coin that belongs to one specific chain (BNB\u2192BSC, MATIC/POL\u2192Polygon, AVAX\u2192Avalanche, XDAI\u2192Gnosis, HYPE\u2192HyperEVM, MNT\u2192Mantle, MON\u2192Monad) selects that chain, so the tool can detect when the wallet is connected elsewhere.',required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Amount of native coin to send. Accepted forms: a plain amount ("0.1"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become the literal "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself (and for the native coin always leaves enough to cover the network fee). Omit when unknown.',required:!1}])}async run(r,n){if(r.chain==null||r.chain===""){let i=rq(r.native_symbol);if(i)return super.run({...r,chain:i},n)}return super.run(r,n)}async buildParameters(r,n){let i={},o=this.requireChain(r,n)??void 0,a=n?.walletAddress??void 0,s=await this.readTokenBalanceAndPrice("native",o,a);if(!s||s.balance==null||s.balance<=0){let d=s?.symbol||"the native coin";return{error:"no_native_balance",_instructions:`The user wants to send ${d} but their wallet holds 0 ${d} on this chain. Tell them, in their language, that they do not have any ${d} to send and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}let l=s.symbol||(typeof r.native_symbol=="string"&&r.native_symbol.trim()?r.native_symbol.trim():void 0);if(l&&(i.native_symbol=l),r.to_address!=null){let d=this.normaliseAddress(r.to_address);d?i.to_address=d:typeof r.to_address=="string"&&r.to_address.trim()&&(i.to_address=r.to_address.trim())}let c=await this.resolveAmountInput({rawAmount:r.amount,tokenAddress:"native",symbol:"the native coin",chain:o,walletAddress:a,gasKind:"send"});if(c&&"error"in c)return c;c&&(i.amount=c.amount);let u=await this.resolveNativeSpendableFormatted(o,a,"send");return u!==void 0&&(i.spendable=u),i}};p();var Dp=class extends Mi{constructor(r){super(r);h(this,"name","open-send-token-form");h(this,"actionType","send_token");h(this,"component","SendTokenForm");h(this,"userInputFields",[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}]);h(this,"description",`Open the SEND TOKEN (ERC-20) form. Use for ANY ERC-20 send/transfer intent: "send token", "send USDC", "transfer 50 DAI to 0x\u2026", "g\u1EEDi 10 USDT". Call this tool EVEN IF the user did not name a token, amount, or recipient \u2014 the tool handles missing token via a picker, the form prompts for the rest. Do NOT use for the chain's native coin (ETH/BNB/MATIC/AVAX) \u2014 use open-send-native-form instead.`);h(this,"parameters",[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol \u2014 the tool will look up the address.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). ALWAYS set this whenever the user names a token to send ("send usdc" \u2192 token_symbol="USDC"); only leave it blank when the user names NO token at all ("send token"), so the tool can show a wallet picker. Used to auto-resolve the contract address and to display the symbol in the form. (Pass either this or contract_address.)',required:!1},{name:"decimals",type:"number",description:"Token decimals (e.g. 6 for USDC, 18 for most ERC-20s). Optional.",required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown.",required:!1},{name:"amount",type:"string",description:'Amount of the token to send. Accepted forms: a plain amount ("100"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself. Omit when unknown.',required:!1},{name:"send_prompt_template",type:"string",description:`A short imperative "send" command IN THE USER'S LANGUAGE, used as the label/command when the user has not yet picked which token to send (token-picker buttons). Write it in the SAME language the user is using right now. Use these exact placeholders (do not translate the braces): "{symbol}" for the token, "{amount}" for the amount, "{to}" for the recipient address, "{chain}" for the chain name. Put the localized verb, the "to" preposition, and the "on <chain>" preposition directly in the text. English example: "send {amount} {symbol} to {to} on {chain}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to} tr\xEAn {chain}". Japanese example: "{chain} \u3067 {to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to}/{chain} too \u2014 the tool removes any whose value is unknown.`,required:!0}])}async buildParameters(r,n){let i=this.normaliseAddress(r.contract_address)!=null,o=typeof r.token_symbol=="string"&&r.token_symbol.trim().length>0;if(!i&&!o&&this.moralis){let d=this.requireChain(r,n)??void 0,f=n?.walletAddress;if(f){let m=await this.moralis.getWalletTokenBalances({address:f,chain:d,excludeSpam:!1,excludeUnverifiedContracts:!1}),y=(m.success?m.data?.result??[]:[]).filter(C=>C.symbol&&(C.native_token||C.token_address)).sort((C,N)=>(N.usd_value??0)-(C.usd_value??0)).slice(0,8);if(y.length===0)return{error:"no_token_holdings",_instructions:"The wallet does not hold any sendable tokens on this chain. Tell the user they have nothing to send and suggest they top up first. Do NOT open the form."};let _=r.to_address!=null?this.normaliseAddress(r.to_address):null,b=this.normaliseAmount(r.amount),w=typeof r.send_prompt_template=="string"?r.send_prompt_template:"",T=d?ve(d):null;return{actionButtons:y.map(C=>{let N=C.symbol,M=C.balance_formatted?this.cleanAmountString(C.balance_formatted):"",A=C.name?C.name:"",U=C.usd_value?`($${C.usd_value.toFixed(2)})`:"";return{label:`${A}:${M} ${N} ${U}`.trim(),prompt:this.buildSendPrompt(w,N,b,_,T)}}),_instructions:"Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n g\u1EEDi token.' / 'You want to send a token.'), then ask them to choose which token from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n g\u1EEDi.' / 'Please choose the token you want to send.'). Do NOT list the tokens in text \u2014 the options already show them. Do NOT mention tool names, UI, or forms."}}}let a=this.requireChain(r,n)??void 0,s=n?.walletAddress??void 0,l=await this.findOwnedTokenForSend(r,a,s);if(l&&"error"in l)return l;let c=l?.token,u={};if(c?.address&&(u.contract_address=c.address),c?.symbol&&(u.token_symbol=c.symbol),c?.decimals!==void 0&&(u.decimals=String(c.decimals)),l?.spendable!==void 0&&(u.spendable=l.spendable),r.to_address!=null){let d=this.normaliseAddress(r.to_address);d?u.to_address=d:typeof r.to_address=="string"&&r.to_address.trim()&&(u.to_address=r.to_address.trim())}if(c?.address){let d=await this.resolveAmountInput({rawAmount:r.amount,tokenAddress:c.address,symbol:c.symbol,chain:a,walletAddress:s});if(d&&"error"in d)return d;d&&(u.amount=d.amount)}else{let d=this.normaliseAmount(r.amount);d&&(u.amount=d)}return u}async findOwnedTokenForSend(r,n,i){let o=this.normaliseAddress(r.contract_address),a=typeof r.token_symbol=="string"&&r.token_symbol.trim()?r.token_symbol.trim():void 0,s=o??a;if(!this.moralis||!i||!s){let g=await this.resolveTokenRef({contractArg:r.contract_address,symbolArg:r.token_symbol,decimalsArg:r.decimals,chain:n,walletAddress:i});return"error"in g?{error:"token_not_found",symbol:g.key,_instructions:`Could not resolve token "${g.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:g.token}}let l=s.toLowerCase(),c=o!=null,u=await this.moralis.getWalletTokenBalances({address:i,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),f=(u.success?u.data?.result??[]:[]).find(g=>c?(g.token_address??"").toLowerCase()===l:(g.symbol??"").toLowerCase()===l);if(f&&f.balance&&!/^0*$/.test(f.balance.trim())){let g=this.parseDecimals(r.decimals);return{token:{address:f.token_address,symbol:f.symbol??a,name:f.name,decimals:g??(typeof f.decimals=="number"?f.decimals:void 0)},spendable:f.balance_formatted?this.cleanAmountString(f.balance_formatted):void 0}}let m=f?.symbol??a??s;return{error:"no_balance",symbol:m,_instructions:`The user does not hold any ${m} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${m} to send, and suggest they top up or pick another token. Do NOT open a form. Do NOT mention tool names, UI, or forms.`}}buildSendPrompt(r,n,i,o,a){let l=(r&&r.includes("{symbol}")?r:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,n).replace(/\{amount\}/g,i??"");return l=this.fillOrDropPhrase(l,"{to}",o),l=this.fillOrDropPhrase(l,"{chain}",a),l.replace(/\s+/g," ").trim()}fillOrDropPhrase(r,n,i){if(i)return r.split(n).join(i);let o=n.replace(/[{}]/g,"\\$&");return r.replace(new RegExp(`\\s*\\S+\\s*${o}`,"g"),"").replace(new RegExp(`${o}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(o,"g"),"")}};p();var Up=class extends Mi{constructor(r){super(r);h(this,"name","open-approve-token-form");h(this,"actionType","approve_token");h(this,"component","ApproveTokenForm");h(this,"userInputFields",[{key:"spender_address",label:"the spender address to approve"}]);h(this,"description",'Open the APPROVE TOKEN form so the user can grant a spender allowance on an ERC-20 token. Use when the user says "approve USDC for Uniswap", "c\u1EA5p quy\u1EC1n 100 USDT cho 0x\u2026", "revoke approval". Pass `contract_address` when you have it; otherwise pass `token_symbol` (e.g. "USDC") and the tool auto-resolves the contract. Always pass `spender_address` (the contract being approved). Pass `amount` for a specific allowance; omit for unlimited (max uint256). For approving 0 to revoke, pass amount="0".');h(this,"parameters",[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). Required when contract_address is not given. Used to auto-resolve the contract.',required:!1},{name:"decimals",type:"number",description:"Token decimals.",required:!1},{name:"spender_address",type:"string",description:"EVM address of the spender contract being approved (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Human-readable allowance amount. Omit for UNLIMITED (max uint256). Pass "0" to revoke.',required:!1}])}async buildParameters(r,n){let i=this.requireChain(r,n)??void 0,o=await this.resolveTokenRef({contractArg:r.contract_address,symbolArg:r.token_symbol,decimalsArg:r.decimals,chain:i,walletAddress:n?.walletAddress??void 0});if("error"in o)return{error:"token_not_found",symbol:o.key,_instructions:`Could not resolve token "${o.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let a=o.token,s=this.normaliseAddress(r.spender_address),l={};if(a?.address&&(l.contract_address=a.address),s&&(l.spender_address=s),a?.symbol&&(l.token_symbol=a.symbol),a?.decimals!==void 0&&(l.decimals=String(a.decimals)),typeof r.amount=="string"&&r.amount.trim()){let c=r.amount.trim(),u=parseFloat(c);Number.isFinite(u)&&u>=0&&(l.amount=c)}else typeof r.amount=="number"&&Number.isFinite(r.amount)&&r.amount>=0&&(l.amount=String(r.amount));return l}};p();var qp=class extends se{constructor(r,n){super();h(this,"name","open-buy-token-form");h(this,"kind","action");h(this,"category","wallet-action");h(this,"moralis");h(this,"pantograph");h(this,"debug");h(this,"description",'Open the BUY TOKEN flow for ANY buy/purchase intent. Handles both cases: (a) the user NAMED a token \u2014 "buy PEPE", "mua DOGE", "buy 100 USDC with ETH": pass `token_symbol` (the destination); if you also know the pay token, fill `pay_with_symbol` (or `pay_with_address`), else leave pay_with_* blank and the tool returns a wallet picker. (b) the user did NOT name a token \u2014 "buy a trending token", "mua token trending", "buy something pumping", "buy hot tokens", "mua token t\u0103ng m\u1EA1nh": leave `token_symbol` blank and the tool returns buttons of the chain\'s current trending tokens so the user picks one. Amount: `buy_amount` = destination to RECEIVE; `pay_with_amount` = payment to SPEND. Never both.');h(this,"parameters",[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"token_symbol",type:"string",description:'Symbol of the token the user wants to BUY (e.g. "PEPE"). Leave EMPTY when the user did not name a token (e.g. "buy a trending token") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"contract_address",type:"string",description:`Destination token address (0x\u2026), or "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from token_symbol.`,required:!1},{name:"buy_amount",type:"string",description:`Quantity of the DESTINATION token (the one being bought) the user wants to RECEIVE. Set this when the amount sits next to the token being bought: "buy 5 PEPE", "mua 5 PEPE", "buy 0.02 PCM with USDC" \u2192 buy_amount = the number next to PEPE/PCM. May also be a USD value when the user sizes the buy in dollars ("buy $5 of PEPE" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$" to a token quantity). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with pay_with_amount \u2014 set at most ONE of the two.`,required:!1},{name:"pay_with_symbol",type:"string",description:'Symbol of the payment token (e.g. "USDC", "ETH"). Set ONLY when the user actually named a token to pay with. Leave EMPTY when they did not \u2014 do NOT default to the native coin / ETH; the tool then returns a picker of the tokens the wallet holds.',required:!1},{name:"pay_with_address",type:"string",description:`Address of the payment token (0x\u2026), OR "native" for the chain's native coin. Set ONLY when the user named the payment token. Leave EMPTY when they did not \u2014 do NOT invent an address or default to native.`,required:!1},{name:"pay_with_amount",type:"string",description:'Quantity of the PAYMENT token (the one being spent) the user wants to SPEND. Set this when the amount sits next to the payment token: "buy PEPE with 10 USDC", "mua PEPE b\u1EB1ng 10 USDC", "spend 0.5 ETH on DOGE" \u2192 pay_with_amount = the number next to USDC/ETH. May also be a PERCENT of the pay-token balance ("buy USDC with 50% USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("buy USDC with 5$ USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set pay_with_symbol to the payment token ("ETH" in "buy USDC with max ETH"). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with buy_amount \u2014 set at most ONE of the two.',required:!1},{name:"limit",type:"number",description:"Only used when no token is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the trending-token picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_with_prompt_template",type:"string",description:`A short "buy X with Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the pay-token picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{token}" = token being bought, "{pay}" = payment token, "{buy_amount}" = quantity of the BOUGHT token (place it next to {token}), "{pay_amount}" = quantity of the PAYMENT token (place it next to {pay}). Put the localized verb and the "with" preposition directly in the text. English example: "buy {buy_amount} {token} with {pay_amount} {pay}". Vietnamese example: "mua {buy_amount} {token} b\u1EB1ng {pay_amount} {pay}". Japanese example: "{pay_amount} {pay} \u3067 {buy_amount} {token} \u8CFC\u5165". Always include {token} and {pay}. Include both {buy_amount} and {pay_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount).`,required:!0}]);r!==void 0&&(this.moralis=new lt(r),this.pantograph=new Pn({baseUrl:r.pantographUrl})),this.debug=n?.debug??!1}dbg(r,n){this.debug&&(n===void 0?console.log(`[BuyTokenTool] ${r}`):console.log(`[BuyTokenTool] ${r}`,JSON.stringify(n)))}async execute(r,n){let i=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let a=await this.run(r,n),s={toolName:this.name,callId:i,success:!0,data:a,duration:Date.now()-o};return a&&typeof a=="object"&&a.ui&&(s.ui=a.ui),a&&Array.isArray(a.actionButtons)&&a.actionButtons.length>0&&(s.actionButtons=a.actionButtons),s}catch(a){return{toolName:this.name,callId:i,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}async run(r,n){if(!n?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let o=Ud(r.chain,n);if(o)return{error:"wrong_chain",_instructions:`The user asked to buy on ${o.requestedLabel}, but their wallet is connected to ${o.connectedLabel}. Tell them, in their language, that to buy on ${o.requestedLabel} they must first switch their wallet's network to ${o.requestedLabel}, or they can buy on ${o.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(r,n)){let s=typeof n?.query=="string"?n.query:void 0;return qd("buy",s)}return this.buildResult(r,n)}async buildResult(r,n){this.correctAmountSide(r,n),this.dropUnmentionedPayToken(r,n),this.dropInventedAmounts(r,n);let i=typeof r.token_symbol=="string"?r.token_symbol.trim():"",o=typeof r.contract_address=="string"?r.contract_address.trim():"",a=this.requireChain(r,n)??void 0,s=n?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:r,chain:a,walletAddress:s,hasMoralis:!!this.moralis}),!i&&!o)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(r,n);let l=await this.resolveSide(r.contract_address,i,a,s,"dest"),c=l.address,u=l.symbol??i,d=l.decimals,f=await this.resolveSide(r.pay_with_address,r.pay_with_symbol,a,s,"pay"),m=f.address,g=f.symbol,y=f.decimals,_=await this.resolveBuyAmountSpec(r.buy_amount,c,a,u),b=m?await this.resolvePayAmountSpec(r.pay_with_amount,m,a,s,g,y??(m==="native"?18:void 0)):this.normaliseAmount(r.pay_with_amount),w=Ho(r.pay_with_amount),T=!!w&&w.kind!=="token",E=null;if(this.dbg("resolved sides",{dest:{destContract:c,destSymbol:u,destDecimals:d},pay:{payAddr:m,paySymbol:g,payDecimals:y},buyAmount:_,payAmount:b}),!c)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${u||o}" to buy on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!m&&this.moralis&&n?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:r,userContext:n,destSymbol:u,destContract:c,buyAmount:_,payAmount:b});if(!m)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${u}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(_&&!b){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:_,destSymbol:u,paySymbol:g});let C=await this.derivePayAmountFromBuy({chain:a,buyAmount:_,destContract:c,destSymbol:u,payAddr:m,paySymbol:g});if(!C)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${g??"of the payment token"} equals ${_} ${u} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${g??"of the payment token"} they want to spend instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};b=C,E=_,T=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:b,derivedFromBuy:E})}if(this.moralis&&n?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:m,paySymbol:g,payAmount:b});let C=await this.checkPayBalance({args:r,userContext:n,chain:a,destSymbol:u,destContract:c,payAddr:m,paySymbol:g,payAmount:b,buyAmount:_,derivedFromBuy:E,amountSizedToBalance:T});if(C)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:C.error,hasButtons:Array.isArray(C.actionButtons)}),C;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!_&&!b&&this.moralis&&n?.walletAddress){this.dbg("Branch 1.5: building amount picker");let C=await this.buildAmountPicker({userContext:n,chain:a,destSymbol:u,payAddr:m,paySymbol:g,buyWithTemplate:typeof r.buy_with_prompt_template=="string"?r.buy_with_prompt_template:""});if(C)return this.dbg("\u2192 Branch 1.5: amount picker returned"),C;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(b&&(y!==void 0||m==="native")){this.dbg("Branch 1.75: building confirm tx");let C=await this.buildConfirmTx({userContext:n,chain:a,destContract:c,destSymbol:u,destDecimals:d,payAddr:m,paySymbol:g,payDecimals:y,payAmount:b});return C&&"ui"in C?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),C):C&&"quoteError"in C?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:C.quoteError}),{error:"quote_failed",quoteError:C.quoteError,_instructions:`Could not quote buying ${u} with ${g??"the selected token"}. The swap provider reported: "${C.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to buy ${u} with ${g??"the selected token"} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs pay amount"),{error:"needs_pay_amount",_instructions:`Ask the user, in their language, how much ${g??"of the payment token"} they want to spend to buy ${u}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(r){if(typeof r!="string")return null;let n=r.trim();return Bt(n)?n:null}normaliseAmount(r){if(typeof r=="number"&&Number.isFinite(r)&&r>0)return String(r);if(typeof r!="string")return null;let n=r.trim();if(!n)return null;let i=n.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!i)return null;let o=parseFloat(i[1]);return Number.isFinite(o)&&o>0?i[1]:null}correctAmountSide(r,n){let i=typeof n?.query=="string"?n.query:"",o=typeof r.token_symbol=="string"?r.token_symbol.trim():"",a=typeof r.pay_with_symbol=="string"?r.pay_with_symbol.trim():"";if(!i||!o||!a)return;let s=typeof r.buy_amount=="string"?r.buy_amount.trim():"",l=typeof r.pay_with_amount=="string"?r.pay_with_amount.trim():"",c=s.length>0,u=l.length>0;if(c===u)return;let d=c?s:l,f=d.match(/[0-9]*\.?[0-9]+/)?.[0];if(!f)return;let m=this.nearestSymbolSide(i,f,o,a);m&&(m==="pay"&&c?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:d,buySym:o,paySym:a}),r.pay_with_amount=d,r.buy_amount=""):m==="buy"&&u&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:d,buySym:o,paySym:a}),r.buy_amount=d,r.pay_with_amount=""))}dropUnmentionedPayToken(r,n){let i=typeof n?.query=="string"?n.query:"";if(!i)return;let o=typeof r.token_symbol=="string"?r.token_symbol.trim():"";if(!o)return;let a=typeof r.pay_with_symbol=="string"?r.pay_with_symbol.trim():"",s=typeof r.pay_with_address=="string"?r.pay_with_address.trim():"";if(!a&&!s)return;let l=i.toLowerCase(),c=a.toLowerCase(),u=s.toLowerCase(),d=c==="native"||u==="native",f=[];if(a&&c!=="native"&&f.push(c),u&&u!=="native"&&f.push(u),d){f.push("native");let g=this.requireChain(r,n)??void 0,y=g?Br(g)?.native.symbol:void 0;y&&f.push(y.toLowerCase())}f.some(g=>Bt(g)?l.includes(g):this.indexOfToken(l,g)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:a,payAddr:s,buySym:o}),r.pay_with_symbol="",r.pay_with_address="")}dropInventedAmounts(r,n){let i=typeof n?.query=="string"?n.query:"";if(!i)return;let o=(i.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),a=s=>{let l=typeof r[s]=="string"?r[s].trim():"";if(!l)return;let c=l.match(/[0-9]*\.?[0-9]+/)?.[0];if(c===void 0)return;let u=parseFloat(c);Number.isFinite(u)&&(o.some(d=>d===u)||(this.dbg(`dropInventedAmounts: clearing invented ${s}`,{val:l}),r[s]=""))};a("buy_amount"),a("pay_with_amount")}nearestSymbolSide(r,n,i,o){let a=r.toLowerCase(),s=a.indexOf(n.toLowerCase()),l=this.indexOfToken(a,i.toLowerCase()),c=this.indexOfToken(a,o.toLowerCase());if(s<0||l<0||c<0)return null;let u=(m,g)=>Math.max(0,m-(s+n.length),s-(m+g)),d=u(l,i.length),f=u(c,o.length);return f===d?null:f<d?"pay":"buy"}indexOfToken(r,n){if(!n)return-1;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=r.match(new RegExp(`(?:^|[^a-z0-9])(${i})(?:[^a-z0-9]|$)`));return o&&o.index!==void 0?o.index+o[0].indexOf(o[1]):-1}requireChain(r,n){let i=typeof r.chain=="string"&&r.chain.trim()?r.chain.trim():null;return i||(typeof n?.chain=="string"&&n.chain.trim()?n.chain.trim():null)}async resolveContractAddress(r,n,i){if(!this.moralis||!r)return;let o=r.trim().toLowerCase(),a=Bt(r.trim()),s=c=>a?(c.token_address??"").toLowerCase()===o:(c.symbol??"").toLowerCase()===o;if(i){let c=await this.moralis.getWalletTokenBalances({address:i,chain:n});if(c.success&&c.data?.result?.length){let u=c.data.result.find(s);if(u)return{address:u.token_address,symbol:u.symbol,name:u.name,decimals:typeof u.decimals=="number"?u.decimals:void 0}}}let l=await this.moralis.searchTokensByKey({key:r,chain:n});if(l.success&&l.data?.length){let u=l.data.find(s)??l.data[0];if(u?.token_address)return{address:u.token_address,symbol:u.symbol,name:u.name,decimals:typeof u.decimals=="number"?u.decimals:void 0}}}async resolveSide(r,n,i,o,a="side"){let s=typeof r=="string"?r.trim():"",l=typeof n=="string"?n.trim():"";if(s.toLowerCase()==="native"||l.toLowerCase()==="native")return{address:"native",symbol:l||void 0};let c=this.normaliseAddress(r),u=l||void 0,d=g=>g.toLowerCase()===zt?"native":g,f=c??u??(s||void 0);if(!f)return this.dbg(`resolveSide:${a}`,{refStr:s,symbolStr:l,chain:i,resolved:"none"}),{address:null,symbol:u};let m=await this.resolveContractAddress(f,i,o);return this.dbg(`resolveSide:${a}`,{refStr:s,symbolStr:l,chain:i,key:f,lookup:m}),m?{address:d(m.address),symbol:u??m.symbol,decimals:m.decimals}:c?{address:d(c),symbol:u}:{address:null,symbol:u}}async buildConfirmTx(r){let{userContext:n,chain:i,destContract:o,destSymbol:a,destDecimals:s,payAddr:l,paySymbol:c,payDecimals:u,payAmount:d}=r,f=n?.walletAddress;if(!f||!i||!o)return null;let m=Br(i),g=Number.parseInt(i,16);if(!m||!Number.isFinite(g))return null;let y=l==="native",_=y?m.native.decimals??18:u;if(_===void 0)return null;let b=this.toRawAmount(d,_);if(!b)return null;let w=y?zt:l,T=o==="native"?zt:o,E;try{E=await(await Zo.getServiceByProvider("debridge")).getQuote({srcChainId:g,srcTokenAddress:w,srcTokenAmount:b,dstChainId:g,dstTokenAddress:T,recipientAddress:f,senderAddress:f,slippage:"auto",isCrossChain:!1})}catch(L){return{quoteError:L instanceof Error?L.message:String(L)}}if(!E.success)return this.dbg("buildConfirmTx: quote failed",{error:E.error,errorMessage:E.errorMessage}),{quoteError:this.extractQuoteError(E)};if(!E.tx)return{quoteError:"No route available for this swap."};let C=E.tx;if(!C.to||typeof C.data!="string")return null;let N={chainId:i,to:C.to,data:C.data,value:C.value??"0",from:f},M=this.extractOutRaw(E),A=M&&s!==void 0?this.trimAmount(Number(M)/10**s):void 0,U;y||(U=await this.buildApproveTx({chain:i,walletAddress:f,payAddr:l,payDec:_,rawAmount:b,quote:E}));let x={component:"BuyTokenConfirmTx",props:{chain:{hexId:i,name:m.name},payToken:{address:y?"native":l,symbol:c,decimals:_,amount:d,rawAmount:b},buyToken:{address:o,symbol:a,decimals:s,amount:A,rawAmount:M},estimatedOut:A,estimatedOutRaw:M,provider:E.provider,swapTx:N,approveTx:U}},O=A?` They will receive about ${A} ${a}.`:"";return{ui:x,_instructions:`The purchase of ${a} with ${d} ${c??"the selected token"} is ready for the user to confirm.${O} Briefly tell the user, in their language, the amount they are spending and the estimated amount they will receive, and ask them to review and confirm to complete the purchase. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (buying) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async derivePayAmountFromBuy(r){let{chain:n,buyAmount:i,destContract:o,payAddr:a}=r,[s,l]=await Promise.all([this.getUsdPrice(o,n),this.getUsdPrice(a,n)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:s,payPrice:l}),!s||!l)return null;let c=Number(i);if(!Number.isFinite(c)||c<=0)return null;let u=1.02,d=c*s/l;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*u)}async getUsdPrice(r,n){if(!this.moralis)return null;let i=r==="native"?zt:r,o=await this.moralis.getTokenMetadata({address:i,chain:n}),a=o.success?o.data?.usd_price:void 0;return typeof a=="number"&&Number.isFinite(a)&&a>0?a:null}async resolvePayAmountSpec(r,n,i,o,a,s){let l=Ho(r);if(!l)return null;let c=d=>s===void 0?d:Od(d,s);if(l.kind==="token")return c(Id(r)??this.toPlainDecimal(l.value));if(l.kind==="percent"){if(!o)return null;let d=await this.readPayBalance(o,n,i);if(this.dbg("resolvePayAmountSpec: percent",{percent:l.percent,paySymbol:a,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let f=d.decimals??s??18;return l.percent>=100?this.cleanAmountString(d.balanceFormatted):Rd(d.balanceFormatted,BigInt(Math.round(l.percent*1e6)),100000000n,f)}let u=await this.getUsdPrice(n,i);return this.dbg("resolvePayAmountSpec: usd",{usd:l.usd,paySymbol:a,price:u}),u?c(this.trimAmount(l.usd/u)):null}async resolveBuyAmountSpec(r,n,i,o){let a=Ho(r);if(!a)return null;if(a.kind==="token")return Id(r)??this.toPlainDecimal(a.value);if(a.kind==="percent"||!n)return null;let s=await this.getUsdPrice(n,i);return this.dbg("resolveBuyAmountSpec: usd",{usd:a.usd,destSymbol:o,price:s}),s?this.trimAmount(a.usd/s):null}async buildApproveTx(r){let{chain:n,walletAddress:i,payAddr:o,payDec:a,rawAmount:s,quote:l}=r;try{let u=await(await Zo.getServiceByProvider("debridge")).checkApproval({chain:n,userAddress:i,tokenAddress:o,amount:s,tokenDecimals:a,quoteData:l});if(!u.isNeeded)return;let d=u.approvalData??{};if(d.to&&typeof d.data=="string")return{chainId:n,to:d.to,data:d.data,value:d.value??"0",from:i};let f=u.contractAddress;if(!f)return;let m=Ad({abi:Nv,functionName:"approve",args:[f,BigInt(s)]});return{chainId:n,to:o,data:m,value:"0",from:i}}catch{return}}toRawAmount(r,n){let i=r.trim();if(!/^\d*\.?\d+$/.test(i))return null;let[o,a=""]=i.split("."),s=a.slice(0,n).padEnd(n,"0");try{let l=BigInt(o||"0")*10n**BigInt(n)+BigInt(s||"0");return l<=0n?null:l.toString()}catch{return null}}extractQuoteError(r){if(r.errorMessage&&r.errorMessage.trim())return r.errorMessage.trim();let n=o=>{if(typeof o=="string"&&o.trim())return o.trim();if(o&&typeof o=="object"){let a=o;for(let s of[a.message,a.errorMessage,a.error])if(typeof s=="string"&&s.trim())return s.trim()}},i=r.raw??{};return n(r.error)??n(i.errorMessage)??n(i.error)??"The swap could not be quoted right now."}extractOutRaw(r){let n=r.raw??{},i=n.tokenOut?.amount??n.tokenOut?.minAmount??n.details?.currencyOut?.amount??n.details?.currencyOut?.minimumAmount??n.estimation?.dstChainTokenOut?.recommendedAmount??n.estimation?.dstChainTokenOut?.amount;return i&&/^\d+$/.test(i)?i:void 0}async buildPayWithPicker(r){let{args:n,userContext:i,destSymbol:o,destContract:a}=r,s=this.requireChain(n,i)??void 0,l=this.moralis,c=i.walletAddress,u=await l.getWalletTokenBalances({address:c,chain:s,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=u.success?u.data?.result??[]:[],f=a?.toLowerCase(),m=o.trim().toLowerCase(),g=d.filter(T=>!T.symbol||m&&T.symbol.toLowerCase()===m?!1:T.native_token?f!=="native":!(!T.token_address||f&&T.token_address.toLowerCase()===f)).sort((T,E)=>(E.usd_value??0)-(T.usd_value??0)).slice(0,8);if(g.length===0)return{error:"no_pay_token_holdings",_instructions:"The wallet has no tokens that can pay for this purchase on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let y=r.buyAmount??this.normaliseAmount(n.buy_amount),_=r.payAmount??this.normaliseAmount(n.pay_with_amount),b=typeof n.buy_with_prompt_template=="string"?n.buy_with_prompt_template:"";return{actionButtons:g.map(T=>{let E=T.symbol,C=T.name?.trim()||E,N=T.balance_formatted?`${this.cleanAmountString(T.balance_formatted)} `:"",M=typeof T.usd_value=="number"&&T.usd_value>0?` ($${T.usd_value.toFixed(2)})`:"",A=`${C}: ${N}${E}${M}`,U=y?this.buildBuyWithPrompt(b,o,E,y,null):this.buildBuyWithPrompt(b,o,E,null,_);return{label:A,prompt:U}}),_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n mua ${o}.' / 'You want to buy ${o}.'), then ask them to choose which token they want to spend to buy ${o} from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua.' / 'Please choose the token to spend.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async checkPayBalance(r){let{args:n,userContext:i,chain:o,destSymbol:a,destContract:s,payAddr:l,payAmount:c,buyAmount:u,derivedFromBuy:d}=r,f=i.walletAddress,m=await this.readPayBalance(f,l,o),g=r.paySymbol??m?.symbol??"the selected token";if(!m){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:g});let T=await this.buildPayWithPicker({args:n,userContext:i,destSymbol:a,destContract:s,buyAmount:u,payAmount:c});return"actionButtons"in T?{error:"no_pay_balance",actionButtons:T.actionButtons,_instructions:`The user wanted to spend ${g} to buy ${a}, but their wallet holds no ${g} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${g} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${g} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to pay with (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua ${a} t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to pay with from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:T}if(!c||r.amountSizedToBalance)return null;let y=m.decimals!==void 0?Od(c,m.decimals):c;if(pv(y,m.balanceFormatted)<=0)return null;let _=this.cleanAmountString(m.balanceFormatted),b=this.percentSpendButtons({balanceFormatted:m.balanceFormatted,balanceNum:m.balanceNum,decimals:m.decimals,paySymbol:g,destSymbol:a,buyWithTemplate:typeof n.buy_with_prompt_template=="string"?n.buy_with_prompt_template:""}),w=d?`Buying ${d} ${a} needs about ${c} ${g}, but they only have ${_} ${g} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them that buying ${d} ${a} would cost about ${c} ${g}, which is more than their balance of ${_} ${g}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${c} ${g} to buy ${a}, but they only have ${_} ${g} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${c} ${g} exceeds their balance of ${_} ${g}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:b,_instructions:w+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readPayBalance(r,n,i){if(!this.moralis)return null;let o=await this.moralis.getWalletTokenBalances({address:r,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1}),a=o.success?o.data?.result??[]:[];this.dbg("readPayBalance",{payAddr:n,chain:i,ok:o.success,count:a.length,held:a.map(u=>({sym:u.symbol,addr:u.token_address,bal:u.balance_formatted}))});let s=n.toLowerCase(),l=a.find(u=>s==="native"?u.native_token===!0:u.token_address?.toLowerCase()===s);if(!l?.balance_formatted)return this.dbg("readPayBalance: pay token NOT held \u2192 null",{payAddr:n}),null;let c=Number(l.balance_formatted);if(!Number.isFinite(c)||c<=0)return this.dbg("readPayBalance: zero/invalid balance \u2192 null",{payAddr:n,balance:l.balance_formatted}),null;if(s==="native"&&i){let u=await Np(i,"swap"),d=$p(c,u,i);if(this.dbg("readPayBalance: native spendable",{balanceNum:c,spendable:d}),d<=0)return this.dbg("readPayBalance: native spendable \u2264 0 \u2192 null",{balanceNum:c}),null;let f=this.trimAmount(d),m=typeof l.decimals=="number"?l.decimals:18;return{balanceFormatted:f,balanceNum:d,symbol:l.symbol,decimals:m}}return this.dbg("readPayBalance: held",{payAddr:n,balance:l.balance_formatted,symbol:l.symbol}),{balanceFormatted:l.balance_formatted,balanceNum:c,symbol:l.symbol,decimals:typeof l.decimals=="number"?l.decimals:void 0}}percentSpendButtons(r){let{balanceFormatted:n,decimals:i,paySymbol:o,destSymbol:a,buyWithTemplate:s}=r,l=i??18;return[25,50,75,100].map(u=>{let d=Rd(this.cleanAmountString(n),BigInt(u),100n,l);return{label:`${u}%`,prompt:this.buildBuyWithPrompt(s,a,o,null,d)}})}async buildAmountPicker(r){let{userContext:n,chain:i,destSymbol:o,payAddr:a,buyWithTemplate:s}=r,l=n.walletAddress,c=await this.readPayBalance(l,a,i),u=r.paySymbol??c?.symbol;if(!c||!u)return null;let d=this.percentSpendButtons({balanceFormatted:c.balanceFormatted,balanceNum:c.balanceNum,decimals:c.decimals,paySymbol:u,destSymbol:o,buyWithTemplate:s}),f=this.cleanAmountString(c.balanceFormatted);return{actionButtons:d,_instructions:`The user's spendable balance is ${f} ${u}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${u} balance (e.g., 'B\u1EA1n mu\u1ED1n mua ${o} b\u1EB1ng ${u}, hi\u1EC7n c\xF3 ${f} ${u} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to buy ${o} with ${u}; you have ${f} ${u} available.'), then ask how much they want to spend and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(r){return Number.isFinite(r)?this.toPlainDecimal(parseFloat(r.toPrecision(8))):"0"}toPlainDecimal(r){let n=String(r);if(!/e/i.test(n))return n;let i=r<0,[o,a]=Math.abs(r).toString().split("e"),s=Number(a),[l,c=""]=o.split("."),u=l+c,d;if(s>=0){let f=l.length+s;d=f>=u.length?u.padEnd(f,"0"):`${u.slice(0,f)}.${u.slice(f)}`}else d=`0.${"0".repeat(-s-l.length)}${u}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),i?`-${d}`:d}cleanAmountString(r){if(!/e/i.test(r))return r;let n=Number(r);return Number.isFinite(n)?this.toPlainDecimal(n):r}buildBuyPrompt(r,n){return(r&&r.includes("{token}")?r:"buy {token}").replace(/\{token\}/g,n).replace(/\s+/g," ").trim()}buildBuyWithPrompt(r,n,i,o,a){return(r&&r.includes("{token}")&&r.includes("{pay}")?r:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,n).replace(/\{pay\}/g,i).replace(/\{buy_amount\}/g,o??"").replace(/\{pay_amount\}/g,a??"").replace(/\s+/g," ").trim()}async buildTrendingPicker(r,n){if(!this.pantograph)return{error:"trending_unavailable",_instructions:"Trending tokens are unavailable in this build (service not configured). Tell the user briefly and ask them to name a token to buy."};let i=this.requireChain(r,n)??void 0,o=typeof r.limit=="number"&&Number.isFinite(r.limit)?Math.floor(r.limit):6,a=Math.max(1,Math.min(10,o)),s=await this.pantograph.getTrendingTokens({chain:i,limit:a}),l=s.success?s.data??[]:[];if(l.length===0)return{error:"no_trending_tokens",_instructions:"No trending tokens are available for this chain right now. Tell the user briefly and suggest they name a token directly."};let c=l.filter(g=>g.symbol),u=typeof r.buy_prompt_template=="string"?r.buy_prompt_template:"",d=c.map(g=>{let y=g.symbol;return{label:y,prompt:this.buildBuyPrompt(u,y)}}),m=c.map((g,y)=>{let _=g.name?.trim()||g.symbol,b=g.symbol,w=typeof g.usdPrice=="number"&&g.usdPrice>0?`$${this.formatPrice(g.usdPrice)}`:"N/A",T=g.pricePercentChange?.["24h"],E=typeof T=="number"&&Number.isFinite(T)?` (${T>0?"+":T<0?"-":""}${this.formatPercent(Math.abs(T))}%)`:"";return`${y+1}. ${_} (${b}) \u2014 ${w}${E}`}).join(`
627
627
  `)+`
628
628
 
629
629
  Is there any token you want to buy?`;return{actionButtons:d,_instructions:`The trending tokens are on ${i?ve(i):"the connected chain"}. Reply in the user's language using the pattern 'state intent \u2192 ask to choose'. Start with a one-line header that states the user's intent (e.g., 'B\u1EA1n mu\u1ED1n mua token \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to buy a token \u2014 here are the tokens currently trending upwards on <chain name>:'), then output EXACTLY the following list, preserving the line breaks, ordering, prices, and percentages verbatim (translate only the wording, never the numbers). The list already ends with a 'choose' prompt. Do NOT add or remove tokens, and do NOT mention tool names, UI, or forms: