keyring-agent-core 0.3.6 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +719 -19
- package/dist/index.js +144 -144
- package/dist/index.native.js +262 -262
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);super(s,t.cause!==void 0?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n,this.metaMessages=o,t.name&&(this.name=t.name)}walk(e){return nc(this,e)}};function nc(r,e){if(e?.(r))return r;let t=r&&typeof r=="object"?r.cause:void 0;return t!=null?nc(t,e):e?null:r}var Nt=class extends M{name="AbiParameterTypeError";constructor(e){super(`Type "${e}" is not a valid ABI type.`,{metaMessages:["Supported: address, bool, string, bytes, bytesN, (u)intN, tuple, and arrays of those."]})}},Ws=class extends M{name="AbiEncodingLengthMismatchError";constructor({expectedLength:e,givenLength:t}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${e}`,`Given length (values): ${t}`]})}},Ys=class extends M{name="AbiEncodingArrayLengthMismatchError";constructor({expectedLength:e,givenLength:t,type:n}){super(`ABI encoding array length mismatch for type ${n}.`,{metaMessages:[`Expected length: ${e}`,`Given length: ${t}`]})}},Ye=class extends M{name="InvalidAbiValueError";constructor({type:e,value:t,reason:n}){super(`Invalid value for ABI type "${e}".`,{metaMessages:[`Value: ${rc(t)}`,`Reason: ${n}`]})}},Gs=class extends M{name="IntegerOutOfRangeError";constructor({type:e,value:t,min:n,max:o}){super(`Number "${t}" is not in safe ${e} range.`,{metaMessages:[`Range: ${n} \u2026 ${o}`]})}},qn=class extends M{name="InvalidAddressError";constructor(e){super(`Address "${rc(e)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function rc(r){if(typeof r=="bigint")return r.toString();if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}}var Ks=class extends M{name="AbiEncodingBytesSizeMismatchError";constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" does not match expected size of bytes${e}.`)}},Ut=class extends M{name="AbiDecodingZeroDataError";constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{metaMessages:["The contract returned no data. Usually this means:","- the address is not a contract on this chain,","- the function does not exist on it, or","- the call was made before the contract was deployed."]})}},js=class extends M{name="AbiDecodingDataSizeTooSmallError";data;params;size;constructor({data:e,params:t,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${t.map(o=>o.type).join(", ")})`,`Data: ${e} (${n} bytes)`]}),this.data=e,this.params=t,this.size=n}},$n=class extends M{name="AbiDecodingOutOfBoundsError";constructor({position:e,length:t}){super(`Position ${e} is out of bounds (${t} bytes).`,{metaMessages:["The return data is truncated or not ABI-encoded."]})}},zs=class extends M{name="AbiItemNotFoundError";constructor({name:e,type:t="function"}){super(`${t[0].toUpperCase()}${t.slice(1)} "${e}" not found on ABI.`,{metaMessages:["Make sure you are using the correct ABI and that the item exists on it."]})}},It=class extends M{name="InvalidAbiSignatureError";constructor(e,t){super(`Invalid ABI signature: "${e}".`,{metaMessages:t?[t]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']})}};var dp=/^0x[0-9a-fA-F]*$/;function mn(r,{strict:e=!0}={}){return typeof r!="string"?!1:e?dp.test(r):r.startsWith("0x")}function rt(r){return r.startsWith("0x")||r.startsWith("0X")?r.slice(2):r}function Go(r){return typeof r=="string"?Math.ceil(rt(r).length/2):r.length}function hn(r,e,t){let n=rt(r),o=(e??0)*2,s=t===void 0?n.length:t*2;return`0x${n.slice(o,s)}`}function Xs(r){return`0x${r.map(rt).join("")}`}function gn(r){let e=new Uint8Array(r.reduce((n,o)=>n+o.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}function Lt(r){let e=rt(r),t=e.length%2?`0${e}`:e,n=new Uint8Array(t.length/2);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*2,o*2+2),16);return n}function kt(r){let e="";for(let t of r)e+=t.toString(16).padStart(2,"0");return`0x${e}`}function yi(r){return new TextEncoder().encode(r)}function bi(r){return new TextDecoder().decode(r)}function xe(r,e={}){let{size:t,signed:n}=e,o=BigInt(r);if(o<0n){if(!t)throw new Error("numberToHex: negative values require a `size`");o+=1n<<BigInt(t*8)}else if(n&&t){let a=(1n<<BigInt(t*8-1))-1n;if(o>a)throw new Error(`numberToHex: ${r} overflows int${t*8}`)}let s=o.toString(16);if(!t)return`0x${s}`;if(s.length>t*2)throw new Error(`numberToHex: ${r} overflows ${t} bytes`);return`0x${s.padStart(t*2,"0")}`}function wi(r,e=32){if(r.length>e)throw new Error(`padLeft: ${r.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(r,e-r.length),t}function ki(r,e=32){if(r.length>e)throw new Error(`padRight: ${r.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(r),t}function fn(r){let e=1n<<256n,t=(r%e+e)%e;return Lt(t.toString(16).padStart(64,"0"))}function Hn(r,{signed:e=!1}={}){let t=BigInt(kt(r));if(!e)return t;let n=BigInt(r.length*8);return t>=1n<<n-1n?t-(1n<<n):t}function Ge(r,{signed:e=!1}={}){return rt(r)?Hn(Lt(r),{signed:e}):0n}function Qs(r,e={}){return Number(Ge(r,e))}var oc=require("js-sha3");var pp=/^0x[0-9a-fA-F]{40}$/;function R(r){return typeof r=="string"&&pp.test(r)}function Vn(r){let e=rt(r).toLowerCase(),t=(0,oc.keccak_256)(e),n="";for(let o=0;o<e.length;o++)n+=parseInt(t[o],16)>=8?e[o].toUpperCase():e[o];return`0x${n}`}function vi(r){if(!R(r))throw new Error(`Address "${r}" is invalid.`);return Vn(r)}function Ti(r,e){return R(r)&&R(e)&&r.toLowerCase()===e.toLowerCase()}var Ai=require("js-sha3");function sc(r){return`0x${(0,Ai.keccak_256)(new TextEncoder().encode(r))}`}function Ot(r){let e=r.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Dt(r){return r.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function Ko(r){let e=Dt(r.type);return e==="tuple"||e.startsWith("tuple[")?`(${(r.components??[]).map(Ko).join(",")})${e.slice(5)}`:e}function Wn(r){return`${r.name??""}(${(r.inputs??[]).map(Ko).join(",")})`}function vt(r){let e=typeof r=="string"?r:Wn(r);return`0x${(0,Ai.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function Pi(r){let e=typeof r=="string"?r:Wn(r);return sc(e)}function ac(r,e){let t=Dt(e.type),n=Ot(t);if(n){let[o,s]=n;return!Array.isArray(r)||o!==null&&r.length!==o?!1:r.every(a=>ac(a,{...e,type:s}))}if(t==="tuple"){let o=e.components??[];return Array.isArray(r)?r.length===o.length:typeof r=="object"&&r!==null}return t==="address"?typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/.test(r):t==="bool"?typeof r=="boolean":t==="string"?typeof r=="string":t.startsWith("bytes")?typeof r=="string"||r instanceof Uint8Array:t.startsWith("uint")||t.startsWith("int")?typeof r=="number"||typeof r=="bigint"||typeof r=="string":!0}function Mt({abi:r,name:e,args:t,type:n}){let o=n??"function",s=r.filter(i=>(i.type??"function")===o);if(e.startsWith("0x")&&e.length===10)return s.find(i=>vt(i)===e.toLowerCase());if(e.includes("("))return s.find(i=>Wn(i)===e);let a=s.filter(i=>i.name===e);return a.length<=1||!t?a[0]:a.find(i=>{let l=i.inputs??[];return l.length===t.length&&l.every((c,u)=>ac(t[u],c))})??a[0]}function yn(r){let e=Mt(r);if(!e)throw new zs({name:r.name,type:r.type??"function"});return e}function ic(r){let e=new Uint8Array(Math.ceil(r.length/32)*32);return e.set(r),{dynamic:!0,encoded:gn([fn(BigInt(r.length)),e])}}function lc(r,e){let t=r.slice(e.length),n=t===""?256:Number(t);if(!Number.isInteger(n)||n<8||n>256||n%8!==0)throw new Nt(r);return n}function cc(r,e){if(typeof r=="bigint")return r;if(typeof r=="number"){if(!Number.isInteger(r))throw new Ye({type:e,value:r,reason:"expected an integer, got a fractional number"});return BigInt(r)}if(typeof r=="string"&&r.trim()!=="")try{return BigInt(r.trim())}catch{throw new Ye({type:e,value:r,reason:"string is not a valid integer"})}throw new Ye({type:e,value:r,reason:"expected a bigint, number or numeric string"})}function uc(r,{bits:e,signed:t,type:n}){let o=t?(1n<<BigInt(e-1))-1n:(1n<<BigInt(e))-1n,s=t?-(1n<<BigInt(e-1)):0n;if(r<s||r>o)throw new Gs({type:n,value:r,min:s,max:o})}function dc(r,e){if(r instanceof Uint8Array)return r;if(typeof r=="string"){if(!mn(r))throw new Ye({type:e,value:r,reason:"expected 0x-prefixed hex"});return Lt(r)}throw new Ye({type:e,value:r,reason:"expected a hex string or Uint8Array"})}function Si(r,e){let t=Ot(r.type);if(t){let[o,s]=t;if(!Array.isArray(e))throw new Ye({type:r.type,value:e,reason:"expected an array"});return mp({...r,type:s},e,o,r.type)}if(r.type==="tuple")return hp(r,e);let n=Dt(r.type);if(n==="address"){if(!R(e))throw new qn(e);return{dynamic:!1,encoded:wi(Lt(rt(e).toLowerCase()))}}if(n==="bool"){if(typeof e!="boolean")throw new Ye({type:n,value:e,reason:"expected a boolean"});let o=new Uint8Array(32);return o[31]=e?1:0,{dynamic:!1,encoded:o}}if(/^uint\d*$/.test(n)){let o=cc(e,n);return uc(o,{bits:lc(n,"uint"),signed:!1,type:n}),{dynamic:!1,encoded:fn(o)}}if(/^int\d*$/.test(n)){let o=cc(e,n);return uc(o,{bits:lc(n,"int"),signed:!0,type:n}),o<0n&&(o+=1n<<256n),{dynamic:!1,encoded:fn(o)}}if(/^bytes\d+$/.test(n)){let o=Number(n.slice(5));if(o<1||o>32)throw new Nt(r.type);let s=dc(e,n);if(s.length!==o)throw new Ks({expectedSize:o,value:String(e)});return{dynamic:!1,encoded:ki(s)}}if(n==="bytes")return ic(dc(e,n));if(n==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new Ye({type:n,value:e,reason:"expected a string"});return ic(typeof e=="string"?yi(e):e)}throw new Nt(r.type)}function xi(r){let e=0;for(let{dynamic:s,encoded:a}of r)e+=s?32:a.length;let t=[],n=[],o=0;for(let{dynamic:s,encoded:a}of r)s?(t.push(fn(BigInt(e+o))),n.push(a),o+=a.length):t.push(a);return gn([...t,...n])}function mp(r,e,t,n){let o=t===null;if(!o&&e.length!==t)throw new Ys({expectedLength:t,givenLength:e.length,type:n});let s=!1,a=[];for(let i of e){let l=Si(r,i);l.dynamic&&(s=!0),a.push(l)}if(o||s){let i=xi(a);if(!o)return{dynamic:!0,encoded:i};let l=fn(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?gn([l,i]):l}}return{dynamic:!1,encoded:gn(a.map(i=>i.encoded))}}function hp(r,e){let t=r.components??[],n=!1,o=[];for(let s=0;s<t.length;s++){let a=t[s],i=Si(a,Array.isArray(e)?e[s]:e[a.name??""]);i.dynamic&&(n=!0),o.push(i)}return{dynamic:n,encoded:n?xi(o):gn(o.map(s=>s.encoded))}}function Yn(r,e){if(r.length!==e.length)throw new Ws({expectedLength:r.length,givenLength:e.length});return r.length===0?"0x":kt(xi(r.map((t,n)=>Si(t,e[n]))))}function D({abi:r,functionName:e,args:t=[]}){let n=yn({abi:r,name:e,args:t,type:"function"}),o=vt(n),s=n.inputs??[];return s.length===0?o:Xs([o,Yn(s,t)])}function Ci({abi:r,errorName:e,args:t=[]}){let n=yn({abi:r,name:e,args:t,type:"error"}),o=n.inputs??[],s=vt(n);return o.length===0?s:Xs([s,Yn(o,t)])}function gp(r){let e=r.replace(/^u?int/,"");return e?Number(e):256}function jo(r,e){if(e<0||e+32>r.length)throw new $n({position:e,length:r.length});return r.subarray(e,e+32)}function _i(r,e){let t=Hn(jo(r,e));if(t>BigInt(r.length))throw new $n({position:Number(t),length:r.length});return Number(t)}function Ri(r){let e=Ot(r.type);if(e){let[n,o]=e;return n===null||Ri({...r,type:o})}if(r.type==="tuple")return(r.components??[]).some(Ri);let t=Dt(r.type);return t==="bytes"||t==="string"}function Ei(r){let e=Ot(r.type);if(e){let[t,n]=e;return t===null?32:t*Ei({...r,type:n})}return r.type==="tuple"?(r.components??[]).reduce((t,n)=>t+Ei(n),0):32}function Ni(r,e,t){let n=[],o=e;for(let s of t)Ri(s)?(n.push(pc(r,e+_i(r,o),s)),o+=32):(n.push(pc(r,o,s)),o+=Ei(s));return n}function fp(r,e,t,n){let o=n===null?_i(r,e):n,s=n===null?e+32:e;return Ni(r,s,new Array(o).fill(t))}function yp(r,e,t){let n=t.components??[],o=Ni(r,e,n);if(n.length===0||n.some(i=>!i.name))return o;let a={};return n.forEach((i,l)=>{a[i.name]=o[l]}),a}function pc(r,e,t){let n=Ot(t.type);if(n){let[s,a]=n;return fp(r,e,{...t,type:a},s)}if(t.type==="tuple")return yp(r,e,t);let o=Dt(t.type);if(o==="address")return Vn(kt(jo(r,e).subarray(12)));if(o==="bool")return Hn(jo(r,e))!==0n;if(/^u?int\d*$/.test(o)){let s=o.startsWith("int"),a=Hn(jo(r,e),{signed:s});return gp(o)>48?a:Number(a)}if(/^bytes\d+$/.test(o)){let s=Number(o.slice(5));return kt(jo(r,e).subarray(0,s))}if(o==="bytes"||o==="string"){let s=_i(r,e),a=e+32;if(a+s>r.length)throw new $n({position:a+s,length:r.length});let i=r.subarray(a,a+s);return o==="bytes"?kt(i):bi(i)}throw new Nt(t.type)}function Te(r,e){let t=typeof e=="string"?Lt(e):e;if(t.length===0){if(r.length>0)throw new Ut;return[]}if(t.length<32)throw new js({data:typeof e=="string"?e:kt(e),params:r,size:t.length});return Ni(t,0,r)}function X(r){if(!r)return null;try{let[e]=Te([{type:"uint256"}],r);return e}catch{return null}}function B(r){if(!r)return null;try{let[e]=Te([{type:"address"}],r),t=e;return/^0x0{40}$/i.test(t)?null:t}catch{return null}}function Gn(r){if(!r)return null;try{let[e]=Te([{type:"string"}],r),t=mc(e);if(t)return t}catch{}try{let[e]=Te([{type:"bytes32"}],r);return Zs(e)}catch{return null}}function Kn(r){return Js(X(r))}function Js(r){let e=typeof r=="bigint"?Number(r):typeof r=="number"?r:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function Zs(r){return typeof r!="string"||!r.startsWith("0x")?null:mc(Buffer.from(r.slice(2),"hex").toString("utf8"))||null}function mc(r){return r.replace(/[^\x20-\x7e]/g,"").trim()}function ot({abi:r,functionName:e,args:t,data:n}){let s=yn({abi:r,name:e,args:t,type:"function"}).outputs??[],a=Te(s,n);if(a.length!==0)return a.length===1?a[0]:a}function Ui({abi:r,data:e}){let t=hn(e,0,4),n=yn({abi:r,name:t,type:"function"}),o=n.inputs??[];return{functionName:n.name,args:o.length===0||Go(e)<=4?[]:Te(o,hn(e,4))}}var hc={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},gc={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},fc={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array.",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."};function jn({abi:r=[],data:e}){let t=hn(e,0,4);if(Go(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let n=[...r,hc,gc],o=Mt({abi:n,name:t,type:"error"})??n.find(a=>(a.type??"")==="error"&&vt(a)===t);if(!o)throw new Error(`Unknown error selector "${t}".`);let s=o.inputs??[];return{abiItem:o,errorName:o.name,args:s.length>0?Te(s,hn(e,4)):void 0}}function zo({abi:r,data:e}){if(!(!e||e==="0x"))try{let{errorName:t,args:n}=jn({abi:r,data:e});if(t==="Error")return String(n?.[0]??"");if(t==="Panic"){let o=Number(n?.[0]??0);return fc[o]??`Panic code ${o}.`}return!n||n.length===0?t:`${t}(${n.map(o=>String(o)).join(", ")})`}catch{return}}var bp=new Set(["pure","view","nonpayable","payable"]),wp=new Set(["external","public","internal","private","calldata","memory","storage"]);function Li(r,e){let t=0;for(let n=e;n<r.length;n++)if(r[n]==="(")t++;else if(r[n]===")"&&(t--,t===0))return n;throw new It(r,"Unbalanced parentheses.")}function bc(r){let e=[],t=0,n="";for(let o of r){if(o==="("&&t++,o===")"&&t--,o===","&&t===0){e.push(n),n="";continue}n+=o}return n.trim()&&e.push(n),e.map(o=>o.trim()).filter(Boolean)}function kp(r){let e=r.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function yc(r,e){let t=!1,n;for(let o of r)o==="indexed"?t=!0:wp.has(o)||(n=o);return{...e,...n?{name:n}:{},...t?{indexed:!0}:{}}}function Oi(r){let e=r.trim();if(e.startsWith("(")){let o=Li(e,0),s=bc(e.slice(1,o)).map(Oi),{suffix:a,rest:i}=kp(e.slice(o+1).trim());return yc(i.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:s})}let[t,...n]=e.split(/\s+/).filter(Boolean);if(!t)throw new It(r,"Missing parameter type.");return yc(n,{type:t})}function Qo(r){return bc(r).map(Oi)}function Xo(r,e,t){let n=r.indexOf("(",e);if(n===-1)throw new It(t,"Missing parameter list.");let o=Li(r,n);return{name:r.slice(e,n).trim(),params:Qo(r.slice(n+1,o)),rest:r.slice(o+1).trim()}}function Ii(r,e){return r.split(/[\s()]+/).find(n=>bp.has(n))??e}function ea(r){let e=r.trim();if(e.startsWith("function ")){let{name:t,params:n,rest:o}=Xo(e,9,r),s=o.indexOf("returns"),a=s===-1?o:o.slice(0,s),i=[];if(s!==-1){let l=o.indexOf("(",s);if(l===-1)throw new It(r,"`returns` without a parameter list.");i=Qo(o.slice(l+1,Li(o,l)))}return{type:"function",name:t,inputs:n,outputs:i,stateMutability:Ii(a,"nonpayable")}}if(e.startsWith("event ")){let{name:t,params:n}=Xo(e,6,r);return{type:"event",name:t,inputs:n}}if(e.startsWith("error ")){let{name:t,params:n}=Xo(e,6,r);return{type:"error",name:t,inputs:n}}if(e.startsWith("constructor")){let{params:t,rest:n}=Xo(e,11,r);return{type:"constructor",inputs:t,stateMutability:Ii(n,"nonpayable")}}if(e.startsWith("fallback")){let{rest:t}=Xo(e,8,r);return{type:"fallback",stateMutability:Ii(t,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new It(r,"Expected function, event, error, constructor, fallback or receive.")}function Di(r){return r.map(ea)}function st({blockNumber:r,blockTag:e="latest"}={}){return r!==void 0?xe(r):e}function Jo(r){let{account:e,to:t,data:n,value:o,gas:s,gasPrice:a,maxFeePerGas:i,maxPriorityFeePerGas:l,nonce:c}=r,u={};return e&&(u.from=e),t&&(u.to=t),n&&(u.data=n),o!==void 0&&(u.value=xe(o)),s!==void 0&&(u.gas=xe(s)),a!==void 0&&(u.gasPrice=xe(a)),i!==void 0&&(u.maxFeePerGas=xe(i)),l!==void 0&&(u.maxPriorityFeePerGas=xe(l)),c!==void 0&&(u.nonce=xe(c)),u}function Mi(r){let e={};for(let[t,n]of Object.entries(r)){let o={};n.balance!==void 0&&(o.balance=xe(n.balance)),n.nonce!==void 0&&(o.nonce=xe(n.nonce)),n.code!==void 0&&(o.code=n.code),n.state&&(o.state=n.state),n.stateDiff&&(o.stateDiff=n.stateDiff),e[t]=o}return e}async function zn(r){return Ge(await r.request({method:"eth_blockNumber"}))}async function Xn(r){return Qs(await r.request({method:"eth_chainId"}))}async function Qn(r,{address:e,...t}){return Ge(await r.request({method:"eth_getBalance",params:[e,st(t)]}))}async function Ft(r,{address:e,...t}){let n=await r.request({method:"eth_getCode",params:[e,st(t)]});return!n||n==="0x"?void 0:n}async function Jn(r,{address:e,slot:t,...n}){return await r.request({method:"eth_getStorageAt",params:[e,t,st(n)]})??void 0}async function Zn(r,{address:e,...t}){return Qs(await r.request({method:"eth_getTransactionCount",params:[e,st(t)]}))}async function er(r){return Ge(await r.request({method:"eth_gasPrice"}))}async function ta(r){return Ge(await r.request({method:"eth_maxPriorityFeePerGas"}))}async function tr(r,{blockNumber:e,blockTag:t,...n}){return Ge(await r.request({method:"eth_estimateGas",params:[Jo(n),st({blockNumber:e,blockTag:t})]}))}async function nr(r,{includeTransactions:e=!1,...t}={}){let n=await r.request({method:"eth_getBlockByNumber",params:[st(t),e]});return n?{...n,blockNumber:n.number?Ge(n.number):void 0,blockTimestamp:n.timestamp?Ge(n.timestamp):void 0,baseFee:n.baseFeePerGas?Ge(n.baseFeePerGas):void 0}:null}var Q="0xcA11bde05977b3631167028862bE2a173976CA11",wc={id:1,hexId:"0x1",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io"}},contracts:{multicall3:{address:Q,blockCreated:14353601}}},kc={id:10,hexId:"0xa",name:"Optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io","https://optimism-rpc.publicnode.com","https://optimism.drpc.org"]}},blockExplorers:{default:{name:"Optimistic Etherscan",url:"https://optimistic.etherscan.io"}},contracts:{multicall3:{address:Q,blockCreated:4286263}}},vc={id:56,hexId:"0x38",name:"BSC",nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18},rpcUrls:{default:{http:["https://bsc-dataseed.binance.org","https://bsc-rpc.publicnode.com","https://bsc.drpc.org"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com"}},contracts:{multicall3:{address:Q}}},Tc={id:137,hexId:"0x89",name:"Polygon",nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com"}},contracts:{multicall3:{address:Q,blockCreated:25770160}}},Ac={id:8453,hexId:"0x2105",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org","https://base-rpc.publicnode.com","https://base.drpc.org"]}},blockExplorers:{default:{name:"BaseScan",url:"https://basescan.org"}},contracts:{multicall3:{address:Q,blockCreated:5022}}},Pc={id:42161,hexId:"0xa4b1",name:"Arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc","https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io"}},contracts:{multicall3:{address:Q,blockCreated:7654707}}},Sc={id:43114,hexId:"0xa86a",name:"Avalanche",nativeCurrency:{name:"Avalanche",symbol:"AVAX",decimals:18},rpcUrls:{default:{http:["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io"}},contracts:{multicall3:{address:Q}}},xc={id:59144,hexId:"0xe708",name:"Linea",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build","https://linea-rpc.publicnode.com","https://linea.drpc.org"]}},blockExplorers:{default:{name:"LineaScan",url:"https://lineascan.build"}},contracts:{multicall3:{address:Q}}},Cc={id:100,hexId:"0x64",name:"Gnosis",nativeCurrency:{name:"xDAI",symbol:"XDAI",decimals:18},rpcUrls:{default:{http:["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"]}},blockExplorers:{default:{name:"Gnosisscan",url:"https://gnosisscan.io"}},contracts:{multicall3:{address:Q}}},Rc={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:Q}}},Ec={id:5e3,hexId:"0x1388",name:"Mantle",nativeCurrency:{name:"Mantle",symbol:"MNT",decimals:18},rpcUrls:{default:{http:["https://rpc.mantle.xyz","https://mantle-rpc.publicnode.com"]}},blockExplorers:{default:{name:"Mantle Explorer",url:"https://explorer.mantle.xyz"}},contracts:{multicall3:{address:Q}}},_c={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:Q}}},bn=[wc,kc,vc,Tc,Ac,Pc,Sc,xc,Cc,Rc,Ec,_c];var Nc=new Map,Fi=new Map;function vp(r,e){return`${r??"unknown"}|${e.toLowerCase()}`}async function Uc(r,e=Q){let t=vp(r.chain?.id??r.chain?.hexId,e),n=Nc.get(t);if(n!==void 0)return n;let o=Fi.get(t);if(o)return o;let s=(async()=>{try{let i=await Ft(r,{address:e})!==void 0;return Nc.set(t,i),i}catch{return!0}finally{Fi.delete(t)}})();return Fi.set(t,s),s}async function wn(r,e,t=!1){return t||typeof r.batch?.multicall=="object"&&r.batch.multicall.assumeMulticall3?!0:Uc(r,e)}var Ke=[{type:"function",name:"aggregate3",stateMutability:"payable",inputs:[{name:"calls",type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],outputs:[{name:"returnData",type:"tuple[]",components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}]}]},{type:"function",name:"getEthBalance",stateMutability:"view",inputs:[{name:"addr",type:"address"}],outputs:[{name:"balance",type:"uint256"}]},{type:"function",name:"getBlockNumber",stateMutability:"view",inputs:[],outputs:[{name:"blockNumber",type:"uint256"}]},{type:"function",name:"getCurrentBlockTimestamp",stateMutability:"view",inputs:[],outputs:[{name:"timestamp",type:"uint256"}]}];var V=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint8"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{name:"from",type:"address",indexed:!0},{name:"to",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]},{type:"event",name:"Approval",inputs:[{name:"owner",type:"address",indexed:!0},{name:"spender",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]}],rr=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];var or=[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"address"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]}];var na=[{type:"function",name:"uri",stateMutability:"view",inputs:[{name:"id",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"},{name:"id",type:"uint256"}],outputs:[{name:"",type:"uint256"}]}];var at=[{type:"function",name:"asset",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"totalAssets",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"convertToAssets",stateMutability:"view",inputs:[{name:"shares",type:"uint256"}],outputs:[{name:"assets",type:"uint256"}]},{type:"function",name:"convertToShares",stateMutability:"view",inputs:[{name:"assets",type:"uint256"}],outputs:[{name:"shares",type:"uint256"}]}];var sr=class extends M{name="ChainNotFoundError";constructor(e){super(`Chain "${e}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]})}},kn=class extends M{name="ClientChainNotConfiguredError";constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]})}},Bt=class extends M{name="ChainDoesNotSupportContractError";constructor({chain:e,contract:t,blockNumber:n}){super(n!==void 0?`Chain "${e}" does not support contract "${t}" at block ${n}.`:`Chain "${e}" does not support contract "${t}".`,{metaMessages:["Pass the contract address explicitly to use it on this chain."]})}};async function Bi(r,e,t){let n=new Array(r.length);if(r.length===0)return n;let o=0,s=Math.max(1,Math.min(e>0?e:r.length,r.length));async function a(){for(;;){let i=o++;if(i>=r.length)return;try{n[i]={status:"fulfilled",value:await t(r[i],i)}}catch(l){n[i]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:s},a)),n}function Zo({blockNumber:r,chain:e,contract:t}){let n=e.contracts?.[t];if(!n)throw new Bt({chain:e.name,contract:t});if(r!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(r))throw new Bt({blockNumber:r,chain:e.name,contract:t});return n.address}var ar=class extends M{name="RawContractError";data;constructor({data:e,shortMessage:t="The contract call reverted."}){super(t),this.data=e}},qi=class extends M{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:e,data:t,functionName:n}){let o=t?zo({abi:e,data:t}):void 0,s,a;if(t&&t!=="0x")try{let i=jn({abi:e,data:t});s=i.errorName,a=i.args}catch{}super(o?`The contract function "${n??"call"}" reverted with the following reason:
|
|
3
|
-
${o}`:`The contract function "${n??"call"}" reverted.`,{metaMessages:t&&t!=="0x"?[`Revert data: ${t}`]:[]}),this.reason=o,this.errorName=s,this.errorArgs=a,this.data=t}},$i=class extends M{name="ContractFunctionZeroDataError";constructor({functionName:e}){super(`The contract function "${e??"call"}" returned no data ("0x").`,{metaMessages:["This usually means:","- the address is not a contract on this chain,","- the ABI does not match the deployed contract, or","- the block predates the contract deployment."]})}},Hi=class extends M{name="ContractFunctionExecutionError";abi;address;args;functionName;constructor(e,{abi:t,address:n,args:o,functionName:s,sender:a}){let i=t&&s?Mt({abi:t,name:s,args:o}):void 0,l=i?Wn(i):s,c=o&&o.length>0?` args: (${o.map(d=>Tp(d)).join(", ")})`:void 0,u=i?.inputs?.length?`(${i.inputs.map(Ko).join(", ")})`:"()";super(e instanceof M?e.shortMessage:`An error occurred calling "${s??"contract"}".`,{cause:e,metaMessages:[...n?[`Contract: ${n}`]:[],...l?[`Function: ${l}${i?"":u}`]:[],...c?[c]:[],...a?[`Sender: ${a}`]:[]]}),this.abi=t,this.address=n,this.args=o,this.functionName=s}},es=class extends M{name="CallExecutionError";constructor(e,{to:t,data:n}){super(e instanceof M?e.shortMessage:"The call failed.",{cause:e,metaMessages:[...t?[`To: ${t}`]:[],...n?[`Data: ${n}`]:[]]})}};function Tp(r){if(typeof r=="bigint")return r.toString();if(typeof r=="string")return r;try{return JSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return String(r)}}function Ic(r){if(!r||typeof r!="object")return;let e=r,t=e.data;if(typeof t=="string"&&t.startsWith("0x"))return t;if(t&&typeof t=="object"){let n=t.data;if(typeof n=="string"&&n.startsWith("0x"))return n}return e.cause?Ic(e.cause):void 0}function ir(r,{abi:e,address:t,args:n,functionName:o,sender:s}){let a=Ic(r),i=r instanceof Ut?new $i({functionName:o}):a!==void 0?new qi({abi:e,data:a,functionName:o}):r;return new Hi(i,{abi:e,address:t,args:n,functionName:o,sender:s})}var Vi=new Map;function ts({fn:r,id:e,shouldSplitBatch:t,wait:n=0}){let o=()=>Vi.get(e)??void 0,s=i=>Vi.set(e,i),a=async i=>{o()===i&&Vi.delete(e);try{let l=await r(i.map(c=>c.item));i.forEach((c,u)=>c.resolve(l[u]))}catch(l){i.forEach(c=>c.reject(l))}};return{schedule(i){return new Promise((l,c)=>{let u={item:i,resolve:l,reject:c},d=o();if(d)if(t?.([...d.map(m=>m.item),i]))a(d);else{d.push(u);return}let p=[u];s(p),setTimeout(()=>{a(p)},n)})}}}function Ap(r){return!!(r.data&&r.to&&!r.account&&!r.value&&!r.gas&&!r.gasPrice&&!r.maxFeePerGas&&!r.maxPriorityFeePerGas&&r.nonce===void 0&&!r.stateOverride)}async function Pp(r,e){let{batchSize:t=1024,wait:n=0}=typeof r.batch?.multicall=="object"?r.batch.multicall:{},{blockNumber:o,blockTag:s="latest",data:a,to:i}=e;if(!r.chain)throw new kn;let l=Zo({blockNumber:o,chain:r.chain,contract:"multicall3"});if(!await wn(r,l,!1))throw new Bt({chain:r.chain.name,contract:"multicall3"});let c=o!==void 0?xe(o):s,{schedule:u}=ts({id:`${r.uid}.call.${c}`,wait:n,shouldSplitBatch:m=>m.reduce((g,h)=>g+(h.data.length-2)/2,0)>t,fn:async m=>{let g=D({abi:Ke,functionName:"aggregate3",args:[m.map(f=>({allowFailure:!0,callData:f.data,target:f.to}))]}),h=await r.request({method:"eth_call",params:[{to:l,data:g},c]});return ot({abi:Ke,functionName:"aggregate3",data:h})}}),{returnData:d,success:p}=await u({data:a,to:i});if(!p)throw new ar({data:d});return d}async function it(r,e){let{blockNumber:t,blockTag:n,stateOverride:o,skipBatch:s,...a}=e;if(r.batch?.multicall&&!s&&Ap(e))try{let l=await Pp(r,{blockNumber:t,blockTag:n,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof kn||l instanceof Bt))throw new es(l,{to:a.to,data:a.data})}let i=[Jo(a),st({blockNumber:t,blockTag:n})];o&&i.push(Mi(o));try{let l=await r.request({method:"eth_call",params:i});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new es(l,{to:a.to,data:a.data})}}var Wi=8;function Lc(r,e){if(e!==void 0&&e>0)return e;let t=typeof r.batch?.multicall=="object"?r.batch.multicall.fallbackConcurrency:void 0;return t!==void 0&&t>0?t:Wi}function ns(r,e,t){if(e)return e;if(!r.chain)throw new kn;let n=r.chain.contracts?.multicall3;return n?t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(t)?Q:n.address:Q}async function lr(r,e,t={}){let{concurrency:n,account:o,blockNumber:s,blockTag:a,stateOverride:i}=t;return(await Bi(e,Lc(r,n),async c=>{let{data:u}=await it(r,{to:c.target,data:c.callData,account:o,blockNumber:s,blockTag:a,stateOverride:i,skipBatch:!0});return u??"0x"})).map(c=>c.status==="fulfilled"?{success:!0,returnData:c.value}:{success:!1,returnData:"0x",error:c.reason})}async function lt(r,e){let{abi:t,address:n,functionName:o,args:s,...a}=e;try{let i=D({abi:t,functionName:o,args:s}),{data:l}=await it(r,{...a,to:n,data:i});return ot({abi:t,functionName:o,args:s,data:l??"0x"})}catch(i){throw ir(i,{abi:t,address:n,args:s,functionName:o,sender:a.account})}}var Sp=1024,xp=50;async function qt(r,e){let{calls:t,account:n,blockNumber:o,blockTag:s,batchSize:a=Sp,maxCalls:i=xp,multicallAddress:l,stateOverride:c,fallbackConcurrency:u}=e,d=t.map(()=>({success:!1,returnData:"0x"}));if(t.length===0)return d;let p=ns(r,l,o),m=[];if(t.forEach((b,y)=>{R(b.target)&&mn(b.callData)&&m.push({index:y,call:b})}),m.length===0)return d;if(!await wn(r,p,l!==void 0))return(await lr(r,m.map(y=>y.call),{account:n,blockNumber:o,blockTag:s,stateOverride:c,concurrency:u})).forEach((y,w)=>{d[m[w].index]={success:y.success,returnData:y.returnData}}),d;let g=[],h;return m.forEach(({call:b,index:y})=>{let w=(b.callData.length-2)/2,k=a>0&&h!==void 0&&h.size+w>a,v=i>0&&h!==void 0&&h.calls.length>=i;(!h||(k||v)&&h.calls.length>0)&&(h={calls:[],indexes:[],size:0},g.push(h)),h.calls.push(b),h.indexes.push(y),h.size+=w}),(await Promise.allSettled(g.map(b=>lt(r,{abi:Ke,address:p,functionName:"aggregate3",args:[b.calls.map(y=>({target:y.target,allowFailure:!0,callData:y.callData}))],account:n,blockNumber:o,blockTag:s,stateOverride:c})))).forEach((b,y)=>{b.status==="fulfilled"&&g[y].indexes.forEach((w,k)=>{let v=b.value[k];v&&(d[w]={success:!!v.success,returnData:v.returnData??"0x"})})}),d}var Oc="https://wallet-api.pantograph.app/keyring/chains_v6",Cp=6,Rp=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,Dc={},cr=null;function Ep(r){let e=Array.isArray(r.rpcs)?r.rpcs:[],t=typeof r.linkProvider=="string"?[r.linkProvider]:[],n=[];for(let o of[...t,...e]){if(typeof o!="string")continue;let s=o.trim();if(!(!s.startsWith("https://")||Rp.test(s))&&(n.includes(s)||n.push(s),n.length>=Cp))break}return n}function Mc(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e={};for(let[t,n]of Object.entries(r)){if(!n||typeof n!="object")continue;let o=n,s=ct(t)??(typeof o.chainId=="number"?ct(o.chainId):void 0);if(!s)continue;let a=Ep(o);a.length>0&&(e[s]=a)}return e}function Fc(r){Dc=r}function Yi(r){let e=ct(r);return e?Dc[e]??[]:[]}function Gi(){cr||ra()}function ra(r={}){let{url:e=Oc,force:t=!1,debug:n=!1}=r;return cr&&!t||(cr=(async()=>{try{let o=await x.get(e);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=Mc(o.data),a=Object.keys(s).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return Fc(s),n&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${e}`),!0}catch(o){if(n){let s=o instanceof Error?o.message:String(o);console.warn(`[chains] remote RPC catalogue unavailable (${s}); using built-in endpoints`)}return cr=null,!1}})()),cr}var _p=new Map(bn.map(r=>[r.hexId.toLowerCase(),r])),Np=new Map(bn.map(r=>[r.id,r]));function ct(r){if(typeof r=="number")return Number.isFinite(r)&&r>=0?`0x${r.toString(16)}`:void 0;let e=r.trim().toLowerCase();if(e)return e.startsWith("0x")?/^0x[0-9a-f]+$/.test(e)?e:void 0:/^\d+$/.test(e)?`0x${Number(e).toString(16)}`:void 0}function Tt(r){if(typeof r=="number")return Np.get(r);let e=ct(r);return e?_p.get(e):void 0}var De=Object.fromEntries(bn.map(r=>[r.hexId,r.rpcUrls.default.http[0]]));function Ki(r){return Tt(r)?.rpcUrls.default.http[0]}var ji={};function vn(r){let e={};if(r)for(let[t,n]of Object.entries(r)){if(typeof n!="string"||!n.trim())continue;let o=ct(t)??t.toLowerCase();e[o]=n.trim()}ji=e}function rs(){return{...ji}}function Tn(r){Gi();let e=ct(r),t=e?ji[e]:void 0,n=Yi(r),o=Tt(r)?.rpcUrls.default.http??[];return[...new Set([...t?[t]:[],...n,...o])]}function An(r){return Tn(r)[0]}function zi(r){let e=Tt(r);if(!e)return;let t=Tn(r),n=e.rpcUrls.default.http;return t.length===0||t.length===n.length&&t.every((o,s)=>o===n[s])?e:{...e,rpcUrls:{default:{http:t}}}}var $t=class extends M{name="HttpRequestError";status;url;body;headers;constructor({body:e,details:t,headers:n,status:o,url:s}){super("HTTP request failed.",{details:t,metaMessages:[`URL: ${s}`,...o?[`Status: ${o}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[]]}),this.status=o,this.url=s,this.body=e,this.headers=n}},ur=class extends M{name="TimeoutError";constructor({body:e,url:t,timeout:n}){super("The request took too long to respond.",{details:`The request timed out after ${n}ms.`,metaMessages:[`URL: ${t}`,...e?[`Request body: ${JSON.stringify(e)}`]:[]]})}},dr=class extends M{name="NetworkError";constructor({cause:e,url:t}){super("Could not reach the RPC endpoint.",{cause:e,metaMessages:[`URL: ${t}`]})}},oa=class extends M{name="UrlRequiredError";constructor(){super("No RPC URL was provided.",{metaMessages:['Pass one to the transport \u2014 http("https://\u2026") \u2014 or give the client a chain that has a default RPC URL.']})}},os=class extends M{name="FallbackTransportError";constructor({cause:e,count:t}){super(`All ${t} fallback transports failed.`,{cause:e})}};var pr=class extends M{name="RpcRequestError";code;data;constructor({body:e,error:t,url:n,shortMessage:o}){super(o??"RPC request failed.",{details:t.message,metaMessages:[...n?[`URL: ${n}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[],`Error code: ${t.code}`]}),this.code=t.code,this.data=t.data}};function Me(r,e,t){return class extends pr{static code=e;name=r;constructor(n){super({...n,shortMessage:t})}}}var Up=Me("ParseRpcError",-32700,"The node could not parse the JSON request."),Ip=Me("InvalidRequestRpcError",-32600,"The JSON request is not valid."),Lp=Me("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),Op=Me("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),Dp=Me("InternalRpcError",-32603,"The node reported an internal error."),Mp=Me("InvalidInputRpcError",-32e3,"The RPC input is not valid."),Fp=Me("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Bp=Me("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),qp=Me("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),$p=Me("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),Xi=Me("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),Hp=Me("UserRejectedRequestError",4001,"The user rejected the request."),Vp=new Map([[-32700,Up],[-32600,Ip],[-32601,Lp],[-32602,Op],[-32603,Dp],[-32e3,Mp],[-32001,Fp],[-32002,Bp],[-32003,qp],[-32004,$p],[-32005,Xi],[4001,Hp]]);function Bc(r){let e=Vp.get(r.error.code);return e?new e(r):new pr(r)}function qc(r){return new Promise(e=>setTimeout(e,r))}async function Qi(r,{retryCount:e=2,delay:t=150,shouldRetry:n=()=>!0}={}){let o=0;for(;;)try{return await r()}catch(s){if(o++,o>e||!n({count:o,error:s}))throw s;let a=typeof t=="function"?t({count:o,error:s}):t*2**(o-1);a>0&&await qc(a)}}function Ji(r){let e=r?.["retry-after"];if(!e)return;let t=Number(e);if(Number.isFinite(t))return t*1e3;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}var Wp=new Set([408,413,429,500,502,503,504]),Yp=new Set([401,402,403]);function sa(r){return r instanceof ur||r instanceof dr?!0:r instanceof $t?r.status?Wp.has(r.status)||r.status>=500:!0:r instanceof Xi?!0:r instanceof pr?r.code===-32603:!1}function aa(r){return r instanceof $t&&r.status&&Yp.has(r.status)?!0:sa(r)}function ia(r,{retryCount:e=3,retryDelay:t=150}={}){return function(o,s={}){return Qi(()=>r(o),{retryCount:s.retryCount??e,shouldRetry:({error:a})=>sa(a),delay:({count:a,error:i})=>{let l=i instanceof $t?Ji(i.headers):void 0;return l!==void 0?l:(s.retryDelay??t)*2**(a-1)}})}}function Ht({key:r,name:e,type:t,request:n,retryCount:o=3,retryDelay:s=150,timeout:a=1e4},i){return{config:{key:r,name:e,type:t,request:n,retryCount:o,retryDelay:s,timeout:a},request:ia(n,{retryCount:o,retryDelay:s}),value:i}}function Vt(r,e={}){let{key:t="fallback",name:n="Fallback",retryCount:o=0,retryDelay:s,onTransportError:a}=e;return(i={})=>{let l=r.map(u=>u(i));if(l.length===0)throw new os({count:0});return Ht({key:t,name:n,type:"fallback",request:async u=>{let d;for(let p=0;p<l.length;p++)try{return await l[p].request(u)}catch(m){if(d=m,a?.({error:m,index:p,method:u.method}),!aa(m))throw m}throw new os({cause:d,count:l.length})},retryCount:o,retryDelay:s,timeout:i.timeout},{transports:l})}}var $c=0;function Hc(){return $c+=1,$c}function Gp(r){let e=r?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let t=r?.message??"";return/timeout/i.test(t)}var mr=class{url;timeout;fetchOptions;constructor(e,{timeout:t=1e4,fetchOptions:n={}}={}){this.url=e,this.timeout=t,this.fetchOptions=n}async post(e){let t;try{t=await x.post(this.url,e,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(n){throw Gp(n)?new ur({body:e,url:this.url,timeout:this.timeout}):new dr({cause:n,url:this.url})}if(!t.ok)throw new $t({body:e,details:E(t),headers:t.headers,status:t.status,url:this.url});return t.data}async request(e){let t={jsonrpc:"2.0",id:Hc(),...e};return await this.post(t)??{id:t.id}}async requestBatch(e){let t=e.map(s=>({jsonrpc:"2.0",id:Hc(),...s})),n=await this.post(t);if(!Array.isArray(n))return t.map(s=>({id:s.id,error:n?.error??{code:-32603,message:"Malformed batch response."}}));let o=new Map(n.map(s=>[s.id,s]));return t.map((s,a)=>o.get(s.id)??n[a]??{id:s.id,error:{code:-32603,message:"Missing response for batched request."}})}};function Vc(r,e,t){if(r.error)throw Bc({body:e,error:r.error,url:t});return r.result}function je(r,e={}){let{batch:t,fetchOptions:n,key:o="http",name:s="HTTP JSON-RPC",retryCount:a,retryDelay:i,timeout:l}=e;return({chain:c,retryCount:u,retryDelay:d,timeout:p}={})=>{let{batchSize:m=1e3,wait:g=0}=typeof t=="object"?t:{},h=l??p??1e4,f=r??c?.rpcUrls.default.http[0];if(!f)throw new oa;let b=new mr(f,{timeout:h,fetchOptions:n});return Ht({key:o,name:s,type:"http",retryCount:a??u,retryDelay:i??d,timeout:h,async request({method:y,params:w}){let k={method:y,params:w};if(t){let{schedule:v}=ts({id:`${f}:${m}:${g}`,wait:g,shouldSplitBatch:A=>A.length>m,fn:A=>b.requestBatch(A)});return Vc(await v(k),k,f)}return Vc(await b.request(k),k,f)}},{url:f})}}var Kp=1024;async function hr(r,e){let{contracts:t,allowFailure:n=!0,account:o,blockNumber:s,blockTag:a,multicallAddress:i,stateOverride:l,fallbackConcurrency:c}=e,u=e.batchSize??(typeof r.batch?.multicall=="object"&&r.batch.multicall.batchSize||Kp),d=new Array(t.length);if(t.length===0)return n?d:[];let p=ns(r,i,s),m=[],g;t.forEach((b,y)=>{let{abi:w,address:k,functionName:v,args:A}=b,S;try{if(!R(k))throw new qn(k);S=D({abi:w,functionName:v,args:A})}catch(O){let _=ir(O,{abi:w,address:k,args:A,functionName:v,sender:o});if(!n)throw _;d[y]={status:"failure",error:_};return}let C=(S.length-2)/2;(!g||u>0&&g.size+C>u&&g.calls.length>0)&&(g={calls:[],indexes:[],size:0},m.push(g)),g.calls.push({target:k,allowFailure:!0,callData:S}),g.indexes.push(y),g.size+=C}),(await wn(r,p,i!==void 0)?await Promise.allSettled(m.map(b=>lt(r,{abi:Ke,address:p,functionName:"aggregate3",args:[b.calls],account:o,blockNumber:s,blockTag:a,stateOverride:l}))):await(async()=>{let b=m.flatMap(w=>w.calls.map((k,v)=>({target:k.target,callData:k.callData,index:w.indexes[v]}))),y=await lr(r,b,{account:o,blockNumber:s,blockTag:a,stateOverride:l,concurrency:c});return m.length=0,y.map((w,k)=>(m.push({calls:[],indexes:[b[k].index],size:0}),w.success?{status:"fulfilled",value:[{success:!0,returnData:w.returnData}]}:{status:"rejected",reason:w.error}))})()).forEach((b,y)=>{let w=m[y];if(b.status==="rejected"){for(let k of w.indexes){let v=t[k],A=ir(b.reason,{abi:v.abi,address:v.address,args:v.args,functionName:v.functionName,sender:o});if(!n)throw A;d[k]={status:"failure",error:A}}return}w.indexes.forEach((k,v)=>{let A=t[k],S=b.value[v];try{if(!S)throw new Error("Multicall returned fewer results than calls.");if(!S.success)throw new ar({data:S.returnData});if(!S.returnData||S.returnData==="0x")throw new Ut;let C=ot({abi:A.abi,functionName:A.functionName,args:A.args,data:S.returnData});d[k]={status:"success",result:C}}catch(C){let O=ir(C,{abi:A.abi,address:A.address,args:A.args,functionName:A.functionName,sender:o});if(!n)throw O;d[k]={status:"failure",error:O}}})});for(let b=0;b<t.length;b++){if(d[b])continue;let y=new Error("Multicall returned no result for this call.");if(!n)throw y;d[b]={status:"failure",error:y}}return n?d:d.map(b=>b.result)}var jp=0,Pn=class{key;name;uid;chain;transport;batch;request;constructor(e={}){let{batch:t,key:n="public",name:o="Public Client",retryCount:s,retryDelay:a,timeout:i}=e;this.chain=Xp(e.chain),this.key=n,this.name=o,this.batch=t,this.uid=`${n}-${++jp}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??zp(e.rpcUrl,this.chain))({chain:this.chain,retryCount:s,retryDelay:a,timeout:i});this.transport={...c.config,...c.value},this.request=c.request}call(e){return it(this,e)}readContract(e){return lt(this,e)}multicall(e){return hr(this,e)}multicallRaw(e){return qt(this,e)}getBlockNumber(){return zn(this)}getChainId(){return Xn(this)}getBalance(e){return Qn(this,e)}getCode(e){return Ft(this,e)}getStorageAt(e){return Jn(this,e)}getTransactionCount(e){return Zn(this,e)}getGasPrice(){return er(this)}estimateMaxPriorityFeePerGas(){return ta(this)}estimateGas(e){return tr(this,e)}getBlock(e){return nr(this,e)}rpc(e,t){return this.request({method:e,params:t})}extend(e){let t=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return Object.assign(t,e(t))}};function zp(r,e){if(r)return je(r);let t=e?.rpcUrls.default.http??[];return t.length>1?Vt(t.map(n=>je(n,{retryCount:1}))):je(t[0])}function Xp(r){if(r===void 0)return;if(typeof r=="object")return r;let e=zi(r);if(!e)throw new sr(r);return e}function Wt(r={}){return new Pn(r)}var Zi=new Map;function Qp(r,e){return{id:parseInt(r,16),hexId:r,name:`Chain ${parseInt(r,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:e}},contracts:{multicall3:{address:Q}}}}function we(r,e={}){let{batch:t=!0,pinRpcUrl:n=!1,fallbackConcurrency:o,assumeMulticall3:s}=e,a=ct(r),i=e.rpcUrl?.trim(),l=a?Tn(a):[],c=i?n?[i]:[...new Set([i,...l])]:l;if(c.length===0)throw new sr(r);let u=`${a??r}|${c.join(",")}|${t?1:0}|${o??""}|${s?1:0}`,d=Zi.get(u);if(d)return d;let p=Wt({chain:a&&!Tt(a)?Qp(a,c):a,transport:c.length===1?je(c[0]):Vt(c.map(m=>je(m,{retryCount:1}))),batch:t?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return Zi.set(u,p),p}function la(){Zi.clear()}function tl(r,e){try{return we(r,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function pe(r,e,t){let n=new Array(e.length).fill(null),o=e.length>0?tl(r,t):null;if(!o)return n;let s=[];if(e.forEach((a,i)=>{!R(a.target)||!mn(a.callData)||s.push({index:i,target:a.target,callData:a.callData})}),s.length===0)return n;try{(await qt(o,{calls:s})).forEach((i,l)=>{i.success&&(n[s[l].index]=i.returnData)})}catch{}return n}function ca(r){return r?.status==="success"?r.result:void 0}async function el(r,e){try{return await r.multicall({contracts:e})}catch{return[]}}async function ua(r,e,t){let n=e.map(()=>({symbol:null,decimals:null})),o=e.length>0?tl(r,t):null;if(!o)return n;let s=[];if(e.forEach((l,c)=>{R(l)&&s.push({index:c,address:l})}),s.length===0)return n;let a=await el(o,s.flatMap(l=>[{address:l.address,abi:V,functionName:"symbol"},{address:l.address,abi:V,functionName:"decimals"}]));s.forEach((l,c)=>{let u=ca(a[c*2]);typeof u=="string"&&u.trim()&&(n[l.index].symbol=u.trim()),n[l.index].decimals=Js(ca(a[c*2+1]))});let i=s.filter(l=>n[l.index].symbol===null);if(i.length>0){let l=await el(o,i.map(c=>({address:c.address,abi:rr,functionName:"symbol"})));i.forEach((c,u)=>{n[c.index].symbol=Zs(ca(l[u]))})}return n}async function Wc(r,e,t){let n=new Array(e.length).fill(null),o=e.length>0?tl(r,t):null;if(!o)return n;let s=[];return e.forEach((i,l)=>{if(R(i.contract))try{s.push({index:l,address:i.contract,tokenId:BigInt(i.tokenId)})}catch{}}),s.length===0||(await el(o,s.map(i=>({address:i.address,abi:or,functionName:"tokenURI",args:[i.tokenId]})))).forEach((i,l)=>{let c=ca(i);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(n[s[l].index]=u)}),n}function ss(r){return gr(String(r))??"0"}function gr(r){let e=r.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",n=e[2]??"",o=e[3]??"";if(n===""&&o==="")return null;let s=e[4]?parseInt(e[4],10):0,a=n+o,i=n.length+s,l;return i<=0?l=`0.${"0".repeat(-i)}${a}`:i>=a.length?l=a+"0".repeat(i-a.length):l=`${a.slice(0,i)}.${a.slice(i)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":t+l}function nl(r){let e=gr(r);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function da(r,e){let t=r<0n,n=(t?-r:r).toString(),o;if(e===0)o=n;else{let s=n.padStart(e+1,"0"),a=s.length-e;o=`${s.slice(0,a)}.${s.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${o}`:o}function Sn(r,e){let t=gr(r);if(t===null||t.startsWith("-"))return null;let[n,o=""]=t.split("."),s=o.slice(0,e).padEnd(e,"0");try{let a=BigInt(n||"0")*10n**BigInt(e)+BigInt(s||"0");return a>0n?a:null}catch{return null}}function xn(r){if(typeof r=="number")return Number.isFinite(r)&&r>0?ss(r):null;if(typeof r!="string")return null;let e=r.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=gr(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function At(r,e){let t=gr(r);if(t===null||e<0)return r;let n=t.startsWith("-"),[o,s=""]=(n?t.slice(1):t).split(".");if(s.length<=e)return t;let a=e===0?o:`${o}.${s.slice(0,e)}`,i=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${i}`:i}function Cn(r,e,t,n){let o=nl(r);if(!o||t<=0n||n<0)return r;let s=o.mant*e*10n**BigInt(n)/(t*10n**BigInt(o.frac));return da(s,n)}function Yt(r,e){let t=nl(r),n=nl(e);if(!t||!n){let i=Number(r),l=Number(e);return i<l?-1:i>l?1:0}let o=Math.max(t.frac,n.frac),s=t.mant*10n**BigInt(o-t.frac),a=n.mant*10n**BigInt(o-n.frac);return s<a?-1:s>a?1:0}var Jp={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"}]},Zp="payment-required",em="PAYMENT-SIGNATURE",tm="X-PAYMENT",nm="payment-response",rm="x-payment-response",om=600,sm=300,am={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 Yc(r){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(r),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(r,"utf8").toString("base64")}function Kc(r){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(r,"base64").toString("utf8")}function im(){let r=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(r);else for(let t=0;t<32;t++)r[t]=Math.floor(Math.random()*256);return"0x"+Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}function jc(r){let e=String(r);if(e.includes(":")){let[n,o]=e.split(":"),s=parseInt(o,10);if(n!=="eip155"||Number.isNaN(s))throw new Error(`Unsupported x402 network: ${r} (only EVM "eip155:*" is supported)`);return s}let t=am[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${r}`);return t}function zc(r){if(!r.query||Object.keys(r.query).length===0)return r.url;let e=Object.entries(r.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return r.url.includes("?")?`${r.url}&${e}`:`${r.url}?${e}`}function pa(r){let e=r.headers[Zp];if(e){let o=Gc(lm(e));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let t=r.data,n=t&&typeof t=="object"?t:Gc(t);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function Gc(r){if(typeof r!="string")return null;try{let e=JSON.parse(r);return e&&typeof e=="object"?e:null}catch{return null}}function lm(r){try{return Kc(r)}catch{return null}}function cm(r){let e=r.amount??r.maxAmountRequired;return typeof r.scheme!="string"||typeof r.network!="string"||e==null||typeof r.asset!="string"||typeof r.payTo!="string"?null:{scheme:r.scheme,network:r.network,amount:String(e),asset:r.asset,payTo:r.payTo,...typeof r.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:r.maxTimeoutSeconds}:{},...r.extra&&typeof r.extra=="object"?{extra:r.extra}:{},...typeof r.resource=="string"?{resource:r.resource}:{},...typeof r.description=="string"?{description:r.description}:{},...typeof r.mimeType=="string"?{mimeType:r.mimeType}:{},...r.outputSchema!=null?{outputSchema:r.outputSchema}:{}}}function um(r){let e=null;for(let t of r){let n=cm(t);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return jc(n.network),n}catch(o){e=o instanceof Error?o.message:String(o)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function rl(r,e,t,n){let o=pa(r);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:a}=o,i=um(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=jc(i.network),c=Math.floor(Date.now()/1e3),u={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-om)),validBefore:String(c+(i.maxTimeoutSeconds??sm)),nonce:im()},d={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:Jp,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:zc(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:s,requirements:i,authorization:u,typedData:d,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...n?{userQuery:n}:{}}}async function dm(r,e,t,n){let o=zc(e),s=await r.request(e.method??"GET",o,e.body,{headers:e.headers});if(s.status===402)return{status:"payment_required",challenge:rl(s,e,t,n)};if(!s.ok)throw new Error(E(s));return{status:"ok",data:s.data}}async function ol(r,e,t){let{url:n,method:o,body:s,headers:a}=e.request,i=await r.request(o,n,s,{headers:{...a??{},...sl(e,t)}});if(i.ok)return i.data;throw new Error(mm(i)??E(i))}function pm(r){return pa(r)!==null}function Xc(r){let e=Qc(r);return e?.errorReason?e.errorReason:pa(r)?.payload.error??null}function mm(r){let e=Xc(r);return e?`x402 payment rejected: ${e}`:null}var hm={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 sl(r,e){let{requirements:t,authorization:n}=r,o={signature:e,authorization:n};if(r.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:o};return{[tm]:Yc(JSON.stringify(a))}}let s={x402Version:2,...r.resource!=null?{resource:r.resource}:{},accepted:gm(t),payload:o,...r.extensions!=null?{extensions:r.extensions}:{}};return{[em]:Yc(JSON.stringify(s))}}function gm(r){let{resource:e,description:t,mimeType:n,outputSchema:o,...s}=r;return s}function Qc(r){let e=r.headers[nm]??r.headers[rm];if(!e)return null;try{return JSON.parse(Kc(e))}catch{return null}}function fm(r,e){return r==null?e:hm[r]??`Chain ${r}`}async function Jc(r){let e=r.requirements,n=r.resource?.description||e.description,o=r.chainId??null,s=null,a=null;if(o!=null){let[l]=await ua("0x"+o.toString(16),[e.asset]);s=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=da(BigInt(e.amount),a)}catch{}return{amount:i,asset:s||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:o!=null?`eip155:${o}`:e.network,networkRaw:e.network,chainId:o,networkLabel:fm(o,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:r.request.url}}function al(r){return async(e,t)=>{let n=r.getPayer(),o=r.getSigner();if(!n||!o)return null;let s;try{s=rl(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let a;try{a=await o({typedData:s.typedData,display:await Jc(s)})}catch{a=null}return a?sl(s,a):null}}var Gt=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Rn(r){if(!r||typeof r!="object")return!1;let e=r;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function as(r){if(r?.aborted)throw new Gt}function il(r,e){if(!e)return{signal:r.signal,cleanup:()=>{}};if(e.aborted)return r.abort(),{signal:r.signal,cleanup:()=>{}};let t=()=>r.abort();return e.addEventListener("abort",t),{signal:r.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Zc={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},ym="https://nft.keyring.app/api/gemini-stable",bm="https://generativelanguage.googleapis.com",wm=new Set([408,429,500,502,503,504]),eu=3e4,ma=r=>new Promise(e=>setTimeout(e,r));function ha(r,e,t){if(t!=null&&t>0)return Math.min(t,eu);let n=Math.min(e*2**(r-1),eu);return n/2+Math.random()*(n/2)}function km(r){if(!r)return null;let e=Number(r);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(r);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var ce=class{model;maxTokens;temperature;baseUrl;apiKey;requestSignal;constructor(e){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?bm:ym)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:o,contents:s}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;as(l);let c=s.length>0?s:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let h of c){let f=h.parts.map(b=>b.functionCall?`fc:${b.functionCall.name}`:b.functionResponse?`fr:${b.functionResponse.name}`:`text:${(b.text??"").slice(0,40)}`).join(", ");console.log(` ${h.role}: [${f}]`)}}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 p={contents:c,generationConfig:d};o&&(p.systemInstruction=o),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,g="Unknown error";for(let h=1;h<=a;h++){as(l);let f;try{f=await x.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(S){if(Rn(S))throw S;if(g=S instanceof Error?S.message:String(S),h>=a)break;await ma(ha(h,i));continue}if(!f.ok){let S=typeof f.data=="string"?f.data:JSON.stringify(f.data)||f.statusText;if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${f.status}: ${S}`,!wm.has(f.status))throw new Error(g);if(h>=a)break;let C=km(f.headers["retry-after"]??null);await ma(ha(h,i,C));continue}if(f.data==null||typeof f.data!="object"){if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=a)break;await ma(ha(h,i));continue}let b=f.data,y=b.candidates?.[0];if(!y)return{text:"",toolCalls:[]};let w="",k=[],v=y.content?.parts;if(!Array.isArray(v)||v.length===0){let S=y.finishReason;if(!(S==="SAFETY"||S==="RECITATION")&&h<a){g=`Gemini returned an empty turn (finishReason=${S??"none"})`,await ma(ha(h,i));continue}return{text:"",toolCalls:[]}}for(let S of v)S.text&&(w+=S.text),S.functionCall&&k.push({toolName:S.functionCall.name,args:S.functionCall.args??{},callId:S.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let A=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:A}}throw new Error(g)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o=[];for(let i of n){let l=o[o.length-1],c=i.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===i.role&&!c&&!u?l.parts.push(...i.parts):o.push({...i,parts:[...i.parts]})}let s=[];for(let i=0;i<o.length;i++){let l=o[i],c=s[s.length-1];l.role==="function"&&!c?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(o[i+1]?.role==="function")||s.push(l)}for(;s.length>0&&s[0].role!=="user";)s.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
|
|
4
|
-
`)}]}:null,contents:s}}toFunctionDeclarations(e){return e.map(t=>{let n={},o=[];for(let s of t.parameters){let a={type:Zc[s.type]??"STRING",description:s.description};s.type==="array"&&(a.items={type:Zc[s.items?.type??"string"]??"STRING"}),n[s.name]=a,s.required&&o.push(s.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:n,required:o}}})}};var fr=class{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(t=>t.category===e)}async execute(e,t,n){let o=this.tools.get(e);if(!o)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let s=Date.now();try{return{...await o.execute(t,n),duration:Date.now()-s}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-s}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var yr=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],vm=new Set(yr),Kt=[...yr],ll=new Set(Kt),Fe="0x1",wr="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Tm(r){return r.map(e=>br[e]??e).join(", ")}function ga(r){let e=new Set;if(r)for(let n of r){let o=fa(n);o&&e.add(o)}let t=yr.filter(n=>!e.has(n));Kt=t.length>0?[...t]:[...yr],ll=new Set(Kt),Fe=Kt.includes("0x1")?"0x1":Kt[0],wr=Tm(Kt)}var Am={"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 F(r){let e=fa(r);return e&&ll.has(e)?e:null}function fa(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Am[e];if(t)return t;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&vm.has(n)?n:null}function ze(r){return F(r)!==null}function Ce(){return[...Kt]}var zt=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${wr}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},jt=r=>typeof r=="string"&&r.trim()!=="";function G(r,e){if(jt(r)){let t=F(r);if(t)return t;throw new zt(r.trim())}if(jt(e?.chain)){let t=F(e.chain);if(t)return t;throw new zt(e.chain.trim())}return null}function ya(r,e){return F(r)??F(e?.chain)??void 0}var br={"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 T(r){let e=fa(r);return e&&br[e]?br[e]:typeof r=="string"&&r.trim()?r.trim():"the requested chain"}var Pm={"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 tu(r,e){let t=fa(r),n=t?Pm[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Sm={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function nu(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase();return e?Sm[e]??null:null}var xm={"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 ru(r){let e=F(r);return e?xm[e]??null:null}function kr(r,e){if(!jt(r))return null;let t=F(r),n=F(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:br[t]??t,connectedLabel:br[n]??n}}function ou(r,e){let t=typeof r=="string"?r.trim():"",n=e&&e.length?e.filter(s=>ll.has(s)):[];return(n.length?n:Kt).map(s=>{let a=br[s]??s;return{label:a,prompt:t?`${t} (${a})`:a}})}function vr(r,e){return{actionButtons:ou(e),_instructions:`The user wants to ${r} 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 ie=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=ou(e,t)}},is=class extends Error{code="no_wallet_connected";constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one."),this.name="NoWalletConnectedError"}};function re(r,e){if(jt(r))return r.trim();if(jt(e?.walletAddress))return e.walletAddress.trim();throw new is}function ge(r,e,t){if(jt(r)){let n=F(r);if(n)return n;throw new zt(r.trim())}if(jt(e?.chain)){let n=F(e.chain);if(n)return n;throw new zt(e.chain.trim())}if(jt(e?.walletAddress))throw new ie(typeof e?.query=="string"?e.query:void 0,t);return Fe}var P=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a=Cm(s);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-o,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(s){return s instanceof ie?{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()-o,actionButtons:s.buttons}:s instanceof is?{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()-o}:{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}};function Cm(r){if(!r||typeof r!="object")return{data:r};let e=r,t=e.actionButtons,n=Array.isArray(t)&&t.length>0?t:void 0,o=e.ui,s=o&&typeof o=="object"&&typeof o.component=="string"?o:void 0;if(!n&&!s)return{data:r};let{actionButtons:a,ui:i,...l}=e;return{data:l,...n?{actionButtons:n}:{},...s?{ui:s}:{}}}var Rm="https://wallet-api.pantograph.app",Em="0x0000000000000000000000000000000000000000",iu={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},lu={"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 _m(r){return iu[r.toLowerCase()]||r}function su(r){let e=[];for(let[t,n]of Object.entries(r))if(n!=null)if(Array.isArray(n))for(let o of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function cl(r){let e=r,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,o=e.price,s=o!=null?parseFloat(String(o)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(s)?{usd_price:s}:{}}}function ba(r){if(Array.isArray(r))return r;let e=r;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Ae(r){if(r==null)return null;let e=typeof r=="number"?r:parseFloat(String(r));return Number.isFinite(e)?e:null}function au(r,e){let t=r.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,o=Ae(r.price_change_percentage_24h)??Ae(r.priceChange24h)??Ae(r.usd_price_24hr_percent_change)??Ae(r.price_change_24h)??Ae(r.priceChange);return{chainId:e,tokenAddress:r.address??r.token_address??"",name:r.name??null,symbol:r.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:r.logoURI??r.icon_image??r.logo??null,usdPrice:Ae(r.price)??Ae(r.usd_price),marketCap:Ae(r.market_cap)??Ae(r.marketCap),totalVolume:{"24h":Ae(r.total_volume)??Ae(r.volume24h)},pricePercentChange:{"24h":o}}}var me=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Rm).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){let n=new Map;if(e.length===0)return n;try{let o=e.map(c=>c.token_address).join(","),s=this.tokensUrl(t,o),a=await x.get(s);if(!a.ok)return n;let i=ba(a.data),l=new Map;for(let c of i)if(c.address){let u=c.address.toLowerCase();l.set(u,{price:c.price!=null?parseFloat(String(c.price)):NaN,icon_image:c.icon_image}),("yieldProtocol"in c||"yieldAsset"in c)&&n.set(u,{yieldProtocol:c.yieldProtocol,yieldAsset:c.yieldAsset})}for(let c=0;c<e.length;c++){let u=l.get(e[c].token_address.toLowerCase());u&&(u.icon_image&&(e[c].logo=u.icon_image,e[c].thumbnail=u.icon_image),isNaN(u.price)||(e[c].usd_price=u.price,e[c].usd_value=parseFloat(e[c].balance_formatted||"0")*u.price))}}catch{}return n}async getYieldPricingTokens(e,t){let n=(t??[]).map(s=>String(s??"").trim()).filter(Boolean);if(n.length===0)return[];let o=typeof e=="number"?e:String(e).startsWith("0x")?parseInt(String(e),16):parseInt(String(e),10);if(!Number.isFinite(o))return[];try{let s=`${this.baseUrl}/keyrings/tokens/all/${o}?addresses=${encodeURIComponent(n.join(","))}`,a=await x.get(s);return a.ok?ba(a.data):[]}catch{return[]}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),o=await x.get(n);if(!o.ok)return null;let s=ba(o.data),a=e.toLowerCase()===Em,i=s.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?cl(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let o=this.tokensUrl(t,e.join(",")),s=await x.get(o);if(!s.ok)return n;let a=ba(s.data),i=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&&i.has(c)&&(n[c]=cl(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let s=parseInt(n||Fe,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=su({chainId:s,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await x.get(i);if(!l.ok)throw new Error(E(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(cl)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Fe,n=5,o=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let s=lu[t.toLowerCase()]??[],a=o!=null?o+s.length:n+s.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,a),s.length>0?this.getTokensMetadata(s,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],u=l.status==="fulfilled"?s.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>au(h,t)):[],d=new Set,p=[];for(let h of u){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(h))}let m=[];for(let h of c){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(h))}let g=o!=null?[...p,...m].slice(0,o):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,t),{success:!0,data:g}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(s=>s.tokenAddress&&(s.marketCap==null||s.totalVolume?.["24h"]==null));if(n.length===0)return;let o=await this.getTokensMetadata(n.map(s=>s.tokenAddress),t);for(let s of n){let a=o[s.tokenAddress.toLowerCase()];a&&(s.marketCap==null&&(s.marketCap=Ae(a.market_cap)??Ae(a.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":Ae(a.total_volume)??Ae(a.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let o=parseInt(e,16),s=su({chainId:o,duration:n,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${s?`?${s}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(a);if(!c.ok)throw new Error(E(c));let u=c.data;if(i=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],i.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return i.map(l=>au(l,e))}async getTopGainers(e){let t=e?.chain||Fe,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,o=e?.duration||"24h";try{let s=await this.fetchTopGainers(t,n,o);return await this.enrichTrendingMarketData(s,t),{success:!0,data:s}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}};function j(r,e,t,n=[]){return{target:r,callData:D({abi:e,functionName:t,args:n})}}var En=1e27,wa=10n**27n,ls=31536e3,Nm=10;function Be(r){return Number.isFinite(r)&&r>=0&&r<=Nm?r:null}function ul(r){return Math.expm1(r)}function qe(r,e){return Number(r)/10**e}function cs(r){return new Date(r).toISOString().slice(0,10)}async function Xt(r,e,t){let n=`${t.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${r.token}?range=h&day=${7}`,o=await x.get(n);if(!o.ok)throw new Error(E(o));return{samples:(Array.isArray(o.data)?o.data:o.data?.data||[]).filter(a=>a?.rate!==null&&a?.rate!==void 0).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.rate)})),current:null,rewards:[]}}var ut=class{underlyingCall(e){return j(e.contract,at,"asset")}liveRateCall(e,t){return null}followUpRateCall(e,t){return null}decodeSize(e,t){if(!Number.isInteger(t.decimals)||t.decimals<0)return null;let n=X(e);return n===null?null:qe(n,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:j(e.contract,at,"convertToAssets",[t])}},dt=class extends ut{type="spark";balanceIsUnderlying=!1;sizeCall(e){return j(e.contract,at,"totalAssets")}fetchApy(e,t,n,o){return Xt(e,t,n)}};var dl=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}];var pl=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]},{type:"function",name:"liquidity",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint128"}]},{type:"function",name:"tickSpacing",stateMutability:"view",inputs:[],outputs:[{name:"",type:"int24"}]},{type:"function",name:"fee",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint24"}]},{type:"function",name:"token0",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"token1",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var va=[{type:"function",name:"getReserveData",stateMutability:"view",inputs:[{name:"asset",type:"address"}],outputs:[{name:"reserveData",type:"tuple",components:[{name:"configuration",type:"uint256"},{name:"liquidityIndex",type:"uint128"},{name:"currentLiquidityRate",type:"uint128"}]}]}],Tr=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],ml=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Pt=[{inputs:[],name:"getUtilization",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseToken",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"utilization",type:"uint256"}],name:"getSupplyRate",outputs:[{name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseTrackingSupplySpeed",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseIndexScale",outputs:[{name:"",type:"uint64"}],stateMutability:"pure",type:"function"}],hl=[{inputs:[{name:"comet",type:"address"}],name:"rewardConfig",outputs:[{name:"token",type:"address"},{name:"rescaleFactor",type:"uint64"},{name:"shouldUpscale",type:"bool"}],stateMutability:"view",type:"function"}];var Ar=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],Qt=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],gl=[{inputs:[],name:"susds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var fl=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],yl=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var Lm=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|
|
1
|
+
"use strict";var Rp=Object.create;var ra=Object.defineProperty;var Ep=Object.getOwnPropertyDescriptor;var _p=Object.getOwnPropertyNames;var Np=Object.getPrototypeOf,Lp=Object.prototype.hasOwnProperty;var Ip=(o,e)=>{for(var t in e)ra(o,t,{get:e[t],enumerable:!0})},kc=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _p(e))!Lp.call(o,r)&&r!==t&&ra(o,r,{get:()=>e[r],enumerable:!(n=Ep(e,r))||n.enumerable});return o};var Up=(o,e,t)=>(t=o!=null?Rp(Np(o)):{},kc(e||!o||!o.__esModule?ra(t,"default",{value:o,enumerable:!0}):t,o)),Dp=o=>kc(ra({},"__esModule",{value:!0}),o);var bb={};Ip(bb,{AI_AGENT_TOOL_NAMES:()=>Ai,AbortError:()=>en,AgentCore:()=>Ni,ApproveTokenTool:()=>Yr,BaseNftAiTool:()=>vt,BaseSwapProvider:()=>mn,BaseTool:()=>P,BaseWalletActionTool:()=>Ze,BuyTokenTool:()=>Kr,CachedResource:()=>St,ChatHistory:()=>Xr,CoinpoolConfigApi:()=>Os,DEFAULT_CHAIN:()=>je,DEFAULT_PROVIDER:()=>Ut,DEFAULT_RPC_BY_CHAIN:()=>Ge,DEFILLAMA_EXTRA_SIGNALS:()=>ut,DEFILLAMA_POOL_CHAIN_HEXES:()=>Dr,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION:()=>He,DebridgeProvider:()=>vr,DefiLlamaEstimatePoolYieldTool:()=>$r,DefiLlamaPoolByAddressTool:()=>qr,DefiLlamaPoolCandidateResolver:()=>Hr,DefiLlamaPoolDetailTool:()=>Br,DefiLlamaPoolSearchTool:()=>Fr,DefiLlamaPoolService:()=>Ue,DefiLlamaTopPoolsTool:()=>Mr,EstimatePoolYieldTool:()=>Cr,GeminiProvider:()=>be,GeminiSearchAiTool:()=>dr,HEX_TO_PANTOGRAPH:()=>Nu,KeyringSettingApi:()=>Bs,KnowledgeBase:()=>Jr,LendingMarketDetailTool:()=>tr,LendingMarketsTool:()=>er,LendingReadService:()=>Jo,LendingService:()=>it,LendingSupplyService:()=>Zo,MULTICALL3_ADDRESS:()=>te,ManageLiquidityRedirectTool:()=>zn,MoralisService:()=>U,NATIVE_GAS_LIMIT:()=>ap,NFC_AGENT_TOOL_NAMES:()=>Ti,NFC_AMAZON_DEFAULT_DOMAIN:()=>Xl,NFC_AMAZON_DOMAINS:()=>zl,NFTContractInfoTool:()=>ar,NFTMetadataTool:()=>ir,NFT_AGENT_TOOL_NAMES:()=>vi,NfcBuyTool:()=>ur,NfcInfoTool:()=>cr,NoFormTool:()=>Gs,OpenAddLiquidityFormTool:()=>Gn,OpenSupplyFormTool:()=>or,POOL_UNISWAP_AGENT_TOOL_NAMES:()=>Si,PantographService:()=>Te,PoolByAddressTool:()=>xr,PoolDetailTool:()=>Pr,PoolFallbackAiTool:()=>pr,PoolPriceRangesTool:()=>jn,PoolSearchTool:()=>Sr,PoolService:()=>se,PoolSwapRouter:()=>yr,PreviewAddLiquidityTool:()=>Kn,PublicClient:()=>Un,RelayProvider:()=>fr,Router:()=>Zr,SUPPLIABLE_TYPES:()=>Hl,SUPPORTED_CHAINS:()=>Eo,SUPPORTED_CHAINS_LABEL:()=>No,SWAP_PROVIDER_CONFIG:()=>kr,SendNativeTool:()=>Vr,SendNftTool:()=>zr,SendTokenTool:()=>Wr,Subagent:()=>ee,SubgraphAddPoolTool:()=>Ur,SubgraphCoinPoolPairsTool:()=>Ir,SubgraphPoolByAddressTool:()=>_r,SubgraphPoolByPositionIdTool:()=>Nr,SubgraphPoolSearchTool:()=>Rr,SubgraphPositionDetailTool:()=>Lr,SubgraphTrendingPoolsTool:()=>Er,Summarizer:()=>Qr,SwapProviderFactory:()=>Fs,SwapRouter:()=>gr,SwapRouterRegistry:()=>Ms,SwapTokenTool:()=>jr,Synthesizer:()=>es,TOKEN_AGENT_TOOL_NAMES:()=>ki,TRANSFER_TOPIC:()=>Yd,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Lu,TokenAnalyticsTool:()=>Fo,TokenHoldersTool:()=>Mo,TokenInfoTool:()=>Oo,TokenScoreTool:()=>Bo,ToolRegistry:()=>Ro,TopGainersTool:()=>$o,TopPoolsTool:()=>Ar,TransactionByHashTool:()=>Qo,TrendingTokensTool:()=>qo,UNISWAP_CHAIN_SLUG:()=>$s,UNRESOLVED_ASSET:()=>$n,UpstashKnowledgeBase:()=>bn,UserSwapRouter:()=>br,WALLET_ACTION_AGENT_TOOL_NAMES:()=>xi,WALLET_AGENT_TOOL_NAMES:()=>wi,WalletApprovalsTool:()=>jo,WalletDefiPositionsTool:()=>zo,WalletDefiProtocolPositionsTool:()=>Xo,WalletHistoryTool:()=>Vo,WalletLendingPositionsTool:()=>nr,WalletNFTsTool:()=>sr,WalletNftTransfersTool:()=>Yo,WalletPnlSummaryTool:()=>Go,WalletPnlTool:()=>Ko,WalletTokenBalancesTool:()=>Ho,WalletTokenTransfersTool:()=>Wo,WebsiteTrustKeyringAgent:()=>Li,ZERO_ADDRESS:()=>le,amazonDomainForLanguage:()=>Ql,apiClient:()=>x,applyYieldConversions:()=>$a,buildApprovals:()=>di,buildChallenge:()=>vl,buildRangePresets:()=>tc,buildUniswapPoolUrl:()=>Ye,call:()=>gt,canDeriveV3PoolAddress:()=>ac,chains:()=>Rn,checkNativeGasAffordable:()=>Ws,checksumAddress:()=>eo,clampTick:()=>Pt,clearPublicClientCache:()=>Sa,coinpoolConfigApi:()=>fn,compareDecimal:()=>Zt,completeX402:()=>Tl,configureSupportedChains:()=>Na,configureSwapProvider:()=>ci,convertSusdsShares:()=>qn,createAiAgent:()=>Js,createDefaultSubagents:()=>Ci,createNfcAgent:()=>Qs,createNftAgent:()=>Xs,createPoolUniswapAgent:()=>Zs,createPublicClient:()=>Qt,createTokenAgent:()=>zs,createTransport:()=>zt,createWalletActionAgent:()=>ea,createWalletAgent:()=>js,createX402SignatureProvider:()=>Pl,decodeAbiParameters:()=>_e,decodeErrorResult:()=>so,decodeFunctionData:()=>Xi,decodeFunctionResult:()=>mt,defiLlamaPoolInfoScope:()=>qe,defiLlamaPoolSupportsLabel:()=>$e,deriveV3PoolAddress:()=>ic,displayFromChallenge:()=>vu,effectivePriceUSD:()=>Ns,encodeAbiParameters:()=>no,encodeApprove:()=>ui,encodeErrorResult:()=>Yi,encodeFunctionData:()=>D,encodeSignedHeader:()=>Al,erc1155Abi:()=>wa,erc20Abi:()=>V,erc20Abi_bytes32:()=>fo,erc721Abi:()=>go,estimateGas:()=>mo,estimateNativeGasReserveWei:()=>Hs,estimateTransactionFeeWei:()=>cc,ethCallAt:()=>Wu,ethCallByChain:()=>Qh,exactAmountString:()=>On,extractOutRaw:()=>$d,extractQuoteError:()=>Hd,fallback:()=>Xt,feeWeiToNative:()=>uc,fetchTopMarketplaces:()=>Jl,floorToDecimals:()=>Nt,formatDefiLlamaPool:()=>Re,getAbiItem:()=>Wt,getAddress:()=>qi,getBalance:()=>lo,getBlock:()=>ho,getBlockNumber:()=>ao,getChain:()=>st,getChainContractAddress:()=>ds,getChainId:()=>io,getChainMeta:()=>we,getCode:()=>Yt,getDefaultRpcUrl:()=>dl,getGasPrice:()=>po,getNativeTokenInfo:()=>Tr,getPublicClient:()=>xe,getRevertReason:()=>is,getRpcOverrides:()=>fs,getStorageAt:()=>co,getTokenPriceUSD:()=>Ma,getTransactionCount:()=>uo,http:()=>at,humanToWei:()=>Dn,ingestKnowledgeBase:()=>Sp,isAbortError:()=>Fn,isAddress:()=>E,isAddressEqual:()=>$i,isPaymentRequired:()=>Wm,isShareBasedProtocol:()=>qa,isShareBasedYieldToken:()=>Ou,isSupplyChain:()=>Ga,keyringSettingApi:()=>hn,listCandidateChains:()=>$l,listSupplyChains:()=>Ya,mulDivFloor:()=>Mn,multicall:()=>xo,multicall3Abi:()=>rt,multicallRaw:()=>Kt,nativeGasShortfall:()=>lp,nfcAmazonSearchUrl:()=>ni,normaliseCountry:()=>oi,normalizeDecimal:()=>Co,normalizePriceRangeToPool:()=>hr,parseAbi:()=>el,parseAbiItem:()=>ya,parseAbiParameters:()=>cs,pickLogo:()=>Dt,planYieldTokenConversions:()=>Fl,priceToTick:()=>Wn,protocolLabelFor:()=>We,psm3For:()=>Ba,readContract:()=>yt,readPaymentError:()=>wu,readPaymentRequired:()=>Ra,readProtocolFeeWei:()=>pi,readReceipt:()=>ku,readSpendableBalance:()=>Ys,registerMaybeNoForm:()=>bi,requestWithX402:()=>Vm,resolveGasLimit:()=>ip,resolveNfcShopLinks:()=>lr,resolveRpcUrl:()=>In,resolveRpcUrls:()=>Ln,resolveTokenPriceUSD:()=>Fu,roundTickToSpacing:()=>At,rpcCall:()=>Vu,setRpcOverrides:()=>Nn,spendableNative:()=>Vs,swapProviderFactory:()=>wr,swapRouterRegistry:()=>li,tickToPrice:()=>lt,toEventSelector:()=>Hi,toFunctionSelector:()=>_t,toPantographChain:()=>lh,toPlainDecimal:()=>ys,valueYieldTokens:()=>Ha,weiToHuman:()=>Ca});module.exports=Dp(bb);var Tc=Up(require("axios"));var vc="0.3.7";var Mp=`keyring-agent-core/${vc} (Keyring Chatbot Agent; +https://keyring.app)`,Ui=null;function Ac(o){Ui=o}var Fp=["payment-signature","x-payment"];function Bp(o){return o?Object.keys(o).some(e=>Fp.includes(e.toLowerCase())):!1}var Pc;function os(o){Pc=o}var qp=3e4,$p=typeof process<"u"&&process.versions?.node!=null,Di=class{instance;constructor(e={}){this.instance=Tc.default.create({baseURL:e.baseURL,timeout:e.timeout??qp,validateStatus:()=>!0,headers:{Accept:"application/json",...$p?{"Accept-Encoding":"gzip, deflate, br","User-Agent":e.userAgent??Mp}:{},...e.headers}})}async request(e,t,n,r={}){let s=r.signal??Pc,a=await this.instance.request({...r,signal:s,method:e,url:t,data:n}),i={};for(let[c,d]of Object.entries(a.headers??{}))d!=null&&(i[c.toLowerCase()]=String(d));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:i};if(l.status===402&&Ui&&!Bp(r.headers)){let c=await Ui(l,{url:t,method:String(e),body:n,headers:r.headers});if(c)return this.request(e,t,n,{...r,headers:{...r.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Di;function _(o){let{data:e,status:t,statusText:n}=o,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let s=e,a=l=>l&&typeof l=="object"?l.message:void 0,i=[s.message,s.errorMessage,s.error,s.error_description,s.detail,a(s.error),a(s.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}function Hp(o){return o instanceof B?o.details||o.shortMessage:o instanceof Error?o.message:typeof o=="string"?o:""}var B=class extends Error{name="BaseError";shortMessage;details;metaMessages;constructor(e,t={}){let n=t.details??Hp(t.cause),r=t.metaMessages??[],s=[e||"An error occurred.",...r.length>0?["",...r]:[],...n?["",`Details: ${n}`]:[]].join(`
|
|
2
|
+
`);super(s,t.cause!==void 0?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n,this.metaMessages=r,t.name&&(this.name=t.name)}walk(e){return Sc(this,e)}};function Sc(o,e){if(e?.(o))return o;let t=o&&typeof o=="object"?o.cause:void 0;return t!=null?Sc(t,e):e?null:o}var Ft=class extends B{name="AbiParameterTypeError";constructor(e){super(`Type "${e}" is not a valid ABI type.`,{metaMessages:["Supported: address, bool, string, bytes, bytesN, (u)intN, tuple, and arrays of those."]})}},sa=class extends B{name="AbiEncodingLengthMismatchError";constructor({expectedLength:e,givenLength:t}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${e}`,`Given length (values): ${t}`]})}},aa=class extends B{name="AbiEncodingArrayLengthMismatchError";constructor({expectedLength:e,givenLength:t,type:n}){super(`ABI encoding array length mismatch for type ${n}.`,{metaMessages:[`Expected length: ${e}`,`Given length: ${t}`]})}},nt=class extends B{name="InvalidAbiValueError";constructor({type:e,value:t,reason:n}){super(`Invalid value for ABI type "${e}".`,{metaMessages:[`Value: ${xc(t)}`,`Reason: ${n}`]})}},ia=class extends B{name="IntegerOutOfRangeError";constructor({type:e,value:t,min:n,max:r}){super(`Number "${t}" is not in safe ${e} range.`,{metaMessages:[`Range: ${n} \u2026 ${r}`]})}},Qn=class extends B{name="InvalidAddressError";constructor(e){super(`Address "${xc(e)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function xc(o){if(typeof o=="bigint")return o.toString();if(typeof o=="string")return o;try{return JSON.stringify(o)??String(o)}catch{return String(o)}}var la=class extends B{name="AbiEncodingBytesSizeMismatchError";constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" does not match expected size of bytes${e}.`)}},Bt=class extends B{name="AbiDecodingZeroDataError";constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{metaMessages:["The contract returned no data. Usually this means:","- the address is not a contract on this chain,","- the function does not exist on it, or","- the call was made before the contract was deployed."]})}},ca=class extends B{name="AbiDecodingDataSizeTooSmallError";data;params;size;constructor({data:e,params:t,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${t.map(r=>r.type).join(", ")})`,`Data: ${e} (${n} bytes)`]}),this.data=e,this.params=t,this.size=n}},Jn=class extends B{name="AbiDecodingOutOfBoundsError";constructor({position:e,length:t}){super(`Position ${e} is out of bounds (${t} bytes).`,{metaMessages:["The return data is truncated or not ABI-encoded."]})}},ua=class extends B{name="AbiItemNotFoundError";constructor({name:e,type:t="function"}){super(`${t[0].toUpperCase()}${t.slice(1)} "${e}" not found on ABI.`,{metaMessages:["Make sure you are using the correct ABI and that the item exists on it."]})}},qt=class extends B{name="InvalidAbiSignatureError";constructor(e,t){super(`Invalid ABI signature: "${e}".`,{metaMessages:t?[t]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']})}};var Vp=/^0x[0-9a-fA-F]*$/;function An(o,{strict:e=!0}={}){return typeof o!="string"?!1:e?Vp.test(o):o.startsWith("0x")}function pt(o){return o.startsWith("0x")||o.startsWith("0X")?o.slice(2):o}function rs(o){return typeof o=="string"?Math.ceil(pt(o).length/2):o.length}function Pn(o,e,t){let n=pt(o),r=(e??0)*2,s=t===void 0?n.length:t*2;return`0x${n.slice(r,s)}`}function da(o){return`0x${o.map(pt).join("")}`}function Sn(o){let e=new Uint8Array(o.reduce((n,r)=>n+r.length,0)),t=0;for(let n of o)e.set(n,t),t+=n.length;return e}function $t(o){let e=pt(o),t=e.length%2?`0${e}`:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function Et(o){let e="";for(let t of o)e+=t.toString(16).padStart(2,"0");return`0x${e}`}function Oi(o){return new TextEncoder().encode(o)}function Mi(o){return new TextDecoder().decode(o)}function Oe(o,e={}){let{size:t,signed:n}=e,r=BigInt(o);if(r<0n){if(!t)throw new Error("numberToHex: negative values require a `size`");r+=1n<<BigInt(t*8)}else if(n&&t){let a=(1n<<BigInt(t*8-1))-1n;if(r>a)throw new Error(`numberToHex: ${o} overflows int${t*8}`)}let s=r.toString(16);if(!t)return`0x${s}`;if(s.length>t*2)throw new Error(`numberToHex: ${o} overflows ${t} bytes`);return`0x${s.padStart(t*2,"0")}`}function Fi(o,e=32){if(o.length>e)throw new Error(`padLeft: ${o.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(o,e-o.length),t}function Bi(o,e=32){if(o.length>e)throw new Error(`padRight: ${o.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(o),t}function xn(o){let e=1n<<256n,t=(o%e+e)%e;return $t(t.toString(16).padStart(64,"0"))}function Zn(o,{signed:e=!1}={}){let t=BigInt(Et(o));if(!e)return t;let n=BigInt(o.length*8);return t>=1n<<n-1n?t-(1n<<n):t}function ot(o,{signed:e=!1}={}){return pt(o)?Zn($t(o),{signed:e}):0n}function pa(o,e={}){return Number(ot(o,e))}var Cc=require("js-sha3");var Wp=/^0x[0-9a-fA-F]{40}$/;function E(o){return typeof o=="string"&&Wp.test(o)}function eo(o){let e=pt(o).toLowerCase(),t=(0,Cc.keccak_256)(e),n="";for(let r=0;r<e.length;r++)n+=parseInt(t[r],16)>=8?e[r].toUpperCase():e[r];return`0x${n}`}function qi(o){if(!E(o))throw new Error(`Address "${o}" is invalid.`);return eo(o)}function $i(o,e){return E(o)&&E(e)&&o.toLowerCase()===e.toLowerCase()}var ma=require("js-sha3");function ha(o){return`0x${(0,ma.keccak_256)(o)}`}function Rc(o){return`0x${(0,ma.keccak_256)(new TextEncoder().encode(o))}`}function Ht(o){let e=o.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Vt(o){return o.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function ss(o){let e=Vt(o.type);return e==="tuple"||e.startsWith("tuple[")?`(${(o.components??[]).map(ss).join(",")})${e.slice(5)}`:e}function to(o){return`${o.name??""}(${(o.inputs??[]).map(ss).join(",")})`}function _t(o){let e=typeof o=="string"?o:to(o);return`0x${(0,ma.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function Hi(o){let e=typeof o=="string"?o:to(o);return Rc(e)}function Ec(o,e){let t=Vt(e.type),n=Ht(t);if(n){let[r,s]=n;return!Array.isArray(o)||r!==null&&o.length!==r?!1:o.every(a=>Ec(a,{...e,type:s}))}if(t==="tuple"){let r=e.components??[];return Array.isArray(o)?o.length===r.length:typeof o=="object"&&o!==null}return t==="address"?typeof o=="string"&&/^0x[0-9a-fA-F]{40}$/.test(o):t==="bool"?typeof o=="boolean":t==="string"?typeof o=="string":t.startsWith("bytes")?typeof o=="string"||o instanceof Uint8Array:t.startsWith("uint")||t.startsWith("int")?typeof o=="number"||typeof o=="bigint"||typeof o=="string":!0}function Wt({abi:o,name:e,args:t,type:n}){let r=n??"function",s=o.filter(i=>(i.type??"function")===r);if(e.startsWith("0x")&&e.length===10)return s.find(i=>_t(i)===e.toLowerCase());if(e.includes("("))return s.find(i=>to(i)===e);let a=s.filter(i=>i.name===e);return a.length<=1||!t?a[0]:a.find(i=>{let l=i.inputs??[];return l.length===t.length&&l.every((c,d)=>Ec(t[d],c))})??a[0]}function Cn(o){let e=Wt(o);if(!e)throw new ua({name:o.name,type:o.type??"function"});return e}function _c(o){let e=new Uint8Array(Math.ceil(o.length/32)*32);return e.set(o),{dynamic:!0,encoded:Sn([xn(BigInt(o.length)),e])}}function Nc(o,e){let t=o.slice(e.length),n=t===""?256:Number(t);if(!Number.isInteger(n)||n<8||n>256||n%8!==0)throw new Ft(o);return n}function Lc(o,e){if(typeof o=="bigint")return o;if(typeof o=="number"){if(!Number.isInteger(o))throw new nt({type:e,value:o,reason:"expected an integer, got a fractional number"});return BigInt(o)}if(typeof o=="string"&&o.trim()!=="")try{return BigInt(o.trim())}catch{throw new nt({type:e,value:o,reason:"string is not a valid integer"})}throw new nt({type:e,value:o,reason:"expected a bigint, number or numeric string"})}function Ic(o,{bits:e,signed:t,type:n}){let r=t?(1n<<BigInt(e-1))-1n:(1n<<BigInt(e))-1n,s=t?-(1n<<BigInt(e-1)):0n;if(o<s||o>r)throw new ia({type:n,value:o,min:s,max:r})}function Uc(o,e){if(o instanceof Uint8Array)return o;if(typeof o=="string"){if(!An(o))throw new nt({type:e,value:o,reason:"expected 0x-prefixed hex"});return $t(o)}throw new nt({type:e,value:o,reason:"expected a hex string or Uint8Array"})}function Vi(o,e){let t=Ht(o.type);if(t){let[r,s]=t;if(!Array.isArray(e))throw new nt({type:o.type,value:e,reason:"expected an array"});return Yp({...o,type:s},e,r,o.type)}if(o.type==="tuple")return Gp(o,e);let n=Vt(o.type);if(n==="address"){if(!E(e))throw new Qn(e);return{dynamic:!1,encoded:Fi($t(pt(e).toLowerCase()))}}if(n==="bool"){if(typeof e!="boolean")throw new nt({type:n,value:e,reason:"expected a boolean"});let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}if(/^uint\d*$/.test(n)){let r=Lc(e,n);return Ic(r,{bits:Nc(n,"uint"),signed:!1,type:n}),{dynamic:!1,encoded:xn(r)}}if(/^int\d*$/.test(n)){let r=Lc(e,n);return Ic(r,{bits:Nc(n,"int"),signed:!0,type:n}),r<0n&&(r+=1n<<256n),{dynamic:!1,encoded:xn(r)}}if(/^bytes\d+$/.test(n)){let r=Number(n.slice(5));if(r<1||r>32)throw new Ft(o.type);let s=Uc(e,n);if(s.length!==r)throw new la({expectedSize:r,value:String(e)});return{dynamic:!1,encoded:Bi(s)}}if(n==="bytes")return _c(Uc(e,n));if(n==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new nt({type:n,value:e,reason:"expected a string"});return _c(typeof e=="string"?Oi(e):e)}throw new Ft(o.type)}function Wi(o){let e=0;for(let{dynamic:s,encoded:a}of o)e+=s?32:a.length;let t=[],n=[],r=0;for(let{dynamic:s,encoded:a}of o)s?(t.push(xn(BigInt(e+r))),n.push(a),r+=a.length):t.push(a);return Sn([...t,...n])}function Yp(o,e,t,n){let r=t===null;if(!r&&e.length!==t)throw new aa({expectedLength:t,givenLength:e.length,type:n});let s=!1,a=[];for(let i of e){let l=Vi(o,i);l.dynamic&&(s=!0),a.push(l)}if(r||s){let i=Wi(a);if(!r)return{dynamic:!0,encoded:i};let l=xn(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?Sn([l,i]):l}}return{dynamic:!1,encoded:Sn(a.map(i=>i.encoded))}}function Gp(o,e){let t=o.components??[],n=!1,r=[];for(let s=0;s<t.length;s++){let a=t[s],i=Vi(a,Array.isArray(e)?e[s]:e[a.name??""]);i.dynamic&&(n=!0),r.push(i)}return{dynamic:n,encoded:n?Wi(r):Sn(r.map(s=>s.encoded))}}function no(o,e){if(o.length!==e.length)throw new sa({expectedLength:o.length,givenLength:e.length});return o.length===0?"0x":Et(Wi(o.map((t,n)=>Vi(t,e[n]))))}function D({abi:o,functionName:e,args:t=[]}){let n=Cn({abi:o,name:e,args:t,type:"function"}),r=_t(n),s=n.inputs??[];return s.length===0?r:da([r,no(s,t)])}function Yi({abi:o,errorName:e,args:t=[]}){let n=Cn({abi:o,name:e,args:t,type:"error"}),r=n.inputs??[],s=_t(n);return r.length===0?s:da([s,no(r,t)])}function Kp(o){let e=o.replace(/^u?int/,"");return e?Number(e):256}function as(o,e){if(e<0||e+32>o.length)throw new Jn({position:e,length:o.length});return o.subarray(e,e+32)}function ji(o,e){let t=Zn(as(o,e));if(t>BigInt(o.length))throw new Jn({position:Number(t),length:o.length});return Number(t)}function Gi(o){let e=Ht(o.type);if(e){let[n,r]=e;return n===null||Gi({...o,type:r})}if(o.type==="tuple")return(o.components??[]).some(Gi);let t=Vt(o.type);return t==="bytes"||t==="string"}function Ki(o){let e=Ht(o.type);if(e){let[t,n]=e;return t===null?32:t*Ki({...o,type:n})}return o.type==="tuple"?(o.components??[]).reduce((t,n)=>t+Ki(n),0):32}function zi(o,e,t){let n=[],r=e;for(let s of t)Gi(s)?(n.push(Dc(o,e+ji(o,r),s)),r+=32):(n.push(Dc(o,r,s)),r+=Ki(s));return n}function jp(o,e,t,n){let r=n===null?ji(o,e):n,s=n===null?e+32:e;return zi(o,s,new Array(r).fill(t))}function zp(o,e,t){let n=t.components??[],r=zi(o,e,n);if(n.length===0||n.some(i=>!i.name))return r;let a={};return n.forEach((i,l)=>{a[i.name]=r[l]}),a}function Dc(o,e,t){let n=Ht(t.type);if(n){let[s,a]=n;return jp(o,e,{...t,type:a},s)}if(t.type==="tuple")return zp(o,e,t);let r=Vt(t.type);if(r==="address")return eo(Et(as(o,e).subarray(12)));if(r==="bool")return Zn(as(o,e))!==0n;if(/^u?int\d*$/.test(r)){let s=r.startsWith("int"),a=Zn(as(o,e),{signed:s});return Kp(r)>48?a:Number(a)}if(/^bytes\d+$/.test(r)){let s=Number(r.slice(5));return Et(as(o,e).subarray(0,s))}if(r==="bytes"||r==="string"){let s=ji(o,e),a=e+32;if(a+s>o.length)throw new Jn({position:a+s,length:o.length});let i=o.subarray(a,a+s);return r==="bytes"?Et(i):Mi(i)}throw new Ft(t.type)}function _e(o,e){let t=typeof e=="string"?$t(e):e;if(t.length===0){if(o.length>0)throw new Bt;return[]}if(t.length<32)throw new ca({data:typeof e=="string"?e:Et(e),params:o,size:t.length});return zi(t,0,o)}function J(o){if(!o)return null;try{let[e]=_e([{type:"uint256"}],o);return e}catch{return null}}function q(o){if(!o)return null;try{let[e]=_e([{type:"address"}],o),t=e;return/^0x0{40}$/i.test(t)?null:t}catch{return null}}function oo(o){if(!o)return null;try{let[e]=_e([{type:"string"}],o),t=Oc(e);if(t)return t}catch{}try{let[e]=_e([{type:"bytes32"}],o);return ga(e)}catch{return null}}function ro(o){return fa(J(o))}function fa(o){let e=typeof o=="bigint"?Number(o):typeof o=="number"?o:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function ga(o){return typeof o!="string"||!o.startsWith("0x")?null:Oc(Buffer.from(o.slice(2),"hex").toString("utf8"))||null}function Oc(o){return o.replace(/[^\x20-\x7e]/g,"").trim()}function mt({abi:o,functionName:e,args:t,data:n}){let s=Cn({abi:o,name:e,args:t,type:"function"}).outputs??[],a=_e(s,n);if(a.length!==0)return a.length===1?a[0]:a}function Xi({abi:o,data:e}){let t=Pn(e,0,4),n=Cn({abi:o,name:t,type:"function"}),r=n.inputs??[];return{functionName:n.name,args:r.length===0||rs(e)<=4?[]:_e(r,Pn(e,4))}}var Mc={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},Fc={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},Bc={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array.",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."};function so({abi:o=[],data:e}){let t=Pn(e,0,4);if(rs(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let n=[...o,Mc,Fc],r=Wt({abi:n,name:t,type:"error"})??n.find(a=>(a.type??"")==="error"&&_t(a)===t);if(!r)throw new Error(`Unknown error selector "${t}".`);let s=r.inputs??[];return{abiItem:r,errorName:r.name,args:s.length>0?_e(s,Pn(e,4)):void 0}}function is({abi:o,data:e}){if(!(!e||e==="0x"))try{let{errorName:t,args:n}=so({abi:o,data:e});if(t==="Error")return String(n?.[0]??"");if(t==="Panic"){let r=Number(n?.[0]??0);return Bc[r]??`Panic code ${r}.`}return!n||n.length===0?t:`${t}(${n.map(r=>String(r)).join(", ")})`}catch{return}}var Xp=new Set(["pure","view","nonpayable","payable"]),Qp=new Set(["external","public","internal","private","calldata","memory","storage"]);function Ji(o,e){let t=0;for(let n=e;n<o.length;n++)if(o[n]==="(")t++;else if(o[n]===")"&&(t--,t===0))return n;throw new qt(o,"Unbalanced parentheses.")}function $c(o){let e=[],t=0,n="";for(let r of o){if(r==="("&&t++,r===")"&&t--,r===","&&t===0){e.push(n),n="";continue}n+=r}return n.trim()&&e.push(n),e.map(r=>r.trim()).filter(Boolean)}function Jp(o){let e=o.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function qc(o,e){let t=!1,n;for(let r of o)r==="indexed"?t=!0:Qp.has(r)||(n=r);return{...e,...n?{name:n}:{},...t?{indexed:!0}:{}}}function Zi(o){let e=o.trim();if(e.startsWith("(")){let r=Ji(e,0),s=$c(e.slice(1,r)).map(Zi),{suffix:a,rest:i}=Jp(e.slice(r+1).trim());return qc(i.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:s})}let[t,...n]=e.split(/\s+/).filter(Boolean);if(!t)throw new qt(o,"Missing parameter type.");return qc(n,{type:t})}function cs(o){return $c(o).map(Zi)}function ls(o,e,t){let n=o.indexOf("(",e);if(n===-1)throw new qt(t,"Missing parameter list.");let r=Ji(o,n);return{name:o.slice(e,n).trim(),params:cs(o.slice(n+1,r)),rest:o.slice(r+1).trim()}}function Qi(o,e){return o.split(/[\s()]+/).find(n=>Xp.has(n))??e}function ya(o){let e=o.trim();if(e.startsWith("function ")){let{name:t,params:n,rest:r}=ls(e,9,o),s=r.indexOf("returns"),a=s===-1?r:r.slice(0,s),i=[];if(s!==-1){let l=r.indexOf("(",s);if(l===-1)throw new qt(o,"`returns` without a parameter list.");i=cs(r.slice(l+1,Ji(r,l)))}return{type:"function",name:t,inputs:n,outputs:i,stateMutability:Qi(a,"nonpayable")}}if(e.startsWith("event ")){let{name:t,params:n}=ls(e,6,o);return{type:"event",name:t,inputs:n}}if(e.startsWith("error ")){let{name:t,params:n}=ls(e,6,o);return{type:"error",name:t,inputs:n}}if(e.startsWith("constructor")){let{params:t,rest:n}=ls(e,11,o);return{type:"constructor",inputs:t,stateMutability:Qi(n,"nonpayable")}}if(e.startsWith("fallback")){let{rest:t}=ls(e,8,o);return{type:"fallback",stateMutability:Qi(t,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new qt(o,"Expected function, event, error, constructor, fallback or receive.")}function el(o){return o.map(ya)}function ht({blockNumber:o,blockTag:e="latest"}={}){return o!==void 0?Oe(o):e}function us(o){let{account:e,to:t,data:n,value:r,gas:s,gasPrice:a,maxFeePerGas:i,maxPriorityFeePerGas:l,nonce:c}=o,d={};return e&&(d.from=e),t&&(d.to=t),n&&(d.data=n),r!==void 0&&(d.value=Oe(r)),s!==void 0&&(d.gas=Oe(s)),a!==void 0&&(d.gasPrice=Oe(a)),i!==void 0&&(d.maxFeePerGas=Oe(i)),l!==void 0&&(d.maxPriorityFeePerGas=Oe(l)),c!==void 0&&(d.nonce=Oe(c)),d}function tl(o){let e={};for(let[t,n]of Object.entries(o)){let r={};n.balance!==void 0&&(r.balance=Oe(n.balance)),n.nonce!==void 0&&(r.nonce=Oe(n.nonce)),n.code!==void 0&&(r.code=n.code),n.state&&(r.state=n.state),n.stateDiff&&(r.stateDiff=n.stateDiff),e[t]=r}return e}async function ao(o){return ot(await o.request({method:"eth_blockNumber"}))}async function io(o){return pa(await o.request({method:"eth_chainId"}))}async function lo(o,{address:e,...t}){return ot(await o.request({method:"eth_getBalance",params:[e,ht(t)]}))}async function Yt(o,{address:e,...t}){let n=await o.request({method:"eth_getCode",params:[e,ht(t)]});return!n||n==="0x"?void 0:n}async function co(o,{address:e,slot:t,...n}){return await o.request({method:"eth_getStorageAt",params:[e,t,ht(n)]})??void 0}async function uo(o,{address:e,...t}){return pa(await o.request({method:"eth_getTransactionCount",params:[e,ht(t)]}))}async function po(o){return ot(await o.request({method:"eth_gasPrice"}))}async function ba(o){return ot(await o.request({method:"eth_maxPriorityFeePerGas"}))}async function mo(o,{blockNumber:e,blockTag:t,...n}){return ot(await o.request({method:"eth_estimateGas",params:[us(n),ht({blockNumber:e,blockTag:t})]}))}async function ho(o,{includeTransactions:e=!1,...t}={}){let n=await o.request({method:"eth_getBlockByNumber",params:[ht(t),e]});return n?{...n,blockNumber:n.number?ot(n.number):void 0,blockTimestamp:n.timestamp?ot(n.timestamp):void 0,baseFee:n.baseFeePerGas?ot(n.baseFeePerGas):void 0}:null}var te="0xcA11bde05977b3631167028862bE2a173976CA11",Hc={id:1,hexId:"0x1",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io"}},contracts:{multicall3:{address:te,blockCreated:14353601}}},Vc={id:10,hexId:"0xa",name:"Optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io","https://optimism-rpc.publicnode.com","https://optimism.drpc.org"]}},blockExplorers:{default:{name:"Optimistic Etherscan",url:"https://optimistic.etherscan.io"}},contracts:{multicall3:{address:te,blockCreated:4286263}}},Wc={id:56,hexId:"0x38",name:"BSC",nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18},rpcUrls:{default:{http:["https://bsc-dataseed.binance.org","https://bsc-rpc.publicnode.com","https://bsc.drpc.org"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com"}},contracts:{multicall3:{address:te}}},Yc={id:137,hexId:"0x89",name:"Polygon",nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com"}},contracts:{multicall3:{address:te,blockCreated:25770160}}},Gc={id:8453,hexId:"0x2105",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org","https://base-rpc.publicnode.com","https://base.drpc.org"]}},blockExplorers:{default:{name:"BaseScan",url:"https://basescan.org"}},contracts:{multicall3:{address:te,blockCreated:5022}}},Kc={id:42161,hexId:"0xa4b1",name:"Arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc","https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io"}},contracts:{multicall3:{address:te,blockCreated:7654707}}},jc={id:43114,hexId:"0xa86a",name:"Avalanche",nativeCurrency:{name:"Avalanche",symbol:"AVAX",decimals:18},rpcUrls:{default:{http:["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io"}},contracts:{multicall3:{address:te}}},zc={id:59144,hexId:"0xe708",name:"Linea",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build","https://linea-rpc.publicnode.com","https://linea.drpc.org"]}},blockExplorers:{default:{name:"LineaScan",url:"https://lineascan.build"}},contracts:{multicall3:{address:te}}},Xc={id:100,hexId:"0x64",name:"Gnosis",nativeCurrency:{name:"xDAI",symbol:"XDAI",decimals:18},rpcUrls:{default:{http:["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"]}},blockExplorers:{default:{name:"Gnosisscan",url:"https://gnosisscan.io"}},contracts:{multicall3:{address:te}}},Qc={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:te}}},Jc={id:5e3,hexId:"0x1388",name:"Mantle",nativeCurrency:{name:"Mantle",symbol:"MNT",decimals:18},rpcUrls:{default:{http:["https://rpc.mantle.xyz","https://mantle-rpc.publicnode.com"]}},blockExplorers:{default:{name:"Mantle Explorer",url:"https://explorer.mantle.xyz"}},contracts:{multicall3:{address:te}}},Zc={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:te}}},Rn=[Hc,Vc,Wc,Yc,Gc,Kc,jc,zc,Xc,Qc,Jc,Zc];var eu=new Map,nl=new Map;function Zp(o,e){return`${o??"unknown"}|${e.toLowerCase()}`}async function tu(o,e=te){let t=Zp(o.chain?.id??o.chain?.hexId,e),n=eu.get(t);if(n!==void 0)return n;let r=nl.get(t);if(r)return r;let s=(async()=>{try{let i=await Yt(o,{address:e})!==void 0;return eu.set(t,i),i}catch{return!0}finally{nl.delete(t)}})();return nl.set(t,s),s}async function En(o,e,t=!1){return t||typeof o.batch?.multicall=="object"&&o.batch.multicall.assumeMulticall3?!0:tu(o,e)}var rt=[{type:"function",name:"aggregate3",stateMutability:"payable",inputs:[{name:"calls",type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],outputs:[{name:"returnData",type:"tuple[]",components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}]}]},{type:"function",name:"getEthBalance",stateMutability:"view",inputs:[{name:"addr",type:"address"}],outputs:[{name:"balance",type:"uint256"}]},{type:"function",name:"getBlockNumber",stateMutability:"view",inputs:[],outputs:[{name:"blockNumber",type:"uint256"}]},{type:"function",name:"getCurrentBlockTimestamp",stateMutability:"view",inputs:[],outputs:[{name:"timestamp",type:"uint256"}]}];var V=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint8"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{name:"from",type:"address",indexed:!0},{name:"to",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]},{type:"event",name:"Approval",inputs:[{name:"owner",type:"address",indexed:!0},{name:"spender",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]}],fo=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];var go=[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"address"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]}];var wa=[{type:"function",name:"uri",stateMutability:"view",inputs:[{name:"id",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"},{name:"id",type:"uint256"}],outputs:[{name:"",type:"uint256"}]}];var ft=[{type:"function",name:"asset",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"totalAssets",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"convertToAssets",stateMutability:"view",inputs:[{name:"shares",type:"uint256"}],outputs:[{name:"assets",type:"uint256"}]},{type:"function",name:"convertToShares",stateMutability:"view",inputs:[{name:"assets",type:"uint256"}],outputs:[{name:"shares",type:"uint256"}]}];var yo=class extends B{name="ChainNotFoundError";constructor(e){super(`Chain "${e}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]})}},_n=class extends B{name="ClientChainNotConfiguredError";constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]})}},Gt=class extends B{name="ChainDoesNotSupportContractError";constructor({chain:e,contract:t,blockNumber:n}){super(n!==void 0?`Chain "${e}" does not support contract "${t}" at block ${n}.`:`Chain "${e}" does not support contract "${t}".`,{metaMessages:["Pass the contract address explicitly to use it on this chain."]})}};async function ol(o,e,t){let n=new Array(o.length);if(o.length===0)return n;let r=0,s=Math.max(1,Math.min(e>0?e:o.length,o.length));async function a(){for(;;){let i=r++;if(i>=o.length)return;try{n[i]={status:"fulfilled",value:await t(o[i],i)}}catch(l){n[i]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:s},a)),n}function ds({blockNumber:o,chain:e,contract:t}){let n=e.contracts?.[t];if(!n)throw new Gt({chain:e.name,contract:t});if(o!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(o))throw new Gt({blockNumber:o,chain:e.name,contract:t});return n.address}var bo=class extends B{name="RawContractError";data;constructor({data:e,shortMessage:t="The contract call reverted."}){super(t),this.data=e}},rl=class extends B{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:e,data:t,functionName:n}){let r=t?is({abi:e,data:t}):void 0,s,a;if(t&&t!=="0x")try{let i=so({abi:e,data:t});s=i.errorName,a=i.args}catch{}super(r?`The contract function "${n??"call"}" reverted with the following reason:
|
|
3
|
+
${r}`:`The contract function "${n??"call"}" reverted.`,{metaMessages:t&&t!=="0x"?[`Revert data: ${t}`]:[]}),this.reason=r,this.errorName=s,this.errorArgs=a,this.data=t}},sl=class extends B{name="ContractFunctionZeroDataError";constructor({functionName:e}){super(`The contract function "${e??"call"}" returned no data ("0x").`,{metaMessages:["This usually means:","- the address is not a contract on this chain,","- the ABI does not match the deployed contract, or","- the block predates the contract deployment."]})}},al=class extends B{name="ContractFunctionExecutionError";abi;address;args;functionName;constructor(e,{abi:t,address:n,args:r,functionName:s,sender:a}){let i=t&&s?Wt({abi:t,name:s,args:r}):void 0,l=i?to(i):s,c=r&&r.length>0?` args: (${r.map(u=>em(u)).join(", ")})`:void 0,d=i?.inputs?.length?`(${i.inputs.map(ss).join(", ")})`:"()";super(e instanceof B?e.shortMessage:`An error occurred calling "${s??"contract"}".`,{cause:e,metaMessages:[...n?[`Contract: ${n}`]:[],...l?[`Function: ${l}${i?"":d}`]:[],...c?[c]:[],...a?[`Sender: ${a}`]:[]]}),this.abi=t,this.address=n,this.args=r,this.functionName=s}},ps=class extends B{name="CallExecutionError";constructor(e,{to:t,data:n}){super(e instanceof B?e.shortMessage:"The call failed.",{cause:e,metaMessages:[...t?[`To: ${t}`]:[],...n?[`Data: ${n}`]:[]]})}};function em(o){if(typeof o=="bigint")return o.toString();if(typeof o=="string")return o;try{return JSON.stringify(o,(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return String(o)}}function nu(o){if(!o||typeof o!="object")return;let e=o,t=e.data;if(typeof t=="string"&&t.startsWith("0x"))return t;if(t&&typeof t=="object"){let n=t.data;if(typeof n=="string"&&n.startsWith("0x"))return n}return e.cause?nu(e.cause):void 0}function wo(o,{abi:e,address:t,args:n,functionName:r,sender:s}){let a=nu(o),i=o instanceof Bt?new sl({functionName:r}):a!==void 0?new rl({abi:e,data:a,functionName:r}):o;return new al(i,{abi:e,address:t,args:n,functionName:r,sender:s})}var il=new Map;function ms({fn:o,id:e,shouldSplitBatch:t,wait:n=0}){let r=()=>il.get(e)??void 0,s=i=>il.set(e,i),a=async i=>{r()===i&&il.delete(e);try{let l=await o(i.map(c=>c.item));i.forEach((c,d)=>c.resolve(l[d]))}catch(l){i.forEach(c=>c.reject(l))}};return{schedule(i){return new Promise((l,c)=>{let d={item:i,resolve:l,reject:c},u=r();if(u)if(t?.([...u.map(m=>m.item),i]))a(u);else{u.push(d);return}let p=[d];s(p),setTimeout(()=>{a(p)},n)})}}}function tm(o){return!!(o.data&&o.to&&!o.account&&!o.value&&!o.gas&&!o.gasPrice&&!o.maxFeePerGas&&!o.maxPriorityFeePerGas&&o.nonce===void 0&&!o.stateOverride)}async function nm(o,e){let{batchSize:t=1024,wait:n=0}=typeof o.batch?.multicall=="object"?o.batch.multicall:{},{blockNumber:r,blockTag:s="latest",data:a,to:i}=e;if(!o.chain)throw new _n;let l=ds({blockNumber:r,chain:o.chain,contract:"multicall3"});if(!await En(o,l,!1))throw new Gt({chain:o.chain.name,contract:"multicall3"});let c=r!==void 0?Oe(r):s,{schedule:d}=ms({id:`${o.uid}.call.${c}`,wait:n,shouldSplitBatch:m=>m.reduce((f,h)=>f+(h.data.length-2)/2,0)>t,fn:async m=>{let f=D({abi:rt,functionName:"aggregate3",args:[m.map(g=>({allowFailure:!0,callData:g.data,target:g.to}))]}),h=await o.request({method:"eth_call",params:[{to:l,data:f},c]});return mt({abi:rt,functionName:"aggregate3",data:h})}}),{returnData:u,success:p}=await d({data:a,to:i});if(!p)throw new bo({data:u});return u}async function gt(o,e){let{blockNumber:t,blockTag:n,stateOverride:r,skipBatch:s,...a}=e;if(o.batch?.multicall&&!s&&tm(e))try{let l=await nm(o,{blockNumber:t,blockTag:n,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof _n||l instanceof Gt))throw new ps(l,{to:a.to,data:a.data})}let i=[us(a),ht({blockNumber:t,blockTag:n})];r&&i.push(tl(r));try{let l=await o.request({method:"eth_call",params:i});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new ps(l,{to:a.to,data:a.data})}}var ll=8;function ou(o,e){if(e!==void 0&&e>0)return e;let t=typeof o.batch?.multicall=="object"?o.batch.multicall.fallbackConcurrency:void 0;return t!==void 0&&t>0?t:ll}function hs(o,e,t){if(e)return e;if(!o.chain)throw new _n;let n=o.chain.contracts?.multicall3;return n?t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(t)?te:n.address:te}async function ko(o,e,t={}){let{concurrency:n,account:r,blockNumber:s,blockTag:a,stateOverride:i}=t;return(await ol(e,ou(o,n),async c=>{let{data:d}=await gt(o,{to:c.target,data:c.callData,account:r,blockNumber:s,blockTag:a,stateOverride:i,skipBatch:!0});return d??"0x"})).map(c=>c.status==="fulfilled"?{success:!0,returnData:c.value}:{success:!1,returnData:"0x",error:c.reason})}async function yt(o,e){let{abi:t,address:n,functionName:r,args:s,...a}=e;try{let i=D({abi:t,functionName:r,args:s}),{data:l}=await gt(o,{...a,to:n,data:i});return mt({abi:t,functionName:r,args:s,data:l??"0x"})}catch(i){throw wo(i,{abi:t,address:n,args:s,functionName:r,sender:a.account})}}var om=1024,rm=50;async function Kt(o,e){let{calls:t,account:n,blockNumber:r,blockTag:s,batchSize:a=om,maxCalls:i=rm,multicallAddress:l,stateOverride:c,fallbackConcurrency:d}=e,u=t.map(()=>({success:!1,returnData:"0x"}));if(t.length===0)return u;let p=hs(o,l,r),m=[];if(t.forEach((b,y)=>{E(b.target)&&An(b.callData)&&m.push({index:y,call:b})}),m.length===0)return u;if(!await En(o,p,l!==void 0))return(await ko(o,m.map(y=>y.call),{account:n,blockNumber:r,blockTag:s,stateOverride:c,concurrency:d})).forEach((y,w)=>{u[m[w].index]={success:y.success,returnData:y.returnData}}),u;let f=[],h;return m.forEach(({call:b,index:y})=>{let w=(b.callData.length-2)/2,k=a>0&&h!==void 0&&h.size+w>a,v=i>0&&h!==void 0&&h.calls.length>=i;(!h||(k||v)&&h.calls.length>0)&&(h={calls:[],indexes:[],size:0},f.push(h)),h.calls.push(b),h.indexes.push(y),h.size+=w}),(await Promise.allSettled(f.map(b=>yt(o,{abi:rt,address:p,functionName:"aggregate3",args:[b.calls.map(y=>({target:y.target,allowFailure:!0,callData:y.callData}))],account:n,blockNumber:r,blockTag:s,stateOverride:c})))).forEach((b,y)=>{b.status==="fulfilled"&&f[y].indexes.forEach((w,k)=>{let v=b.value[k];v&&(u[w]={success:!!v.success,returnData:v.returnData??"0x"})})}),u}var ru="https://wallet-api.pantograph.app/keyring/chains_v6",sm=6,am=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,su={},vo=null;function im(o){let e=Array.isArray(o.rpcs)?o.rpcs:[],t=typeof o.linkProvider=="string"?[o.linkProvider]:[],n=[];for(let r of[...t,...e]){if(typeof r!="string")continue;let s=r.trim();if(!(!s.startsWith("https://")||am.test(s))&&(n.includes(s)||n.push(s),n.length>=sm))break}return n}function au(o){if(!o||typeof o!="object"||Array.isArray(o))return{};let e={};for(let[t,n]of Object.entries(o)){if(!n||typeof n!="object")continue;let r=n,s=bt(t)??(typeof r.chainId=="number"?bt(r.chainId):void 0);if(!s)continue;let a=im(r);a.length>0&&(e[s]=a)}return e}function iu(o){su=o}function cl(o){let e=bt(o);return e?su[e]??[]:[]}function ul(){vo||ka()}function ka(o={}){let{url:e=ru,force:t=!1,debug:n=!1}=o;return vo&&!t||(vo=(async()=>{try{let r=await x.get(e);if(!r.ok)throw new Error(`HTTP ${r.status} ${r.statusText}`);let s=au(r.data),a=Object.keys(s).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return iu(s),n&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${e}`),!0}catch(r){if(n){let s=r instanceof Error?r.message:String(r);console.warn(`[chains] remote RPC catalogue unavailable (${s}); using built-in endpoints`)}return vo=null,!1}})()),vo}var lm=new Map(Rn.map(o=>[o.hexId.toLowerCase(),o])),cm=new Map(Rn.map(o=>[o.id,o]));function bt(o){if(typeof o=="number")return Number.isFinite(o)&&o>=0?`0x${o.toString(16)}`:void 0;let e=o.trim().toLowerCase();if(e)return e.startsWith("0x")?/^0x[0-9a-f]+$/.test(e)?e:void 0:/^\d+$/.test(e)?`0x${Number(e).toString(16)}`:void 0}function st(o){if(typeof o=="number")return cm.get(o);let e=bt(o);return e?lm.get(e):void 0}var Ge=Object.fromEntries(Rn.map(o=>[o.hexId,o.rpcUrls.default.http[0]]));function dl(o){return st(o)?.rpcUrls.default.http[0]}var pl={};function Nn(o){let e={};if(o)for(let[t,n]of Object.entries(o)){if(typeof n!="string"||!n.trim())continue;let r=bt(t)??t.toLowerCase();e[r]=n.trim()}pl=e}function fs(){return{...pl}}function Ln(o){ul();let e=bt(o),t=e?pl[e]:void 0,n=cl(o),r=st(o)?.rpcUrls.default.http??[];return[...new Set([...t?[t]:[],...n,...r])]}function In(o){return Ln(o)[0]}function ml(o){let e=st(o);if(!e)return;let t=Ln(o),n=e.rpcUrls.default.http;return t.length===0||t.length===n.length&&t.every((r,s)=>r===n[s])?e:{...e,rpcUrls:{default:{http:t}}}}var jt=class extends B{name="HttpRequestError";status;url;body;headers;constructor({body:e,details:t,headers:n,status:r,url:s}){super("HTTP request failed.",{details:t,metaMessages:[`URL: ${s}`,...r?[`Status: ${r}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[]]}),this.status=r,this.url=s,this.body=e,this.headers=n}},To=class extends B{name="TimeoutError";constructor({body:e,url:t,timeout:n}){super("The request took too long to respond.",{details:`The request timed out after ${n}ms.`,metaMessages:[`URL: ${t}`,...e?[`Request body: ${JSON.stringify(e)}`]:[]]})}},Ao=class extends B{name="NetworkError";constructor({cause:e,url:t}){super("Could not reach the RPC endpoint.",{cause:e,metaMessages:[`URL: ${t}`]})}},va=class extends B{name="UrlRequiredError";constructor(){super("No RPC URL was provided.",{metaMessages:['Pass one to the transport \u2014 http("https://\u2026") \u2014 or give the client a chain that has a default RPC URL.']})}},gs=class extends B{name="FallbackTransportError";constructor({cause:e,count:t}){super(`All ${t} fallback transports failed.`,{cause:e})}};var Po=class extends B{name="RpcRequestError";code;data;constructor({body:e,error:t,url:n,shortMessage:r}){super(r??"RPC request failed.",{details:t.message,metaMessages:[...n?[`URL: ${n}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[],`Error code: ${t.code}`]}),this.code=t.code,this.data=t.data}};function Ke(o,e,t){return class extends Po{static code=e;name=o;constructor(n){super({...n,shortMessage:t})}}}var um=Ke("ParseRpcError",-32700,"The node could not parse the JSON request."),dm=Ke("InvalidRequestRpcError",-32600,"The JSON request is not valid."),pm=Ke("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),mm=Ke("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),hm=Ke("InternalRpcError",-32603,"The node reported an internal error."),fm=Ke("InvalidInputRpcError",-32e3,"The RPC input is not valid."),gm=Ke("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),ym=Ke("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),bm=Ke("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),wm=Ke("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),hl=Ke("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),km=Ke("UserRejectedRequestError",4001,"The user rejected the request."),vm=new Map([[-32700,um],[-32600,dm],[-32601,pm],[-32602,mm],[-32603,hm],[-32e3,fm],[-32001,gm],[-32002,ym],[-32003,bm],[-32004,wm],[-32005,hl],[4001,km]]);function lu(o){let e=vm.get(o.error.code);return e?new e(o):new Po(o)}function cu(o){return new Promise(e=>setTimeout(e,o))}async function fl(o,{retryCount:e=2,delay:t=150,shouldRetry:n=()=>!0}={}){let r=0;for(;;)try{return await o()}catch(s){if(r++,r>e||!n({count:r,error:s}))throw s;let a=typeof t=="function"?t({count:r,error:s}):t*2**(r-1);a>0&&await cu(a)}}function gl(o){let e=o?.["retry-after"];if(!e)return;let t=Number(e);if(Number.isFinite(t))return t*1e3;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}var Tm=new Set([408,413,429,500,502,503,504]),Am=new Set([401,402,403]);function Ta(o){return o instanceof To||o instanceof Ao?!0:o instanceof jt?o.status?Tm.has(o.status)||o.status>=500:!0:o instanceof hl?!0:o instanceof Po?o.code===-32603:!1}function Aa(o){return o instanceof jt&&o.status&&Am.has(o.status)?!0:Ta(o)}function Pa(o,{retryCount:e=3,retryDelay:t=150}={}){return function(r,s={}){return fl(()=>o(r),{retryCount:s.retryCount??e,shouldRetry:({error:a})=>Ta(a),delay:({count:a,error:i})=>{let l=i instanceof jt?gl(i.headers):void 0;return l!==void 0?l:(s.retryDelay??t)*2**(a-1)}})}}function zt({key:o,name:e,type:t,request:n,retryCount:r=3,retryDelay:s=150,timeout:a=1e4},i){return{config:{key:o,name:e,type:t,request:n,retryCount:r,retryDelay:s,timeout:a},request:Pa(n,{retryCount:r,retryDelay:s}),value:i}}function Xt(o,e={}){let{key:t="fallback",name:n="Fallback",retryCount:r=0,retryDelay:s,onTransportError:a}=e;return(i={})=>{let l=o.map(d=>d(i));if(l.length===0)throw new gs({count:0});return zt({key:t,name:n,type:"fallback",request:async d=>{let u;for(let p=0;p<l.length;p++)try{return await l[p].request(d)}catch(m){if(u=m,a?.({error:m,index:p,method:d.method}),!Aa(m))throw m}throw new gs({cause:u,count:l.length})},retryCount:r,retryDelay:s,timeout:i.timeout},{transports:l})}}var uu=0;function du(){return uu+=1,uu}function Pm(o){let e=o?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let t=o?.message??"";return/timeout/i.test(t)}var So=class{url;timeout;fetchOptions;constructor(e,{timeout:t=1e4,fetchOptions:n={}}={}){this.url=e,this.timeout=t,this.fetchOptions=n}async post(e){let t;try{t=await x.post(this.url,e,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(n){throw Pm(n)?new To({body:e,url:this.url,timeout:this.timeout}):new Ao({cause:n,url:this.url})}if(!t.ok)throw new jt({body:e,details:_(t),headers:t.headers,status:t.status,url:this.url});return t.data}async request(e){let t={jsonrpc:"2.0",id:du(),...e};return await this.post(t)??{id:t.id}}async requestBatch(e){let t=e.map(s=>({jsonrpc:"2.0",id:du(),...s})),n=await this.post(t);if(!Array.isArray(n))return t.map(s=>({id:s.id,error:n?.error??{code:-32603,message:"Malformed batch response."}}));let r=new Map(n.map(s=>[s.id,s]));return t.map((s,a)=>r.get(s.id)??n[a]??{id:s.id,error:{code:-32603,message:"Missing response for batched request."}})}};function pu(o,e,t){if(o.error)throw lu({body:e,error:o.error,url:t});return o.result}function at(o,e={}){let{batch:t,fetchOptions:n,key:r="http",name:s="HTTP JSON-RPC",retryCount:a,retryDelay:i,timeout:l}=e;return({chain:c,retryCount:d,retryDelay:u,timeout:p}={})=>{let{batchSize:m=1e3,wait:f=0}=typeof t=="object"?t:{},h=l??p??1e4,g=o??c?.rpcUrls.default.http[0];if(!g)throw new va;let b=new So(g,{timeout:h,fetchOptions:n});return zt({key:r,name:s,type:"http",retryCount:a??d,retryDelay:i??u,timeout:h,async request({method:y,params:w}){let k={method:y,params:w};if(t){let{schedule:v}=ms({id:`${g}:${m}:${f}`,wait:f,shouldSplitBatch:A=>A.length>m,fn:A=>b.requestBatch(A)});return pu(await v(k),k,g)}return pu(await b.request(k),k,g)}},{url:g})}}var Sm=1024;async function xo(o,e){let{contracts:t,allowFailure:n=!0,account:r,blockNumber:s,blockTag:a,multicallAddress:i,stateOverride:l,fallbackConcurrency:c}=e,d=e.batchSize??(typeof o.batch?.multicall=="object"&&o.batch.multicall.batchSize||Sm),u=new Array(t.length);if(t.length===0)return n?u:[];let p=hs(o,i,s),m=[],f;t.forEach((b,y)=>{let{abi:w,address:k,functionName:v,args:A}=b,S;try{if(!E(k))throw new Qn(k);S=D({abi:w,functionName:v,args:A})}catch(F){let R=wo(F,{abi:w,address:k,args:A,functionName:v,sender:r});if(!n)throw R;u[y]={status:"failure",error:R};return}let C=(S.length-2)/2;(!f||d>0&&f.size+C>d&&f.calls.length>0)&&(f={calls:[],indexes:[],size:0},m.push(f)),f.calls.push({target:k,allowFailure:!0,callData:S}),f.indexes.push(y),f.size+=C}),(await En(o,p,i!==void 0)?await Promise.allSettled(m.map(b=>yt(o,{abi:rt,address:p,functionName:"aggregate3",args:[b.calls],account:r,blockNumber:s,blockTag:a,stateOverride:l}))):await(async()=>{let b=m.flatMap(w=>w.calls.map((k,v)=>({target:k.target,callData:k.callData,index:w.indexes[v]}))),y=await ko(o,b,{account:r,blockNumber:s,blockTag:a,stateOverride:l,concurrency:c});return m.length=0,y.map((w,k)=>(m.push({calls:[],indexes:[b[k].index],size:0}),w.success?{status:"fulfilled",value:[{success:!0,returnData:w.returnData}]}:{status:"rejected",reason:w.error}))})()).forEach((b,y)=>{let w=m[y];if(b.status==="rejected"){for(let k of w.indexes){let v=t[k],A=wo(b.reason,{abi:v.abi,address:v.address,args:v.args,functionName:v.functionName,sender:r});if(!n)throw A;u[k]={status:"failure",error:A}}return}w.indexes.forEach((k,v)=>{let A=t[k],S=b.value[v];try{if(!S)throw new Error("Multicall returned fewer results than calls.");if(!S.success)throw new bo({data:S.returnData});if(!S.returnData||S.returnData==="0x")throw new Bt;let C=mt({abi:A.abi,functionName:A.functionName,args:A.args,data:S.returnData});u[k]={status:"success",result:C}}catch(C){let F=wo(C,{abi:A.abi,address:A.address,args:A.args,functionName:A.functionName,sender:r});if(!n)throw F;u[k]={status:"failure",error:F}}})});for(let b=0;b<t.length;b++){if(u[b])continue;let y=new Error("Multicall returned no result for this call.");if(!n)throw y;u[b]={status:"failure",error:y}}return n?u:u.map(b=>b.result)}var xm=0,Un=class{key;name;uid;chain;transport;batch;request;constructor(e={}){let{batch:t,key:n="public",name:r="Public Client",retryCount:s,retryDelay:a,timeout:i}=e;this.chain=Rm(e.chain),this.key=n,this.name=r,this.batch=t,this.uid=`${n}-${++xm}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??Cm(e.rpcUrl,this.chain))({chain:this.chain,retryCount:s,retryDelay:a,timeout:i});this.transport={...c.config,...c.value},this.request=c.request}call(e){return gt(this,e)}readContract(e){return yt(this,e)}multicall(e){return xo(this,e)}multicallRaw(e){return Kt(this,e)}getBlockNumber(){return ao(this)}getChainId(){return io(this)}getBalance(e){return lo(this,e)}getCode(e){return Yt(this,e)}getStorageAt(e){return co(this,e)}getTransactionCount(e){return uo(this,e)}getGasPrice(){return po(this)}estimateMaxPriorityFeePerGas(){return ba(this)}estimateGas(e){return mo(this,e)}getBlock(e){return ho(this,e)}rpc(e,t){return this.request({method:e,params:t})}extend(e){let t=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return Object.assign(t,e(t))}};function Cm(o,e){if(o)return at(o);let t=e?.rpcUrls.default.http??[];return t.length>1?Xt(t.map(n=>at(n,{retryCount:1}))):at(t[0])}function Rm(o){if(o===void 0)return;if(typeof o=="object")return o;let e=ml(o);if(!e)throw new yo(o);return e}function Qt(o={}){return new Un(o)}var yl=new Map;function Em(o,e){return{id:parseInt(o,16),hexId:o,name:`Chain ${parseInt(o,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:e}},contracts:{multicall3:{address:te}}}}function xe(o,e={}){let{batch:t=!0,pinRpcUrl:n=!1,fallbackConcurrency:r,assumeMulticall3:s}=e,a=bt(o),i=e.rpcUrl?.trim(),l=a?Ln(a):[],c=i?n?[i]:[...new Set([i,...l])]:l;if(c.length===0)throw new yo(o);let d=`${a??o}|${c.join(",")}|${t?1:0}|${r??""}|${s?1:0}`,u=yl.get(d);if(u)return u;let p=Qt({chain:a&&!st(a)?Em(a,c):a,transport:c.length===1?at(c[0]):Xt(c.map(m=>at(m,{retryCount:1}))),batch:t?{multicall:{fallbackConcurrency:r,assumeMulticall3:s}}:void 0});return yl.set(d,p),p}function Sa(){yl.clear()}function wl(o,e){try{return xe(o,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function ve(o,e,t){let n=new Array(e.length).fill(null),r=e.length>0?wl(o,t):null;if(!r)return n;let s=[];if(e.forEach((a,i)=>{!E(a.target)||!An(a.callData)||s.push({index:i,target:a.target,callData:a.callData})}),s.length===0)return n;try{(await Kt(r,{calls:s})).forEach((i,l)=>{i.success&&(n[s[l].index]=i.returnData)})}catch{}return n}function xa(o){return o?.status==="success"?o.result:void 0}async function bl(o,e){try{return await o.multicall({contracts:e})}catch{return[]}}async function Jt(o,e,t){let n=e.map(()=>({symbol:null,decimals:null})),r=e.length>0?wl(o,t):null;if(!r)return n;let s=[];if(e.forEach((l,c)=>{E(l)&&s.push({index:c,address:l})}),s.length===0)return n;let a=await bl(r,s.flatMap(l=>[{address:l.address,abi:V,functionName:"symbol"},{address:l.address,abi:V,functionName:"decimals"}]));s.forEach((l,c)=>{let d=xa(a[c*2]);typeof d=="string"&&d.trim()&&(n[l.index].symbol=d.trim()),n[l.index].decimals=fa(xa(a[c*2+1]))});let i=s.filter(l=>n[l.index].symbol===null);if(i.length>0){let l=await bl(r,i.map(c=>({address:c.address,abi:fo,functionName:"symbol"})));i.forEach((c,d)=>{n[c.index].symbol=ga(xa(l[d]))})}return n}async function mu(o,e,t){let n=new Array(e.length).fill(null),r=e.length>0?wl(o,t):null;if(!r)return n;let s=[];return e.forEach((i,l)=>{if(E(i.contract))try{s.push({index:l,address:i.contract,tokenId:BigInt(i.tokenId)})}catch{}}),s.length===0||(await bl(r,s.map(i=>({address:i.address,abi:go,functionName:"tokenURI",args:[i.tokenId]})))).forEach((i,l)=>{let c=xa(i);if(typeof c!="string")return;let d=c.replace(/\0+$/,"").trim();d&&(n[s[l].index]=d)}),n}function ys(o){return Co(String(o))??"0"}function Co(o){let e=o.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",n=e[2]??"",r=e[3]??"";if(n===""&&r==="")return null;let s=e[4]?parseInt(e[4],10):0,a=n+r,i=n.length+s,l;return i<=0?l=`0.${"0".repeat(-i)}${a}`:i>=a.length?l=a+"0".repeat(i-a.length):l=`${a.slice(0,i)}.${a.slice(i)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":t+l}function kl(o){let e=Co(o);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function Ca(o,e){let t=o<0n,n=(t?-o:o).toString(),r;if(e===0)r=n;else{let s=n.padStart(e+1,"0"),a=s.length-e;r=`${s.slice(0,a)}.${s.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${r}`:r}function Dn(o,e){let t=Co(o);if(t===null||t.startsWith("-"))return null;let[n,r=""]=t.split("."),s=r.slice(0,e).padEnd(e,"0");try{let a=BigInt(n||"0")*10n**BigInt(e)+BigInt(s||"0");return a>0n?a:null}catch{return null}}function On(o){if(typeof o=="number")return Number.isFinite(o)&&o>0?ys(o):null;if(typeof o!="string")return null;let e=o.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Co(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function Nt(o,e){let t=Co(o);if(t===null||e<0)return o;let n=t.startsWith("-"),[r,s=""]=(n?t.slice(1):t).split(".");if(s.length<=e)return t;let a=e===0?r:`${r}.${s.slice(0,e)}`,i=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${i}`:i}function Mn(o,e,t,n){let r=kl(o);if(!r||t<=0n||n<0)return o;let s=r.mant*e*10n**BigInt(n)/(t*10n**BigInt(r.frac));return Ca(s,n)}function Zt(o,e){let t=kl(o),n=kl(e);if(!t||!n){let i=Number(o),l=Number(e);return i<l?-1:i>l?1:0}let r=Math.max(t.frac,n.frac),s=t.mant*10n**BigInt(r-t.frac),a=n.mant*10n**BigInt(r-n.frac);return s<a?-1:s>a?1:0}var _m={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"}]},Nm="payment-required",Lm="PAYMENT-SIGNATURE",Im="X-PAYMENT",Um="payment-response",Dm="x-payment-response",Om=600,Mm=300,Fm={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 hu(o){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(o),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(o,"utf8").toString("base64")}function gu(o){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(o),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(o,"base64").toString("utf8")}function Bm(){let o=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(o);else for(let t=0;t<32;t++)o[t]=Math.floor(Math.random()*256);return"0x"+Array.from(o,t=>t.toString(16).padStart(2,"0")).join("")}function yu(o){let e=String(o);if(e.includes(":")){let[n,r]=e.split(":"),s=parseInt(r,10);if(n!=="eip155"||Number.isNaN(s))throw new Error(`Unsupported x402 network: ${o} (only EVM "eip155:*" is supported)`);return s}let t=Fm[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${o}`);return t}function bu(o){if(!o.query||Object.keys(o.query).length===0)return o.url;let e=Object.entries(o.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return o.url.includes("?")?`${o.url}&${e}`:`${o.url}?${e}`}function Ra(o){let e=o.headers[Nm];if(e){let r=fu(qm(e));return r&&Array.isArray(r.accepts)?{version:2,payload:r}:null}let t=o.data,n=t&&typeof t=="object"?t:fu(t);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function fu(o){if(typeof o!="string")return null;try{let e=JSON.parse(o);return e&&typeof e=="object"?e:null}catch{return null}}function qm(o){try{return gu(o)}catch{return null}}function $m(o){let e=o.amount??o.maxAmountRequired;return typeof o.scheme!="string"||typeof o.network!="string"||e==null||typeof o.asset!="string"||typeof o.payTo!="string"?null:{scheme:o.scheme,network:o.network,amount:String(e),asset:o.asset,payTo:o.payTo,...typeof o.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:o.maxTimeoutSeconds}:{},...o.extra&&typeof o.extra=="object"?{extra:o.extra}:{},...typeof o.resource=="string"?{resource:o.resource}:{},...typeof o.description=="string"?{description:o.description}:{},...typeof o.mimeType=="string"?{mimeType:o.mimeType}:{},...o.outputSchema!=null?{outputSchema:o.outputSchema}:{}}}function Hm(o){let e=null;for(let t of o){let n=$m(t);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return yu(n.network),n}catch(r){e=r instanceof Error?r.message:String(r)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function vl(o,e,t,n){let r=Ra(o);if(!r)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:a}=r,i=Hm(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=yu(i.network),c=Math.floor(Date.now()/1e3),d={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-Om)),validBefore:String(c+(i.maxTimeoutSeconds??Mm)),nonce:Bm()},u={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:_m,primaryType:"TransferWithAuthorization",message:{...d}};return{request:{url:bu(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:s,requirements:i,authorization:d,typedData:u,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...n?{userQuery:n}:{}}}async function Vm(o,e,t,n){let r=bu(e),s=await o.request(e.method??"GET",r,e.body,{headers:e.headers});if(s.status===402)return{status:"payment_required",challenge:vl(s,e,t,n)};if(!s.ok)throw new Error(_(s));return{status:"ok",data:s.data}}async function Tl(o,e,t){let{url:n,method:r,body:s,headers:a}=e.request,i=await o.request(r,n,s,{headers:{...a??{},...Al(e,t)}});if(i.ok)return i.data;throw new Error(Ym(i)??_(i))}function Wm(o){return Ra(o)!==null}function wu(o){let e=ku(o);return e?.errorReason?e.errorReason:Ra(o)?.payload.error??null}function Ym(o){let e=wu(o);return e?`x402 payment rejected: ${e}`:null}var Gm={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 Al(o,e){let{requirements:t,authorization:n}=o,r={signature:e,authorization:n};if(o.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:r};return{[Im]:hu(JSON.stringify(a))}}let s={x402Version:2,...o.resource!=null?{resource:o.resource}:{},accepted:Km(t),payload:r,...o.extensions!=null?{extensions:o.extensions}:{}};return{[Lm]:hu(JSON.stringify(s))}}function Km(o){let{resource:e,description:t,mimeType:n,outputSchema:r,...s}=o;return s}function ku(o){let e=o.headers[Um]??o.headers[Dm];if(!e)return null;try{return JSON.parse(gu(e))}catch{return null}}function jm(o,e){return o==null?e:Gm[o]??`Chain ${o}`}async function vu(o){let e=o.requirements,n=o.resource?.description||e.description,r=o.chainId??null,s=null,a=null;if(r!=null){let[l]=await Jt("0x"+r.toString(16),[e.asset]);s=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=Ca(BigInt(e.amount),a)}catch{}return{amount:i,asset:s||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:r!=null?`eip155:${r}`:e.network,networkRaw:e.network,chainId:r,networkLabel:jm(r,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:o.request.url}}function Pl(o){return async(e,t)=>{let n=o.getPayer(),r=o.getSigner();if(!n||!r)return null;let s;try{s=vl(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let a;try{a=await r({typedData:s.typedData,display:await vu(s)})}catch{a=null}return a?Al(s,a):null}}var en=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Fn(o){if(!o||typeof o!="object")return!1;let e=o;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function bs(o){if(o?.aborted)throw new en}function Sl(o,e){if(!e)return{signal:o.signal,cleanup:()=>{}};if(e.aborted)return o.abort(),{signal:o.signal,cleanup:()=>{}};let t=()=>o.abort();return e.addEventListener("abort",t),{signal:o.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Tu={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},zm="https://nft.keyring.app/api/gemini-stable",Xm="https://generativelanguage.googleapis.com",Qm=new Set([408,429,500,502,503,504]),Au=3e4,Ea=o=>new Promise(e=>setTimeout(e,o));function _a(o,e,t){if(t!=null&&t>0)return Math.min(t,Au);let n=Math.min(e*2**(o-1),Au);return n/2+Math.random()*(n/2)}function Jm(o){if(!o)return null;let e=Number(o);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(o);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var be=class{model;maxTokens;temperature;baseUrl;apiKey;requestSignal;constructor(e){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?Xm:zm)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:s}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;bs(l);let c=s.length>0?s:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let h of c){let g=h.parts.map(b=>b.functionCall?`fc:${b.functionCall.name}`:b.functionResponse?`fr:${b.functionResponse.name}`:`text:${(b.text??"").slice(0,40)}`).join(", ");console.log(` ${h.role}: [${g}]`)}}let d=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),u={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};d!=null&&(u.thinkingConfig={thinkingBudget:d});let p={contents:c,generationConfig:u};r&&(p.systemInstruction=r),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let h=1;h<=a;h++){bs(l);let g;try{g=await x.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(S){if(Fn(S))throw S;if(f=S instanceof Error?S.message:String(S),h>=a)break;await Ea(_a(h,i));continue}if(!g.ok){let S=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${g.status}: ${S}`,!Qm.has(g.status))throw new Error(f);if(h>=a)break;let C=Jm(g.headers["retry-after"]??null);await Ea(_a(h,i,C));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=a)break;await Ea(_a(h,i));continue}let b=g.data,y=b.candidates?.[0];if(!y)return{text:"",toolCalls:[]};let w="",k=[],v=y.content?.parts;if(!Array.isArray(v)||v.length===0){let S=y.finishReason;if(!(S==="SAFETY"||S==="RECITATION")&&h<a){f=`Gemini returned an empty turn (finishReason=${S??"none"})`,await Ea(_a(h,i));continue}return{text:"",toolCalls:[]}}for(let S of v)S.text&&(w+=S.text),S.functionCall&&k.push({toolName:S.functionCall.name,args:S.functionCall.args??{},callId:S.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let A=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:A}}throw new Error(f)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(u=>u.functionCall),d=l?.parts.some(u=>u.functionCall);l&&l.role===i.role&&!c&&!d?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let s=[];for(let i=0;i<r.length;i++){let l=r[i],c=s[s.length-1];l.role==="function"&&!c?.parts.some(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.functionCall)&&!(r[i+1]?.role==="function")||s.push(l)}for(;s.length>0&&s[0].role!=="user";)s.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
|
|
4
|
+
`)}]}:null,contents:s}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let s of t.parameters){let a={type:Tu[s.type]??"STRING",description:s.description};s.type==="array"&&(a.items={type:Tu[s.items?.type??"string"]??"STRING"}),n[s.name]=a,s.required&&r.push(s.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:n,required:r}}})}};var Ro=class{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(t=>t.category===e)}async execute(e,t,n){let r=this.tools.get(e);if(!r)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let s=Date.now();try{return{...await r.execute(t,n),duration:Date.now()-s}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-s}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var Eo=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Zm=new Set(Eo),tn=[...Eo],xl=new Set(tn),je="0x1",No="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function eh(o){return o.map(e=>_o[e]??e).join(", ")}function Na(o){let e=new Set;if(o)for(let n of o){let r=La(n);r&&e.add(r)}let t=Eo.filter(n=>!e.has(n));tn=t.length>0?[...t]:[...Eo],xl=new Set(tn),je=tn.includes("0x1")?"0x1":tn[0],No=eh(tn)}var th={"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 M(o){let e=La(o);return e&&xl.has(e)?e:null}function La(o){if(typeof o!="string")return null;let e=o.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=th[e];if(t)return t;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&Zm.has(n)?n:null}function Me(o){return M(o)!==null}function Fe(){return[...tn]}var on=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${No}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},nn=o=>typeof o=="string"&&o.trim()!=="";function j(o,e){if(nn(o)){let t=M(o);if(t)return t;throw new on(o.trim())}if(nn(e?.chain)){let t=M(e.chain);if(t)return t;throw new on(e.chain.trim())}return null}function Ia(o,e){return M(o)??M(e?.chain)??void 0}var _o={"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 T(o){let e=La(o);return e&&_o[e]?_o[e]:typeof o=="string"&&o.trim()?o.trim():"the requested chain"}var nh={"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 Pu(o,e){let t=La(o),n=t?nh[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var oh={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Su(o){if(typeof o!="string")return null;let e=o.trim().toLowerCase();return e?oh[e]??null:null}var rh={"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 xu(o){let e=M(o);return e?rh[e]??null:null}function Lo(o,e){if(!nn(o))return null;let t=M(o),n=M(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:_o[t]??t,connectedLabel:_o[n]??n}}function Cu(o,e){let t=typeof o=="string"?o.trim():"",n=e&&e.length?e.filter(s=>xl.has(s)):[];return(n.length?n:tn).map(s=>{let a=_o[s]??s;return{label:a,prompt:t?`${t} (${a})`:a}})}function Io(o,e){return{actionButtons:Cu(e),_instructions:`The user wants to ${o} 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 fe=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=Cu(e,t)}},ws=class extends Error{code="no_wallet_connected";constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one."),this.name="NoWalletConnectedError"}};function ae(o,e){if(nn(o))return o.trim();if(nn(e?.walletAddress))return e.walletAddress.trim();throw new ws}function Ae(o,e,t){if(nn(o)){let n=M(o);if(n)return n;throw new on(o.trim())}if(nn(e?.chain)){let n=M(e.chain);if(n)return n;throw new on(e.chain.trim())}if(nn(e?.walletAddress))throw new fe(typeof e?.query=="string"?e.query:void 0,t);return je}var P=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let s=await this.run(e,t),a=sh(s);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-r,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(s){return s instanceof fe?{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()-r,actionButtons:s.buttons}:s instanceof ws?{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()-r}:{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-r}}}};function sh(o){if(!o||typeof o!="object")return{data:o};let e=o,t=e.actionButtons,n=Array.isArray(t)&&t.length>0?t:void 0,r=e.ui,s=r&&typeof r=="object"&&typeof r.component=="string"?r:void 0;if(!n&&!s)return{data:o};let{actionButtons:a,ui:i,...l}=e;return{data:l,...n?{actionButtons:n}:{},...s?{ui:s}:{}}}var ah="https://wallet-api.pantograph.app",ih="0x0000000000000000000000000000000000000000",Nu={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Lu={"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 lh(o){return Nu[o.toLowerCase()]||o}function Ru(o){let e=[];for(let[t,n]of Object.entries(o))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function Cl(o){let e=o,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,s=r!=null?parseFloat(String(r)):NaN,a=typeof e.symbolOnchain=="string"?e.symbolOnchain.trim():"";return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...a?{symbol:a}:{},...Number.isFinite(s)?{usd_price:s}:{}}}function Eu(o){if(Array.isArray(o))return o;let e=o;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Ne(o){if(o==null)return null;let e=typeof o=="number"?o:parseFloat(String(o));return Number.isFinite(e)?e:null}function _u(o,e){let t=o.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=Ne(o.price_change_percentage_24h)??Ne(o.priceChange24h)??Ne(o.usd_price_24hr_percent_change)??Ne(o.price_change_24h)??Ne(o.priceChange);return{chainId:e,tokenAddress:o.address??o.token_address??"",name:o.name??null,symbol:typeof o.symbolOnchain=="string"&&o.symbolOnchain.trim()||o.symbol||null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:o.logoURI??o.icon_image??o.logo??null,usdPrice:Ne(o.price)??Ne(o.usd_price),marketCap:Ne(o.market_cap)??Ne(o.marketCap),totalVolume:{"24h":Ne(o.total_volume)??Ne(o.volume24h)},pricePercentChange:{"24h":r}}}var ch=100;function uh(o,e){let t=[];for(let n=0;n<o.length;n+=e)t.push(o.slice(n,n+e));return t}var Te=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??ah).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async fetchTokensAll(e,t){let n=uh(t,ch);return(await Promise.all(n.map(async s=>{try{let a=`${this.baseUrl}/keyrings/tokens/all/${e}?addresses=${encodeURIComponent(s.join(","))}`,i=await x.get(a);return i.ok?Eu(i.data):[]}catch{return[]}}))).flat()}async enrichTokenPrices(e,t){let n=new Map;if(e.length===0)return n;try{let r=e.map(i=>i.token_address),s=await this.fetchTokensAll(parseInt(t,16),r),a=new Map;for(let i of s)if(i.address){let l=i.address.toLowerCase(),c=typeof i.symbolOnchain=="string"?i.symbolOnchain.trim():"";a.set(l,{price:i.price!=null?parseFloat(String(i.price)):NaN,icon_image:i.icon_image,...c?{symbolOnchain:c}:{}}),("yieldProtocol"in i||"yieldAsset"in i)&&n.set(l,{yieldProtocol:i.yieldProtocol,yieldAsset:i.yieldAsset})}for(let i=0;i<e.length;i++){let l=a.get(e[i].token_address.toLowerCase());l&&(l.icon_image&&(e[i].logo=l.icon_image,e[i].thumbnail=l.icon_image),l.symbolOnchain&&(e[i].symbol=l.symbolOnchain),isNaN(l.price)||(e[i].usd_price=l.price,e[i].usd_value=parseFloat(e[i].balance_formatted||"0")*l.price))}}catch{}return n}async getYieldPricingTokens(e,t){let n=(t??[]).map(s=>String(s??"").trim()).filter(Boolean);if(n.length===0)return[];let r=typeof e=="number"?e:String(e).startsWith("0x")?parseInt(String(e),16):parseInt(String(e),10);if(!Number.isFinite(r))return[];try{return await this.fetchTokensAll(r,n)}catch{return[]}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),r=await x.get(n);if(!r.ok)return null;let s=Eu(r.data),a=e.toLowerCase()===ih,i=s.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?Cl(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=await this.fetchTokensAll(parseInt(t,16),e),s=new Set(e.map(a=>a.toLowerCase()));for(let a of r){let i=a.address?.toLowerCase()||a.token_address?.toLowerCase()||(a.address===""?"":null);i&&s.has(i)&&(n[i]=Cl(a))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let s=parseInt(n||je,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=Ru({chainId:s,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await x.get(i);if(!l.ok)throw new Error(_(l));let c=l.data,d=c?.result??c?.data??c,u=[];return Array.isArray(d)?u=d:d&&typeof d=="object"&&(u=Object.values(d).flat()),{success:!0,data:u.map(Cl)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||je,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let s=Lu[t.toLowerCase()]??[],a=r!=null?r+s.length:n+s.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,a),s.length>0?this.getTokensMetadata(s,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],d=l.status==="fulfilled"?s.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>_u(h,t)):[],u=new Set,p=[];for(let h of d){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),m.push(h))}let f=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(s=>s.tokenAddress&&(s.marketCap==null||s.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(s=>s.tokenAddress),t);for(let s of n){let a=r[s.tokenAddress.toLowerCase()];a&&(s.marketCap==null&&(s.marketCap=Ne(a.market_cap)??Ne(a.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":Ne(a.total_volume)??Ne(a.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=parseInt(e,16),s=Ru({chainId:r,duration:n,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${s?`?${s}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(a);if(!c.ok)throw new Error(_(c));let d=c.data;if(i=Array.isArray(d)?d:Array.isArray(d.data)?d.data:[],i.length>0)break;l<4&&await new Promise(u=>setTimeout(u,2e3))}return i.map(l=>_u(l,e))}async getTopGainers(e){let t=e?.chain||je,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,r=e?.duration||"24h";try{let s=await this.fetchTopGainers(t,n,r);return await this.enrichTrendingMarketData(s,t),{success:!0,data:s}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}};function X(o,e,t,n=[]){return{target:o,callData:D({abi:e,functionName:t,args:n})}}var Bn=1e27,Ua=10n**27n,ks=31536e3,dh=10;function ze(o){return Number.isFinite(o)&&o>=0&&o<=dh?o:null}function Rl(o){return Math.expm1(o)}function Xe(o,e){return Number(o)/10**e}function vs(o){return new Date(o).toISOString().slice(0,10)}async function rn(o,e,t){let n=`${t.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${o.token}?range=h&day=${7}`,r=await x.get(n);if(!r.ok)throw new Error(_(r));return{samples:(Array.isArray(r.data)?r.data:r.data?.data||[]).filter(a=>a?.rate!==null&&a?.rate!==void 0).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.rate)})),current:null,rewards:[]}}var wt=class{underlyingCall(e){return X(e.contract,ft,"asset")}liveRateCall(e,t){return null}followUpRateCall(e,t){return null}decodeSize(e,t){if(!Number.isInteger(t.decimals)||t.decimals<0)return null;let n=J(e);return n===null?null:Xe(n,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:X(e.contract,ft,"convertToAssets",[t])}},kt=class extends wt{type="spark";balanceIsUnderlying=!1;sizeCall(e){return X(e.contract,ft,"totalAssets")}fetchApy(e,t,n,r){return rn(e,t,n)}};var El=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}];var _l=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]},{type:"function",name:"liquidity",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint128"}]},{type:"function",name:"tickSpacing",stateMutability:"view",inputs:[],outputs:[{name:"",type:"int24"}]},{type:"function",name:"fee",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint24"}]},{type:"function",name:"token0",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"token1",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Oa=[{type:"function",name:"getReserveData",stateMutability:"view",inputs:[{name:"asset",type:"address"}],outputs:[{name:"reserveData",type:"tuple",components:[{name:"configuration",type:"uint256"},{name:"liquidityIndex",type:"uint128"},{name:"currentLiquidityRate",type:"uint128"}]}]}],Uo=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],Nl=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Lt=[{inputs:[],name:"getUtilization",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseToken",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"utilization",type:"uint256"}],name:"getSupplyRate",outputs:[{name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseTrackingSupplySpeed",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseIndexScale",outputs:[{name:"",type:"uint64"}],stateMutability:"pure",type:"function"}],Ll=[{inputs:[{name:"comet",type:"address"}],name:"rewardConfig",outputs:[{name:"token",type:"address"},{name:"rescaleFactor",type:"uint64"},{name:"shouldUpscale",type:"bool"}],stateMutability:"view",type:"function"}];var Do=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],sn=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],Il=[{inputs:[],name:"susds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var Ul=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],Dl=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var hh=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|
|
5
5
|
value: supplyAPYHistory(request: $request) { date avgRate { value } }
|
|
6
6
|
reserve(request: $reserve) {
|
|
7
7
|
incentives {
|
|
@@ -11,50 +11,50 @@ ${o}`:`The contract function "${n??"call"}" reverted.`,{metaMessages:t&&t!=="0x"
|
|
|
11
11
|
... on MerklSupplyIncentive { extraSupplyApr { value } payoutToken { symbol } customMessage }
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
}`;function
|
|
14
|
+
}`;function fh(o){return(o||[]).flatMap(e=>{let t=Number(e?.extraSupplyApr?.value);return!Number.isFinite(t)||t<=0?[]:[{fraction:Rl(t),tokenSymbol:e?.rewardTokenSymbol??e?.payoutToken?.symbol??null,conditions:e?.customMessage?.trim()||null}]})}var Ts=class extends wt{type="aave-v3";balanceIsUnderlying=!0;underlyingCall(e){return X(e.token,Uo,"UNDERLYING_ASSET_ADDRESS")}sizeCall(e){return X(e.token,V,"totalSupply")}liveRateCall(e,t){return X(e.contract,Oa,"getReserveData",[t.address])}decodeLiveRate(e){if(!e)return null;let t;try{let[n]=_e(Oa[0].outputs,e);t=n.currentLiquidityRate}catch{return null}return ze(Rl(Number(t)/Bn))}async fetchApy(e,t,n,r){let s={chainId:t.chainId,market:e.contract,underlyingToken:r.address,window:"LAST_WEEK"},a=await x.post(n.aaveApiUrl,{operationName:"SupplyAPYHistory",query:hh,variables:{request:s,reserve:{chainId:t.chainId,market:e.contract,underlyingToken:r.address}}});if(!a.ok)throw new Error(_(a));return{samples:(a.data?.data?.value||[]).filter(i=>i?.avgRate?.value!==null&&i?.avgRate?.value!==void 0).map(i=>({timeMs:Date.parse(i?.date??""),fraction:Number(i?.avgRate?.value)})),current:null,rewards:fh(a.data?.data?.reserve?.incentives)}}};var gh={1:"0x1B0e765F6224C21223AeA2af16c1C46E38885a40",10:"0x443EA0340cb75a160F31A440722dec7b5bc3C2E9",130:"0x6f7D514bbD4aFf3BcD1140B7344b32f063dEe486",137:"0x45939657d1CA34A8FA39A924B71D28Fe8431e581",2020:"0x31CdEe8609Bc15fD33cc525f101B70a81b2B1E59",5e3:"0xCd83CbBFCE149d141A5171C3D6a0F0fCCeE225Ab",8453:"0x123964802e6ABabBE1Bc9547D72Ef1B69B00A6b1",42161:"0x88730d254A2f7e6AC8388c3198aFd694bA9f7fae",59144:"0x2c7118c4C88B9841FCF839074c26Ae8f035f2921",534352:"0x70167D30964cbFDc315ECAe02441Af747bE0c5Ee"};async function yh(o,e){let t=gh[Number(e)];if(!t)return null;let[n]=await ve(e,[X(t,Ll,"rewardConfig",[o.contract])]),r=q(n);if(r===null||/^0x0+$/i.test(r))return null;let[s]=await Jt(e,[r]);return{address:r,symbol:s?.symbol??null}}async function bh(o,e,t){let n=String(e.chainId),[r,s,a]=await ve(n,[X(o.contract,Lt,"baseTrackingSupplySpeed"),X(o.contract,Lt,"baseIndexScale"),X(o.token,V,"totalSupply")]),i=J(r),l=J(s),c=J(a);if(i===null||i===0n||l===null||l===0n)return[];if(c===null||c===0n)return[];if(!Number.isInteger(t.decimals)||t.decimals<0)return[];let d=await yh(o,n);if(d===null)return[];let[u,p]=await Promise.all([Ma(n,d.address),Ma(n,t.address)]);if(!(Number(u)>0)||!(Number(p)>0))return[];let m=Xe(c,t.decimals)*Number(p);if(!(m>0))return[];let h=Number(i)/Number(l)*ks*Number(u)/m,g=ze(h);return g===null||g<=0?[]:[{fraction:g,tokenSymbol:d.symbol,conditions:null}]}var As=class extends wt{type="compound-v3";balanceIsUnderlying=!0;underlyingCall(e){return X(e.contract,Lt,"baseToken")}sizeCall(e){return X(e.token,V,"totalSupply")}liveRateCall(e){return X(e.contract,Lt,"getUtilization")}followUpRateCall(e,t){let n=J(t);return n===null?null:X(e.contract,Lt,"getSupplyRate",[n])}decodeLiveRate(e){let t=J(e);return t===null?null:ze(Number(t)/1e18*ks)}async fetchApy(e,t,n,r){let[s,a]=await Promise.all([rn(e,t,n),bh(e,t,r).catch(()=>[])]);return{...s,rewards:a}}};var wh="https://api.maple.finance/v2/graphql",kh=`query PoolApy($id: ID!) {
|
|
15
15
|
poolV2(id: $id) {
|
|
16
16
|
tvl
|
|
17
17
|
weeklyApy
|
|
18
18
|
}
|
|
19
|
-
}
|
|
19
|
+
}`,vh=1e28;function Th(o,e){if(o==null||!Number.isInteger(e.decimals)||e.decimals<0)return null;let t=Number(o)/10**e.decimals;return Number.isFinite(t)&&t>=0?t:null}function Ah(o){return o==null?null:ze(Number(o)/vh/100)}async function Ph(o){let e=await x.post(wh,{operationName:"PoolApy",query:kh,variables:{id:o.contract.toLowerCase()}});if(!e.ok)throw new Error(_(e));return e.data?.data?.poolV2}var Ps=class extends kt{type="maple";async fetchApy(e,t,n,r){let[s,a]=await Promise.all([rn(e,t,n),Ph(e)]);return{...s,current:Ah(a?.weeklyApy),sizeOverride:Th(a?.tvl,r)}}};var Sh=`query VaultV2ByAddress($address: String!, $chainId: Int!, $options: TimeseriesOptions) {
|
|
20
20
|
vaultV2ByAddress(address: $address, chainId: $chainId) {
|
|
21
21
|
netApy
|
|
22
22
|
avgNetApy(lookback: SEVEN_DAYS)
|
|
23
23
|
historicalState { avgNetApy(options: $options) { x y } }
|
|
24
24
|
}
|
|
25
|
-
}`,ms=class extends dt{type="morpho-v2";async fetchApy(e,t,n){let o=Math.floor(Date.now()/1e3),s=await x.post(n.morphoApiUrl,{operationName:"VaultV2ByAddress",query:Ym,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:o-7*86400,endTimestamp:o,interval:"HOUR"}}});if(!s.ok)throw new Error(E(s));let a=s.data?.data?.vaultV2ByAddress,i=Number(a?.netApy),l=Number(a?.avgNetApy);return{avgOverride:Number.isFinite(l)?l:null,samples:(a?.historicalState?.avgNetApy||[]).filter(c=>c?.y!==null&&c?.y!==void 0).map(c=>({timeMs:Number(c?.x)*1e3,fraction:Number(c?.y)})),current:Number.isFinite(i)?i:null,rewards:[]}}};var hs=class extends dt{type="spark";liveRateCall(e){return j(e.contract,Ar,"rateProvider")}followUpRateCall(e,t){let n=B(t);return n===null?null:j(n,Qt,"getAPR")}decodeLiveRate(e){let t=X(e);return t===null?null:Be(Math.expm1(Number(t)/En))}},gs=class extends dt{type="spark-ethereum";liveRateCall(e){return j(e.contract,Ar,"vsr")}decodeLiveRate(e){let t=X(e);if(t===null||t<=0n)return null;let n=Number(t-wa)/En;return n>-1?Be(Math.expm1(Math.log1p(n)*ls)):null}};var fs=class extends ut{type="spark-l2-susds";balanceIsUnderlying=!1;underlyingCall(){return null}sizeCall(e){return j(e.token,V,"totalSupply")}liveRateCall(e){return j(e.contract,Qt,"getAPR")}decodeLiveRate(e){let t=X(e);return t===null?null:Be(Math.expm1(Number(t)/En))}convertToAssetsCall(e){return j(e.contract,Qt,"getConversionRate")}fetchApy(e,t,n){return Xt(e,t,n)}};function _n(r,e,t,n){if(e<=0n||!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)return null;let o=r*e/wa,s=n-t;return s===0?o:s>0?o*10n**BigInt(s):o/10n**BigInt(-s)}var Aa={"aave-v3":{protocol:new us,label:"Aave V3",home:"https://app.aave.com"},"compound-v3":{protocol:new ds,label:"Compound V3",home:"https://app.compound.finance"},spark:{protocol:new hs,label:"Spark",home:"https://app.spark.fi"},"spark-ethereum":{protocol:new gs,label:"Spark",home:"https://app.spark.fi"},"spark-l2-susds":{protocol:new fs,label:"Spark",home:"https://app.spark.fi"},"morpho-v2":{protocol:new ms,label:"Morpho V2",home:"https://app.morpho.org"},maple:{protocol:new ps,label:"Maple",home:"https://app.maple.finance"}},Gm=Aa.spark.protocol;function Jt(r){return Aa[r.type]?.protocol??Gm}function Ne(r){return Aa[r]?.label??null}function ys(r){return Aa[r]?.home??null}var Nn="0x0000000000000000000000000000000000000000";function bs(r){let e=parseInt(r,16);return Number.isFinite(e)?{chainId:e}:null}function St(r){if(typeof r=="number")return Number.isInteger(r)&&r>0?`0x${r.toString(16)}`:null;if(typeof r!="string")return null;let e=r.trim().toLowerCase();if(!e)return null;if(!/^(0x[0-9a-f]+|\d+)$/.test(e))return F(e);let t=e.startsWith("0x")?parseInt(e,16):Number(e);return Number.isInteger(t)&&t>0?`0x${t.toString(16)}`:null}var Km={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function Pa(r){let e=St(r);return e?Km[e]??null:null}function cu(r){return["susds","usds","rateProvider"].map(e=>({target:r,callData:D({abi:gl,functionName:e})}))}var uu=3,jm={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function bl(r){let e=St(r),t=e?jm[e]:void 0;return t?{target:t,callData:D({abi:Qt,functionName:"getConversionRate"})}:null}var zm=new Set(["spark","spark-ethereum","spark-l2-susds","morpho-v2","maple"]),du="spark-l2-susds";function Sa(r){return!!r&&zm.has(r)}var wl=r=>{if(r==null||r==="")return null;let e=Number(r);return!Number.isInteger(e)||e<0||e>36?null:e},Xm=r=>{if(r==null||r==="")return null;let e=Number(r);return Number.isFinite(e)&&e>0?e:null};function ws(r){let e=Xm(r.yieldAsset?.fixedPrice);return e!==null?e:Number.isFinite(r.priceUSD)?r.priceUSD:0}function pu(r){if(!Sa(r.yieldProtocol)||wl(r.yieldAsset?.decimals)===null||r.yieldProtocol===du&&!bl(r.chain))return!1;let e=ws(r);return Number.isFinite(e)&&e>0}function kl(r){let e=[],t=[];for(let n of r)if(!(n.rawBalance<=0n)&&pu(n)){if(n.yieldProtocol===du){let o=bl(n.chain);if(!o)continue;e.push({key:n.key,...o}),t.push(n.key);continue}e.push({key:n.key,target:n.address,callData:D({abi:at,functionName:"convertToAssets",args:[n.rawBalance]})})}return{calls:e,rateKeys:t}}function xa(r,e,t){let n=new Map(r.map(i=>[i.key,i])),o=new Set(e.rateKeys),s=new Map;e.calls.forEach((i,l)=>{let c=X(t[l]??null);if(c===null)return;if(!o.has(i.key)){s.set(i.key,c);return}let u=n.get(i.key),d=wl(u?.yieldAsset?.decimals);if(!u||d===null)return;let p=_n(u.rawBalance,c,u.decimals,d);p!==null&&s.set(i.key,p)});let a=new Map;for(let i of r){let l=qe(i.rawBalance,i.decimals),c=ws(i),u=s.get(i.key),d={underlyingAmount:l,valueUSD:l*c,pricePerTokenUSD:c,converted:!1};if(u===void 0){a.set(i.key,d);continue}let p=wl(i.yieldAsset?.decimals);if(p===null){a.set(i.key,d);continue}let m=qe(u,p),g=m*c;a.set(i.key,{underlyingAmount:m,valueUSD:g,pricePerTokenUSD:l>0?g/l:c,converted:!0})}return a}async function Ca(r,e,t={}){let n=e.map(a=>a.chain==null?{...a,chain:r}:a),o=kl(n);if(o.calls.length===0)return xa(n,o,[]);let s=await pe(String(r),o.calls,t.rpcUrl);return xa(n,o,s)}async function Ta(r,e,t={}){let n=await Qm(r,e,t.apiBaseUrl);return n?hu(r,n,t):null}async function hu(r,e,t={}){let n=mu(e?.price),o=l=>l!=null&&l>0?l:null;if(!Sa(e?.yieldProtocol))return o(n);let s=ws({key:"price",address:"",rawBalance:0n,decimals:0,priceUSD:n??0,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:r});if(!(s>0))return null;let a=Math.trunc(mu(e?.decimals)??18);if(!Number.isInteger(a)||a<0||a>36)return o(n);let i={key:"price",address:String(e?.address??"").toLowerCase(),rawBalance:10n**BigInt(a),decimals:a,priceUSD:s,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:r};try{let c=(await Ca(r,[i],t)).get(i.key);return c?.converted?o(c.pricePerTokenUSD):null}catch{return null}}async function Qm(r,e,t){let n=String(e??"").toLowerCase();if(!n)return null;try{return(await new me(t?{baseUrl:t}:void 0).getYieldPricingTokens(r,[n])).find(a=>String(a?.address??"").toLowerCase()===n)??null}catch{return null}}function mu(r){if(r==null||r==="")return null;let e=typeof r=="number"?r:Number(r);return Number.isFinite(e)?e:null}var Jm="https://nft.keyring.app",Zm="https://nft.keyring.app",eh=.01,N=5,J=1e3,th=25,nh="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",rh="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function oe(r){return r||Fe}function Z(r){let e=[];for(let[t,n]of Object.entries(r))if(n!=null)if(Array.isArray(n))for(let o of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ee(r){return new Promise(e=>setTimeout(e,r))}function oh(r){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!r||typeof r!="object")return e;let t=r;if("active_protocols"in t||"total_usd_value"in t){let o=t;return{...e,...o,protocols:o.protocols||[]}}let n=t.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(o=>({protocol_id:o.protocolId,protocol_name:o.protocolName,protocol_url:o.protocolUrl??"",protocol_logo:o.protocolLogo??"",positions:o.positionCount??0,total_usd_value:o.totalUsd??0,total_unclaimed_usd_value:o.totalUnclaimedUsd??0,account_health_factor:o.accountHealthFactor??null}))}}function sh(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.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(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function vl(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var L=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Jm).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Zm).replace(/\/+$/,""),this.pantograph=new me({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:o,excludeSpam:s=!1,excludeUnverifiedContracts:a=!1,convertYieldValues:i=!0}=e;if(!t)return{success:!1,error:"Address is required"};let l=oe(n),c="Unknown error";for(let u=1;u<=N;u++)try{let d={chain:l,exclude_spam:s,exclude_unverified_contracts:a,limit:100};o&&(d.token_addresses=o);let p=[],m=null;do{m&&(d.cursor=m);let h=Z(d),f=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,b=await x.get(f);if(!b.ok)throw new U(b.status,E(b));let y=b.data,w=y?.data??y;w?.result?.length>0&&p.push(...w.result),m=w?.cursor??null}while(m);let g={result:p};if(g?.result?.length>0){g.result=g.result.filter(f=>parseFloat(f.balance||"0")>0),g.result=g.result.map(f=>({...f,token_address:f.token_address.toLowerCase()===nh?rh:f.token_address}));let h=await this.enrichTokenPrices(g.result,l);i&&await this.applyYieldValues(g.result,l,h),g.result=g.result.filter(f=>f.usd_value==null||f.usd_value>=eh)}return{success:!0,data:g}}catch(d){if(c=d instanceof Error?d.message:"Unknown error",d instanceof U&&d.status===400)break;u<N&&await ee(J)}return{success:!1,error:c}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let o=oe(n),s="Unknown error",a=await this.pantograph.getTokenMetadata(t,o);if(a)return{success:!0,data:a};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${Z({chain:o,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${Z({chain:o,include:"percent_change"})}`)]),u=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){s="Token metadata not found",i<N&&await ee(J);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}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(s=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await ee(J)}return{success:!1,error:s}}async getWalletNFTs(e){let{address:t,chain:n,limit:o=100,excludeSpam:s=!1,cursor:a,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=oe(n),d=[],p=a,m,g;for(let h=0;h<th;h++){let f=await this.fetchWalletNftsPage({address:t,moralisChain:u,limit:o,excludeSpam:s,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!f.success){if(d.length===0)return f;break}let b=f.data;if(!b)break;let{result:y,cursor:w,page:k,page_size:v}=b;if(Array.isArray(y)&&d.push(...y),m=k,g=v,p=typeof w=="string"&&w.trim()?w:void 0,!p)break}return{success:!0,data:{result:d,cursor:p,page:m,page_size:g}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:n,limit:o,excludeSpam:s,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,u="Unknown error";for(let d=1;d<=N;d++)try{let p={chain:n,format:c,limit:o,exclude_spam:s,media_items:!0,normalizeMetadata:!0};a&&(p.cursor=a),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let m=Z(p),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await x.get(g);if(!h.ok)throw new U(h.status,E(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;d<N&&await ee(J)}return{success:!1,error:u}}async getWalletNftCollections(e){let{address:t,chain:n,limit:o=100,excludeSpam:s=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=oe(n),l="Unknown error";for(let c=1;c<=N;c++)try{let u={chain:i,limit:o,exclude_spam:s};a&&(u.cursor=a);let d=Z(u),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${d}`,m=await x.get(p);if(!m.ok)throw new U(m.status,E(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 U&&u.status===400)break;c<N&&await ee(J)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:n,chain:o,format:s="decimal",normalizeMetadata:a=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!R(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=oe(o),u="Unknown error";for(let d=1;d<=N;d++)try{let p={chain:c,format:s,normalizeMetadata:a,media_items:i};l&&(p.include=l);let m=Z(p),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await x.get(g);if(!h.ok)throw new U(h.status,E(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof U&&p.status===400)break;d<N&&await ee(J)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let o=oe(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=Z({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,E(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<N&&await ee(J)}return{success:!1,error:s}}async getWalletHistory(e){let{address:t,chain:n,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=oe(n),g=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let f=1;f<=N;f++)try{let b={chain:m,limit:g,order:u};s&&(b.from_date=s),a&&(b.to_date=a),i!=null&&(b.from_block=i),l!=null&&(b.to_block=l),c&&(b.cursor=c),d!=null&&(b.include_internal_transactions=d),p!=null&&(b.nft_metadata=p);let y=Z(b),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${y}`,k=await x.get(w);if(!k.ok)throw new U(k.status,E(k));let v=k.data;return{success:!0,data:v?.data??v}}catch(b){if(h=b instanceof Error?b.message:"Unknown error",b instanceof U&&b.status===400)break;f<N&&await ee(J)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:o,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=oe(n),m=Math.max(1,Math.min(100,Math.floor(s))),g="Unknown error";for(let h=1;h<=N;h++)try{let f={chain:p,limit:m,order:d};a&&(f.from_date=a),i&&(f.to_date=i),l!=null&&(f.from_block=l),c!=null&&(f.to_block=c),u&&(f.cursor=u),o?.length&&(f.contract_addresses=o);let b=Z(f),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${b}`,w=await x.get(y);if(!w.ok)throw new U(w.status,E(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(f){if(g=f instanceof Error?f.message:"Unknown error",f instanceof U&&f.status===400)break;h<N&&await ee(J)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:o,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=oe(n),h=Math.max(1,Math.min(100,Math.floor(s))),f="Unknown error";for(let b=1;b<=N;b++)try{let y={chain:g,limit:h,order:d,format:m};a&&(y.from_date=a),i&&(y.to_date=i),l!=null&&(y.from_block=l),c!=null&&(y.to_block=c),u&&(y.cursor=u),o?.length&&(y.contract_addresses=o),p!=null&&(y.include_prices=p);let w=Z(y),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,v=await x.get(k);if(!v.ok)throw new U(v.status,E(v));let A=v.data;return{success:!0,data:A?.data??A}}catch(y){if(f=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;b<N&&await ee(J)}return{success:!1,error:f}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!R(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let o=oe(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=Z({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,E(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<N&&await ee(J)}return{success:!1,error:s}}async getWalletPnlSummary(e){let{address:t,chain:n,days:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let s=oe(n),a="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:s};o&&(l.days=o);let c=Z(l),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await x.get(u);if(!d.ok)throw new U(d.status,E(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await ee(J)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:n,days:o,tokenAddresses:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=oe(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:a};o&&(c.days=o),s&&s.length>0&&(c.token_addresses=s.slice(0,25));let u=Z(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await x.get(d);if(!p.ok)throw new U(p.status,E(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await ee(J)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let o=oe(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=Z({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,E(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<N&&await ee(J)}return{success:!1,error:s}}async getWalletApprovals(e){let{address:t,chain:n,limit:o,cursor:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=oe(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:a};o!=null&&(c.limit=o),s&&(c.cursor=s);let u=Z(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await x.get(d);if(!p.ok)throw new U(p.status,E(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof U&&c.status===400)break;l<N&&await ee(J)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let o=oe(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=Z({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,E(c));let u=c.data,d=u?.data??u;return{success:!0,data:oh(d)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<N&&await ee(J)}return{success:!1,error:s}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let o=oe(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=Z({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,E(c));let u=c.data,d=u?.data??u;return{success:!0,data:sh(d)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<N&&await ee(J)}return{success:!1,error:s}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!R(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let s=oe(o),a="Unknown error";for(let i=1;i<=N;i++)try{let l=Z({chains:s}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,u=await x.get(c);if(!u.ok)throw new U(u.status,E(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(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(f=>({token_type:f.tokenType,address:f.address,contract_address:f.address,name:f.name??"",symbol:f.symbol??"",decimals:f.decimals??18,logo:f.logo,balance:f.balance??"0",balance_formatted:f.balanceFormatted??"0",usd_price:f.usdPrice,usd_value:f.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await ee(J)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!R(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let o=oe(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=Z({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,E(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<N&&await ee(J)}return{success:!1,error:s}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!R(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let o=oe(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=Z({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new U(c.status,E(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<N&&await ee(J)}return{success:!1,error:s}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,o="Unknown error";for(let s=1;s<=N;s++)try{let a={};t&&(a.chain=oe(t)),n!=null&&(a.limit=n);let i=Z(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new U(c.status,E(c));let u=c.data,d=u?.data??u;return{success:!0,data:vl(d)}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof U&&a.status===400)break;s<N&&await ee(J)}return{success:!1,error:o}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=oe(t)),n&&(l.time_frame=n),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=Z(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new U(d.status,E(d));let p=d.data,m=p?.data??p;return{success:!0,data:vl(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await ee(J)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=oe(t)),n&&(l.time_frame=n),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=Z(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new U(d.status,E(d));let p=d.data,m=p?.data??p;return{success:!0,data:vl(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<N&&await ee(J)}return{success:!1,error:a}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}async applyYieldValues(e,t,n){if(e.length===0||n.size===0)return;let o=[],s=new Map;if(e.forEach((a,i)=>{let l=n.get(a.token_address.toLowerCase());if(!l?.yieldProtocol||!/^\d+$/.test(a.balance??""))return;let c=BigInt(a.balance);if(c<=0n)return;let u=String(i);s.set(u,a),o.push({key:u,address:a.token_address,rawBalance:c,decimals:a.decimals,priceUSD:a.usd_price??0,yieldProtocol:l.yieldProtocol,yieldAsset:l.yieldAsset,chain:t})}),o.length!==0)try{let a=await Ca(t,o);for(let[i,l]of a){let c=s.get(i);c&&(!Number.isFinite(l.valueUSD)||!Number.isFinite(l.pricePerTokenUSD)||l.pricePerTokenUSD<=0||(c.usd_value=l.valueUSD,c.usd_price=l.pricePerTokenUSD))}}catch{}}};var Pr=class extends P{name="get-token-info";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';category="blockchain-data";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}];service;llm;constructor(e){super(),this.service=new L(e),this.llm=new ce(e?.llm??{})}async run(e,t){let n=e.keyword||"",o=e.prompt||"",s=t?.walletAddress||void 0;if(!n)return{error:"Missing required parameter: keyword"};let a;try{a=ge(e.chain,t)}catch(i){if(i instanceof zt)return await this.researchTokenChainAgnostic(n,o,s);throw i}return await this.searchToken(n,a,o,s)}async researchTokenChainAgnostic(e,t,n){let o=[n?`User's connected wallet address: ${n}`: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(`
|
|
26
|
-
`),s=t?await this.askGeminiWithSearch(t,
|
|
27
|
-
`),[a,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),o?this.findTokenInWallet(o,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,s):Promise.resolve(null)]),c=a.success&&a.data?Array.isArray(a.data)?a.data:[]:[],u=e.toLowerCase(),d=f=>f.symbol?.toLowerCase()===u||f.token_address?.toLowerCase()===u,p=[...c].sort((f,b)=>(d(f)?0:1)-(d(b)?0:1)),m=null,g=p[0];if(g?.token_address){let f=await this.service.getTokenMetadata({address:g.token_address,chain:t});f.success&&f.data&&(m=f.data)}return!m&&g&&(m={...g}),{_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:t,userHoldsToken:!!i,walletBalance:i,token:m,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let o=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1});if(!o.success||!o.data?.result)return null;let s=n.toLowerCase(),a=o.data.result.find(i=>i.token_address.toLowerCase()===s||i.symbol?.toLowerCase()===s||i.name?.toLowerCase().includes(s));return a||null}};var Sr=class extends P{name="get-token-holders";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. ';category="blockchain-data";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}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=ge(e.chain,t),o=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(s){let d=await this.resolveContractAddress(s,n,o);if(!d)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${n?T(n):"the selected chain"}. Try passing contractAddress directly.`};a=d.address,i=d.symbol,l=d.name}let c=await this.service.getTokenHolders({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let u=c.data;return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:n||"default"},totalHolders:u.totalHolders,holdersByAcquisition:u.holdersByAcquisition,holderChange:u.holderChange,holderSupply:u.holderSupply,holderDistribution:u.holderDistribution}}async resolveContractAddress(e,t,n){let o=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var xr=class extends P{name="get-token-analytics";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.`;category="blockchain-data";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}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=ge(e.chain,t),o=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(s){let d=await this.resolveContractAddress(s,n,o);if(!d)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${n?T(n):"the selected chain"}. Try passing contractAddress directly.`};a=d.address,i=d.symbol,l=d.name}let c=await this.service.getTokenAnalytics({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let u=c.data??{};return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:n||"default"},usdPrice:u.usdPrice??null,totalLiquidity:u.totalLiquidity??null,totalFullyDilutedValuation:u.totalFullyDilutedValuation??null,totalBuyVolume:u.totalBuyVolume??null,totalSellVolume:u.totalSellVolume??null,totalBuyers:u.totalBuyers??null,totalSellers:u.totalSellers??null,totalBuys:u.totalBuys??null,totalSells:u.totalSells??null,uniqueWallets:u.uniqueWallets??null,pricePercentChange:u.pricePercentChange??null}}async resolveContractAddress(e,t,n){let o=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Cr=class extends P{name="get-token-score";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.`;category="blockchain-data";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}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=ge(e.chain,t),o=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(s){let p=await this.resolveContractAddress(s,n,o);if(!p)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${n?T(n):"the selected chain"}. Try passing contractAddress directly.`};a=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let u=c.data??{},d=u.metrics??{};return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:n||"default"},score:u.score??null,updatedAt:u.updatedAt??null,metrics:{usdPrice:d.usdPrice??null,liquidityUsd:d.liquidityUsd??null,volumeUsd:d.volumeUsd??null,transactions:d.transactions??null,supply:d.supply??null}}}async resolveContractAddress(e,t,n){let o=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Rr=class extends P{name="get-trending-tokens";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.';category="blockchain-data";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}];service;constructor(e){super(),this.service=new me({baseUrl:e?.pantographUrl})}async run(e,t){let n=ya(e.chain,t),o=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,s=await this.service.getTrendingTokens({chain:n,limit:o});if(!s.success)return{error:s.error||"Failed to fetch trending tokens"};let a=s.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):
|
|
25
|
+
}`,Ss=class extends kt{type="morpho-v2";async fetchApy(e,t,n){let r=Math.floor(Date.now()/1e3),s=await x.post(n.morphoApiUrl,{operationName:"VaultV2ByAddress",query:Sh,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:r-7*86400,endTimestamp:r,interval:"HOUR"}}});if(!s.ok)throw new Error(_(s));let a=s.data?.data?.vaultV2ByAddress,i=Number(a?.netApy),l=Number(a?.avgNetApy);return{avgOverride:Number.isFinite(l)?l:null,samples:(a?.historicalState?.avgNetApy||[]).filter(c=>c?.y!==null&&c?.y!==void 0).map(c=>({timeMs:Number(c?.x)*1e3,fraction:Number(c?.y)})),current:Number.isFinite(i)?i:null,rewards:[]}}};var xs=class extends kt{type="spark";liveRateCall(e){return X(e.contract,Do,"rateProvider")}followUpRateCall(e,t){let n=q(t);return n===null?null:X(n,sn,"getAPR")}decodeLiveRate(e){let t=J(e);return t===null?null:ze(Math.expm1(Number(t)/Bn))}},Cs=class extends kt{type="spark-ethereum";liveRateCall(e){return X(e.contract,Do,"vsr")}decodeLiveRate(e){let t=J(e);if(t===null||t<=0n)return null;let n=Number(t-Ua)/Bn;return n>-1?ze(Math.expm1(Math.log1p(n)*ks)):null}};var Rs=class extends wt{type="spark-l2-susds";balanceIsUnderlying=!1;underlyingCall(){return null}sizeCall(e){return X(e.token,V,"totalSupply")}liveRateCall(e){return X(e.contract,sn,"getAPR")}decodeLiveRate(e){let t=J(e);return t===null?null:ze(Math.expm1(Number(t)/Bn))}convertToAssetsCall(e){return X(e.contract,sn,"getConversionRate")}fetchApy(e,t,n){return rn(e,t,n)}};function qn(o,e,t,n){if(e<=0n||!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)return null;let r=o*e/Ua,s=n-t;return s===0?r:s>0?r*10n**BigInt(s):r/10n**BigInt(-s)}var Fa={"aave-v3":{protocol:new Ts,label:"Aave V3",home:"https://app.aave.com"},"compound-v3":{protocol:new As,label:"Compound V3",home:"https://app.compound.finance"},spark:{protocol:new xs,label:"Spark",home:"https://app.spark.fi"},"spark-ethereum":{protocol:new Cs,label:"Spark",home:"https://app.spark.fi"},"spark-l2-susds":{protocol:new Rs,label:"Spark",home:"https://app.spark.fi"},"morpho-v2":{protocol:new Ss,label:"Morpho V2",home:"https://app.morpho.org"},maple:{protocol:new Ps,label:"Maple",home:"https://app.maple.finance"}},xh=Fa.spark.protocol;function an(o){return Fa[o.type]?.protocol??xh}function We(o){return Fa[o]?.label??null}function Es(o){return Fa[o]?.home??null}var $n="0x0000000000000000000000000000000000000000";function _s(o){let e=parseInt(o,16);return Number.isFinite(e)?{chainId:e}:null}function It(o){if(typeof o=="number")return Number.isInteger(o)&&o>0?`0x${o.toString(16)}`:null;if(typeof o!="string")return null;let e=o.trim().toLowerCase();if(!e)return null;if(!/^(0x[0-9a-f]+|\d+)$/.test(e))return M(e);let t=e.startsWith("0x")?parseInt(e,16):Number(e);return Number.isInteger(t)&&t>0?`0x${t.toString(16)}`:null}var Ch={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function Ba(o){let e=It(o);return e?Ch[e]??null:null}function Iu(o){return["susds","usds","rateProvider"].map(e=>({target:o,callData:D({abi:Il,functionName:e})}))}var Uu=3,Rh={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function Ol(o){let e=It(o),t=e?Rh[e]:void 0;return t?{target:t,callData:D({abi:sn,functionName:"getConversionRate"})}:null}var Eh=new Set(["spark","spark-ethereum","spark-l2-susds","morpho-v2","maple"]),Du="spark-l2-susds";function qa(o){return!!o&&Eh.has(o)}var Ml=o=>{if(o==null||o==="")return null;let e=Number(o);return!Number.isInteger(e)||e<0||e>36?null:e},_h=o=>{if(o==null||o==="")return null;let e=Number(o);return Number.isFinite(e)&&e>0?e:null};function Ns(o){let e=_h(o.yieldAsset?.fixedPrice);return e!==null?e:Number.isFinite(o.priceUSD)?o.priceUSD:0}function Ou(o){if(!qa(o.yieldProtocol)||Ml(o.yieldAsset?.decimals)===null||o.yieldProtocol===Du&&!Ol(o.chain))return!1;let e=Ns(o);return Number.isFinite(e)&&e>0}function Fl(o){let e=[],t=[];for(let n of o)if(!(n.rawBalance<=0n)&&Ou(n)){if(n.yieldProtocol===Du){let r=Ol(n.chain);if(!r)continue;e.push({key:n.key,...r}),t.push(n.key);continue}e.push({key:n.key,target:n.address,callData:D({abi:ft,functionName:"convertToAssets",args:[n.rawBalance]})})}return{calls:e,rateKeys:t}}function $a(o,e,t){let n=new Map(o.map(i=>[i.key,i])),r=new Set(e.rateKeys),s=new Map;e.calls.forEach((i,l)=>{let c=J(t[l]??null);if(c===null)return;if(!r.has(i.key)){s.set(i.key,c);return}let d=n.get(i.key),u=Ml(d?.yieldAsset?.decimals);if(!d||u===null)return;let p=qn(d.rawBalance,c,d.decimals,u);p!==null&&s.set(i.key,p)});let a=new Map;for(let i of o){let l=Xe(i.rawBalance,i.decimals),c=Ns(i),d=s.get(i.key),u={underlyingAmount:l,valueUSD:l*c,pricePerTokenUSD:c,converted:!1};if(d===void 0){a.set(i.key,u);continue}let p=Ml(i.yieldAsset?.decimals);if(p===null){a.set(i.key,u);continue}let m=Xe(d,p),f=m*c;a.set(i.key,{underlyingAmount:m,valueUSD:f,pricePerTokenUSD:l>0?f/l:c,converted:!0})}return a}async function Ha(o,e,t={}){let n=e.map(a=>a.chain==null?{...a,chain:o}:a),r=Fl(n);if(r.calls.length===0)return $a(n,r,[]);let s=await ve(String(o),r.calls,t.rpcUrl);return $a(n,r,s)}async function Ma(o,e,t={}){let n=await Nh(o,e,t.apiBaseUrl);return n?Fu(o,n,t):null}async function Fu(o,e,t={}){let n=Mu(e?.price),r=l=>l!=null&&l>0?l:null;if(!qa(e?.yieldProtocol))return r(n);let s=Ns({key:"price",address:"",rawBalance:0n,decimals:0,priceUSD:n??0,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:o});if(!(s>0))return null;let a=Math.trunc(Mu(e?.decimals)??18);if(!Number.isInteger(a)||a<0||a>36)return r(n);let i={key:"price",address:String(e?.address??"").toLowerCase(),rawBalance:10n**BigInt(a),decimals:a,priceUSD:s,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:o};try{let c=(await Ha(o,[i],t)).get(i.key);return c?.converted?r(c.pricePerTokenUSD):null}catch{return null}}async function Nh(o,e,t){let n=String(e??"").toLowerCase();if(!n)return null;try{return(await new Te(t?{baseUrl:t}:void 0).getYieldPricingTokens(o,[n])).find(a=>String(a?.address??"").toLowerCase()===n)??null}catch{return null}}function Mu(o){if(o==null||o==="")return null;let e=typeof o=="number"?o:Number(o);return Number.isFinite(e)?e:null}var Lh="https://nft.keyring.app",Ih="https://nft.keyring.app",Uh=.01,N=5,ne=1e3,Dh=25,Oh="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Mh="0x0000000000000000000000000000000000000000",L=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function ie(o){return o||je}function oe(o){let e=[];for(let[t,n]of Object.entries(o))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function re(o){return new Promise(e=>setTimeout(e,o))}function Fh(o){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!o||typeof o!="object")return e;let t=o;if("active_protocols"in t||"total_usd_value"in t){let r=t;return{...e,...r,protocols:r.protocols||[]}}let n=t.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(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",positions:r.positionCount??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,account_health_factor:r.accountHealthFactor??null}))}}function Bh(o){if(Array.isArray(o))return o;if(o&&typeof o=="object"){let e=o;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.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(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Bl(o){if(Array.isArray(o))return o;if(o&&typeof o=="object"){let e=o;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var U=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Lh).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Ih).replace(/\/+$/,""),this.pantograph=new Te({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:s=!1,excludeUnverifiedContracts:a=!1,convertYieldValues:i=!0}=e;if(!t)return{success:!1,error:"Address is required"};let l=ie(n),c="Unknown error";for(let d=1;d<=N;d++)try{let u={chain:l,exclude_spam:s,exclude_unverified_contracts:a,limit:100};r&&(u.token_addresses=r);let p=[],m=null;do{m&&(u.cursor=m);let h=oe(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,b=await x.get(g);if(!b.ok)throw new L(b.status,_(b));let y=b.data,w=y?.data??y;w?.result?.length>0&&p.push(...w.result),m=w?.cursor??null}while(m);let f={result:p};if(f?.result?.length>0){f.result=f.result.filter(g=>parseFloat(g.balance||"0")>0),f.result=f.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===Oh?Mh:g.token_address}));let h=await this.enrichTokenPrices(f.result,l);i&&await this.applyYieldValues(f.result,l,h),f.result=f.result.filter(g=>g.usd_value==null||g.usd_value>=Uh)}return{success:!0,data:f}}catch(u){if(c=u instanceof Error?u.message:"Unknown error",u instanceof L&&u.status===400)break;d<N&&await re(ne)}return{success:!1,error:c}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=ie(n),s="Unknown error",a=await this.pantograph.getTokenMetadata(t,r);if(a)return{success:!0,data:a};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${oe({chain:r,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${oe({chain:r,include:"percent_change"})}`)]),d=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;d=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!d){s="Token metadata not found",i<N&&await re(ne);continue}let u=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;u=p?.data??p}return{success:!0,data:{...d,...u?.usd_price?{usd_price:u.usd_price}:{},...u?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:u.usd_price_change_percentage_24h}:{}}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await re(ne)}return{success:!1,error:s}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=100,excludeSpam:s=!1,cursor:a,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let d=ie(n),u=[],p=a,m,f;for(let h=0;h<Dh;h++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:d,limit:r,excludeSpam:s,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!g.success){if(u.length===0)return g;break}let b=g.data;if(!b)break;let{result:y,cursor:w,page:k,page_size:v}=b;if(Array.isArray(y)&&u.push(...y),m=k,f=v,p=typeof w=="string"&&w.trim()?w:void 0,!p)break}return{success:!0,data:{result:u,cursor:p,page:m,page_size:f}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:n,limit:r,excludeSpam:s,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:n,format:c,limit:r,exclude_spam:s,media_items:!0,normalizeMetadata:!0};a&&(p.cursor=a),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let m=oe(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await x.get(f);if(!h.ok)throw new L(h.status,_(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof L&&p.status===400)break;u<N&&await re(ne)}return{success:!1,error:d}}async getWalletNftCollections(e){let{address:t,chain:n,limit:r=100,excludeSpam:s=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=ie(n),l="Unknown error";for(let c=1;c<=N;c++)try{let d={chain:i,limit:r,exclude_spam:s};a&&(d.cursor=a);let u=oe(d),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${u}`,m=await x.get(p);if(!m.ok)throw new L(m.status,_(m));let f=m.data;return{success:!0,data:f?.data??f}}catch(d){if(l=d instanceof Error?d.message:"Unknown error",d instanceof L&&d.status===400)break;c<N&&await re(ne)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:s="decimal",normalizeMetadata:a=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!E(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=ie(r),d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:c,format:s,normalizeMetadata:a,media_items:i};l&&(p.include=l);let m=oe(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await x.get(f);if(!h.ok)throw new L(h.status,_(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof L&&p.status===400)break;u<N&&await re(ne)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=ie(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=oe({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await re(ne)}return{success:!1,error:s}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:c,order:d="DESC",includeInternalTransactions:u,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=ie(n),f=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let g=1;g<=N;g++)try{let b={chain:m,limit:f,order:d};s&&(b.from_date=s),a&&(b.to_date=a),i!=null&&(b.from_block=i),l!=null&&(b.to_block=l),c&&(b.cursor=c),u!=null&&(b.include_internal_transactions=u),p!=null&&(b.nft_metadata=p);let y=oe(b),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${y}`,k=await x.get(w);if(!k.ok)throw new L(k.status,_(k));let v=k.data;return{success:!0,data:v?.data??v}}catch(b){if(h=b instanceof Error?b.message:"Unknown error",b instanceof L&&b.status===400)break;g<N&&await re(ne)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=ie(n),m=Math.max(1,Math.min(100,Math.floor(s))),f="Unknown error";for(let h=1;h<=N;h++)try{let g={chain:p,limit:m,order:u};a&&(g.from_date=a),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),d&&(g.cursor=d),r?.length&&(g.contract_addresses=r);let b=oe(g),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${b}`,w=await x.get(y);if(!w.ok)throw new L(w.status,_(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(g){if(f=g instanceof Error?g.message:"Unknown error",g instanceof L&&g.status===400)break;h<N&&await re(ne)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=ie(n),h=Math.max(1,Math.min(100,Math.floor(s))),g="Unknown error";for(let b=1;b<=N;b++)try{let y={chain:f,limit:h,order:u,format:m};a&&(y.from_date=a),i&&(y.to_date=i),l!=null&&(y.from_block=l),c!=null&&(y.to_block=c),d&&(y.cursor=d),r?.length&&(y.contract_addresses=r),p!=null&&(y.include_prices=p);let w=oe(y),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,v=await x.get(k);if(!v.ok)throw new L(v.status,_(v));let A=v.data;return{success:!0,data:A?.data??A}}catch(y){if(g=y instanceof Error?y.message:"Unknown error",y instanceof L&&y.status===400)break;b<N&&await re(ne)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!E(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=ie(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=oe({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await re(ne)}return{success:!1,error:s}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let s=ie(n),a="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:s};r&&(l.days=r);let c=oe(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await x.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data;return{success:!0,data:p?.data??p}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await re(ne)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=ie(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:a};r&&(c.days=r),s&&s.length>0&&(c.token_addresses=s.slice(0,25));let d=oe(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await x.get(u);if(!p.ok)throw new L(p.status,_(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof L&&c.status===400)break;l<N&&await re(ne)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=ie(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=oe({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await re(ne)}return{success:!1,error:s}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=ie(n),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:a};r!=null&&(c.limit=r),s&&(c.cursor=s);let d=oe(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await x.get(u);if(!p.ok)throw new L(p.status,_(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof L&&c.status===400)break;l<N&&await re(ne)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=ie(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=oe({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Fh(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await re(ne)}return{success:!1,error:s}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=ie(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=oe({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Bh(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await re(ne)}return{success:!1,error:s}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!E(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let s=ie(r),a="Unknown error";for(let i=1;i<=N;i++)try{let l=oe({chains:s}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,d=await x.get(c);if(!d.ok)throw new L(d.status,_(d));let m=d.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(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(g=>({token_type:g.tokenType,address:g.address,contract_address:g.address,name:g.name??"",symbol:g.symbol??"",decimals:g.decimals??18,logo:g.logo,balance:g.balance??"0",balance_formatted:g.balanceFormatted??"0",usd_price:g.usdPrice,usd_value:g.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await re(ne)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!E(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=ie(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=oe({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await re(ne)}return{success:!1,error:s}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!E(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=ie(n),s="Unknown error";for(let a=1;a<=N;a++)try{let i=oe({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await re(ne)}return{success:!1,error:s}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let s=1;s<=N;s++)try{let a={};t&&(a.chain=ie(t)),n!=null&&(a.limit=n);let i=oe(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Bl(u)}}catch(a){if(r=a instanceof Error?a.message:"Unknown error",a instanceof L&&a.status===400)break;s<N&&await re(ne)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=ie(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),s!=null&&(l.security_score=s);let c=oe(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:Bl(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await re(ne)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=ie(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),s!=null&&(l.security_score=s);let c=oe(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await x.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:Bl(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await re(ne)}return{success:!1,error:a}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}async applyYieldValues(e,t,n){if(e.length===0||n.size===0)return;let r=[],s=new Map;if(e.forEach((a,i)=>{let l=n.get(a.token_address.toLowerCase());if(!l?.yieldProtocol||!/^\d+$/.test(a.balance??""))return;let c=BigInt(a.balance);if(c<=0n)return;let d=String(i);s.set(d,a),r.push({key:d,address:a.token_address,rawBalance:c,decimals:a.decimals,priceUSD:a.usd_price??0,yieldProtocol:l.yieldProtocol,yieldAsset:l.yieldAsset,chain:t})}),r.length!==0)try{let a=await Ha(t,r);for(let[i,l]of a){let c=s.get(i);c&&(!Number.isFinite(l.valueUSD)||!Number.isFinite(l.pricePerTokenUSD)||l.pricePerTokenUSD<=0||(c.usd_value=l.valueUSD,c.usd_price=l.pricePerTokenUSD))}}catch{}}};var Oo=class extends P{name="get-token-info";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';category="blockchain-data";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}];service;llm;constructor(e){super(),this.service=new U(e),this.llm=new be(e?.llm??{})}async run(e,t){let n=e.keyword||"",r=e.prompt||"",s=t?.walletAddress||void 0;if(!n)return{error:"Missing required parameter: keyword"};let a;try{a=Ae(e.chain,t)}catch(i){if(i instanceof on)return await this.researchTokenChainAgnostic(n,r,s);throw i}return await this.searchToken(n,a,r,s)}async researchTokenChainAgnostic(e,t,n){let r=[n?`User's connected wallet address: ${n}`: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(`
|
|
26
|
+
`),s=t?await this.askGeminiWithSearch(t,r):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:e,token:null,userHoldsToken:!1,research:s}}async searchToken(e,t,n,r){let s=[r?`User's connected wallet address: ${r}`:null,t?`Current chain (hex chain ID): ${t}, 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(`
|
|
27
|
+
`),[a,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),r?this.findTokenInWallet(r,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,s):Promise.resolve(null)]),c=a.success&&a.data?Array.isArray(a.data)?a.data:[]:[],d=e.toLowerCase(),u=g=>g.symbol?.toLowerCase()===d||g.token_address?.toLowerCase()===d,p=[...c].sort((g,b)=>(u(g)?0:1)-(u(b)?0:1)),m=null,f=p[0];if(f?.token_address){let g=await this.service.getTokenMetadata({address:f.token_address,chain:t});g.success&&g.data&&(m=g.data)}return!m&&f&&(m={...f}),{_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:t,userHoldsToken:!!i,walletBalance:i,token:m,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1});if(!r.success||!r.data?.result)return null;let s=n.toLowerCase(),a=r.data.result.find(i=>i.token_address.toLowerCase()===s||i.symbol?.toLowerCase()===s||i.name?.toLowerCase().includes(s));return a||null}};var Mo=class extends P{name="get-token-holders";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. ';category="blockchain-data";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}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=Ae(e.chain,t),r=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(s){let u=await this.resolveContractAddress(s,n,r);if(!u)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${n?T(n):"the selected chain"}. Try passing contractAddress directly.`};a=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenHolders({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:n||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===r)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Fo=class extends P{name="get-token-analytics";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.`;category="blockchain-data";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}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=Ae(e.chain,t),r=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(s){let u=await this.resolveContractAddress(s,n,r);if(!u)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${n?T(n):"the selected chain"}. Try passing contractAddress directly.`};a=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenAnalytics({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:n||"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(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===r)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Bo=class extends P{name="get-token-score";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.`;category="blockchain-data";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}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=Ae(e.chain,t),r=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(s){let p=await this.resolveContractAddress(s,n,r);if(!p)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${n?T(n):"the selected chain"}. Try passing contractAddress directly.`};a=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},u=d.metrics??{};return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:n||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:u.usdPrice??null,liquidityUsd:u.liquidityUsd??null,volumeUsd:u.volumeUsd??null,transactions:u.transactions??null,supply:u.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===r)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var qo=class extends P{name="get-trending-tokens";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.';category="blockchain-data";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}];service;constructor(e){super(),this.service=new Te({baseUrl:e?.pantographUrl})}async run(e,t){let n=Ia(e.chain,t),r=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,s=await this.service.getTrendingTokens({chain:n,limit:r});if(!s.success)return{error:s.error||"Failed to fetch trending tokens"};let a=s.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):
|
|
28
28
|
<rank>. <name> (<symbol>)
|
|
29
29
|
- Price: <usdPrice>
|
|
30
30
|
- Market Cap: <marketCap>
|
|
31
31
|
- 24h Price Change: <pricePercentChange.24h>
|
|
32
32
|
- 24h Volume: <totalVolume.24h>
|
|
33
|
-
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+3.56%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?T(n):"all",count:a.length,tokens:a}}};var
|
|
33
|
+
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+3.56%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?T(n):"all",count:a.length,tokens:a}}};var qu={"1h":"1h","1d":"24h","1w":"7d","1M":"30d"},Bu=Object.keys(qu),$o=class extends P{name="get-top-gainers";description='List tokens with the highest USD price increase over a chosen timeframe (1h / 1d / 1w / 1M). Returns name & symbol, current USD price, market cap, 24h volume, and the price change % over the selected window. Scoped to a single chain \u2014 pass `chain` to pick the network, otherwise the connected chain (or Ethereum) is used. Use this tool for questions like: "What are today\'s top gainers?", "Biggest pumps this week?", "Which tokens went up most in the last hour?", "Top gainers on Base". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";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 the connected chain, or Ethereum (0x1).',required:!1},{name:"timeFrame",type:"string",description:`Window over which the price change is measured. Allowed values: "1h" (last hour), "1d" (last 24h), "1w" (last 7 days), "1M" (last 30 days). Pick the timeframe that matches the user's question \u2014 e.g. "today" \u2192 "1d", "this week" \u2192 "1w". Defaults to "1d".`,required:!1},{name:"limit",type:"number",description:'Number of top gainers to return. Only set this when the user asks for a specific count (e.g. "show 20 top gainers" \u2192 20). Omit otherwise.',required:!1}];service;constructor(e){super(),this.service=new Te({baseUrl:e?.pantographUrl})}async run(e,t){let n=Ia(e.chain,t),r=typeof e.timeFrame=="string"?e.timeFrame.trim():void 0;if(r&&!Bu.includes(r))return{error:`Invalid timeFrame "${r}". Allowed values: ${Bu.join(", ")}.`};let s=r||void 0,a=s?qu[s]:void 0,i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,l=await this.service.getTopGainers({chain:n,limit:i,duration:a});if(!l.success)return{error:l.error||"Failed to fetch top gainers"};let c=l.data??[];return{_instructions:`Start with a one-line header like "Here are the top gainers 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):
|
|
34
34
|
<rank>. <name> (<symbol>)
|
|
35
35
|
- Price: <usdPrice>
|
|
36
36
|
- Market Cap: <marketCap>
|
|
37
37
|
- Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
|
|
38
38
|
- 24h Volume: <totalVolume.24h>
|
|
39
|
-
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?T(n):"all",timeFrame:s??null,count:c.length,tokens:c}}};var _r=class extends P{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new L(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,o=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(o+"00").slice(0,2)}`}async run(e,t){let n=re(e.address,t),o=G(e.chain,t);if(o){let i=await this.service.getWalletTokenBalances({address:n,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(n,o,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let s=Ce(),a=await Promise.all(s.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",o=e.symbol||"",s=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let o=n.reduce((s,a)=>s+(a.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(o)}`,tokens:n.map(s=>this.toTokenLine(s))}}renderBalancesByChain(e,t){let n=t.map(s=>{let a=s.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=s.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:T(s.chain),total:a,tokens:i}}).filter(s=>s.tokens.length>0).sort((s,a)=>a.total-s.total),o=n.reduce((s,a)=>s+a.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(o)}`,chains:n.map(s=>({chain:s.chain,totalUsdValue:`$${this.truncateUsd(s.total)}`,tokens:s.tokens.map(a=>this.toTokenLine(a))}))}}};var Nr=class extends P{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=re(e.address,t),o=ge(e.chain,t),s=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,a=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,u=Number.isFinite(l)?l:void 0,d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",g=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,f=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,b=Number.isFinite(f)&&f>0?f:10,y=await this.service.getWalletHistory({address:n,chain:o,limit:b,fromDate:s,toDate:a,fromBlock:c,toBlock:u,cursor:d,order:m,includeInternalTransactions:g,nftMetadata:h});if(!y.success)return{error:y.error||"Failed to fetch wallet history"};let k=(y.data?.result||[]).map(v=>{let A=tu(o,v.hash);return A?{...v,explorerUrl:A}:v});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:o||"default",pagination:{cursor:y.data?.cursor??null,hasMore:!!y.data?.cursor},transactionCount:k.length,transactions:k}}};function ah(r){if(r.value_decimal)return r.value_decimal;let e=parseInt(r.token_decimals??"18",10);if(isNaN(e)||e===0)return r.value;try{let t=BigInt(r.value),n=BigInt(10)**BigInt(e),o=t/n,a=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return a?`${o}.${a}`:`${o}`}catch{return r.value}}var Ur=class extends P{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=re(e.address,t),o=ge(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",g=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=g==="send"?"send":g==="receive"?"receive":"all",f=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(_=>typeof _=="string"&&!!_).map(_=>_.trim()):void 0,y,w;if(f){let _=await this.resolveContractAddressBySymbol(f,n,o);_&&(b=[_.address],y=_.symbol,w=_.name)}let k=await this.service.getWalletTokenTransfers({address:n,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let v=n.toLowerCase(),S=(k.data?.result||[]).map(_=>{let H=_.from_address.toLowerCase()===v,q=H?"send":"receive",$=H?_.to_address:_.from_address,te=H?_.to_address_label??void 0:_.from_address_label??void 0,nt=H?_.to_address_entity??void 0:_.from_address_entity??void 0;return{..._,direction:q,amount_formatted:ah(_),counterparty:$,counterparty_label:te,counterparty_entity:nt}}),C=h==="all"?S:S.filter(_=>_.direction===h);if(f&&!b){let _=f.toLowerCase();C=C.filter(H=>(H.token_symbol??"").toLowerCase()===_)}let O=this.buildCounterparties(C);return{walletAddress:n,chain:o||"default",resolvedToken:y?{symbol:y,name:w,contractAddress:b?.[0]}:null,filters:{tokenSymbol:f||null,contractAddresses:b||null,direction:h,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??a,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:C.length,transfers:C,counterparties:O}}async resolveContractAddressBySymbol(e,t,n){let o=e.toLowerCase(),s=await this.service.getWalletTokenBalances({address:t,chain:n});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let a=await this.service.searchTokensByKey({key:e,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}}}buildCounterparties(e){let t=new Map,n=new Map;for(let s of e){let a=s.direction==="send"?t:n,i=s.counterparty.toLowerCase(),l=parseFloat(s.amount_formatted)||0,c=a.get(i);c?(c.total+=l,c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,total:l,count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Ir=class extends P{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=re(e.address,t),o=ge(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",g=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",f=h==="send"?"send":h==="receive"?"receive":"all",b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,y=await this.service.getWalletNftTransfers({address:n,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m,includePrices:g});if(!y.success)return{error:y.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),v=(y.data?.result||[]).map(C=>{let O=C.from_address.toLowerCase()===w,_=O?"send":"receive",H=O?C.to_address:C.from_address,q=O?C.to_address_label??void 0:C.from_address_label??void 0,$=O?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:_,counterparty:H,counterparty_label:q,counterparty_entity:$}}),A=f==="all"?v:v.filter(C=>C.direction===f),S=this.buildCounterparties(A);return{walletAddress:n,chain:o||"default",filters:{contractAddresses:b||null,direction:f,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null,includePrices:g??null},pagination:{cursor:y.data?.cursor??null,pageSize:y.data?.page_size??a,page:y.data?.page??null,hasMore:!!y.data?.cursor},transferCount:A.length,transfers:A,counterparties:S}}buildCounterparties(e){let t=new Map,n=new Map;for(let s of e){let a=s.direction==="send"?t:n,i=s.counterparty.toLowerCase(),l=s.token_name??s.token_address,c=a.get(i);c?(c.tokenIds.add(s.token_id),c.collections.add(l),c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,tokenIds:new Set([s.token_id]),collections:new Set([l]),count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var ih=["all","7","30","60","90"],Lr=class extends P{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=re(e.address,t),o=G(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=ih.includes(s)?s:void 0;if(o){let h=await this.service.getWalletPnlSummary({address:n,chain:o,days:a});return h.success?{walletAddress:n,chain:o,days:a??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(Ce().map(async h=>{let f=await this.service.getWalletPnlSummary({address:n,chain:h,days:a});return{chain:h,data:f.success?f.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:T(h.chain),summary:this.mapSummary(h.data)})),u=l.reduce((h,f)=>h+Number(f.data.total_realized_profit_usd||0),0),d=l.reduce((h,f)=>h+Number(f.data.total_bought_volume_usd||0),0),p=l.reduce((h,f)=>h+Number(f.data.total_sold_volume_usd||0),0),m=l.reduce((h,f)=>h+Number(f.data.total_trade_volume||0),0),g={totalCountOfTrades:l.reduce((h,f)=>h+f.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:l.reduce((h,f)=>h+f.data.total_buys,0),totalSells:l.reduce((h,f)=>h+f.data.total_sells,0),totalBoughtVolumeUsd:d,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",summary:g,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var lh=["all","7","30","60","90"],Ra=25,Or=class extends P{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${Ra}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${Ra}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${Ra}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=re(e.address,t),o=G(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=lh.includes(s)?s:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[];if(o){let d=await this.fetchChainPnl(n,o,a,i,l);return d.ok?{walletAddress:n,chain:o,days:a??"all",filters:{tokenAddresses:d.tokenAddresses??null,resolvedSymbols:d.resolvedFromSymbols.length>0?d.resolvedFromSymbols:null,unresolvedSymbols:d.unresolvedSymbols.length>0?d.unresolvedSymbols:null},tokenCount:d.tokens.length,tokens:d.tokens}:{error:d.error||"Failed to fetch wallet PnL"}}let u=(await Promise.all(Ce().map(async d=>({chain:d,res:await this.fetchChainPnl(n,d,a,i,l)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:T(d.chain),tokenCount:d.res.tokens.length,tokens:d.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:u.reduce((d,p)=>d+p.tokenCount,0),chains:u}}async fetchChainPnl(e,t,n,o,s){let a=[],i=[];o.length>0&&(await Promise.all(o.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?a.push({symbol:o[m],address:p.address}):i.push(o[m])});let l=ch([...a.map(d=>d.address),...s]).slice(0,Ra),c=l.length>0?l:void 0,u=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:u.success,error:u.error,tokens:u.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let o=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function ch(r){let e=new Set,t=[];for(let n of r){let o=n.toLowerCase();e.has(o)||(e.add(o),t.push(n))}return t}var uh=BigInt(2)**BigInt(255),Dr=class extends P{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=re(e.address,t),o=ge(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:o,limit:a,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,d=(c.result||[]).map(h=>dh(h)),p=0,m=0,g=[];for(let h of d){h.isUnlimited&&(m+=1);let f=parseFloat(h.token.usdAtRisk??"");Number.isFinite(f)&&(p+=f);let b=h.token.possibleSpam||h.token.verifiedContract===!1,y=!h.spender.label&&!h.spender.entity;(b||h.isUnlimited&&y)&&g.push(h)}return{walletAddress:n,chain:o||"default",filters:{limit:a,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??a,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:g.length},approvals:d,riskyApprovals:g}}};function dh(r){let e=ph(r.value);return{blockNumber:r.block_number,blockTimestamp:r.block_timestamp??null,transactionHash:r.transaction_hash??null,value:r.value,valueFormatted:r.value_formatted??null,isUnlimited:e,token:{address:r.token.address,addressLabel:r.token.address_label??null,name:r.token.name??null,symbol:r.token.symbol??null,logo:r.token.logo??null,possibleSpam:!!r.token.possible_spam,verifiedContract:r.token.verified_contract??null,currentBalance:r.token.current_balance??null,currentBalanceFormatted:r.token.current_balance_formatted??null,usdPrice:r.token.usd_price??null,usdAtRisk:r.token.usd_at_risk??null},spender:{address:r.spender.address,label:r.spender.address_label??null,entity:r.spender.entity??null,entityLogo:r.spender.entity_logo??null}}}function ph(r){if(!r)return!1;try{return BigInt(r)>=uh}catch{return!1}}var Mr=class extends P{name="get-wallet-defi-positions";description=`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=re(e.address,t),o=G(e.chain,t);if(o){let i=await this.service.getWalletDefiPositions({address:n,chain:o});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:o,positionCount:l.length,positions:l.map(yu)}}let a=(await Promise.all(Ce().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:T(i.chain),positionCount:i.rows.length,positions:i.rows.map(yu)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function yu(r){return{protocolName:r.protocol_name,protocolId:r.protocol_id,protocolUrl:r.protocol_url,protocolLogo:r.protocol_logo,accountHealthFactor:r.account_data?.health_factor??null,position:mh(r.position)}}function mh(r){return{label:r.label,address:r.address,balanceUsd:r.balance_usd,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,tokens:(r.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:r.position_details??null}}var Fr=class extends P{name="get-wallet-defi-protocol-positions";description=`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=re(e.address,t),s=G(e.chain,t);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:n,chain:s});return l.success?l.data?{walletAddress:o,chain:s,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(Ce().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:T(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(hh)}}};function hh(r){return{label:r.label,address:r.address,balanceUsd:r.balance_usd,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,tokens:(r.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:r.position_details??null}}function gh(r){try{return(Number(BigInt(r))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return r}}var Br=class extends P{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let o=ge(e.chain,t),s=await this.service.getTransactionByHash({transactionHash:n,chain:o});if(!s.success||!s.data)return{error:s.error||"Failed to fetch transaction"};let a=s.data,i=(a.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=a.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:a.hash,status:a.receipt_status==="1"?"success":a.receipt_status==="0"?"failed":"unknown",timestamp:a.block_timestamp,blockNumber:a.block_number,from:{address:a.from_address,label:a.from_address_label||null,entity:a.from_address_entity||null},to:a.to_address?{address:a.to_address,label:a.to_address_label||null,entity:a.to_address_entity||null}:null,valueEth:gh(a.value||"0"),fee:a.transaction_fee,gasUsed:a.receipt_gas_used,gasPriceGwei:a.gas_price?(Number(a.gas_price)/1e9).toFixed(4):null,decodedCall:a.decoded_call?{signature:a.decoded_call.signature,label:a.decoded_call.label,params:a.decoded_call.params}:null,decodedEvents:i,contractCreated:a.receipt_contract_address||null,logs:l}}};var bu=new Map;function fh(r){let e=bu.get(r);if(e)return e;let t=Wt({rpcUrl:r});return bu.set(r,t),t}async function wu(r,e,t=[]){let n=await fh(r).rpc(e,t);if(n===void 0)throw new Error(`RPC ${e}: empty result`);return n}function ku(r,e,t){return wu(r,"eth_call",[{to:e,data:t},"latest"])}async function yh(r,e,t){let n=An(r);if(!n)return null;try{return await ku(n,e,t)}catch{return null}}function I(r,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${r}`):console.log(`[LEND] ${r}`,JSON.stringify(e,bh)))}function bh(r,e){return typeof e=="bigint"?`${e}n`:e}var wh=6e4,Tl=new Map;async function ks(r,e){let t=St(e),n=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(n))return[];let o=`${r}|${t}`,s=Tl.get(o);if(s&&Date.now()-s.at<wh)return s.markets;let a=kh(r,t,n),i=a.then(l=>l.markets);return Tl.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||Tl.delete(o)}),i}async function Ea(r,e){return(await ks(r,e)).length>0}async function kh(r,e,t){try{let n=`${r}/supply/v2?chainId=${t}&limit=100&page=1`;I("catalog: GET",n);let o=await x.get(n);if(!o.ok){let a=o.status>=400&&o.status<500;return I(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:o.status,message:E(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=vh(a,e);return i?[i]:[]});return I("catalog: got markets",{chain:e,rawItems:o.data?.data?.items?.length??0,usable:s.length,tokens:s.map(a=>a.token)}),{markets:s,answered:!0}}catch(n){return I("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:n?.message}),{markets:[],answered:!1}}}function vu(r,e){let t=e.trim().toLowerCase();if(!t)return[];if(R(t))return r.filter(o=>o.contract===t||o.token===t);let n=r.filter(o=>o.name.trim().toLowerCase()===t);return n.length>0?n:r.filter(o=>{let s=o.name.trim().toLowerCase(),a=o.protocol.trim().toLowerCase();return s.includes(t)||t.includes(s)||a.includes(t)||t.includes(a)})}function vh(r,e){if(r?.isDeleted===!0)return null;let t=typeof r?.contract=="string"?r.contract.toLowerCase():"";if(!R(t))return null;let n=typeof r?.token=="string"&&R(r.token)?r.token.toLowerCase():t,o=Number(r?.rating?.balanceScore),s=r?.type?.trim()||"unknown";return{chain:e,name:r?.name?.trim()||"USDC lending market",protocol:r?.protocolId?.name?.trim()||"Unknown",protocolLabel:Ne(s),protocolUrl:r?.protocolId?.domain?.trim()||null,type:s,contract:t,token:n,platformScore:Number.isFinite(o)?o:null}}function Al(){return Ce()}async function _a(r){let e=Al(),t=await Promise.all(e.map(n=>Ea(r,n)));return e.filter((n,o)=>t[o])}async function Na(r,e){let t=F(e);return t?Ea(r,t):!1}async function Tu(r,e){let t=e.map(s=>F(s)).filter(s=>!!s),n=[...new Set(t)],o=await Promise.all(n.map(s=>Ea(r,s)));return n.filter((s,a)=>o[a])}function Un(r){return ys(r)}var Au=6;async function Pu(r,e,t){let n=e.map(w=>R(w)?w.toLowerCase():null);if(n.every(w=>w===null))return I("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=Pa(r),s;try{I("discovery: probing 5 accessors per token",{chain:r,tokens:n,psm:o}),s=await pe(r,[...n.flatMap(w=>w?Th(w):[]),...o?cu(o):[]])}catch(w){return I("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:r,message:w?.message}),e.map(()=>null)}let a=o?s.slice(s.length-uu):[],i=B(a[0])?.toLowerCase()??null,l=B(a[1]),c=B(a[2]),u=i&&l&&c?{susds:i,usds:l,oracle:c}:null;o&&I("discovery: PSM3 lookup",{psm:o,susds:i,usds:l,oracle:c});let d=0,p=n.map(w=>{if(!w)return null;let k=s.slice(d,d+Au);return d+=Au,I("discovery: probe answers",{token:w,"POOL()":B(k[0]),"UNDERLYING_ASSET_ADDRESS()":B(k[1]),"baseToken()":B(k[2]),"asset()":B(k[3]),"vsr()":X(k[4])?.toString()??null,"manager()":B(k[5])}),{token:w,slice:k}}),m=new Set;for(let w of p){if(!w)continue;let k=B(w.slice[0]);k&&B(w.slice[1])&&m.add(k.toLowerCase())}let g=await Ah(r,[...m]);m.size>0&&I("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let h=new Map;for(let w of p){if(!w||B(w.slice[0])&&B(w.slice[1])||B(w.slice[2])||!B(w.slice[3]))continue;let v=B(w.slice[5]);v&&h.set(w.token,v.toLowerCase())}let f=await Ph(r,h);h.size>0&&I("discovery: Maple manager authentication",{claimed:[...h.keys()],genuine:[...f]});let b=p.flatMap(w=>w?B(w.slice[0])&&B(w.slice[1])||B(w.slice[2])?[]:f.has(w.token)?[]:B(w.slice[3])?[w.token]:[]:[]),y=await Sh(r,[...new Set(b)],t);return b.length>0&&I("discovery: Morpho vault lookup",{asked:[...new Set(b)],recognised:[...y.keys()]}),p.map(w=>{if(!w)return null;let{token:k,slice:v}=w,A={chain:r,protocolUrl:null,token:k,platformScore:null};if(u&&k===u.susds)return I("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...A,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Ne("spark-l2-susds"),protocolUrl:Un("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let S=B(v[0]);if(S&&B(v[1])){let C=g.has(S.toLowerCase());return I("discovery: classified",{token:k,as:C?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:S}),C?{...A,name:"Aave v3",protocol:"AAVE",protocolLabel:Ne("aave-v3"),protocolUrl:Un("aave-v3"),type:"aave-v3",contract:S}:null}if(B(v[2]))return I("discovery: classified",{token:k,as:"compound-v3"}),{...A,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Ne("compound-v3"),protocolUrl:Un("compound-v3"),type:"compound-v3",contract:k};if(B(v[3])){if(f.has(k))return I("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...A,name:"Maple",protocol:"MAPLE",protocolLabel:Ne("maple"),protocolUrl:Un("maple"),type:"maple",contract:k};if(y.has(k)){I("discovery: classified",{token:k,as:"morpho-v2"});let _=y.get(k)||"Morpho V2";return{...A,name:_,protocol:"MORPHO",protocolLabel:Ne("morpho-v2"),protocolUrl:Un("morpho-v2"),type:"morpho-v2",contract:k}}let O=X(v[4])!==null;return I("discovery: classified",{token:k,as:O?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),O?{...A,name:"Spark",protocol:"SPARK",protocolLabel:Ne("spark-ethereum"),protocolUrl:Un("spark-ethereum"),type:"spark-ethereum",contract:k}:{...A,name:"Spark",protocol:"SPARK",protocolLabel:Ne("spark"),protocolUrl:Un("spark"),type:"spark",contract:k}}return I("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function Th(r){return[{target:r,callData:D({abi:Tr,functionName:"POOL"})},{target:r,callData:D({abi:Tr,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:r,callData:D({abi:Pt,functionName:"baseToken"})},{target:r,callData:D({abi:at,functionName:"asset"})},{target:r,callData:D({abi:Ar,functionName:"vsr"})},{target:r,callData:D({abi:fl,functionName:"manager"})}]}async function Ah(r,e){if(e.length===0)return new Set;try{let t=await pe(r,e.map(n=>({target:n,callData:D({abi:ml,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,o)=>B(t[o])!==null))}catch{return new Set}}async function Ph(r,e){if(e.size===0)return new Set;let t=[...e.entries()];try{let n=await pe(r,t.map(([,o])=>({target:o,callData:D({abi:yl,functionName:"pool"})})));return new Set(t.filter(([o],s)=>B(n[s])?.toLowerCase()===o.toLowerCase()).map(([o])=>o))}catch{return new Set}}async function Sh(r,e,t){let n=parseInt(r,16);if(e.length===0||!Number.isFinite(n))return new Map;let o=await Promise.all(e.map(async s=>{try{let a=await x.post(t,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:n}}),i=a.ok?a.data?.data?.vaultV2ByAddress:null;return i?[s,i.name?.trim()||""]:null}catch{return null}}));return new Map(o.filter(s=>s!==null))}var xh=.01;function Ch(r){return r.reduce((e,t)=>t.conditions===null?e+t.apyPercent:e,0)}function Rh(r,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),n=rs();n[r]!==t&&vn({...n,[r]:t})}var qr=class{constructor(e,t,n){this.coinPoolBaseUrl=e;this.endpoints=t;this.describer=n}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(e,t,n){let o=Date.now();I("describeReceiptTokens: START",{chain:e,tokens:t,hasRpcUrl:!!n});let s=St(e);s&&Rh(s,n);let a=s?bs(s):null,i=[...new Set(t.filter(R).map(p=>p.toLowerCase()))];if(I("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!a,wanted:i}),!s||!a||i.length===0)return I("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!a,wantedCount:i.length}),new Map;I("describeReceiptTokens: on-chain discovery for",i);let l=await Pu(s,i,this.endpoints.morphoApiUrl),u=[...new Map(i.flatMap((p,m)=>{let g=l[m];return I("describeReceiptTokens: discovery result",{token:p,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[p,g]]:[]})).entries()];if(u.length===0)return I("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;I("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([p,m])=>({token:p,type:m.type,contract:m.contract}))});let d=await this.describer.describe(s,a,u.map(([,p])=>p));return I("describeReceiptTokens: DONE",{ms:Date.now()-o,overviews:d.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(d.map((p,m)=>[u[m][0],p]))}async findMarketByReceiptToken(e,t,n){if(I("findMarketByReceiptToken: called",{chain:e,receiptToken:t,hasRpcUrl:!!n}),!R(t))return I("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:t}),null;let s=(await this.describeReceiptTokens(e,[t],n)).get(t.toLowerCase())??null;return I("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(e){if(!R(e.address))return[];let t=await Tu(this.coinPoolBaseUrl,e.chains);return(await Promise.all(t.map(o=>this.positionsForChain(o,e.address)))).flat().sort((o,s)=>s.suppliedUsdc-o.suppliedUsdc||(s.avgApyPercent??0)-(o.avgApyPercent??0))}async describeResolvedMarkets(e,t){let n=St(e),o=n?bs(n):null;return n&&o?this.describer.describe(n,o,t):[]}async positionsForChain(e,t){let n=bs(e),o=await ks(this.coinPoolBaseUrl,e);if(!n||o.length===0)return[];let s=await this.describer.readBalances(e,t,o);if(s.length===0)return[];let a=await this.describer.describe(e,n,s.map(l=>l.market)),i=await this.describer.convertToUnderlying(e,s,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=i[c];return u<xh?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Ch(l.rewards))/100}]})}};var Pl=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var $r=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return _a(this.coinPoolBaseUrl)}async isSupported(e){return Na(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=F(e);return t?ks(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let n=await this.getMarkets(e);return vu(n,t)}canSupply(e){return Pl.includes(e.type)}async readReceiptToken(e,t){let n=Jt(t).balanceIsUnderlying;try{let o=await pe(e,[{target:t.token,callData:D({abi:V,functionName:"symbol"})},{target:t.token,callData:D({abi:V,functionName:"decimals"})}]);return{symbol:Gn(o[0]),decimals:Kn(o[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};var Eh={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},_h={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",130:"proto_unichain_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},Nh={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Uh={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function Ua(r){let e=$h(r.chain);return(e===null?null:Ih(r,e))??ys(r.type)??qh(r,e)}function Ih(r,e){switch(r.type){case"morpho-v2":{let t=Eh[e];if(!t||!r.contract)return null;let n=`https://app.morpho.org/${t}/vault/${Sl(r.contract)}`,o=Dh(r.name);return o?`${n}/${o}`:n}case"aave-v3":{let t=_h[e],n=Lh(r);return!t||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${Sl(n)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=Nh[e],n=Fh(r);return!t||!n?null:`https://app.spark.fi/savings/${t}/${n}`}case"compound-v3":{let t=Uh[e],n=Mh(r);return!t||!n?null:`https://app.compound.finance/?market=${n}-${t}`}default:return null}}function Lh(r){let e=r.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Oh=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Dh(r){let e=r?.trim().toLowerCase()||"";return!e||Oh.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Mh(r){let e=r.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Fh(r){let e=r.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(e))return e;let t=`${r.name||""} ${r.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(t.includes(o))return o;if(r.type==="spark-ethereum")return Bh[r.contract?.trim().toLowerCase()||""]??null;let n=r.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(n)||n.startsWith("s")?null:`s${n}`}var Bh={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function qh(r,e){let t=r.protocolUrl?.trim();if(!t)return null;let n=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let o=new URL(n);return e!==null&&o.searchParams.set("chainId",String(e)),r.contract&&o.searchParams.set("contract",Sl(r.contract)),o.toString()}catch{return n}}function Sl(r){let e=r.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function $h(r){let e=r?.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)&&t>0?t:null}var Hh=new Set(["spark","spark-ethereum"]),Vh=8;function Wh(r,e,t){if(r.market.type!=="spark-l2-susds")return X(e);let n=X(e);return n===null||r.tokenDecimals===null?null:_n(r.rawBalance,n,r.tokenDecimals,t)}var Ia=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new xl(Vh);pantograph=new me;async describe(e,t,n){if(n.length===0)return[];I("describe: START",{chain:e,count:n.length,types:n.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(e,n);I("describe: assets resolved",o);let[a,i]=await Promise.all([this.readMarketState(e,n,o),Promise.all(n.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,t,o[c]))))]);return I("describe: on-chain state",a),I("describe: APY fetched",i.map((l,c)=>({type:n[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),n.map((l,c)=>{let{totalSuppliedUsdc:u,liveApyFraction:d}=a[c],p=i[c].sizeOverride??u,m=Gh(i[c].samples,d??i[c].current,i[c].rewards,i[c].avgOverride??null);return I("describe: summarised",{market:l.name,type:l.type,liveFrom:d!==null?"on-chain":i[c].current!==null?"api":"none",rawSamples:i[c].samples.length,historyPoints:m.history.length,currentApyPercent:m.currentApyPercent,avgApyPercent:m.avgApyPercent,apyChangePercent:m.apyChangePercent,totalSuppliedUsdc:p,asset:o[c]?.symbol}),{...l,protocolUrl:Ua({...l,asset:o[c],shareSymbol:s[c]}),asset:o[c],totalSuppliedUsdc:p,avgApyPercent:m.avgApyPercent,currentApyPercent:m.currentApyPercent,baseApyPercent:m.baseApyPercent,rewardApyPercent:m.rewardApyPercent,rewards:m.rewards,apyChangePercent:m.apyChangePercent,apyHistory:m.history}})}async readBalances(e,t,n){let o=D({abi:V,functionName:"balanceOf",args:[t]}),s=D({abi:V,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await pe(e,a);return n.flatMap((l,c)=>{let u=X(i[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Kn(i[c*2+1])}]})}async convertToUnderlying(e,t,n){let o=[],s=t.map(i=>{let l=Jt(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await pe(e,o);return t.map((i,l)=>{let c=n[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return qe(i.rawBalance,c);let u=Wh(i,a[s[l]],c);return u===null?qe(i.rawBalance,i.tokenDecimals??c):qe(u,c)})}async resolveAssets(e,t){let n={address:Nn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(p=>{let m=Jt(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),a;try{let p=o.length>0?await pe(e,o):[];a=s.map(m=>m<0?null:B(p[m]))}catch{a=t.map(()=>null)}a=a.map((p,m)=>p??t[m]?.assetAddress??null);let i=[...new Set(a.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,u]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i),this.readShareSymbols(e,t)]);return{assets:a.map(p=>{if(!p)return n;let m=p.toLowerCase(),g=l.get(m),h=c.get(m)??null;return g?.decimals!==null&&g?.decimals!==void 0?{address:p,decimals:g.decimals,symbol:g.symbol??null,logo:h}:{address:p,decimals:NaN,symbol:null,logo:h}}),shareSymbols:u}}async readShareSymbols(e,t){let n=D({abi:V,functionName:"symbol"}),o=[],s=t.map(a=>!Hh.has(a.type)||!a.contract?-1:(o.push({target:a.contract,callData:n}),o.length-1));if(o.length===0)return t.map(()=>null);try{let a=await pe(e,o);return s.map(i=>i<0?null:Gn(a[i]))}catch{return t.map(()=>null)}}async readAssetMetadata(e,t){let n=new Map;if(t.length===0)return n;let o=D({abi:V,functionName:"decimals"}),s=D({abi:V,functionName:"symbol"});try{let a=await pe(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{n.set(i,{decimals:Kn(a[l*2]),symbol:Gn(a[l*2+1])})})}catch{}return n}async fetchAssetLogos(e,t){let n=new Map;if(t.length===0)return n;try{let o=await this.pantograph.getTokensMetadata(t,e);for(let[s,a]of Object.entries(o)){let i=a.icon_image||a.logo||a.logoURI;i&&n.set(s.toLowerCase(),i)}}catch{}return I("resolveAssets: logos",{chain:e,requested:t.length,found:n.size}),n}async readMarketState(e,t,n){let o=[],s=t.map((u,d)=>{let p=Jt(u),m=n[d],g={market:u,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(u,m));let h=p.liveRateCall(u,m);return h&&(g.rate=o.length,o.push(h)),g}),a=await pe(e,o),i=[],l=s.map(u=>{if(u.rate<0)return-1;let d=u.protocol.followUpRateCall(u.market,a[u.rate]);return d?(i.push(d),i.length-1):-1}),c=i.length>0?await pe(e,i):[];return s.map((u,d)=>{let p=u.rate<0?null:a[u.rate],m=l[d]>=0?c[l[d]]:p;return{totalSuppliedUsdc:u.protocol.decodeSize(a[u.size],u.asset),liveApyFraction:m===null?null:u.protocol.decodeLiveRate(m)}})}async fetchApy(e,t,n){try{I("fetchApy: requesting",{market:e.name,type:e.type,asset:n?.symbol});let o=await Jt(e).fetchApy(e,t,this.endpoints,n);return I("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return I("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},xl=class{constructor(e){this.limit=e}limit;active=0;waiting=[];async run(e){this.active>=this.limit?await new Promise(t=>this.waiting.push(t)):this.active++;try{return await e()}finally{let t=this.waiting.shift();t?t():this.active--}}};function Yh(r,e){let t=cs(Date.now()),n=new Map,o=null;for(let i of r)!Number.isFinite(i.timeMs)||!Number.isFinite(i.fraction)||i.fraction<0||cs(i.timeMs)>t||((!o||i.timeMs>o.timeMs)&&(o=i),n.set(i.timeMs,i.fraction));let s=[...n.entries()].sort((i,l)=>i[0]-l[0]).map(([i,l])=>({date:new Date(i).toISOString(),apyPercent:l*100})),a=e??(o&&cs(o.timeMs)===t?o.fraction:null);return{history:s,live:a}}function Gh(r,e,t=[],n=null){let{history:o,live:s}=Yh(r,e),a=s===null?null:s*100,i=t.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=i.length===0?null:i.reduce((m,g)=>m+g.apyPercent,0),c=a===null?null:a+(l??0),u={baseApyPercent:a,rewardApyPercent:l,rewards:i},d=n!==null&&Number.isFinite(n)?n*100:null;if(o.length===0)return{history:o,avgApyPercent:d,currentApyPercent:c,apyChangePercent:null,...u};let p=o.reduce((m,g)=>m+g.apyPercent,0);return{history:o,avgApyPercent:d??p/o.length,currentApyPercent:c,apyChangePercent:jh(o,a),...u}}var Su=3600*1e3,Kh=Su/2;function jh(r,e){if(e===null)return null;let t=Date.now()-Su,n=null,o=Number.POSITIVE_INFINITY;for(let s=r.length-1;s>=0;s--){let a=Math.abs(Date.parse(r[s].date)-t);if(a>o)break;o=a,n=r[s]}return!n||o>Kh?null:e-n.apyPercent}function xu(r,e){if(!Number.isFinite(r))return r;let t=10**e,n=Number((r*t).toPrecision(15));return(r<0?-Math.floor(-n):Math.floor(n))/t+0}var Xe=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",n={lendingRatesBaseUrl:e.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},o=new Ia(n);this.read=new qr(t,n,o),this.supply=new $r(t)}async listSupportedChains(){return this.supply.listChains()}async isSupported(e){return this.supply.isSupported(e)}async getMarkets(e){return this.supply.getMarkets(e)}async findMarket(e,t){return this.supply.findMarket(e,t)}canSupply(e){return this.supply.canSupply(e)}async readReceiptToken(e,t){return this.supply.readReceiptToken(e,t)}async describeReceiptTokens(e,t,n){return this.read.describeReceiptTokens(e,t,n)}async findMarketByReceiptToken(e,t,n){return this.read.findMarketByReceiptToken(e,t,n)}async describeResolvedMarkets(e,t){return this.read.describeResolvedMarkets(e,t)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async n=>this.read.describeResolvedMarkets(n,await this.getMarkets(n))))).flat().sort((n,o)=>(o.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};var vs="{market}",Eu=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],Oa=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],_u="[[LIST]]",Nu=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',Uu=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function Iu(r,e,t){let[n]=zh([r],e,t),[o]=r.canSupply?Cl(r,e,t):[];return{name:r.name?.trim()||r.protocol,protocol:r.protocol,protocolUrl:r.protocolUrl,chain:t,apyPercent:r.apyPercent,detailPrompt:n?.prompt??"",detailLabel:n?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function zh(r,e,t){return Lu(r,{labelTemplate:La(e.detail_button_label),promptTemplate:La(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${vs}`,...t===void 0?{}:{chainName:t}})}function Cl(r,e,t){return Lu([r],{labelTemplate:La(e.supply_button_label),promptTemplate:La(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${vs}`,promptFallback:`supply to ${vs}`,...t===void 0?{}:{chainName:t},max:1})}function Lu(r,e){let t=typeof e.chainName=="string"?e.chainName.trim():"",n=[],o=new Set;for(let s of r){if(e.max!==void 0&&n.length>=e.max)break;let a=s.name?.trim();!a||o.has(a.toLowerCase())||(o.add(a.toLowerCase()),n.push({label:Cu(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:Cu(Xh(e.promptTemplate),a,e.promptFallback)+Qh(s.contract,t)}))}return n}function Xh(r){let[e,t]=[r[0],r[1]];return e===void 0||e===e.toLowerCase()||t!==void 0&&t!==t.toLowerCase()?r:e.toLowerCase()+r.slice(1)}function La(r){return typeof r=="string"?r:""}function Qh(r,e){let t=r?.trim();if(!t||!/^0x[a-fA-F0-9]{40}$/.test(t))return"";let n=e?.trim();return n?` (market: ${t} - ${n})`:` (market: ${t})`}function Cu(r,e,t,n=!0){let s=r&&(!n||r.includes(vs))?r:t;return Jh(s).split(vs).join(e).replace(/\s+/g," ").trim()}var Ru="{chain}";function Jh(r){if(!r.includes(Ru))return r;let e=Ru.replace(/[{}]/g,"\\$&");return r.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}var Da=[{id:"aave-v3",label:"Aave v3",types:["aave-v3"],aliases:["aave","aavev3","aave3","ave"]},{id:"compound-v3",label:"Compound v3",types:["compound-v3"],aliases:["compound","compoundv3","compound3","comet","comp"]},{id:"spark-any",label:"Spark",types:["spark","spark-ethereum"],aliases:["spark","sparkfi","sparklend","sparkprotocol"]},{id:"morpho-v2",label:"Morpho",types:["morpho-v2"],aliases:["morpho","morphov2","morpho2","morphoblue","metamorpho"]}],El=Da.map(r=>r.label),Rl={euler:"Euler",venus:"Venus",radiant:"Radiant",benqi:"Benqi",qi:"Benqi",fluid:"Fluid",instadapp:"Fluid",silo:"Silo",moonwell:"Moonwell",sonne:"Sonne",granary:"Granary",ironbank:"Iron Bank",cream:"Cream",maker:"Maker",makerdao:"Maker",sky:"Sky",justlend:"JustLend",kamino:"Kamino",solend:"Solend",marginfi:"marginfi",save:"Save",curve:"Curve",yearn:"Yearn",convex:"Convex",pendle:"Pendle",ethena:"Ethena",gearbox:"Gearbox",notional:"Notional",exactly:"Exactly",seamless:"Seamless",zerolend:"ZeroLend",dforce:"dForce",tectonic:"Tectonic",liqee:"Liqee"};function Ou(r){let e=typeof r=="string"?r.trim():"";if(!e)return{kind:"none"};let t=ng(e);if(!t)return{kind:"none"};let n=Zh(t);if(n){let s=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>s.has(a.type)}}let o=tg(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function Zh(r){let e=Da.filter(t=>t.aliases.includes(r));if(e.length===1)return e[0];if(e.length>1)return null;if(r.length>=3){let t=Da.filter(n=>n.aliases.some(o=>o.includes(r)||r.includes(o)));if(t.length===1)return t[0];if(t.length>1)return null}return eg(r)}function eg(r){let e=null,t=!1;for(let n of Da)for(let o of n.aliases){let s=Du(o);if(s===0||Math.abs(o.length-r.length)>s)continue;let a=Mu(r,o,s);a>s||(!e||a<e.distance?(e={spec:n,distance:a},t=!1):a===e.distance&&n!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function Du(r){return r.length<=4?0:r.length<=9?2:3}function tg(r){let e=Rl[r];if(e)return e;if(r.length>=4){let o=new Set(Object.entries(Rl).filter(([s])=>s.length>=4&&(s.includes(r)||r.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let t=null,n=!1;for(let[o,s]of Object.entries(Rl)){let a=Du(o);if(a===0||Math.abs(o.length-r.length)>a)continue;let i=Mu(r,o,a);i>a||(!t||i<t.distance?(t={label:s,distance:i},n=!1):i===t.distance&&s!==t.label&&(n=!0))}return t&&!n?t.label:null}function ng(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function Mu(r,e,t){if(r===e)return 0;if(!r.length)return e.length;if(!e.length)return r.length;let n=new Array(e.length+1),o=Array.from({length:e.length+1},(a,i)=>i),s=new Array(e.length+1);for(let a=1;a<=r.length;a++){s[0]=a;let i=s[0];for(let c=1;c<=e.length;c++){let u=o[c-1]+(r[a-1]===e[c-1]?0:1),d=Math.min(s[c-1]+1,o[c]+1,u);a>1&&c>1&&r[a-1]===e[c-2]&&r[a-2]===e[c-1]&&(d=Math.min(d,n[c-2]+1)),s[c]=d,d<i&&(i=d)}if(i>t)return t+1;let l=n;n=o,o=s,s=l}return o[e.length]}function le(r,e){return r==null?null:xu(r,e)}var Pe=2,Zt=2;function Ma(r){let e=le(r.currentApyPercent,Pe),t=r.rewards.map(s=>({apyPercent:le(s.apyPercent,Pe)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),n=r.rewardApyPercent===null?null:t.reduce((s,a)=>s+Math.round(a.apyPercent*100),0)/100;if(n===null||e===null)return{currentApyPercent:e,rewardApyPercent:n,rewards:t,baseApyPercent:le(r.baseApyPercent,Pe)};let o=Math.round(e*100)-Math.round(n*100);return{currentApyPercent:e,rewardApyPercent:n,rewards:t,baseApyPercent:o/100}}var rg=["apy","score","size"],Fu=3,Bu=40,Hr=class extends P{name="get-lending-markets";kind="ui";description='BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${El.join(", ")}. Set it whenever the user names a protocol \u2014 "supply aave", "morpho vaults", "l\xE3i su\u1EA5t b\xEAn Compound" \u2014 and pass what they wrote, VERBATIM. Do NOT correct their spelling, do NOT translate it, and do NOT map it to a name from the supported list yourself: misspellings are resolved for you, and a protocol that is NOT supported is reported back so you can tell the user. Pass it even when you believe the protocol is unsupported \u2014 that is how the user gets told. OMIT it when the user named no protocol; never guess one to narrow a list they asked for in full.`,required:!1},{name:"limit",type:"number",description:`How many markets to return, 1-${Bu}. Default ${Fu} \u2014 the top markets by the chosen ranking, which answers "where can I earn on my USDC" on its own. Raise it ONLY when the user asks for more than that, for the full list, or to compare broadly; lower it when they want a shorter shortlist.`,required:!1},{name:"sort",type:"string",description:'Ranking: "apy" (default, highest live protocol APY first), "score" (safest / best-rated first \u2014 use when the user asks for safe, reliable or trusted markets), or "size" (largest market first \u2014 use when the user asks for the biggest or most liquid markets).',required:!1},...Eu,...Oa];service;constructor(e){super(),this.service=new Xe(e)}async run(e,t){let n=G(e.chain,void 0),o=n?null:F(t?.chain),s=n??o,a=s?await this.service.isSupported(s):!1,i=a?[]:await this.service.listSupportedChains();if(s&&!a)return{_instructions:`There are no lending markets on ${T(s)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:T(s),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:i.map(y=>T(y))};let l=Ou(e.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,u=sg(e.sort),d=ag(e.limit),p=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?p.filter(y=>l.matches(y)):p;if(l.kind==="supported"&&m.length===0&&p.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?T(s):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?T(s):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(p.map(y=>y.protocol))]};let g=[...m].sort(og[u]).slice(0,d),h=g.map(y=>Iu({name:y.name,contract:y.contract,protocol:y.protocol,protocolUrl:y.protocolUrl,apyPercent:le(y.currentApyPercent,Pe),canSupply:this.service.supply.canSupply(y)},e,T(y.chain))),b={component:"LendingMarketList",props:{chain:s?T(s):"all",multiChain:new Set(h.map(y=>y.chain)).size>1,markets:h}};return{...h.length>0?{ui:b}:{},_instructions:this.instructions(g,u,h.length>0,l.kind==="supported"?l.label:null),chain:s?T(s):"all",chainsQueried:c.map(y=>T(y)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:u,marketCount:h.length,totalMarketsAvailable:m.length,marketNames:h.map(y=>y.name)}}unsupportedProtocol(e){let t=e.kind==="unsupported",n=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${n}, which has no lending markets here. In their language: tell them plainly that ${n} is ${t?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${n} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:t?e.label:e.requested,protocolSupported:!1,supportedProtocols:[...El],marketCount:0,marketNames:[]}}instructions(e,t,n=!1,o=null){if(e.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let s={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[t];return[o?`These are the ${o} lending markets the user can supply to, ${s}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,`Write your reply in TWO parts separated by a line containing exactly ${_u} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",t==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${T(e[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${s} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",n?Nu:""].filter(Boolean).join(" ")}},og={apy:(r,e)=>(e.currentApyPercent??-1)-(r.currentApyPercent??-1),score:(r,e)=>(e.platformScore??-1)-(r.platformScore??-1),size:(r,e)=>(e.totalSuppliedUsdc??-1)-(r.totalSuppliedUsdc??-1)};function sg(r){let e=typeof r=="string"?r.trim().toLowerCase():"";return rg.includes(e)?e:"apy"}function ag(r){let e=typeof r=="number"?r:Number(r);return!Number.isFinite(e)||e<1?Fu:Math.min(Math.floor(e),Bu)}function qu(r){let{currentApyPercent:e,avgApyPercent:t,totalSuppliedUsdc:n,rewardApyPercent:o,baseApyPercent:s,platformScore:a}=r;return r.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:o!==null&&s!==null&&o>s*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:e!==null&&t!==null&&t>0&&e>t*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:n!==null&&n<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&n!==null&&n>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:n!==null&&n>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}function Fa(r){let e=typeof r=="string"?r.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(e);if(t)return t[1];let n=/0x[a-fA-F0-9]{40}/.exec(e);return n&&n[0]!==e?n[0]:e}var Vr=class extends P{name="get-lending-market-detail";category="blockchain-data";description='Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...Oa];service;constructor(e){super(),this.service=new Xe(e)}async run(e,t){let o=G(e.chain,void 0)??F(t?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let d=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(o),chainsWithLendingMarkets:d.map(p=>T(p)),_instructions:`There are no lending markets on ${T(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=Fa(e.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let a=await this.service.findMarket(o,s);if(a.length===0)return{error:"market_not_found",market:s,chain:T(o),_instructions:`No lending market matching "${s}" exists on ${T(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(a.length>1)return{error:"ambiguous_market",market:s,chain:T(o),candidates:a.map(d=>({marketName:d.name,protocol:d.protocol})),_instructions:`"${s}" matches ${a.length} different markets on ${T(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${T(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let i=a[0],l=await this.describeOne(o,i);if(!l)return{error:"market_unavailable",marketName:i.name,chain:T(o),_instructions:`${i.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let c=this.service.supply.canSupply(i),u=c?Cl({name:i.name,contract:i.contract},e,T(o)):[];return{_instructions:this.instructions(l,u.length>0,c),...u.length>0?{actionButtons:u}:{},marketName:l.name,protocol:l.protocolLabel??l.protocol,protocolUrl:l.protocolUrl,chain:T(l.chain),suppliedAssetSymbol:l.asset.symbol,totalSuppliedUsdc:le(l.totalSuppliedUsdc,Zt),...Ma(l),avgApyPercent:le(l.avgApyPercent,Pe),apyChangePercent:le(l.apyChangePercent,Pe),platformScore:l.platformScore,supplySupported:c}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}instructions(e,t,n){let o=qu(e);return[`This is the full picture of ONE lending market, ${e.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',n?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",t?Uu:""].filter(Boolean).join(" ")}};var Wr=class extends P{name="get-wallet-lending-positions";description='Get a wallet\'s own LENDING / SUPPLY (earn, deposit, savings) positions in the curated lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much it has supplied there, the AVERAGE supply APY over the last week (plus the live rate and the day-over-day change), the estimated yearly yield on that balance, and the market total supplied. Balances are read on-chain, so they match the app. Use for questions like: "Which protocols am I supplying on?", "Show my lending positions", "How much am I earning on my USDC?", "What APY am I getting?", "Where is my USDC deposited?", "My Aave / Compound / Spark / Morpho supply", "what am I earning on Aave", "my savings positions". This is the PREFERRED tool for any "what am I earning / supplying / depositing" question, even when the user names a protocol ("my Aave v3 supply", "my Spark deposit") \u2014 it is the only source of the 7-day average APY, the estimated yearly yield and the platform safety score. Each position reports its OWN asset, which is usually USDC but need not be \u2014 never assume the amounts are dollars without checking `suppliedAssetSymbol`. Chains and markets come from the live catalogue, so do not rule a chain out from memory: call the tool and let it answer. For protocols outside Aave v3 / Compound v3 / Spark / Morpho (Aave v2, MakerDAO\u2026), or when this tool reports nothing but the user insists they have a deposit, fall back to get-wallet-defi-positions. Do NOT use for: markets the wallet has NOT supplied to yet \u2014 where to deposit, best available APY, "promising lending" \u2192 get-lending-markets; the BORROW side of these same protocols, plus LP / staking \u2192 get-wallet-defi-positions (or get-wallet-defi-protocol-positions for one named protocol); plain token balances \u2192 get-wallet-token-balances.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:`Hex chain ID to scope to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry lending markets is resolved at call time, so do NOT filter the request against a list you remember. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 positions are then read on the connected wallet's own chain.`,required:!1}];service;constructor(e){super(),this.service=new Xe(e)}async run(e,t){let n=re(e.address,t);if(!R(n))return{error:`"${n}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=G(e.chain,t),s=o?await this.service.isSupported(o):!1,a=s?[]:await this.service.listSupportedChains();if(o&&!s)return{_instructions:`There are no lending markets on ${T(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:n,chain:T(o),positionCount:0,positions:[],chainsWithLendingMarkets:a.map(c=>T(c))};let i=o?[o]:a,l=await this.service.getSupplyPositions({address:n,chains:i});return{_instructions:this.instructions(l),walletAddress:n,chain:o?T(o):"all",chainsQueried:i.map(c=>T(c)),positionCount:l.length,totals:ig(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:T(c.chain),suppliedUsdc:le(c.suppliedUsdc,Zt),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:le(c.avgApyPercent,Pe),...Ma(c),apyChangePercent:le(c.apyChangePercent,Pe),estimatedAnnualYieldUsdc:le(c.estimatedAnnualYieldUsdc,Zt),marketTotalSuppliedUsdc:le(c.totalSuppliedUsdc,Zt),apyHistory:c.apyHistory.map(u=>({...u,apyPercent:le(u.apyPercent,Pe)})),platformScore:c.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(n=>n.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function ig(r){if(new Set(r.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let n=r.reduce((a,i)=>a+i.suppliedUsdc,0),o=r.filter(a=>a.avgApyPercent!==null),s=o.reduce((a,i)=>a+i.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:r[0]?.asset.symbol??null,suppliedUsdc:le(n,Zt),estimatedAnnualYieldUsdc:le(r.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),Zt),weightedAvgApyPercent:le(s>0?o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s:null,Pe)}}var Yr=class extends P{name="open-supply-usdc-form";kind="ui";category="lending-action";description='Open the SUPPLY form so the user can DEPOSIT into a specific lending market and start earning yield. This is the tool for a supply COMMAND: the user names a market and tells you to act on it, in any wording and any language \u2014 "supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare "Supply Aave", or a tapped "Supply \u2026" button. A supply verb plus a market name is already a complete command; terseness is not ambiguity, and the words the user left out are supplied by context rather than looked up. Each market deposits its OWN asset (usually USDC), resolved from the market itself \u2014 so a message that names no asset is still this tool: resolve the market from whatever the user did name. An amount is optional. Pass `market` \u2014 the market name or protocol exactly as it was shown to them (e.g. "Aave v3 USDC", "Spark"), and `amount` ONLY when they named one. Supports Aave v3, Compound v3, Spark and Morpho vaults, on whichever chains currently carry them \u2014 that set is resolved at call time, so never refuse a chain from memory. PRECONDITION: a connected wallet. The boundary is command vs question: use this to ACT on one market; to LIST or compare markets \u2192 get-lending-markets; for what the wallet already supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}];service;moralis;constructor(e){super(),this.service=new Xe(e),this.moralis=new L(e?.moralis)}async run(e,t){let n=t?.walletAddress;if(!n)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let s=G(e.chain,void 0)??F(t?.chain);if(!s)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};if(!await this.service.isSupported(s)){let b=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(s),chainsWithLendingMarkets:b.map(y=>T(y)),_instructions:`There are no lending markets on ${T(s)}, so nothing can be supplied there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let a=Fa(e.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let i=await this.service.findMarket(s,a);if(i.length===0)return{error:"market_not_found",market:a,chain:T(s),_instructions:`No lending market matching "${a}" exists on ${T(s)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(i.length>1)return{error:"ambiguous_market",market:a,chain:T(s),candidates:i.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${a}" matches ${i.length} different markets on ${T(s)}, so the supply cannot target one yet. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+a+`" and chain for ${T(s)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let l=i[0];if(!this.service.supply.canSupply(l))return{error:"unsupported_protocol",marketName:l.name,protocol:l.protocol,_instructions:`Supplying to ${l.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let c=await this.describeOne(s,l),u=lg(c);if(!u)return{error:"asset_unresolved",marketName:l.name,chain:T(s),_instructions:`The asset ${l.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[d,p]=await Promise.all([this.assetBalance(n,s,u.address),this.service.readReceiptToken(s,l)]);if(d&&Yt(d.amount,"0")<=0)return{error:"no_asset_balance",marketName:l.name,chain:T(s),assetSymbol:u.symbol,assetBalance:"0",_instructions:`The user has no ${u.symbol} available to supply to ${l.name} on ${T(s)}. In the user's language, tell them plainly that they have no ${u.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let m=cg(e.amount),g=m?At(m,u.decimals):null;if(g&&d&&Yt(g,d.amount)>0)return{error:"insufficient_asset_balance",marketName:l.name,chain:T(s),assetSymbol:u.symbol,requestedAmount:m,assetBalance:d.amount,_instructions:`The user wants to supply ${m} ${u.symbol} to ${l.name}, but they only hold ${d.amount} ${u.symbol} on ${T(s)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${m} ${u.symbol} exceeds their balance of ${d.amount} ${u.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let h={action:"supply_usdc",chainId:s,chainName:T(s),walletAddress:n,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??Ua(l),contract:l.contract,token:l.token,apyPercent:c?.currentApyPercent??c?.avgApyPercent??null,receiptToken:p},asset:u,...g?{prefillAmount:g}:{},...d?{spendable:d.amount}:{},...d?.usd?{spendableUsd:d.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:h},marketName:l.name,protocol:l.protocol,chain:T(s),apyPercent:le(h.market.apyPercent,Pe),assetSymbol:u.symbol,assetBalance:d?.amount??null,_instructions:this.instructions(l,u.symbol)}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}async assetBalance(e,t,n){try{let o=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[n]});if(!o.success)return null;let s=(o.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===n.toLowerCase());if(!s?.balance_formatted)return{amount:"0",usd:null};let a=typeof s.usd_value=="number"?String(s.usd_value):null;return{amount:String(s.balance_formatted),usd:a}}catch{return null}}instructions(e,t){return[`The supply action for ${e.name} is ready.`,`In the user's language, invite them to enter the amount of ${t} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${t}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function lg(r){let e=r?.asset;return!e?.address||e.address===Nn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function cg(r){let e=typeof r=="string"?r.trim():typeof r=="number"?String(r):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var Ba="https://ipfs.pantograph.app/ipfs/",$u=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function In(r){let e=r?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Ba}${t[1]}`:$u.test(e)?`${Ba}${e}`:null}function Hu(r){let e=r?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Ba}${t[1]}`:$u.test(e)?`${Ba}${e}`:null}function Vu(r){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(r)}function _l(r){if(!r||typeof r!="object")return;let e=r,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function ug(r){if(typeof atob=="function"){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function dg(r){let e=r.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",n=e[2]??"";try{let o=/;base64/i.test(t)?ug(n):decodeURIComponent(n);return JSON.parse(o)}catch{try{return JSON.parse(n)}catch{return null}}}function Wu(r){let e=r?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=dg(e);return t?In(_l(t)):null}var pg=12,mg=6e3;async function hg(r,e,t){let n=new Array(r.length),o=0,s=new Array(Math.max(1,Math.min(e,r.length))).fill(0).map(async()=>{for(;o<r.length;){let a=o++;n[a]=await t(r[a],a)}});return await Promise.all(s),n}async function gg(r,e){try{let t=await x.get(r,{timeout:e});if(!t.ok)return null;let n=t.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function fg(r,e){let t=r?.trim();if(!t)return null;if(/^data:/i.test(t))return Wu(t);let n=Hu(t);if(!n)return null;if(Vu(n))return n;let o=await gg(n,e);if(o){let s=In(_l(o));if(s)return s}return null}async function qa(r,e,t){if(e.length===0)return[];let n=t?.concurrency??pg,o=t?.timeoutMs??mg,s=await Wc(r,e,t?.rpcUrl);return hg(s,n,a=>fg(a,o))}var Yu=100,yg=100,Gr="{name}",Gu="{chain}",Kr=class extends P{name="get-wallet-nfts";description=`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`;category="nft";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}];service;constructor(e){super(),this.service=new L(e)}async run(e,t){let n=re(e.address,t),o=G(e.chain,t),s=o?[o]:Ce(),a=Ag(e.contract_address),i=zu(e.collection_name);return a||i?this.listNfts({address:n,chains:s,singleChain:!!o,contract:a,collectionName:i}):this.listCollections({address:n,chains:s,singleChain:!!o,args:e})}async listCollections(e){let{address:t,chains:n,singleChain:o,args:s}=e,a=await Promise.all(n.map(async c=>{let u=await this.service.getWalletNftCollections({address:t,chain:c,limit:Yu});return{chain:c,rows:u.success?Ku(u.data?.result??[]):[],ok:u.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(u=>({name:wg(u),contractAddress:u.token_address,chain:T(c.chain),nftCount:u.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=vg(i,s);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:n,singleChain:o,contract:s,collectionName:a}=e,i=await Promise.all(n.map(async m=>{let g=await this.service.getWalletNFTs({address:t,chain:m,limit:Yu,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:g.success?Ku(g.data?.result??[]):[],ok:g.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(g=>bg(g,{contract:s,collectionName:a})).map(g=>({chain:m.chain,row:g})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:m,row:g},h)=>{let f=kg(g);return{name:f.name,tokenId:f.tokenId,contractAddress:f.contractAddress,image:u[h]??f.image,chain:T(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:d}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),n=new Map;e.forEach((o,s)=>{let a=n.get(o.chain)??[];a.push(s),n.set(o.chain,a)});try{await Promise.all([...n.entries()].map(async([o,s])=>{let a=s.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await qa(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Ku(r){return r.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function bg(r,e){if(e.contract)return r.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(r.name??"").toLowerCase().includes(t)}return!1}function wg(r){let e=r.name?.trim();if(e)return e;let t=r.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function kg(r){return{name:r.normalized_metadata?.name||r.name||`#${r.token_id}`,tokenId:r.token_id,contractAddress:r.token_address,image:In(r.normalized_metadata?.image||r.media?.original_media_url)}}function vg(r,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",o=[];for(let s of r){if(o.length>=yg)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${Gr} NFTs on ${Gu}`:`show my ${Gr} NFTs`,l=ju(n,{[Gr]:s.name,[Gu]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:Tg(t,s.name,Gr),prompt:`${l} (${s.contractAddress})`})}return o}function ju(r,e,t){let n=r&&r.includes(Gr)?r:t;for(let[o,s]of Object.entries(e))n=n.split(o).join(s);return n.replace(/\s+/g," ").trim()}function Tg(r,e,t){return ju(r,{[Gr]:e},t)}function zu(r){if(typeof r!="string")return;let e=r.trim();return e||void 0}function Ag(r){let e=zu(r);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var Pg="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",pt=class extends P{kind="data";category="nft";llm;constructor(e){super(),this.llm=new ce(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:Pg,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var jr=class extends pt{name="get-nft-contract-info";description='Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.';parameters=pt.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`);presentInstructions="Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks."};var zr=class extends pt{name="get-nft-metadata";description='Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.';parameters=pt.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`);presentInstructions="Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points."};var Nl={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},Ul="amazon.com";function Sg(r){return r?r.trim().toLowerCase().split(/[-_]/)[0]:""}function Il(r){let e=Sg(r);return Nl[e]??Ul}function $a(r){return`https://${Il(r)}/s?k=NFC%20Tag`}function Ha(r){if(!r)return"";let e=r.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var xg=720*60*1e3,Xu=new Map,Qu=3;function Cg(r){return[`A user in country "${r}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Qu} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function Rg(r){if(!r)return[];let e=r.indexOf("["),t=r.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(r.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let o=[],s=new Set;for(let a of n){if(!a||typeof a!="object")continue;let i=a.label,l=a.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!s.has(c)&&(s.add(c),o.push({label:i.trim(),url:l.trim()}),o.length>=Qu))break}return o}async function Ll(r,e){let t=Ha(r);if(!t||!e)return null;let n=Xu.get(t);if(n&&n.expires>Date.now())return n.links;let o=Date.now(),s=[{role:"user",content:Cg(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=Rg(a.text);if(i.length)return Xu.set(t,{links:i,expires:Date.now()+xg}),i}catch{}return null}async function Xr(r){let e=await Ll(r.country,r.llm);return e&&e.length?e:[{label:"Amazon",url:$a(r.language)}]}function Eg(r){return r.length<=1?r.length===1?`[${r[0].label}](${r[0].url})`:"":r.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
40
|
-
`)}var
|
|
41
|
-
`),
|
|
39
|
+
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?T(n):"all",timeFrame:s??null,count:c.length,tokens:c}}};var Ho=class extends P{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new U(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,r=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(r+"00").slice(0,2)}`}async run(e,t){let n=ae(e.address,t),r=j(e.chain,t);if(r){let i=await this.service.getWalletTokenBalances({address:n,chain:r,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(n,r,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let s=Fe(),a=await Promise.all(s.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",r=e.symbol||"",s=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${r} (${s})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let r=n.reduce((s,a)=>s+(a.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(r)}`,tokens:n.map(s=>this.toTokenLine(s))}}renderBalancesByChain(e,t){let n=t.map(s=>{let a=s.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=s.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:T(s.chain),total:a,tokens:i}}).filter(s=>s.tokens.length>0).sort((s,a)=>a.total-s.total),r=n.reduce((s,a)=>s+a.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(r)}`,chains:n.map(s=>({chain:s.chain,totalUsdValue:`$${this.truncateUsd(s.total)}`,tokens:s.tokens.map(a=>this.toTokenLine(a))}))}}};var Vo=class extends P{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=ae(e.address,t),r=Ae(e.chain,t),s=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,a=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,d=Number.isFinite(l)?l:void 0,u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,b=Number.isFinite(g)&&g>0?g:10,y=await this.service.getWalletHistory({address:n,chain:r,limit:b,fromDate:s,toDate:a,fromBlock:c,toBlock:d,cursor:u,order:m,includeInternalTransactions:f,nftMetadata:h});if(!y.success)return{error:y.error||"Failed to fetch wallet history"};let k=(y.data?.result||[]).map(v=>{let A=Pu(r,v.hash);return A?{...v,explorerUrl:A}:v});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:r||"default",pagination:{cursor:y.data?.cursor??null,hasMore:!!y.data?.cursor},transactionCount:k.length,transactions:k}}};function qh(o){if(o.value_decimal)return o.value_decimal;let e=parseInt(o.token_decimals??"18",10);if(isNaN(e)||e===0)return o.value;try{let t=BigInt(o.value),n=BigInt(10)**BigInt(e),r=t/n,a=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return a?`${r}.${a}`:`${r}`}catch{return o.value}}var Wo=class extends P{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=ae(e.address,t),r=Ae(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(R=>typeof R=="string"&&!!R).map(R=>R.trim()):void 0,y,w;if(g){let R=await this.resolveContractAddressBySymbol(g,n,r);R&&(b=[R.address],y=R.symbol,w=R.name)}let k=await this.service.getWalletTokenTransfers({address:n,chain:r,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let v=n.toLowerCase(),S=(k.data?.result||[]).map(R=>{let me=R.from_address.toLowerCase()===v,H=me?"send":"receive",O=me?R.to_address:R.from_address,he=me?R.to_address_label??void 0:R.from_address_label??void 0,Ve=me?R.to_address_entity??void 0:R.from_address_entity??void 0;return{...R,direction:H,amount_formatted:qh(R),counterparty:O,counterparty_label:he,counterparty_entity:Ve}}),C=h==="all"?S:S.filter(R=>R.direction===h);if(g&&!b){let R=g.toLowerCase();C=C.filter(me=>(me.token_symbol??"").toLowerCase()===R)}let F=this.buildCounterparties(C);return{walletAddress:n,chain:r||"default",resolvedToken:y?{symbol:y,name:w,contractAddress:b?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:b||null,direction:h,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??a,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:C.length,transfers:C,counterparties:F}}async resolveContractAddressBySymbol(e,t,n){let r=e.toLowerCase(),s=await this.service.getWalletTokenBalances({address:t,chain:n});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let a=await this.service.searchTokensByKey({key:e,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===r)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let s of e){let a=s.direction==="send"?t:n,i=s.counterparty.toLowerCase(),l=parseFloat(s.amount_formatted)||0,c=a.get(i);c?(c.total+=l,c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,total:l,count:1,first:s.block_timestamp,last:s.block_timestamp})}let r=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Yo=class extends P{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=ae(e.address,t),r=Ae(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,y=await this.service.getWalletNftTransfers({address:n,chain:r,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m,includePrices:f});if(!y.success)return{error:y.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),v=(y.data?.result||[]).map(C=>{let F=C.from_address.toLowerCase()===w,R=F?"send":"receive",me=F?C.to_address:C.from_address,H=F?C.to_address_label??void 0:C.from_address_label??void 0,O=F?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:R,counterparty:me,counterparty_label:H,counterparty_entity:O}}),A=g==="all"?v:v.filter(C=>C.direction===g),S=this.buildCounterparties(A);return{walletAddress:n,chain:r||"default",filters:{contractAddresses:b||null,direction:g,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null,includePrices:f??null},pagination:{cursor:y.data?.cursor??null,pageSize:y.data?.page_size??a,page:y.data?.page??null,hasMore:!!y.data?.cursor},transferCount:A.length,transfers:A,counterparties:S}}buildCounterparties(e){let t=new Map,n=new Map;for(let s of e){let a=s.direction==="send"?t:n,i=s.counterparty.toLowerCase(),l=s.token_name??s.token_address,c=a.get(i);c?(c.tokenIds.add(s.token_id),c.collections.add(l),c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,tokenIds:new Set([s.token_id]),collections:new Set([l]),count:1,first:s.block_timestamp,last:s.block_timestamp})}let r=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var $h=["all","7","30","60","90"],Go=class extends P{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=ae(e.address,t),r=j(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=$h.includes(s)?s:void 0;if(r){let h=await this.service.getWalletPnlSummary({address:n,chain:r,days:a});return h.success?{walletAddress:n,chain:r,days:a??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(Fe().map(async h=>{let g=await this.service.getWalletPnlSummary({address:n,chain:h,days:a});return{chain:h,data:g.success?g.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:T(h.chain),summary:this.mapSummary(h.data)})),d=l.reduce((h,g)=>h+Number(g.data.total_realized_profit_usd||0),0),u=l.reduce((h,g)=>h+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((h,g)=>h+Number(g.data.total_sold_volume_usd||0),0),m=l.reduce((h,g)=>h+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((h,g)=>h+g.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:u>0?d/u*100:0,totalBuys:l.reduce((h,g)=>h+g.data.total_buys,0),totalSells:l.reduce((h,g)=>h+g.data.total_sells,0),totalBoughtVolumeUsd:u,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",summary:f,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var Hh=["all","7","30","60","90"],Va=25,Ko=class extends P{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${Va}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${Va}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${Va}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=ae(e.address,t),r=j(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Hh.includes(s)?s:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[];if(r){let u=await this.fetchChainPnl(n,r,a,i,l);return u.ok?{walletAddress:n,chain:r,days:a??"all",filters:{tokenAddresses:u.tokenAddresses??null,resolvedSymbols:u.resolvedFromSymbols.length>0?u.resolvedFromSymbols:null,unresolvedSymbols:u.unresolvedSymbols.length>0?u.unresolvedSymbols:null},tokenCount:u.tokens.length,tokens:u.tokens}:{error:u.error||"Failed to fetch wallet PnL"}}let d=(await Promise.all(Fe().map(async u=>({chain:u,res:await this.fetchChainPnl(n,u,a,i,l)})))).filter(u=>u.res.ok&&u.res.tokens.length>0).map(u=>({chain:T(u.chain),tokenCount:u.res.tokens.length,tokens:u.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:d.reduce((u,p)=>u+p.tokenCount,0),chains:d}}async fetchChainPnl(e,t,n,r,s){let a=[],i=[];r.length>0&&(await Promise.all(r.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?a.push({symbol:r[m],address:p.address}):i.push(r[m])});let l=Vh([...a.map(u=>u.address),...s]).slice(0,Va),c=l.length>0?l:void 0,d=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===r)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Vh(o){let e=new Set,t=[];for(let n of o){let r=n.toLowerCase();e.has(r)||(e.add(r),t.push(n))}return t}var Wh=BigInt(2)**BigInt(255),jo=class extends P{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=ae(e.address,t),r=Ae(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:r,limit:a,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,u=(c.result||[]).map(h=>Yh(h)),p=0,m=0,f=[];for(let h of u){h.isUnlimited&&(m+=1);let g=parseFloat(h.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let b=h.token.possibleSpam||h.token.verifiedContract===!1,y=!h.spender.label&&!h.spender.entity;(b||h.isUnlimited&&y)&&f.push(h)}return{walletAddress:n,chain:r||"default",filters:{limit:a,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??a,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:u.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:u,riskyApprovals:f}}};function Yh(o){let e=Gh(o.value);return{blockNumber:o.block_number,blockTimestamp:o.block_timestamp??null,transactionHash:o.transaction_hash??null,value:o.value,valueFormatted:o.value_formatted??null,isUnlimited:e,token:{address:o.token.address,addressLabel:o.token.address_label??null,name:o.token.name??null,symbol:o.token.symbol??null,logo:o.token.logo??null,possibleSpam:!!o.token.possible_spam,verifiedContract:o.token.verified_contract??null,currentBalance:o.token.current_balance??null,currentBalanceFormatted:o.token.current_balance_formatted??null,usdPrice:o.token.usd_price??null,usdAtRisk:o.token.usd_at_risk??null},spender:{address:o.spender.address,label:o.spender.address_label??null,entity:o.spender.entity??null,entityLogo:o.spender.entity_logo??null}}}function Gh(o){if(!o)return!1;try{return BigInt(o)>=Wh}catch{return!1}}var zo=class extends P{name="get-wallet-defi-positions";description=`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=ae(e.address,t),r=j(e.chain,t);if(r){let i=await this.service.getWalletDefiPositions({address:n,chain:r});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:r,positionCount:l.length,positions:l.map($u)}}let a=(await Promise.all(Fe().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:T(i.chain),positionCount:i.rows.length,positions:i.rows.map($u)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function $u(o){return{protocolName:o.protocol_name,protocolId:o.protocol_id,protocolUrl:o.protocol_url,protocolLogo:o.protocol_logo,accountHealthFactor:o.account_data?.health_factor??null,position:Kh(o.position)}}function Kh(o){return{label:o.label,address:o.address,balanceUsd:o.balance_usd,totalUnclaimedUsdValue:o.total_unclaimed_usd_value,tokens:(o.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:o.position_details??null}}var Xo=class extends P{name="get-wallet-defi-protocol-positions";description=`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let r=ae(e.address,t),s=j(e.chain,t);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:s});return l.success?l.data?{walletAddress:r,chain:s,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(Fe().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:T(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:r,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(jh)}}};function jh(o){return{label:o.label,address:o.address,balanceUsd:o.balance_usd,totalUnclaimedUsdValue:o.total_unclaimed_usd_value,tokens:(o.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:o.position_details??null}}function zh(o){try{return(Number(BigInt(o))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return o}}var Qo=class extends P{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let r=Ae(e.chain,t),s=await this.service.getTransactionByHash({transactionHash:n,chain:r});if(!s.success||!s.data)return{error:s.error||"Failed to fetch transaction"};let a=s.data,i=(a.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=a.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:a.hash,status:a.receipt_status==="1"?"success":a.receipt_status==="0"?"failed":"unknown",timestamp:a.block_timestamp,blockNumber:a.block_number,from:{address:a.from_address,label:a.from_address_label||null,entity:a.from_address_entity||null},to:a.to_address?{address:a.to_address,label:a.to_address_label||null,entity:a.to_address_entity||null}:null,valueEth:zh(a.value||"0"),fee:a.transaction_fee,gasUsed:a.receipt_gas_used,gasPriceGwei:a.gas_price?(Number(a.gas_price)/1e9).toFixed(4):null,decodedCall:a.decoded_call?{signature:a.decoded_call.signature,label:a.decoded_call.label,params:a.decoded_call.params}:null,decodedEvents:i,contractCreated:a.receipt_contract_address||null,logs:l}}};var Hu=new Map;function Xh(o){let e=Hu.get(o);if(e)return e;let t=Qt({rpcUrl:o});return Hu.set(o,t),t}async function Vu(o,e,t=[]){let n=await Xh(o).rpc(e,t);if(n===void 0)throw new Error(`RPC ${e}: empty result`);return n}function Wu(o,e,t){return Vu(o,"eth_call",[{to:e,data:t},"latest"])}async function Qh(o,e,t){let n=In(o);if(!n)return null;try{return await Wu(n,e,t)}catch{return null}}function I(o,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${o}`):console.log(`[LEND] ${o}`,JSON.stringify(e,Jh)))}function Jh(o,e){return typeof e=="bigint"?`${e}n`:e}var Zh=6e4,ql=new Map;async function Ls(o,e){let t=It(e),n=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(n))return[];let r=`${o}|${t}`,s=ql.get(r);if(s&&Date.now()-s.at<Zh)return s.markets;let a=ef(o,t,n),i=a.then(l=>l.markets);return ql.set(r,{at:Date.now(),markets:i}),a.then(l=>{l.answered||ql.delete(r)}),i}async function Wa(o,e){return(await Ls(o,e)).length>0}async function ef(o,e,t){try{let n=`${o}/supply/v2?chainId=${t}&limit=100&page=1`;I("catalog: GET",n);let r=await x.get(n);if(!r.ok){let a=r.status>=400&&r.status<500;return I(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:r.status,message:_(r)}),{markets:[],answered:a}}let s=(r.data?.data?.items||[]).flatMap(a=>{let i=tf(a,e);return i?[i]:[]});return I("catalog: got markets",{chain:e,rawItems:r.data?.data?.items?.length??0,usable:s.length,tokens:s.map(a=>a.token)}),{markets:s,answered:!0}}catch(n){return I("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:n?.message}),{markets:[],answered:!1}}}function Yu(o,e){let t=e.trim().toLowerCase();if(!t)return[];if(E(t))return o.filter(r=>r.contract===t||r.token===t);let n=o.filter(r=>r.name.trim().toLowerCase()===t);return n.length>0?n:o.filter(r=>{let s=r.name.trim().toLowerCase(),a=r.protocol.trim().toLowerCase();return s.includes(t)||t.includes(s)||a.includes(t)||t.includes(a)})}function tf(o,e){if(o?.isDeleted===!0)return null;let t=typeof o?.contract=="string"?o.contract.toLowerCase():"";if(!E(t))return null;let n=typeof o?.token=="string"&&E(o.token)?o.token.toLowerCase():t,r=Number(o?.rating?.balanceScore),s=o?.type?.trim()||"unknown";return{chain:e,name:o?.name?.trim()||"USDC lending market",protocol:o?.protocolId?.name?.trim()||"Unknown",protocolLabel:We(s),protocolUrl:o?.protocolId?.domain?.trim()||null,type:s,contract:t,token:n,platformScore:Number.isFinite(r)?r:null}}function $l(){return Fe()}async function Ya(o){let e=$l(),t=await Promise.all(e.map(n=>Wa(o,n)));return e.filter((n,r)=>t[r])}async function Ga(o,e){let t=M(e);return t?Wa(o,t):!1}async function Gu(o,e){let t=e.map(s=>M(s)).filter(s=>!!s),n=[...new Set(t)],r=await Promise.all(n.map(s=>Wa(o,s)));return n.filter((s,a)=>r[a])}function Hn(o){return Es(o)}var Ku=6;async function ju(o,e,t){let n=e.map(w=>E(w)?w.toLowerCase():null);if(n.every(w=>w===null))return I("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let r=Ba(o),s;try{I("discovery: probing 5 accessors per token",{chain:o,tokens:n,psm:r}),s=await ve(o,[...n.flatMap(w=>w?nf(w):[]),...r?Iu(r):[]])}catch(w){return I("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:o,message:w?.message}),e.map(()=>null)}let a=r?s.slice(s.length-Uu):[],i=q(a[0])?.toLowerCase()??null,l=q(a[1]),c=q(a[2]),d=i&&l&&c?{susds:i,usds:l,oracle:c}:null;r&&I("discovery: PSM3 lookup",{psm:r,susds:i,usds:l,oracle:c});let u=0,p=n.map(w=>{if(!w)return null;let k=s.slice(u,u+Ku);return u+=Ku,I("discovery: probe answers",{token:w,"POOL()":q(k[0]),"UNDERLYING_ASSET_ADDRESS()":q(k[1]),"baseToken()":q(k[2]),"asset()":q(k[3]),"vsr()":J(k[4])?.toString()??null,"manager()":q(k[5])}),{token:w,slice:k}}),m=new Set;for(let w of p){if(!w)continue;let k=q(w.slice[0]);k&&q(w.slice[1])&&m.add(k.toLowerCase())}let f=await of(o,[...m]);m.size>0&&I("discovery: Aave pool authentication",{claimed:[...m],genuine:[...f]});let h=new Map;for(let w of p){if(!w||q(w.slice[0])&&q(w.slice[1])||q(w.slice[2])||!q(w.slice[3]))continue;let v=q(w.slice[5]);v&&h.set(w.token,v.toLowerCase())}let g=await rf(o,h);h.size>0&&I("discovery: Maple manager authentication",{claimed:[...h.keys()],genuine:[...g]});let b=p.flatMap(w=>w?q(w.slice[0])&&q(w.slice[1])||q(w.slice[2])?[]:g.has(w.token)?[]:q(w.slice[3])?[w.token]:[]:[]),y=await sf(o,[...new Set(b)],t);return b.length>0&&I("discovery: Morpho vault lookup",{asked:[...new Set(b)],recognised:[...y.keys()]}),p.map(w=>{if(!w)return null;let{token:k,slice:v}=w,A={chain:o,protocolUrl:null,token:k,platformScore:null};if(d&&k===d.susds)return I("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:d.oracle}),{...A,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:We("spark-l2-susds"),protocolUrl:Hn("spark-l2-susds"),type:"spark-l2-susds",contract:d.oracle,assetAddress:d.usds};let S=q(v[0]);if(S&&q(v[1])){let C=f.has(S.toLowerCase());return I("discovery: classified",{token:k,as:C?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:S}),C?{...A,name:"Aave v3",protocol:"AAVE",protocolLabel:We("aave-v3"),protocolUrl:Hn("aave-v3"),type:"aave-v3",contract:S}:null}if(q(v[2]))return I("discovery: classified",{token:k,as:"compound-v3"}),{...A,name:"Compound v3",protocol:"COMPOUND",protocolLabel:We("compound-v3"),protocolUrl:Hn("compound-v3"),type:"compound-v3",contract:k};if(q(v[3])){if(g.has(k))return I("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...A,name:"Maple",protocol:"MAPLE",protocolLabel:We("maple"),protocolUrl:Hn("maple"),type:"maple",contract:k};if(y.has(k)){I("discovery: classified",{token:k,as:"morpho-v2"});let R=y.get(k)||"Morpho V2";return{...A,name:R,protocol:"MORPHO",protocolLabel:We("morpho-v2"),protocolUrl:Hn("morpho-v2"),type:"morpho-v2",contract:k}}let F=J(v[4])!==null;return I("discovery: classified",{token:k,as:F?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),F?{...A,name:"Spark",protocol:"SPARK",protocolLabel:We("spark-ethereum"),protocolUrl:Hn("spark-ethereum"),type:"spark-ethereum",contract:k}:{...A,name:"Spark",protocol:"SPARK",protocolLabel:We("spark"),protocolUrl:Hn("spark"),type:"spark",contract:k}}return I("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function nf(o){return[{target:o,callData:D({abi:Uo,functionName:"POOL"})},{target:o,callData:D({abi:Uo,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:o,callData:D({abi:Lt,functionName:"baseToken"})},{target:o,callData:D({abi:ft,functionName:"asset"})},{target:o,callData:D({abi:Do,functionName:"vsr"})},{target:o,callData:D({abi:Ul,functionName:"manager"})}]}async function of(o,e){if(e.length===0)return new Set;try{let t=await ve(o,e.map(n=>({target:n,callData:D({abi:Nl,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,r)=>q(t[r])!==null))}catch{return new Set}}async function rf(o,e){if(e.size===0)return new Set;let t=[...e.entries()];try{let n=await ve(o,t.map(([,r])=>({target:r,callData:D({abi:Dl,functionName:"pool"})})));return new Set(t.filter(([r],s)=>q(n[s])?.toLowerCase()===r.toLowerCase()).map(([r])=>r))}catch{return new Set}}async function sf(o,e,t){let n=parseInt(o,16);if(e.length===0||!Number.isFinite(n))return new Map;let r=await Promise.all(e.map(async s=>{try{let a=await x.post(t,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:n}}),i=a.ok?a.data?.data?.vaultV2ByAddress:null;return i?[s,i.name?.trim()||""]:null}catch{return null}}));return new Map(r.filter(s=>s!==null))}var af=.01;function lf(o){return o.reduce((e,t)=>t.conditions===null?e+t.apyPercent:e,0)}function cf(o,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),n=fs();n[o]!==t&&Nn({...n,[o]:t})}var Jo=class{constructor(e,t,n){this.coinPoolBaseUrl=e;this.endpoints=t;this.describer=n}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(e,t,n){let r=Date.now();I("describeReceiptTokens: START",{chain:e,tokens:t,hasRpcUrl:!!n});let s=It(e);s&&cf(s,n);let a=s?_s(s):null,i=[...new Set(t.filter(E).map(p=>p.toLowerCase()))];if(I("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!a,wanted:i}),!s||!a||i.length===0)return I("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!a,wantedCount:i.length}),new Map;I("describeReceiptTokens: on-chain discovery for",i);let l=await ju(s,i,this.endpoints.morphoApiUrl),d=[...new Map(i.flatMap((p,m)=>{let f=l[m];return I("describeReceiptTokens: discovery result",{token:p,found:!!f,protocol:f?.protocol,type:f?.type,contract:f?.contract}),f?[[p,f]]:[]})).entries()];if(d.length===0)return I("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-r}),new Map;I("describeReceiptTokens: describing markets",{count:d.length,markets:d.map(([p,m])=>({token:p,type:m.type,contract:m.contract}))});let u=await this.describer.describe(s,a,d.map(([,p])=>p));return I("describeReceiptTokens: DONE",{ms:Date.now()-r,overviews:u.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(u.map((p,m)=>[d[m][0],p]))}async findMarketByReceiptToken(e,t,n){if(I("findMarketByReceiptToken: called",{chain:e,receiptToken:t,hasRpcUrl:!!n}),!E(t))return I("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:t}),null;let s=(await this.describeReceiptTokens(e,[t],n)).get(t.toLowerCase())??null;return I("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(e){if(!E(e.address))return[];let t=await Gu(this.coinPoolBaseUrl,e.chains);return(await Promise.all(t.map(r=>this.positionsForChain(r,e.address)))).flat().sort((r,s)=>s.suppliedUsdc-r.suppliedUsdc||(s.avgApyPercent??0)-(r.avgApyPercent??0))}async describeResolvedMarkets(e,t){let n=It(e),r=n?_s(n):null;return n&&r?this.describer.describe(n,r,t):[]}async positionsForChain(e,t){let n=_s(e),r=await Ls(this.coinPoolBaseUrl,e);if(!n||r.length===0)return[];let s=await this.describer.readBalances(e,t,r);if(s.length===0)return[];let a=await this.describer.describe(e,n,s.map(l=>l.market)),i=await this.describer.convertToUnderlying(e,s,a.map(l=>l.asset));return a.flatMap((l,c)=>{let d=i[c];return d<af?[]:[{...l,suppliedUsdc:d,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:d*(l.avgApyPercent+lf(l.rewards))/100}]})}};var Hl=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Zo=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return Ya(this.coinPoolBaseUrl)}async isSupported(e){return Ga(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=M(e);return t?Ls(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let n=await this.getMarkets(e);return Yu(n,t)}canSupply(e){return Hl.includes(e.type)}async readReceiptToken(e,t){let n=an(t).balanceIsUnderlying;try{let r=await ve(e,[{target:t.token,callData:D({abi:V,functionName:"symbol"})},{target:t.token,callData:D({abi:V,functionName:"decimals"})}]);return{symbol:oo(r[0]),decimals:ro(r[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};var uf={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},df={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",130:"proto_unichain_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},pf={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},mf={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function Ka(o){let e=Tf(o.chain);return(e===null?null:hf(o,e))??Es(o.type)??vf(o,e)}function hf(o,e){switch(o.type){case"morpho-v2":{let t=uf[e];if(!t||!o.contract)return null;let n=`https://app.morpho.org/${t}/vault/${Vl(o.contract)}`,r=yf(o.name);return r?`${n}/${r}`:n}case"aave-v3":{let t=df[e],n=ff(o);return!t||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${Vl(n)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=pf[e],n=wf(o);return!t||!n?null:`https://app.spark.fi/savings/${t}/${n}`}case"compound-v3":{let t=mf[e],n=bf(o);return!t||!n?null:`https://app.compound.finance/?market=${n}-${t}`}default:return null}}function ff(o){let e=o.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var gf=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function yf(o){let e=o?.trim().toLowerCase()||"";return!e||gf.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function bf(o){let e=o.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function wf(o){let e=o.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(e))return e;let t=`${o.name||""} ${o.token||""}`.toLowerCase();for(let r of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(t.includes(r))return r;if(o.type==="spark-ethereum")return kf[o.contract?.trim().toLowerCase()||""]??null;let n=o.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(n)||n.startsWith("s")?null:`s${n}`}var kf={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function vf(o,e){let t=o.protocolUrl?.trim();if(!t)return null;let n=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let r=new URL(n);return e!==null&&r.searchParams.set("chainId",String(e)),o.contract&&r.searchParams.set("contract",Vl(o.contract)),r.toString()}catch{return n}}function Vl(o){let e=o.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function Tf(o){let e=o?.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)&&t>0?t:null}var Af=new Set(["spark","spark-ethereum"]),Pf=8;function Sf(o,e,t){if(o.market.type!=="spark-l2-susds")return J(e);let n=J(e);return n===null||o.tokenDecimals===null?null:qn(o.rawBalance,n,o.tokenDecimals,t)}var ja=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new Wl(Pf);pantograph=new Te;async describe(e,t,n){if(n.length===0)return[];I("describe: START",{chain:e,count:n.length,types:n.map(l=>l.type)});let{assets:r,shareSymbols:s}=await this.resolveAssets(e,n);I("describe: assets resolved",r);let[a,i]=await Promise.all([this.readMarketState(e,n,r),Promise.all(n.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,t,r[c]))))]);return I("describe: on-chain state",a),I("describe: APY fetched",i.map((l,c)=>({type:n[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),n.map((l,c)=>{let{totalSuppliedUsdc:d,liveApyFraction:u}=a[c],p=i[c].sizeOverride??d,m=Cf(i[c].samples,u??i[c].current,i[c].rewards,i[c].avgOverride??null);return I("describe: summarised",{market:l.name,type:l.type,liveFrom:u!==null?"on-chain":i[c].current!==null?"api":"none",rawSamples:i[c].samples.length,historyPoints:m.history.length,currentApyPercent:m.currentApyPercent,avgApyPercent:m.avgApyPercent,apyChangePercent:m.apyChangePercent,totalSuppliedUsdc:p,asset:r[c]?.symbol}),{...l,protocolUrl:Ka({...l,asset:r[c],shareSymbol:s[c]}),asset:r[c],totalSuppliedUsdc:p,avgApyPercent:m.avgApyPercent,currentApyPercent:m.currentApyPercent,baseApyPercent:m.baseApyPercent,rewardApyPercent:m.rewardApyPercent,rewards:m.rewards,apyChangePercent:m.apyChangePercent,apyHistory:m.history}})}async readBalances(e,t,n){let r=D({abi:V,functionName:"balanceOf",args:[t]}),s=D({abi:V,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:r},{target:l.token,callData:s}]),i=await ve(e,a);return n.flatMap((l,c)=>{let d=J(i[c*2]);return d===null||d<=0n?[]:[{market:l,rawBalance:d,tokenDecimals:ro(i[c*2+1])}]})}async convertToUnderlying(e,t,n){let r=[],s=t.map(i=>{let l=an(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(r.push(l),r.length-1):-1}),a=await ve(e,r);return t.map((i,l)=>{let c=n[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return Xe(i.rawBalance,c);let d=Sf(i,a[s[l]],c);return d===null?Xe(i.rawBalance,i.tokenDecimals??c):Xe(d,c)})}async resolveAssets(e,t){let n={address:$n,decimals:NaN,symbol:null,logo:null},r=[],s=t.map(p=>{let m=an(p).underlyingCall(p);return m?(r.push(m),r.length-1):-1}),a;try{let p=r.length>0?await ve(e,r):[];a=s.map(m=>m<0?null:q(p[m]))}catch{a=t.map(()=>null)}a=a.map((p,m)=>p??t[m]?.assetAddress??null);let i=[...new Set(a.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,d]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i),this.readShareSymbols(e,t)]);return{assets:a.map(p=>{if(!p)return n;let m=p.toLowerCase(),f=l.get(m),h=c.get(m)??null;return f?.decimals!==null&&f?.decimals!==void 0?{address:p,decimals:f.decimals,symbol:f.symbol??null,logo:h}:{address:p,decimals:NaN,symbol:null,logo:h}}),shareSymbols:d}}async readShareSymbols(e,t){let n=D({abi:V,functionName:"symbol"}),r=[],s=t.map(a=>!Af.has(a.type)||!a.contract?-1:(r.push({target:a.contract,callData:n}),r.length-1));if(r.length===0)return t.map(()=>null);try{let a=await ve(e,r);return s.map(i=>i<0?null:oo(a[i]))}catch{return t.map(()=>null)}}async readAssetMetadata(e,t){let n=new Map;if(t.length===0)return n;let r=D({abi:V,functionName:"decimals"}),s=D({abi:V,functionName:"symbol"});try{let a=await ve(e,t.flatMap(i=>[{target:i,callData:r},{target:i,callData:s}]));t.forEach((i,l)=>{n.set(i,{decimals:ro(a[l*2]),symbol:oo(a[l*2+1])})})}catch{}return n}async fetchAssetLogos(e,t){let n=new Map;if(t.length===0)return n;try{let r=await this.pantograph.getTokensMetadata(t,e);for(let[s,a]of Object.entries(r)){let i=a.icon_image||a.logo||a.logoURI;i&&n.set(s.toLowerCase(),i)}}catch{}return I("resolveAssets: logos",{chain:e,requested:t.length,found:n.size}),n}async readMarketState(e,t,n){let r=[],s=t.map((d,u)=>{let p=an(d),m=n[u],f={market:d,protocol:p,asset:m,size:r.length,rate:-1};r.push(p.sizeCall(d,m));let h=p.liveRateCall(d,m);return h&&(f.rate=r.length,r.push(h)),f}),a=await ve(e,r),i=[],l=s.map(d=>{if(d.rate<0)return-1;let u=d.protocol.followUpRateCall(d.market,a[d.rate]);return u?(i.push(u),i.length-1):-1}),c=i.length>0?await ve(e,i):[];return s.map((d,u)=>{let p=d.rate<0?null:a[d.rate],m=l[u]>=0?c[l[u]]:p;return{totalSuppliedUsdc:d.protocol.decodeSize(a[d.size],d.asset),liveApyFraction:m===null?null:d.protocol.decodeLiveRate(m)}})}async fetchApy(e,t,n){try{I("fetchApy: requesting",{market:e.name,type:e.type,asset:n?.symbol});let r=await an(e).fetchApy(e,t,this.endpoints,n);return I("fetchApy: got",{market:e.name,samples:r.samples.length,current:r.current,avgOverride:r.avgOverride??null}),r}catch(r){return I("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:r?.message}),{samples:[],current:null,rewards:[]}}}},Wl=class{constructor(e){this.limit=e}limit;active=0;waiting=[];async run(e){this.active>=this.limit?await new Promise(t=>this.waiting.push(t)):this.active++;try{return await e()}finally{let t=this.waiting.shift();t?t():this.active--}}};function xf(o,e){let t=vs(Date.now()),n=new Map,r=null;for(let i of o)!Number.isFinite(i.timeMs)||!Number.isFinite(i.fraction)||i.fraction<0||vs(i.timeMs)>t||((!r||i.timeMs>r.timeMs)&&(r=i),n.set(i.timeMs,i.fraction));let s=[...n.entries()].sort((i,l)=>i[0]-l[0]).map(([i,l])=>({date:new Date(i).toISOString(),apyPercent:l*100})),a=e??(r&&vs(r.timeMs)===t?r.fraction:null);return{history:s,live:a}}function Cf(o,e,t=[],n=null){let{history:r,live:s}=xf(o,e),a=s===null?null:s*100,i=t.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=i.length===0?null:i.reduce((m,f)=>m+f.apyPercent,0),c=a===null?null:a+(l??0),d={baseApyPercent:a,rewardApyPercent:l,rewards:i},u=n!==null&&Number.isFinite(n)?n*100:null;if(r.length===0)return{history:r,avgApyPercent:u,currentApyPercent:c,apyChangePercent:null,...d};let p=r.reduce((m,f)=>m+f.apyPercent,0);return{history:r,avgApyPercent:u??p/r.length,currentApyPercent:c,apyChangePercent:Ef(r,a),...d}}var zu=3600*1e3,Rf=zu/2;function Ef(o,e){if(e===null)return null;let t=Date.now()-zu,n=null,r=Number.POSITIVE_INFINITY;for(let s=o.length-1;s>=0;s--){let a=Math.abs(Date.parse(o[s].date)-t);if(a>r)break;r=a,n=o[s]}return!n||r>Rf?null:e-n.apyPercent}function Xu(o,e){if(!Number.isFinite(o))return o;let t=10**e,n=Number((o*t).toPrecision(15));return(o<0?-Math.floor(-n):Math.floor(n))/t+0}var it=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",n={lendingRatesBaseUrl:e.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},r=new ja(n);this.read=new Jo(t,n,r),this.supply=new Zo(t)}async listSupportedChains(){return this.supply.listChains()}async isSupported(e){return this.supply.isSupported(e)}async getMarkets(e){return this.supply.getMarkets(e)}async findMarket(e,t){return this.supply.findMarket(e,t)}canSupply(e){return this.supply.canSupply(e)}async readReceiptToken(e,t){return this.supply.readReceiptToken(e,t)}async describeReceiptTokens(e,t,n){return this.read.describeReceiptTokens(e,t,n)}async findMarketByReceiptToken(e,t,n){return this.read.findMarketByReceiptToken(e,t,n)}async describeResolvedMarkets(e,t){return this.read.describeResolvedMarkets(e,t)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async n=>this.read.describeResolvedMarkets(n,await this.getMarkets(n))))).flat().sort((n,r)=>(r.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};var Is="{market}",Zu=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],Xa=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],ed="[[LIST]]",td=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',nd=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function od(o,e,t){let[n]=_f([o],e,t),[r]=o.canSupply?Yl(o,e,t):[];return{name:o.name?.trim()||o.protocol,protocol:o.protocol,protocolUrl:o.protocolUrl,chain:t,apyPercent:o.apyPercent,detailPrompt:n?.prompt??"",detailLabel:n?.label??"",supplyPrompt:r?.prompt??"",supplyLabel:r?.label??""}}function _f(o,e,t){return rd(o,{labelTemplate:za(e.detail_button_label),promptTemplate:za(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Is}`,...t===void 0?{}:{chainName:t}})}function Yl(o,e,t){return rd([o],{labelTemplate:za(e.supply_button_label),promptTemplate:za(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Is}`,promptFallback:`supply to ${Is}`,...t===void 0?{}:{chainName:t},max:1})}function rd(o,e){let t=typeof e.chainName=="string"?e.chainName.trim():"",n=[],r=new Set;for(let s of o){if(e.max!==void 0&&n.length>=e.max)break;let a=s.name?.trim();!a||r.has(a.toLowerCase())||(r.add(a.toLowerCase()),n.push({label:Qu(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:Qu(Nf(e.promptTemplate),a,e.promptFallback)+Lf(s.contract,t)}))}return n}function Nf(o){let[e,t]=[o[0],o[1]];return e===void 0||e===e.toLowerCase()||t!==void 0&&t!==t.toLowerCase()?o:e.toLowerCase()+o.slice(1)}function za(o){return typeof o=="string"?o:""}function Lf(o,e){let t=o?.trim();if(!t||!/^0x[a-fA-F0-9]{40}$/.test(t))return"";let n=e?.trim();return n?` (market: ${t} - ${n})`:` (market: ${t})`}function Qu(o,e,t,n=!0){let s=o&&(!n||o.includes(Is))?o:t;return If(s).split(Is).join(e).replace(/\s+/g," ").trim()}var Ju="{chain}";function If(o){if(!o.includes(Ju))return o;let e=Ju.replace(/[{}]/g,"\\$&");return o.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}var Qa=[{id:"aave-v3",label:"Aave v3",types:["aave-v3"],aliases:["aave","aavev3","aave3","ave"]},{id:"compound-v3",label:"Compound v3",types:["compound-v3"],aliases:["compound","compoundv3","compound3","comet","comp"]},{id:"spark-any",label:"Spark",types:["spark","spark-ethereum"],aliases:["spark","sparkfi","sparklend","sparkprotocol"]},{id:"morpho-v2",label:"Morpho",types:["morpho-v2"],aliases:["morpho","morphov2","morpho2","morphoblue","metamorpho"]}],Kl=Qa.map(o=>o.label),Gl={euler:"Euler",venus:"Venus",radiant:"Radiant",benqi:"Benqi",qi:"Benqi",fluid:"Fluid",instadapp:"Fluid",silo:"Silo",moonwell:"Moonwell",sonne:"Sonne",granary:"Granary",ironbank:"Iron Bank",cream:"Cream",maker:"Maker",makerdao:"Maker",sky:"Sky",justlend:"JustLend",kamino:"Kamino",solend:"Solend",marginfi:"marginfi",save:"Save",curve:"Curve",yearn:"Yearn",convex:"Convex",pendle:"Pendle",ethena:"Ethena",gearbox:"Gearbox",notional:"Notional",exactly:"Exactly",seamless:"Seamless",zerolend:"ZeroLend",dforce:"dForce",tectonic:"Tectonic",liqee:"Liqee"};function sd(o){let e=typeof o=="string"?o.trim():"";if(!e)return{kind:"none"};let t=Mf(e);if(!t)return{kind:"none"};let n=Uf(t);if(n){let s=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>s.has(a.type)}}let r=Of(t);return r?{kind:"unsupported",label:r,requested:e}:{kind:"unknown",requested:e}}function Uf(o){let e=Qa.filter(t=>t.aliases.includes(o));if(e.length===1)return e[0];if(e.length>1)return null;if(o.length>=3){let t=Qa.filter(n=>n.aliases.some(r=>r.includes(o)||o.includes(r)));if(t.length===1)return t[0];if(t.length>1)return null}return Df(o)}function Df(o){let e=null,t=!1;for(let n of Qa)for(let r of n.aliases){let s=ad(r);if(s===0||Math.abs(r.length-o.length)>s)continue;let a=id(o,r,s);a>s||(!e||a<e.distance?(e={spec:n,distance:a},t=!1):a===e.distance&&n!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function ad(o){return o.length<=4?0:o.length<=9?2:3}function Of(o){let e=Gl[o];if(e)return e;if(o.length>=4){let r=new Set(Object.entries(Gl).filter(([s])=>s.length>=4&&(s.includes(o)||o.includes(s))).map(([,s])=>s));if(r.size===1)return[...r][0];if(r.size>1)return null}let t=null,n=!1;for(let[r,s]of Object.entries(Gl)){let a=ad(r);if(a===0||Math.abs(r.length-o.length)>a)continue;let i=id(o,r,a);i>a||(!t||i<t.distance?(t={label:s,distance:i},n=!1):i===t.distance&&s!==t.label&&(n=!0))}return t&&!n?t.label:null}function Mf(o){return o.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function id(o,e,t){if(o===e)return 0;if(!o.length)return e.length;if(!e.length)return o.length;let n=new Array(e.length+1),r=Array.from({length:e.length+1},(a,i)=>i),s=new Array(e.length+1);for(let a=1;a<=o.length;a++){s[0]=a;let i=s[0];for(let c=1;c<=e.length;c++){let d=r[c-1]+(o[a-1]===e[c-1]?0:1),u=Math.min(s[c-1]+1,r[c]+1,d);a>1&&c>1&&o[a-1]===e[c-2]&&o[a-2]===e[c-1]&&(u=Math.min(u,n[c-2]+1)),s[c]=u,u<i&&(i=u)}if(i>t)return t+1;let l=n;n=r,r=s,s=l}return r[e.length]}function ge(o,e){return o==null?null:Xu(o,e)}var Le=2,ln=2;function Ja(o){let e=ge(o.currentApyPercent,Le),t=o.rewards.map(s=>({apyPercent:ge(s.apyPercent,Le)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),n=o.rewardApyPercent===null?null:t.reduce((s,a)=>s+Math.round(a.apyPercent*100),0)/100;if(n===null||e===null)return{currentApyPercent:e,rewardApyPercent:n,rewards:t,baseApyPercent:ge(o.baseApyPercent,Le)};let r=Math.round(e*100)-Math.round(n*100);return{currentApyPercent:e,rewardApyPercent:n,rewards:t,baseApyPercent:r/100}}var Ff=["apy","score","size"],ld=3,cd=40,er=class extends P{name="get-lending-markets";kind="ui";description='BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${Kl.join(", ")}. Set it whenever the user names a protocol \u2014 "supply aave", "morpho vaults", "l\xE3i su\u1EA5t b\xEAn Compound" \u2014 and pass what they wrote, VERBATIM. Do NOT correct their spelling, do NOT translate it, and do NOT map it to a name from the supported list yourself: misspellings are resolved for you, and a protocol that is NOT supported is reported back so you can tell the user. Pass it even when you believe the protocol is unsupported \u2014 that is how the user gets told. OMIT it when the user named no protocol; never guess one to narrow a list they asked for in full.`,required:!1},{name:"limit",type:"number",description:`How many markets to return, 1-${cd}. Default ${ld} \u2014 the top markets by the chosen ranking, which answers "where can I earn on my USDC" on its own. Raise it ONLY when the user asks for more than that, for the full list, or to compare broadly; lower it when they want a shorter shortlist.`,required:!1},{name:"sort",type:"string",description:'Ranking: "apy" (default, highest live protocol APY first), "score" (safest / best-rated first \u2014 use when the user asks for safe, reliable or trusted markets), or "size" (largest market first \u2014 use when the user asks for the biggest or most liquid markets).',required:!1},...Zu,...Xa];service;constructor(e){super(),this.service=new it(e)}async run(e,t){let n=j(e.chain,void 0),r=n?null:M(t?.chain),s=n??r,a=s?await this.service.isSupported(s):!1,i=a?[]:await this.service.listSupportedChains();if(s&&!a)return{_instructions:`There are no lending markets on ${T(s)}`+(r?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:T(s),connectedChainHasNoMarkets:r!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:i.map(y=>T(y))};let l=sd(e.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,d=qf(e.sort),u=$f(e.limit),p=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?p.filter(y=>l.matches(y)):p;if(l.kind==="supported"&&m.length===0&&p.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?T(s):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?T(s):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(p.map(y=>y.protocol))]};let f=[...m].sort(Bf[d]).slice(0,u),h=f.map(y=>od({name:y.name,contract:y.contract,protocol:y.protocol,protocolUrl:y.protocolUrl,apyPercent:ge(y.currentApyPercent,Le),canSupply:this.service.supply.canSupply(y)},e,T(y.chain))),b={component:"LendingMarketList",props:{chain:s?T(s):"all",multiChain:new Set(h.map(y=>y.chain)).size>1,markets:h}};return{...h.length>0?{ui:b}:{},_instructions:this.instructions(f,d,h.length>0,l.kind==="supported"?l.label:null),chain:s?T(s):"all",chainsQueried:c.map(y=>T(y)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:d,marketCount:h.length,totalMarketsAvailable:m.length,marketNames:h.map(y=>y.name)}}unsupportedProtocol(e){let t=e.kind==="unsupported",n=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${n}, which has no lending markets here. In their language: tell them plainly that ${n} is ${t?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${n} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:t?e.label:e.requested,protocolSupported:!1,supportedProtocols:[...Kl],marketCount:0,marketNames:[]}}instructions(e,t,n=!1,r=null){if(e.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let s={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[t];return[r?`These are the ${r} lending markets the user can supply to, ${s}. The list is SCOPED to ${r} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,`Write your reply in TWO parts separated by a line containing exactly ${ed} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",t==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${T(e[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${s} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",n?td:""].filter(Boolean).join(" ")}},Bf={apy:(o,e)=>(e.currentApyPercent??-1)-(o.currentApyPercent??-1),score:(o,e)=>(e.platformScore??-1)-(o.platformScore??-1),size:(o,e)=>(e.totalSuppliedUsdc??-1)-(o.totalSuppliedUsdc??-1)};function qf(o){let e=typeof o=="string"?o.trim().toLowerCase():"";return Ff.includes(e)?e:"apy"}function $f(o){let e=typeof o=="number"?o:Number(o);return!Number.isFinite(e)||e<1?ld:Math.min(Math.floor(e),cd)}function ud(o){let{currentApyPercent:e,avgApyPercent:t,totalSuppliedUsdc:n,rewardApyPercent:r,baseApyPercent:s,platformScore:a}=o;return o.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:r!==null&&s!==null&&r>s*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:e!==null&&t!==null&&t>0&&e>t*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:n!==null&&n<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&n!==null&&n>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:n!==null&&n>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}function Za(o){let e=typeof o=="string"?o.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(e);if(t)return t[1];let n=/0x[a-fA-F0-9]{40}/.exec(e);return n&&n[0]!==e?n[0]:e}var tr=class extends P{name="get-lending-market-detail";category="blockchain-data";description='Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...Xa];service;constructor(e){super(),this.service=new it(e)}async run(e,t){let r=j(e.chain,void 0)??M(t?.chain);if(!r)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(r)){let u=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(r),chainsWithLendingMarkets:u.map(p=>T(p)),_instructions:`There are no lending markets on ${T(r)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=Za(e.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let a=await this.service.findMarket(r,s);if(a.length===0)return{error:"market_not_found",market:s,chain:T(r),_instructions:`No lending market matching "${s}" exists on ${T(r)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(a.length>1)return{error:"ambiguous_market",market:s,chain:T(r),candidates:a.map(u=>({marketName:u.name,protocol:u.protocol})),_instructions:`"${s}" matches ${a.length} different markets on ${T(r)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${T(r)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let i=a[0],l=await this.describeOne(r,i);if(!l)return{error:"market_unavailable",marketName:i.name,chain:T(r),_instructions:`${i.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let c=this.service.supply.canSupply(i),d=c?Yl({name:i.name,contract:i.contract},e,T(r)):[];return{_instructions:this.instructions(l,d.length>0,c),...d.length>0?{actionButtons:d}:{},marketName:l.name,protocol:l.protocolLabel??l.protocol,protocolUrl:l.protocolUrl,chain:T(l.chain),suppliedAssetSymbol:l.asset.symbol,totalSuppliedUsdc:ge(l.totalSuppliedUsdc,ln),...Ja(l),avgApyPercent:ge(l.avgApyPercent,Le),apyChangePercent:ge(l.apyChangePercent,Le),platformScore:l.platformScore,supplySupported:c}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}instructions(e,t,n){let r=ud(e);return[`This is the full picture of ONE lending market, ${e.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${r.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${r.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',n?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",t?nd:""].filter(Boolean).join(" ")}};var nr=class extends P{name="get-wallet-lending-positions";description='Get a wallet\'s own LENDING / SUPPLY (earn, deposit, savings) positions in the curated lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much it has supplied there, the AVERAGE supply APY over the last week (plus the live rate and the day-over-day change), the estimated yearly yield on that balance, and the market total supplied. Balances are read on-chain, so they match the app. Use for questions like: "Which protocols am I supplying on?", "Show my lending positions", "How much am I earning on my USDC?", "What APY am I getting?", "Where is my USDC deposited?", "My Aave / Compound / Spark / Morpho supply", "what am I earning on Aave", "my savings positions". This is the PREFERRED tool for any "what am I earning / supplying / depositing" question, even when the user names a protocol ("my Aave v3 supply", "my Spark deposit") \u2014 it is the only source of the 7-day average APY, the estimated yearly yield and the platform safety score. Each position reports its OWN asset, which is usually USDC but need not be \u2014 never assume the amounts are dollars without checking `suppliedAssetSymbol`. Chains and markets come from the live catalogue, so do not rule a chain out from memory: call the tool and let it answer. For protocols outside Aave v3 / Compound v3 / Spark / Morpho (Aave v2, MakerDAO\u2026), or when this tool reports nothing but the user insists they have a deposit, fall back to get-wallet-defi-positions. Do NOT use for: markets the wallet has NOT supplied to yet \u2014 where to deposit, best available APY, "promising lending" \u2192 get-lending-markets; the BORROW side of these same protocols, plus LP / staking \u2192 get-wallet-defi-positions (or get-wallet-defi-protocol-positions for one named protocol); plain token balances \u2192 get-wallet-token-balances.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:`Hex chain ID to scope to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry lending markets is resolved at call time, so do NOT filter the request against a list you remember. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 positions are then read on the connected wallet's own chain.`,required:!1}];service;constructor(e){super(),this.service=new it(e)}async run(e,t){let n=ae(e.address,t);if(!E(n))return{error:`"${n}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let r=j(e.chain,t),s=r?await this.service.isSupported(r):!1,a=s?[]:await this.service.listSupportedChains();if(r&&!s)return{_instructions:`There are no lending markets on ${T(r)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:n,chain:T(r),positionCount:0,positions:[],chainsWithLendingMarkets:a.map(c=>T(c))};let i=r?[r]:a,l=await this.service.getSupplyPositions({address:n,chains:i});return{_instructions:this.instructions(l),walletAddress:n,chain:r?T(r):"all",chainsQueried:i.map(c=>T(c)),positionCount:l.length,totals:Hf(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:T(c.chain),suppliedUsdc:ge(c.suppliedUsdc,ln),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:ge(c.avgApyPercent,Le),...Ja(c),apyChangePercent:ge(c.apyChangePercent,Le),estimatedAnnualYieldUsdc:ge(c.estimatedAnnualYieldUsdc,ln),marketTotalSuppliedUsdc:ge(c.totalSuppliedUsdc,ln),apyHistory:c.apyHistory.map(d=>({...d,apyPercent:ge(d.apyPercent,Le)})),platformScore:c.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(n=>n.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Hf(o){if(new Set(o.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let n=o.reduce((a,i)=>a+i.suppliedUsdc,0),r=o.filter(a=>a.avgApyPercent!==null),s=r.reduce((a,i)=>a+i.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:o[0]?.asset.symbol??null,suppliedUsdc:ge(n,ln),estimatedAnnualYieldUsdc:ge(o.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),ln),weightedAvgApyPercent:ge(s>0?r.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s:null,Le)}}var or=class extends P{name="open-supply-usdc-form";kind="ui";category="lending-action";description='Open the SUPPLY form so the user can DEPOSIT into a specific lending market and start earning yield. This is the tool for a supply COMMAND: the user names a market and tells you to act on it, in any wording and any language \u2014 "supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare "Supply Aave", or a tapped "Supply \u2026" button. A supply verb plus a market name is already a complete command; terseness is not ambiguity, and the words the user left out are supplied by context rather than looked up. Each market deposits its OWN asset (usually USDC), resolved from the market itself \u2014 so a message that names no asset is still this tool: resolve the market from whatever the user did name. An amount is optional. Pass `market` \u2014 the market name or protocol exactly as it was shown to them (e.g. "Aave v3 USDC", "Spark"), and `amount` ONLY when they named one. Supports Aave v3, Compound v3, Spark and Morpho vaults, on whichever chains currently carry them \u2014 that set is resolved at call time, so never refuse a chain from memory. PRECONDITION: a connected wallet. The boundary is command vs question: use this to ACT on one market; to LIST or compare markets \u2192 get-lending-markets; for what the wallet already supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}];service;moralis;constructor(e){super(),this.service=new it(e),this.moralis=new U(e?.moralis)}async run(e,t){let n=t?.walletAddress;if(!n)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let s=j(e.chain,void 0)??M(t?.chain);if(!s)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};if(!await this.service.isSupported(s)){let b=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(s),chainsWithLendingMarkets:b.map(y=>T(y)),_instructions:`There are no lending markets on ${T(s)}, so nothing can be supplied there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let a=Za(e.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let i=await this.service.findMarket(s,a);if(i.length===0)return{error:"market_not_found",market:a,chain:T(s),_instructions:`No lending market matching "${a}" exists on ${T(s)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(i.length>1)return{error:"ambiguous_market",market:a,chain:T(s),candidates:i.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${a}" matches ${i.length} different markets on ${T(s)}, so the supply cannot target one yet. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+a+`" and chain for ${T(s)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let l=i[0];if(!this.service.supply.canSupply(l))return{error:"unsupported_protocol",marketName:l.name,protocol:l.protocol,_instructions:`Supplying to ${l.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let c=await this.describeOne(s,l),d=Vf(c);if(!d)return{error:"asset_unresolved",marketName:l.name,chain:T(s),_instructions:`The asset ${l.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[u,p]=await Promise.all([this.assetBalance(n,s,d.address),this.service.readReceiptToken(s,l)]);if(u&&Zt(u.amount,"0")<=0)return{error:"no_asset_balance",marketName:l.name,chain:T(s),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${l.name} on ${T(s)}. In the user's language, tell them plainly that they have no ${d.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let m=Wf(e.amount),f=m?Nt(m,d.decimals):null;if(f&&u&&Zt(f,u.amount)>0)return{error:"insufficient_asset_balance",marketName:l.name,chain:T(s),assetSymbol:d.symbol,requestedAmount:m,assetBalance:u.amount,_instructions:`The user wants to supply ${m} ${d.symbol} to ${l.name}, but they only hold ${u.amount} ${d.symbol} on ${T(s)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${m} ${d.symbol} exceeds their balance of ${u.amount} ${d.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let h={action:"supply_usdc",chainId:s,chainName:T(s),walletAddress:n,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??Ka(l),contract:l.contract,token:l.token,apyPercent:c?.currentApyPercent??c?.avgApyPercent??null,receiptToken:p},asset:d,...f?{prefillAmount:f}:{},...u?{spendable:u.amount}:{},...u?.usd?{spendableUsd:u.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:h},marketName:l.name,protocol:l.protocol,chain:T(s),apyPercent:ge(h.market.apyPercent,Le),assetSymbol:d.symbol,assetBalance:u?.amount??null,_instructions:this.instructions(l,d.symbol)}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}async assetBalance(e,t,n){try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[n]});if(!r.success)return null;let s=(r.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===n.toLowerCase());if(!s?.balance_formatted)return{amount:"0",usd:null};let a=typeof s.usd_value=="number"?String(s.usd_value):null;return{amount:String(s.balance_formatted),usd:a}}catch{return null}}instructions(e,t){return[`The supply action for ${e.name} is ready.`,`In the user's language, invite them to enter the amount of ${t} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${t}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function Vf(o){let e=o?.asset;return!e?.address||e.address===$n||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Wf(o){let e=typeof o=="string"?o.trim():typeof o=="number"?String(o):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var ei="https://ipfs.pantograph.app/ipfs/",dd=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Vn(o){let e=o?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ei}${t[1]}`:dd.test(e)?`${ei}${e}`:null}function pd(o){let e=o?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ei}${t[1]}`:dd.test(e)?`${ei}${e}`:null}function md(o){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(o)}function jl(o){if(!o||typeof o!="object")return;let e=o,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function Yf(o){if(typeof atob=="function"){let e=atob(o),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(o,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Gf(o){let e=o.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",n=e[2]??"";try{let r=/;base64/i.test(t)?Yf(n):decodeURIComponent(n);return JSON.parse(r)}catch{try{return JSON.parse(n)}catch{return null}}}function hd(o){let e=o?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Gf(e);return t?Vn(jl(t)):null}var Kf=12,jf=6e3;async function zf(o,e,t){let n=new Array(o.length),r=0,s=new Array(Math.max(1,Math.min(e,o.length))).fill(0).map(async()=>{for(;r<o.length;){let a=r++;n[a]=await t(o[a],a)}});return await Promise.all(s),n}async function Xf(o,e){try{let t=await x.get(o,{timeout:e});if(!t.ok)return null;let n=t.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function Qf(o,e){let t=o?.trim();if(!t)return null;if(/^data:/i.test(t))return hd(t);let n=pd(t);if(!n)return null;if(md(n))return n;let r=await Xf(n,e);if(r){let s=Vn(jl(r));if(s)return s}return null}async function ti(o,e,t){if(e.length===0)return[];let n=t?.concurrency??Kf,r=t?.timeoutMs??jf,s=await mu(o,e,t?.rpcUrl);return zf(s,n,a=>Qf(a,r))}var fd=100,Jf=100,rr="{name}",gd="{chain}",sr=class extends P{name="get-wallet-nfts";description=`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`;category="nft";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}];service;constructor(e){super(),this.service=new U(e)}async run(e,t){let n=ae(e.address,t),r=j(e.chain,t),s=r?[r]:Fe(),a=rg(e.contract_address),i=wd(e.collection_name);return a||i?this.listNfts({address:n,chains:s,singleChain:!!r,contract:a,collectionName:i}):this.listCollections({address:n,chains:s,singleChain:!!r,args:e})}async listCollections(e){let{address:t,chains:n,singleChain:r,args:s}=e,a=await Promise.all(n.map(async c=>{let d=await this.service.getWalletNftCollections({address:t,chain:c,limit:fd});return{chain:c,rows:d.success?yd(d.data?.result??[]):[],ok:d.success}}));if(r&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(d=>({name:eg(d),contractAddress:d.token_address,chain:T(c.chain),nftCount:d.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(r?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=ng(i,s);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:n,singleChain:r,contract:s,collectionName:a}=e,i=await Promise.all(n.map(async m=>{let f=await this.service.getWalletNFTs({address:t,chain:m,limit:fd,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:f.success?yd(f.data?.result??[]):[],ok:f.success}}));if(r&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>Zf(f,{contract:s,collectionName:a})).map(f=>({chain:m.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??s??""}"`+(r?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,d=await this.resolveOnchainImages(l),u=l.map(({chain:m,row:f},h)=>{let g=tg(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:d[h]??g.image,chain:T(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:u}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),n=new Map;e.forEach((r,s)=>{let a=n.get(r.chain)??[];a.push(s),n.set(r.chain,a)});try{await Promise.all([...n.entries()].map(async([r,s])=>{let a=s.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await ti(r,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function yd(o){return o.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Zf(o,e){if(e.contract)return o.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(o.name??"").toLowerCase().includes(t)}return!1}function eg(o){let e=o.name?.trim();if(e)return e;let t=o.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function tg(o){return{name:o.normalized_metadata?.name||o.name||`#${o.token_id}`,tokenId:o.token_id,contractAddress:o.token_address,image:Vn(o.normalized_metadata?.image||o.media?.original_media_url)}}function ng(o,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",r=[];for(let s of o){if(r.length>=Jf)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${rr} NFTs on ${gd}`:`show my ${rr} NFTs`,l=bd(n,{[rr]:s.name,[gd]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),r.push({label:og(t,s.name,rr),prompt:`${l} (${s.contractAddress})`})}return r}function bd(o,e,t){let n=o&&o.includes(rr)?o:t;for(let[r,s]of Object.entries(e))n=n.split(r).join(s);return n.replace(/\s+/g," ").trim()}function og(o,e,t){return bd(o,{[rr]:e},t)}function wd(o){if(typeof o!="string")return;let e=o.trim();return e||void 0}function rg(o){let e=wd(o);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var sg="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",vt=class extends P{kind="data";category="nft";llm;constructor(e){super(),this.llm=new be(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:sg,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var ar=class extends vt{name="get-nft-contract-info";description='Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.';parameters=vt.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`);presentInstructions="Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks."};var ir=class extends vt{name="get-nft-metadata";description='Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.';parameters=vt.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`);presentInstructions="Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points."};var zl={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},Xl="amazon.com";function ag(o){return o?o.trim().toLowerCase().split(/[-_]/)[0]:""}function Ql(o){let e=ag(o);return zl[e]??Xl}function ni(o){return`https://${Ql(o)}/s?k=NFC%20Tag`}function oi(o){if(!o)return"";let e=o.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var ig=720*60*1e3,kd=new Map,vd=3;function lg(o){return[`A user in country "${o}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${vd} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function cg(o){if(!o)return[];let e=o.indexOf("["),t=o.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(o.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let r=[],s=new Set;for(let a of n){if(!a||typeof a!="object")continue;let i=a.label,l=a.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!s.has(c)&&(s.add(c),r.push({label:i.trim(),url:l.trim()}),r.length>=vd))break}return r}async function Jl(o,e){let t=oi(o);if(!t||!e)return null;let n=kd.get(t);if(n&&n.expires>Date.now())return n.links;let r=Date.now(),s=[{role:"user",content:lg(t),timestamp:r}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=cg(a.text);if(i.length)return kd.set(t,{links:i,expires:Date.now()+ig}),i}catch{}return null}async function lr(o){let e=await Jl(o.country,o.llm);return e&&e.length?e:[{label:"Amazon",url:ni(o.language)}]}function ug(o){return o.length<=1?o.length===1?`[${o[0].label}](${o[0].url})`:"":o.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
40
|
+
`)}var Td=["WHAT IT IS: NFC (Near-Field Communication) is a short-range wireless standard operating at 13.56 MHz, a",'subset of the older RFID family. An "NFC tag" is a tiny passive chip + antenna (often embedded in a','sticker, card, keyfob, wristband, or ring). "Passive" means it has no battery \u2014 it draws all its power from',"the electromagnetic field of the reader (a smartphone or dedicated reader) when held within ~2\u20134 cm. The","tag does nothing on its own; it simply waits to be tapped, then hands over the small piece of data it holds.","","HOW IT WORKS: When an NFC-enabled phone comes close, the reader emits a 13.56 MHz radio field. Through","inductive (magnetic) coupling that field powers the tag, which then transmits its stored data back to the","reader \u2014 no pairing, no app launch, no internet required for the handshake. The exchange is bidirectional","and near-instant (well under a second). Tags can be READ many times and, unless locked, also re-WRITTEN.","Data is stored in the standardised NDEF format (NFC Data Exchange Format) so any NFC phone can parse it the","same way. NFC works in three modes: reader/writer (phone reads or writes a tag), peer-to-peer (two devices","exchange data), and card-emulation (the phone itself acts like a tag, e.g. for tap-to-pay).","","WHAT'S INSIDE AN NFC TAG: just two parts \u2014 (1) a microchip (the integrated circuit) that holds a small","block of memory plus simple logic, and (2) a thin coiled antenna (usually etched copper or aluminium) that","both harvests power from the reader's field and carries the data signal. There is no battery and no moving","parts, which is why tags are paper-thin, cheap, and last for years (often rated for ~10 years of storage","and 100,000+ rewrites). Common chips differ mainly by memory size: NTAG213 (~144 bytes), NTAG215","(~504 bytes), NTAG216 (~888 bytes); larger/industrial families (e.g. ICODE, MIFARE) add more memory or","security features.","","WHAT IT CAN STORE: capacity is small \u2014 tens to a few hundred bytes of usable memory \u2014 so a tag holds a","compact payload, not files. Typical contents: a website URL, plain text, a contact card (vCard), Wi-Fi","credentials (SSID + password for one-tap join), an app-launch or deep link, a phone number / email,","geo-coordinates, a Bluetooth pairing handoff, or a small identifier/token. It is NOT mass storage \u2014 large","content lives elsewhere and the tag holds a pointer (a link or ID) to it.","","COMMON REAL-WORLD USES: contactless payments (Apple Pay / Google Pay via card emulation); transit and","access cards (metro, office door badges, hotel keys); product tags and anti-counterfeit / authenticity","checks; smart posters and marketing (tap to open a page, menu, or promo); pairing speakers/headphones with",'one tap; digital business cards and "tap to share contact"; smart-home automations (tap a tag by the door',"to run a routine); inventory, asset tracking, and ticketing; and tap-to-act crypto flows (e.g. open a","wallet address or a dapp link).","","HOW TO USE ONE: (1) Get an NFC tag (sticker/card/keyfob). (2) Make sure the phone has NFC enabled","(Settings \u2192 Connections/NFC; most modern Android phones and iPhone XS and later support it). (3) To WRITE,",'install an NFC writer app (e.g. "NFC Tools"), choose the record type (URL, text, Wi-Fi\u2026), enter the data,',"and tap the phone to the tag to program it. (4) To READ, just tap the phone to the tag \u2014 the action fires","automatically. (5) Optionally LOCK the tag to make it read-only so the data cannot be overwritten. Keep the","tag away from metal surfaces, which can detune the antenna and block reads.","","WHY THEY ARE POPULAR: they are extremely cheap (cents each), battery-free and maintenance-free, work with","the phone almost everyone already carries, and need just a tap \u2014 no app pairing, codes, or setup. The very","short range is a feature, not a bug: you must deliberately bring the devices together, which makes NFC","trusted for payments and access where accidental or remote reads would be a security risk.","","CRYPTO / WALLET CONTEXT: because a tag can hold a short identifier or address, NFC is handy for tap-to-act","flows \u2014 e.g. encoding a public wallet address or a deep link. Private keys/seed phrases should never be","written to an open, re-writable tag; treat tags as public, tamper-readable pointers, not secure key vaults.","","PRACTICAL TIPS: re-writable blank tags are inexpensive; pick a chip with enough memory for the payload",'(NTAG215+ for longer URLs or vCards). Use a metal-shielded ("on-metal") tag if you must stick it to a',"metal surface. Range is intentionally tiny (a few cm) for security \u2014 you must deliberately tap."].join(`
|
|
41
|
+
`),cr=class extends P{kind="data";name="nfc-info";category="nfc";description='Use when the user asks a conceptual / how-to question about NFC tags \u2014 what an NFC tag is, how NFC works, what data a tag can store, tag types/capacity, or how to read/write/use one ("what is an NFC tag", "how does NFC work", "what can I store on an NFC tag", "how do I use an NFC tag"). Returns an expert reference to answer from, plus a country-appropriate Amazon buy link to close with. Pass the current turn\'s BCP-47 `language` so the right storefront is picked. For a pure "where to buy" question with no explanation needed, prefer nfc-buy-link.';parameters=[{name:"language",type:"string",description:`The BCP-47 language tag of the user's current message (e.g. "en", "vi", "ja", "zh", "de"). Used only to pick the local Amazon storefront for the closing buy link. Optional (defaults to amazon.com).`,required:!1}];llm;constructor(e){super(),e&&(this.llm=new be(e))}async run(e,t){let n=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,r=await lr({country:t?.country,language:n,llm:this.llm}),s=ug(r),a=r.length>1;return{reference:Td,marketplaceLinks:r,_instructions:`Answer the user's NFC question as a knowledgeable, friendly expert, writing in the USER'S language (translate naturally \u2014 never leave it in English when they wrote another language). Draw on the reference below for the facts (do NOT invent anything beyond it), but write a polished, well-organized answer \u2014 not a terse one-liner. FORMAT: Use short Markdown section headings (bold or "##") and bullet points so it is easy to scan, similar to a great encyclopedia entry. For a broad question like "what is an NFC tag", give a thorough multi-section answer: open with a 1\u20132 sentence plain-language definition, then cover sections such as "How it works", "What's inside", "What it can store", "Common uses", "How to use one", and "Why they're popular" \u2014 include concrete specifics (the 13.56 MHz frequency, chip names + byte capacities, example payloads, numbered steps). Aim for genuinely useful depth, several short paragraphs/lists, not a wall of dense text. For a NARROW question (e.g. only "what can it store" or "how do I write one"), answer just that part in focused detail and skip the unrelated sections. Do not mention tools, this reference, or that anything is canned. AT THE END, add a short closing line telling them where they can buy NFC tags, then include EACH of these exact CLICKABLE Markdown links `+(a?"as a NUMBERED Markdown list (1., 2., 3.), ONE store per line, in this exact order and numbering":"inline")+` (keep every URL byte-for-byte; localize only the visible text; keep the form [text](url)):
|
|
42
42
|
${s}
|
|
43
43
|
Never show a raw URL on its own and never drop a link. Reference:
|
|
44
44
|
|
|
45
|
-
`+
|
|
46
|
-
`)}var
|
|
45
|
+
`+Td}}};function dg(o){return o.length<=1?o.length===1?`[${o[0].label}](${o[0].url})`:"":o.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
46
|
+
`)}var ur=class extends P{kind="data";name="nfc-buy-link";category="nfc";description='Use when the user asks WHERE / HOW to BUY or get an NFC tag ("where can I buy an NFC tag", "where to get NFC tags", "buy NFC tag"). Returns the largest local e-commerce platforms for the user\'s country (or a language-based Amazon link when the country is unknown), each pre-filled with an "NFC Tag" search. Pass the BCP-47 language tag of the current turn as `language`.';parameters=[{name:"language",type:"string",description:`The BCP-47 language tag of the user's current message (e.g. "en", "vi", "ja", "zh", "de"). Used to pick the Amazon storefront in the fallback case. Optional \u2014 omit only if truly unknown.`,required:!1}];llm;constructor(e){super(),e&&(this.llm=new be(e))}async run(e,t){let n=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,r=await lr({country:t?.country,language:n,llm:this.llm}),s=dg(r),a=r.length>1;return{marketplaceLinks:r,message:a?`You can buy NFC tags here:
|
|
47
47
|
${s}`:`You can buy NFC tags on ${s}.`,_instructions:"Tell the user, in their OWN language, where they can buy NFC tags. "+(a?"Add one short intro line, then present the stores as a NUMBERED Markdown list (1., 2., 3.), ONE store per line, each a CLICKABLE Markdown link. ":"Output ONE short, friendly sentence with the store as a CLICKABLE Markdown link. ")+`Keep every URL byte-for-byte exactly as given; you may localize only the visible link text. Keep the form [text](url). NEVER show a raw URL on its own and NEVER drop a link. No second copy, and do not mention tools. The exact links to include, in this order and numbering:
|
|
48
|
-
${s}`}}};var
|
|
49
|
-
${
|
|
50
|
-
`)}`,timestamp:s},{role:"user",content:n,timestamp:s}];try{return{source:"gemini-search-ai",answer:(await this.llm.chat(a,void 0,{googleSearch:!0,maxRetries:1})).text?.trim()??""}}catch(i){return{error:i instanceof Error?i.message:String(i)}}}};var
|
|
48
|
+
${s}`}}};var pg="You are a sharp, search-grounded crypto & DeFi analyst. Use the live Google Search grounding to back claims with up-to-date data, and attribute the source/outlet and approximate date for any news or figures you report. NEVER invent specific on-chain numbers, prices, addresses, or transaction hashes \u2014 if the data isn't available, say so. Be concise, practical, and honest about uncertainty; for anything touching returns or strategy, add a brief reminder that it is informational, not financial advice. Answer in the user's language. Do NOT mention tools, APIs, search, or that you are a fallback.",dr=class extends P{name="gemini-search-ai";description="Ask a search-grounded Gemini model for blockchain / crypto insights that no dedicated tool can answer. Use this as a LAST-RESORT fallback when the specialised data tools are insufficient. Backed by live Google Search grounding \u2014 good for: market analysis, category/theme queries (meme, AI, gaming, L2, RWA), DeFi protocol explanations, cross-chain comparisons, trend / sentiment, recent news or announcements, gas insights, NFT collection lore, and any open-ended crypto reasoning question. Chain-agnostic \u2014 write the chain (Ethereum, BSC, Base, \u2026) and any addresses, time range, or token symbols directly into the prompt. Do NOT use this for: token balances \u2192 get-wallet-token-balances; token prices/metadata \u2192 get-token-info; NFT holdings \u2192 get-wallet-nfts; NFT contract info \u2192 get-nft-contract-info; transaction details \u2192 get-transaction-by-hash; wallet history \u2192 get-wallet-history; token transfers \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; token holders \u2192 get-token-holders; wallet PnL \u2192 get-wallet-pnl or get-wallet-pnl-summary; pool / liquidity data \u2192 pool-agent tools.";category="blockchain-ai";parameters=[{name:"prompt",type:"string",description:'A clear, self-contained English question for the AI. Must include every detail needed to answer without the conversation context: chain (Ethereum / BSC / Base / \u2026), wallet or contract addresses, token symbols, time range, what to compare or rank. Instruct the model to use up-to-date web sources when relevant, and to cite approximate dates and the source/outlet for any news it reports. For market-direction or "why is X up/down" questions, explicitly ask the model to identify the concrete CATALYST behind the move (listing, unlock, partnership, hack, macro, narrative rotation, whale flows) rather than just restating the price change, and to end with a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and what to watch) without giving financial advice or price targets. Example: "List the top 10 meme-category tokens on Ethereum right now, ranked by 24h trading volume, using up-to-date market data." Example: "Explain why PEPE on Ethereum has moved over the last 7 days: identify the main catalyst(s) with dated, sourced news, summarize sentiment, and give a brief hedged short-term outlook."',required:!0}];llm;constructor(e){super(),this.llm=new be(e??{})}async run(e,t){let n=typeof e.prompt=="string"?e.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=[];t?.walletAddress&&r.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&r.push(`- Current chain: ${t.chain}`),r.push("Use this context only when relevant to the question. Do not invent on-chain values.");let s=Date.now(),a=[{role:"system",content:pg,timestamp:s},{role:"system",content:`[USER CONTEXT]
|
|
49
|
+
${r.join(`
|
|
50
|
+
`)}`,timestamp:s},{role:"user",content:n,timestamp:s}];try{return{source:"gemini-search-ai",answer:(await this.llm.chat(a,void 0,{googleSearch:!0,maxRetries:1})).text?.trim()??""}}catch(i){return{error:i instanceof Error?i.message:String(i)}}}};var mg=`You are a world-class DEX liquidity-pool master and analyst \u2014 the deepest pool expert there is.
|
|
51
51
|
You know everything about liquidity pools across protocols and chains: Uniswap V2/V3/V4, PancakeSwap, Curve, Balancer, SushiSwap, Aerodrome, and more.
|
|
52
52
|
Your expertise covers: concentrated liquidity and tick ranges, fee tiers, TVL / 24h volume / fee APR, impermanent loss, LP position management and rebalancing, range strategy (wide vs narrow), pool health and risk, MEV / slippage, incentives & farming, and how pool mechanics differ between AMM designs.
|
|
53
53
|
You answer ANY pool-related question \u2014 conceptual, strategic, comparative, or current-events \u2014 clearly and accurately.
|
|
54
54
|
Use the live Google Search grounding you are given to back claims with up-to-date data (TVL, volumes, APRs, recent protocol changes) whenever relevant; never invent specific on-chain numbers.
|
|
55
|
-
Be concise, practical, and honest about uncertainty. End anything that touches returns or strategy with a brief reminder that it is informational, not financial advice. Answer in the user's language. Do NOT mention tools, APIs, or that you are a fallback.`,
|
|
56
|
-
${
|
|
57
|
-
`)}`,timestamp:s},{role:"user",content:n,timestamp:s}];try{return{source:"pool-fallback-ai",answer:(await this.llm.chat(a,void 0,{googleSearch:!0,maxRetries:1})).text?.trim()??""}}catch(i){return{error:i instanceof Error?i.message:String(i)}}}};function
|
|
55
|
+
Be concise, practical, and honest about uncertainty. End anything that touches returns or strategy with a brief reminder that it is informational, not financial advice. Answer in the user's language. Do NOT mention tools, APIs, or that you are a fallback.`,pr=class extends P{name="pool-fallback-ai";description="Ask a master liquidity-pool analyst (search-grounded AI) any DEX pool question that no structured pool tool can answer. This is the LAST-RESORT pool fallback. Backed by live Google Search \u2014 great for: how Uniswap V3 / V4 pools and concentrated liquidity work, fee-tier and range strategy, impermanent loss, comparing protocols (Uniswap vs Curve vs PancakeSwap \u2026), pool risk / safety, incentives & farming, recent pool-related news or protocol changes, and any open-ended or conceptual pool reasoning. Chain-agnostic \u2014 write the chain (Ethereum, BSC, Base, \u2026) and any pool address or token symbols directly into the prompt. Do NOT use this when a structured subgraph tool fits (pool search, trending pools, pool/position detail by address or id, price-range candidates, add-liquidity) \u2014 only when none of them can serve the question.";category="blockchain-ai";parameters=[{name:"prompt",type:"string",description:'A clear, self-contained English question for the pool master. Must include every detail needed to answer without the conversation context: chain (Ethereum / BSC / Base / \u2026), pool address or token symbols, fee tier, time range, what to compare or explain. Instruct the model to use up-to-date web sources when relevant. Example: "Explain how to choose a price range for an ETH/USDC 0.05% Uniswap V3 pool on Base, and the trade-offs between a narrow and a wide range, using current market context."',required:!0}];llm;constructor(e){super(),this.llm=new be(e??{})}async run(e,t){let n=typeof e.prompt=="string"?e.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=[];t?.walletAddress&&r.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&r.push(`- Current chain: ${t.chain}`),r.push("Use this context only when relevant to the question. Do not invent on-chain values.");let s=Date.now(),a=[{role:"system",content:mg,timestamp:s},{role:"system",content:`[USER CONTEXT]
|
|
56
|
+
${r.join(`
|
|
57
|
+
`)}`,timestamp:s},{role:"user",content:n,timestamp:s}];try{return{source:"pool-fallback-ai",answer:(await this.llm.chat(a,void 0,{googleSearch:!0,maxRetries:1})).text?.trim()??""}}catch(i){return{error:i instanceof Error?i.message:String(i)}}}};function cn(o){return o===8388608}function ri(o,e,t){return t==="V4"||typeof o!="number"||!Number.isFinite(o)||o<=0||cn(o)||typeof e!="number"||!Number.isFinite(e)||e<=0||e>=o?1:1-e/o}function si(o,e,t=1){if(!(typeof o!="number"||!Number.isFinite(o))&&!(typeof e!="number"||!Number.isFinite(e))&&!cn(e))return o*e*t/1e6}function W(o){return typeof o=="number"&&Number.isFinite(o)&&o>0?o:void 0}var hg="https://interface.gateway.uniswap.org",fg="/v1/graphql",gg="https://entry-gateway.backend-prod.api.uniswap.org",Ad="/data.v1.SearchService/SearchTokens",yg="/data.v2.DataApiService/ListPools",ai=100,bg=20,wg="https://liquidity.backend-prod.api.uniswap.org",kg="/uniswap.liquidity.v2.LiquidityService/GetPool",Tt=3,Us=800,Pd=800,vg="0x0000000000000000000000000000000000000000",Nd={"0x1":"ETHEREUM","0xa":"OPTIMISM","0x38":"BNB","0x89":"POLYGON","0x2105":"BASE","0xa4b1":"ARBITRUM","0xa86a":"AVALANCHE","0xe708":"LINEA"},Tg=`query V3Pool($chain: Chain!, $address: String!) {
|
|
58
58
|
v3Pool(chain: $chain, address: $address) {
|
|
59
59
|
id
|
|
60
60
|
protocolVersion
|
|
@@ -87,7 +87,7 @@ fragment TokenPrice on Token {
|
|
|
87
87
|
id
|
|
88
88
|
market(currency: USD) { id price { id value __typename } __typename }
|
|
89
89
|
__typename
|
|
90
|
-
}`,
|
|
90
|
+
}`,Ld=`
|
|
91
91
|
fragment SimpleTokenDetails on Token {
|
|
92
92
|
...TokenBasicInfoParts
|
|
93
93
|
project { id isSpam logoUrl name safetyLevel __typename }
|
|
@@ -102,7 +102,7 @@ fragment TokenPrice on Token {
|
|
|
102
102
|
id
|
|
103
103
|
market(currency: USD) { id price { id value __typename } __typename }
|
|
104
104
|
__typename
|
|
105
|
-
}`,
|
|
105
|
+
}`,Ag=`query V2Pair($chain: Chain!, $address: String!) {
|
|
106
106
|
v2Pair(chain: $chain, address: $address) {
|
|
107
107
|
id
|
|
108
108
|
protocolVersion
|
|
@@ -119,7 +119,7 @@ fragment TokenPrice on Token {
|
|
|
119
119
|
__typename
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
|
-
${
|
|
122
|
+
${Ld}`,Pg=`query V4Pool($chain: Chain!, $poolId: String!) {
|
|
123
123
|
v4Pool(chain: $chain, poolId: $poolId) {
|
|
124
124
|
id
|
|
125
125
|
protocolVersion
|
|
@@ -140,7 +140,7 @@ ${ld}`,Vg=`query V4Pool($chain: Chain!, $poolId: String!) {
|
|
|
140
140
|
__typename
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
|
-
${ld}`,tn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function As(r){return new Promise(e=>setTimeout(e,r))}async function td(r,e,t){let n;return Promise.race([r,new Promise(o=>{n=setTimeout(()=>o(t),e)})]).finally(()=>clearTimeout(n))}function Ga(r){if(!r)return 1;let e=r.toLowerCase();return tn[e]??1}function Ol(r){if(!r)return"ETHEREUM";let e=r.toLowerCase();return id[e]??"ETHEREUM"}var Wg=Object.fromEntries(Object.entries(tn).map(([r,e])=>[e,r]));function cd(r){if(typeof r!="number")return;let e=Wg[r];return e?id[e]:void 0}function Yg(r){if(typeof r!="string")return;let e=r.replace("PROTOCOL_VERSION_","").toUpperCase();return e==="V2"||e==="V3"||e==="V4"?e:void 0}function Gg(r){switch(r){case"volume1Day":return"POOLS_ORDER_BY_VOLUME_1D";case"volume30Day":return"POOLS_ORDER_BY_VOLUME_30D";case"apr":return"POOLS_ORDER_BY_APR";case"tvl":return"POOLS_ORDER_BY_TVL";default:return}}function nd(r){let e=r.pool,t=e?.poolId?.trim();if(!e||!t)return;let n=r.stats??{},o=Yg(e.protocolVersion),s=cd(e.chainId),a=Va(e.feeTier,e.protocolFee,o);return{id:t,chain:s,protocolVersion:o,feeTier:e.feeTier,isDynamicFee:e.isDynamicFee,totalLiquidity:nn(n.tvl),volume1Day:nn(n.volume1d),volume30Day:nn(n.volume30d),apr:z(n.apr),totalApr:z(n.totalApr),volumeToTvlRatio:typeof n.volume1dTvlRatio=="number"?n.volume1dTvlRatio:void 0,lpFeeShare:a,fee24hUsd:Wa(n.volume1d,e.feeTier,a),token0:sd(e.token0),token1:sd(e.token1)}}function nn(r){return typeof r=="number"&&Number.isFinite(r)?{value:r,currency:"USD"}:void 0}function Dl(r){if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r!="string"||r.trim()==="")return;let e=Number(r);return Number.isFinite(e)?e:void 0}function rd(r,e,t,n){if(!r&&!e&&!n)return;let o=Dl(t);return{...n,address:e??n?.address,symbol:r?.symbol??n?.symbol,name:r?.name??n?.name,decimals:r?.decimals??n?.decimals,logo:r?.logoUrl??n?.logo,price:nn(o)??n?.price,market:o!==void 0?{price:nn(o)}:n?.market,project:n?.project}}function od(r,e){let t=r.poolIdentifier,n=r.protocolVersion==="V4",o=r.hookAddress&&r.hookAddress!==qg?r.hookAddress:e?.hook?.address??void 0;return{id:e?.id,protocolVersion:r.protocolVersion??e?.protocolVersion,address:n?e?.address:t??e?.address,poolId:n?t??e?.poolId:e?.poolId,feeTier:r.feeTier??e?.feeTier,tickSpacing:r.tickSpacing??e?.tickSpacing,isDynamicFee:r.isDynamicFee??e?.isDynamicFee,hook:o?{address:o}:void 0,totalLiquidity:nn(r.tvlUsd)??e?.totalLiquidity,totalLiquidityPercentChange24h:nn(r.tvlUsdChange1d)??e?.totalLiquidityPercentChange24h,volume24h:nn(r.volumeUsd1d)??e?.volume24h,token0Supply:Dl(r.token0Supply)??e?.token0Supply,token1Supply:Dl(r.token1Supply)??e?.token1Supply,txCount:e?.txCount,historicalVolume:e?.historicalVolume,token0:rd(r.token0Metadata,r.token0Address,r.token0PriceUsd,e?.token0),token1:rd(r.token1Metadata,r.token1Address,r.token1PriceUsd,e?.token1),protocolFee:r.protocolFee,apr:z(r.apr),totalApr:z(r.totalApr),currentTick:r.currentTick,sqrtPriceX96:r.sqrtPriceX96,liquidity:r.liquidity}}function sd(r){if(r)return{chain:cd(r.chainId),address:r.address,symbol:r.symbol,name:r.name,decimals:r.decimals,standard:r.type?.replace("TOKEN_TYPE_",""),logo:r.project?.logoUrl,project:r.project?.logoUrl?{logo:{url:r.project.logoUrl}}:void 0}}function ad(r,e){switch(e){case"volume1Day":return r.volume1Day?.value??0;case"volume1Week":return r.volume1Week?.value??0;case"volume30Day":return r.volume30Day?.value??0;case"txCount":return r.txCount??0;case"apr":return r.apr??r.totalApr??0;default:return r.totalLiquidity?.value??0}}var Re=class{baseUrl;searchBaseUrl;liquidityBaseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Ig).replace(/\/$/,""),this.searchBaseUrl=(e?.searchBaseUrl??Og).replace(/\/$/,""),this.liquidityBaseUrl=(e?.liquidityBaseUrl??Fg).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=F(e)??e.toLowerCase();return Object.prototype.hasOwnProperty.call(tn,t)}listSupportedChains(){return Object.keys(tn).filter(e=>ze(e))}async listPools(e){let t=await this.listPoolsPage(e);return t.success?{success:!0,data:t.data?.pools??[]}:{success:!1,error:t.error}}async listPoolsPage(e){if(e.chainIds.length===0)return{success:!1,error:"At least one chain is required"};let t=`${this.searchBaseUrl}${Dg}`,n=JSON.stringify({chainIds:e.chainIds,sort:{orderBy:e.orderBy,ascending:e.ascending===!0},filter:{protocolVersions:e.protocolVersions.map(s=>`PROTOCOL_VERSION_${s}`),includeSpam:e.includeSpam===!0,applyTopLevelFilters:!0},page:{pageSize:Math.min(Math.max(Math.floor(e.pageSize),1),Ya),...e.pageToken?{pageToken:e.pageToken}:{}}}),o="Unknown error";for(let s=1;s<=mt;s++)try{let a=await x.post(t,n,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!a.ok)throw new Error(E(a));let i=a.data;return{success:!0,data:{pools:i.pools??[],nextPageToken:i.page?.nextPageToken||void 0}}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<mt&&await As(Ts)}return{success:!1,error:o}}async listAllPools(e){let t=[],n=new Set,o;for(let s=0;s<Mg;s++){let a=await this.listPoolsPage({...e,pageToken:o});if(!a.success||!a.data){if(s===0)return{success:!1,error:a.error||"Failed to fetch pools"};break}t.push(...a.data.pools);let i=a.data.nextPageToken;if(!i||a.data.pools.length===0||n.has(i))break;n.add(i),o=i}return{success:!0,data:t}}async getTopPools(e){let t=e?.protocolVersion??"V3",n=e?.limit&&e.limit>0?Math.floor(e.limit):10,o=e?.sortBy??"tvl",s=e?.multichain?Object.values(tn):[Ga(e?.chain)],a=Gg(o),i=a?Math.min(n,Ya):Ya,l=await this.listPools({chainIds:s,protocolVersions:[t],orderBy:a??"POOLS_ORDER_BY_TVL",pageSize:i});return!l.success||!l.data?{success:!1,error:l.error||"Failed to fetch pools"}:{success:!0,data:l.data.map(d=>nd(d)).filter(d=>d!==void 0).sort((d,p)=>ad(p,o)-ad(d,o)).slice(0,n)}}async getPool(e){let t=e.addressOrId?.trim();if(!t)return{success:!1,error:"Pool address or id is required"};let n=`${this.liquidityBaseUrl}${Bg}`,o=JSON.stringify({pool:{chainId:Ga(e.chain),addressOrId:t}}),s="Unknown error";for(let a=1;a<=mt;a++)try{let i=await x.post(n,o,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(i.status===404)return{success:!1,error:"Pool not found"};if(!i.ok)throw new Error(E(i));let l=i.data?.pool;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<mt&&await As(Ts)}return{success:!1,error:s}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:$g,variables:{chain:Ol(e.chain),address:t},pickField:"v3Pool"}):{success:!1,error:"Pool address is required"}}async getV2PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V2Pair",query:Hg,variables:{chain:Ol(e.chain),address:t},pickField:"v2Pair"}):{success:!1,error:"Pair address is required"}}async getV4PoolDetail(e){let t=e.poolId?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V4Pool",query:Vg,variables:{chain:Ol(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async getPoolDetailEnriched(e){let t=await this.getPool(e);if(!t.success||!t.data)return{success:!1,error:t.error||"Failed to fetch pool detail"};let n=t.data;if(e.enrich===!1)return{success:!0,data:od(n,void 0)};let o=n.protocolVersion,s=n.poolIdentifier??e.addressOrId.trim(),a=o==="V4"?this.getV4PoolDetail({poolId:s,chain:e.chain}):o==="V2"?this.getV2PoolDetail({address:s,chain:e.chain}):this.getV3PoolDetail({address:s,chain:e.chain}),i=await td(a.then(l=>l.success?l.data:void 0).catch(()=>{}),ed,void 0);return{success:!0,data:od(n,i)}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${Lg}`,n=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),o="Unknown error";for(let s=1;s<=mt;s++)try{let a=await x.post(t,n,{headers:{accept:"*/*","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web","_dd-custom-header-graph-ql-operation-name":e.operationName,"_dd-custom-header-graph-ql-operation-type":"query"}});if(!a.ok)throw new Error(E(a));let i=a.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let l=i.data?.[e.pickField]??void 0;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<mt&&await As(Ts)}return{success:!1,error:o}}async searchTokens(e){let t=e.query?.trim();return t?R(t)?{success:!1,error:"Address is invalid for token search. If you pasted a 0x address, it may be a Uniswap pool \u2014 try the pool search tool instead."}:this.fetchSearchTokens({query:t,chain:e.chain,page:e.page,size:e.size}):{success:!1,error:"Search query is required"}}async getTokenSafetyByAddress(e,t){let n=Array.from(new Set(e.filter(s=>typeof s=="string"&&R(s.trim())).map(s=>s.trim()))),o=new Map;return n.length===0||await td(Promise.all(n.map(async s=>{let a=await this.fetchSearchTokens({query:s,chain:t,size:5});if(!a.success)return;let i=s.toLowerCase(),l=(a.data??[]).find(c=>c.address?.toLowerCase()===i);l&&o.set(i,l)})).catch(()=>{}),ed,void 0),o}async fetchSearchTokens(e){let t=Ga(e.chain),n=e.page&&e.page>0?Math.floor(e.page):1,o=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,s=`${this.searchBaseUrl}${Zu}`,a=JSON.stringify({searchQuery:e.query,chainIds:[t],searchType:"TOKEN",page:n,size:o}),i="Unknown error";for(let l=1;l<=mt;l++)try{let c=await x.post(s,a,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!c.ok)throw new Error(E(c));return{success:!0,data:c.data.tokens??[]}}catch(c){i=c instanceof Error?c.message:"Unknown error",l<mt&&await As(Ts)}return{success:!1,error:i}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let n=Ga(e.chain),o=e.page&&e.page>0?Math.floor(e.page):1,s=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,a=e.protocolVersion??"V3",i=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=`${this.searchBaseUrl}${Zu}`,c=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"POOL",page:o,size:s}),[u,d]=await Promise.allSettled([this.fetchSearchPools(l,c),this.listPools({chainIds:[n],protocolVersions:a==="ALL"?["V2","V3","V4"]:[a],orderBy:"POOLS_ORDER_BY_TVL",pageSize:Ya})]);if(u.status==="rejected"||!u.value.success)return{success:!1,error:u.status==="rejected"?String(u.reason):u.value.error??"Failed to search pools"};let p=t.toLowerCase().split(/\s+/).filter(Boolean),m=u.value.data??[];a!=="ALL"&&(m=m.filter(y=>y.protocolVersion===a)),i!=null&&(m=m.filter(y=>y.feeTier===i));let g=new Map,h=new Map,f=new Map;for(let y of m)y.id&&g.set(y.id.toLowerCase(),y);if(d.status==="fulfilled"&&d.value.success&&d.value.data)for(let y of d.value.data){let w=nd(y);if(!w||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),v=(w.token1?.symbol??"").toLowerCase(),A=(w.token0?.name??"").toLowerCase(),S=(w.token1?.name??"").toLowerCase();if(!p.some($=>k.includes($)||v.includes($)||A.includes($)||S.includes($)))continue;let O=w.id.toLowerCase(),_=w.totalLiquidity?.value,H=w.volume1Day?.value,q=g.get(O);g.set(O,{...q??{id:w.id,protocolVersion:w.protocolVersion,feeTier:w.feeTier,token0:w.token0?{address:w.token0.address,symbol:w.token0.symbol,name:w.token0.name,decimals:w.token0.decimals}:void 0,token1:w.token1?{address:w.token1.address,symbol:w.token1.symbol,name:w.token1.name,decimals:w.token1.decimals}:void 0},..._!=null?{tvlUsd:_}:{},...H!=null?{volume1DayUsd:H}:{},...w.isDynamicFee===!0||en(w.feeTier)?{isDynamicFee:!0}:{}}),h.set(O,w.chain),f.set(O,w.apr)}let b=Array.from(g.entries()).sort(([,y],[,w])=>this.matchScore(w,p)-this.matchScore(y,p));for(let[y,w]of b){let k=z(f.get(y));k!=null&&(w.apr=k)}return{success:!0,data:b.map(([,y])=>y)}}async fetchSearchPools(e,t){let n="Unknown error";for(let o=1;o<=mt;o++)try{let s=await x.post(e,t,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!s.ok)throw new Error(E(s));return{success:!0,data:s.data.pools??[]}}catch(s){n=s instanceof Error?s.message:"Unknown error",o<mt&&await As(Ts)}return{success:!1,error:n}}matchScore(e,t){let n=[e.token0?.symbol??"",e.token1?.symbol??""].map(s=>s.toLowerCase()),o=0;for(let s of t){let a=0;for(let i of n)i===s?a=Math.max(a,3):i.startsWith(s)?a=Math.max(a,2):i.includes(s)&&(a=Math.max(a,1));o+=a}return o}};var ud=2n**96n;function fe(r,e=8){return!Number.isFinite(r)||r===0?r:Number(r.toPrecision(e))}function dd(r,e,t){let n=r*r,o=ud*ud,s=n*10n**18n/o;return Number(s)/1e18*Math.pow(10,e-t)}function Qe(r,e,t){return Math.pow(1.0001,r)*Math.pow(10,e-t)}function Ln(r,e,t){if(r<=0)throw new Error("priceToTick: price must be > 0");let n=r/Math.pow(10,e-t),o=Math.log(n)/Math.log(1.0001),s=Math.round(o);return Math.abs(o-s)<.001?s:Math.floor(o)}function no(r,e,t){let n={minPrice:r,maxPrice:e,inverted:!1};if(!Number.isFinite(r)||!Number.isFinite(e)||!Number.isFinite(t)||r<=0||e<=0||t<=0||r>=e)return n;let o={minPrice:1/e,maxPrice:1/r,inverted:!0},s=c=>t>=c.minPrice&&t<=c.maxPrice,a=s(n),i=s(o);if(a&&!i)return n;if(i&&!a)return o;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(o)<l(n)?o:n}function ht(r,e,t="nearest"){let n=Math.abs(r-Math.round(r))<1e-6?Math.round(r):r,o=(n%e+e)%e;if(o===0)return n;let s=n-o,a=s+e;return t==="down"?s:t==="up"?a:n-s<a-n?s:a}var rn=-887272,to=887272;function gt(r){return r<rn?rn:r>to?to:r}var Kg={"0x1":"https://gateway.thegraph.com/api/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV","0xa4b1":"https://gateway.thegraph.com/api/subgraphs/id/FbCGRftH4a3yZugY7TnbYgPJVEv2LvMT6oF1fxPe9aJM","0x89":"https://gateway.thegraph.com/api/subgraphs/id/3hCPRGf4z88VC5rsBKU5AA9FBBq5nF3jbKJG7VZCbhjm","0x38":"https://gateway.thegraph.com/api/subgraphs/id/GcKPSgHoY42xNYVAkSPDhXSzi6aJDRQSKqBSXezL47gV","0x2105":"https://gateway.thegraph.com/api/subgraphs/id/HMuAwufqZ1YCRmzL2SfHTVkzZovC9VL2UAKhjvRqKiR1","0xa":"https://gateway.thegraph.com/api/subgraphs/id/Cghf4LfVqPiFw6fp6Y5X5Ubc8UpmUhSfJL82zwiBFLaj","0xa86a":"https://gateway.thegraph.com/api/subgraphs/id/GVH9h9KZ9CqheUEL93qMbq7QwgoBu32QXQDPR6bev4Eo"},jg={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},zg={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},pd={"0x1":"0x1",1:"0x1",eth:"0x1",ethereum:"0x1",mainnet:"0x1","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","0x38":"0x38",56:"0x38",bnb:"0x38",bsc:"0x38","0x2105":"0x2105",8453:"0x2105",base:"0x2105","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a"},md={100:.01,500:.05,3e3:.3,1e4:1},Xg={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},Qg=300*1e3,ye=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...Kg,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([n])=>ze(n))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return pd[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),n=pd[t];return!!(n&&this.subgraphUrls[n])}chainName(e){let t=this.resolveChain(e);return jg[t]||t}numericChainId(e){return zg[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let n=this.resolveChain(e),o=this.subgraphUrls[n];if(!o)throw new Error(`No subgraph available for chain: ${e}`);let s=await x.post(o,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!s.ok)throw new Error(`Subgraph query failed: ${E(s)}`);let a=s.data;if(a.errors&&a.errors.length>0)throw new Error(`Subgraph error: ${a.errors[0].message||"Unknown"}`);return a.data}poolFragment(){return`
|
|
143
|
+
${Ld}`,un={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function Ds(o){return new Promise(e=>setTimeout(e,o))}async function Sd(o,e,t){let n;return Promise.race([o,new Promise(r=>{n=setTimeout(()=>r(t),e)})]).finally(()=>clearTimeout(n))}function ii(o){if(!o)return 1;let e=o.toLowerCase();return un[e]??1}function Zl(o){if(!o)return"ETHEREUM";let e=o.toLowerCase();return Nd[e]??"ETHEREUM"}var Sg=Object.fromEntries(Object.entries(un).map(([o,e])=>[e,o]));function Id(o){if(typeof o!="number")return;let e=Sg[o];return e?Nd[e]:void 0}function xg(o){if(typeof o!="string")return;let e=o.replace("PROTOCOL_VERSION_","").toUpperCase();return e==="V2"||e==="V3"||e==="V4"?e:void 0}function Cg(o){switch(o){case"volume1Day":return"POOLS_ORDER_BY_VOLUME_1D";case"volume30Day":return"POOLS_ORDER_BY_VOLUME_30D";case"apr":return"POOLS_ORDER_BY_APR";case"tvl":return"POOLS_ORDER_BY_TVL";default:return}}function xd(o){let e=o.pool,t=e?.poolId?.trim();if(!e||!t)return;let n=o.stats??{},r=xg(e.protocolVersion),s=Id(e.chainId),a=ri(e.feeTier,e.protocolFee,r);return{id:t,chain:s,protocolVersion:r,feeTier:e.feeTier,isDynamicFee:e.isDynamicFee,totalLiquidity:dn(n.tvl),volume1Day:dn(n.volume1d),volume30Day:dn(n.volume30d),apr:W(n.apr),totalApr:W(n.totalApr),volumeToTvlRatio:typeof n.volume1dTvlRatio=="number"?n.volume1dTvlRatio:void 0,lpFeeShare:a,fee24hUsd:si(n.volume1d,e.feeTier,a),token0:Ed(e.token0),token1:Ed(e.token1)}}function dn(o){return typeof o=="number"&&Number.isFinite(o)?{value:o,currency:"USD"}:void 0}function ec(o){if(typeof o=="number")return Number.isFinite(o)?o:void 0;if(typeof o!="string"||o.trim()==="")return;let e=Number(o);return Number.isFinite(e)?e:void 0}function Cd(o,e,t,n){if(!o&&!e&&!n)return;let r=ec(t);return{...n,address:e??n?.address,symbol:o?.symbol??n?.symbol,name:o?.name??n?.name,decimals:o?.decimals??n?.decimals,logo:o?.logoUrl??n?.logo,price:dn(r)??n?.price,market:r!==void 0?{price:dn(r)}:n?.market,project:n?.project}}function Rd(o,e){let t=o.poolIdentifier,n=o.protocolVersion==="V4",r=o.hookAddress&&o.hookAddress!==vg?o.hookAddress:e?.hook?.address??void 0;return{id:e?.id,protocolVersion:o.protocolVersion??e?.protocolVersion,address:n?e?.address:t??e?.address,poolId:n?t??e?.poolId:e?.poolId,feeTier:o.feeTier??e?.feeTier,tickSpacing:o.tickSpacing??e?.tickSpacing,isDynamicFee:o.isDynamicFee??e?.isDynamicFee,hook:r?{address:r}:void 0,totalLiquidity:dn(o.tvlUsd)??e?.totalLiquidity,totalLiquidityPercentChange24h:dn(o.tvlUsdChange1d)??e?.totalLiquidityPercentChange24h,volume24h:dn(o.volumeUsd1d)??e?.volume24h,token0Supply:ec(o.token0Supply)??e?.token0Supply,token1Supply:ec(o.token1Supply)??e?.token1Supply,txCount:e?.txCount,historicalVolume:e?.historicalVolume,token0:Cd(o.token0Metadata,o.token0Address,o.token0PriceUsd,e?.token0),token1:Cd(o.token1Metadata,o.token1Address,o.token1PriceUsd,e?.token1),protocolFee:o.protocolFee,apr:W(o.apr),totalApr:W(o.totalApr),currentTick:o.currentTick,sqrtPriceX96:o.sqrtPriceX96,liquidity:o.liquidity}}function Ed(o){if(o)return{chain:Id(o.chainId),address:o.address,symbol:o.symbol,name:o.name,decimals:o.decimals,standard:o.type?.replace("TOKEN_TYPE_",""),logo:o.project?.logoUrl,project:o.project?.logoUrl?{logo:{url:o.project.logoUrl}}:void 0}}function _d(o,e){switch(e){case"volume1Day":return o.volume1Day?.value??0;case"volume1Week":return o.volume1Week?.value??0;case"volume30Day":return o.volume30Day?.value??0;case"txCount":return o.txCount??0;case"apr":return o.apr??o.totalApr??0;default:return o.totalLiquidity?.value??0}}var Be=class{baseUrl;searchBaseUrl;liquidityBaseUrl;constructor(e){this.baseUrl=(e?.baseUrl??hg).replace(/\/$/,""),this.searchBaseUrl=(e?.searchBaseUrl??gg).replace(/\/$/,""),this.liquidityBaseUrl=(e?.liquidityBaseUrl??wg).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=M(e)??e.toLowerCase();return Object.prototype.hasOwnProperty.call(un,t)}listSupportedChains(){return Object.keys(un).filter(e=>Me(e))}async listPools(e){let t=await this.listPoolsPage(e);return t.success?{success:!0,data:t.data?.pools??[]}:{success:!1,error:t.error}}async listPoolsPage(e){if(e.chainIds.length===0)return{success:!1,error:"At least one chain is required"};let t=`${this.searchBaseUrl}${yg}`,n=JSON.stringify({chainIds:e.chainIds,sort:{orderBy:e.orderBy,ascending:e.ascending===!0},filter:{protocolVersions:e.protocolVersions.map(s=>`PROTOCOL_VERSION_${s}`),includeSpam:e.includeSpam===!0,applyTopLevelFilters:!0},page:{pageSize:Math.min(Math.max(Math.floor(e.pageSize),1),ai),...e.pageToken?{pageToken:e.pageToken}:{}}}),r="Unknown error";for(let s=1;s<=Tt;s++)try{let a=await x.post(t,n,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!a.ok)throw new Error(_(a));let i=a.data;return{success:!0,data:{pools:i.pools??[],nextPageToken:i.page?.nextPageToken||void 0}}}catch(a){r=a instanceof Error?a.message:"Unknown error",s<Tt&&await Ds(Us)}return{success:!1,error:r}}async listAllPools(e){let t=[],n=new Set,r;for(let s=0;s<bg;s++){let a=await this.listPoolsPage({...e,pageToken:r});if(!a.success||!a.data){if(s===0)return{success:!1,error:a.error||"Failed to fetch pools"};break}t.push(...a.data.pools);let i=a.data.nextPageToken;if(!i||a.data.pools.length===0||n.has(i))break;n.add(i),r=i}return{success:!0,data:t}}async getTopPools(e){let t=e?.protocolVersion??"V3",n=e?.limit&&e.limit>0?Math.floor(e.limit):10,r=e?.sortBy??"tvl",s=e?.multichain?Object.values(un):[ii(e?.chain)],a=Cg(r),i=a?Math.min(n,ai):ai,l=await this.listPools({chainIds:s,protocolVersions:[t],orderBy:a??"POOLS_ORDER_BY_TVL",pageSize:i});return!l.success||!l.data?{success:!1,error:l.error||"Failed to fetch pools"}:{success:!0,data:l.data.map(u=>xd(u)).filter(u=>u!==void 0).sort((u,p)=>_d(p,r)-_d(u,r)).slice(0,n)}}async getPool(e){let t=e.addressOrId?.trim();if(!t)return{success:!1,error:"Pool address or id is required"};let n=`${this.liquidityBaseUrl}${kg}`,r=JSON.stringify({pool:{chainId:ii(e.chain),addressOrId:t}}),s="Unknown error";for(let a=1;a<=Tt;a++)try{let i=await x.post(n,r,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(i.status===404)return{success:!1,error:"Pool not found"};if(!i.ok)throw new Error(_(i));let l=i.data?.pool;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<Tt&&await Ds(Us)}return{success:!1,error:s}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:Tg,variables:{chain:Zl(e.chain),address:t},pickField:"v3Pool"}):{success:!1,error:"Pool address is required"}}async getV2PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V2Pair",query:Ag,variables:{chain:Zl(e.chain),address:t},pickField:"v2Pair"}):{success:!1,error:"Pair address is required"}}async getV4PoolDetail(e){let t=e.poolId?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V4Pool",query:Pg,variables:{chain:Zl(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async getPoolDetailEnriched(e){let t=await this.getPool(e);if(!t.success||!t.data)return{success:!1,error:t.error||"Failed to fetch pool detail"};let n=t.data;if(e.enrich===!1)return{success:!0,data:Rd(n,void 0)};let r=n.protocolVersion,s=n.poolIdentifier??e.addressOrId.trim(),a=r==="V4"?this.getV4PoolDetail({poolId:s,chain:e.chain}):r==="V2"?this.getV2PoolDetail({address:s,chain:e.chain}):this.getV3PoolDetail({address:s,chain:e.chain}),i=await Sd(a.then(l=>l.success?l.data:void 0).catch(()=>{}),Pd,void 0);return{success:!0,data:Rd(n,i)}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${fg}`,n=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),r="Unknown error";for(let s=1;s<=Tt;s++)try{let a=await x.post(t,n,{headers:{accept:"*/*","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web","_dd-custom-header-graph-ql-operation-name":e.operationName,"_dd-custom-header-graph-ql-operation-type":"query"}});if(!a.ok)throw new Error(_(a));let i=a.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let l=i.data?.[e.pickField]??void 0;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(a){r=a instanceof Error?a.message:"Unknown error",s<Tt&&await Ds(Us)}return{success:!1,error:r}}async searchTokens(e){let t=e.query?.trim();return t?E(t)?{success:!1,error:"Address is invalid for token search. If you pasted a 0x address, it may be a Uniswap pool \u2014 try the pool search tool instead."}:this.fetchSearchTokens({query:t,chain:e.chain,page:e.page,size:e.size}):{success:!1,error:"Search query is required"}}async getTokenSafetyByAddress(e,t){let n=Array.from(new Set(e.filter(s=>typeof s=="string"&&E(s.trim())).map(s=>s.trim()))),r=new Map;return n.length===0||await Sd(Promise.all(n.map(async s=>{let a=await this.fetchSearchTokens({query:s,chain:t,size:5});if(!a.success)return;let i=s.toLowerCase(),l=(a.data??[]).find(c=>c.address?.toLowerCase()===i);l&&r.set(i,l)})).catch(()=>{}),Pd,void 0),r}async fetchSearchTokens(e){let t=ii(e.chain),n=e.page&&e.page>0?Math.floor(e.page):1,r=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,s=`${this.searchBaseUrl}${Ad}`,a=JSON.stringify({searchQuery:e.query,chainIds:[t],searchType:"TOKEN",page:n,size:r}),i="Unknown error";for(let l=1;l<=Tt;l++)try{let c=await x.post(s,a,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!c.ok)throw new Error(_(c));return{success:!0,data:c.data.tokens??[]}}catch(c){i=c instanceof Error?c.message:"Unknown error",l<Tt&&await Ds(Us)}return{success:!1,error:i}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let n=ii(e.chain),r=e.page&&e.page>0?Math.floor(e.page):1,s=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,a=e.protocolVersion??"V3",i=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=`${this.searchBaseUrl}${Ad}`,c=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"POOL",page:r,size:s}),[d,u]=await Promise.allSettled([this.fetchSearchPools(l,c),this.listPools({chainIds:[n],protocolVersions:a==="ALL"?["V2","V3","V4"]:[a],orderBy:"POOLS_ORDER_BY_TVL",pageSize:ai})]);if(d.status==="rejected"||!d.value.success)return{success:!1,error:d.status==="rejected"?String(d.reason):d.value.error??"Failed to search pools"};let p=t.toLowerCase().split(/\s+/).filter(Boolean),m=d.value.data??[];a!=="ALL"&&(m=m.filter(y=>y.protocolVersion===a)),i!=null&&(m=m.filter(y=>y.feeTier===i));let f=new Map,h=new Map,g=new Map;for(let y of m)y.id&&f.set(y.id.toLowerCase(),y);if(u.status==="fulfilled"&&u.value.success&&u.value.data)for(let y of u.value.data){let w=xd(y);if(!w||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),v=(w.token1?.symbol??"").toLowerCase(),A=(w.token0?.name??"").toLowerCase(),S=(w.token1?.name??"").toLowerCase();if(!p.some(O=>k.includes(O)||v.includes(O)||A.includes(O)||S.includes(O)))continue;let F=w.id.toLowerCase(),R=w.totalLiquidity?.value,me=w.volume1Day?.value,H=f.get(F);f.set(F,{...H??{id:w.id,protocolVersion:w.protocolVersion,feeTier:w.feeTier,token0:w.token0?{address:w.token0.address,symbol:w.token0.symbol,name:w.token0.name,decimals:w.token0.decimals}:void 0,token1:w.token1?{address:w.token1.address,symbol:w.token1.symbol,name:w.token1.name,decimals:w.token1.decimals}:void 0},...R!=null?{tvlUsd:R}:{},...me!=null?{volume1DayUsd:me}:{},...w.isDynamicFee===!0||cn(w.feeTier)?{isDynamicFee:!0}:{}}),h.set(F,w.chain),g.set(F,w.apr)}let b=Array.from(f.entries()).sort(([,y],[,w])=>this.matchScore(w,p)-this.matchScore(y,p));for(let[y,w]of b){let k=W(g.get(y));k!=null&&(w.apr=k)}return{success:!0,data:b.map(([,y])=>y)}}async fetchSearchPools(e,t){let n="Unknown error";for(let r=1;r<=Tt;r++)try{let s=await x.post(e,t,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!s.ok)throw new Error(_(s));return{success:!0,data:s.data.pools??[]}}catch(s){n=s instanceof Error?s.message:"Unknown error",r<Tt&&await Ds(Us)}return{success:!1,error:n}}matchScore(e,t){let n=[e.token0?.symbol??"",e.token1?.symbol??""].map(s=>s.toLowerCase()),r=0;for(let s of t){let a=0;for(let i of n)i===s?a=Math.max(a,3):i.startsWith(s)?a=Math.max(a,2):i.includes(s)&&(a=Math.max(a,1));r+=a}return r}};var Ud=2n**96n;function Pe(o,e=8){return!Number.isFinite(o)||o===0?o:Number(o.toPrecision(e))}function Dd(o,e,t){let n=o*o,r=Ud*Ud,s=n*10n**18n/r;return Number(s)/1e18*Math.pow(10,e-t)}function lt(o,e,t){return Math.pow(1.0001,o)*Math.pow(10,e-t)}function Wn(o,e,t){if(o<=0)throw new Error("priceToTick: price must be > 0");let n=o/Math.pow(10,e-t),r=Math.log(n)/Math.log(1.0001),s=Math.round(r);return Math.abs(r-s)<.001?s:Math.floor(r)}function hr(o,e,t){let n={minPrice:o,maxPrice:e,inverted:!1};if(!Number.isFinite(o)||!Number.isFinite(e)||!Number.isFinite(t)||o<=0||e<=0||t<=0||o>=e)return n;let r={minPrice:1/e,maxPrice:1/o,inverted:!0},s=c=>t>=c.minPrice&&t<=c.maxPrice,a=s(n),i=s(r);if(a&&!i)return n;if(i&&!a)return r;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(r)<l(n)?r:n}function At(o,e,t="nearest"){let n=Math.abs(o-Math.round(o))<1e-6?Math.round(o):o,r=(n%e+e)%e;if(r===0)return n;let s=n-r,a=s+e;return t==="down"?s:t==="up"?a:n-s<a-n?s:a}var pn=-887272,mr=887272;function Pt(o){return o<pn?pn:o>mr?mr:o}var Rg={"0x1":"https://gateway.thegraph.com/api/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV","0xa4b1":"https://gateway.thegraph.com/api/subgraphs/id/FbCGRftH4a3yZugY7TnbYgPJVEv2LvMT6oF1fxPe9aJM","0x89":"https://gateway.thegraph.com/api/subgraphs/id/3hCPRGf4z88VC5rsBKU5AA9FBBq5nF3jbKJG7VZCbhjm","0x38":"https://gateway.thegraph.com/api/subgraphs/id/GcKPSgHoY42xNYVAkSPDhXSzi6aJDRQSKqBSXezL47gV","0x2105":"https://gateway.thegraph.com/api/subgraphs/id/HMuAwufqZ1YCRmzL2SfHTVkzZovC9VL2UAKhjvRqKiR1","0xa":"https://gateway.thegraph.com/api/subgraphs/id/Cghf4LfVqPiFw6fp6Y5X5Ubc8UpmUhSfJL82zwiBFLaj","0xa86a":"https://gateway.thegraph.com/api/subgraphs/id/GVH9h9KZ9CqheUEL93qMbq7QwgoBu32QXQDPR6bev4Eo"},Eg={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},_g={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},Od={"0x1":"0x1",1:"0x1",eth:"0x1",ethereum:"0x1",mainnet:"0x1","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","0x38":"0x38",56:"0x38",bnb:"0x38",bsc:"0x38","0x2105":"0x2105",8453:"0x2105",base:"0x2105","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a"},Md={100:.01,500:.05,3e3:.3,1e4:1},Ng={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},Lg=300*1e3,Se=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...Rg,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([n])=>Me(n))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return Od[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),n=Od[t];return!!(n&&this.subgraphUrls[n])}chainName(e){let t=this.resolveChain(e);return Eg[t]||t}numericChainId(e){return _g[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let n=this.resolveChain(e),r=this.subgraphUrls[n];if(!r)throw new Error(`No subgraph available for chain: ${e}`);let s=await x.post(r,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!s.ok)throw new Error(`Subgraph query failed: ${_(s)}`);let a=s.data;if(a.errors&&a.errors.length>0)throw new Error(`Subgraph error: ${a.errors[0].message||"Unknown"}`);return a.data}poolFragment(){return`
|
|
144
144
|
id
|
|
145
145
|
token0 { id symbol name }
|
|
146
146
|
token1 { id symbol name }
|
|
@@ -157,16 +157,16 @@ ${ld}`,tn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
|
|
|
157
157
|
volumeToken0
|
|
158
158
|
volumeToken1
|
|
159
159
|
}
|
|
160
|
-
`}hasValidVolume(e){let t=e.poolDayData?.[0];return t?parseFloat(t.volumeToken0||"0")!==0&&parseFloat(t.volumeToken1||"0")!==0&&parseFloat(t.volumeUSD||"0")!==0:!1}sanitize(e){return!isFinite(e)||isNaN(e)||e>1e11?0:e}mapPool(e,t){let n=e,
|
|
160
|
+
`}hasValidVolume(e){let t=e.poolDayData?.[0];return t?parseFloat(t.volumeToken0||"0")!==0&&parseFloat(t.volumeToken1||"0")!==0&&parseFloat(t.volumeUSD||"0")!==0:!1}sanitize(e){return!isFinite(e)||isNaN(e)||e>1e11?0:e}mapPool(e,t){let n=e,r=Number(n.feeTier||0),s=Md[r]??r/1e4,a=this.sanitize(parseFloat(n.totalValueLockedUSD||"0")),i=n.poolDayData?.[0],l=parseFloat(i?.volumeUSD||"0"),c=parseFloat(i?.feesUSD||"0"),d=null;return a>0&&c>0&&(d=parseFloat((c*365*100/a).toFixed(2))),{poolAddress:n.id,pair:`${n.token0.symbol}/${n.token1.symbol}`,token0:{symbol:n.token0.symbol,address:n.token0.id,name:n.token0.name},token1:{symbol:n.token1.symbol,address:n.token1.id,name:n.token1.name},tvl:a,volume24hUsd:l,fees24hUsd:c,apr:d,feeTierBps:r,feeTierPercent:s,liquidity:n.liquidity||"0",chain:this.chainName(t)}}async fetchDefiLlamaUniswap(){let e=Date.now();if(this.llamaCache&&e-this.llamaCacheAt<Lg)return this.llamaCache;try{let t=await x.get("https://yields.llama.fi/pools");if(!t.ok)throw new Error(`DefiLlama: ${_(t)}`);let r=(t.data.data||[]).filter(s=>s.project==="uniswap-v3");return this.llamaCache=r,this.llamaCacheAt=e,r}catch{return this.llamaCache??[]}}parseLlamaFeeTier(e){if(!e)return null;let t=e.match(/^([\d.]+)%/);return t?Math.round(parseFloat(t[1])*1e4):null}enrichWithLlama(e,t){return t.length?e.map(n=>{let r=this.resolveChain(n.chain),s=n.feeTierBps,a=n.token0.address.toLowerCase(),i=n.token1.address.toLowerCase(),l=t.filter(p=>Ng[p.chain.toLowerCase()]===r),c=l.find(p=>{if(!p.underlyingTokens||p.underlyingTokens.length<2)return!1;let m=p.underlyingTokens.map(h=>h.toLowerCase());if(!(m.includes(a)&&m.includes(i)))return!1;let f=this.parseLlamaFeeTier(p.poolMeta);return f===null||f===s});if(!c){let p=n.token0.symbol.toUpperCase(),m=n.token1.symbol.toUpperCase(),f=[p,m].sort().join("-");c=l.find(h=>{if([...h.symbol.split("-").map(y=>y.toUpperCase())].sort().join("-")!==f)return!1;let b=this.parseLlamaFeeTier(h.poolMeta);return b===null||b===s})}if(!c)return n;let d=c.apyBase??c.apy??null,u={...n};return W(d)!=null&&(u.apr=parseFloat(d.toFixed(2))),c.tvlUsd!=null&&(u.tvl=this.sanitize(c.tvlUsd)),c.volumeUsd1d!=null&&(u.volume24hUsd=this.sanitize(c.volumeUsd1d)),u}):e}async searchPools(e){let{tokens:t,chain:n,sortBy:r,filters:s}=e,a=this.resolveChain(n),i=t.map(h=>{let g=h.toUpperCase(),b=new Set([g]);return g.startsWith("W")||b.add("W"+g),g.startsWith("W")&&g.length>1&&b.add(g.slice(1)),[...b]}),l=['totalValueLockedUSD_gt: "10000"','liquidity_gt: "0"','volumeUSD_gt: "0"'];s?.feeTier&&l.push(`feeTier: "${s.feeTier}"`);let c="totalValueLockedUSD";r==="volume"?c="volumeUSD":r==="fee"?c="feeTier":r==="liquidity"&&(c="liquidity");let d=r==="fee"?"asc":"desc",u=h=>h.length===1?`symbol: "${h[0]}"`:`symbol_in: [${h.map(g=>`"${g}"`).join(", ")}]`,p=(h,g)=>`{
|
|
161
161
|
pools(
|
|
162
|
-
first: ${
|
|
162
|
+
first: ${g}
|
|
163
163
|
orderBy: ${c}
|
|
164
|
-
orderDirection: ${
|
|
164
|
+
orderDirection: ${d}
|
|
165
165
|
where: { ${[...l,...h].join(", ")} }
|
|
166
166
|
) {
|
|
167
167
|
${this.poolFragment()}
|
|
168
168
|
}
|
|
169
|
-
}`,m;if(i.length>0){let
|
|
169
|
+
}`,m;if(i.length>0){let g,b;i.length>=2?(g=p([`token0_: { ${u(i[0])} }`,`token1_: { ${u(i[1])} }`],100),b=p([`token0_: { ${u(i[1])} }`,`token1_: { ${u(i[0])} }`],100)):(g=p([`token0_: { ${u(i[0])} }`],100),b=p([`token1_: { ${u(i[0])} }`],100));let[y,w]=await Promise.allSettled([this.querySubgraph(a,g),this.querySubgraph(a,b)]),k=y.status==="fulfilled"?(y.value?.pools||[]).filter(S=>this.hasValidVolume(S)).map(S=>this.mapPool(S,a)):[],v=w.status==="fulfilled"?(w.value?.pools||[]).filter(S=>this.hasValidVolume(S)).map(S=>this.mapPool(S,a)):[],A=new Set(k.map(S=>S.poolAddress));m=[...k,...v.filter(S=>!A.has(S.poolAddress))]}else m=((await this.querySubgraph(a,p([],100)))?.pools||[]).filter(g=>this.hasValidVolume(g)).map(g=>this.mapPool(g,a));let f=await this.fetchDefiLlamaUniswap();return f.length>0&&(m=this.enrichWithLlama(m,f)),s?.minTVL!=null&&(m=m.filter(h=>h.tvl>=s.minTVL)),s?.maxTVL!=null&&(m=m.filter(h=>h.tvl<=s.maxTVL)),s?.minAPR!=null&&(m=m.filter(h=>h.apr!=null&&h.apr>=s.minAPR)),s?.maxAPR!=null&&(m=m.filter(h=>h.apr!=null&&h.apr<=s.maxAPR)),r==="apr"?m.sort((h,g)=>(g.apr??0)-(h.apr??0)):r==="liquidity"&&m.sort((h,g)=>{let b=BigInt(g.liquidity||"0")-BigInt(h.liquidity||"0");return b>0n?1:b<0n?-1:0}),m}async getTrendingPools(e){let t=this.resolveChain(e.chain),n=`{
|
|
170
170
|
pools(
|
|
171
171
|
first: 100
|
|
172
172
|
orderBy: volumeUSD
|
|
@@ -179,13 +179,13 @@ ${ld}`,tn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
|
|
|
179
179
|
pool(id: "${e.poolAddress.toLowerCase()}") {
|
|
180
180
|
${this.poolFragment()}
|
|
181
181
|
}
|
|
182
|
-
}`,
|
|
182
|
+
}`,r=await this.querySubgraph(t,n);if(!r?.pool)return null;let s=this.mapPool(r.pool,t),a=await this.fetchDefiLlamaUniswap();return a.length>0&&(s=this.enrichWithLlama([s],a)[0]),s}async getPoolByPositionId(e){let t=this.resolveChain(e.chain),n=`{
|
|
183
183
|
position(id: "${e.positionId}") {
|
|
184
184
|
pool {
|
|
185
185
|
${this.poolFragment()}
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
|
-
}`,
|
|
188
|
+
}`,r=await this.querySubgraph(t,n);if(!r?.position?.pool)return null;let s=this.mapPool(r.position.pool,t),a=await this.fetchDefiLlamaUniswap();return a.length>0&&(s=this.enrichWithLlama([s],a)[0]),s}async getPositionDetail(e){let t=this.resolveChain(e.chain),n=`{
|
|
189
189
|
position(id: "${e.positionId}") {
|
|
190
190
|
id
|
|
191
191
|
liquidity
|
|
@@ -199,30 +199,30 @@ ${ld}`,tn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
|
|
|
199
199
|
${this.poolFragment()}
|
|
200
200
|
}
|
|
201
201
|
}
|
|
202
|
-
}`,o=await this.querySubgraph(t,n);if(!o?.position?.pool)return null;let s=o.position,a=this.mapPool(s.pool,t),i=await this.fetchDefiLlamaUniswap(),l=i.length>0?this.enrichWithLlama([a],i)[0]:a,c=l.feeTierBps,u=l.feeTierPercent;return{position:{positionId:s.id,poolAddress:l.poolAddress,pair:l.pair,token0:{symbol:l.token0.symbol,address:l.token0.address},token1:{symbol:l.token1.symbol,address:l.token1.address},feeTierBps:c,feeTierPercent:u,chain:l.chain,liquidity:s.liquidity,depositedToken0:s.depositedToken0,depositedToken1:s.depositedToken1,withdrawnToken0:s.withdrawnToken0,withdrawnToken1:s.withdrawnToken1,collectedFeesToken0:s.collectedFeesToken0,collectedFeesToken1:s.collectedFeesToken1},pool:l}}async getCoinPoolPairs(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let o=(await this.fetchCoinPoolV2Items(t)).map(s=>this.mapCoinPoolV2Item(s)).filter(s=>s!==null);if(e.tokens&&e.tokens.length>=2){let s=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase();o=o.filter(i=>{let[l="",c=""]=i.pair.toUpperCase().split("/");return l.includes(s)&&c.includes(a)||l.includes(a)&&c.includes(s)})}return o}async getCoinPoolByAddress(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(s=>s.poolId?.toLowerCase()===n).map(s=>this.mapCoinPoolV2Item(s)).filter(s=>s!==null).sort((s,a)=>(a.apr??-1/0)-(s.apr??-1/0))}async fetchCoinPoolV2Items(e){if(!this.coinPoolBaseUrl)return[];try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(E(n));return n.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,o=A=>A==null||!Number.isFinite(A)?0:Math.pow(1.0001,A)*Math.pow(10,t-n),s=o(e.minTick),a=o(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?s:a>0?1/a:0,p=u?a:s>0?1/s:0,m=u?c:c>0?1/c:0,g=u?e.token0.symbol:e.token1.symbol,h=u?e.token1.symbol:e.token0.symbol;if(!m||!d&&!p)return null;let f=Math.min(d,p),b=Math.max(d,p);if(m<f||m>b)return null;let y=Number(e.fee),w=md[y]??y/1e4,k=z(e.apr)??z(e.aprAvg)??null,v=z(e.aprAvg)??null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:v,token0Price:i,token1Price:l,priceRange:{minPrice:fe(d),maxPrice:fe(p),currentPrice:fe(m),baseToken:g,quoteToken:h}}}};var on=class{config;constructor(e){this.config=e}withRoute(e){let t=Object.create(this);return t.getQuote=n=>this.getQuote({route:e,...n}),t}};var ft=class{constructor(e,t=Number.POSITIVE_INFINITY){this.loader=e;this.ttlMs=t}loader;ttlMs;value=null;loadedAt=0;inFlight=null;async get(){return this.value!==null&&Date.now()-this.loadedAt<this.ttlMs?this.value:this.inFlight?this.inFlight:(this.inFlight=(async()=>{try{let e=await this.loader();return e!==null&&(this.value=e,this.loadedAt=Date.now()),e}catch{return this.value}finally{this.inFlight=null}})(),this.inFlight)}};var Jg="https://api.relay.link";function hd(r){return r===7565164||r==="7565164"?792703809:r}var ro=class extends on{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Jg,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c}=e,u=await sn.getAffiliateFee(this.getProviderName(),t,e.route),d={user:i||l,originChainId:hd(t),destinationChainId:hd(s),originCurrency:n,destinationCurrency:a,amount:o,recipient:i||l,tradeType:"EXACT_INPUT"};u&&(d.appFees=[{recipient:u.affiliateFeeRecipient,fee:Math.floor(u.affiliateFeePercent*100)}]),typeof c=="number"&&Number.isFinite(c)&&(d.slippageTolerance=Math.floor(c*100).toString());try{let p=await this.request("/quote/v2","POST",d);if(!p||p.error)return{success:!1,error:p?.error??"Unknown error",errorMessage:p?.message??"Failed to fetch quote from Relay"};let m=(p.steps??[]).filter(y=>y.id==="approve"),g=p.steps?.find(y=>y.id==="swap"||y.id==="deposit"),h=g?.items?.[0]?.data,f=Array.isArray(h?.instructions);return{success:!0,provider:"relay",tx:h?f?{data:{instructions:h.instructions??[],addressLookupTableAddresses:h.addressLookupTableAddresses??[]},chainId:h.chainId}:{from:h.from,to:h.to,data:h.data,value:h.value,chainId:h.chainId,gas:h.gas,maxFeePerGas:h.maxFeePerGas,maxPriorityFeePerGas:h.maxPriorityFeePerGas}:null,isCrossChain:t!==s,srcChainId:t,dstChainId:s,raw:{steps:p.steps,fees:p.fees,details:p.details,approveSteps:m,requestId:g?.requestId}}}catch(p){return{success:!1,error:p,errorMessage:p instanceof Error?p.message:"Failed to fetch quote"}}}async checkApproval(e){let t=e.quoteData?.raw,o=(t?.approveSteps??(t?.approveStep?[t.approveStep]:[])).map(s=>s.items?.[0]?.data).filter(s=>!!s?.to&&typeof s.data=="string").map(s=>({to:s.to,from:s.from,data:s.data,value:s.value??"0",chainId:s.chainId,gas:s.gas,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas}));return o.length>0?{isNeeded:!0,integrated:!0,approvals:o,approvalData:o[0],contractAddress:o[0].to,message:o.length>1?`${o.length} approval steps are included in the quote and run first, in order.`:"Approval step is included in quote and will be executed first."}:{isNeeded:!1,integrated:!0,approvals:[],message:"No approval needed or already approved"}}async trackTransaction(e){try{let n=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return n==="success"||n==="refunded"?{success:!0,status:"COMPLETED"}:n==="failure"||n==="expired"?{success:!0,status:"FAILED"}:{success:!0,status:"PENDING"}}catch(t){return{success:!1,status:"ERROR",error:t instanceof Error?t.message:String(t)}}}async request(e,t,n){let o={"Content-Type":"application/json"};this.apiKey&&(o["x-api-key"]=this.apiKey);let s=`${this.apiBaseUrl}${e}`,a;if(t==="GET"&&n){let l=Object.entries(n).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(u))}`).join("&");s=`${s}?${l}`}else t==="POST"&&n&&(a=n);let i=await x.request(t,s,a,{headers:o});if(!i.ok)throw new Error(E(i));return i.data}};var Zg="https://api.coinpool.app/config/addresses",ef="https://api.coinpool.app/config/bridgeProviderByChain",gd="createPoolProxyV3",tf="nftPositionUniswap",nf=/^0x[0-9a-fA-F]{40}$/,Ps=class{addresses;providerMap;constructor(e=Zg,t=ef){this.addresses=new ft(async()=>(await x.get(e,{headers:{Accept:"application/json"}})).data?.data??null),this.providerMap=new ft(async()=>(await x.get(t,{headers:{Accept:"application/json"}})).data?.data??null)}async getProviderByChain(e){let n=(await this.providerMap.get())?.[String(e)];return this.isProviderName(n)?n:null}async getGatewayAddress(e){return this.getAddress(gd,e)}async getPositionManagerAddress(e){return this.getAddress(tf,e)}async getGatewayChains(){return this.listChainsWithAddress(gd)}async getAddress(e,t){let n=await this.addresses.get();if(!n)return;let o=this.toDecimalChainKey(t);if(o)return this.firstAddress(n[e]?.[o])}async listChainsWithAddress(e){let t=(await this.addresses.get())?.[e];if(!t||typeof t!="object")return[];let n=[];for(let[o,s]of Object.entries(t)){let a=this.firstAddress(s);a&&nf.test(a)&&n.push(o)}return n}firstAddress(e){let t=Array.isArray(e)?e[0]:e;return typeof t=="string"?t.trim():void 0}toDecimalChainKey(e){let t=e.trim();if(/^0x[0-9a-fA-F]+$/.test(t)){let n=Number.parseInt(t,16);return Number.isFinite(n)?String(n):null}return/^\d+$/.test(t)?t:null}isProviderName(e){return e==="debridge"||e==="relay"}},an=new Ps;var oo=class{async resolve(e){try{return await this.resolveProvider(e)??xt}catch{return xt}}toNumericChainId(e){if(e==null)return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}},so=class extends oo{constructor(t=an){super();this.config=t}config;route="pool";async resolveProvider({srcChainId:t}){let n=this.toNumericChainId(t);return n===null?null:this.config.getProviderByChain(n)}},ao=class extends oo{constructor(t=sn){super();this.setting=t}setting;route="userSwap";async resolveProvider({srcChainId:t,dstChainId:n}){return this.setting.getBridgeProvider(t,n)}};var Ss=class{routers=new Map;constructor(e=[new so,new ao]){for(let t of e)this.routers.set(t.route,t)}async resolveProvider(e){return await this.routers.get(e.route)?.resolve(e)??xt}},Ka=new Ss;var xs=class{configOverride;routersOverride;cache=new Map;constructor(e,t){this.configOverride=e,this.routersOverride=t}get providers(){return this.configOverride??lo}get routers(){return this.routersOverride??Ka}async getService(e){let t=this.getServiceByProvider(await this.resolveProvider(e));return e.route?t.withRoute(e.route):t}getServiceByProvider(e){let t=this.cache.get(e);if(t)return t;let n=this.createService(e);return this.cache.set(e,n),n}resetCache(){this.cache.clear()}async resolveProvider(e){return this.routers.resolveProvider(e)}createService(e){let t=this.providers[e]??{};switch(e){case"debridge":return new co(t);case"relay":return new ro(t);default:{let n=e;throw new Error(`Unknown swap provider: ${String(n)}`)}}}},io=new xs;var lo={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},xt="relay";function ja(r,e){let t={...lo[r]??{},...e};for(let n of Object.keys(t))t[n]===void 0&&delete t[n];lo[r]=t,io.resetCache()}var rf="https://exchange-api.keyring.app/admin/setting?configs=others",of="https://api.relay.link/chains",sf="https://dln.debridge.finance/v1.0/supported-chains-info",af=14400*1e3,lf=300*1e3,cf=new Set([728126428,7565164]),fd={relay:"relay",debridge:"deBridge"},Cs=class{setting;chainSupport;constructor(e=rf){this.setting=new ft(async()=>(await x.get(e,{headers:{Accept:"application/json"}})).data?.others??null,lf),this.chainSupport=new ft(async()=>this.fetchChainSupport(),af)}async getBridgeProvider(e,t){let n=this.toChainKey(e),o=this.toChainKey(t??e),[s,a]=await Promise.all([this.setting.get(),this.chainSupport.get()]),i=this.normalizeProvider(s?.keyringV2?.bridgeProvider)??xt;if(!n||!o||!a)return i;let l=this.requireChainKeys(s?.keyringV2,"debridge"),c=l.includes(n)||l.includes(o),u=a.debridge.has(n)&&a.debridge.has(o);return c&&u?"debridge":i}async getAffiliateFee(e,t,n="userSwap"){let o=await this.setting.get();if(!o)return null;let s=n==="pool"?this.resolveLegacyFee(o,e,t):this.resolveKeyringV2Fee(o,e,t);return!s.recipient||s.percent<=0?null:{affiliateFeeRecipient:s.recipient,affiliateFeePercent:s.percent}}resolveLegacyFee(e,t,n){return t==="debridge"?{recipient:this.parseRecipientMap(e.affiliateRecipient)?.[String(n)],percent:this.toPercent(e.AFFILIATE_FEE_PERENT)}:{recipient:e.RELAY_AFFILIATE_FEE_RECIPIENT,percent:this.toPercent(e.RELAY_AFFILIATE_FEE_PERCENT)}}resolveKeyringV2Fee(e,t,n){let o=e.keyringV2;if(!o)return{recipient:void 0,percent:0};let s=o[fd[t]],a=String(n);return{percent:this.toPercent(s?.affiliateFeePercentCustom?.[a])||this.toPercent(s?.affiliateFeePercent),recipient:s?.affiliateRecipientCustom?.[a]||o.affiliateRecipientDefault}}parseRecipientMap(e){if(!e)return null;try{let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}async fetchChainSupport(){let[e,t]=await Promise.allSettled([x.get(of,{headers:{Accept:"application/json"}}),x.get(sf,{headers:{Accept:"application/json"}})]),n=new Set;if(e.status==="fulfilled")for(let s of e.value.data?.chains??[]){if(s?.vmType!=="evm")continue;let a=this.toChainKey(s.id);a&&n.add(a)}let o=new Set;if(t.status==="fulfilled")for(let s of t.value.data?.chains??[]){let a=s?.originalChainId??s?.chainId;if(a===void 0||cf.has(a))continue;let i=this.toChainKey(a);i&&o.add(i)}return{relay:n,debridge:o}}requireChainKeys(e,t){return(e?.[fd[t]]?.requireChain??[]).map(o=>this.toChainKey(o)).filter(o=>o!==null)}normalizeProvider(e){if(typeof e!="string")return null;let t=e.toLowerCase();return t==="relay"?"relay":t==="debridge"?"debridge":null}toChainKey(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?String(e):null;let t=e.trim();if(!t)return null;let n=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(n)?String(n):null}toPercent(e){if(e==null)return 0;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}},sn=new Cs;function za(r,e){return D({abi:V,functionName:"approve",args:[r,e]})}async function uf(r,e,t,n,o){try{return await we(r).call({account:t,to:e,data:za(n,o)}),!0}catch(s){return df(s)?!1:null}}function df(r){let e=r?.name??"";if(e==="ContractFunctionRevertedError"||e==="CallExecutionError")return!0;let t=r instanceof Error?r.message.toLowerCase():String(r??"").toLowerCase();return t.includes("revert")||t.includes("execution reverted")||t.includes("invalid opcode")||t.includes("out of gas")}async function Xa({chain:r,token:e,owner:t,spender:n,amount:o,allowance:s}){let a=l=>({to:e,from:t,data:za(n,l),value:"0"});return s!=null&&s>=o?[]:s===0n||!r?[a(o)]:await uf(r,e,t,n,o)===!1?[a(0n),a(o)]:[a(o)]}var pf="https://dln.debridge.finance/v1.0",mf="0x0000000000000000000000000000000000000000",hf=new Set([429,500]),gf=5,ff=1e3,yf=r=>new Promise(e=>setTimeout(e,r)),co=class extends on{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??pf,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:u}=e,d=u??t!==s,p=await sn.getAffiliateFee(this.getProviderName(),t,e.route);try{if(d){let h={srcChainId:String(t),srcChainTokenIn:n,srcChainTokenInAmount:o,dstChainId:String(s),dstChainTokenOut:a,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:l,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent);let f=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,h);return f.error||f.errorMessage?{success:!1,error:f.error??f.errorMessage,errorMessage:f.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:f.tx,estimation:f.estimation,isCrossChain:!0,srcChainId:t,dstChainId:s,raw:f}}let m={chainId:String(t),tokenIn:n,tokenInAmount:o,tokenOut:a,tokenOutRecipient:i,accesstoken:this.accessToken};p&&(m.affiliateFeeRecipient=p.affiliateFeeRecipient,m.affiliateFeePercent=p.affiliateFeePercent),c!==void 0&&(m.slippage=c);let g=await this.get(`${this.apiBaseUrl}/chain/transaction`,m);return g.error||g.errorMessage?{success:!1,error:g.error??g.errorMessage,errorMessage:g.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:g.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:g}}catch(m){return{success:!1,error:m,errorMessage:m instanceof Error?m.message:"Failed to fetch quote"}}}async checkApproval(e){let{chain:t,userAddress:n,tokenAddress:o,amount:s}=e,a=e.quoteData?.tx?.to;if(!a)return{isNeeded:!1,error:"No contract address found in quote"};if(!o||o.toLowerCase()===mf)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Native coin needs no approval."};let i;try{i=BigInt(s)}catch{i=0n}let l=await this.readAllowance(t,o,n,a);if(l!==null&&l>=i)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Sufficient allowance already granted."};let c=await Xa({chain:t,token:o,owner:n,spender:a,amount:i,allowance:l});return{isNeeded:!0,integrated:!1,approvals:c,approvalData:c[0],contractAddress:a,message:c.length>1?"Approval required: the standing allowance must be reset to 0 before the new one is granted.":l===null?"Could not read allowance; approval required before the swap.":"Approval required: current allowance is below the swap amount."}}async readAllowance(e,t,n,o){if(!e)return null;try{return await we(e).readContract({address:t,abi:V,functionName:"allowance",args:[n,o]})}catch{return null}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let n=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!n.orderIds?.length)return{success:!1,status:"PENDING"};let o=n.orderIds[0];switch(((await this.get(`${this.apiBaseUrl}/dln/order/${o}/status`,{accesstoken:this.accessToken})).status??"").toUpperCase()){case"FULFILLED":case"SENTUNLOCK":case"CLAIMEDUNLOCK":return{success:!0,status:"COMPLETED"};case"ORDERCANCELLED":case"SENTORDERCANCEL":case"CLAIMEDORDERCANCEL":return{success:!0,status:"FAILED"};default:return{success:!0,status:"PENDING"}}}catch(n){return{success:!1,status:"ERROR",error:n instanceof Error?n.message:String(n)}}}async get(e,t){let n=Object.entries(t).map(([a,i])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(i))}`).join("&"),o=n?`${e}?${n}`:e,s=await x.get(o,{headers:{Accept:"application/json"}});for(let a=0;a<gf&&hf.has(s.status);a++)await yf(ff),s=await x.get(o,{headers:{Accept:"application/json"}});return s.data}};function yd(r){let e=r.raw??{},t=e.tokenOut?.amount??e.tokenOut?.minAmount??e.details?.currencyOut?.amount??e.details?.currencyOut?.minimumAmount??e.estimation?.dstChainTokenOut?.recommendedAmount??e.estimation?.dstChainTokenOut?.amount;return t&&/^\d+$/.test(t)?t:void 0}function bd(r){if(r.errorMessage&&r.errorMessage.trim())return r.errorMessage.trim();let e=n=>{if(typeof n=="string"&&n.trim())return n.trim();if(n&&typeof n=="object"){let o=n;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},t=r.raw??{};return e(r.error)??e(t.errorMessage)??e(t.error)??"The swap could not be quoted right now."}var bf={1:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",10:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",56:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",137:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",143:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",1514:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",4326:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",4663:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",8453:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",42161:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",43114:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",59144:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",25:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",999:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",1776:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66"},wf=[{inputs:[],name:"globalFixedNativeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}];function wd(r){if(r==null)return null;if(typeof r=="number")return Number.isFinite(r)?String(r):null;let e=r.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)?String(t):null}async function Qa(r){let{provider:e,srcChainId:t}=r,n=wd(t),o=wd(r.dstChainId??t);if(!n||!o||n===o||e!=="debridge")return 0n;let s=bf[n];if(!s)return 0n;try{let a=await we(n).readContract({address:s,abi:wf,functionName:"globalFixedNativeFee"});return typeof a=="bigint"&&a>0n?a:0n}catch{return 0n}}var se="0x0000000000000000000000000000000000000000",kd={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:De["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:De["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:De["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:De["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:De["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:De["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:De["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:De["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function ue(r){return kd[r.toLowerCase()]}function uo(r){return ue(r)?.native}var vd="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function Ml(r){let e=r.stableTicks??3,t=r.widePercent??{down:50,up:100},n=Qe(r.currentTick,r.token0Decimals,r.token1Decimals),o=gt(ht(r.currentTick-e*r.tickSpacing,r.tickSpacing,"down")),s=gt(ht(r.currentTick+e*r.tickSpacing,r.tickSpacing,"up")),a=n*(1-t.down/100),i=n*(1+t.up/100),l=Ln(a,r.token0Decimals,r.token1Decimals),c=Ln(i,r.token0Decimals,r.token1Decimals),u=gt(ht(l,r.tickSpacing,"down")),d=gt(ht(c,r.tickSpacing,"up")),p=(m,g,h,f,b)=>{let y=Qe(f,r.token0Decimals,r.token1Decimals),w=Qe(b,r.token0Decimals,r.token1Decimals);return{id:m,label:g,description:h,tickLower:f,tickUpper:b,minPrice:y,maxPrice:w,minPercentChange:(y-n)/n*100,maxPercentChange:(w-n)/n*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",o,s),p("wide","Wide","Good for volatile pairs",u,d)]}var Se=class{swapFactory;constructor(e){this.swapFactory=e?.swapFactory??io}isSupported(e){if(!e)return!1;let t=F(e)??e.toLowerCase();return!!ue(t)}listSupportedChains(){return Object.keys(kd).filter(e=>ze(e))}getRpcUrl(e){let t=An(e);if(t)return t;let n=ue(e);if(!n)throw new Error(`Unsupported chain: ${e}`);return n.defaultRpc}async getGatewayAddress(e){return an.getGatewayAddress(e)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await an.getGatewayChains(),t=[];for(let n of e){let o=F(n);o&&ue(o)&&!t.includes(o)&&t.push(o)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return an.getPositionManagerAddress(e)}client(e){return we(e)}async ethCall(e,t,n){let{data:o}=await this.client(e).call({to:t,data:n});return o??"0x"}async getNativeBalance(e,t){return this.client(e).getBalance({address:t})}async getGasPrice(e){return this.client(e).getGasPrice()}async getTransactionReceipt(e,t){return this.client(e).rpc("eth_getTransactionReceipt",[t])}async extractMintedNftId(e,t){let n=await this.getPositionManagerAddress(e);if(!n)return null;let o=n.toLowerCase();for(let s of t.logs??[]){if((s.address??"").toLowerCase()!==o)continue;let a=s.topics??[];if(!(a.length<4||a[0]?.toLowerCase()!==vd||"0x"+a[1].slice(-40).toLowerCase()!==se))try{return BigInt(a[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=ue(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let n=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*n*18n/10n}async readPoolOnchain(e,t){let o={address:t,abi:pl},[s,a,i,l,c,u]=await this.client(e).multicall({contracts:[{...o,functionName:"slot0"},{...o,functionName:"liquidity"},{...o,functionName:"tickSpacing"},{...o,functionName:"fee"},{...o,functionName:"token0"},{...o,functionName:"token1"}],allowFailure:!1}),[d,p]=s,m=c.toLowerCase(),g=u.toLowerCase(),[h,f]=await Promise.all([this.readErc20Decimals(e,m),this.readErc20Decimals(e,g)]),b=dd(d,h,f);return{poolAddress:t,chainId:e,fee:l,tickSpacing:i,liquidity:a,sqrtPriceX96:d,currentTick:p,token0:m,token1:g,currentPrice:b}}async readErc20Decimals(e,t){return t.toLowerCase()===se?18:this.client(e).readContract({address:t,abi:V,functionName:"decimals"})}async getNativePriceUsd(e){let t=ue(e);if(!t)return null;try{let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,o=await x.get(n);if(!o.ok)return null;let a=o.data[t.native.coingeckoId]?.usd;return typeof a=="number"?a:null}catch{return null}}splitNativeAmountForRange(e){let{nativeAmountWei:t,pool:n,tickLower:o,tickUpper:s,token0Decimals:a,token1Decimals:i}=e,l=2**96,c=Number(n.sqrtPriceX96)/l,u=Math.pow(1.0001,o/2),d=Math.pow(1.0001,s/2);if(c<=u)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(c>=d)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let p=1/c-1/d,m=c-u,g=c*c,h=p*g,b=h+m;if(!Number.isFinite(b)||b<=0)throw new Error("splitNativeAmountForRange: invalid total value");let y=h/b,w=1-y,k=1000000000000000n,v=BigInt(Math.floor(y*Number(k))),A=t*v/k,S=t-A;return{ratio0:y,ratio1:w,amountInFor0Wei:A,amountInFor1Wei:S}}async fetchSwapLeg(e){let t=Number.parseInt(e.chainId,16);if(!Number.isFinite(t))throw new Error(`Invalid hex chain id: ${e.chainId}`);let o=await(await this.swapFactory.getService({route:"pool",srcChainId:t})).getQuote({srcChainId:t,srcTokenAddress:e.tokenIn,srcTokenAmount:e.tokenInAmount,dstChainId:t,dstTokenAddress:e.tokenOut,recipientAddress:e.tokenOutRecipient,senderAddress:e.senderAddress??e.tokenOutRecipient,slippage:e.slippage,isCrossChain:!1});if(!o.success||!o.tx)throw new Error(o.errorMessage??"Swap quote failed");let s=o.tx;if(!s.to||typeof s.data!="string")throw new Error("Swap quote returned an unsupported tx shape (non-EVM payload?)");let a=o.raw??{},i=a.tokenOut?.minAmount??a.details?.currencyOut?.minimumAmount??"0";return{to:s.to,data:s.data,value:s.value??"0",minAmountOut:i}}};var kf={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},vf=/^0x[a-fA-F0-9]{40}$/;function Tf(r,e){if(typeof r!="string"||typeof e!="string")return null;let t=kf[r.toLowerCase()];return!t||!vf.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function Je(r,e){let t=Tf(r,e);return t?{uniswapUrl:t}:{}}var Td=Object.keys(tn),$e="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a, Linea=0xe708, Gnosis=0x64, HyperEVM=0x3e7, Mantle=0x1388, Monad=0x8f. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";function Ee(){return Td.filter(r=>ze(r)).map(r=>T(r)).join(", ")}function He(){return{kind:"info",async listSupported(){return Td.filter(r=>ze(r))},async isSupported(r){if(!r)return!1;let e=F(r)??r.toLowerCase();return Object.prototype.hasOwnProperty.call(tn,e)}}}function po(r){return{kind:"add-liquidity",listSupported:()=>r.listAddLiquiditySupportedChains(),isSupported:e=>r.isAddLiquiditySupported(e)}}function Fl(r,e,t){let n=o=>typeof o=="string"&&o.trim()!=="";if(n(r))return F(r)??r.trim();if(n(e?.chain))return F(e.chain)??e.chain.trim();if(n(e?.walletAddress))throw new ie(typeof e?.query=="string"?e.query:void 0,t);return Fe}async function _e(r,e,t){let n=await r.listSupported(),o=Fl(e,t,n);return await r.isSupported(o)?{ok:!0,chain:o}:{ok:!1,result:Bl(o,n,r.kind)}}function Bl(r,e,t="info"){return{_instructions:`${t==="add-liquidity"?"Adding liquidity is NOT available on this network. Tell the user, in their language, that they cannot add liquidity / provide LP on this chain yet (note: viewing pool info may still work on other chains). Then name the chains where adding liquidity IS available":"Liquidity-pool data is NOT available on this network. Tell the user, in their language, that pools are not supported on this chain. Then name the chains where pools ARE available"} using EXACTLY and ONLY the entries in the \`supportedChains\` field below \u2014 copy them verbatim, add nothing. CRITICAL: this list is the complete, authoritative set. Do NOT add, infer, or invent ANY other chain \u2014 NOT EVEN a chain this app supports for wallet/token/DeFi features (for example Gnosis, HyperEVM, Mantle, and Monad are NOT pool chains; never list them unless they literally appear in \`supportedChains\`). Keep it short and friendly. Do NOT mention tools, services, APIs, forms, or any internals.`,unsupportedChain:T(r),supportedChains:e.map(o=>T(o))}}var Ja="{pair}";var ln=[{name:"add_button_label",type:"string",description:`Label template for the per-pool "Add liquidity" buttons that render under EVERY pool you show, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each pool automatically. Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:`A short "add liquidity" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a pool's button is clicked. ALWAYS provide it. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name or a pool address yourself \u2014 the pool address and the chain these pools are on are appended automatically as "(Pool: 0x\u2026 - <chain>)".`,required:!1}],Ze=' A clickable "Add liquidity" button is shown below your reply for each pool automatically \u2014 do NOT list, number, or repeat those buttons in your text; just deliver your analysis.';function et(r,e,t){return ql(r,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function ql(r,e,t,n){let o=typeof n=="string"?n.trim():"",s=[];for(let a of r){if(s.length>=5)break;let i=a.token0?.symbol?.trim(),l=a.token1?.symbol?.trim();if(!i||!l)continue;let c=Pf(i,l,a.feeTierPercent);s.push({label:Ad(e,c,`Add liquidity to ${Ja}`),prompt:Ad(t,c,`add liquidity to ${Ja}`)+Af(a.address,o)})}return s}function Af(r,e){let n=[typeof r=="string"&&r.trim()?`Pool: ${r.trim()}`:"",e].filter(Boolean);return n.length>0?` (${n.join(" - ")})`:""}function Pf(r,e,t){let n=`${r}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${n} ${Sf(t)}%`:n}function Sf(r){return Number(r.toFixed(4)).toString()}function Ad(r,e,t){return(r&&r.includes(Ja)?r:t).split(Ja).join(e).replace(/\s+/g," ").trim()}var Ue="You are a seasoned DEX liquidity-pool analyst with deep, credible expertise. Deliver a genuinely insightful, professional read \u2014 the kind a sophisticated LP would pay for \u2014 in natural, flowing prose rather than a rigid template, never sacrificing depth or authority for a conversational tone. ",Ie='Ground every judgement rigorously in the data, never guesses \u2014 and only use a signal when its data is present: \u2022 capital efficiency = `volumeToTvlRatio` (volume \xF7 TVL) \u2014 higher means each $ of liquidity earns more fees; >1 is very active, <0.1 is sluggish. \u2022 APR quality \u2014 a very high APR sitting on a TINY TVL is usually volatile/unsustainable (treat with caution); a solid APR on deep TVL is the sweet spot. When an APR field is ABSENT there is no yield reading for that pool: say nothing about its APR \u2014 never print "APR 0%", "APR: N/A", a dash, or infer the yield from other fields. Judge such a pool on its remaining metrics alone. \u2022 TVL trend \u2014 when a 24h TVL % change is present, note whether liquidity is growing or shrinking. \u2022 TVL depth \u2014 deeper pools = lower slippage and a steadier position; thin pools carry higher risk. \u2022 fee tier vs pair type \u2014 stable/correlated pairs suit low tiers (0.01\u20130.05%), volatile pairs suit higher tiers (0.3\u20131%). \u2022 token safety \u2014 when a token exposes isSpam=true or a non-VERIFIED safetyLevel, FLAG it prominently as a risk. \u2022 transfer tax \u2014 when a token exposes transferFeeBps, it charges that tax (in basis points: 200 = 2%) on transfers. FLAG it prominently: it eats directly into LP returns, and a high or one-sided tax is a common honeypot trait. \u2022 unrecognized token \u2014 when a token exposes isUnrecognizedToken=true, Uniswap does not know that contract at all. Treat this as a SEVERE warning, stronger than any safetyLevel: a token wearing a well-known ticker (WBTC, USDC\u2026) on a contract Uniswap cannot identify is most likely an impostor. Say so plainly and advise verifying the contract address before providing any liquidity. ',Le="Give a clear one-line worthiness verdict for LPs (e.g. a \u2B50 rating or High / Medium / Low attractiveness), woven naturally into the prose rather than tacked on as a fixed label. ",ke="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",tt=`LINKS \u2014 write every pool pair as PLAIN TEXT only (e.g. "USDC/WETH"). Do NOT create markdown links, do NOT output any URLs, and do NOT print raw pool or token contract addresses anywhere in your answer. The system automatically turns each pool's pair into the correct clickable link after you reply, so you must NEVER add a link, a "Link to pool" line, a "View on Uniswap" line, or a bare URL yourself \u2014 doing so produces wrong/duplicate links. Just name each pair in text. Format numbers human-readably (e.g. $12.5M, +1.23%, 0.05%). Omit null fields. Answer in the user's language. Do NOT mention tool or API names.`;var xf=["tvl","volume1Day","volume30Day","apr"],Cf=["V2","V3","V4"],mo=class extends P{name="get-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens (symbol, name, address, decimals), TVL, rolling volume (1d / 30d), and estimated APR. Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap V3 pools on Base", "which pool has the most liquidity for USDC", "show pools with highest 24h volume on Arbitrum". Source: https://app.uniswap.org/explore (ListPools gateway). Supports: `+Ee();category="blockchain-data";parameters=[{name:"chain",type:"string",description:$e,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", or "V4". Default is "V3" (the dataset with the richest stats). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume30Day", or "apr" (estimated annualized fee yield, net of the protocol fee). Pools are returned in descending order by this metric.',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"multichain",type:"boolean",description:"When true, request Uniswap's multichain aggregated view instead of a single chain. Defaults to false. Most queries should leave this off.",required:!1,default:!1},{name:"forAddLiquidity",type:"boolean",description:'Set TRUE only when this ranking is the ENTRY POINT of the ADD-LIQUIDITY flow \u2014 the user wants to add / provide liquidity ("add pool", "i want to add liquidity", "th\xEAm thanh kho\u1EA3n") but named NO specific pool, so you show top pools (use sortBy="apr") for them to pick one. In that mode the tool gates on ADD-LIQUIDITY chain support (only chains with a gateway) and, when the connected chain has no gateway, returns the "adding liquidity is not available on this chain" message with the correct supported list \u2014 so the user is told up front, not after picking a pool. OMIT (false) for ordinary informational rankings ("top pools on Base", "biggest pools").',required:!1,default:!1},...ln];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new Re(e),this.subgraphFallback=new ye(t),this.pool=new Se}async run(e,t){let n=e.forAddLiquidity===!0,o=n?po(this.pool):He(),s=await o.listSupported(),a=Fl(e.chain,t,s),i=this.parseProtocolVersion(e.protocolVersion),l=this.parseSortKey(e.sortBy),c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,u=!n&&e.multichain===!0;if(!u&&!await o.isSupported(a))return Bl(a,s,o.kind);let d=await this.service.getTopPools({chain:a,protocolVersion:i,sortBy:l,limit:c,multichain:u});if(!d.success)return{error:d.error||"Failed to fetch top pools"};let p=(d.data??[]).map(w=>this.formatPool(w)),m="uniswap";if(p.length===0&&i==="V3"){let w=await this.fetchV3Fallback(a,l,c);w.length>0&&(p=w,m="subgraph")}let g=p.map(w=>this.withExpertSignals(w)),h=await this.pool.isAddLiquiditySupported(a)?et(g,e,T(a)):[],f=m==="subgraph",b=f?`"Volume past day" (translate naturally into the user's language; NEVER call it "24h volume", "daily volume", or "24h")`:"24h volume";return{_instructions:(f?`BEGIN your answer with "According to the latest data from Subgraph Uniswap V3," (translate the sentence naturally into the user's language but keep the word "Subgraph" as-is). `:"")+Ue+`You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, ${b}, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. `+Ie+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+Le+ke+"Mention the chain and the sort metric in the intro line. "+tt+(h.length>0?Ze:""),chain:a,protocolVersion:i,sortBy:l,source:m,count:g.length,pools:g.map(w=>({...w,...Je(a,w.address)})),...h.length>0?{actionButtons:h}:{}}}withExpertSignals(e){let t=a=>Math.round(a*1e3)/1e3;if(typeof e.volumeToTvlRatio=="number"&&Number.isFinite(e.volumeToTvlRatio))return{...e,volumeToTvlRatio:t(e.volumeToTvlRatio)};let n=e.tvlUsd,o=e.volume1DayUsd,s=typeof n=="number"&&n>0&&typeof o=="number"?t(o/n):void 0;return{...e,volumeToTvlRatio:s}}async fetchV3Fallback(e,t,n){try{return(await this.subgraphFallback.getTrendingPools({chain:e})).map(i=>this.formatSubgraphPool(i,e)).sort((i,l)=>this.fallbackSortValue(l,t)-this.fallbackSortValue(i,t)).slice(0,n)}catch{return[]}}fallbackSortValue(e,t){switch(t){case"apr":return e.apr??0;case"volume1Day":case"volume30Day":return e.volume1DayUsd??0;default:return e.tvlUsd??0}}formatSubgraphPool(e,t){return{apr:z(e.apr),totalApr:void 0,address:e.poolAddress,chain:t,protocolVersion:"V3",feeTierBps:e.feeTierBps,feeTierPercent:typeof e.feeTierBps=="number"?e.feeTierBps/1e4:void 0,tvlUsd:e.tvl,fee24hUsd:e.fees24hUsd,volume1DayUsd:e.volume24hUsd,volume1WeekUsd:void 0,volume30DayUsd:void 0,volumeToTvlRatio:void 0,txCount:void 0,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0}}parseProtocolVersion(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(Cf.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(xf.includes(t))return t}return"tvl"}formatPool(e){let t=e.isDynamicFee===!0||en(e.feeTier);return{apr:z(e.apr),totalApr:typeof e.totalApr=="number"&&typeof e.apr=="number"&&e.totalApr>e.apr?e.totalApr:void 0,address:e.id,chain:e.chain,protocolVersion:e.protocolVersion,feeTierBps:t?void 0:e.feeTier,feeTierPercent:!t&&typeof e.feeTier=="number"?e.feeTier/1e4:void 0,...t?{isDynamicFee:!0}:{},tvlUsd:e.totalLiquidity?.value,fee24hUsd:e.fee24hUsd,volume1DayUsd:e.volume1Day?.value,volume1WeekUsd:e.volume1Week?.value,volume30DayUsd:e.volume30Day?.value,volumeToTvlRatio:e.volumeToTvlRatio,txCount:e.txCount,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.price?.value,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.price?.value,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}};var $l={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},Rf={100:.01,500:.05,3e3:.3,1e4:1},cn=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=F(e);return!!(t&&$l[t])}listSupportedChains(){return Object.keys($l).filter(e=>F(e)===e)}numericChainId(e){let t=F(e);return t?$l[t]:void 0}async getPairs(e){let t=this.numericChainId(e.chain);if(!t)return[];let o=(await this.fetchV2Items(t)).map(s=>this.mapV2Item(s)).filter(s=>s!==null);if(e.tokens&&e.tokens.length>=2){let s=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase(),i=(l,c)=>l.includes(c)||c.includes(l);o=o.filter(l=>{let[c="",u=""]=l.pair.toUpperCase().split("/");return i(c,s)&&i(u,a)||i(c,a)&&i(u,s)})}return o}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(s=>s.poolId?.toLowerCase()===n).map(s=>this.mapV2Item(s)).filter(s=>s!==null).sort((s,a)=>(a.apr??-1/0)-(s.apr??-1/0))}async fetchV2Items(e){try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(E(n));return n.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,o=A=>A==null||!Number.isFinite(A)?0:Math.pow(1.0001,A)*Math.pow(10,t-n),s=o(e.minTick),a=o(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?s:a>0?1/a:0,p=u?a:s>0?1/s:0,m=u?c:c>0?1/c:0,g=u?e.token0.symbol:e.token1.symbol,h=u?e.token1.symbol:e.token0.symbol;if(!m||!d&&!p)return null;let f=Math.min(d,p),b=Math.max(d,p);if(m<f||m>b)return null;let y=Number(e.fee),w=Rf[y]??y/1e4,k=z(e.apr)??z(e.aprAvg)??null,v=z(e.aprAvg)??null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:v,token0Price:i,token1Price:l,priceRange:{minPrice:fe(d),maxPrice:fe(p),currentPrice:fe(m),baseToken:g,quoteToken:h}}}};function Ef(r){if(!(!r||r.length===0))return r.map(e=>({timestamp:e.timestamp,volumeUsd:e.value}))}function _f(r,e){if(!(typeof r!="number"||typeof e!="number"||e<=0))return Math.round(r/e*1e3)/1e3}function On(r,e){let t=e!==void 0&&Array.from(e.values()).some(i=>i.safetyLevel!=null),n=r.totalLiquidity?.value,o=r.volume24h?.value,s=r.feeTier,a=Va(s,r.protocolFee,r.protocolVersion);return{address:r.address??r.poolId,protocolVersion:r.protocolVersion,poolId:r.poolId,tickSpacing:r.tickSpacing,isDynamicFee:r.isDynamicFee,hookAddress:r.hook?.address,feeTierBps:s,feeTierPercent:typeof s=="number"?s/1e4:void 0,tvlUsd:n,tvlChange24hPercent:r.totalLiquidityPercentChange24h?.value,volume24hUsd:o,fees24hUsd:Wa(o,s,a),lpFeeShare:a,aprPercent:z(r.apr),totalAprPercent:z(r.totalApr),volumeToTvlRatio:_f(o,n),txCount:r.txCount,historicalVolumeWeek:Ef(r.historicalVolume),token0:Pd(r.token0,r.token0Supply,e,t),token1:Pd(r.token1,r.token1Supply,e,t)}}function Pd(r,e,t,n){if(!r)return;let o=r.address?t?.get(r.address.toLowerCase()):void 0,s=n&&r.address!=null&&!o?.safetyLevel,a=o?.isSpam==null?void 0:o.isSpam.toUpperCase()==="TRUE",i=Number(o?.feeData?.buyFeeBps??0),l=Number(o?.feeData?.sellFeeBps??0),c=Number.isFinite(i)&&Number.isFinite(l)?Math.max(i,l):0;return{address:r.address,symbol:r.symbol,name:r.name,decimals:r.decimals,priceUsd:r.market?.price?.value??r.price?.value,reserve:e,isSpam:a??r.project?.isSpam??void 0,safetyLevel:o?.safetyLevel??r.project?.safetyLevel??void 0,transferFeeBps:c>0?c:void 0,isUnrecognizedToken:s||void 0}}var Sd=/^0x[a-fA-F0-9]{40}$/,Nf=6,ho=class extends P{name="get-pool-detail";description="Get detailed stats for a Uniswap V3 pool by token pair (and optional fee tier). Always runs a search first and filters by the provided symbols + fee tier. When the filter resolves to exactly one pool, returns its full detail. When the pair is fully named but NO fee tier is given, returns detail plus a comparative analysis of ALL the pair's fee-tier variants (no need to ask the user to pick). When only one token is given (so the matches are different pairs), returns a `candidates` list \u2014 show it and ask which pair they want, then re-call this tool with the missing info. Detail response includes: pool address, fee tier (bps and %), both tokens (symbol, name, address, decimals, USD price), token0/token1 reserves, total TVL with 24h % change, 24h volume, weekly historical volume series, total tx count, and the pool's fee APR (net of the protocol fee). NEVER pass a pool address \u2014 the tool resolves the address itself by searching. Token contract addresses are NOT pool addresses. Source: https://app.uniswap.org. Supports: "+Ee();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter \u2014 USDC/WETH and WETH/USDC resolve to the same pool. When both token0Symbol and token1Symbol are provided the search is filtered to that exact pair.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 when omitted the tool returns all pools containing token0Symbol so the user can pick.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points (bps): 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. "USDC/WETH 0.05%" \u2192 feeTier=500). NEVER guess or infer one. When the user has not mentioned a fee tier, OMIT it \u2014 the tool then returns detail plus a comparative analysis of ALL fee-tier variants of the pair (no need to ask the user to pick one).',required:!1},{name:"chain",type:"string",description:$e,required:!1},...ln];service;coinPool;pool;constructor(e,t){super(),this.service=new Re(e),this.coinPool=new cn(t),this.pool=new Se}async run(e,t){let n=await _e(He(),e.chain,t);if(!n.ok)return n.result;let o=n.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0;if(!s)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let l=a?`${s} ${a}`:s,c=await this.service.searchPools({query:l,chain:o,page:1,size:100,protocolVersion:"V3"});if(!c.success)return{error:c.error||"Pool search failed"};let u=c.data??[],p=u.filter(f=>this.matchesFilter(f,s,a,i,"ordered")),m=!1;if(p.length===0&&a){let f=u.filter(b=>this.matchesFilter(b,s,a,i,"reversed"));f.length>0&&(p=f,m=!0)}if(p.length===0)return{error:`No V3 pool matched ${this.describeQuery(s,a,i)} on ${T(o)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let f=p[0];if(!f.id||!Sd.test(f.id))return{error:"Resolved pool has no valid address"};let[b,y,w]=await Promise.all([this.service.getPoolDetailEnriched({addressOrId:f.id,chain:o}),this.fetchPriceRanges(o,f.id,f.token0?.symbol,f.token1?.symbol),this.service.getTokenSafetyByAddress([f.token0?.address,f.token1?.address],o)]);if(!b.success||!b.data)return{error:b.error||"Failed to fetch pool detail"};let k={...On(b.data,w),...Je(o,f.id)},v=await this.pool.isAddLiquiditySupported(o)?et([k],e,T(o)):[];return{priceRanges:y,_instructions:Ue+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, token1 reserve + USD price, and total tx count. Optionally include the weekly historical volume as a sparkline-style bullet list. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+Ie+Le+'PRICE RANGES: when `priceRanges` is a non-empty array, add a "Suggested price ranges" section listing each candidate \u2014 fee tier (`fee`), the min\u2013max range (`priceRange.minPrice`\u2013`priceRange.maxPrice` in baseToken/quoteToken units), the current price (`priceRange.currentPrice`), and its `apr` \u2014 omitting the APR for any entry whose `apr` is null/absent (never "APR 0%", "N/A" or a dash). CRITICAL: that `apr` is the yield for THAT specific range only \u2014 NEVER present it as the overall pool APR. Sort by apr desc; note the top entry is the most concentrated/highest-yield range but narrower = higher risk of going out of range. When `priceRanges` is empty or absent, simply omit this section. '+ke+tt+(v.length>0?Ze:""),pairOrderMatched:m?"reversed":"ordered",pool:k,...v.length>0?{actionButtons:v}:{}}}if(a){let f=this.rankCandidates(p).slice(0,Nf),[b,y]=await Promise.all([Promise.all(f.map(async k=>{if(!k.id||!Sd.test(k.id))return;let v=await this.service.getPoolDetailEnriched({addressOrId:k.id,chain:o});if(!(!v.success||!v.data))return{detail:v.data,id:k.id}})),this.service.getTokenSafetyByAddress(f.flatMap(k=>[k.token0?.address,k.token1?.address]),o)]),w=b.filter(k=>k!=null).map(k=>({...On(k.detail,y),...Je(o,k.id)}));if(w.length>0){let k=await this.pool.isAddLiquiditySupported(o)?et(w,e,T(o)):[];return{_instructions:Ue+"The user named a pair WITHOUT a fee tier, so here is EVERY fee-tier variant of that pair \u2014 do NOT ask them to pick a tier. Present them as a ranked list (rank them by capital efficiency / fee yield, not just TVL). For each variant show the fee tier (%), TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), and tx count. Analyze every variant \u2014 give each its own genuine read, never skip one, and never repeat the same sentence structure. "+Ie+"Focus on which fee tier is the right home for THIS pair: lower tiers (0.01\u20130.05%) win on stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 and the tier that actually captures most of the real volume with deep TVL is usually the one to LP in. Close with an overall section naming the single best fee tier to provide liquidity in right now and why. "+Le+ke+tt+(k.length>0?Ze:""),chain:o,pairOrderMatched:m?"reversed":"ordered",multiFeeTier:!0,count:w.length,pools:w,...k.length>0?{actionButtons:k}:{}}}}let g=this.rankCandidates(p).slice(0,10).map(f=>{let b=this.formatCandidate(f);return{...b,...Je(o,b.address)}}),h=await this.pool.isAddLiquiditySupported(o)?et(g,e,T(o)):[];return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume) and ask the user which one they want to see. Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. When they answer, re-call this tool with their selection \u2014 pass token0Symbol + token1Symbol + feeTier (use the exact feeTier in bps from the chosen candidate). Format numbers human-readably (e.g. $12.5M, 0.05%). Do NOT mention tool/API names."+(h.length>0?Ze:""),chain:o,pairOrderMatched:m?"reversed":"ordered",reason:this.candidateReason(s,a,i),missing:this.missingFields(a,i),candidates:g,...h.length>0?{actionButtons:h}:{}}}matchesFilter(e,t,n,o,s){if(o!=null&&e.feeTier!==o)return!1;let a=(e.token0?.symbol??"").toLowerCase(),i=(e.token1?.symbol??"").toLowerCase(),l=t.toLowerCase();if(n){let c=n.toLowerCase();return s==="reversed"?this.symbolIncludes(a,c)&&this.symbolIncludes(i,l):this.symbolIncludes(a,l)&&this.symbolIncludes(i,c)}return this.symbolIncludes(a,l)||this.symbolIncludes(i,l)}symbolIncludes(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}describeQuery(e,t,n){let o=t?`${e}/${t}`:e;return n!=null?`${o} at fee tier ${n} bps`:o}candidateReason(e,t,n){return t?n==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${n} bps. Ask the user which one they meant.`:`Multiple pools contain ${e}. Ask the user for the other token (and fee tier).`}missingFields(e,t){let n=[];return e||n.push("token1Symbol"),t==null&&n.push("feeTier"),n}rankCandidates(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}formatCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}async fetchPriceRanges(e,t,n,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&n&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[n,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}};var Uf=["V2","V3","V4","ALL"],go=class extends P{name="search-pools";description='Search Uniswap liquidity pools on a given chain by free-text query \u2014 a SINGLE token symbol or token name. Returns matching pools with: pool address, fee tier (bps + %), protocol version, both tokens (symbol, name, address, decimals, logo), and short-window USD volume buckets (6h / 12h / 24h). Use this tool when the user names ONE token and wants pools related to it: "find WBTC pools on Optimism", "pools containing PEPE on Ethereum", "show USDC pools". Do NOT use for: (a) two-symbol pair lookups like "USDC/WETH 0.05%" \u2014 use get-pool-detail; (b) raw 0x addresses (token or pool) \u2014 use lookup-pool-by-address; (c) chain-wide rankings with no token mentioned \u2014 use get-top-pools. Source: https://app.uniswap.org search. Supports: '+Ee();category="blockchain-data";parameters=[{name:"query",type:"string",description:'Single token symbol or name to search pools by (e.g. "WBTC", "USDC", "pepe"). Do NOT pass a 0x address (use lookup-pool-by-address) or a two-symbol pair (use get-pool-detail).',required:!0},{name:"chain",type:"string",description:$e,required:!1},{name:"protocolVersion",type:"string",description:'Filter results by Uniswap protocol version: "V2", "V3", "V4", or "ALL" to include every version. Default is "V3" \u2014 only switch when the user explicitly asks for V2, V4, or all versions.',required:!1,default:"V3"},{name:"page",type:"number",description:"1-based page index. Defaults to 1.",required:!1,default:1},{name:"size",type:"number",description:'Page size (max 50). Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"feeTier",type:"number",description:'Optional fee tier filter in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. When provided, only pools with this exact fee tier are returned. Pass it whenever the user mentions a fee tier in the current message OR earlier in the conversation (e.g. "USDC/WETH 0.05% pool on Base" \u2192 feeTier=500). Omit otherwise.',required:!1},...ln];service;pool;constructor(e){super(),this.service=new Re(e),this.pool=new Se}async run(e,t){let n=typeof e.query=="string"?e.query.trim():"";if(!n)return{error:"Search query is required"};let o=await _e(He(),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,i=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):5,l=this.parseProtocolFilter(e.protocolVersion),c=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,u=await this.service.searchPools({query:n,chain:s,page:a,size:i,protocolVersion:l,feeTier:c});if(!u.success)return{error:u.error||"Failed to search pools"};let d=(u.data??[]).map(m=>this.formatPool(m)),p=await this.pool.isAddLiquiditySupported(s)?et(d,e,T(s)):[];return{_instructions:Ue+"Present the pools that match the search AND give an expert read on each. Render each pool as its own block: a bold header with the pair (token0/token1 symbols) + fee tier (%), then beneath it the metrics that have data \u2014 TVL (USD), 24h volume (USD), APR (%), tx count, protocol version. Skip any field that is null/undefined \u2014 never show zeros or dashes for missing data. Then add an expert read on each pool \u2014 is it worth providing liquidity in, and why. "+Ie+Le+"When several pools share the searched token, finish with a clear TOP PICK among them. "+ke+"Mention the search query and chain in the intro. "+tt+(p.length>0?Ze:""),query:n,chain:s,protocolVersion:l,feeTierBps:c,feeTierPercent:c!=null?c/1e4:void 0,page:a,size:i,count:d.length,pools:d.map(m=>({...m,...Je(s,m.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(Uf.includes(t))return t}return"V3"}formatPool(e){let t=e.isDynamicFee===!0||en(e.feeTier),n={address:e.id,chainId:e.chainId,protocolVersion:e.protocolVersion,feeTierBps:t?void 0:e.feeTier,feeTierPercent:!t&&typeof e.feeTier=="number"?e.feeTier/1e4:void 0,...t?{isDynamicFee:!0}:{}},o=z(e.apr);o!=null&&(n.apr=o),e.tvlUsd!=null&&(n.tvlUsd=e.tvlUsd);let s=e.volume1DayUsd??e.volumeUsd24hr;s!=null&&(n.volume24hUsd=s),e.volumeUsd6hr!=null&&(n.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(n.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(n.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&s!=null&&(n.volumeToTvlRatio=Math.round(s/e.tvlUsd*1e3)/1e3);let a=e.token0,i=e.token1;return a&&(n.token0={address:a.address,symbol:a.symbol,name:a.name,decimals:a.decimals}),i&&(n.token1={address:i.address,symbol:i.symbol,name:i.name,decimals:i.decimals}),n}};var fo=class extends P{name="lookup-pool-by-address";description=`Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use this tool when the user pastes a single address and asks about "the pool" without saying which kind. For pool detail (when the address is a pool): pair, fee tier, TVL with 24h % change, 24h volume, 24h fees, estimated APR, token reserves with USD prices, and each token's safety flags. For token resolution (when the address is a token): the resolved token (symbol, name, decimals) plus a ranked list of pools that include it (pair, fee tier, 24h volume, pool address). Source: https://app.uniswap.org. Supports: `+Ee();category="blockchain-data";parameters=[{name:"address",type:"string",description:"A 0x-prefixed EVM address. May be a Uniswap pool contract OR a token contract \u2014 the tool figures out which.",required:!0},{name:"chain",type:"string",description:$e,required:!1},...ln];service;pool;constructor(e){super(),this.service=new Re(e),this.pool=new Se}async run(e,t){let n=await _e(He(),e.chain,t);if(!n.ok)return n.result;let o=n.chain,s=typeof e.address=="string"?e.address.trim():"",[a,i]=await Promise.all([this.service.searchPools({query:s,chain:o,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:s,chain:o,page:1,size:5})]),l=a.success?this.findPoolByAddress(a.data??[],s):void 0;if(l)return this.handlePoolHit(l,o,e);let c=i.success?this.findTokenByAddress(i.data??[],s):void 0;return c?this.handleTokenHit(c,o,e):!a.success&&!i.success?{error:a.error||i.error||"Failed to resolve address"}:{error:`Address ${s} did not match any pool or token Uniswap knows on ${T(o)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t,n){if(!e.id)return{error:"Resolved pool has no identifier"};let o=await this.service.getPoolDetailEnriched({addressOrId:e.id,chain:t,enrich:!1});if(!o.success||!o.data)return{error:o.error||"Failed to fetch pool detail"};let s=await this.service.getTokenSafetyByAddress([o.data.token0?.address,o.data.token1?.address],t),a=o.data.protocolVersion??e.protocolVersion??"V3",i={...On(o.data,s),...Je(t,e.id)},l=await this.pool.isAddLiquiditySupported(t)?et([i],n,T(t)):[];return{_instructions:`The address is a Uniswap ${a} pool. `+Ue+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), protocol version, and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, and token1 reserve + USD price. For V4 pools also mention tickSpacing, isDynamicFee, and the hook address if present. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+Ie+Le+ke+tt+(l.length>0?Ze:""),resolvedAs:"pool",chain:t,protocolVersion:a,pool:i,...l.length>0?{actionButtons:l}:{}}}async handleTokenHit(e,t,n){let o=e.symbol?.trim();if(!o)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let s=await this.service.searchPools({query:o,chain:t,page:1,size:100,protocolVersion:"V3"});if(!s.success)return{error:s.error||"Failed to fetch pools for resolved token"};let a=(e.address??"").toLowerCase(),l=[...(s.data??[]).filter(d=>{let p=(d.token0?.address??"").toLowerCase(),m=(d.token1?.address??"").toLowerCase();return p===a||m===a})].sort((d,p)=>(p.volumeUsd24hr??0)-(d.volumeUsd24hr??0)).slice(0,10),c=l.map(d=>({...this.formatPoolCandidate(d),...Je(t,d.id)})),u=await this.pool.isAddLiquiditySupported(t)?et(c,n,T(t)):[];return{_instructions:"The address is a token, not a pool. Tell the user which token it is (symbol + name), then render the matching pools as a numbered list: pair (token0/token1 symbols), fee tier (%), protocol version, 24h volume (USD). Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. Ask which pool they want detail on; when they answer, re-call this tool with that pool address to fetch the detail. Format numbers human-readably. Omit null fields. Do NOT mention tool/API names."+(u.length>0?Ze:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...u.length>0?{actionButtons:u}:{}}}findPoolByAddress(e,t){let n=t.toLowerCase();return e.find(o=>(o.id??"").toLowerCase()===n)}findTokenByAddress(e,t){let n=t.toLowerCase();return e.find(o=>(o.address??"").toLowerCase()===n)}formatToken(e){return{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,isSpam:e.isSpam,safetyLevel:e.safetyLevel}}formatPoolCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}};var xd=/^0x[a-fA-F0-9]{40}$/,Cd=/^0x[a-fA-F0-9]{64}$/,yo=class extends P{name="open-add-liquidity-form";kind="ui";category="pool-action";description='Open the Add-Liquidity form for a specific Uniswap V3 pool. Use this when the user wants to provide liquidity / add LP / farm / stake / deposit into a pool \u2014 natural-language verbs in any language all map here. Resolves the pool by its exact address when the message carries one (the add-liquidity buttons under a pool listing append "(Pool: 0x\u2026 - <chain>)" \u2014 pass that address through as `poolAddress`), otherwise by token symbols and optional fee tier. Reads on-chain state, checks the connected wallet\'s NATIVE balance, then returns a UI payload that the FE renders as the form (with two preset ranges: Stable \xB13 ticks and Wide -50%/+100%). CONSTRAINT: the gateway only accepts the chain\'s NATIVE coin as input (ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche). The native amount is auto-split via deBridge into both pool tokens \u2014 the user never selects a different input. If the user asks to add liquidity using a NON-NATIVE token amount (e.g. "add pool with 5 USDT", "th\xEAm 100 USDC"), pass that symbol via `requestedNonNativeToken` so the tool can return error="unsupported_input_token" \u2014 never silently convert their non-native amount into native or USD. PRECONDITION: a connected wallet (userContext.walletAddress). If absent, the tool returns error="wallet_not_connected" and the agent must ask the user to connect. VERSION CONSTRAINT: only Uniswap V3 pools can be added to. When the pool the user picked is V2 or V4, the tool returns error="unsupported_protocol_version" with the version \u2014 tell the user that version is not supported yet (the pool DOES exist; never say it was not found).';parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's 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"). Required to uniquely identify the pool.',required:!0},{name:"poolAddress",type:"string",description:`The pool's exact on-chain address (0x\u2026), when the user's message names one \u2014 the add-liquidity buttons under a pool listing carry it as "(Pool: 0x\u2026 - <chain>)". Pass it through VERBATIM whenever it is present: it pins the flow to that exact pool instead of re-searching by symbols, which can land on a different pool of the same pair. Omit when the user named no address.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. Omit when unknown \u2014 the tool will resolve the best match automatically.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prefillNativeAmount",type:"number",description:"Optional NATIVE-COIN amount (human-readable) to pre-fill the form's input field. ONLY pass this when the user named an amount in the chain's native coin itself \u2014 ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche. Example: \"add 0.1 ETH to USDC/WETH on Base\". Pass the plain decimal number (e.g. 0.1 for 0.1 ETH). DO NOT convert a non-native amount (USDC, USDT, DAI, WBTC, \u2026) into native here \u2014 pass `requestedNonNativeToken` instead so the tool can reject. Mutually exclusive with prefillUsdAmount \u2014 pass one or neither.",required:!1},{name:"prefillUsdAmount",type:"number",description:'Optional USD amount to pre-fill the form\'s input field. Use this ONLY when the user explicitly speaks in USD/dollars \u2014 e.g. "add $10 to this pool", "10 dollars", "10 \u0111\xF4". The tool converts the USD value to native amount automatically using the current native-token price. DO NOT use this as a workaround for non-native token amounts (e.g. "5 USDT" is NOT $5 \u2014 USDT may de-peg, and even if 1:1 the user asked for a token, not USD). For non-native token amounts pass `requestedNonNativeToken` instead. Mutually exclusive with prefillNativeAmount \u2014 pass one or neither.',required:!1},{name:"requestedNonNativeToken",type:"string",description:`Set this ONLY when the user named an AMOUNT in a non-native token \u2014 e.g. "add pool with 5 USDT", "add 100 USDC to USDC/WETH", "th\xEAm 5 USDT v\xE0o pool". The trigger is "<number> <non-native-symbol>" in the user's message, NOT the mere appearance of the symbol. Pass the symbol the user attached the amount to (e.g. "USDT", "USDC", "DAI"). CRITICAL: If the user also names a NATIVE amount in the same message (e.g. "add USDC/WETH with 0.1 ETH", "th\xEAm pool USDC/WETH 0.3% v\u1EDBi 0.000005 ETH"), the native amount is the input \u2014 leave this EMPTY and use prefillNativeAmount. The pool pair symbols (the two tokens after "pool" / "to") are NEVER the input token by themselves \u2014 they only identify which pool. The tool will return error="unsupported_input_token" so the agent can tell the user that only the chain's native coin is accepted as input. DO NOT silently convert the user's non-native amount into a native amount or USD amount \u2014 the user explicitly named a different asset and must be informed, not auto-corrected. Leave empty when the user did name a native amount, a USD amount, or no amount at all.`,required:!1},{name:"rangeStrategy",type:"string",description:'Optional preset that pre-fills the min/max price inputs (FE keeps them editable). One of: "stable" \u2014 \xB13 tickSpacing around the current price (narrow, higher yield, higher out-of-range risk; pick for stablecoin / low-volatility pairs and when the user says "safe", "tight", "high yield", "t\u1EADp trung"); "wide" \u2014 currentPrice \xD7 [0.5, 2.0] (broad, lower yield, less rebalancing; pick when the user says "wide", "set and forget", "r\u1ED9ng"); "full" \u2014 full V3 tick range (V2-style, lowest yield, never goes out of range; pick when the user says "full range", "v2-style", "kh\xF4ng lo out of range"). Omit when the user did not signal a preference AND did not provide explicit minPrice/maxPrice. Mutually exclusive with minPrice/maxPrice \u2014 if both are passed, explicit prices win.',required:!1},{name:"minPrice",type:"number",description:'Optional explicit lower bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 minPrice=1800. Must be paired with maxPrice. When set, overrides rangeStrategy.',required:!1},{name:"maxPrice",type:"number",description:'Optional explicit upper bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 maxPrice=2200. Must be paired with minPrice. When set, overrides rangeStrategy.',required:!1},{name:"add_button_label",type:"string",description:`Label template for the per-fee-tier "Add liquidity" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. ALWAYS pass this when you call the tool with a pair but NO feeTier (the tool may return several fee-tier variants for the pair, and each gets a one-tap button). Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:'A short "add liquidity" command template IN THE USER\'S CURRENT LANGUAGE, submitted as the next user turn when a fee-tier button is clicked \u2014 it carries the chosen fee tier so the tool resolves that exact pool. ALWAYS pass this alongside `add_button_label` when calling with a pair but no feeTier. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain this pair is on is appended to the prompt automatically.',required:!1}];uniswap;pool;coinPool;minProvideUsd;constructor(e){super(),this.uniswap=new Re(e),this.pool=new Se(e?.pool),this.coinPool=new cn(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&typeof s=="object"&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let n=await _e(po(this.pool),e.chain,t);if(!n.ok)return n.result;let o=n.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.poolAddress=="string"?e.poolAddress.trim():"",c=xd.test(l)||Cd.test(l)?l.toLowerCase():"",u=Cd.test(l),d=typeof e.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,p=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,m=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,g=m&&d!=null&&(m.toLowerCase()===s.toLowerCase()||m.toLowerCase()===a.toLowerCase())?null:m,h=this.parseRangeStrategy(e.rangeStrategy),f=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,b=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!s||!a)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let y=ue(o);if(!y)return{error:"unsupported_chain",chain:o,_instructions:`Chain ${o} is not supported by the add-liquidity flow.`};let w=uo(o);if(g&&w&&g.toLowerCase()!==w.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:g,nativeSymbol:w.symbol,chainName:y.name,_instructions:`The user asked to add liquidity using ${g}, but this app only supports the chain's native coin (${w.symbol} on ${y.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${w.symbol} or in USD. DO NOT silently convert their ${g} amount, do NOT pre-fill the form, and do NOT call this tool again until the user provides a native or USD amount.`};let k=await this.pool.getGatewayAddress(o);if(!k)return{error:"no_gateway_configured",chain:o,_instructions:`No gateway contract is configured for chain ${o} (${y.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let v=t?.walletAddress;if(!v)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before adding liquidity. Do NOT render the form."};if(u)return this.unsupportedVersionResult({protocolVersion:"V4",token0:{symbol:s},token1:{symbol:a}},s,a,y.name);let A=await this.uniswap.searchPools({query:`${s} ${a}`,chain:o,page:1,size:100,protocolVersion:"V3",feeTier:c?void 0:i});if(!A.success)return{error:A.error||"pool_search_failed"};let S=A.data??[],C=c?S.find(Y=>typeof Y.id=="string"&&Y.id.toLowerCase()===c):void 0;if(c&&!C){let Y=await this.findUnsupportedVersionPool(o,s,a,i,c);if(Y)return this.unsupportedVersionResult(Y,s,a,y.name)}let O=C??S.find(Y=>this.matchesPairExact(Y,s,a,i)),_=O?[]:S.filter(Y=>this.matchesPair(Y,s,a,i));if(!O&&_.length===0){let Y=await this.findUnsupportedVersionPool(o,s,a,i,c);return Y?this.unsupportedVersionResult(Y,s,a,y.name):{error:"pool_not_found",_instructions:`No V3 pool found for ${s}/${a}${i!=null?` at ${i}bps`:""} on ${y.name}. Verify the inputs with the user.`}}if(!O&&_.length>1){let Y=_.map(de=>{let Bn=de.volume1DayUsd??de.volumeUsd24hr,Hs=de.tvlUsd,Xl=typeof Bn=="number"&&typeof Hs=="number"&&Hs>0?Bn/Hs:void 0;return{address:de.id,token0Symbol:de.token0?.symbol,token1Symbol:de.token1?.symbol,feeTier:de.feeTier,feeTierPercent:de.feeTier!=null?de.feeTier/1e4:void 0,volume24hUsd:Bn,tvlUsd:Hs,...Xl!=null?{volumeToTvlRatio:Xl}:void 0,...de.apr?{apr:de.apr}:void 0}}).sort((de,Bn)=>(Bn.volumeToTvlRatio??Bn.apr??-1/0)-(de.volumeToTvlRatio??de.apr??-1/0)).slice(0,5),hi=ql(Y.map(de=>({token0:{symbol:de.token0Symbol},token1:{symbol:de.token1Symbol},feeTierPercent:de.feeTierPercent,address:de.address})),typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",T(o));return{relatedPools:Y,count:Y.length,...hi.length>0?{actionButtons:hi}:{},_instructions:Ue+"The user wants to ADD LIQUIDITY to this pair but named NO fee tier \u2014 `relatedPools` holds the related pools (the pair's fee-tier variants and closely-matching pools). Do NOT just ask them to pick blindly: give a genuine comparative read. Present them as a ranked list (rank by capital efficiency / fee yield, not just TVL); for each show the fee tier (%), TVL (USD), 24h volume (USD), and estimated APR (%) when present. Analyze each with its own real read \u2014 never skip one or repeat the same sentence structure. "+Ie+"Focus on which fee tier is the best home for THIS pair to LP in: lower tiers (0.01\u20130.05%) suit stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 the tier that captures most of the real volume on deep TVL is usually the one to provide liquidity in. Close by naming the single best fee tier to add liquidity in right now and why, then invite the user to confirm a tier to continue. When they choose, re-run the add-liquidity step with token0Symbol + token1Symbol + the chosen feeTier (in bps). "+Le+ke+tt+(hi.length>0?' A clickable "Add liquidity" button is shown below your reply for each fee-tier candidate automatically \u2014 do NOT list, number, or repeat those buttons.':"")}}let H=O??_[0];if(!H.id||!xd.test(H.id))return{error:"invalid_pool_address"};let q=this.fetchPriceRanges(o,H.id,H.token0?.symbol,H.token1?.symbol),$=await this.pool.readPoolOnchain(o,H.id),[te,nt,he]=await Promise.all([this.pool.getNativeBalance(o,v),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),ne=te>nt?te-nt:0n,be=uo(o),ve=Number(ne)/10**be.decimals,Dn=Number(te)/10**be.decimals,Ho=he!=null?ve*he:null,[Vo,Wo]=await Promise.all([this.pool.readErc20Decimals(o,$.token0),this.pool.readErc20Decimals(o,$.token1)]),Mn={min:Qe(rn,Vo,Wo),max:Qe(to,Vo,Wo)},Et=null;te===0n?Et="no_balance":Ho!=null&&Ho<this.minProvideUsd&&(Et="insufficient_balance");let dn=H.token0,_t=H.token1,pn=[25,50,75,100].map(Y=>({percent:Y,amountWei:(ne*BigInt(Y)/100n).toString(),amount:ve*(Y/100)})),wt=null,Fn=null;if(d!=null){Fn=d;let Y=BigInt(Math.floor(Fn*10**be.decimals));Y>0n&&(wt=Y.toString())}else if(p!=null&&he!=null&&he>0){Fn=p/he;let Y=BigInt(Math.floor(Fn*10**be.decimals));Y>0n&&(wt=Y.toString())}let zl={address:se,isNative:!0,symbol:be.symbol,name:be.name,decimals:be.decimals,priceUsd:he,balanceWei:te.toString(),balance:Dn,gasReserveWei:nt.toString(),spendableWei:ne.toString(),spendable:ve,spendableUsd:Ho,quickRates:pn,minProvideUsd:this.minProvideUsd,warning:Et,warningMessage:Et==="no_balance"?`You have no ${be.symbol} on ${y.name}. Top up to add liquidity.`:Et==="insufficient_balance"?`Spendable ${be.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:Fn,prefillAmountWei:wt},K=this.computePrefillRange({explicitMinPrice:f,explicitMaxPrice:b,rangeStrategy:h,currentPrice:$.currentPrice,currentTick:$.currentTick,tickSpacing:$.tickSpacing,token0Decimals:Vo,token1Decimals:Wo,priceBounds:Mn}),jd={component:"AddLiquidityForm",props:{chain:{hexId:o,name:y.name},pool:{address:$.poolAddress,fee:$.fee,feePercent:$.fee/1e4,tickSpacing:$.tickSpacing,currentTick:$.currentTick,currentPrice:fe($.currentPrice),sqrtPriceX96:$.sqrtPriceX96.toString(),token0:{address:$.token0,symbol:dn?.symbol,name:dn?.name,logo:dn?.logo},token1:{address:$.token1,symbol:_t?.symbol,name:_t?.name,logo:_t?.logo}},inputToken:zl,priceBounds:Mn,prefillRange:K,gatewayAddress:k}},zd=this.orientRangesToForm(await q,$.currentPrice,dn?.symbol,_t?.symbol);return{ui:jd,suggestedRanges:zd,summary:this.buildSummary({chainName:y.name,pair:`${dn?.symbol??s}/${_t?.symbol??a}`,feePercent:$.fee/1e4,warning:Et,minProvideUsd:this.minProvideUsd,nativeSymbol:be.symbol}),_instructions:'The add-liquidity action is ready. In the user\'s language, invite them to enter the amount and price range to add liquidity, naming the pool + chain (e.g. "Enter the amount and price range to add liquidity to <pool> on <chain>"). Speak ONLY of the user\'s action (adding liquidity). NEVER say you "opened a form", "opened" anything, or describe any screen/form/window/UI being shown \u2014 phrase it as the next step the user takes, not as something you did. If warning="no_balance" tell them they need to top up. If warning="insufficient_balance" tell them the balance is below the minimum. REFERENCE RANGES: when `suggestedRanges` is a non-empty array, briefly offer 1\u20133 of them (highest `apr` first) as price ranges the user can REFERENCE when filling in their range \u2014 for each give the min\u2013max (`minPrice`\u2013`maxPrice`) and its `apr` \u2014 omitting the APR for any entry whose `apr` is absent (never "APR 0%", "N/A" or a dash). These prices are ALREADY in the SAME unit the form shows (`quoteSymbol` per `baseSymbol`), so quote them as-is \u2014 do NOT invert them. CRITICAL: that `apr` is the yield for THAT specific range ONLY \u2014 NEVER present it as the overall pool APR; narrower = higher out-of-range risk. These are only in-range suggestions to reference \u2014 the user still chooses their own range. When `suggestedRanges` is empty or absent, omit this entirely. '+ke+"Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, data sources, or internal tool names. Wait for the user to fill in amount + price range before proceeding."}}async fetchPriceRanges(e,t,n,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&n&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[n,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,n,o){let s=a=>Number.isFinite(a)&&a>0;return s(t)?e.map(a=>{let{minPrice:i,maxPrice:l,currentPrice:c}=a.priceRange,u=i,d=l,p=c;if(s(c)){let m=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<m&&(u=s(l)?1/l:0,d=s(i)?1/i:0,p=1/c)}return{fee:a.fee,apr:z(a.apr),minPrice:fe(u),maxPrice:fe(d),currentPrice:fe(p),baseSymbol:n,quoteSymbol:o}}).filter(a=>s(a.minPrice)&&s(a.maxPrice)):[]}unsupportedVersionResult(e,t,n,o){let s=e.protocolVersion??"V4";return{error:"unsupported_protocol_version",protocolVersion:s,pair:`${e.token0?.symbol??t}/${e.token1?.symbol??n}`,chain:o,_instructions:`This is a Uniswap ${s} pool, and adding liquidity currently works only for V3 pools. Tell the user \u2014 in their language \u2014 that the pool they picked does exist but that adding liquidity to ${s} pools is not supported yet, only V3 pools are. Suggest they pick a V3 pool for this pair instead (one may well exist). Keep it short and friendly. Do NOT say the pool was not found, and do NOT mention tools, services, APIs, forms, or any internals.`}}async findUnsupportedVersionPool(e,t,n,o,s){try{let a=await this.uniswap.searchPools({query:`${t} ${n}`,chain:e,page:1,size:100,protocolVersion:"ALL"});if(!a.success)return;let i=(a.data??[]).filter(l=>l.protocolVersion&&l.protocolVersion!=="V3");return i.length===0?void 0:s?i.find(l=>typeof l.id=="string"&&l.id.toLowerCase()===s):i.find(l=>this.matchesPairExact(l,t,n,o))??i.find(l=>this.matchesPair(l,t,n,o))}catch{return}}matchesPairExact(e,t,n,o){if(!o||o!=null&&e.feeTier!==o)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase();return s===i&&a===l||s===l&&a===i}matchesPair(e,t,n,o){if(o!=null&&e.feeTier!==o)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase(),c=this.symMatch(s,i)&&this.symMatch(a,l),u=this.symMatch(s,l)&&this.symMatch(a,i);return c||u}symMatch(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}parseRangeStrategy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="stable"||t==="wide"||t==="full"?t:null}computePrefillRange(e){let{explicitMinPrice:t,explicitMaxPrice:n,rangeStrategy:o,currentPrice:s,priceBounds:a}=e;if(t!=null&&n!=null&&n>t){let{minPrice:i,maxPrice:l}=no(t,n,s);return{strategy:"user",minPrice:Math.max(i,a.min),maxPrice:Math.min(l,a.max)}}if(o==="full")return{strategy:"full",minPrice:a.min,maxPrice:a.max};if(o==="stable"||o==="wide"){let l=Ml({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===o);if(l)return{strategy:o,minPrice:l.minPrice,maxPrice:l.maxPrice}}return null}buildSummary(e){let t=[`Ready to add liquidity to the ${e.pair} ${e.feePercent}% pool on ${e.chainName}. Enter an amount and a price range to continue.`];return e.warning==="no_balance"?t.push(`You'll need some ${e.nativeSymbol} on ${e.chainName} first \u2014 top up to continue.`):e.warning==="insufficient_balance"&&t.push(`Your spendable ${e.nativeSymbol} is below the $${e.minProvideUsd} minimum \u2014 top up before continuing.`),t.join(" ")}};var If=/^0x[a-fA-F0-9]{40}$/,bo=class extends P{name="preview-add-liquidity";kind="action";category="pool-action";description='Preview the add-liquidity transaction. Call this whenever a concrete pool ADDRESS, a native amount, and BOTH min and max price (in token1 per token0) are known \u2014 whether the user filled the AddLiquidityForm OR stated all of them directly in chat (e.g. "add to USDC/WETH with 0.01 ETH, range 0.0005-0.0007, pool=0x\u2026"). Do NOT require the form to have been opened first. The tool converts prices \u2192 ticks (rounded to tickSpacing), fetches deBridge swap quotes for both legs, encodes the gateway.mint call, and returns an unsigned tx the FE will sign. REQUIRES the exact poolAddress (from open-add-liquidity-form props.pool.address or given by the user) \u2014 if only token symbols / a fee tier are known, resolve the pool via open-add-liquidity-form first.';parameters=[{name:"poolAddress",type:"string",description:"V3 pool contract address (returned by open-add-liquidity-form in props.pool.address).",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 .Must match the pool's chain. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.`,required:!1},{name:"minPrice",type:"number",description:`Lower bound of the position price range, in token1-per-token0 units (decimal-adjusted \u2014 the SAME unit as pool.currentPrice from open-add-liquidity-form). Example: if currentPrice is 1800 (USDC per WETH), minPrice 900 means "the position is in-range while WETH \u2265 900 USDC". Must be >= 0 and < maxPrice. Pass 0 for a "full-range lower" position (the range extends down to price 0, i.e. Uniswap's MIN_TICK). CRITICAL: copy the number the user gave VERBATIM \u2014 every digit and every leading zero. Do NOT add or drop a zero, round, or rescale it. Tiny decimals like 0.000533 are easy to mis-transcribe (0.000533 must stay 0.000533, NEVER 0.0000533). If unsure, prefer the user's exact characters over your own reformatting.`,required:!0},{name:"maxPrice",type:"number",description:`Upper bound of the position price range, in the same units as minPrice. Must be > minPrice. Pass a very large number (or props.priceBounds.max) for a "full range upper" position. CRITICAL: copy the user's number VERBATIM \u2014 every digit and leading zero; never add/drop a zero, round, or rescale.`,required:!0},{name:"nativeAmount",type:"number",description:"Native amount the user wants to spend, as a human-readable decimal number (e.g. 0.1 for 0.1 ETH). The tool converts to wei internally.",required:!0},{name:"slippageBps",type:"number",description:"Slippage tolerance in basis points (100 = 1%). Optional \u2014 defaults to 100.",required:!1}];pool;defaultSlippageBps;mintMinPercent;pantograph;constructor(e){super(),this.pool=new Se(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new me}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=await _e(po(this.pool),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=Number(e.minPrice),i=Number(e.maxPrice),l=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,c=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!n||!s||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!If.test(n))return{error:"invalid_pool_address",_instructions:"poolAddress is not a valid EVM address. Re-open the add-liquidity form to get the correct pool address."};if(a<0||i<=0||a>=i)return{error:"invalid_price_range",_instructions:"minPrice must be >= 0 (0 = full-range lower), maxPrice must be > 0, and minPrice must be strictly less than maxPrice."};if(l<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let u=ue(s);if(!u)return{error:"unsupported_chain",chain:s};let d=await this.pool.getGatewayAddress(s);if(!d)return{error:"no_gateway_configured",chain:s};let p=t?.walletAddress;if(!p)return{error:"wallet_not_connected"};let m=uo(s),g=BigInt(Math.floor(l*10**m.decimals));if(g<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let h=await this.pool.readPoolOnchain(s,n),[f,b]=await Promise.all([this.pool.readErc20Decimals(s,h.token0),this.pool.readErc20Decimals(s,h.token1)]),{minPrice:y,maxPrice:w}=no(a,i,h.currentPrice),k=y===0?rn:Ln(y,f,b),v=Ln(w,f,b),A=y===0?gt(ht(rn,h.tickSpacing,"up")):gt(ht(k,h.tickSpacing,"down")),S=gt(ht(v,h.tickSpacing,"up"));if(A>=S||A<rn||S>to)return{error:"invalid_range_after_alignment",_instructions:"After aligning to tickSpacing the range collapsed. Ask the user for a wider price range.",rawTickLower:k,rawTickUpper:v,tickLower:A,tickUpper:S};let C={tickLower:A,tickUpper:S,minPrice:fe(Qe(A,f,b)),maxPrice:fe(Qe(S,f,b))},O=h.currentTick;if(O<A||O>=S){let K=O<A?"below":"above";return{error:"out_of_range",_instructions:`The chosen price range does NOT include the pool's current price, so this would be an OUT-OF-RANGE position (it would sit entirely in one token and earn no fees until the price moves back into the range). The current price is ${K==="below"?"BELOW":"ABOVE"} the chosen range. Tell the user (in their language) that their range is out of range, show the current price and their chosen min/max, and ask them to pick a range that brackets the current price. Do NOT proceed with the transaction. Do NOT mention tool names.`,currentPrice:fe(h.currentPrice),requestedRange:{minPrice:C.minPrice,maxPrice:C.maxPrice},side:K}}let[_,H,q]=await Promise.all([this.pool.getNativeBalance(s,p),this.pool.estimateGasReserveWei(s),this.pool.getNativePriceUsd(s)]),$=g+H;if(_<$)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:_.toString(),requiredWei:$.toString(),gasReserveWei:H.toString()};let te=this.pool.splitNativeAmountForRange({nativeAmountWei:g,pool:h,tickLower:A,tickUpper:S,token0Decimals:f,token1Decimals:b}),nt=h.token0.toLowerCase()===se,he=h.token1.toLowerCase()===se,ne=[];if(nt||te.amountInFor0Wei===0n)ne.push({tokenIn:se,tokenOut:h.token0,amountIn:te.amountInFor0Wei,tx:{to:se,data:"0x",value:"0"},minAmountOut:nt?te.amountInFor0Wei:0n});else{let K=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:se,tokenInAmount:te.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:d,slippage:typeof c=="number"?c:"auto"});ne.push({tokenIn:se,tokenOut:h.token0,amountIn:te.amountInFor0Wei,tx:{to:K.to,data:K.data,value:K.value},minAmountOut:BigInt(K.minAmountOut||"0")})}if(he||te.amountInFor1Wei===0n)ne.push({tokenIn:se,tokenOut:h.token1,amountIn:te.amountInFor1Wei,tx:{to:se,data:"0x",value:"0"},minAmountOut:he?te.amountInFor1Wei:0n});else{let K=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:se,tokenInAmount:te.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:d,slippage:typeof c=="number"?c:"auto"});ne.push({tokenIn:se,tokenOut:h.token1,amountIn:te.amountInFor1Wei,tx:{to:K.to,data:K.data,value:K.value},minAmountOut:BigInt(K.minAmountOut||"0")})}let be=K=>K*BigInt(this.mintMinPercent)/100n,ve=be(ne[0].minAmountOut),Dn=be(ne[1].minAmountOut),Ho=ne.map(K=>({tokenIn:K.tokenIn,tokenInAmount:BigInt(K.amountIn),tokenOut:K.tokenOut,tokenOutAmount:BigInt(K.minAmountOut)})),Vo=ne.map(K=>({to:K.tx.to,data:K.tx.data,value:BigInt(K.tx.value||"0")})),Wo=D({abi:dl,functionName:"mint",args:[Ho,Vo,{fee:Number(h.fee),amount0Min:BigInt(ve),amount1Min:BigInt(Dn),tickLower:A,tickUpper:S}]}),Mn=l,Et={chainId:s,to:d,data:Wo,value:g.toString(),from:p},dn={nativeIn:Mn,nativeSymbol:m.symbol,nativeInUsd:q!=null?Mn*q:null,ratio:{token0Percent:te.ratio0,token1Percent:te.ratio1},expectedToken0:Number(ne[0].minAmountOut)/10**f,expectedToken1:Number(ne[1].minAmountOut)/10**b,amount0Min:ve.toString(),amount1Min:Dn.toString(),slippageBps:c},_t=await this.pantograph.getTokensMetadata([h.token0,h.token1],s),pn=_t[h.token0],wt=_t[h.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:s,name:u.name},unsignedTx:Et,summary:dn,pool:{...h,feePercent:h.fee/1e4,currentPrice:fe(h.currentPrice),token0:{address:h.token0,symbol:pn?.auditGoplus?.token_symbol||pn.symbol,name:pn.name,decimals:pn.decimals,logo:pn.icon_image},token1:{address:h.token1,symbol:wt?.auditGoplus?.token_symbol||wt.symbol,name:wt.name,decimals:wt.decimals,logo:wt.icon_image}},range:C,gatewayAddress:d}},summary:`Ready to add ${Mn} ${m.symbol} to pool ${h.token0}/${h.token1} ${h.fee/1e4}% on ${u.name}, range [${C.minPrice}, ${C.maxPrice}].`,_instructions:"A confirmation panel has been opened on the FE; the user will sign and broadcast the unsigned tx with their wallet. Briefly tell them (in their language) what is about to happen \u2014 the native amount, the auto-split ratio between the two pool tokens, and the chosen price range. Do NOT mention internal tool/component names."}}};var Lf=365,Of=1e3,Df=/^0x[a-fA-F0-9]{40}$/;function Mf(r,e){return{depositUsd:r,aprPercent:e*100,dailyUsd:r*e/Lf,weeklyUsd:r*e/52,monthlyUsd:r*e/12,yearlyUsd:r*e}}var wo=class extends P{name="estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap V3 pool. Answers questions like: "If I put $1000 into the USDC/WETH 0.05% pool, how much per day?", "b\u1ECF 500$ v\xE0o pool ETH/USDC 0.3% m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "APR of WBTC/ETH 0.3% on Arbitrum". BEHAVIOR (designed to minimize back-and-forth with the user):
|
|
202
|
+
}`,r=await this.querySubgraph(t,n);if(!r?.position?.pool)return null;let s=r.position,a=this.mapPool(s.pool,t),i=await this.fetchDefiLlamaUniswap(),l=i.length>0?this.enrichWithLlama([a],i)[0]:a,c=l.feeTierBps,d=l.feeTierPercent;return{position:{positionId:s.id,poolAddress:l.poolAddress,pair:l.pair,token0:{symbol:l.token0.symbol,address:l.token0.address},token1:{symbol:l.token1.symbol,address:l.token1.address},feeTierBps:c,feeTierPercent:d,chain:l.chain,liquidity:s.liquidity,depositedToken0:s.depositedToken0,depositedToken1:s.depositedToken1,withdrawnToken0:s.withdrawnToken0,withdrawnToken1:s.withdrawnToken1,collectedFeesToken0:s.collectedFeesToken0,collectedFeesToken1:s.collectedFeesToken1},pool:l}}async getCoinPoolPairs(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchCoinPoolV2Items(t)).map(s=>this.mapCoinPoolV2Item(s)).filter(s=>s!==null);if(e.tokens&&e.tokens.length>=2){let s=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase();r=r.filter(i=>{let[l="",c=""]=i.pair.toUpperCase().split("/");return l.includes(s)&&c.includes(a)||l.includes(a)&&c.includes(s)})}return r}async getCoinPoolByAddress(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(s=>s.poolId?.toLowerCase()===n).map(s=>this.mapCoinPoolV2Item(s)).filter(s=>s!==null).sort((s,a)=>(a.apr??-1/0)-(s.apr??-1/0))}async fetchCoinPoolV2Items(e){if(!this.coinPoolBaseUrl)return[];try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(_(n));return n.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=A=>A==null||!Number.isFinite(A)?0:Math.pow(1.0001,A)*Math.pow(10,t-n),s=r(e.minTick),a=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,d=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),u=d?s:a>0?1/a:0,p=d?a:s>0?1/s:0,m=d?c:c>0?1/c:0,f=d?e.token0.symbol:e.token1.symbol,h=d?e.token1.symbol:e.token0.symbol;if(!m||!u&&!p)return null;let g=Math.min(u,p),b=Math.max(u,p);if(m<g||m>b)return null;let y=Number(e.fee),w=Md[y]??y/1e4,k=W(e.apr)??W(e.aprAvg)??null,v=W(e.aprAvg)??null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:v,token0Price:i,token1Price:l,priceRange:{minPrice:Pe(u),maxPrice:Pe(p),currentPrice:Pe(m),baseToken:f,quoteToken:h}}}};var mn=class{config;constructor(e){this.config=e}withRoute(e){let t=Object.create(this);return t.getQuote=n=>this.getQuote({route:e,...n}),t}};var St=class{constructor(e,t=Number.POSITIVE_INFINITY){this.loader=e;this.ttlMs=t}loader;ttlMs;value=null;loadedAt=0;inFlight=null;async get(){return this.value!==null&&Date.now()-this.loadedAt<this.ttlMs?this.value:this.inFlight?this.inFlight:(this.inFlight=(async()=>{try{let e=await this.loader();return e!==null&&(this.value=e,this.loadedAt=Date.now()),e}catch{return this.value}finally{this.inFlight=null}})(),this.inFlight)}};var Ig="https://api.relay.link";function Fd(o){return o===7565164||o==="7565164"?792703809:o}var fr=class extends mn{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Ig,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c}=e,d=await hn.getAffiliateFee(this.getProviderName(),t,e.route),u={user:i||l,originChainId:Fd(t),destinationChainId:Fd(s),originCurrency:n,destinationCurrency:a,amount:r,recipient:i||l,tradeType:"EXACT_INPUT"};d&&(u.appFees=[{recipient:d.affiliateFeeRecipient,fee:Math.floor(d.affiliateFeePercent*100)}]),typeof c=="number"&&Number.isFinite(c)&&(u.slippageTolerance=Math.floor(c*100).toString());try{let p=await this.request("/quote/v2","POST",u);if(!p||p.error)return{success:!1,error:p?.error??"Unknown error",errorMessage:p?.message??"Failed to fetch quote from Relay"};let m=(p.steps??[]).filter(y=>y.id==="approve"),f=p.steps?.find(y=>y.id==="swap"||y.id==="deposit"),h=f?.items?.[0]?.data,g=Array.isArray(h?.instructions);return{success:!0,provider:"relay",tx:h?g?{data:{instructions:h.instructions??[],addressLookupTableAddresses:h.addressLookupTableAddresses??[]},chainId:h.chainId}:{from:h.from,to:h.to,data:h.data,value:h.value,chainId:h.chainId,gas:h.gas,maxFeePerGas:h.maxFeePerGas,maxPriorityFeePerGas:h.maxPriorityFeePerGas}:null,isCrossChain:t!==s,srcChainId:t,dstChainId:s,raw:{steps:p.steps,fees:p.fees,details:p.details,approveSteps:m,requestId:f?.requestId}}}catch(p){return{success:!1,error:p,errorMessage:p instanceof Error?p.message:"Failed to fetch quote"}}}async checkApproval(e){let t=e.quoteData?.raw,r=(t?.approveSteps??(t?.approveStep?[t.approveStep]:[])).map(s=>s.items?.[0]?.data).filter(s=>!!s?.to&&typeof s.data=="string").map(s=>({to:s.to,from:s.from,data:s.data,value:s.value??"0",chainId:s.chainId,gas:s.gas,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas}));return r.length>0?{isNeeded:!0,integrated:!0,approvals:r,approvalData:r[0],contractAddress:r[0].to,message:r.length>1?`${r.length} approval steps are included in the quote and run first, in order.`:"Approval step is included in quote and will be executed first."}:{isNeeded:!1,integrated:!0,approvals:[],message:"No approval needed or already approved"}}async trackTransaction(e){try{let n=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return n==="success"||n==="refunded"?{success:!0,status:"COMPLETED"}:n==="failure"||n==="expired"?{success:!0,status:"FAILED"}:{success:!0,status:"PENDING"}}catch(t){return{success:!1,status:"ERROR",error:t instanceof Error?t.message:String(t)}}}async request(e,t,n){let r={"Content-Type":"application/json"};this.apiKey&&(r["x-api-key"]=this.apiKey);let s=`${this.apiBaseUrl}${e}`,a;if(t==="GET"&&n){let l=Object.entries(n).map(([c,d])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`).join("&");s=`${s}?${l}`}else t==="POST"&&n&&(a=n);let i=await x.request(t,s,a,{headers:r});if(!i.ok)throw new Error(_(i));return i.data}};var Ug="https://api.coinpool.app/config/addresses",Dg="https://api.coinpool.app/config/bridgeProviderByChain",Bd="createPoolProxyV3",Og="nftPositionUniswap",Mg=/^0x[0-9a-fA-F]{40}$/,Os=class{addresses;providerMap;constructor(e=Ug,t=Dg){this.addresses=new St(async()=>(await x.get(e,{headers:{Accept:"application/json"}})).data?.data??null),this.providerMap=new St(async()=>(await x.get(t,{headers:{Accept:"application/json"}})).data?.data??null)}async getProviderByChain(e){let n=(await this.providerMap.get())?.[String(e)];return this.isProviderName(n)?n:null}async getGatewayAddress(e){return this.getAddress(Bd,e)}async getPositionManagerAddress(e){return this.getAddress(Og,e)}async getGatewayChains(){return this.listChainsWithAddress(Bd)}async getAddress(e,t){let n=await this.addresses.get();if(!n)return;let r=this.toDecimalChainKey(t);if(r)return this.firstAddress(n[e]?.[r])}async listChainsWithAddress(e){let t=(await this.addresses.get())?.[e];if(!t||typeof t!="object")return[];let n=[];for(let[r,s]of Object.entries(t)){let a=this.firstAddress(s);a&&Mg.test(a)&&n.push(r)}return n}firstAddress(e){let t=Array.isArray(e)?e[0]:e;return typeof t=="string"?t.trim():void 0}toDecimalChainKey(e){let t=e.trim();if(/^0x[0-9a-fA-F]+$/.test(t)){let n=Number.parseInt(t,16);return Number.isFinite(n)?String(n):null}return/^\d+$/.test(t)?t:null}isProviderName(e){return e==="debridge"||e==="relay"}},fn=new Os;var gr=class{async resolve(e){try{return await this.resolveProvider(e)??Ut}catch{return Ut}}toNumericChainId(e){if(e==null)return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}},yr=class extends gr{constructor(t=fn){super();this.config=t}config;route="pool";async resolveProvider({srcChainId:t}){let n=this.toNumericChainId(t);return n===null?null:this.config.getProviderByChain(n)}},br=class extends gr{constructor(t=hn){super();this.setting=t}setting;route="userSwap";async resolveProvider({srcChainId:t,dstChainId:n}){return this.setting.getBridgeProvider(t,n)}};var Ms=class{routers=new Map;constructor(e=[new yr,new br]){for(let t of e)this.routers.set(t.route,t)}async resolveProvider(e){return await this.routers.get(e.route)?.resolve(e)??Ut}},li=new Ms;var Fs=class{configOverride;routersOverride;cache=new Map;constructor(e,t){this.configOverride=e,this.routersOverride=t}get providers(){return this.configOverride??kr}get routers(){return this.routersOverride??li}async getService(e){let t=this.getServiceByProvider(await this.resolveProvider(e));return e.route?t.withRoute(e.route):t}getServiceByProvider(e){let t=this.cache.get(e);if(t)return t;let n=this.createService(e);return this.cache.set(e,n),n}resetCache(){this.cache.clear()}async resolveProvider(e){return this.routers.resolveProvider(e)}createService(e){let t=this.providers[e]??{};switch(e){case"debridge":return new vr(t);case"relay":return new fr(t);default:{let n=e;throw new Error(`Unknown swap provider: ${String(n)}`)}}}},wr=new Fs;var kr={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},Ut="relay";function ci(o,e){let t={...kr[o]??{},...e};for(let n of Object.keys(t))t[n]===void 0&&delete t[n];kr[o]=t,wr.resetCache()}var Fg="https://exchange-api.keyring.app/admin/setting?configs=others",Bg="https://api.relay.link/chains",qg="https://dln.debridge.finance/v1.0/supported-chains-info",$g=14400*1e3,Hg=300*1e3,Vg=new Set([728126428,7565164]),qd={relay:"relay",debridge:"deBridge"},Bs=class{setting;chainSupport;constructor(e=Fg){this.setting=new St(async()=>(await x.get(e,{headers:{Accept:"application/json"}})).data?.others??null,Hg),this.chainSupport=new St(async()=>this.fetchChainSupport(),$g)}async getBridgeProvider(e,t){let n=this.toChainKey(e),r=this.toChainKey(t??e),[s,a]=await Promise.all([this.setting.get(),this.chainSupport.get()]),i=this.normalizeProvider(s?.keyringV2?.bridgeProvider)??Ut;if(!n||!r||!a)return i;let l=this.requireChainKeys(s?.keyringV2,"debridge"),c=l.includes(n)||l.includes(r),d=a.debridge.has(n)&&a.debridge.has(r);return c&&d?"debridge":i}async getAffiliateFee(e,t,n="userSwap"){let r=await this.setting.get();if(!r)return null;let s=n==="pool"?this.resolveLegacyFee(r,e,t):this.resolveKeyringV2Fee(r,e,t);return!s.recipient||s.percent<=0?null:{affiliateFeeRecipient:s.recipient,affiliateFeePercent:s.percent}}resolveLegacyFee(e,t,n){return t==="debridge"?{recipient:this.parseRecipientMap(e.affiliateRecipient)?.[String(n)],percent:this.toPercent(e.AFFILIATE_FEE_PERENT)}:{recipient:e.RELAY_AFFILIATE_FEE_RECIPIENT,percent:this.toPercent(e.RELAY_AFFILIATE_FEE_PERCENT)}}resolveKeyringV2Fee(e,t,n){let r=e.keyringV2;if(!r)return{recipient:void 0,percent:0};let s=r[qd[t]],a=String(n);return{percent:this.toPercent(s?.affiliateFeePercentCustom?.[a])||this.toPercent(s?.affiliateFeePercent),recipient:s?.affiliateRecipientCustom?.[a]||r.affiliateRecipientDefault}}parseRecipientMap(e){if(!e)return null;try{let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}async fetchChainSupport(){let[e,t]=await Promise.allSettled([x.get(Bg,{headers:{Accept:"application/json"}}),x.get(qg,{headers:{Accept:"application/json"}})]),n=new Set;if(e.status==="fulfilled")for(let s of e.value.data?.chains??[]){if(s?.vmType!=="evm")continue;let a=this.toChainKey(s.id);a&&n.add(a)}let r=new Set;if(t.status==="fulfilled")for(let s of t.value.data?.chains??[]){let a=s?.originalChainId??s?.chainId;if(a===void 0||Vg.has(a))continue;let i=this.toChainKey(a);i&&r.add(i)}return{relay:n,debridge:r}}requireChainKeys(e,t){return(e?.[qd[t]]?.requireChain??[]).map(r=>this.toChainKey(r)).filter(r=>r!==null)}normalizeProvider(e){if(typeof e!="string")return null;let t=e.toLowerCase();return t==="relay"?"relay":t==="debridge"?"debridge":null}toChainKey(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?String(e):null;let t=e.trim();if(!t)return null;let n=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(n)?String(n):null}toPercent(e){if(e==null)return 0;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}},hn=new Bs;function ui(o,e){return D({abi:V,functionName:"approve",args:[o,e]})}async function Wg(o,e,t,n,r){try{return await xe(o).call({account:t,to:e,data:ui(n,r)}),!0}catch(s){return Yg(s)?!1:null}}function Yg(o){let e=o?.name??"";if(e==="ContractFunctionRevertedError"||e==="CallExecutionError")return!0;let t=o instanceof Error?o.message.toLowerCase():String(o??"").toLowerCase();return t.includes("revert")||t.includes("execution reverted")||t.includes("invalid opcode")||t.includes("out of gas")}async function di({chain:o,token:e,owner:t,spender:n,amount:r,allowance:s}){let a=l=>({to:e,from:t,data:ui(n,l),value:"0"});return s!=null&&s>=r?[]:s===0n||!o?[a(r)]:await Wg(o,e,t,n,r)===!1?[a(0n),a(r)]:[a(r)]}var Gg="https://dln.debridge.finance/v1.0",Kg="0x0000000000000000000000000000000000000000",jg=new Set([429,500]),zg=5,Xg=1e3,Qg=o=>new Promise(e=>setTimeout(e,o)),vr=class extends mn{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Gg,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:d}=e,u=d??t!==s,p=await hn.getAffiliateFee(this.getProviderName(),t,e.route);try{if(u){let h={srcChainId:String(t),srcChainTokenIn:n,srcChainTokenInAmount:r,dstChainId:String(s),dstChainTokenOut:a,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:l,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent);let g=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,h);return g.error||g.errorMessage?{success:!1,error:g.error??g.errorMessage,errorMessage:g.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:g.tx,estimation:g.estimation,isCrossChain:!0,srcChainId:t,dstChainId:s,raw:g}}let m={chainId:String(t),tokenIn:n,tokenInAmount:r,tokenOut:a,tokenOutRecipient:i,accesstoken:this.accessToken};p&&(m.affiliateFeeRecipient=p.affiliateFeeRecipient,m.affiliateFeePercent=p.affiliateFeePercent),c!==void 0&&(m.slippage=c);let f=await this.get(`${this.apiBaseUrl}/chain/transaction`,m);return f.error||f.errorMessage?{success:!1,error:f.error??f.errorMessage,errorMessage:f.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:f.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:f}}catch(m){return{success:!1,error:m,errorMessage:m instanceof Error?m.message:"Failed to fetch quote"}}}async checkApproval(e){let{chain:t,userAddress:n,tokenAddress:r,amount:s}=e,a=e.quoteData?.tx?.to;if(!a)return{isNeeded:!1,error:"No contract address found in quote"};if(!r||r.toLowerCase()===Kg)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Native coin needs no approval."};let i;try{i=BigInt(s)}catch{i=0n}let l=await this.readAllowance(t,r,n,a);if(l!==null&&l>=i)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Sufficient allowance already granted."};let c=await di({chain:t,token:r,owner:n,spender:a,amount:i,allowance:l});return{isNeeded:!0,integrated:!1,approvals:c,approvalData:c[0],contractAddress:a,message:c.length>1?"Approval required: the standing allowance must be reset to 0 before the new one is granted.":l===null?"Could not read allowance; approval required before the swap.":"Approval required: current allowance is below the swap amount."}}async readAllowance(e,t,n,r){if(!e)return null;try{return await xe(e).readContract({address:t,abi:V,functionName:"allowance",args:[n,r]})}catch{return null}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let n=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!n.orderIds?.length)return{success:!1,status:"PENDING"};let r=n.orderIds[0];switch(((await this.get(`${this.apiBaseUrl}/dln/order/${r}/status`,{accesstoken:this.accessToken})).status??"").toUpperCase()){case"FULFILLED":case"SENTUNLOCK":case"CLAIMEDUNLOCK":return{success:!0,status:"COMPLETED"};case"ORDERCANCELLED":case"SENTORDERCANCEL":case"CLAIMEDORDERCANCEL":return{success:!0,status:"FAILED"};default:return{success:!0,status:"PENDING"}}}catch(n){return{success:!1,status:"ERROR",error:n instanceof Error?n.message:String(n)}}}async get(e,t){let n=Object.entries(t).map(([a,i])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(i))}`).join("&"),r=n?`${e}?${n}`:e,s=await x.get(r,{headers:{Accept:"application/json"}});for(let a=0;a<zg&&jg.has(s.status);a++)await Qg(Xg),s=await x.get(r,{headers:{Accept:"application/json"}});return s.data}};function $d(o){let e=o.raw??{},t=e.tokenOut?.amount??e.tokenOut?.minAmount??e.details?.currencyOut?.amount??e.details?.currencyOut?.minimumAmount??e.estimation?.dstChainTokenOut?.recommendedAmount??e.estimation?.dstChainTokenOut?.amount;return t&&/^\d+$/.test(t)?t:void 0}function Hd(o){if(o.errorMessage&&o.errorMessage.trim())return o.errorMessage.trim();let e=n=>{if(typeof n=="string"&&n.trim())return n.trim();if(n&&typeof n=="object"){let r=n;for(let s of[r.message,r.errorMessage,r.error])if(typeof s=="string"&&s.trim())return s.trim()}},t=o.raw??{};return e(o.error)??e(t.errorMessage)??e(t.error)??"The swap could not be quoted right now."}var Jg={1:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",10:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",56:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",137:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",143:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",1514:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",4326:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",4663:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",8453:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",42161:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",43114:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",59144:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",25:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",999:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",1776:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66"},Zg=[{inputs:[],name:"globalFixedNativeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}];function Vd(o){if(o==null)return null;if(typeof o=="number")return Number.isFinite(o)?String(o):null;let e=o.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)?String(t):null}async function pi(o){let{provider:e,srcChainId:t}=o,n=Vd(t),r=Vd(o.dstChainId??t);if(!n||!r||n===r||e!=="debridge")return 0n;let s=Jg[n];if(!s)return 0n;try{let a=await xe(n).readContract({address:s,abi:Zg,functionName:"globalFixedNativeFee"});return typeof a=="bigint"&&a>0n?a:0n}catch{return 0n}}var le="0x0000000000000000000000000000000000000000",Wd={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:Ge["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:Ge["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:Ge["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:Ge["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:Ge["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:Ge["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:Ge["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:Ge["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function we(o){return Wd[o.toLowerCase()]}function Tr(o){return we(o)?.native}var Yd="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function tc(o){let e=o.stableTicks??3,t=o.widePercent??{down:50,up:100},n=lt(o.currentTick,o.token0Decimals,o.token1Decimals),r=Pt(At(o.currentTick-e*o.tickSpacing,o.tickSpacing,"down")),s=Pt(At(o.currentTick+e*o.tickSpacing,o.tickSpacing,"up")),a=n*(1-t.down/100),i=n*(1+t.up/100),l=Wn(a,o.token0Decimals,o.token1Decimals),c=Wn(i,o.token0Decimals,o.token1Decimals),d=Pt(At(l,o.tickSpacing,"down")),u=Pt(At(c,o.tickSpacing,"up")),p=(m,f,h,g,b)=>{let y=lt(g,o.token0Decimals,o.token1Decimals),w=lt(b,o.token0Decimals,o.token1Decimals);return{id:m,label:f,description:h,tickLower:g,tickUpper:b,minPrice:y,maxPrice:w,minPercentChange:(y-n)/n*100,maxPercentChange:(w-n)/n*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",r,s),p("wide","Wide","Good for volatile pairs",d,u)]}var se=class{swapFactory;constructor(e){this.swapFactory=e?.swapFactory??wr}isSupported(e){if(!e)return!1;let t=M(e)??e.toLowerCase();return!!we(t)}listSupportedChains(){return Object.keys(Wd).filter(e=>Me(e))}getRpcUrl(e){let t=In(e);if(t)return t;let n=we(e);if(!n)throw new Error(`Unsupported chain: ${e}`);return n.defaultRpc}async getGatewayAddress(e){return fn.getGatewayAddress(e)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await fn.getGatewayChains(),t=[];for(let n of e){let r=M(n);r&&we(r)&&!t.includes(r)&&t.push(r)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return fn.getPositionManagerAddress(e)}client(e){return xe(e)}async ethCall(e,t,n){let{data:r}=await this.client(e).call({to:t,data:n});return r??"0x"}async getNativeBalance(e,t){return this.client(e).getBalance({address:t})}async getGasPrice(e){return this.client(e).getGasPrice()}async getTransactionReceipt(e,t){return this.client(e).rpc("eth_getTransactionReceipt",[t])}async extractMintedNftId(e,t){let n=await this.getPositionManagerAddress(e);if(!n)return null;let r=n.toLowerCase();for(let s of t.logs??[]){if((s.address??"").toLowerCase()!==r)continue;let a=s.topics??[];if(!(a.length<4||a[0]?.toLowerCase()!==Yd||"0x"+a[1].slice(-40).toLowerCase()!==le))try{return BigInt(a[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=we(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let n=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*n*18n/10n}async readPoolOnchain(e,t){let r={address:t,abi:_l},[s,a,i,l,c,d]=await this.client(e).multicall({contracts:[{...r,functionName:"slot0"},{...r,functionName:"liquidity"},{...r,functionName:"tickSpacing"},{...r,functionName:"fee"},{...r,functionName:"token0"},{...r,functionName:"token1"}],allowFailure:!1}),[u,p]=s,m=c.toLowerCase(),f=d.toLowerCase(),[h,g]=await Promise.all([this.readErc20Decimals(e,m),this.readErc20Decimals(e,f)]),b=Dd(u,h,g);return{poolAddress:t,chainId:e,fee:l,tickSpacing:i,liquidity:a,sqrtPriceX96:u,currentTick:p,token0:m,token1:f,currentPrice:b}}async readErc20Decimals(e,t){return t.toLowerCase()===le?18:this.client(e).readContract({address:t,abi:V,functionName:"decimals"})}async getNativePriceUsd(e){let t=we(e);if(!t)return null;try{let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,r=await x.get(n);if(!r.ok)return null;let a=r.data[t.native.coingeckoId]?.usd;return typeof a=="number"?a:null}catch{return null}}splitNativeAmountForRange(e){let{nativeAmountWei:t,pool:n,tickLower:r,tickUpper:s,token0Decimals:a,token1Decimals:i}=e,l=2**96,c=Number(n.sqrtPriceX96)/l,d=Math.pow(1.0001,r/2),u=Math.pow(1.0001,s/2);if(c<=d)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(c>=u)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let p=1/c-1/u,m=c-d,f=c*c,h=p*f,b=h+m;if(!Number.isFinite(b)||b<=0)throw new Error("splitNativeAmountForRange: invalid total value");let y=h/b,w=1-y,k=1000000000000000n,v=BigInt(Math.floor(y*Number(k))),A=t*v/k,S=t-A;return{ratio0:y,ratio1:w,amountInFor0Wei:A,amountInFor1Wei:S}}async fetchSwapLeg(e){let t=Number.parseInt(e.chainId,16);if(!Number.isFinite(t))throw new Error(`Invalid hex chain id: ${e.chainId}`);let r=await(await this.swapFactory.getService({route:"pool",srcChainId:t})).getQuote({srcChainId:t,srcTokenAddress:e.tokenIn,srcTokenAmount:e.tokenInAmount,dstChainId:t,dstTokenAddress:e.tokenOut,recipientAddress:e.tokenOutRecipient,senderAddress:e.senderAddress??e.tokenOutRecipient,slippage:e.slippage,isCrossChain:!1});if(!r.success||!r.tx)throw new Error(r.errorMessage??"Swap quote failed");let s=r.tx;if(!s.to||typeof s.data!="string")throw new Error("Swap quote returned an unsupported tx shape (non-EVM payload?)");let a=r.raw??{},i=a.tokenOut?.minAmount??a.details?.currencyOut?.minimumAmount??"0";return{to:s.to,data:s.data,value:s.value??"0",minAmountOut:i}}};var ey={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},ty=/^0x[a-fA-F0-9]{40}$/;function qs(o,e){if(typeof o!="string"||typeof e!="string")return null;let t=ey[o.toLowerCase()];return!t||!ty.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function ct(o,e){let t=qs(o,e);return t?{uniswapUrl:t}:{}}var Gd=Object.keys(un),Qe="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a, Linea=0xe708, Gnosis=0x64, HyperEVM=0x3e7, Mantle=0x1388, Monad=0x8f. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";function Ie(){return Gd.filter(o=>Me(o)).map(o=>T(o)).join(", ")}function Je(){return{kind:"info",async listSupported(){return Gd.filter(o=>Me(o))},async isSupported(o){if(!o)return!1;let e=M(o)??o.toLowerCase();return Object.prototype.hasOwnProperty.call(un,e)}}}function gn(o){return{kind:"add-liquidity",listSupported:()=>o.listAddLiquiditySupportedChains(),isSupported:e=>o.isAddLiquiditySupported(e)}}function nc(o,e,t){let n=r=>typeof r=="string"&&r.trim()!=="";if(n(o))return M(o)??o.trim();if(n(e?.chain))return M(e.chain)??e.chain.trim();if(n(e?.walletAddress))throw new fe(typeof e?.query=="string"?e.query:void 0,t);return je}async function Z(o,e,t){let n=await o.listSupported(),r=nc(e,t,n);return await o.isSupported(r)?{ok:!0,chain:r}:{ok:!1,result:oc(r,n,o.kind)}}function oc(o,e,t="info"){return{_instructions:`${t==="add-liquidity"?"Adding liquidity is NOT available on this network. Tell the user, in their language, that they cannot add liquidity / provide LP on this chain yet (note: viewing pool info may still work on other chains). Then name the chains where adding liquidity IS available":"Liquidity-pool data is NOT available on this network. Tell the user, in their language, that pools are not supported on this chain. Then name the chains where pools ARE available"} using EXACTLY and ONLY the entries in the \`supportedChains\` field below \u2014 copy them verbatim, add nothing. CRITICAL: this list is the complete, authoritative set. Do NOT add, infer, or invent ANY other chain \u2014 NOT EVEN a chain this app supports for wallet/token/DeFi features (for example Gnosis, HyperEVM, Mantle, and Monad are NOT pool chains; never list them unless they literally appear in \`supportedChains\`). Keep it short and friendly. Do NOT mention tools, services, APIs, forms, or any internals.`,unsupportedChain:T(o),supportedChains:e.map(r=>T(r))}}var mi="{pair}";var Ce=[{name:"add_button_label",type:"string",description:`Label template for the per-pool "Add liquidity" buttons that render under EVERY pool you show, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each pool automatically. Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:`A short "add liquidity" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a pool's button is clicked. ALWAYS provide it. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name or a pool address yourself \u2014 the pool address and the chain these pools are on are appended automatically as "(Pool: 0x\u2026 - <chain>)".`,required:!1}],ce=' A clickable "Add liquidity" button is shown below your reply for each pool automatically \u2014 do NOT list, number, or repeat those buttons in your text; just deliver your analysis.';function ue(o,e,t){return rc(o,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function rc(o,e,t,n){let r=typeof n=="string"?n.trim():"",s=[];for(let a of o){if(s.length>=5)break;let i=a.token0?.symbol?.trim(),l=a.token1?.symbol?.trim();if(!i||!l)continue;let c=oy(i,l,a.feeTierPercent);s.push({label:Kd(e,c,`Add liquidity to ${mi}`),prompt:Kd(t,c,`add liquidity to ${mi}`)+ny(a.address,r)})}return s}function ny(o,e){let n=[typeof o=="string"&&o.trim()?`Pool: ${o.trim()}`:"",e].filter(Boolean);return n.length>0?` (${n.join(" - ")})`:""}function oy(o,e,t){let n=`${o}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${n} ${ry(t)}%`:n}function ry(o){return Number(o.toFixed(4)).toString()}function Kd(o,e,t){return(o&&o.includes(mi)?o:t).split(mi).join(e).replace(/\s+/g," ").trim()}var de="You are a seasoned DEX liquidity-pool analyst with deep, credible expertise. Deliver a genuinely insightful, professional read \u2014 the kind a sophisticated LP would pay for \u2014 in natural, flowing prose rather than a rigid template, never sacrificing depth or authority for a conversational tone. ",pe='Ground every judgement rigorously in the data, never guesses \u2014 and only use a signal when its data is present: \u2022 capital efficiency = `volumeToTvlRatio` (volume \xF7 TVL) \u2014 higher means each $ of liquidity earns more fees; >1 is very active, <0.1 is sluggish. \u2022 APR quality \u2014 a very high APR sitting on a TINY TVL is usually volatile/unsustainable (treat with caution); a solid APR on deep TVL is the sweet spot. When an APR field is ABSENT there is no yield reading for that pool: say nothing about its APR \u2014 never print "APR 0%", "APR: N/A", a dash, or infer the yield from other fields. Judge such a pool on its remaining metrics alone. \u2022 TVL trend \u2014 when a 24h TVL % change is present, note whether liquidity is growing or shrinking. \u2022 TVL depth \u2014 deeper pools = lower slippage and a steadier position; thin pools carry higher risk. \u2022 fee tier vs pair type \u2014 stable/correlated pairs suit low tiers (0.01\u20130.05%), volatile pairs suit higher tiers (0.3\u20131%). \u2022 token safety \u2014 when a token exposes isSpam=true or a non-VERIFIED safetyLevel, FLAG it prominently as a risk. \u2022 transfer tax \u2014 when a token exposes transferFeeBps, it charges that tax (in basis points: 200 = 2%) on transfers. FLAG it prominently: it eats directly into LP returns, and a high or one-sided tax is a common honeypot trait. \u2022 unrecognized token \u2014 when a token exposes isUnrecognizedToken=true, Uniswap does not know that contract at all. Treat this as a SEVERE warning, stronger than any safetyLevel: a token wearing a well-known ticker (WBTC, USDC\u2026) on a contract Uniswap cannot identify is most likely an impostor. Say so plainly and advise verifying the contract address before providing any liquidity. ',ye="Give a clear one-line worthiness verdict for LPs (e.g. a \u2B50 rating or High / Medium / Low attractiveness), woven naturally into the prose rather than tacked on as a fixed label. ",G="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",z=`LINKS \u2014 write every pool pair as PLAIN TEXT only (e.g. "USDC/WETH"). Do NOT create markdown links, do NOT output any URLs, and do NOT print raw pool or token contract addresses anywhere in your answer. The system automatically turns each pool's pair into the correct clickable link after you reply, so you must NEVER add a link, a "Link to pool" line, a "View on Uniswap" line, or a bare URL yourself \u2014 doing so produces wrong/duplicate links. Just name each pair in text. Format numbers human-readably (e.g. $12.5M, +1.23%, 0.05%). Omit null fields. Answer in the user's language. Do NOT mention tool or API names.`;var sy=["tvl","volume1Day","volume30Day","apr"],ay=["V2","V3","V4"],Ar=class extends P{name="uniswap-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens (symbol, name, address, decimals), TVL, rolling volume (1d / 30d), and estimated APR. Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap V3 pools on Base", "which pool has the most liquidity for USDC", "show pools with highest 24h volume on Arbitrum". Source: https://app.uniswap.org/explore (ListPools gateway). Supports: `+Ie();category="blockchain-data";parameters=[{name:"chain",type:"string",description:Qe,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", or "V4". Default is "V3" (the dataset with the richest stats). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume30Day", or "apr" (estimated annualized fee yield, net of the protocol fee). Pools are returned in descending order by this metric.',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"multichain",type:"boolean",description:"When true, request Uniswap's multichain aggregated view instead of a single chain. Defaults to false. Most queries should leave this off.",required:!1,default:!1},{name:"forAddLiquidity",type:"boolean",description:'Set TRUE only when this ranking is the ENTRY POINT of the ADD-LIQUIDITY flow \u2014 the user wants to add / provide liquidity ("add pool", "i want to add liquidity", "th\xEAm thanh kho\u1EA3n") but named NO specific pool, so you show top pools (use sortBy="apr") for them to pick one. In that mode the tool gates on ADD-LIQUIDITY chain support (only chains with a gateway) and, when the connected chain has no gateway, returns the "adding liquidity is not available on this chain" message with the correct supported list \u2014 so the user is told up front, not after picking a pool. OMIT (false) for ordinary informational rankings ("top pools on Base", "biggest pools").',required:!1,default:!1},...Ce];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new Be(e),this.subgraphFallback=new Se(t),this.pool=new se}async run(e,t){let n=e.forAddLiquidity===!0,r=n?gn(this.pool):Je(),s=await r.listSupported(),a=nc(e.chain,t,s),i=this.parseProtocolVersion(e.protocolVersion),l=this.parseSortKey(e.sortBy),c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=!n&&e.multichain===!0;if(!d&&!await r.isSupported(a))return oc(a,s,r.kind);let u=await this.service.getTopPools({chain:a,protocolVersion:i,sortBy:l,limit:c,multichain:d});if(!u.success)return{error:u.error||"Failed to fetch top pools"};let p=(u.data??[]).map(w=>this.formatPool(w)),m="uniswap";if(p.length===0&&i==="V3"){let w=await this.fetchV3Fallback(a,l,c);w.length>0&&(p=w,m="subgraph")}let f=p.map(w=>this.withExpertSignals(w)),h=await this.pool.isAddLiquiditySupported(a)?ue(f,e,T(a)):[],g=m==="subgraph",b=g?`"Volume past day" (translate naturally into the user's language; NEVER call it "24h volume", "daily volume", or "24h")`:"24h volume";return{_instructions:(g?`BEGIN your answer with "According to the latest data from Subgraph Uniswap V3," (translate the sentence naturally into the user's language but keep the word "Subgraph" as-is). `:"")+de+`You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, ${b}, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. `+pe+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+ye+G+"Mention the chain and the sort metric in the intro line. "+z+(h.length>0?ce:""),chain:a,protocolVersion:i,sortBy:l,source:m,count:f.length,pools:f.map(w=>({...w,...ct(a,w.address)})),...h.length>0?{actionButtons:h}:{}}}withExpertSignals(e){let t=a=>Math.round(a*1e3)/1e3;if(typeof e.volumeToTvlRatio=="number"&&Number.isFinite(e.volumeToTvlRatio))return{...e,volumeToTvlRatio:t(e.volumeToTvlRatio)};let n=e.tvlUsd,r=e.volume1DayUsd,s=typeof n=="number"&&n>0&&typeof r=="number"?t(r/n):void 0;return{...e,volumeToTvlRatio:s}}async fetchV3Fallback(e,t,n){try{return(await this.subgraphFallback.getTrendingPools({chain:e})).map(i=>this.formatSubgraphPool(i,e)).sort((i,l)=>this.fallbackSortValue(l,t)-this.fallbackSortValue(i,t)).slice(0,n)}catch{return[]}}fallbackSortValue(e,t){switch(t){case"apr":return e.apr??0;case"volume1Day":case"volume30Day":return e.volume1DayUsd??0;default:return e.tvlUsd??0}}formatSubgraphPool(e,t){return{apr:W(e.apr),totalApr:void 0,address:e.poolAddress,chain:t,protocolVersion:"V3",feeTierBps:e.feeTierBps,feeTierPercent:typeof e.feeTierBps=="number"?e.feeTierBps/1e4:void 0,tvlUsd:e.tvl,fee24hUsd:e.fees24hUsd,volume1DayUsd:e.volume24hUsd,volume1WeekUsd:void 0,volume30DayUsd:void 0,volumeToTvlRatio:void 0,txCount:void 0,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0}}parseProtocolVersion(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(ay.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(sy.includes(t))return t}return"tvl"}formatPool(e){let t=e.isDynamicFee===!0||cn(e.feeTier);return{apr:W(e.apr),totalApr:typeof e.totalApr=="number"&&typeof e.apr=="number"&&e.totalApr>e.apr?e.totalApr:void 0,address:e.id,chain:e.chain,protocolVersion:e.protocolVersion,feeTierBps:t?void 0:e.feeTier,feeTierPercent:!t&&typeof e.feeTier=="number"?e.feeTier/1e4:void 0,...t?{isDynamicFee:!0}:{},tvlUsd:e.totalLiquidity?.value,fee24hUsd:e.fee24hUsd,volume1DayUsd:e.volume1Day?.value,volume1WeekUsd:e.volume1Week?.value,volume30DayUsd:e.volume30Day?.value,volumeToTvlRatio:e.volumeToTvlRatio,txCount:e.txCount,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.price?.value,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.price?.value,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}};var sc={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},iy={100:.01,500:.05,3e3:.3,1e4:1},yn=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=M(e);return!!(t&&sc[t])}listSupportedChains(){return Object.keys(sc).filter(e=>M(e)===e)}numericChainId(e){let t=M(e);return t?sc[t]:void 0}async getPairs(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchV2Items(t)).map(s=>this.mapV2Item(s)).filter(s=>s!==null);if(e.tokens&&e.tokens.length>=2){let s=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase(),i=(l,c)=>l.includes(c)||c.includes(l);r=r.filter(l=>{let[c="",d=""]=l.pair.toUpperCase().split("/");return i(c,s)&&i(d,a)||i(c,a)&&i(d,s)})}return r}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(s=>s.poolId?.toLowerCase()===n).map(s=>this.mapV2Item(s)).filter(s=>s!==null).sort((s,a)=>(a.apr??-1/0)-(s.apr??-1/0))}async fetchV2Items(e){try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(_(n));return n.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=A=>A==null||!Number.isFinite(A)?0:Math.pow(1.0001,A)*Math.pow(10,t-n),s=r(e.minTick),a=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,d=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),u=d?s:a>0?1/a:0,p=d?a:s>0?1/s:0,m=d?c:c>0?1/c:0,f=d?e.token0.symbol:e.token1.symbol,h=d?e.token1.symbol:e.token0.symbol;if(!m||!u&&!p)return null;let g=Math.min(u,p),b=Math.max(u,p);if(m<g||m>b)return null;let y=Number(e.fee),w=iy[y]??y/1e4,k=W(e.apr)??W(e.aprAvg)??null,v=W(e.aprAvg)??null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:v,token0Price:i,token1Price:l,priceRange:{minPrice:Pe(u),maxPrice:Pe(p),currentPrice:Pe(m),baseToken:f,quoteToken:h}}}};function ly(o){if(!(!o||o.length===0))return o.map(e=>({timestamp:e.timestamp,volumeUsd:e.value}))}function cy(o,e){if(!(typeof o!="number"||typeof e!="number"||e<=0))return Math.round(o/e*1e3)/1e3}function Yn(o,e){let t=e!==void 0&&Array.from(e.values()).some(i=>i.safetyLevel!=null),n=o.totalLiquidity?.value,r=o.volume24h?.value,s=o.feeTier,a=ri(s,o.protocolFee,o.protocolVersion);return{address:o.address??o.poolId,protocolVersion:o.protocolVersion,poolId:o.poolId,tickSpacing:o.tickSpacing,isDynamicFee:o.isDynamicFee,hookAddress:o.hook?.address,feeTierBps:s,feeTierPercent:typeof s=="number"?s/1e4:void 0,tvlUsd:n,tvlChange24hPercent:o.totalLiquidityPercentChange24h?.value,volume24hUsd:r,fees24hUsd:si(r,s,a),lpFeeShare:a,aprPercent:W(o.apr),totalAprPercent:W(o.totalApr),volumeToTvlRatio:cy(r,n),txCount:o.txCount,historicalVolumeWeek:ly(o.historicalVolume),token0:jd(o.token0,o.token0Supply,e,t),token1:jd(o.token1,o.token1Supply,e,t)}}function jd(o,e,t,n){if(!o)return;let r=o.address?t?.get(o.address.toLowerCase()):void 0,s=n&&o.address!=null&&!r?.safetyLevel,a=r?.isSpam==null?void 0:r.isSpam.toUpperCase()==="TRUE",i=Number(r?.feeData?.buyFeeBps??0),l=Number(r?.feeData?.sellFeeBps??0),c=Number.isFinite(i)&&Number.isFinite(l)?Math.max(i,l):0;return{address:o.address,symbol:o.symbol,name:o.name,decimals:o.decimals,priceUsd:o.market?.price?.value??o.price?.value,reserve:e,isSpam:a??o.project?.isSpam??void 0,safetyLevel:r?.safetyLevel??o.project?.safetyLevel??void 0,transferFeeBps:c>0?c:void 0,isUnrecognizedToken:s||void 0}}var zd=/^0x[a-fA-F0-9]{40}$/,uy=6,Pr=class extends P{name="uniswap-pool-detail";description="Get detailed stats for a Uniswap V3 pool by token pair (and optional fee tier). Always runs a search first and filters by the provided symbols + fee tier. When the filter resolves to exactly one pool, returns its full detail. When the pair is fully named but NO fee tier is given, returns detail plus a comparative analysis of ALL the pair's fee-tier variants (no need to ask the user to pick). When only one token is given (so the matches are different pairs), returns a `candidates` list \u2014 show it and ask which pair they want, then re-call this tool with the missing info. Detail response includes: pool address, fee tier (bps and %), both tokens (symbol, name, address, decimals, USD price), token0/token1 reserves, total TVL with 24h % change, 24h volume, weekly historical volume series, total tx count, and the pool's fee APR (net of the protocol fee). NEVER pass a pool address \u2014 the tool resolves the address itself by searching. Token contract addresses are NOT pool addresses. Source: https://app.uniswap.org. Supports: "+Ie();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter \u2014 USDC/WETH and WETH/USDC resolve to the same pool. When both token0Symbol and token1Symbol are provided the search is filtered to that exact pair.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 when omitted the tool returns all pools containing token0Symbol so the user can pick.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points (bps): 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. "USDC/WETH 0.05%" \u2192 feeTier=500). NEVER guess or infer one. When the user has not mentioned a fee tier, OMIT it \u2014 the tool then returns detail plus a comparative analysis of ALL fee-tier variants of the pair (no need to ask the user to pick one).',required:!1},{name:"chain",type:"string",description:Qe,required:!1},...Ce];service;coinPool;pool;constructor(e,t){super(),this.service=new Be(e),this.coinPool=new yn(t),this.pool=new se}async run(e,t){let n=await Z(Je(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0;if(!s)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let l=a?`${s} ${a}`:s,c=await this.service.searchPools({query:l,chain:r,page:1,size:100,protocolVersion:"V3"});if(!c.success)return{error:c.error||"Pool search failed"};let d=c.data??[],p=d.filter(g=>this.matchesFilter(g,s,a,i,"ordered")),m=!1;if(p.length===0&&a){let g=d.filter(b=>this.matchesFilter(b,s,a,i,"reversed"));g.length>0&&(p=g,m=!0)}if(p.length===0)return{error:`No V3 pool matched ${this.describeQuery(s,a,i)} on ${T(r)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!zd.test(g.id))return{error:"Resolved pool has no valid address"};let[b,y,w]=await Promise.all([this.service.getPoolDetailEnriched({addressOrId:g.id,chain:r}),this.fetchPriceRanges(r,g.id,g.token0?.symbol,g.token1?.symbol),this.service.getTokenSafetyByAddress([g.token0?.address,g.token1?.address],r)]);if(!b.success||!b.data)return{error:b.error||"Failed to fetch pool detail"};let k={...Yn(b.data,w),...ct(r,g.id)},v=await this.pool.isAddLiquiditySupported(r)?ue([k],e,T(r)):[];return{priceRanges:y,_instructions:de+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, token1 reserve + USD price, and total tx count. Optionally include the weekly historical volume as a sparkline-style bullet list. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+pe+ye+'PRICE RANGES: when `priceRanges` is a non-empty array, add a "Suggested price ranges" section listing each candidate \u2014 fee tier (`fee`), the min\u2013max range (`priceRange.minPrice`\u2013`priceRange.maxPrice` in baseToken/quoteToken units), the current price (`priceRange.currentPrice`), and its `apr` \u2014 omitting the APR for any entry whose `apr` is null/absent (never "APR 0%", "N/A" or a dash). CRITICAL: that `apr` is the yield for THAT specific range only \u2014 NEVER present it as the overall pool APR. Sort by apr desc; note the top entry is the most concentrated/highest-yield range but narrower = higher risk of going out of range. When `priceRanges` is empty or absent, simply omit this section. '+G+z+(v.length>0?ce:""),pairOrderMatched:m?"reversed":"ordered",pool:k,...v.length>0?{actionButtons:v}:{}}}if(a){let g=this.rankCandidates(p).slice(0,uy),[b,y]=await Promise.all([Promise.all(g.map(async k=>{if(!k.id||!zd.test(k.id))return;let v=await this.service.getPoolDetailEnriched({addressOrId:k.id,chain:r});if(!(!v.success||!v.data))return{detail:v.data,id:k.id}})),this.service.getTokenSafetyByAddress(g.flatMap(k=>[k.token0?.address,k.token1?.address]),r)]),w=b.filter(k=>k!=null).map(k=>({...Yn(k.detail,y),...ct(r,k.id)}));if(w.length>0){let k=await this.pool.isAddLiquiditySupported(r)?ue(w,e,T(r)):[];return{_instructions:de+"The user named a pair WITHOUT a fee tier, so here is EVERY fee-tier variant of that pair \u2014 do NOT ask them to pick a tier. Present them as a ranked list (rank them by capital efficiency / fee yield, not just TVL). For each variant show the fee tier (%), TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), and tx count. Analyze every variant \u2014 give each its own genuine read, never skip one, and never repeat the same sentence structure. "+pe+"Focus on which fee tier is the right home for THIS pair: lower tiers (0.01\u20130.05%) win on stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 and the tier that actually captures most of the real volume with deep TVL is usually the one to LP in. Close with an overall section naming the single best fee tier to provide liquidity in right now and why. "+ye+G+z+(k.length>0?ce:""),chain:r,pairOrderMatched:m?"reversed":"ordered",multiFeeTier:!0,count:w.length,pools:w,...k.length>0?{actionButtons:k}:{}}}}let f=this.rankCandidates(p).slice(0,10).map(g=>{let b=this.formatCandidate(g);return{...b,...ct(r,b.address)}}),h=await this.pool.isAddLiquiditySupported(r)?ue(f,e,T(r)):[];return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume) and ask the user which one they want to see. Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. When they answer, re-call this tool with their selection \u2014 pass token0Symbol + token1Symbol + feeTier (use the exact feeTier in bps from the chosen candidate). Format numbers human-readably (e.g. $12.5M, 0.05%). Do NOT mention tool/API names."+(h.length>0?ce:""),chain:r,pairOrderMatched:m?"reversed":"ordered",reason:this.candidateReason(s,a,i),missing:this.missingFields(a,i),candidates:f,...h.length>0?{actionButtons:h}:{}}}matchesFilter(e,t,n,r,s){if(r!=null&&e.feeTier!==r)return!1;let a=(e.token0?.symbol??"").toLowerCase(),i=(e.token1?.symbol??"").toLowerCase(),l=t.toLowerCase();if(n){let c=n.toLowerCase();return s==="reversed"?this.symbolIncludes(a,c)&&this.symbolIncludes(i,l):this.symbolIncludes(a,l)&&this.symbolIncludes(i,c)}return this.symbolIncludes(a,l)||this.symbolIncludes(i,l)}symbolIncludes(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at fee tier ${n} bps`:r}candidateReason(e,t,n){return t?n==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${n} bps. Ask the user which one they meant.`:`Multiple pools contain ${e}. Ask the user for the other token (and fee tier).`}missingFields(e,t){let n=[];return e||n.push("token1Symbol"),t==null&&n.push("feeTier"),n}rankCandidates(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}formatCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&n&&r&&(s=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}};var dy=["V2","V3","V4","ALL"],Sr=class extends P{name="uniswap-search-pools";description='Search Uniswap liquidity pools on a given chain by free-text query \u2014 a SINGLE token symbol or token name. Returns matching pools with: pool address, fee tier (bps + %), protocol version, both tokens (symbol, name, address, decimals, logo), and short-window USD volume buckets (6h / 12h / 24h). Use this tool when the user names ONE token and wants pools related to it: "find WBTC pools on Optimism", "pools containing PEPE on Ethereum", "show USDC pools". Do NOT use for: (a) two-symbol pair lookups like "USDC/WETH 0.05%" \u2014 use get-pool-detail; (b) raw 0x addresses (token or pool) \u2014 use lookup-pool-by-address; (c) chain-wide rankings with no token mentioned \u2014 use get-top-pools. Source: https://app.uniswap.org search. Supports: '+Ie();category="blockchain-data";parameters=[{name:"query",type:"string",description:'Single token symbol or name to search pools by (e.g. "WBTC", "USDC", "pepe"). Do NOT pass a 0x address (use lookup-pool-by-address) or a two-symbol pair (use get-pool-detail).',required:!0},{name:"chain",type:"string",description:Qe,required:!1},{name:"protocolVersion",type:"string",description:'Filter results by Uniswap protocol version: "V2", "V3", "V4", or "ALL" to include every version. Default is "V3" \u2014 only switch when the user explicitly asks for V2, V4, or all versions.',required:!1,default:"V3"},{name:"page",type:"number",description:"1-based page index. Defaults to 1.",required:!1,default:1},{name:"size",type:"number",description:'Page size (max 50). Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"feeTier",type:"number",description:'Optional fee tier filter in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. When provided, only pools with this exact fee tier are returned. Pass it whenever the user mentions a fee tier in the current message OR earlier in the conversation (e.g. "USDC/WETH 0.05% pool on Base" \u2192 feeTier=500). Omit otherwise.',required:!1},...Ce];service;pool;constructor(e){super(),this.service=new Be(e),this.pool=new se}async run(e,t){let n=typeof e.query=="string"?e.query.trim():"";if(!n)return{error:"Search query is required"};let r=await Z(Je(),e.chain,t);if(!r.ok)return r.result;let s=r.chain,a=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,i=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):5,l=this.parseProtocolFilter(e.protocolVersion),c=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,d=await this.service.searchPools({query:n,chain:s,page:a,size:i,protocolVersion:l,feeTier:c});if(!d.success)return{error:d.error||"Failed to search pools"};let u=(d.data??[]).map(m=>this.formatPool(m)),p=await this.pool.isAddLiquiditySupported(s)?ue(u,e,T(s)):[];return{_instructions:de+"Present the pools that match the search AND give an expert read on each. Render each pool as its own block: a bold header with the pair (token0/token1 symbols) + fee tier (%), then beneath it the metrics that have data \u2014 TVL (USD), 24h volume (USD), APR (%), tx count, protocol version. Skip any field that is null/undefined \u2014 never show zeros or dashes for missing data. Then add an expert read on each pool \u2014 is it worth providing liquidity in, and why. "+pe+ye+"When several pools share the searched token, finish with a clear TOP PICK among them. "+G+"Mention the search query and chain in the intro. "+z+(p.length>0?ce:""),query:n,chain:s,protocolVersion:l,feeTierBps:c,feeTierPercent:c!=null?c/1e4:void 0,page:a,size:i,count:u.length,pools:u.map(m=>({...m,...ct(s,m.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(dy.includes(t))return t}return"V3"}formatPool(e){let t=e.isDynamicFee===!0||cn(e.feeTier),n={address:e.id,chainId:e.chainId,protocolVersion:e.protocolVersion,feeTierBps:t?void 0:e.feeTier,feeTierPercent:!t&&typeof e.feeTier=="number"?e.feeTier/1e4:void 0,...t?{isDynamicFee:!0}:{}},r=W(e.apr);r!=null&&(n.apr=r),e.tvlUsd!=null&&(n.tvlUsd=e.tvlUsd);let s=e.volume1DayUsd??e.volumeUsd24hr;s!=null&&(n.volume24hUsd=s),e.volumeUsd6hr!=null&&(n.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(n.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(n.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&s!=null&&(n.volumeToTvlRatio=Math.round(s/e.tvlUsd*1e3)/1e3);let a=e.token0,i=e.token1;return a&&(n.token0={address:a.address,symbol:a.symbol,name:a.name,decimals:a.decimals}),i&&(n.token1={address:i.address,symbol:i.symbol,name:i.name,decimals:i.decimals}),n}};var xr=class extends P{name="uniswap-pool-by-address";description=`Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use this tool when the user pastes a single address and asks about "the pool" without saying which kind. For pool detail (when the address is a pool): pair, fee tier, TVL with 24h % change, 24h volume, 24h fees, estimated APR, token reserves with USD prices, and each token's safety flags. For token resolution (when the address is a token): the resolved token (symbol, name, decimals) plus a ranked list of pools that include it (pair, fee tier, 24h volume, pool address). Source: https://app.uniswap.org. Supports: `+Ie();category="blockchain-data";parameters=[{name:"address",type:"string",description:"A 0x-prefixed EVM address. May be a Uniswap pool contract OR a token contract \u2014 the tool figures out which.",required:!0},{name:"chain",type:"string",description:Qe,required:!1},...Ce];service;pool;constructor(e){super(),this.service=new Be(e),this.pool=new se}async run(e,t){let n=await Z(Je(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,s=typeof e.address=="string"?e.address.trim():"",[a,i]=await Promise.all([this.service.searchPools({query:s,chain:r,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:s,chain:r,page:1,size:5})]),l=a.success?this.findPoolByAddress(a.data??[],s):void 0;if(l)return this.handlePoolHit(l,r,e);let c=i.success?this.findTokenByAddress(i.data??[],s):void 0;return c?this.handleTokenHit(c,r,e):!a.success&&!i.success?{error:a.error||i.error||"Failed to resolve address"}:{error:`Address ${s} did not match any pool or token Uniswap knows on ${T(r)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t,n){if(!e.id)return{error:"Resolved pool has no identifier"};let r=await this.service.getPoolDetailEnriched({addressOrId:e.id,chain:t,enrich:!1});if(!r.success||!r.data)return{error:r.error||"Failed to fetch pool detail"};let s=await this.service.getTokenSafetyByAddress([r.data.token0?.address,r.data.token1?.address],t),a=r.data.protocolVersion??e.protocolVersion??"V3",i={...Yn(r.data,s),...ct(t,e.id)},l=await this.pool.isAddLiquiditySupported(t)?ue([i],n,T(t)):[];return{_instructions:`The address is a Uniswap ${a} pool. `+de+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), protocol version, and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, and token1 reserve + USD price. For V4 pools also mention tickSpacing, isDynamicFee, and the hook address if present. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+pe+ye+G+z+(l.length>0?ce:""),resolvedAs:"pool",chain:t,protocolVersion:a,pool:i,...l.length>0?{actionButtons:l}:{}}}async handleTokenHit(e,t,n){let r=e.symbol?.trim();if(!r)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let s=await this.service.searchPools({query:r,chain:t,page:1,size:100,protocolVersion:"V3"});if(!s.success)return{error:s.error||"Failed to fetch pools for resolved token"};let a=(e.address??"").toLowerCase(),l=[...(s.data??[]).filter(u=>{let p=(u.token0?.address??"").toLowerCase(),m=(u.token1?.address??"").toLowerCase();return p===a||m===a})].sort((u,p)=>(p.volumeUsd24hr??0)-(u.volumeUsd24hr??0)).slice(0,10),c=l.map(u=>({...this.formatPoolCandidate(u),...ct(t,u.id)})),d=await this.pool.isAddLiquiditySupported(t)?ue(c,n,T(t)):[];return{_instructions:"The address is a token, not a pool. Tell the user which token it is (symbol + name), then render the matching pools as a numbered list: pair (token0/token1 symbols), fee tier (%), protocol version, 24h volume (USD). Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. Ask which pool they want detail on; when they answer, re-call this tool with that pool address to fetch the detail. Format numbers human-readably. Omit null fields. Do NOT mention tool/API names."+(d.length>0?ce:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...d.length>0?{actionButtons:d}:{}}}findPoolByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.id??"").toLowerCase()===n)}findTokenByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.address??"").toLowerCase()===n)}formatToken(e){return{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,isSpam:e.isSpam,safetyLevel:e.safetyLevel}}formatPoolCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}};var hi=class{uniswap;constructor(e){this.uniswap=new Be(e)}async resolveCandidates(e){let t=await this.uniswap.searchPools({query:`${e.token0Symbol} ${e.token1Symbol}`,chain:e.chain,page:1,size:100,protocolVersion:e.protocolVersion,feeTier:e.feeTier});return t.success?t.data??[]:null}};var Xd=/^0x[a-fA-F0-9]{40}$/,Qd=/^0x[a-fA-F0-9]{64}$/,Gn=class extends P{name="pool-open-add-liquidity-form";kind="ui";category="pool-action";description='Open the Add-Liquidity form for a specific Uniswap V3 pool. Use this when the user wants to provide liquidity / add LP / farm / stake / deposit into a pool \u2014 natural-language verbs in any language all map here. Resolves the pool by its exact address when the message carries one (the add-liquidity buttons under a pool listing append "(Pool: 0x\u2026 - <chain>)" \u2014 pass that address through as `poolAddress`), otherwise by token symbols and optional fee tier. Reads on-chain state, checks the connected wallet\'s NATIVE balance, then returns a UI payload that the FE renders as the form (with two preset ranges: Stable \xB13 ticks and Wide -50%/+100%). CONSTRAINT: the gateway only accepts the chain\'s NATIVE coin as input (ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche). The native amount is auto-split via deBridge into both pool tokens \u2014 the user never selects a different input. If the user asks to add liquidity using a NON-NATIVE token amount (e.g. "add pool with 5 USDT", "th\xEAm 100 USDC"), pass that symbol via `requestedNonNativeToken` so the tool can return error="unsupported_input_token" \u2014 never silently convert their non-native amount into native or USD. PRECONDITION: a connected wallet (userContext.walletAddress). If absent, the tool returns error="wallet_not_connected" and the agent must ask the user to connect. VERSION CONSTRAINT: only Uniswap V3 pools can be added to. When the pool the user picked is V2 or V4, the tool returns error="unsupported_protocol_version" with the version \u2014 tell the user that version is not supported yet (the pool DOES exist; never say it was not found).';parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's 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"). Required to uniquely identify the pool.',required:!0},{name:"poolAddress",type:"string",description:`The pool's exact on-chain address (0x\u2026), when the user's message names one \u2014 the add-liquidity buttons under a pool listing carry it as "(Pool: 0x\u2026 - <chain>)". Pass it through VERBATIM whenever it is present: it pins the flow to that exact pool instead of re-searching by symbols, which can land on a different pool of the same pair. Omit when the user named no address.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. Omit when unknown \u2014 the tool will resolve the best match automatically.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prefillNativeAmount",type:"number",description:"Optional NATIVE-COIN amount (human-readable) to pre-fill the form's input field. ONLY pass this when the user named an amount in the chain's native coin itself \u2014 ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche. Example: \"add 0.1 ETH to USDC/WETH on Base\". Pass the plain decimal number (e.g. 0.1 for 0.1 ETH). DO NOT convert a non-native amount (USDC, USDT, DAI, WBTC, \u2026) into native here \u2014 pass `requestedNonNativeToken` instead so the tool can reject. Mutually exclusive with prefillUsdAmount \u2014 pass one or neither.",required:!1},{name:"prefillUsdAmount",type:"number",description:'Optional USD amount to pre-fill the form\'s input field. Use this ONLY when the user explicitly speaks in USD/dollars \u2014 e.g. "add $10 to this pool", "10 dollars", "10 \u0111\xF4". The tool converts the USD value to native amount automatically using the current native-token price. DO NOT use this as a workaround for non-native token amounts (e.g. "5 USDT" is NOT $5 \u2014 USDT may de-peg, and even if 1:1 the user asked for a token, not USD). For non-native token amounts pass `requestedNonNativeToken` instead. Mutually exclusive with prefillNativeAmount \u2014 pass one or neither.',required:!1},{name:"requestedNonNativeToken",type:"string",description:`Set this ONLY when the user named an AMOUNT in a non-native token \u2014 e.g. "add pool with 5 USDT", "add 100 USDC to USDC/WETH", "th\xEAm 5 USDT v\xE0o pool". The trigger is "<number> <non-native-symbol>" in the user's message, NOT the mere appearance of the symbol. Pass the symbol the user attached the amount to (e.g. "USDT", "USDC", "DAI"). CRITICAL: If the user also names a NATIVE amount in the same message (e.g. "add USDC/WETH with 0.1 ETH", "th\xEAm pool USDC/WETH 0.3% v\u1EDBi 0.000005 ETH"), the native amount is the input \u2014 leave this EMPTY and use prefillNativeAmount. The pool pair symbols (the two tokens after "pool" / "to") are NEVER the input token by themselves \u2014 they only identify which pool. The tool will return error="unsupported_input_token" so the agent can tell the user that only the chain's native coin is accepted as input. DO NOT silently convert the user's non-native amount into a native amount or USD amount \u2014 the user explicitly named a different asset and must be informed, not auto-corrected. Leave empty when the user did name a native amount, a USD amount, or no amount at all.`,required:!1},{name:"rangeStrategy",type:"string",description:'Optional preset that pre-fills the min/max price inputs (FE keeps them editable). One of: "stable" \u2014 \xB13 tickSpacing around the current price (narrow, higher yield, higher out-of-range risk; pick for stablecoin / low-volatility pairs and when the user says "safe", "tight", "high yield", "t\u1EADp trung"); "wide" \u2014 currentPrice \xD7 [0.5, 2.0] (broad, lower yield, less rebalancing; pick when the user says "wide", "set and forget", "r\u1ED9ng"); "full" \u2014 full V3 tick range (V2-style, lowest yield, never goes out of range; pick when the user says "full range", "v2-style", "kh\xF4ng lo out of range"). Omit when the user did not signal a preference AND did not provide explicit minPrice/maxPrice. Mutually exclusive with minPrice/maxPrice \u2014 if both are passed, explicit prices win.',required:!1},{name:"minPrice",type:"number",description:'Optional explicit lower bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 minPrice=1800. Must be paired with maxPrice. When set, overrides rangeStrategy.',required:!1},{name:"maxPrice",type:"number",description:'Optional explicit upper bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 maxPrice=2200. Must be paired with minPrice. When set, overrides rangeStrategy.',required:!1},{name:"add_button_label",type:"string",description:`Label template for the per-fee-tier "Add liquidity" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. ALWAYS pass this when you call the tool with a pair but NO feeTier (the tool may return several fee-tier variants for the pair, and each gets a one-tap button). Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:'A short "add liquidity" command template IN THE USER\'S CURRENT LANGUAGE, submitted as the next user turn when a fee-tier button is clicked \u2014 it carries the chosen fee tier so the tool resolves that exact pool. ALWAYS pass this alongside `add_button_label` when calling with a pair but no feeTier. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain this pair is on is appended to the prompt automatically.',required:!1}];resolver;pool;coinPool;minProvideUsd;constructor(e){super(),this.resolver=e?.resolver??new hi(e),this.pool=new se(e?.pool),this.coinPool=new yn(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-r};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&typeof s=="object"&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-r}}}async run(e,t){let n=await Z(gn(this.pool),e.chain,t);if(!n.ok)return n.result;let r=n.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.poolAddress=="string"?e.poolAddress.trim():"",c=Xd.test(l)||Qd.test(l)?l.toLowerCase():"",d=Qd.test(l),u=typeof e.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,p=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,m=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,f=m&&u!=null&&(m.toLowerCase()===s.toLowerCase()||m.toLowerCase()===a.toLowerCase())?null:m,h=this.parseRangeStrategy(e.rangeStrategy),g=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,b=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!s||!a)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let y=we(r);if(!y)return{error:"unsupported_chain",chain:r,_instructions:`Chain ${r} is not supported by the add-liquidity flow.`};let w=Tr(r);if(f&&w&&f.toLowerCase()!==w.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:f,nativeSymbol:w.symbol,chainName:y.name,_instructions:`The user asked to add liquidity using ${f}, but this app only supports the chain's native coin (${w.symbol} on ${y.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${w.symbol} or in USD. DO NOT silently convert their ${f} amount, do NOT pre-fill the form, and do NOT call this tool again until the user provides a native or USD amount.`};let k=await this.pool.getGatewayAddress(r);if(!k)return{error:"no_gateway_configured",chain:r,_instructions:`No gateway contract is configured for chain ${r} (${y.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let v=t?.walletAddress;if(!v)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before adding liquidity. Do NOT render the form."};if(d)return this.unsupportedVersionResult({protocolVersion:"V4",token0:{symbol:s},token1:{symbol:a}},s,a,y.name);let A=await this.resolver.resolveCandidates({chain:r,token0Symbol:s,token1Symbol:a,protocolVersion:"V3",feeTier:c?void 0:i});if(A===null)return{error:"pool_search_failed"};let S=c?A.find(K=>typeof K.id=="string"&&K.id.toLowerCase()===c):void 0;if(c&&!S){let K=await this.findUnsupportedVersionPool(r,s,a,i,c);if(K)return this.unsupportedVersionResult(K,s,a,y.name)}let C=S??A.find(K=>this.matchesPairExact(K,s,a,i)),F=C?[]:A.filter(K=>this.matchesPair(K,s,a,i));if(!C&&F.length===0){let K=await this.findUnsupportedVersionPool(r,s,a,i,c);return K?this.unsupportedVersionResult(K,s,a,y.name):{error:"pool_not_found",_instructions:`No V3 pool found for ${s}/${a}${i!=null?` at ${i}bps`:""} on ${y.name}. Verify the inputs with the user.`}}if(!C&&F.length>1){let K=F.map(ke=>{let Xn=ke.volume1DayUsd??ke.volumeUsd24hr,oa=ke.tvlUsd,wc=typeof Xn=="number"&&typeof oa=="number"&&oa>0?Xn/oa:void 0;return{address:ke.id,token0Symbol:ke.token0?.symbol,token1Symbol:ke.token1?.symbol,feeTier:ke.feeTier,feeTierPercent:ke.feeTier!=null?ke.feeTier/1e4:void 0,volume24hUsd:Xn,tvlUsd:oa,...wc!=null?{volumeToTvlRatio:wc}:void 0,...ke.apr?{apr:ke.apr}:void 0}}).sort((ke,Xn)=>(Xn.volumeToTvlRatio??Xn.apr??-1/0)-(ke.volumeToTvlRatio??ke.apr??-1/0)).slice(0,5),Ii=rc(K.map(ke=>({token0:{symbol:ke.token0Symbol},token1:{symbol:ke.token1Symbol},feeTierPercent:ke.feeTierPercent,address:ke.address})),typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",T(r));return{relatedPools:K,count:K.length,...Ii.length>0?{actionButtons:Ii}:{},_instructions:de+"The user wants to ADD LIQUIDITY to this pair but named NO fee tier \u2014 `relatedPools` holds the related pools (the pair's fee-tier variants and closely-matching pools). Do NOT just ask them to pick blindly: give a genuine comparative read. Present them as a ranked list (rank by capital efficiency / fee yield, not just TVL); for each show the fee tier (%), TVL (USD), 24h volume (USD), and estimated APR (%) when present. Analyze each with its own real read \u2014 never skip one or repeat the same sentence structure. "+pe+"Focus on which fee tier is the best home for THIS pair to LP in: lower tiers (0.01\u20130.05%) suit stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 the tier that captures most of the real volume on deep TVL is usually the one to provide liquidity in. Close by naming the single best fee tier to add liquidity in right now and why, then invite the user to confirm a tier to continue. When they choose, re-run the add-liquidity step with token0Symbol + token1Symbol + the chosen feeTier (in bps). "+ye+G+z+(Ii.length>0?' A clickable "Add liquidity" button is shown below your reply for each fee-tier candidate automatically \u2014 do NOT list, number, or repeat those buttons.':"")}}let R=C??F[0];if(!R.id||!Xd.test(R.id))return{error:"invalid_pool_address"};let me=this.fetchPriceRanges(r,R.id,R.token0?.symbol,R.token1?.symbol),H=await this.pool.readPoolOnchain(r,R.id),[O,he,Ve]=await Promise.all([this.pool.getNativeBalance(r,v),this.pool.estimateGasReserveWei(r),this.pool.getNativePriceUsd(r)]),Mt=O>he?O-he:0n,$=Tr(r),De=Number(Mt)/10**$.decimals,wn=Number(O)/10**$.decimals,Ee=Ve!=null?De*Ve:null,[kn,ns]=await Promise.all([this.pool.readErc20Decimals(r,H.token0),this.pool.readErc20Decimals(r,H.token1)]),ta={min:lt(pn,kn,ns),max:lt(mr,kn,ns)},dt=null;O===0n?dt="no_balance":Ee!=null&&Ee<this.minProvideUsd&&(dt="insufficient_balance");let vn=R.token0,Tn=R.token1,na=[25,50,75,100].map(K=>({percent:K,amountWei:(Mt*BigInt(K)/100n).toString(),amount:De*(K/100)})),Rt=null,tt=null;if(u!=null){tt=u;let K=BigInt(Math.floor(tt*10**$.decimals));K>0n&&(Rt=K.toString())}else if(p!=null&&Ve!=null&&Ve>0){tt=p/Ve;let K=BigInt(Math.floor(tt*10**$.decimals));K>0n&&(Rt=K.toString())}let yc={address:le,isNative:!0,symbol:$.symbol,name:$.name,decimals:$.decimals,priceUsd:Ve,balanceWei:O.toString(),balance:wn,gasReserveWei:he.toString(),spendableWei:Mt.toString(),spendable:De,spendableUsd:Ee,quickRates:na,minProvideUsd:this.minProvideUsd,warning:dt,warningMessage:dt==="no_balance"?`You have no ${$.symbol} on ${y.name}. Top up to add liquidity.`:dt==="insufficient_balance"?`Spendable ${$.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:tt,prefillAmountWei:Rt},bc=this.computePrefillRange({explicitMinPrice:g,explicitMaxPrice:b,rangeStrategy:h,currentPrice:H.currentPrice,currentTick:H.currentTick,tickSpacing:H.tickSpacing,token0Decimals:kn,token1Decimals:ns,priceBounds:ta}),xp={component:"AddLiquidityForm",props:{chain:{hexId:r,name:y.name},pool:{address:H.poolAddress,fee:H.fee,feePercent:H.fee/1e4,tickSpacing:H.tickSpacing,currentTick:H.currentTick,currentPrice:Pe(H.currentPrice),sqrtPriceX96:H.sqrtPriceX96.toString(),token0:{address:H.token0,symbol:vn?.symbol,name:vn?.name,logo:vn?.logo},token1:{address:H.token1,symbol:Tn?.symbol,name:Tn?.name,logo:Tn?.logo}},inputToken:yc,priceBounds:ta,prefillRange:bc,gatewayAddress:k}},Cp=this.orientRangesToForm(await me,H.currentPrice,vn?.symbol,Tn?.symbol);return{ui:xp,suggestedRanges:Cp,summary:this.buildSummary({chainName:y.name,pair:`${vn?.symbol??s}/${Tn?.symbol??a}`,feePercent:H.fee/1e4,warning:dt,minProvideUsd:this.minProvideUsd,nativeSymbol:$.symbol}),_instructions:'The add-liquidity action is ready. In the user\'s language, invite them to enter the amount and price range to add liquidity, naming the pool + chain (e.g. "Enter the amount and price range to add liquidity to <pool> on <chain>"). Speak ONLY of the user\'s action (adding liquidity). NEVER say you "opened a form", "opened" anything, or describe any screen/form/window/UI being shown \u2014 phrase it as the next step the user takes, not as something you did. If warning="no_balance" tell them they need to top up. If warning="insufficient_balance" tell them the balance is below the minimum. REFERENCE RANGES: when `suggestedRanges` is a non-empty array, briefly offer 1\u20133 of them (highest `apr` first) as price ranges the user can REFERENCE when filling in their range \u2014 for each give the min\u2013max (`minPrice`\u2013`maxPrice`) and its `apr` \u2014 omitting the APR for any entry whose `apr` is absent (never "APR 0%", "N/A" or a dash). These prices are ALREADY in the SAME unit the form shows (`quoteSymbol` per `baseSymbol`), so quote them as-is \u2014 do NOT invert them. CRITICAL: that `apr` is the yield for THAT specific range ONLY \u2014 NEVER present it as the overall pool APR; narrower = higher out-of-range risk. These are only in-range suggestions to reference \u2014 the user still chooses their own range. When `suggestedRanges` is empty or absent, omit this entirely. '+G+"Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, data sources, or internal tool names. Wait for the user to fill in amount + price range before proceeding."}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&n&&r&&(s=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,n,r){let s=a=>Number.isFinite(a)&&a>0;return s(t)?e.map(a=>{let{minPrice:i,maxPrice:l,currentPrice:c}=a.priceRange,d=i,u=l,p=c;if(s(c)){let m=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<m&&(d=s(l)?1/l:0,u=s(i)?1/i:0,p=1/c)}return{fee:a.fee,apr:W(a.apr),minPrice:Pe(d),maxPrice:Pe(u),currentPrice:Pe(p),baseSymbol:n,quoteSymbol:r}}).filter(a=>s(a.minPrice)&&s(a.maxPrice)):[]}unsupportedVersionResult(e,t,n,r){let s=e.protocolVersion??"V4";return{error:"unsupported_protocol_version",protocolVersion:s,pair:`${e.token0?.symbol??t}/${e.token1?.symbol??n}`,chain:r,_instructions:`This is a Uniswap ${s} pool, and adding liquidity currently works only for V3 pools. Tell the user \u2014 in their language \u2014 that the pool they picked does exist but that adding liquidity to ${s} pools is not supported yet, only V3 pools are. Suggest they pick a V3 pool for this pair instead (one may well exist). Keep it short and friendly. Do NOT say the pool was not found, and do NOT mention tools, services, APIs, forms, or any internals.`}}async findUnsupportedVersionPool(e,t,n,r,s){try{let a=await this.resolver.resolveCandidates({chain:e,token0Symbol:t,token1Symbol:n,protocolVersion:"ALL"});if(a===null)return;let i=a.filter(l=>l.protocolVersion&&l.protocolVersion!=="V3");return i.length===0?void 0:s?i.find(l=>typeof l.id=="string"&&l.id.toLowerCase()===s):i.find(l=>this.matchesPairExact(l,t,n,r))??i.find(l=>this.matchesPair(l,t,n,r))}catch{return}}matchesPairExact(e,t,n,r){if(!r||r!=null&&e.feeTier!==r)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase();return s===i&&a===l||s===l&&a===i}matchesPair(e,t,n,r){if(r!=null&&e.feeTier!==r)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase(),c=this.symMatch(s,i)&&this.symMatch(a,l),d=this.symMatch(s,l)&&this.symMatch(a,i);return c||d}symMatch(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}parseRangeStrategy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="stable"||t==="wide"||t==="full"?t:null}computePrefillRange(e){let{explicitMinPrice:t,explicitMaxPrice:n,rangeStrategy:r,currentPrice:s,priceBounds:a}=e;if(t!=null&&n!=null&&n>t){let{minPrice:i,maxPrice:l}=hr(t,n,s);return{strategy:"user",minPrice:Math.max(i,a.min),maxPrice:Math.min(l,a.max)}}if(r==="full")return{strategy:"full",minPrice:a.min,maxPrice:a.max};if(r==="stable"||r==="wide"){let l=tc({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===r);if(l)return{strategy:r,minPrice:l.minPrice,maxPrice:l.maxPrice}}return null}buildSummary(e){let t=[`Ready to add liquidity to the ${e.pair} ${e.feePercent}% pool on ${e.chainName}. Enter an amount and a price range to continue.`];return e.warning==="no_balance"?t.push(`You'll need some ${e.nativeSymbol} on ${e.chainName} first \u2014 top up to continue.`):e.warning==="insufficient_balance"&&t.push(`Your spendable ${e.nativeSymbol} is below the $${e.minProvideUsd} minimum \u2014 top up before continuing.`),t.join(" ")}};var py=/^0x[a-fA-F0-9]{40}$/,Kn=class extends P{name="pool-preview-add-liquidity";kind="action";category="pool-action";description='Preview the add-liquidity transaction. Call this whenever a concrete pool ADDRESS, a native amount, and BOTH min and max price (in token1 per token0) are known \u2014 whether the user filled the AddLiquidityForm OR stated all of them directly in chat (e.g. "add to USDC/WETH with 0.01 ETH, range 0.0005-0.0007, pool=0x\u2026"). Do NOT require the form to have been opened first. The tool converts prices \u2192 ticks (rounded to tickSpacing), fetches deBridge swap quotes for both legs, encodes the gateway.mint call, and returns an unsigned tx the FE will sign. REQUIRES the exact poolAddress (from open-add-liquidity-form props.pool.address or given by the user) \u2014 if only token symbols / a fee tier are known, resolve the pool via open-add-liquidity-form first.';parameters=[{name:"poolAddress",type:"string",description:"V3 pool contract address (returned by open-add-liquidity-form in props.pool.address).",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 .Must match the pool's chain. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.`,required:!1},{name:"minPrice",type:"number",description:`Lower bound of the position price range, in token1-per-token0 units (decimal-adjusted \u2014 the SAME unit as pool.currentPrice from open-add-liquidity-form). Example: if currentPrice is 1800 (USDC per WETH), minPrice 900 means "the position is in-range while WETH \u2265 900 USDC". Must be >= 0 and < maxPrice. Pass 0 for a "full-range lower" position (the range extends down to price 0, i.e. Uniswap's MIN_TICK). CRITICAL: copy the number the user gave VERBATIM \u2014 every digit and every leading zero. Do NOT add or drop a zero, round, or rescale it. Tiny decimals like 0.000533 are easy to mis-transcribe (0.000533 must stay 0.000533, NEVER 0.0000533). If unsure, prefer the user's exact characters over your own reformatting.`,required:!0},{name:"maxPrice",type:"number",description:`Upper bound of the position price range, in the same units as minPrice. Must be > minPrice. Pass a very large number (or props.priceBounds.max) for a "full range upper" position. CRITICAL: copy the user's number VERBATIM \u2014 every digit and leading zero; never add/drop a zero, round, or rescale.`,required:!0},{name:"nativeAmount",type:"number",description:"Native amount the user wants to spend, as a human-readable decimal number (e.g. 0.1 for 0.1 ETH). The tool converts to wei internally.",required:!0},{name:"slippageBps",type:"number",description:"Slippage tolerance in basis points (100 = 1%). Optional \u2014 defaults to 100.",required:!1}];pool;defaultSlippageBps;mintMinPercent;pantograph;constructor(e){super(),this.pool=new se(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new Te}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-r};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-r}}}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=await Z(gn(this.pool),e.chain,t);if(!r.ok)return r.result;let s=r.chain,a=Number(e.minPrice),i=Number(e.maxPrice),l=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,c=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!n||!s||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!py.test(n))return{error:"invalid_pool_address",_instructions:"poolAddress is not a valid EVM address. Re-open the add-liquidity form to get the correct pool address."};if(a<0||i<=0||a>=i)return{error:"invalid_price_range",_instructions:"minPrice must be >= 0 (0 = full-range lower), maxPrice must be > 0, and minPrice must be strictly less than maxPrice."};if(l<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let d=we(s);if(!d)return{error:"unsupported_chain",chain:s};let u=await this.pool.getGatewayAddress(s);if(!u)return{error:"no_gateway_configured",chain:s};let p=t?.walletAddress;if(!p)return{error:"wallet_not_connected"};let m=Tr(s),f=BigInt(Math.floor(l*10**m.decimals));if(f<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let h=await this.pool.readPoolOnchain(s,n),[g,b]=await Promise.all([this.pool.readErc20Decimals(s,h.token0),this.pool.readErc20Decimals(s,h.token1)]),{minPrice:y,maxPrice:w}=hr(a,i,h.currentPrice),k=y===0?pn:Wn(y,g,b),v=Wn(w,g,b),A=y===0?Pt(At(pn,h.tickSpacing,"up")):Pt(At(k,h.tickSpacing,"down")),S=Pt(At(v,h.tickSpacing,"up"));if(A>=S||A<pn||S>mr)return{error:"invalid_range_after_alignment",_instructions:"After aligning to tickSpacing the range collapsed. Ask the user for a wider price range.",rawTickLower:k,rawTickUpper:v,tickLower:A,tickUpper:S};let C={tickLower:A,tickUpper:S,minPrice:Pe(lt(A,g,b)),maxPrice:Pe(lt(S,g,b))},F=h.currentTick;if(F<A||F>=S){let Q=F<A?"below":"above";return{error:"out_of_range",_instructions:`The chosen price range does NOT include the pool's current price, so this would be an OUT-OF-RANGE position (it would sit entirely in one token and earn no fees until the price moves back into the range). The current price is ${Q==="below"?"BELOW":"ABOVE"} the chosen range. Tell the user (in their language) that their range is out of range, show the current price and their chosen min/max, and ask them to pick a range that brackets the current price. Do NOT proceed with the transaction. Do NOT mention tool names.`,currentPrice:Pe(h.currentPrice),requestedRange:{minPrice:C.minPrice,maxPrice:C.maxPrice},side:Q}}let[R,me,H]=await Promise.all([this.pool.getNativeBalance(s,p),this.pool.estimateGasReserveWei(s),this.pool.getNativePriceUsd(s)]),O=f+me;if(R<O)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:R.toString(),requiredWei:O.toString(),gasReserveWei:me.toString()};let he=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:h,tickLower:A,tickUpper:S,token0Decimals:g,token1Decimals:b}),Ve=h.token0.toLowerCase()===le,Mt=h.token1.toLowerCase()===le,$=[];if(Ve||he.amountInFor0Wei===0n)$.push({tokenIn:le,tokenOut:h.token0,amountIn:he.amountInFor0Wei,tx:{to:le,data:"0x",value:"0"},minAmountOut:Ve?he.amountInFor0Wei:0n});else{let Q=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:le,tokenInAmount:he.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});$.push({tokenIn:le,tokenOut:h.token0,amountIn:he.amountInFor0Wei,tx:{to:Q.to,data:Q.data,value:Q.value},minAmountOut:BigInt(Q.minAmountOut||"0")})}if(Mt||he.amountInFor1Wei===0n)$.push({tokenIn:le,tokenOut:h.token1,amountIn:he.amountInFor1Wei,tx:{to:le,data:"0x",value:"0"},minAmountOut:Mt?he.amountInFor1Wei:0n});else{let Q=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:le,tokenInAmount:he.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});$.push({tokenIn:le,tokenOut:h.token1,amountIn:he.amountInFor1Wei,tx:{to:Q.to,data:Q.data,value:Q.value},minAmountOut:BigInt(Q.minAmountOut||"0")})}let De=Q=>Q*BigInt(this.mintMinPercent)/100n,wn=De($[0].minAmountOut),Ee=De($[1].minAmountOut),kn=$.map(Q=>({tokenIn:Q.tokenIn,tokenInAmount:BigInt(Q.amountIn),tokenOut:Q.tokenOut,tokenOutAmount:BigInt(Q.minAmountOut)})),ns=$.map(Q=>({to:Q.tx.to,data:Q.tx.data,value:BigInt(Q.tx.value||"0")})),ta=D({abi:El,functionName:"mint",args:[kn,ns,{fee:Number(h.fee),amount0Min:BigInt(wn),amount1Min:BigInt(Ee),tickLower:A,tickUpper:S}]}),dt=l,vn={chainId:s,to:u,data:ta,value:f.toString(),from:p},Tn={nativeIn:dt,nativeSymbol:m.symbol,nativeInUsd:H!=null?dt*H:null,ratio:{token0Percent:he.ratio0,token1Percent:he.ratio1},expectedToken0:Number($[0].minAmountOut)/10**g,expectedToken1:Number($[1].minAmountOut)/10**b,amount0Min:wn.toString(),amount1Min:Ee.toString(),slippageBps:c},na=await this.pantograph.getTokensMetadata([h.token0,h.token1],s),Rt=na[h.token0],tt=na[h.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:s,name:d.name},unsignedTx:vn,summary:Tn,pool:{...h,feePercent:h.fee/1e4,currentPrice:Pe(h.currentPrice),token0:{address:h.token0,symbol:Rt?.auditGoplus?.token_symbol||Rt.symbol,name:Rt.name,decimals:Rt.decimals,logo:Rt.icon_image},token1:{address:h.token1,symbol:tt?.auditGoplus?.token_symbol||tt.symbol,name:tt.name,decimals:tt.decimals,logo:tt.icon_image}},range:C,gatewayAddress:u}},summary:`Ready to add ${dt} ${m.symbol} to pool ${h.token0}/${h.token1} ${h.fee/1e4}% on ${d.name}, range [${C.minPrice}, ${C.maxPrice}].`,_instructions:"A confirmation panel has been opened on the FE; the user will sign and broadcast the unsigned tx with their wallet. Briefly tell them (in their language) what is about to happen \u2014 the native amount, the auto-split ratio between the two pool tokens, and the chosen price range. Do NOT mention internal tool/component names."}}};var my=365,hy=1e3,fy=/^0x[a-fA-F0-9]{40}$/;function gy(o,e){return{depositUsd:o,aprPercent:e*100,dailyUsd:o*e/my,weeklyUsd:o*e/52,monthlyUsd:o*e/12,yearlyUsd:o*e}}var Cr=class extends P{name="uniswap-estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap V3 pool. Answers questions like: "If I put $1000 into the USDC/WETH 0.05% pool, how much per day?", "b\u1ECF 500$ v\xE0o pool ETH/USDC 0.3% m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "APR of WBTC/ETH 0.3% on Arbitrum". BEHAVIOR (designed to minimize back-and-forth with the user):
|
|
203
203
|
\u2022 If only ONE token symbol is given \u2192 auto-pick the highest-volume V3 pool containing that token and compute yield. Do NOT ask the user for the other token.
|
|
204
204
|
\u2022 If BOTH tokens are given but fee tier is missing AND multiple fee tiers exist \u2192 return candidates (one per fee tier) so the agent can ask the user to pick.
|
|
205
205
|
\u2022 If depositUsd is missing \u2192 default to $1000 and clearly mark the result as a per-$1000 example. Do NOT ask the user for the deposit amount.
|
|
206
206
|
\u2022 If chain is missing \u2192 default to userContext.chain or "0x1" (Ethereum).
|
|
207
|
-
Source: Uniswap Explore (live 24h data). Supports: `+Ee();category="blockchain-data";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:$e,required:!1}];service;constructor(e){super(),this.service=new Re(e)}async run(e,t){let n=await _e(He(),e.chain,t);if(!n.ok)return n.result;let o=n.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:Of;if(!s)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let u=a?`${s} ${a}`:s,d=await this.service.searchPools({query:u,chain:o,page:1,size:50,protocolVersion:"V3"});if(!d.success)return{error:d.error||"Pool search failed"};let p=d.data??[],m=this.filterPools(p,s,a,i);if(m.length===0)return{error:`No V3 pool found for ${this.describeQuery(s,a,i)} on ${T(o)}. Verify the token symbols with the user.`};let g=this.rankByVolume(m);if(a&&i==null&&new Set(g.map(S=>S.feeTier).filter(S=>typeof S=="number")).size>1){let S=this.dedupeByFeeTier(g).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:`${s}/${a} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:S.map(C=>({pair:C.token0?.symbol&&C.token1?.symbol?`${C.token0.symbol}/${C.token1.symbol}`:void 0,feeTierBps:C.feeTier,feeTierPercent:typeof C.feeTier=="number"?C.feeTier/1e4:void 0,volume24hUsd:C.volumeUsd24hr,address:C.id}))}}let h=g[0];if(!h.id||!Df.test(h.id))return{error:"Resolved pool has no valid address."};let f=await this.service.getPoolDetailEnriched({addressOrId:h.id,chain:o,enrich:!1});if(!f.success||!f.data)return{error:f.error||"Failed to fetch pool detail."};let b=On(f.data),y=typeof b.aprPercent=="number"?b.aprPercent/100:void 0,w={address:b.address,pair:b.token0?.symbol&&b.token1?.symbol?`${b.token0.symbol}/${b.token1.symbol}`:void 0,feeTierBps:b.feeTierBps,feeTierPercent:b.feeTierPercent,tvlUsd:b.tvlUsd,volume24hUsd:b.volume24hUsd,fees24hUsd:b.fees24hUsd,lpFeeShare:b.lpFeeShare,volumeToTvlRatio:b.volumeToTvlRatio,aprPercent:b.aprPercent,chain:o,token0:b.token0?{symbol:b.token0.symbol}:void 0,token1:b.token1?{symbol:b.token1.symbol}:void 0},k=a?void 0:`User only provided ${s}; auto-picked the highest-volume V3 pool containing it.`;if(y==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:w,autoPickedReason:k,aprUnavailableReason:b.tvlUsd?b.isDynamicFee?"This pool's fee is set per swap by a hook, so it has no fixed rate to project a yield from":"Volume data unavailable":"TVL is zero or unavailable"};let v=Mf(c,y);return{_instructions:Ue+"Present the yield estimate naturally in the user's language. "+(l?"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. ')+(k?'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. "+Ie+Le+ke+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:w,estimate:v,depositMode:l?"user-specified":"default-1000-example",autoPickedReason:k,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(e,t,n,o){let s=t.toLowerCase(),a=n?n.toLowerCase():"";return e.filter(i=>{if(o!=null&&i.feeTier!==o)return!1;let l=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return a?this.sym(l,s)&&this.sym(c,a)||this.sym(l,a)&&this.sym(c,s):this.sym(l,s)||this.sym(c,s)})}sym(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}rankByVolume(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,n=[];for(let o of e)typeof o.feeTier=="number"&&(t.has(o.feeTier)||(t.add(o.feeTier),n.push(o)));return n}describeQuery(e,t,n){let o=t?`${e}/${t}`:e;return n!=null?`${o} at ${n} bps`:o}};var ko=class extends P{name="get-pool-price-ranges";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: '+Ee()+".";category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:$e,required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new cn(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=await _e(He(),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getPairs({chain:s,tokens:n});if(i.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:n,chain:s,pairs:[],count:0};let l=[...i].sort((c,u)=>(u.apr??-1/0)-(c.apr??-1/0)).slice(0,a);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)". When an entry has no `apr` (null/absent) there is no yield reading for it: omit the APR part entirely for that entry \u2014 never write "APR 0%", "N/A" or a dash. Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+ke+"Do NOT mention tool or API names.",tokens:n,chain:s,count:l.length,pairs:l}}};var Rd="https://coinpool.app/my-liquidity",vo=class extends P{name="manage-liquidity-redirect";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.';category="pool-action";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(e){let t=e.action==="collect"||e.action==="close"?e.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${t==="collect"?"collect their earned fees":t==="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: ${Rd} \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:Rd,action:t}}};var Ff=["tvl","volume","apr","fee","liquidity"],To=class extends P{name="subgraph-search-pools";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).';category="blockchain-data";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}];service;constructor(e){super(),this.service=new ye(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(g=>typeof g=="string"&&g.trim().length>0).map(g=>g.trim().toUpperCase()),o=(Array.isArray(e.chains)?e.chains:[]).filter(g=>typeof g=="string"&&g.trim().length>0),s=o.filter(g=>!this.service.isSupported(g)),a=o.filter(g=>this.service.isSupported(g)).map(g=>this.service.resolveChain(g));if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ie(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&Ff.includes(e.sortBy)?e.sortBy:"tvl",c={minTVL:typeof e.minTVL=="number"?e.minTVL:void 0,maxTVL:typeof e.maxTVL=="number"?e.maxTVL:void 0,minAPR:typeof e.minAPR=="number"?e.minAPR:void 0,maxAPR:typeof e.maxAPR=="number"?e.maxAPR:void 0,feeTier:typeof e.feeTier=="number"?e.feeTier:void 0},u=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5;if(o.length>0&&a.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:s.map(T),supportedChains:this.service.listSupportedChains().map(T),pools:[],count:0};let p=(await Promise.allSettled(i.map(g=>this.service.searchPools({tokens:n,chain:g,sortBy:l,filters:c})))).flatMap(g=>g.status==="fulfilled"?g.value:[]);l==="apr"?p.sort((g,h)=>(h.apr??0)-(g.apr??0)):l==="tvl"?p.sort((g,h)=>h.tvl-g.tvl):l==="volume"?p.sort((g,h)=>h.volume24hUsd-g.volume24hUsd):l==="fee"&&p.sort((g,h)=>g.feeTierBps-h.feeTierBps),p=p.slice(0,u);let m=[];return n.length===2&&(m=(await Promise.allSettled(i.map(h=>this.service.getCoinPoolPairs({chain:h,tokens:n})))).flatMap((h,f)=>h.status==="fulfilled"?h.value.map(b=>({...b,chain:T(i[f])})):[]),m.sort((h,f)=>(f.apr??-1/0)-(h.apr??-1/0)),m=m.slice(0,u)),{_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:n,chains:i.map(T),unsupportedChains:s.map(T),sortBy:l,filters:c,count:p.length,pools:p.map(g=>this.formatPool(g)),coinPoolPairs:m}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:Oe(e)}}};function Oe(r){return`https://app.uniswap.org/explore/pools/${Rs[r.chain]||r.chain}/${r.poolAddress}`}var Rs={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var Ao=class extends P{name="subgraph-trending-pools";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).';category="blockchain-data";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}];service;constructor(e){super(),this.service=new ye(e)}async run(e,t){let n=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),o=n.filter(u=>!this.service.isSupported(u)),s=n.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(n.length>0&&s.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(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ie(typeof t?.query=="string"?t.query:void 0);let a=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,c=(await Promise.allSettled(a.map(u=>this.service.getTrendingPools({chain:u})))).flatMap(u=>u.status==="fulfilled"?u.value:[]);return c.sort((u,d)=>d.volume24hUsd-u.volume24hUsd),c=c.slice(0,i),{_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:a,unsupportedChains:o,count:c.length,pools:c.map(u=>({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:Oe(u)}))}}};var Po=class extends P{name="subgraph-pool-by-address";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").';category="blockchain-data";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}];service;constructor(e){super(),this.service=new ye(e)}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n))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 e.chain=="string"&&e.chain.trim();if(!o&&!t?.chain&&t?.walletAddress)throw new ie(typeof t?.query=="string"?t.query:void 0);let s=o?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(s))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[s],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(s),[i,l]=await Promise.all([this.service.getPoolByAddress({poolAddress:n,chain:a}),this.service.getCoinPoolByAddress({chain:a,poolAddress:n}).catch(()=>[])]);return i?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(l.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:a,coinPoolPairs:l,pool:{pair:i.pair,poolAddress:i.poolAddress,chain:i.chain,feeTierBps:i.feeTierBps,feeTierPercent:i.feeTierPercent,tvlUsd:i.tvl,volumePastDayUsd:i.volume24hUsd,fees24hUsd:i.fees24hUsd,apr:i.apr,token0:i.token0,token1:i.token1,uniswapUrl:Oe(i)}}:{error:`No pool found at ${n} on ${T(a)}.`}}};var So=class extends P{name="subgraph-pool-by-position-id";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.';category="blockchain-data";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:[]}];service;constructor(e){super(),this.service=new ye(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string."};let o=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),s=o.filter(u=>!this.service.isSupported(u)),a=o.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(o.length>0&&a.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:s,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ie(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(u=>this.service.getPoolByPositionId({positionId:n,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);return c?{_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 (skip the APR entirely when it is null \u2014 never write "APR 0%", "N/A" or a dash). 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:n,pool:{pair:c.pair,poolAddress:c.poolAddress,chain:c.chain,feeTierBps:c.feeTierBps,feeTierPercent:c.feeTierPercent,tvlUsd:c.tvl,volumePastDayUsd:c.volume24hUsd,fees24hUsd:c.fees24hUsd,apr:c.apr,token0:c.token0,token1:c.token1,uniswapUrl:Oe(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:n,chains:i,found:!1}}};var xo=class extends P{name="subgraph-position-detail";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.`;category="blockchain-data";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:[]}];service;constructor(e){super(),this.service=new ye(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let o=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),s=o.filter(d=>!this.service.isSupported(d)),a=o.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(o.length>0&&a.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:s,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ie(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(d=>this.service.getPositionDetail({positionId:n,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);if(!c)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:n,chains:i,found:!1};let u=Rs[c.position.chain]||c.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 \u2014 skip the APR entirely when it is null, never write "APR 0%", "N/A" or a dash). 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:n,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${u}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:Oe(c.pool)}}}};var Co=class extends P{name="subgraph-coinpool-pairs";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.';category="blockchain-data";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}];service;constructor(e){super(),this.service=new ye(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=typeof e.chain=="string"&&e.chain.trim();if(!o&&!t?.chain&&t?.walletAddress)throw new ie(typeof t?.query=="string"?t.query:void 0);let s=o?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(s))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[s],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(s),i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,l=await this.service.getCoinPoolPairs({chain:a,tokens:n});if(l.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:n,chain:a,pairs:[],count:0};let c=[...l].sort((u,d)=>(d.apr??-1/0)-(u.apr??-1/0)).slice(0,i);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)". When an entry has no `apr` (null/absent), omit the APR part for that entry \u2014 never write "APR 0%", "N/A" or a dash. Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:n,chain:a,count:c.length,pairs:c}}};var Ro=class extends P{name="subgraph-add-pool";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.';category="blockchain-data";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}];service;linkAddLiquidity;constructor(e){super(),this.service=new ye(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let d=this.linkAddLiquidity??null,p=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",m="",g=[];if(this.service.isSupported(p)){m=this.service.resolveChain(p);try{g=(await this.service.searchPools({tokens:[],chain:m,sortBy:"tvl"})).slice(0,5)}catch{g=[]}}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:
|
|
207
|
+
Source: Uniswap Explore (live 24h data). Supports: `+Ie();category="blockchain-data";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:Qe,required:!1}];service;constructor(e){super(),this.service=new Be(e)}async run(e,t){let n=await Z(Je(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:hy;if(!s)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let d=a?`${s} ${a}`:s,u=await this.service.searchPools({query:d,chain:r,page:1,size:50,protocolVersion:"V3"});if(!u.success)return{error:u.error||"Pool search failed"};let p=u.data??[],m=this.filterPools(p,s,a,i);if(m.length===0)return{error:`No V3 pool found for ${this.describeQuery(s,a,i)} on ${T(r)}. Verify the token symbols with the user.`};let f=this.rankByVolume(m);if(a&&i==null&&new Set(f.map(S=>S.feeTier).filter(S=>typeof S=="number")).size>1){let S=this.dedupeByFeeTier(f).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:`${s}/${a} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:S.map(C=>({pair:C.token0?.symbol&&C.token1?.symbol?`${C.token0.symbol}/${C.token1.symbol}`:void 0,feeTierBps:C.feeTier,feeTierPercent:typeof C.feeTier=="number"?C.feeTier/1e4:void 0,volume24hUsd:C.volumeUsd24hr,address:C.id}))}}let h=f[0];if(!h.id||!fy.test(h.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getPoolDetailEnriched({addressOrId:h.id,chain:r,enrich:!1});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let b=Yn(g.data),y=typeof b.aprPercent=="number"?b.aprPercent/100:void 0,w={address:b.address,pair:b.token0?.symbol&&b.token1?.symbol?`${b.token0.symbol}/${b.token1.symbol}`:void 0,feeTierBps:b.feeTierBps,feeTierPercent:b.feeTierPercent,tvlUsd:b.tvlUsd,volume24hUsd:b.volume24hUsd,fees24hUsd:b.fees24hUsd,lpFeeShare:b.lpFeeShare,volumeToTvlRatio:b.volumeToTvlRatio,aprPercent:b.aprPercent,chain:r,token0:b.token0?{symbol:b.token0.symbol}:void 0,token1:b.token1?{symbol:b.token1.symbol}:void 0},k=a?void 0:`User only provided ${s}; auto-picked the highest-volume V3 pool containing it.`;if(y==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:w,autoPickedReason:k,aprUnavailableReason:b.tvlUsd?b.isDynamicFee?"This pool's fee is set per swap by a hook, so it has no fixed rate to project a yield from":"Volume data unavailable":"TVL is zero or unavailable"};let v=gy(c,y);return{_instructions:de+"Present the yield estimate naturally in the user's language. "+(l?"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. ')+(k?'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. "+pe+ye+G+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:w,estimate:v,depositMode:l?"user-specified":"default-1000-example",autoPickedReason:k,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(e,t,n,r){let s=t.toLowerCase(),a=n?n.toLowerCase():"";return e.filter(i=>{if(r!=null&&i.feeTier!==r)return!1;let l=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return a?this.sym(l,s)&&this.sym(c,a)||this.sym(l,a)&&this.sym(c,s):this.sym(l,s)||this.sym(c,s)})}sym(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}rankByVolume(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,n=[];for(let r of e)typeof r.feeTier=="number"&&(t.has(r.feeTier)||(t.add(r.feeTier),n.push(r)));return n}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at ${n} bps`:r}};var jn=class extends P{name="pool-price-ranges";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: '+Ie()+".";category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:Qe,required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;scope;constructor(e){if(super(),this.service=new yn(e),this.scope=e?.scope??Je(),e?.supportsLabel){let t=Ie();if(!this.description.includes(t))throw new Error("PoolPriceRangesTool: description no longer contains the default supported-chain label; update the description or the label so `supportsLabel` can override it.");this.description=this.description.replace(t,e.supportsLabel)}if(e?.chainParamDescription){let t=this.parameters.find(n=>n.name==="chain");t&&(t.description=e.chainParamDescription)}}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=await Z(this.scope,e.chain,t);if(!r.ok)return r.result;let s=r.chain,a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getPairs({chain:s,tokens:n});if(i.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:n,chain:s,pairs:[],count:0};let l=[...i].sort((c,d)=>(d.apr??-1/0)-(c.apr??-1/0)).slice(0,a);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)". When an entry has no `apr` (null/absent) there is no yield reading for it: omit the APR part entirely for that entry \u2014 never write "APR 0%", "N/A" or a dash. Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+G+"Do NOT mention tool or API names.",tokens:n,chain:s,count:l.length,pairs:l}}};var Jd="https://coinpool.app/my-liquidity",zn=class extends P{name="pool-manage-liquidity-redirect";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.';category="pool-action";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(e){let t=e.action==="collect"||e.action==="close"?e.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${t==="collect"?"collect their earned fees":t==="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: ${Jd} \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:Jd,action:t}}};var yy=["tvl","volume","apr","fee","liquidity"],Rr=class extends P{name="subgraph-search-pools";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).';category="blockchain-data";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}];service;constructor(e){super(),this.service=new Se(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),r=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),s=r.filter(f=>!this.service.isSupported(f)),a=r.filter(f=>this.service.isSupported(f)).map(f=>this.service.resolveChain(f));if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new fe(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&yy.includes(e.sortBy)?e.sortBy:"tvl",c={minTVL:typeof e.minTVL=="number"?e.minTVL:void 0,maxTVL:typeof e.maxTVL=="number"?e.maxTVL:void 0,minAPR:typeof e.minAPR=="number"?e.minAPR:void 0,maxAPR:typeof e.maxAPR=="number"?e.maxAPR:void 0,feeTier:typeof e.feeTier=="number"?e.feeTier:void 0},d=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5;if(r.length>0&&a.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:s.map(T),supportedChains:this.service.listSupportedChains().map(T),pools:[],count:0};let p=(await Promise.allSettled(i.map(f=>this.service.searchPools({tokens:n,chain:f,sortBy:l,filters:c})))).flatMap(f=>f.status==="fulfilled"?f.value:[]);l==="apr"?p.sort((f,h)=>(h.apr??0)-(f.apr??0)):l==="tvl"?p.sort((f,h)=>h.tvl-f.tvl):l==="volume"?p.sort((f,h)=>h.volume24hUsd-f.volume24hUsd):l==="fee"&&p.sort((f,h)=>f.feeTierBps-h.feeTierBps),p=p.slice(0,d);let m=[];return n.length===2&&(m=(await Promise.allSettled(i.map(h=>this.service.getCoinPoolPairs({chain:h,tokens:n})))).flatMap((h,g)=>h.status==="fulfilled"?h.value.map(b=>({...b,chain:T(i[g])})):[]),m.sort((h,g)=>(g.apr??-1/0)-(h.apr??-1/0)),m=m.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:n,chains:i.map(T),unsupportedChains:s.map(T),sortBy:l,filters:c,count:p.length,pools:p.map(f=>this.formatPool(f)),coinPoolPairs:m}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:Ye(e)}}};function Ye(o){return`https://app.uniswap.org/explore/pools/${$s[o.chain]||o.chain}/${o.poolAddress}`}var $s={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var Er=class extends P{name="subgraph-trending-pools";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).';category="blockchain-data";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}];service;constructor(e){super(),this.service=new Se(e)}async run(e,t){let n=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),r=n.filter(d=>!this.service.isSupported(d)),s=n.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(n.length>0&&s.length===0)return{_instructions:"User requested unsupported chains. Politely list them and the supported chains; do not show pool data.",unsupportedChains:r,supportedChains:this.service.listSupportedChains(),pools:[],count:0};if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new fe(typeof t?.query=="string"?t.query:void 0);let a=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,c=(await Promise.allSettled(a.map(d=>this.service.getTrendingPools({chain:d})))).flatMap(d=>d.status==="fulfilled"?d.value:[]);return c.sort((d,u)=>u.volume24hUsd-d.volume24hUsd),c=c.slice(0,i),{_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:a,unsupportedChains:r,count:c.length,pools:c.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:Ye(d)}))}}};var _r=class extends P{name="subgraph-pool-by-address";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").';category="blockchain-data";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}];service;constructor(e){super(),this.service=new Se(e)}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"This only supports Uniswap V3 pools. Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address)."};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new fe(typeof t?.query=="string"?t.query:void 0);let s=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(s))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[s],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(s),[i,l]=await Promise.all([this.service.getPoolByAddress({poolAddress:n,chain:a}),this.service.getCoinPoolByAddress({chain:a,poolAddress:n}).catch(()=>[])]);return i?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(l.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:a,coinPoolPairs:l,pool:{pair:i.pair,poolAddress:i.poolAddress,chain:i.chain,feeTierBps:i.feeTierBps,feeTierPercent:i.feeTierPercent,tvlUsd:i.tvl,volumePastDayUsd:i.volume24hUsd,fees24hUsd:i.fees24hUsd,apr:i.apr,token0:i.token0,token1:i.token1,uniswapUrl:Ye(i)}}:{error:`No pool found at ${n} on ${T(a)}.`}}};var Nr=class extends P{name="subgraph-pool-by-position-id";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.';category="blockchain-data";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:[]}];service;constructor(e){super(),this.service=new Se(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),s=r.filter(d=>!this.service.isSupported(d)),a=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.length>0&&a.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:s,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new fe(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(d=>this.service.getPoolByPositionId({positionId:n,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);return c?{_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 (skip the APR entirely when it is null \u2014 never write "APR 0%", "N/A" or a dash). 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:n,pool:{pair:c.pair,poolAddress:c.poolAddress,chain:c.chain,feeTierBps:c.feeTierBps,feeTierPercent:c.feeTierPercent,tvlUsd:c.tvl,volumePastDayUsd:c.volume24hUsd,fees24hUsd:c.fees24hUsd,apr:c.apr,token0:c.token0,token1:c.token1,uniswapUrl:Ye(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:n,chains:i,found:!1}}};var Lr=class extends P{name="subgraph-position-detail";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.`;category="blockchain-data";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:[]}];service;constructor(e){super(),this.service=new Se(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),s=r.filter(u=>!this.service.isSupported(u)),a=r.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(r.length>0&&a.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:s,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new fe(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(u=>this.service.getPositionDetail({positionId:n,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);if(!c)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:n,chains:i,found:!1};let d=$s[c.position.chain]||c.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 \u2014 skip the APR entirely when it is null, never write "APR 0%", "N/A" or a dash). 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:n,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${d}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:Ye(c.pool)}}}};var Ir=class extends P{name="subgraph-coinpool-pairs";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.';category="blockchain-data";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}];service;constructor(e){super(),this.service=new Se(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new fe(typeof t?.query=="string"?t.query:void 0);let s=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(s))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[s],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(s),i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,l=await this.service.getCoinPoolPairs({chain:a,tokens:n});if(l.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:n,chain:a,pairs:[],count:0};let c=[...l].sort((d,u)=>(u.apr??-1/0)-(d.apr??-1/0)).slice(0,i);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)". When an entry has no `apr` (null/absent), omit the APR part for that entry \u2014 never write "APR 0%", "N/A" or a dash. Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:n,chain:a,count:c.length,pairs:c}}};var Ur=class extends P{name="subgraph-add-pool";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.';category="blockchain-data";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}];service;linkAddLiquidity;constructor(e){super(),this.service=new Se(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let u=this.linkAddLiquidity??null,p=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",m="",f=[];if(this.service.isSupported(p)){m=this.service.resolveChain(p);try{f=(await this.service.searchPools({tokens:[],chain:m,sortBy:"tvl"})).slice(0,5)}catch{f=[]}}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:
|
|
208
208
|
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.
|
|
209
|
-
`+(
|
|
210
|
-
Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:m||void 0,addLiquidityLink:d,count:g.length,pools:g.map(h=>this.formatPool(h))}}let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase()),s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,a=typeof e.chain=="string"&&e.chain.trim();if(!a&&!t?.chain&&t?.walletAddress)throw new ie(typeof t?.query=="string"?t.query:void 0);let i=a?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(i))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:[T(i)],supportedChains:this.service.listSupportedChains().map(T)};let l=this.service.resolveChain(i);if(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let d=await this.service.getPoolByAddress({poolAddress:n,chain:l});return d?this.poolsResult([d],l,!0):{error:`No pool found at ${n} on ${T(l)}.`}}if(o.length>0){let d=await this.service.searchPools({tokens:o,chain:l,sortBy:"tvl",filters:{feeTier:s}});if(d.length===0)return{error:`No Uniswap V3 pool found for ${o.join("/")}${s!=null?` at ${s}bps`:""} on ${T(l)}. Ask the user to check the token symbols, or try a different pair.`};let p=o.length===2?await this.fetchCoinPoolPairs(l,o):[];return this.poolsResult(d.slice(0,8),l,!0,p)}let c=await this.service.searchPools({tokens:[],chain:l,sortBy:"tvl"}),u=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(u)+"Do NOT mention tool names, UI, or forms.",chain:l,needsSelection:!0,addLiquidityLink:u,count:c.length,pools:c.slice(0,6).map(d=>this.formatPool(d))}}async fetchCoinPoolPairs(e,t){try{return[...await this.service.getCoinPoolPairs({chain:e,tokens:t})].sort((o,s)=>(s.apr??-1/0)-(o.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(e){return e?`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 (${e}) 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. [${e}](${e}). For example: "You can add liquidity here: [${e}](${e})". 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(e,t,n,o=[]){let s=n?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). '+(s?`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. [${s}](${s}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${s}](${s})." 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:t,addLiquidityLink:s,count:e.length,pools:e.map(i=>this.formatPool(i)),coinPoolPairs:o}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:Oe(e)}}};function yt(r){if(typeof r=="number")return Number.isFinite(r)&&r>0?{kind:"token",value:r,raw:String(r)}:null;if(typeof r!="string")return null;let e=r.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 t=e.match(/^%?\s*([0-9]*\.?[0-9]+)\s*%$|^%\s*([0-9]*\.?[0-9]+)$/);if(t){let s=parseFloat(t[1]??t[2]);return Number.isFinite(s)&&s>0?{kind:"percent",percent:s,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 s=parseFloat(n[1]??n[2]??n[3]??n[4]);return Number.isFinite(s)&&s>0?{kind:"usd",usd:s,raw:e}:null}let o=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(o){let s=parseFloat(o[1]);return Number.isFinite(s)&&s>0?{kind:"token",value:s,raw:e}:null}return null}function Ed(r,e){switch(r.kind){case"token":return{ok:!0,amount:r.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*r.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:r.usd/e.usdPrice}}}var _d={send:30000n,swap:1000000n};async function Bf(r){try{let e=await we(r).getGasPrice();return e>0n?e:0n}catch{return 0n}}function Nd(r,e){let t=_d[r],n=qf(e);return n!==null&&n>t?n:t}function qf(r){let e=r?.tx?.gas??r?.estimatedTransactionFee?.details?.gasLimit;if(e==null)return null;try{let t=typeof e=="bigint"?e:BigInt(e);return t>0n?t:null}catch{return null}}async function Hl(r,e,t={}){let[n,o]=await Promise.all([Bf(r),t.provider?Qa({provider:t.provider,srcChainId:r,dstChainId:t.dstChainId??r}):Promise.resolve(0n)]);return(n>0n?Nd(e,t.quoteGas)*n:0n)+o}async function Es(r,e,t={}){return Hl(r,e,t)}function _s(r,e,t){if(e<=0n)return r;let n=ue(t)?.native.decimals;if(n===void 0)return r;let o=Number(e)/10**n;return!Number.isFinite(o)||o<=0?r:Math.max(0,r-o)}function Vl(r,e){let t=ue(e)?.native.decimals;if(t===void 0)return null;let n=Number(r)/10**t;return Number.isFinite(n)?n:null}function Ud(r){let{nativeBalance:e,feeWei:t,chainId:n}=r;if(t<=0n)return null;let o=Vl(t,n);if(o===null||o<=0||!Number.isFinite(e)||e>o)return null;let s=Math.ceil(Math.max(0,o-e)*1e8)/1e8;return s>0?s:1e-8}async function Ns(r){let{chainId:e,gasKind:t,readNativeBalance:n,feeContext:o}=r;if(!e)return null;try{let[s,a]=await Promise.all([Hl(e,t,o??{}),n()]),i=Ud({nativeBalance:a?.balance??0,feeWei:s,chainId:e});return i===null?null:{shortfall:i,nativeSymbol:a?.symbol??ue(e)?.native.symbol??"the native coin",fee:Vl(s,e)??0}}catch{return null}}var Ve=class extends P{kind="ui";category="wallet-action";buildUI(e){let t={action:this.actionType,chainId:e.chainId,chainName:T(e.chainId),walletAddress:e.walletAddress,parameters:e.parameters};return{component:this.component,props:t}}userInputFields=[];moralis;constructor(e){super(),e!==void 0&&(this.moralis=new L(e))}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}parseDecimals(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isInteger(t)&&t>=0)return t}}async resolveTokenRef(e){let{contractArg:t,symbolArg:n,decimalsArg:o,chain:s,walletAddress:a}=e,i=this.parseDecimals(o),l=typeof n=="string"&&n.trim()?n.trim():void 0,c=this.normaliseAddress(t),u=typeof t=="string"&&t.trim()?t.trim():void 0,d=c??l??u;if(!d)return{token:void 0};let p=await this.resolveContractAddress(d,s,a);return p?{token:{address:p.address,symbol:l??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:l,decimals:i}}:{error:"token_not_found",key:d}}requireWallet(e){let t=e?.walletAddress;return t?{ok:!0,address:t}:{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(e,t){return G(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:n,chain:o,walletAddress:s,gasKind:a}=e,i=yt(t);if(!i)return null;let l=e.symbol??"the token",c=n.toLowerCase()==="native",u=!!a&&c&&!!o;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let d=await this.readTokenBalanceAndPrice(n,o,s),p=d?.balance;u&&d?.balance!==void 0&&(p=await this.computeNativeSpendable(o,a,d.balance));let m=Ed(i,{balance:p,usdPrice:d?.usdPrice});return m.ok?{amount:this.toPlainDecimal(m.amount)}:m.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${l} balance to work out ${i.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 ${l} 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 ${l} to work out ${i.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 ${l} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(e,t,n){let o=await Es(e,t);return _s(n,o,e)}async resolveNativeSpendableFormatted(e,t,n){if(!(!e||!t))try{let o=await this.readTokenBalanceAndPrice("native",e,t);if(o?.balance===void 0)return;let s=await this.computeNativeSpendable(e,n,o.balance);return this.toPlainDecimal(s)}catch{return}}async readTokenBalanceAndPrice(e,t,n){if(!this.moralis||!n)return;let o=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=o.success?o.data?.result??[]:[],a=e.toLowerCase()==="native",i=e.toLowerCase(),l=s.find(u=>a?u.native_token===!0:(u.token_address??"").toLowerCase()===i);if(!l)return;let c=l.balance_formatted!=null?Number(l.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof l.usd_price=="number"&&l.usd_price>0?l.usd_price:void 0,balanceFormatted:l.balance_formatted,symbol:l.symbol}}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isFinite(t)||t<=0)return;let o=n*t;if(!(!Number.isFinite(o)||o<=0))return this.toPlainDecimal(o)}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let n=this.requireWallet(t);if(!n.ok)return n.payload;let o=kr(e.chain,t);if(o){let f=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${f} on ${o.requestedLabel}, but their wallet is connected to ${o.connectedLabel}. Tell them, in their language, that to ${f} on ${o.requestedLabel} they must first switch their wallet's network to ${o.requestedLabel}, or they can ${f} on ${o.connectedLabel} (their current network) instead. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}let s=this.requireChain(e,t);if(!s){let f=typeof t?.query=="string"?t.query:void 0;return vr(this.actionType.replace(/_/g," "),f)}let a=await this.buildParameters(e,t);if(a&&typeof a=="object"&&"error"in a&&typeof a.error=="string"||a&&typeof a=="object"&&"actionButtons"in a&&Array.isArray(a.actionButtons)||a&&typeof a=="object"&&"ui"in a&&a.ui&&typeof a.ui=="object"&&typeof a.ui.component=="string")return a;let i=a,l=this.buildUI({parameters:i,chainId:s,walletAddress:n.address}),c=f=>{let b=i[f];return b!=null&&b!==""},u=this.userInputFields.filter(f=>!(Array.isArray(f.key)?f.key:[f.key]).some(c)).map(f=>f.label),d=this.userInputFields.map(f=>{let y=(Array.isArray(f.key)?f.key:[f.key]).find(c);return y?`${f.label}: ${i[y]}`:null}).filter(f=>f!=null),p=this.actionType.replace(/_/g," "),m='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.',g="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.",h=u.length>0?`The ${p} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${u.join(", ")}. `+(d.length>0?`Already provided: ${d.join("; ")}. `:"")+`${g} ${m}`:`The ${p} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${p}. `+(d.length>0?`Details provided: ${d.join("; ")}. `:"")+`${g} ${m}`;return{ui:l,action:this.actionType,chainId:s,parameters:i,_instructions:h}}};var Eo=class extends Ve{name="open-send-native-form";actionType="send_native";component="SendNativeForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}async run(e,t){if(e.chain==null||e.chain===""){let n=nu(e.native_symbol);if(n)return super.run({...e,chain:n},t)}return super.run(e,t)}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.`;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 buildParameters(e,t){let n={},o=this.requireChain(e,t)??void 0,s=t?.walletAddress??void 0,a=await this.readTokenBalanceAndPrice("native",o,s);if(!a||a.balance==null||a.balance<=0){let d=a?.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 i=a.symbol||(typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0);if(i&&(n.native_symbol=i),e.to_address!=null){let d=this.normaliseAddress(e.to_address);d?n.to_address=d:typeof e.to_address=="string"&&e.to_address.trim()&&(n.to_address=e.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:o,walletAddress:s,gasKind:"send"});if(l&&"error"in l)return l;l&&(n.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(o,s,"send");c!==void 0&&(n.spendable=c);let u=this.formatSpendableUsd(c,a.usdPrice);return u!==void 0&&(n.spendableUsd=u),n}};var _o=class extends Ve{name="open-send-token-form";actionType="send_token";component="SendTokenForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}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.`;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(e,t){let n=this.normaliseAddress(e.contract_address)!=null,o=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!n&&!o&&this.moralis){let d=this.requireChain(e,t)??void 0,p=t?.walletAddress;if(p){let m=await this.moralis.getWalletTokenBalances({address:p,chain:d,excludeSpam:!1,excludeUnverifiedContracts:!1}),h=(m.success?m.data?.result??[]:[]).filter(v=>v.symbol&&(v.native_token||v.token_address)).sort((v,A)=>(A.usd_value??0)-(v.usd_value??0)).slice(0,8);if(h.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 f=e.to_address!=null?this.normaliseAddress(e.to_address):null,b=this.normaliseAmount(e.amount),y=typeof e.send_prompt_template=="string"?e.send_prompt_template:"",w=d?T(d):null;return{actionButtons:h.map(v=>{let A=v.symbol,S=v.balance_formatted?this.cleanAmountString(v.balance_formatted):"",C=v.name?v.name:"",O=v.usd_value?`($${v.usd_value.toFixed(2)})`:"";return{label:`${C}:${S} ${A} ${O}`.trim(),prompt:this.buildSendPrompt(y,A,b,f,w)}}),_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 s=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0,i=await this.findOwnedTokenForSend(e,s,a);if(i&&"error"in i)return i;let l=i?.token,c={};l?.address&&(c.contract_address=l.address),l?.symbol&&(c.token_symbol=l.symbol),l?.decimals!==void 0&&(c.decimals=String(l.decimals)),i?.spendable!==void 0&&(c.spendable=i.spendable);let u=this.formatSpendableUsd(i?.spendable,i?.usdPrice);if(u!==void 0&&(c.spendableUsd=u),e.to_address!=null){let d=this.normaliseAddress(e.to_address);d?c.to_address=d:typeof e.to_address=="string"&&e.to_address.trim()&&(c.to_address=e.to_address.trim())}if(l?.address){let d=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:l.address,symbol:l.symbol,chain:s,walletAddress:a});if(d&&"error"in d)return d;d&&(c.amount=d.amount)}else{let d=this.normaliseAmount(e.amount);d&&(c.amount=d)}return c}async findOwnedTokenForSend(e,t,n){let o=this.normaliseAddress(e.contract_address),s=typeof e.token_symbol=="string"&&e.token_symbol.trim()?e.token_symbol.trim():void 0,a=o??s;if(!this.moralis||!n||!a){let m=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:n});return"error"in m?{error:"token_not_found",symbol:m.key,_instructions:`Could not resolve token "${m.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:m.token}}let i=a.toLowerCase(),l=o!=null,c=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=(c.success?c.data?.result??[]:[]).find(m=>l?(m.token_address??"").toLowerCase()===i:(m.symbol??"").toLowerCase()===i);if(d&&d.balance&&!/^0*$/.test(d.balance.trim())){let m=this.parseDecimals(e.decimals);return{token:{address:d.token_address,symbol:d.symbol??s,name:d.name,decimals:m??(typeof d.decimals=="number"?d.decimals:void 0)},spendable:d.balance_formatted?this.cleanAmountString(d.balance_formatted):void 0,usdPrice:typeof d.usd_price=="number"&&d.usd_price>0?d.usd_price:void 0}}let p=d?.symbol??s??a;return{error:"no_balance",symbol:p,_instructions:`The user does not hold any ${p} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${p} 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(e,t,n,o,s){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,n??"");return i=this.fillOrDropPhrase(i,"{to}",o),i=this.fillOrDropPhrase(i,"{chain}",s),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,n){if(n)return e.split(t).join(n);let o=t.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${o}`,"g"),"").replace(new RegExp(`${o}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(o,"g"),"")}};var No=class extends Ve{name="open-approve-token-form";actionType="approve_token";component="ApproveTokenForm";userInputFields=[{key:"spender_address",label:"the spender address to approve"}];constructor(e){super(e)}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".';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(e,t){let n=this.requireChain(e,t)??void 0,o=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:n,walletAddress:t?.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 s=o.token,a=this.normaliseAddress(e.spender_address),i={};if(s?.address&&(i.contract_address=s.address),a&&(i.spender_address=a),s?.symbol&&(i.token_symbol=s.symbol),s?.decimals!==void 0&&(i.decimals=String(s.decimals)),typeof e.amount=="string"&&e.amount.trim()){let l=e.amount.trim(),c=parseFloat(l);Number.isFinite(c)&&c>=0&&(i.amount=l)}else typeof e.amount=="number"&&Number.isFinite(e.amount)&&e.amount>=0&&(i.amount=String(e.amount));return i}};function Za(r){let{action:e,fromSym:t,toSym:n,amount:o,spendable:s}=r,a=e==="swap"?`swap ${t} to ${n}`:`buy ${n} with ${t}`,i=e==="swap"?"swapping":"buying",l=e==="swap"?`swap ${o} ${t} to ${n}`:`buy ${n} with ${o} ${t}`,c=s?` They have ${s} ${t} available to spend.`:"";return(o?`The user wants to ${l}.${c} Reply briefly in the user's language confirming the amount and asking them to review and complete it. `:`The user wants to ${a}.${c} Reply briefly in the user's language: state what they want to do${s?" and their available balance":""}, then ask how much they want to ${e}. `)+`Do NOT list amounts or percentages, and do NOT state an estimated receive amount or a rate \u2014 you do not have one. Speak only of the user's action (${i}) \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, buttons, or forms.`}var Ct=r=>r.logo||r.icon_image||r.logoURI||r.thumbnail||void 0,$f=r=>Number.isFinite(r)?ss(parseFloat(r.toPrecision(8))):"0",Hf=r=>{if(!/e/i.test(r))return r;let e=Number(r);return Number.isFinite(e)?ss(e):r};async function Us(r){let{moralis:e,walletAddress:t,tokenAddress:n,chain:o,kind:s="swap",feeContext:a,dbg:i}=r;if(!e)return null;let l=await e.getWalletTokenBalances({address:t,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1}),c=l.success?l.data?.result??[]:[];i?.("readSpendableBalance",{tokenAddress:n,chain:o,ok:l.success,count:c.length});let u=n.toLowerCase(),d=c.find(m=>u==="native"?m.native_token===!0:m.token_address?.toLowerCase()===u);if(!d?.balance_formatted)return i?.("readSpendableBalance: token NOT held \u2192 null",{tokenAddress:n}),null;let p=Number(d.balance_formatted);if(!Number.isFinite(p)||p<=0)return i?.("readSpendableBalance: zero/invalid balance \u2192 null",{tokenAddress:n,balance:d.balance_formatted}),null;if(u==="native"&&o){let m=await Es(o,s,a??{}),g=_s(p,m,o);if(i?.("readSpendableBalance: native spendable",{balanceNum:p,spendable:g}),g<=0)return i?.("readSpendableBalance: native spendable \u2264 0 \u2192 null",{balanceNum:p}),null;let h=$f(g),f=typeof d.decimals=="number"?d.decimals:18;return Id({balanceFormatted:h,balanceNum:g,symbol:d.symbol,decimals:f,logo:Ct(d)})}return i?.("readSpendableBalance: held",{tokenAddress:n,balance:d.balance_formatted,symbol:d.symbol}),Id({balanceFormatted:d.balance_formatted,balanceNum:p,symbol:d.symbol,decimals:typeof d.decimals=="number"?d.decimals:void 0,logo:Ct(d)})}function Id(r){let e=Hf(r.balanceFormatted),t=r.decimals===void 0?null:Sn(e,r.decimals);return{...r,balanceFormatted:e,rawAmount:t?.toString()}}function Uo(r){let e=r?.trim();if(!e)return"";let t=T(e);return!t||t==="the requested chain"||t===e?"":` (${t})`}var Io=class extends P{name="open-buy-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new L(e),this.pantograph=new me({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[BuyTokenTool] ${e}`):console.log(`[BuyTokenTool] ${e}`,JSON.stringify(t)))}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.';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}. Do NOT write the chain name yourself \u2014 the chain these tokens are on is appended automatically as a "(<chain>)" suffix, e.g. "buy PEPE (Base)".`,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). Do NOT write the chain name yourself \u2014 the chain is appended automatically as a "(<chain>)" suffix, e.g. "buy PEPE with ETH (Base)".`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){if(!t?.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=kr(e.chain,t);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(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return vr("buy",a)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let n=typeof e.token_symbol=="string"?e.token_symbol.trim():"",o=typeof e.contract_address=="string"?e.contract_address.trim():"",s=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:s,walletAddress:a,hasMoralis:!!this.moralis}),!n&&!o)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(e,t);let i=await this.resolveSide(e.contract_address,n,s,a,"dest"),l=i.address,c=i.symbol??n,u=i.decimals,d=i.logo,p=await this.resolveSide(e.pay_with_address,e.pay_with_symbol,s,a,"pay"),m=p.address,g=p.symbol,h=p.decimals,f=await this.resolveBuyAmountSpec(e.buy_amount,l,s,c),b=m?await this.resolvePayAmountSpec(e.pay_with_amount,m,s,a,g,h??(m==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),y=yt(e.pay_with_amount),w=!!y&&y.kind!=="token",k=null;if(this.dbg("resolved sides",{dest:{destContract:l,destSymbol:c,destDecimals:u},pay:{payAddr:m,paySymbol:g,payDecimals:h},buyAmount:f,payAmount:b}),!l)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${c||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&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:c,destContract:l,buyAmount:f,payAmount:b});if(!m)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${c}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(f&&!b){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:f,destSymbol:c,paySymbol:g});let v=await this.derivePayAmountFromBuy({chain:s,buyAmount:f,destContract:l,destSymbol:c,payAddr:m,paySymbol:g});if(!v)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 ${f} ${c} 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=v,k=f,w=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:b,derivedFromBuy:k})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:m,paySymbol:g,payAmount:b});let v=await this.checkPayBalance({args:e,userContext:t,chain:s,destSymbol:c,destContract:l,payAddr:m,paySymbol:g,payAmount:b,buyAmount:f,derivedFromBuy:k,amountSizedToBalance:w});if(v)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:v.error,hasButtons:Array.isArray(v.actionButtons)}),v;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!f&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{payAmount:b});let v=await this.buildAmountForm({userContext:t,chain:s,destContract:l,destSymbol:c,destDecimals:u,destLogo:d,payAddr:m,paySymbol:g,payDecimals:h,payAmount:b??void 0});if(v)return this.dbg("\u2192 Branch 1.5: amount form returned"),v;this.dbg("Branch 1.5: amount form null \u2014 needs a resolvable pay token")}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 ${c}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!n)return null;let o=parseFloat(n[1]);return Number.isFinite(o)&&o>0?n[1]:null}correctAmountSide(e,t){let n=typeof t?.query=="string"?t.query:"",o=typeof e.token_symbol=="string"?e.token_symbol.trim():"",s=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"";if(!n||!o||!s)return;let a=typeof e.buy_amount=="string"?e.buy_amount.trim():"",i=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",l=a.length>0,c=i.length>0;if(l===c)return;let u=l?a:i,d=u.match(/[0-9]*\.?[0-9]+/)?.[0];if(!d)return;let p=this.nearestSymbolSide(n,d,o,s);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:u,buySym:o,paySym:s}),e.pay_with_amount=u,e.buy_amount=""):p==="buy"&&c&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:u,buySym:o,paySym:s}),e.buy_amount=u,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let o=typeof e.token_symbol=="string"?e.token_symbol.trim():"";if(!o)return;let s=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"",a=typeof e.pay_with_address=="string"?e.pay_with_address.trim():"";if(!s&&!a)return;let i=n.toLowerCase(),l=s.toLowerCase(),c=a.toLowerCase(),u=l==="native"||c==="native",d=[];if(s&&l!=="native"&&d.push(l),c&&c!=="native"&&d.push(c),u){d.push("native");let m=this.requireChain(e,t)??void 0,g=m?ue(m)?.native.symbol:void 0;g&&d.push(g.toLowerCase())}d.some(m=>R(m)?i.includes(m):this.indexOfToken(i,m)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:s,payAddr:a,buySym:o}),e.pay_with_symbol="",e.pay_with_address="")}dropInventedAmounts(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let o=(n.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),s=a=>{let i=typeof e[a]=="string"?e[a].trim():"";if(!i)return;let l=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(l===void 0)return;let c=parseFloat(l);Number.isFinite(c)&&(o.some(u=>u===c)||(this.dbg(`dropInventedAmounts: clearing invented ${a}`,{val:i}),e[a]=""))};s("buy_amount"),s("pay_with_amount")}nearestSymbolSide(e,t,n,o){let s=e.toLowerCase(),a=s.indexOf(t.toLowerCase()),i=this.indexOfToken(s,n.toLowerCase()),l=this.indexOfToken(s,o.toLowerCase());if(a<0||i<0||l<0)return null;let c=(p,m)=>Math.max(0,p-(a+t.length),a-(p+m)),u=c(i,n.length),d=c(l,o.length);return d===u?null:d<u?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=e.match(new RegExp(`(?:^|[^a-z0-9])(${n})(?:[^a-z0-9]|$)`));return o&&o.index!==void 0?o.index+o[0].indexOf(o[1]):-1}requireChain(e,t){return G(e.chain,t)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:Ct(c)}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:Ct(c)}}}async resolveSide(e,t,n,o,s="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,u=m=>m.toLowerCase()===se?"native":m,d=l??c??(a||void 0);if(!d)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(d,n,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:n,key:d,lookup:p}),p?{address:u(p.address),symbol:c??p.symbol,decimals:p.decimals,logo:p.logo}:l?{address:u(l),symbol:c}:{address:null,symbol:c}}async derivePayAmountFromBuy(e){let{chain:t,buyAmount:n,destContract:o,payAddr:s}=e,[a,i]=await Promise.all([this.getUsdPrice(o,t),this.getUsdPrice(s,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:a,payPrice:i}),!a||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,u=l*a/i;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?se:e,o=await this.moralis.getTokenMetadata({address:n,chain:t}),s=o.success?o.data?.usd_price:void 0;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}async resolvePayAmountSpec(e,t,n,o,s,a){let i=yt(e);if(!i)return null;let l=u=>a===void 0?u:At(u,a);if(i.kind==="token")return l(xn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let u=await this.readPayBalance(o,t,n);if(this.dbg("resolvePayAmountSpec: percent",{percent:i.percent,paySymbol:s,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??a??18;return i.percent>=100?this.cleanAmountString(u.balanceFormatted):Cn(u.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,d)}let c=await this.getUsdPrice(t,n);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,n,o){let s=yt(e);if(!s)return null;if(s.kind==="token")return xn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,n);return this.dbg("resolveBuyAmountSpec: usd",{usd:s.usd,destSymbol:o,price:a}),a?this.trimAmount(s.usd/a):null}async buildPayWithPicker(e){let{args:t,userContext:n,destSymbol:o,destContract:s}=e,a=this.requireChain(t,n)??void 0,i=this.moralis,l=n.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1}),u=c.success?c.data?.result??[]:[],d=s?.toLowerCase(),p=o.trim().toLowerCase(),m=u.filter(y=>!y.symbol||p&&y.symbol.toLowerCase()===p?!1:y.native_token?d!=="native":!(!y.token_address||d&&y.token_address.toLowerCase()===d)).sort((y,w)=>(w.usd_value??0)-(y.usd_value??0)).slice(0,8);if(m.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 g=e.buyAmount??this.normaliseAmount(t.buy_amount),h=e.payAmount??this.normaliseAmount(t.pay_with_amount),f=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:m.map(y=>{let w=y.symbol,k=y.name?.trim()||w,v=y.balance_formatted?`${this.cleanAmountString(y.balance_formatted)} `:"",A=typeof y.usd_value=="number"&&y.usd_value>0?` ($${y.usd_value.toFixed(2)})`:"",S=`${k}: ${v}${w}${A}`,C=g?this.buildBuyWithPrompt(f,o,w,g,null,a):this.buildBuyWithPrompt(f,o,w,null,h,a);return{label:S,prompt:C}}),_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(e){let{args:t,userContext:n,chain:o,destSymbol:s,destContract:a,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:u}=e,d=n.walletAddress,p=await this.readPayBalance(d,i,o),m=e.paySymbol??p?.symbol??"the selected token";if(!p){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:m});let y=await this.buildPayWithPicker({args:t,userContext:n,destSymbol:s,destContract:a,buyAmount:c,payAmount:l});return"actionButtons"in y?{error:"no_pay_balance",actionButtons:y.actionButtons,_instructions:`The user wanted to spend ${m} to buy ${s}, but their wallet holds no ${m} 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 ${m} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${m} 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 ${s} 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.`}:y}if(i.toLowerCase()!=="native"){let y=await Ns({chainId:o,gasKind:"swap",readNativeBalance:()=>this.readNativeHeldBalance(d,o)});if(y)return this.dbg("checkPayBalance: cannot cover gas",y),{error:"insufficient_native_for_gas",_instructions:`The wallet holds ${m} but cannot cover the network fee for this purchase: it needs about ${y.shortfall} more ${y.nativeSymbol}. Tell the user in their language that they need roughly ${y.shortfall} more ${y.nativeSymbol} to pay the network fee before they can buy ${s} (e.g., 'B\u1EA1n c\u1EA7n th\xEAm kho\u1EA3ng ${y.shortfall} ${y.nativeSymbol} \u0111\u1EC3 tr\u1EA3 ph\xED m\u1EA1ng.'), and suggest they top up ${y.nativeSymbol} first. Do NOT open a form, do NOT invent a different number, and do NOT mention tool names, UI, or forms.`}}if(!l||e.amountSizedToBalance)return null;let g=p.decimals!==void 0?At(l,p.decimals):l;if(Yt(g,p.balanceFormatted)<=0)return null;let h=this.cleanAmountString(p.balanceFormatted),f=this.percentSpendButtons({balanceFormatted:p.balanceFormatted,balanceNum:p.balanceNum,decimals:p.decimals,paySymbol:m,destSymbol:s,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"",...o===void 0?{}:{chain:o}}),b=u?`Buying ${u} ${s} needs about ${l} ${m}, but they only have ${h} ${m} 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 ${u} ${s} would cost about ${l} ${m}, which is more than their balance of ${h} ${m}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${l} ${m} to buy ${s}, but they only have ${h} ${m} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${l} ${m} exceeds their balance of ${h} ${m}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:f,_instructions:b+'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(e,t,n){return Us({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:n,kind:"swap",dbg:(o,s)=>this.dbg(o,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let n=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(n.success?n.data?.result??[]:[]).find(i=>i.native_token===!0),a=s?.balance_formatted!=null?Number(s.balance_formatted):0;return{balance:Number.isFinite(a)?a:0,...s?.symbol===void 0?{}:{symbol:s.symbol}}}catch{return{balance:0}}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,paySymbol:o,destSymbol:s,buyWithTemplate:a,chain:i}=e,l=n??18;return[25,50,75,100].map(u=>{let d=Cn(this.cleanAmountString(t),BigInt(u),100n,l);return{label:`${u}%`,prompt:this.buildBuyWithPrompt(a,s,o,null,d,i)}})}async buildAmountForm(e){let{userContext:t,chain:n,destContract:o,destSymbol:s,destDecimals:a,destLogo:i,payAddr:l,payAmount:c}=e,u=t.walletAddress;if(!n)return null;let d=ue(n);if(!d)return null;let p=await this.readPayBalance(u,l,n),m=e.paySymbol??p?.symbol;if(!m)return null;let g=l==="native",h=p?.decimals??e.payDecimals??(g?d.native.decimals??18:void 0);if(h===void 0)return null;let f=p?.balanceFormatted,b=p?.rawAmount??(f?Sn(f,h)?.toString():void 0);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:n,name:d.name},fromToken:{address:g?"native":l,symbol:m,decimals:h,amount:f,rawAmount:b??void 0,logo:p?.logo},toToken:{address:o,symbol:s,decimals:a,logo:i},walletAddress:u,intent:"buy",initialAmount:c}},_instructions:Za({action:"buy",fromSym:m,toSym:s,amount:c,spendable:f})}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildBuyPrompt(e,t,n){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+Uo(n)}buildBuyWithPrompt(e,t,n,o,s,a){return(e&&e.includes("{token}")&&e.includes("{pay}")?e:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,t).replace(/\{pay\}/g,n).replace(/\{buy_amount\}/g,o??"").replace(/\{pay_amount\}/g,s??"").replace(/\s+/g," ").trim()+Uo(a)}async buildTrendingPicker(e,t){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 n=this.requireChain(e,t)??void 0,o=typeof e.limit=="number"&&Number.isFinite(e.limit)?Math.floor(e.limit):6,s=Math.max(1,Math.min(10,o)),a=await this.pantograph.getTrendingTokens({chain:n,limit:s}),i=a.success?a.data??[]:[];if(i.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 l=i.filter(m=>m.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",u=l.map(m=>{let g=m.symbol;return{label:g,prompt:this.buildBuyPrompt(c,g,n)}}),p=l.map((m,g)=>{let h=m.name?.trim()||m.symbol,f=m.symbol,b=typeof m.usdPrice=="number"&&m.usdPrice>0?`$${this.formatPrice(m.usdPrice)}`:"N/A",y=m.pricePercentChange?.["24h"],w=typeof y=="number"&&Number.isFinite(y)?` (${y>0?"+":y<0?"-":""}${this.formatPercent(Math.abs(y))}%)`:"";return`${g+1}. ${h} (${f}) \u2014 ${b}${w}`}).join(`
|
|
209
|
+
`+(f.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':"")+(f.length>0?"3) ":"2) ")+this.linkInstruction(u)+`
|
|
210
|
+
Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:m||void 0,addLiquidityLink:u,count:f.length,pools:f.map(h=>this.formatPool(h))}}let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=(Array.isArray(e.tokens)?e.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase()),s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,a=typeof e.chain=="string"&&e.chain.trim();if(!a&&!t?.chain&&t?.walletAddress)throw new fe(typeof t?.query=="string"?t.query:void 0);let i=a?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(i))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:[T(i)],supportedChains:this.service.listSupportedChains().map(T)};let l=this.service.resolveChain(i);if(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let u=await this.service.getPoolByAddress({poolAddress:n,chain:l});return u?this.poolsResult([u],l,!0):{error:`No pool found at ${n} on ${T(l)}.`}}if(r.length>0){let u=await this.service.searchPools({tokens:r,chain:l,sortBy:"tvl",filters:{feeTier:s}});if(u.length===0)return{error:`No Uniswap V3 pool found for ${r.join("/")}${s!=null?` at ${s}bps`:""} on ${T(l)}. Ask the user to check the token symbols, or try a different pair.`};let p=r.length===2?await this.fetchCoinPoolPairs(l,r):[];return this.poolsResult(u.slice(0,8),l,!0,p)}let c=await this.service.searchPools({tokens:[],chain:l,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:l,needsSelection:!0,addLiquidityLink:d,count:c.length,pools:c.slice(0,6).map(u=>this.formatPool(u))}}async fetchCoinPoolPairs(e,t){try{return[...await this.service.getCoinPoolPairs({chain:e,tokens:t})].sort((r,s)=>(s.apr??-1/0)-(r.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(e){return e?`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 (${e}) 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. [${e}](${e}). For example: "You can add liquidity here: [${e}](${e})". 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(e,t,n,r=[]){let s=n?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). '+(s?`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. [${s}](${s}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${s}](${s})." 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:t,addLiquidityLink:s,count:e.length,pools:e.map(i=>this.formatPool(i)),coinPoolPairs:r}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:Ye(e)}}};var np={"0x1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x89":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa4b1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x38":"0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7","0x2105":"0x33128a8fC17869897dcE68Ed026d694621f6FDfD","0xa86a":"0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD"},by="e34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54",Zd=/^0x[a-fA-F0-9]{40}$/;function fi(o){let e=o.startsWith("0x")?o.slice(2):o,t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}function ep(o){let e=new Uint8Array(32);return e.set(fi(o.toLowerCase()),12),e}function wy(o){let e=new Uint8Array(32),t=BigInt(o);for(let n=31;n>=0&&t>0n;n--)e[n]=Number(t&0xffn),t>>=8n;return e}function tp(o){let e=o.reduce((r,s)=>r+s.length,0),t=new Uint8Array(e),n=0;for(let r of o)t.set(r,n),n+=r.length;return t}function ac(o){return Object.prototype.hasOwnProperty.call(np,o.toLowerCase())}function ic(o,e,t,n){let r=np[o.toLowerCase()];if(!r||!Zd.test(e)||!Zd.test(t)||!Number.isInteger(n)||n<=0)return null;let s=e.toLowerCase(),a=t.toLowerCase();if(s===a)return null;let[i,l]=BigInt(s)<BigInt(a)?[s,a]:[a,s],c=ha(tp([ep(i),ep(l),wy(n)]));return`0x${ha(tp([new Uint8Array([255]),fi(r),fi(c),fi(by)])).slice(2).slice(24)}`}var rp={"0x1":"Ethereum","0xa":"OP Mainnet","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche"},ky={ethereum:"0x1","op mainnet":"0xa",optimism:"0xa",bsc:"0x38",binance:"0x38",polygon:"0x89",base:"0x2105",arbitrum:"0xa4b1","arbitrum one":"0xa4b1",avalanche:"0xa86a","avalanche c-chain":"0xa86a"},op={"uniswap-v2":"V2","uniswap-v3":"V3","uniswap-v4":"V4"},vy=new Set([100,200,300,400,500,1e3,2500,3e3,1e4,2e4]),Ty="https://yields.llama.fi",Ay=300*1e3,Dr=Object.keys(rp),lc=new Map,Ue=class{baseUrl;cacheTtlMs;constructor(e){this.baseUrl=(e?.baseUrl||Ty).replace(/\/$/,""),this.cacheTtlMs=e?.cacheTtlMs??Ay}get store(){let e=lc.get(this.baseUrl);return e||(e={pools:null,fetchedAt:0,inflight:null},lc.set(this.baseUrl,e)),e}isSupported(e){return e?Object.prototype.hasOwnProperty.call(rp,e.toLowerCase()):!1}listSupportedChains(){return[...Dr]}async snapshot(){let e=this.store,t=Date.now();return e.pools&&t-e.fetchedAt<this.cacheTtlMs?e.pools:(e.inflight||(e.inflight=(async()=>{try{let n=await x.get(`${this.baseUrl}/pools`);if(!n.ok)throw new Error(`DefiLlama: ${_(n)}`);let r=n.data,a=(Array.isArray(r?.data)?r.data:[]).filter(i=>i&&typeof i.project=="string"&&op[i.project]!==void 0).map(i=>this.normalize(i)).filter(i=>i!==null);return e.pools=a,e.fetchedAt=Date.now(),a}catch(n){if(e.pools)return e.pools;throw n}finally{e.inflight=null}})()),e.inflight)}clearCache(){lc.delete(this.baseUrl)}parseFeeTierBps(e){if(typeof e!="string")return;let t=e.match(/([\d.]+)\s*%/);if(!t)return;let n=parseFloat(t[1]);if(!Number.isFinite(n)||n<=0)return;let r=Math.round(n*1e4);return vy.has(r)?r:void 0}normalize(e){let t=ky[String(e.chain).toLowerCase()];if(!t)return null;let n=op[e.project];if(!n)return null;let r=this.parseFeeTierBps(e.poolMeta),s=String(e.symbol||"").split(/[-/]/).map(p=>p.trim()).filter(Boolean),a=Array.isArray(e.underlyingTokens)?e.underlyingTokens.filter(p=>typeof p=="string"):[],i=n==="V3"&&r&&a.length===2&&ac(t)?ic(t,a[0],a[1],r)??void 0:void 0,l=typeof e.tvlUsd=="number"&&e.tvlUsd>0?e.tvlUsd:0,c=typeof e.volumeUsd1d=="number"&&e.volumeUsd1d>=0?e.volumeUsd1d:void 0,d=W(e.apyBase??e.apy),u=W(e.apy)??d;return{id:e.pool,pair:s.length>=2?`${s[0]}/${s[1]}`:String(e.symbol||""),chain:t,protocolVersion:n,address:i,feeTierBps:r,feeTierPercent:r!==void 0?r/1e4:void 0,tvlUsd:l,apr:d!==void 0?parseFloat(d.toFixed(2)):void 0,totalApr:u!==void 0?parseFloat(u.toFixed(2)):void 0,volume1DayUsd:c,volume7DayUsd:typeof e.volumeUsd7d=="number"&&e.volumeUsd7d>=0?e.volumeUsd7d:void 0,volumeToTvlRatio:c!==void 0&&l>0?parseFloat((c/l).toFixed(4)):void 0,fee24hUsd:c!==void 0&&r!==void 0?parseFloat((c*r/1e6).toFixed(2)):void 0,token0:s[0]||a[0]?{symbol:s[0],address:a[0]}:void 0,token1:s[1]||a[1]?{symbol:s[1],address:a[1]}:void 0,isStablecoin:e.stablecoin===!0?!0:void 0,ilRisk:typeof e.ilRisk=="string"?e.ilRisk:void 0,aprChange1D:typeof e.apyPct1D=="number"?e.apyPct1D:void 0,aprChange7D:typeof e.apyPct7D=="number"?e.apyPct7D:void 0,aprChange30D:typeof e.apyPct30D=="number"?e.apyPct30D:void 0,aprMean30d:typeof e.apyMean30d=="number"?parseFloat(e.apyMean30d.toFixed(2)):void 0}}sortValue(e,t){switch(t){case"apr":return e.apr??-1;case"volume1Day":return e.volume1DayUsd??-1;case"volume7Day":return e.volume7DayUsd??-1;default:return e.tvlUsd}}sorted(e,t){return[...e].sort((n,r)=>this.sortValue(r,t)-this.sortValue(n,t))}async getTopPools(e){try{let t=await this.snapshot(),n=e.protocolVersion??"V3",r=Math.min(Math.max(e.limit??10,1),50),s=t.filter(a=>a.chain===e.chain);return n!=="ALL"&&(s=s.filter(a=>a.protocolVersion===n)),e.forAddLiquidity&&(s=s.filter(a=>a.address!==void 0)),{success:!0,data:this.sorted(s,e.sortBy??"tvl").slice(0,r)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async searchPools(e){try{let t=await this.snapshot(),n=e.protocolVersion??"V3",r=Math.min(Math.max(e.limit??10,1),50),s=String(e.query||"").split(/[\s,/-]+/).map(i=>i.trim().toLowerCase()).filter(Boolean),a=t.filter(i=>i.chain===e.chain);return n!=="ALL"&&(a=a.filter(i=>i.protocolVersion===n)),e.forAddLiquidity&&(a=a.filter(i=>i.address!==void 0)),s.length>0&&(a=a.filter(i=>{let l=[i.token0?.symbol?.toLowerCase(),i.token1?.symbol?.toLowerCase(),i.token0?.address?.toLowerCase(),i.token1?.address?.toLowerCase()].filter(c=>typeof c=="string");return s.every(c=>l.some(d=>c.startsWith("0x")?d===c:this.symbolMatches(d,c)))})),{success:!0,data:this.sorted(a,e.sortBy??"tvl").slice(0,r)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}symbolMatches(e,t){return e===t||e===`w${t}`||t===`w${e}`}async getPoolsByPair(e){let t=[e.token0Symbol,e.token1Symbol].filter(Boolean).join(" "),n=await this.searchPools({chain:e.chain,query:t,limit:50,sortBy:"tvl",protocolVersion:e.protocolVersion??"V3"});return!n.success||!n.data?n:{success:!0,data:e.feeTierBps!==void 0?n.data.filter(s=>s.feeTierBps===e.feeTierBps):n.data}}async findByPoolAddress(e){try{let t=await this.snapshot(),n=e.address.toLowerCase();return{success:!0,data:t.find(s=>s.chain===e.chain&&s.address===n)??null}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async findPoolsByTokenAddress(e){try{let t=await this.snapshot(),n=e.address.toLowerCase(),r=t.filter(s=>s.chain===e.chain&&(s.token0?.address?.toLowerCase()===n||s.token1?.address?.toLowerCase()===n));return{success:!0,data:this.sorted(r,"tvl").slice(0,Math.min(e.limit??10,50))}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}};function qe(){return{kind:"info",async listSupported(){return Dr.filter(o=>Me(o))},async isSupported(o){if(!o)return!1;let e=M(o)??o.toLowerCase();return Dr.includes(e)}}}function $e(){return Dr.filter(o=>Me(o)).map(o=>T(o)).join(", ")}var He="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";var Py=["V2","V3","V4"];function Or(o){if(typeof o!="string")return"V3";let e=o.trim().toUpperCase();return e==="ALL"?"ALL":Py.includes(e)?e:"V3"}function Sy(o){return Object.fromEntries(Object.entries(o).filter(([,e])=>e!=null))}function Re(o){let e=qs(o.chain,o.address);return Sy({pair:o.pair,address:o.address,chain:o.chain,protocolVersion:o.protocolVersion,feeTierBps:o.feeTierBps,feeTierPercent:o.feeTierPercent,tvlUsd:o.tvlUsd,volume1DayUsd:o.volume1DayUsd,volume7DayUsd:o.volume7DayUsd,fee24hUsd:o.fee24hUsd,apr:o.apr,totalApr:o.totalApr!==void 0&&o.totalApr!==o.apr?o.totalApr:void 0,volumeToTvlRatio:o.volumeToTvlRatio,aprChange1D:o.aprChange1D,aprChange7D:o.aprChange7D,aprMean30d:o.aprMean30d,isStablecoin:o.isStablecoin,ilRisk:o.ilRisk,token0:o.token0,token1:o.token1,uniswapUrl:e??void 0,addLiquidityUnavailable:o.address===void 0?!0:void 0})}var ut='\u2022 APR trend \u2014 `aprChange1D` / `aprChange7D` are the change in APR over the last day / week in PERCENTAGE POINTS, and `aprMean30d` is the 30-day average APR. A spot `apr` far above `aprMean30d` is a spike that is unlikely to hold; one near or below it is steadier. Use these to judge whether a yield is durable rather than a snapshot. \u2022 `ilRisk` = "no" marks a pool upstream considers free of impermanent-loss exposure (typically a correlated or stablecoin pair); "yes" is the normal volatile-pair case. `isStablecoin` marks a stablecoin pair. \u2022 `totalApr` (when present and higher than `apr`) includes incentive/reward emissions on top of swap fees \u2014 call that out, since emissions can end at any time while fee yield does not. \u2022 `addLiquidityUnavailable: true` means this pool cannot be added to in-app \u2014 never offer to add liquidity to it. ';var xy=["tvl","volume1Day","volume7Day","apr"],Mr=class extends P{name="defillama-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens, TVL, rolling volume (1d / 7d), fee revenue, and APR (with 1d/7d/30d APR trend). Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap pools on Base", "which pools have the most liquidity", "show pools with the highest APR on Arbitrum". Source: DefiLlama Yields. Supports: `+$e();category="blockchain-data";parameters=[{name:"chain",type:"string",description:He,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", "V4", or "ALL". Default is "V3" (the dataset with the richest stats and the only one that supports adding liquidity in-app). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume7Day", or "apr" (annualized fee yield). Pools are returned in descending order by this metric. There is no 30-day volume or transaction-count ranking \u2014 for "most active" use "volume1Day".',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"forAddLiquidity",type:"boolean",description:"Set true when the user wants to ADD LIQUIDITY and is picking a pool (rather than just browsing). Validates ADD-LIQUIDITY chain support up front and returns ONLY pools that can actually be added to, so the user never picks a pool that dead-ends at the next step.",required:!1,default:!1},...Ce];service;pool;constructor(e){super(),this.service=new Ue(e),this.pool=new se}async run(e,t){let n=e.forAddLiquidity===!0,r=await Z(n?gn(this.pool):qe(),e.chain,t);if(!r.ok)return r.result;let s=r.chain,a=Or(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=xy.includes(i)?i:"tvl",c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=await this.service.getTopPools({chain:s,limit:c,sortBy:l,protocolVersion:a,forAddLiquidity:n});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=(d.data??[]).map(Re);if(u.length===0)return{_instructions:"No pools matched on this chain. Tell the user plainly, in their language, that no pools were found here and suggest another chain. Do NOT invent pools. Do NOT mention tools or APIs.",chain:T(s),count:0,pools:[]};let p=await this.pool.isAddLiquiditySupported(s)?ue(u.filter(m=>m.address!==void 0),e,T(s)):[];return{_instructions:de+"You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, 24h volume, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. "+pe+ut+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+ye+G+"Mention the chain and the sort metric in the intro line. "+z+(p.length>0?ce:""),chain:s,protocolVersion:a,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var Cy=["tvl","volume1Day","volume7Day","apr"],Fr=class extends P{name="defillama-search-pools";description='Search Uniswap liquidity pools by token symbol, token name, or token address on a given EVM chain. Use for: "show pools for USDC", "find WBTC pools on Base", "pools containing PEPE", "USDC/ETH pools on Arbitrum", "top USDC pools". Use this WHENEVER the user names a specific token \u2014 even with words like "top" or "biggest". Returns matching pools with pair, fee tier, TVL, 24h/7d volume, and APR. Source: DefiLlama Yields. Supports: '+$e();category="blockchain-data";parameters=[{name:"query",type:"string",description:'The token symbol(s), token name, or token address to search for. For a PAIR, pass both symbols separated by a space ("USDC WETH") \u2014 every term must appear in the pool, so this returns that pair specifically. For a single token pass just its symbol ("USDC").',required:!0},{name:"chain",type:"string",description:He,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", "V4", or "ALL". Default "V3". Use "ALL" only when the user explicitly wants every version.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric for the matches: "tvl" (default), "volume1Day", "volume7Day", or "apr". Use "volume1Day" when the user asked for the "top"/"biggest"/"most active" pools of a token.',required:!1,default:"tvl"},{name:"limit",type:"number",description:"Maximum number of pools to return. Defaults to 5, max 50.",required:!1,default:5},...Ce];service;pool;constructor(e){super(),this.service=new Ue(e),this.pool=new se}async run(e,t){let n=await Z(qe(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,s=typeof e.query=="string"?e.query.trim():"";if(!s)return{_instructions:"No search term was provided. Ask the user which token they want pools for, in their language. Do NOT mention tools or APIs."};let a=Or(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=Cy.includes(i)?i:"tvl",c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=await this.service.searchPools({chain:r,query:s,limit:c,sortBy:l,protocolVersion:a});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=(d.data??[]).map(Re);if(u.length===0)return{_instructions:"No pools matched this token on this chain. Tell the user plainly, in their language, that no pools were found for it here, and suggest checking another chain or a different token. NEVER invent pools. Do NOT mention tools or APIs.",chain:T(r),query:s,count:0,pools:[]};let p=await this.pool.isAddLiquiditySupported(r)?ue(u.filter(m=>m.address!==void 0),e,T(r)):[];return{_instructions:de+`Present the pools matching "${s}" as a ranked list, then deliver the analysis. For each pool include: pair, fee tier (in %), TVL in USD, 24h volume, and APR (in %). CRITICAL: every pool MUST have its own 2\u20133 sentence expert read directly under its facts \u2014 never a bare list. Vary the wording between pools and surface the non-obvious insight. `+pe+ut+"IMPORTANT \u2014 same pair, different pools: two pools can show the SAME pair and fee tier yet be different contracts (one of the tokens is an impostor wearing a well-known ticker). When you see that, flag the one with far lower TVL as the likely impostor and tell the user to verify the token contract before providing liquidity. Close with a short overall read: which of these pools is the most attractive for an LP right now and why. "+ye+G+z+(p.length>0?ce:""),chain:r,query:s,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var Br=class extends P{name="defillama-pool-detail";description='Get full statistics for ONE specific Uniswap pool identified by its TOKEN PAIR (and optional fee tier). Use for: "details for USDC/WETH 0.05% on Base", "TVL and APR of the WBTC/USDC pool", "how is the ETH/USDC pool doing". Returns TVL, 24h/7d volume, fee revenue, APR (with trend), fee tier, and both tokens. Pass token symbols \u2014 NEVER a pool address (use lookup-pool-by-address for an address). When several fee tiers match, returns a candidates list to choose from instead of a single pool. Source: DefiLlama Yields. Supports: '+$e();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of the first token in the pair, e.g. "USDC". Required.',required:!0},{name:"token1Symbol",type:"string",description:`Symbol of the second token, e.g. "WETH". Omit when the user named only one token \u2014 the tool then returns that token's pools as candidates.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points as Uniswap stores it: 100 = 0.01%, 500 = 0.05%, 3000 = 0.3%, 10000 = 1%. Omit when the user did not name one \u2014 the tool then returns the matching tiers as candidates.",required:!1},{name:"chain",type:"string",description:He,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version: "V2", "V3", "V4", or "ALL". Default "V3".',required:!1,default:"V3"},...Ce];service;pool;constructor(e){super(),this.service=new Ue(e),this.pool=new se}async run(e,t){let n=await Z(qe(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"";if(!s)return{_instructions:"No token was named. Ask the user which pool they mean, in their language. Do NOT mention tools or APIs."};let a=typeof e.token1Symbol=="string"&&e.token1Symbol.trim()?e.token1Symbol.trim():void 0,i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.round(e.feeTier):void 0,l=Or(e.protocolVersion),c=await this.service.getPoolsByPair({chain:r,token0Symbol:s,token1Symbol:a,feeTierBps:i,protocolVersion:l});if(!c.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:c.error};let d=c.data??[],u=[s,a].filter(Boolean).join("/");if(d.length===0)return{_instructions:"No pool matched that pair on this chain. Tell the user plainly, in their language, that this pool was not found here, and suggest another chain or checking the token symbols. NEVER invent pool stats. Do NOT mention tools or APIs.",chain:T(r),pair:u,pool:null};let p=await this.pool.isAddLiquiditySupported(r);if(d.length>1){let h=d.map(Re),g=p?ue(h.filter(b=>b.address!==void 0),e,T(r)):[];return{_instructions:`Several ${u} pools exist on this chain \u2014 they differ by fee tier. Present them as a short numbered list (pair, fee %, TVL, 24h volume, APR) with a one-line expert note on each saying which kind of LP it suits, then ask the user which one they want. Do NOT present any single one as "the" pool and do NOT merge their stats. `+z+(g.length>0?ce:""),chain:r,pair:u,count:h.length,candidates:h,...g.length>0?{actionButtons:g}:{}}}let m=Re(d[0]),f=p&&m.address!==void 0?ue([m],e,T(r)):[];return{_instructions:de+"Give a thorough read on this ONE pool. Lead with the facts \u2014 pair, fee tier (in %), chain, TVL, 24h volume, 24h fee revenue, and APR (in %) \u2014 then deliver several sentences of genuine expert analysis in flowing prose. "+pe+ut+"Close by telling the user concretely whether this pool is worth providing liquidity in right now, and for which kind of LP it is best suited. "+ye+G+z+(f.length>0?ce:""),chain:r,pair:u,pool:m,...f.length>0?{actionButtons:f}:{}}}};var Ry=/^0x[a-fA-F0-9]{40}$/,qr=class extends P{name="defillama-pool-by-address";description='Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use when the user pastes a single 0x address without saying which it is ("what is 0x88e6\u2026", "tell me about this address"). For pool resolution: pair, fee tier, TVL, volume, fee revenue and APR. For token resolution: the token plus a ranked list of pools containing it. Source: DefiLlama Yields, with an on-chain read as fallback. Supports: '+$e();category="blockchain-data";parameters=[{name:"address",type:"string",description:"A 0x-prefixed EVM address. May be a Uniswap pool contract OR a token contract \u2014 the tool figures out which.",required:!0},{name:"chain",type:"string",description:He,required:!1},...Ce];service;pool;constructor(e){super(),this.service=new Ue(e),this.pool=new se}async run(e,t){let n=await Z(qe(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,s=typeof e.address=="string"?e.address.trim():"";if(!Ry.test(s))return{_instructions:"The value provided is not a valid EVM address. Ask the user, in their language, to re-send the full 0x address. Do NOT mention tools or APIs."};let a=s.toLowerCase(),i=await this.pool.isAddLiquiditySupported(r),l=await this.service.findByPoolAddress({chain:r,address:a});if(l.success&&l.data){let u=Re(l.data),p=i&&u.address!==void 0?ue([u],e,T(r)):[];return{_instructions:de+"This address is a liquidity POOL. Lead with the facts \u2014 pair, fee tier (in %), chain, TVL, 24h volume, 24h fee revenue and APR (in %) \u2014 then give several sentences of genuine expert analysis. "+pe+ut+"Close by saying concretely whether this pool is worth providing liquidity in right now. "+ye+G+z+(p.length>0?ce:""),chain:r,resolvedAs:"pool",pool:u,...p.length>0?{actionButtons:p}:{}}}let c=await this.service.findPoolsByTokenAddress({chain:r,address:a,limit:10});if(c.success&&c.data&&c.data.length>0){let u=c.data.map(Re),p=c.data[0],m=p.token0?.address?.toLowerCase()===a?p.token0?.symbol:p.token1?.symbol,f=i?ue(u.filter(h=>h.address!==void 0),e,T(r)):[];return{_instructions:"The address is a TOKEN, not a pool. Tell the user which token it is, then present the pools containing it as a ranked numbered list (pair, fee %, TVL, 24h volume, APR) with a brief expert note on each. Invite them to pick one for a deeper look. "+pe+ut+z+(f.length>0?ce:""),chain:r,resolvedAs:"token",token:{address:a,symbol:m},count:u.length,pools:u,...f.length>0?{actionButtons:f}:{}}}let d=await this.readPoolOnchain(r,a);if(d){let u=i?ue([d],e,T(r)):[];return{_instructions:de+"This address IS a real Uniswap V3 pool on-chain, but it is not covered by the market-data feed, so ONLY the on-chain facts below are available: the token pair, the fee tier, and the current price. State those plainly, then say clearly that TVL, volume and APR are not available for this pool. CRITICAL: do NOT invent, estimate, or infer TVL, volume, APR or any yield figure \u2014 you have none. A pool missing from the market-data feed is usually very new or very thinly traded; say so, and advise the user to check its liquidity depth carefully before providing liquidity. "+G+z+(u.length>0?ce:""),chain:r,resolvedAs:"pool",dataSource:"onchain-only",pool:d,...u.length>0?{actionButtons:u}:{}}}return{_instructions:`This address matched neither a pool nor a token on ${T(r)}. Tell the user plainly, in their language, that nothing was found for it on this network, and suggest they check the address or try another chain. NEVER invent pool or token data. Do NOT mention tools or APIs.`,chain:T(r),address:a,resolvedAs:null}}async readPoolOnchain(e,t){try{let n=await this.pool.readPoolOnchain(e,t),[r,s]=await Jt(e,[n.token0,n.token1]).catch(()=>[{symbol:null,decimals:null},{symbol:null,decimals:null}]),a=r?.symbol??void 0,i=s?.symbol??void 0,l=qs(e,t);return{pair:a&&i?`${a}/${i}`:void 0,address:t,chain:e,protocolVersion:"V3",feeTierBps:n.fee,feeTierPercent:n.fee/1e4,currentPrice:n.currentPrice,token0:{symbol:a,address:n.token0},token1:{symbol:i,address:n.token1},...l?{uniswapUrl:l}:{}}}catch{return null}}};var Ey=1e3,_y=365;function Ny(o,e){let t=e/100;return{depositUsd:o,aprPercent:e,dailyUsd:o*t/_y,weeklyUsd:o*t/52,monthlyUsd:o*t/12,yearlyUsd:o*t}}var $r=class extends P{name="defillama-estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap pool. Use for: "if I put $1000 into USDC/WETH how much do I earn per day?", "b\u1ECF 500$ v\xE0o pool n\xE0y l\u1EDDi bao nhi\xEAu?", "APR of the WBTC/ETH pool", "daily income for this pool". Call it IMMEDIATELY with whatever the user gave \u2014 it fills the gaps itself: \u2022 Only ONE token named \u2192 pass just token0Symbol; the tool auto-picks that token's highest-volume pool. \u2022 BOTH tokens but no fee tier AND several tiers exist \u2192 returns candidates (one per fee tier) to choose from. \u2022 No deposit amount \u2192 defaults to $1000 and marks the result as a per-$1000 example. Source: DefiLlama Yields. Supports: `+$e();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of the first token, e.g. "USDC". Required.',required:!0},{name:"token1Symbol",type:"string",description:`Symbol of the second token, e.g. "WETH". Omit when the user named only one token \u2014 the tool then auto-picks that token's highest-volume pool rather than asking.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.3%, 10000 = 1%. OMIT when the user has not mentioned one \u2014 the tool returns candidates if the pair has several tiers.",required:!1},{name:"depositUsd",type:"number",description:"The USD amount the user wants to deposit. OMIT when they did not say \u2014 the tool defaults to $1000 and labels the result a per-$1000 example. Do NOT ask the user for this up front.",required:!1},{name:"chain",type:"string",description:He,required:!1}];service;constructor(e){super(),this.service=new Ue(e)}async run(e,t){let n=await Z(qe(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"";if(!s)return{_instructions:"No token was named. Ask the user which pool they want the yield estimate for, in their language. Do NOT mention tools or APIs."};let a=typeof e.token1Symbol=="string"&&e.token1Symbol.trim()?e.token1Symbol.trim():void 0,i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.round(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:Ey,d=await this.service.getPoolsByPair({chain:r,token0Symbol:s,token1Symbol:a,feeTierBps:i});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=[s,a].filter(Boolean).join("/"),p=d.data??[];if(p.length===0)return{_instructions:"No pool matched that pair on this chain, so no yield can be estimated. Tell the user plainly, in their language, and suggest another chain or different tokens. NEVER invent an APR or an earnings figure. Do NOT mention tools or APIs.",chain:T(r),pair:u};let m=new Set(p.map(y=>y.feeTierBps).filter(y=>y!==void 0));if(a&&i===void 0&&m.size>1){let y=this.dedupeByFeeTier(p).slice(0,5);return{_instructions:`The ${u} pair has several fee tiers. Present them as a short numbered list (fee %, TVL, 24h volume, APR) and ask the user which one they mean. When they answer, call this tool again with the chosen feeTier \u2014 and pass along the original deposit amount if the user gave one. Do NOT estimate earnings yet, and do NOT merge the tiers into one figure. `+z,chain:r,pair:u,candidates:y.map(Re)}}let f=[...p].sort((y,w)=>(w.volume1DayUsd??0)-(y.volume1DayUsd??0)),h=f[0],g=a?f.length>1?`Auto-selected the highest-volume ${u} pool at this fee tier.`:void 0:`Auto-selected the highest-volume ${s} pool.`;if(h.apr===void 0)return{_instructions:"This pool has no APR reading, so earnings CANNOT be projected. Say so plainly in the user's language and show the TVL and 24h volume instead. CRITICAL: never invent, estimate, or infer an APR or an earnings figure. "+z,chain:r,pair:u,pool:Re(h),...g?{autoPickedReason:g}:{}};let b=Ny(c,h.apr);return{_instructions:(l?"Lead with: pool (pair + fee %), chain, APR %. Then show the projected earnings for the user's deposit \u2014 daily, weekly, monthly and yearly, in USD with 2 decimals. ":'IMPORTANT: the user did NOT specify a deposit amount \u2014 this 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 the daily / weekly / monthly / yearly figures in USD with 2 decimals. Afterwards you MAY invite the user to share their actual budget for a personalized number. ')+(g?'Mention naturally that this is the most active pool for that token (e.g. "the highest-volume USDC/WETH pool") \u2014 never say you "auto-picked" it. ':"")+"Note briefly that this projection assumes the current APR holds and that real returns vary with trading volume. "+G+z,chain:r,pair:u,pool:Re(h),depositMode:l?"user-specified":"default-1000-example",estimate:b,...g?{autoPickedReason:g}:{}}}dedupeByFeeTier(e){let t=new Map;for(let n of e){if(n.feeTierBps===void 0)continue;let r=t.get(n.feeTierBps);(!r||n.tvlUsd>r.tvlUsd)&&t.set(n.feeTierBps,n)}return[...t.values()].sort((n,r)=>r.tvlUsd-n.tvlUsd)}};var Hr=class{service;constructor(e){this.service=new Ue(e)}async resolveCandidates(e){let t=e.protocolVersion==="ALL"?"ALL":"V3",n=await this.service.getPoolsByPair({chain:e.chain,token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,feeTierBps:e.feeTier,protocolVersion:t});return n.success?(n.data??[]).filter(r=>r.protocolVersion==="V3"?r.address!==void 0:t==="ALL").map(r=>({id:r.address,protocolVersion:r.protocolVersion,feeTier:r.feeTierBps,token0:r.token0,token1:r.token1,tvlUsd:r.tvlUsd,volume1DayUsd:r.volume1DayUsd,apr:r.apr})):null}};function xt(o){if(typeof o=="number")return Number.isFinite(o)&&o>0?{kind:"token",value:o,raw:String(o)}:null;if(typeof o!="string")return null;let e=o.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 t=e.match(/^%?\s*([0-9]*\.?[0-9]+)\s*%$|^%\s*([0-9]*\.?[0-9]+)$/);if(t){let s=parseFloat(t[1]??t[2]);return Number.isFinite(s)&&s>0?{kind:"percent",percent:s,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 s=parseFloat(n[1]??n[2]??n[3]??n[4]);return Number.isFinite(s)&&s>0?{kind:"usd",usd:s,raw:e}:null}let r=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(r){let s=parseFloat(r[1]);return Number.isFinite(s)&&s>0?{kind:"token",value:s,raw:e}:null}return null}function sp(o,e){switch(o.kind){case"token":return{ok:!0,amount:o.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*o.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:o.usd/e.usdPrice}}}var ap={send:30000n,swap:1000000n};async function Ly(o){try{let e=await xe(o).getGasPrice();return e>0n?e:0n}catch{return 0n}}function ip(o,e){let t=ap[o],n=Iy(e);return n!==null&&n>t?n:t}function Iy(o){let e=o?.tx?.gas??o?.estimatedTransactionFee?.details?.gasLimit;if(e==null)return null;try{let t=typeof e=="bigint"?e:BigInt(e);return t>0n?t:null}catch{return null}}async function cc(o,e,t={}){let[n,r]=await Promise.all([Ly(o),t.provider?pi({provider:t.provider,srcChainId:o,dstChainId:t.dstChainId??o}):Promise.resolve(0n)]);return(n>0n?ip(e,t.quoteGas)*n:0n)+r}async function Hs(o,e,t={}){return cc(o,e,t)}function Vs(o,e,t){if(e<=0n)return o;let n=we(t)?.native.decimals;if(n===void 0)return o;let r=Number(e)/10**n;return!Number.isFinite(r)||r<=0?o:Math.max(0,o-r)}function uc(o,e){let t=we(e)?.native.decimals;if(t===void 0)return null;let n=Number(o)/10**t;return Number.isFinite(n)?n:null}function lp(o){let{nativeBalance:e,feeWei:t,chainId:n}=o;if(t<=0n)return null;let r=uc(t,n);if(r===null||r<=0||!Number.isFinite(e)||e>r)return null;let s=Math.ceil(Math.max(0,r-e)*1e8)/1e8;return s>0?s:1e-8}async function Ws(o){let{chainId:e,gasKind:t,readNativeBalance:n,feeContext:r}=o;if(!e)return null;try{let[s,a]=await Promise.all([cc(e,t,r??{}),n()]),i=lp({nativeBalance:a?.balance??0,feeWei:s,chainId:e});return i===null?null:{shortfall:i,nativeSymbol:a?.symbol??we(e)?.native.symbol??"the native coin",fee:uc(s,e)??0}}catch{return null}}var Ze=class extends P{kind="ui";category="wallet-action";buildUI(e){let t={action:this.actionType,chainId:e.chainId,chainName:T(e.chainId),walletAddress:e.walletAddress,parameters:e.parameters};return{component:this.component,props:t}}userInputFields=[];moralis;constructor(e){super(),e!==void 0&&(this.moralis=new U(e))}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),s=E(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}parseDecimals(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isInteger(t)&&t>=0)return t}}async resolveTokenRef(e){let{contractArg:t,symbolArg:n,decimalsArg:r,chain:s,walletAddress:a}=e,i=this.parseDecimals(r),l=typeof n=="string"&&n.trim()?n.trim():void 0,c=this.normaliseAddress(t),d=typeof t=="string"&&t.trim()?t.trim():void 0,u=c??l??d;if(!u)return{token:void 0};let p=await this.resolveContractAddress(u,s,a);return p?{token:{address:p.address,symbol:p.symbolIsOnchain?p.symbol:l??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:l,decimals:i}}:{error:"token_not_found",key:u}}requireWallet(e){let t=e?.walletAddress;return t?{ok:!0,address:t}:{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(e,t){return j(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return E(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:n,chain:r,walletAddress:s,gasKind:a}=e,i=xt(t);if(!i)return null;let l=e.symbol??"the token",c=n.toLowerCase()==="native",d=!!a&&c&&!!r;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let u=await this.readTokenBalanceAndPrice(n,r,s),p=u?.balance;d&&u?.balance!==void 0&&(p=await this.computeNativeSpendable(r,a,u.balance));let m=sp(i,{balance:p,usdPrice:u?.usdPrice});return m.ok?{amount:this.toPlainDecimal(m.amount)}:m.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${l} balance to work out ${i.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 ${l} 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 ${l} to work out ${i.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 ${l} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(e,t,n){let r=await Hs(e,t);return Vs(n,r,e)}async resolveNativeSpendableFormatted(e,t,n){if(!(!e||!t))try{let r=await this.readTokenBalanceAndPrice("native",e,t);if(r?.balance===void 0)return;let s=await this.computeNativeSpendable(e,n,r.balance);return this.toPlainDecimal(s)}catch{return}}async readTokenBalanceAndPrice(e,t,n){if(!this.moralis||!n)return;let r=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=r.success?r.data?.result??[]:[],a=e.toLowerCase()==="native",i=e.toLowerCase(),l=s.find(d=>a?d.native_token===!0:(d.token_address??"").toLowerCase()===i);if(!l)return;let c=l.balance_formatted!=null?Number(l.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof l.usd_price=="number"&&l.usd_price>0?l.usd_price:void 0,balanceFormatted:l.balance_formatted,symbol:l.symbol}}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=r.split("."),c=i+l,d;if(a>=0){let u=i.length+a;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-a-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),n?`-${d}`:d}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isFinite(t)||t<=0)return;let r=n*t;if(!(!Number.isFinite(r)||r<=0))return this.toPlainDecimal(r)}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-r};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-r}}}async run(e,t){let n=this.requireWallet(t);if(!n.ok)return n.payload;let r=Lo(e.chain,t);if(r){let g=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${g} on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to ${g} on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can ${g} on ${r.connectedLabel} (their current network) instead. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}let s=this.requireChain(e,t);if(!s){let g=typeof t?.query=="string"?t.query:void 0;return Io(this.actionType.replace(/_/g," "),g)}let a=await this.buildParameters(e,t);if(a&&typeof a=="object"&&"error"in a&&typeof a.error=="string"||a&&typeof a=="object"&&"actionButtons"in a&&Array.isArray(a.actionButtons)||a&&typeof a=="object"&&"ui"in a&&a.ui&&typeof a.ui=="object"&&typeof a.ui.component=="string")return a;let i=a,l=this.buildUI({parameters:i,chainId:s,walletAddress:n.address}),c=g=>{let b=i[g];return b!=null&&b!==""},d=this.userInputFields.filter(g=>!(Array.isArray(g.key)?g.key:[g.key]).some(c)).map(g=>g.label),u=this.userInputFields.map(g=>{let y=(Array.isArray(g.key)?g.key:[g.key]).find(c);return y?`${g.label}: ${i[y]}`:null}).filter(g=>g!=null),p=this.actionType.replace(/_/g," "),m='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.',f="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.",h=d.length>0?`The ${p} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${d.join(", ")}. `+(u.length>0?`Already provided: ${u.join("; ")}. `:"")+`${f} ${m}`:`The ${p} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${p}. `+(u.length>0?`Details provided: ${u.join("; ")}. `:"")+`${f} ${m}`;return{ui:l,action:this.actionType,chainId:s,parameters:i,_instructions:h}}};var Vr=class extends Ze{name="open-send-native-form";actionType="send_native";component="SendNativeForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}async run(e,t){if(e.chain==null||e.chain===""){let n=Su(e.native_symbol);if(n)return super.run({...e,chain:n},t)}return super.run(e,t)}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.`;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 buildParameters(e,t){let n={},r=this.requireChain(e,t)??void 0,s=t?.walletAddress??void 0,a=await this.readTokenBalanceAndPrice("native",r,s);if(!a||a.balance==null||a.balance<=0){let u=a?.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.`}}let i=a.symbol||(typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0);if(i&&(n.native_symbol=i),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?n.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(n.to_address=e.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:r,walletAddress:s,gasKind:"send"});if(l&&"error"in l)return l;l&&(n.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(r,s,"send");c!==void 0&&(n.spendable=c);let d=this.formatSpendableUsd(c,a.usdPrice);return d!==void 0&&(n.spendableUsd=d),n}};var Wr=class extends Ze{name="open-send-token-form";actionType="send_token";component="SendTokenForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}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.`;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(e,t){let n=this.normaliseAddress(e.contract_address)!=null,r=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!n&&!r&&this.moralis){let u=this.requireChain(e,t)??void 0,p=t?.walletAddress;if(p){let m=await this.moralis.getWalletTokenBalances({address:p,chain:u,excludeSpam:!1,excludeUnverifiedContracts:!1}),h=(m.success?m.data?.result??[]:[]).filter(v=>v.symbol&&(v.native_token||v.token_address)).sort((v,A)=>(A.usd_value??0)-(v.usd_value??0)).slice(0,8);if(h.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 g=e.to_address!=null?this.normaliseAddress(e.to_address):null,b=this.normaliseAmount(e.amount),y=typeof e.send_prompt_template=="string"?e.send_prompt_template:"",w=u?T(u):null;return{actionButtons:h.map(v=>{let A=v.symbol,S=v.balance_formatted?this.cleanAmountString(v.balance_formatted):"",C=v.name?v.name:"",F=v.usd_value?`($${v.usd_value.toFixed(2)})`:"";return{label:`${C}:${S} ${A} ${F}`.trim(),prompt:this.buildSendPrompt(y,A,b,g,w)}}),_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 s=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0,i=await this.findOwnedTokenForSend(e,s,a);if(i&&"error"in i)return i;let l=i?.token,c={};l?.address&&(c.contract_address=l.address),l?.symbol&&(c.token_symbol=l.symbol),l?.decimals!==void 0&&(c.decimals=String(l.decimals)),i?.spendable!==void 0&&(c.spendable=i.spendable);let d=this.formatSpendableUsd(i?.spendable,i?.usdPrice);if(d!==void 0&&(c.spendableUsd=d),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?c.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(c.to_address=e.to_address.trim())}if(l?.address){let u=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:l.address,symbol:l.symbol,chain:s,walletAddress:a});if(u&&"error"in u)return u;u&&(c.amount=u.amount)}else{let u=this.normaliseAmount(e.amount);u&&(c.amount=u)}return c}async findOwnedTokenForSend(e,t,n){let r=this.normaliseAddress(e.contract_address),s=typeof e.token_symbol=="string"&&e.token_symbol.trim()?e.token_symbol.trim():void 0,a=r??s;if(!this.moralis||!n||!a){let m=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:n});return"error"in m?{error:"token_not_found",symbol:m.key,_instructions:`Could not resolve token "${m.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:m.token}}let i=a.toLowerCase(),l=r!=null,c=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),u=(c.success?c.data?.result??[]:[]).find(m=>l?(m.token_address??"").toLowerCase()===i:(m.symbol??"").toLowerCase()===i);if(u&&u.balance&&!/^0*$/.test(u.balance.trim())){let m=this.parseDecimals(e.decimals);return{token:{address:u.token_address,symbol:u.symbol??s,name:u.name,decimals:m??(typeof u.decimals=="number"?u.decimals:void 0)},spendable:u.balance_formatted?this.cleanAmountString(u.balance_formatted):void 0,usdPrice:typeof u.usd_price=="number"&&u.usd_price>0?u.usd_price:void 0}}let p=u?.symbol??s??a;return{error:"no_balance",symbol:p,_instructions:`The user does not hold any ${p} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${p} 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(e,t,n,r,s){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,n??"");return i=this.fillOrDropPhrase(i,"{to}",r),i=this.fillOrDropPhrase(i,"{chain}",s),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,n){if(n)return e.split(t).join(n);let r=t.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${r}`,"g"),"").replace(new RegExp(`${r}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(r,"g"),"")}};var Yr=class extends Ze{name="open-approve-token-form";actionType="approve_token";component="ApproveTokenForm";userInputFields=[{key:"spender_address",label:"the spender address to approve"}];constructor(e){super(e)}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".';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(e,t){let n=this.requireChain(e,t)??void 0,r=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:n,walletAddress:t?.walletAddress??void 0});if("error"in r)return{error:"token_not_found",symbol:r.key,_instructions:`Could not resolve token "${r.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let s=r.token,a=this.normaliseAddress(e.spender_address),i={};if(s?.address&&(i.contract_address=s.address),a&&(i.spender_address=a),s?.symbol&&(i.token_symbol=s.symbol),s?.decimals!==void 0&&(i.decimals=String(s.decimals)),typeof e.amount=="string"&&e.amount.trim()){let l=e.amount.trim(),c=parseFloat(l);Number.isFinite(c)&&c>=0&&(i.amount=l)}else typeof e.amount=="number"&&Number.isFinite(e.amount)&&e.amount>=0&&(i.amount=String(e.amount));return i}};function gi(o){let{action:e,fromSym:t,toSym:n,amount:r,spendable:s}=o,a=e==="swap"?`swap ${t} to ${n}`:`buy ${n} with ${t}`,i=e==="swap"?"swapping":"buying",l=e==="swap"?`swap ${r} ${t} to ${n}`:`buy ${n} with ${r} ${t}`,c=s?` They have ${s} ${t} available to spend.`:"";return(r?`The user wants to ${l}.${c} Reply briefly in the user's language confirming the amount and asking them to review and complete it. `:`The user wants to ${a}.${c} Reply briefly in the user's language: state what they want to do${s?" and their available balance":""}, then ask how much they want to ${e}. `)+`Do NOT list amounts or percentages, and do NOT state an estimated receive amount or a rate \u2014 you do not have one. Speak only of the user's action (${i}) \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, buttons, or forms.`}var Dt=o=>o.logo||o.icon_image||o.logoURI||o.thumbnail||void 0,Uy=o=>Number.isFinite(o)?ys(parseFloat(o.toPrecision(8))):"0",Dy=o=>{if(!/e/i.test(o))return o;let e=Number(o);return Number.isFinite(e)?ys(e):o};async function Ys(o){let{moralis:e,walletAddress:t,tokenAddress:n,chain:r,kind:s="swap",feeContext:a,dbg:i}=o;if(!e)return null;let l=await e.getWalletTokenBalances({address:t,chain:r,excludeSpam:!1,excludeUnverifiedContracts:!1}),c=l.success?l.data?.result??[]:[];i?.("readSpendableBalance",{tokenAddress:n,chain:r,ok:l.success,count:c.length});let d=n.toLowerCase(),u=c.find(m=>d==="native"?m.native_token===!0:m.token_address?.toLowerCase()===d);if(!u?.balance_formatted)return i?.("readSpendableBalance: token NOT held \u2192 null",{tokenAddress:n}),null;let p=Number(u.balance_formatted);if(!Number.isFinite(p)||p<=0)return i?.("readSpendableBalance: zero/invalid balance \u2192 null",{tokenAddress:n,balance:u.balance_formatted}),null;if(d==="native"&&r){let m=await Hs(r,s,a??{}),f=Vs(p,m,r);if(i?.("readSpendableBalance: native spendable",{balanceNum:p,spendable:f}),f<=0)return i?.("readSpendableBalance: native spendable \u2264 0 \u2192 null",{balanceNum:p}),null;let h=Uy(f),g=typeof u.decimals=="number"?u.decimals:18;return cp({balanceFormatted:h,balanceNum:f,symbol:u.symbol,decimals:g,logo:Dt(u)})}return i?.("readSpendableBalance: held",{tokenAddress:n,balance:u.balance_formatted,symbol:u.symbol}),cp({balanceFormatted:u.balance_formatted,balanceNum:p,symbol:u.symbol,decimals:typeof u.decimals=="number"?u.decimals:void 0,logo:Dt(u)})}function cp(o){let e=Dy(o.balanceFormatted),t=o.decimals===void 0?null:Dn(e,o.decimals);return{...o,balanceFormatted:e,rawAmount:t?.toString()}}function Gr(o){let e=o?.trim();if(!e)return"";let t=T(e);return!t||t==="the requested chain"||t===e?"":` (${t})`}async function yi(o,e){let t=o?st(o)?.nativeCurrency:void 0,n=e.map(a=>a&&(a.address==="native"?{...a,symbol:t?.symbol??a.symbol,decimals:t?.decimals??a.decimals,symbolIsOnchain:t?.symbol?!0:a.symbolIsOnchain??!1}:{...a})),r=[];if(n.forEach((a,i)=>{if(!a||a.address==="native"||!E(a.address))return;let l=a.symbolIsOnchain===!0&&!!a.symbol?.trim(),c=typeof a.decimals=="number"&&Number.isFinite(a.decimals);l&&c||r.push({index:i,address:a.address})}),!o||r.length===0)return n;let s=await Jt(o,r.map(a=>a.address)).catch(()=>[]);return r.forEach((a,i)=>{let l=s[i];if(!l)return;let c=n[a.index];typeof l.symbol=="string"&&l.symbol.trim()&&(c.symbol=l.symbol.trim(),c.symbolIsOnchain=!0),typeof l.decimals=="number"&&Number.isFinite(l.decimals)&&(c.decimals=l.decimals)}),n}var Kr=class extends P{name="open-buy-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new U(e),this.pantograph=new Te({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[BuyTokenTool] ${e}`):console.log(`[BuyTokenTool] ${e}`,JSON.stringify(t)))}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.';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}. Do NOT write the chain name yourself \u2014 the chain these tokens are on is appended automatically as a "(<chain>)" suffix, e.g. "buy PEPE (Base)".`,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). Do NOT write the chain name yourself \u2014 the chain is appended automatically as a "(<chain>)" suffix, e.g. "buy PEPE with ETH (Base)".`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-r};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let r=Lo(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to buy on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to buy on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can buy on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Io("buy",a)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let n=typeof e.token_symbol=="string"?e.token_symbol.trim():"",r=typeof e.contract_address=="string"?e.contract_address.trim():"",s=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:s,walletAddress:a,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(e,t);let[i,l]=await Promise.all([this.resolveSide(e.contract_address,n,s,a,"dest"),this.resolveSide(e.pay_with_address,e.pay_with_symbol,s,a,"pay")]),[c,d]=await yi(s,[i.address?{...i,address:i.address}:void 0,l.address?{...l,address:l.address}:void 0]),u=i.address,p=c?.symbol??n,m=c?.decimals,f=i.logo,h=l.address,g=d?.symbol,b=d?.decimals,y=await this.resolveBuyAmountSpec(e.buy_amount,u,s,p),w=h?await this.resolvePayAmountSpec(e.pay_with_amount,h,s,a,g,b??(h==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),k=xt(e.pay_with_amount),v=!!k&&k.kind!=="token",A=null;if(this.dbg("resolved sides",{dest:{destContract:u,destSymbol:p,destDecimals:m},pay:{payAddr:h,paySymbol:g,payDecimals:b},buyAmount:y,payAmount:w}),!u)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${p||r}" 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(!h&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:p,destContract:u,buyAmount:y,payAmount:w});if(!h)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${p}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(y&&!w){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:y,destSymbol:p,paySymbol:g});let S=await this.derivePayAmountFromBuy({chain:s,buyAmount:y,destContract:u,destSymbol:p,payAddr:h,paySymbol:g});if(!S)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 ${y} ${p} 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.`};w=S,A=y,v=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:w,derivedFromBuy:A})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:h,paySymbol:g,payAmount:w});let S=await this.checkPayBalance({args:e,userContext:t,chain:s,destSymbol:p,destContract:u,payAddr:h,paySymbol:g,payAmount:w,buyAmount:y,derivedFromBuy:A,amountSizedToBalance:v});if(S)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:S.error,hasButtons:Array.isArray(S.actionButtons)}),S;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!y&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{payAmount:w});let S=await this.buildAmountForm({userContext:t,chain:s,destContract:u,destSymbol:p,destDecimals:m,destLogo:f,payAddr:h,paySymbol:g,payDecimals:b,payAmount:w??void 0});if(S)return this.dbg("\u2192 Branch 1.5: amount form returned"),S;this.dbg("Branch 1.5: amount form null \u2014 needs a resolvable pay token")}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 ${p}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return E(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!n)return null;let r=parseFloat(n[1]);return Number.isFinite(r)&&r>0?n[1]:null}correctAmountSide(e,t){let n=typeof t?.query=="string"?t.query:"",r=typeof e.token_symbol=="string"?e.token_symbol.trim():"",s=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"";if(!n||!r||!s)return;let a=typeof e.buy_amount=="string"?e.buy_amount.trim():"",i=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",l=a.length>0,c=i.length>0;if(l===c)return;let d=l?a:i,u=d.match(/[0-9]*\.?[0-9]+/)?.[0];if(!u)return;let p=this.nearestSymbolSide(n,u,r,s);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:d,buySym:r,paySym:s}),e.pay_with_amount=d,e.buy_amount=""):p==="buy"&&c&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:d,buySym:r,paySym:s}),e.buy_amount=d,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=typeof e.token_symbol=="string"?e.token_symbol.trim():"";if(!r)return;let s=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"",a=typeof e.pay_with_address=="string"?e.pay_with_address.trim():"";if(!s&&!a)return;let i=n.toLowerCase(),l=s.toLowerCase(),c=a.toLowerCase(),d=l==="native"||c==="native",u=[];if(s&&l!=="native"&&u.push(l),c&&c!=="native"&&u.push(c),d){u.push("native");let m=this.requireChain(e,t)??void 0,f=m?we(m)?.native.symbol:void 0;f&&u.push(f.toLowerCase())}u.some(m=>E(m)?i.includes(m):this.indexOfToken(i,m)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:s,payAddr:a,buySym:r}),e.pay_with_symbol="",e.pay_with_address="")}dropInventedAmounts(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=(n.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),s=a=>{let i=typeof e[a]=="string"?e[a].trim():"";if(!i)return;let l=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(l===void 0)return;let c=parseFloat(l);Number.isFinite(c)&&(r.some(d=>d===c)||(this.dbg(`dropInventedAmounts: clearing invented ${a}`,{val:i}),e[a]=""))};s("buy_amount"),s("pay_with_amount")}nearestSymbolSide(e,t,n,r){let s=e.toLowerCase(),a=s.indexOf(t.toLowerCase()),i=this.indexOfToken(s,n.toLowerCase()),l=this.indexOfToken(s,r.toLowerCase());if(a<0||i<0||l<0)return null;let c=(p,m)=>Math.max(0,p-(a+t.length),a-(p+m)),d=c(i,n.length),u=c(l,r.length);return u===d?null:u<d?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|[^a-z0-9])(${n})(?:[^a-z0-9]|$)`));return r&&r.index!==void 0?r.index+r[0].indexOf(r[1]):-1}requireChain(e,t){return j(e.chain,t)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),s=E(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:Dt(c)}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:Dt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,n,r,s="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,d=m=>m.toLowerCase()===le?"native":m,u=l??c??(a||void 0);if(!u)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,n,r);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:n,key:u,lookup:p}),p?{address:d(p.address),symbol:p.symbolIsOnchain?p.symbol:c??p.symbol,decimals:p.decimals,logo:p.logo,symbolIsOnchain:p.symbolIsOnchain??!1}:l?{address:d(l),symbol:c}:{address:null,symbol:c}}async derivePayAmountFromBuy(e){let{chain:t,buyAmount:n,destContract:r,payAddr:s}=e,[a,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(s,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:a,payPrice:i}),!a||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,d=l*a/i;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?le:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),s=r.success?r.data?.usd_price:void 0;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}async resolvePayAmountSpec(e,t,n,r,s,a){let i=xt(e);if(!i)return null;let l=d=>a===void 0?d:Nt(d,a);if(i.kind==="token")return l(On(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let d=await this.readPayBalance(r,t,n);if(this.dbg("resolvePayAmountSpec: percent",{percent:i.percent,paySymbol:s,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let u=d.decimals??a??18;return i.percent>=100?this.cleanAmountString(d.balanceFormatted):Mn(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,n);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,n,r){let s=xt(e);if(!s)return null;if(s.kind==="token")return On(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,n);return this.dbg("resolveBuyAmountSpec: usd",{usd:s.usd,destSymbol:r,price:a}),a?this.trimAmount(s.usd/a):null}async buildPayWithPicker(e){let{args:t,userContext:n,destSymbol:r,destContract:s}=e,a=this.requireChain(t,n)??void 0,i=this.moralis,l=n.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=c.success?c.data?.result??[]:[],u=s?.toLowerCase(),p=r.trim().toLowerCase(),m=d.filter(y=>!y.symbol||p&&y.symbol.toLowerCase()===p?!1:y.native_token?u!=="native":!(!y.token_address||u&&y.token_address.toLowerCase()===u)).sort((y,w)=>(w.usd_value??0)-(y.usd_value??0)).slice(0,8);if(m.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 f=e.buyAmount??this.normaliseAmount(t.buy_amount),h=e.payAmount??this.normaliseAmount(t.pay_with_amount),g=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:m.map(y=>{let w=y.symbol,k=y.name?.trim()||w,v=y.balance_formatted?`${this.cleanAmountString(y.balance_formatted)} `:"",A=typeof y.usd_value=="number"&&y.usd_value>0?` ($${y.usd_value.toFixed(2)})`:"",S=`${k}: ${v}${w}${A}`,C=f?this.buildBuyWithPrompt(g,r,w,f,null,a):this.buildBuyWithPrompt(g,r,w,null,h,a);return{label:S,prompt:C}}),_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 ${r}.' / 'You want to buy ${r}.'), then ask them to choose which token they want to spend to buy ${r} 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(e){let{args:t,userContext:n,chain:r,destSymbol:s,destContract:a,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:d}=e,u=n.walletAddress,p=await this.readPayBalance(u,i,r),m=e.paySymbol??p?.symbol??"the selected token";if(!p){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:m});let y=await this.buildPayWithPicker({args:t,userContext:n,destSymbol:s,destContract:a,buyAmount:c,payAmount:l});return"actionButtons"in y?{error:"no_pay_balance",actionButtons:y.actionButtons,_instructions:`The user wanted to spend ${m} to buy ${s}, but their wallet holds no ${m} 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 ${m} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${m} 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 ${s} 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.`}:y}if(i.toLowerCase()!=="native"){let y=await Ws({chainId:r,gasKind:"swap",readNativeBalance:()=>this.readNativeHeldBalance(u,r)});if(y)return this.dbg("checkPayBalance: cannot cover gas",y),{error:"insufficient_native_for_gas",_instructions:`The wallet holds ${m} but cannot cover the network fee for this purchase: it needs about ${y.shortfall} more ${y.nativeSymbol}. Tell the user in their language that they need roughly ${y.shortfall} more ${y.nativeSymbol} to pay the network fee before they can buy ${s} (e.g., 'B\u1EA1n c\u1EA7n th\xEAm kho\u1EA3ng ${y.shortfall} ${y.nativeSymbol} \u0111\u1EC3 tr\u1EA3 ph\xED m\u1EA1ng.'), and suggest they top up ${y.nativeSymbol} first. Do NOT open a form, do NOT invent a different number, and do NOT mention tool names, UI, or forms.`}}if(!l||e.amountSizedToBalance)return null;let f=p.decimals!==void 0?Nt(l,p.decimals):l;if(Zt(f,p.balanceFormatted)<=0)return null;let h=this.cleanAmountString(p.balanceFormatted),g=this.percentSpendButtons({balanceFormatted:p.balanceFormatted,balanceNum:p.balanceNum,decimals:p.decimals,paySymbol:m,destSymbol:s,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"",...r===void 0?{}:{chain:r}}),b=d?`Buying ${d} ${s} needs about ${l} ${m}, but they only have ${h} ${m} 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} ${s} would cost about ${l} ${m}, which is more than their balance of ${h} ${m}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${l} ${m} to buy ${s}, but they only have ${h} ${m} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${l} ${m} exceeds their balance of ${h} ${m}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:g,_instructions:b+'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(e,t,n){return Ys({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:n,kind:"swap",dbg:(r,s)=>this.dbg(r,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let n=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(n.success?n.data?.result??[]:[]).find(i=>i.native_token===!0),a=s?.balance_formatted!=null?Number(s.balance_formatted):0;return{balance:Number.isFinite(a)?a:0,...s?.symbol===void 0?{}:{symbol:s.symbol}}}catch{return{balance:0}}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,paySymbol:r,destSymbol:s,buyWithTemplate:a,chain:i}=e,l=n??18;return[25,50,75,100].map(d=>{let u=Mn(this.cleanAmountString(t),BigInt(d),100n,l);return{label:`${d}%`,prompt:this.buildBuyWithPrompt(a,s,r,null,u,i)}})}async buildAmountForm(e){let{userContext:t,chain:n,destContract:r,destSymbol:s,destDecimals:a,destLogo:i,payAddr:l,payAmount:c}=e,d=t.walletAddress;if(!n)return null;let u=we(n);if(!u)return null;let p=await this.readPayBalance(d,l,n),m=e.paySymbol??p?.symbol;if(!m)return null;let f=l==="native",h=p?.decimals??e.payDecimals??(f?u.native.decimals??18:void 0);if(h===void 0)return null;let g=p?.balanceFormatted,b=p?.rawAmount??(g?Dn(g,h)?.toString():void 0);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:n,name:u.name},fromToken:{address:f?"native":l,symbol:m,decimals:h,amount:g,rawAmount:b??void 0,logo:p?.logo},toToken:{address:r,symbol:s,decimals:a,logo:i},walletAddress:d,intent:"buy",initialAmount:c}},_instructions:gi({action:"buy",fromSym:m,toSym:s,amount:c,spendable:g})}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=r.split("."),c=i+l,d;if(a>=0){let u=i.length+a;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-a-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),n?`-${d}`:d}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildBuyPrompt(e,t,n){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+Gr(n)}buildBuyWithPrompt(e,t,n,r,s,a){return(e&&e.includes("{token}")&&e.includes("{pay}")?e:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,t).replace(/\{pay\}/g,n).replace(/\{buy_amount\}/g,r??"").replace(/\{pay_amount\}/g,s??"").replace(/\s+/g," ").trim()+Gr(a)}async buildTrendingPicker(e,t){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 n=this.requireChain(e,t)??void 0,r=typeof e.limit=="number"&&Number.isFinite(e.limit)?Math.floor(e.limit):6,s=Math.max(1,Math.min(10,r)),a=await this.pantograph.getTrendingTokens({chain:n,limit:s}),i=a.success?a.data??[]:[];if(i.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 l=i.filter(m=>m.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",d=l.map(m=>{let f=m.symbol;return{label:f,prompt:this.buildBuyPrompt(c,f,n)}}),p=l.map((m,f)=>{let h=m.name?.trim()||m.symbol,g=m.symbol,b=typeof m.usdPrice=="number"&&m.usdPrice>0?`$${this.formatPrice(m.usdPrice)}`:"N/A",y=m.pricePercentChange?.["24h"],w=typeof y=="number"&&Number.isFinite(y)?` (${y>0?"+":y<0?"-":""}${this.formatPercent(Math.abs(y))}%)`:"";return`${f+1}. ${h} (${g}) \u2014 ${b}${w}`}).join(`
|
|
211
211
|
`)+`
|
|
212
212
|
|
|
213
|
-
Is there any token you want to buy?`;return{actionButtons:
|
|
213
|
+
Is there any token you want to buy?`;return{actionButtons:d,_instructions:`The trending tokens are on ${n?T(n):"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:
|
|
214
214
|
|
|
215
|
-
${p}`}}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var Lo=class extends P{name="open-swap-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new L(e),this.pantograph=new me({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[SwapTokenTool] ${e}`):console.log(`[SwapTokenTool] ${e}`,JSON.stringify(t)))}description='Open the SWAP TOKEN flow for ANY swap/exchange/convert intent where the user swaps a token they ALREADY HOLD into another token \u2014 "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang ETH", "convert DAI to USDC", "exchange 10 USDC for PEPE". The FROM token is the user\'s own holding (the source). Handles both cases: (a) the user named the destination \u2014 "swap USDC to USDT": pass `from_symbol` (the source, e.g. "USDC") and `to_symbol` (the destination, e.g. "USDT"). (b) the user named only the source \u2014 "swap USDC": pass `from_symbol` and leave `to_symbol` blank; the tool returns buttons of the chain\'s current trending tokens so the user picks what to receive. If the user named NO token at all \u2014 "swap" / "\u0111\u1ED5i token": leave both blank and the tool returns the wallet\'s holdings so the user picks what to swap FROM. Amount: `from_amount` = source to SPEND; `to_amount` = destination to RECEIVE. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"from_symbol",type:"string",description:`Symbol of the SOURCE token the user wants to swap FROM \u2014 a token they already hold (e.g. "USDC"). Leave EMPTY only when the user named no token at all (e.g. "swap") \u2014 the tool then returns the wallet's holdings to pick the source from.`,required:!1},{name:"from_address",type:"string",description:`Source token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from from_symbol.`,required:!1},{name:"from_amount",type:"string",description:'Quantity of the SOURCE token (the one being swapped FROM / spent) the user wants to SPEND. Set this when the amount sits next to the source token: "swap 10 USDC to USDT", "\u0111\u1ED5i 10 USDC sang ETH" \u2192 from_amount = the number next to USDC. May also be a PERCENT of the source balance ("swap 50% USDC to USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("swap $5 USDC to 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 from_symbol to the source token ("ETH" in "swap max ETH to USDC"). Mutually exclusive with to_amount \u2014 set at most ONE of the two.',required:!1},{name:"to_symbol",type:"string",description:'Symbol of the DESTINATION token the user wants to RECEIVE (e.g. "USDT"). Leave EMPTY when the user did not name a destination (e.g. "swap USDC") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"to_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 to_symbol.`,required:!1},{name:"to_amount",type:"string",description:`Quantity of the DESTINATION token (the one being received) the user wants to RECEIVE. Set this when the amount sits next to the destination token: "swap USDC to 5 USDT" \u2192 to_amount = the number next to USDT. May also be a USD value ("swap USDC to $5 USDT" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$"). Mutually exclusive with from_amount \u2014 set at most ONE.`,required:!1},{name:"limit",type:"number",description:"Only used when no destination is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"swap_from_prompt_template",type:"string",description:`A short "swap {token}" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the source picker when the user named NEITHER side (a bare "swap"). Use the exact placeholder "{token}" (do not translate the braces) for the source symbol; put the localized verb directly in the text. English example: "swap {token}". Vietnamese example: "\u0111\u1ED5i {token}". Japanese example: "{token} \u3092\u30B9\u30EF\u30C3\u30D7". Always include {token}. Do NOT write the chain name yourself \u2014 the chain these holdings are on is appended automatically as a "(<chain>)" suffix, e.g. "swap ETH (Base)".`,required:!0},{name:"swap_to_prompt_template",type:"string",description:`A short "swap X to Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the destination (trending) picker, the percentage-spend buttons, and the source picker whenever the user already named a destination ("swap to USDC"). Use these exact placeholders (do not translate the braces): "{from}" = source token, "{to}" = destination token, "{from_amount}" = quantity of the SOURCE token (place it next to {from}), "{to_amount}" = quantity of the DESTINATION token (place it next to {to}). Put the localized verb and the "to" preposition directly in the text. English example: "swap {from_amount} {from} to {to_amount} {to}". Vietnamese example: "\u0111\u1ED5i {from_amount} {from} sang {to_amount} {to}". Japanese example: "{from_amount} {from} \u3092 {to_amount} {to} \u306B\u30B9\u30EF\u30C3\u30D7". Always include {from} and {to}. Include both {from_amount} and {to_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount). Do NOT write the chain name yourself \u2014 the chain is appended automatically as a "(<chain>)" suffix, e.g. "swap ETH to USDC (Base)".`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before swapping. Do NOT proceed."};let o=kr(e.chain,t);if(o)return{error:"wrong_chain",_instructions:`The user asked to swap on ${o.requestedLabel}, but their wallet is connected to ${o.connectedLabel}. Tell them, in their language, that to swap on ${o.requestedLabel} they must first switch their wallet's network to ${o.requestedLabel}, or they can swap on ${o.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return vr("swap",a)}return this.buildResult(e,t)}async buildResult(e,t){let n=typeof e.from_symbol=="string"?e.from_symbol.trim():"",o=typeof e.from_address=="string"?e.from_address.trim():"",s=typeof e.to_symbol=="string"?e.to_symbol.trim():"",a=this.requireChain(e,t)??void 0,i=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:a,walletAddress:i,hasMoralis:!!this.moralis}),!n&&!o){this.dbg("\u2192 Branch 0: source picker (no source token named)");let A=typeof e.to_address=="string"?e.to_address.trim():"",S=s||A;return await this.buildSourcePicker(e,t,S?{symbol:S,amount:this.normaliseAmount(e.to_amount)}:void 0)}let l=await this.resolveSide(e.from_address,n,a,i,"from"),c=l.address,u=l.symbol??n,d=l.decimals,p=await this.resolveSide(e.to_address,s,a,i,"to"),m=p.address,g=p.symbol??s,h=p.decimals,f=p.logo,b=await this.resolveToAmountSpec(e.to_amount,m,a,g),y=c?await this.resolveFromAmountSpec(e.from_amount,c,a,i,u,d??(c==="native"?18:void 0)):this.normaliseAmount(e.from_amount),w=yt(e.from_amount),k=!!w&&w.kind!=="token",v=null;if(this.dbg("resolved sides",{from:{fromContract:c,fromSym:u,fromDecimals:d},to:{toContract:m,toSym:g,toDecimals:h},fromAmount:y,toAmount:b}),!c)return this.dbg("\u2192 source token not resolved"),{error:"from_token_not_found",_instructions:`Could not find the token "${u||o}" to swap from 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&&t?.walletAddress)return this.dbg("\u2192 Branch 1: destination picker (dest token missing)"),await this.buildToTrendingPicker({args:e,userContext:t,fromSym:u,fromContract:c,fromAmount:y,toAmount:b});if(!m)return{error:"to_token_missing",_instructions:`Ask the user, in their language, which token they want to receive when swapping ${u}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(b&&!y){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:b,fromSym:u,toSym:g});let A=await this.deriveFromAmountFromTo({chain:a,toAmount:b,toContract:m,toSym:g,fromContract:c,fromSym:u});if(!A)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs from amount"),{error:"needs_from_amount",_instructions:`Could not work out how much ${u??"of the source token"} equals ${b} ${g} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${u??"of the source token"} they want to swap instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};y=A,v=b,k=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:y,derivedFromTo:v})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:c,fromSym:u,fromAmount:y});let A=await this.checkFromBalance({args:e,userContext:t,chain:a,fromContract:c,fromSym:u,toSym:g,fromAmount:y,toAmount:b,derivedFromTo:v,amountSizedToBalance:k});if(A)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:A.error,hasButtons:Array.isArray(A.actionButtons)}),A;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!b&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{fromAmount:y});let A=await this.buildAmountForm({userContext:t,chain:a,fromContract:c,fromSym:u,fromDecimals:d,toContract:m,toSym:g,toDecimals:h,toLogo:f,fromAmount:y??void 0});if(A)return this.dbg("\u2192 Branch 1.5: amount form returned"),A;this.dbg("Branch 1.5: amount form null \u2014 needs a resolvable source token")}return this.dbg("\u2192 needs from amount"),{error:"needs_from_amount",_instructions:`Ask the user, in their language, how much ${u??"of the source token"} they want to swap to ${g}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}requireChain(e,t){return G(e.chain,t)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:Ct(c)}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:Ct(c)}}}async resolveSide(e,t,n,o,s="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,u=m=>m.toLowerCase()===se?"native":m,d=l??c??(a||void 0);if(!d)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(d,n,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:n,key:d,lookup:p}),p?{address:u(p.address),symbol:c??p.symbol,decimals:p.decimals,logo:p.logo}:l?{address:u(l),symbol:c}:{address:null,symbol:c}}async deriveFromAmountFromTo(e){let{chain:t,toAmount:n,toContract:o,fromContract:s}=e,[a,i]=await Promise.all([this.getUsdPrice(o,t),this.getUsdPrice(s,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:a,fromPrice:i}),!a||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,u=l*a/i;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?se:e,o=await this.moralis.getTokenMetadata({address:n,chain:t}),s=o.success?o.data?.usd_price:void 0;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}async resolveFromAmountSpec(e,t,n,o,s,a){let i=yt(e);if(!i)return null;let l=u=>a===void 0?u:At(u,a);if(i.kind==="token")return l(xn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let u=await this.readFromBalance(o,t,n);if(this.dbg("resolveFromAmountSpec: percent",{percent:i.percent,fromSym:s,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??a??18;return i.percent>=100?this.cleanAmountString(u.balanceFormatted):Cn(u.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,d)}let c=await this.getUsdPrice(t,n);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,n,o){let s=yt(e);if(!s)return null;if(s.kind==="token")return xn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,n);return this.dbg("resolveToAmountSpec: usd",{usd:s.usd,toSym:o,price:a}),a?this.trimAmount(s.usd/a):null}async buildSourcePicker(e,t,n){if(!this.moralis||!t?.walletAddress)return{error:"source_unavailable",_instructions:"Cannot list the wallet holdings in this build. Tell the user briefly and ask them to name the token they want to swap from."};let o=this.requireChain(e,t)??void 0,s=t.walletAddress,a=await this.moralis.getWalletTokenBalances({address:s,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1}),l=(a.success?a.data?.result??[]:[]).filter(m=>m.symbol?m.native_token?!0:!!m.token_address:!1).sort((m,g)=>(g.usd_value??0)-(m.usd_value??0)).slice(0,8);if(l.length===0)return{error:"no_swap_holdings",_instructions:"The wallet holds no tokens to swap on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let c=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"",u=typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:"",d=l.map(m=>{let g=m.symbol,h=m.name?.trim()||g,f=m.balance_formatted?`${this.cleanAmountString(m.balance_formatted)} `:"",b=typeof m.usd_value=="number"&&m.usd_value>0?` ($${m.usd_value.toFixed(2)})`:"",y=`${h}: ${f}${g}${b}`,w=n?this.buildSwapToPrompt(u,g,n.symbol,null,n.amount??null,o):this.buildSwapFromPrompt(c,g,o);return{label:y,prompt:w}}),p=n?`state what the user wants to do, naming the destination they already gave (e.g., 'B\u1EA1n mu\u1ED1n swap sang ${n.symbol}.' / 'You want to swap to ${n.symbol}.')`:"state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n swap token.' / 'You want to swap a token.')";return{actionButtons:d,_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first ${p}, then ask them to choose which token to swap from in the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap.' / 'Please choose the token to swap from.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async buildToTrendingPicker(e){let{args:t,userContext:n,fromSym:o,fromContract:s}=e,a=this.requireChain(t,n)??void 0,i=this.pantograph,l=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,l)),u=await i.getTrendingTokens({chain:a,limit:c+2}),d=u.success?u.data??[]:[],p=s?.toLowerCase(),m=o.toLowerCase(),g=d.filter(v=>!(!v.symbol||p&&p!=="native"&&v.tokenAddress&&v.tokenAddress.toLowerCase()===p||v.symbol.toLowerCase()===m)).slice(0,c);if(g.length===0)return{error:"no_trending_tokens",_instructions:`No trending tokens are available to swap ${o} into on this chain right now. Tell the user briefly and suggest they name the token they want to receive directly. Do NOT mention tool names, UI, or forms.`};let h=e.fromAmount??this.normaliseAmount(t.from_amount),f=e.toAmount??this.normaliseAmount(t.to_amount),b=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",y=g.map(v=>{let A=v.symbol,S=h?this.buildSwapToPrompt(b,o,A,h,null,a):this.buildSwapToPrompt(b,o,A,null,f,a);return{label:A,prompt:S}}),k=g.map((v,A)=>{let S=v.name?.trim()||v.symbol,C=v.symbol,O=typeof v.usdPrice=="number"&&v.usdPrice>0?`$${this.formatPrice(v.usdPrice)}`:"N/A",_=v.pricePercentChange?.["24h"],H=typeof _=="number"&&Number.isFinite(_)?` (${_>0?"+":_<0?"-":""}${this.formatPercent(Math.abs(_))}%)`:"";return`${A+1}. ${S} (${C}) \u2014 ${O}${H}`}).join(`
|
|
215
|
+
${p}`}}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var jr=class extends P{name="open-swap-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new U(e),this.pantograph=new Te({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[SwapTokenTool] ${e}`):console.log(`[SwapTokenTool] ${e}`,JSON.stringify(t)))}description='Open the SWAP TOKEN flow for ANY swap/exchange/convert intent where the user swaps a token they ALREADY HOLD into another token \u2014 "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang ETH", "convert DAI to USDC", "exchange 10 USDC for PEPE". The FROM token is the user\'s own holding (the source). Handles both cases: (a) the user named the destination \u2014 "swap USDC to USDT": pass `from_symbol` (the source, e.g. "USDC") and `to_symbol` (the destination, e.g. "USDT"). (b) the user named only the source \u2014 "swap USDC": pass `from_symbol` and leave `to_symbol` blank; the tool returns buttons of the chain\'s current trending tokens so the user picks what to receive. If the user named NO token at all \u2014 "swap" / "\u0111\u1ED5i token": leave both blank and the tool returns the wallet\'s holdings so the user picks what to swap FROM. Amount: `from_amount` = source to SPEND; `to_amount` = destination to RECEIVE. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"from_symbol",type:"string",description:`Symbol of the SOURCE token the user wants to swap FROM \u2014 a token they already hold (e.g. "USDC"). Leave EMPTY only when the user named no token at all (e.g. "swap") \u2014 the tool then returns the wallet's holdings to pick the source from.`,required:!1},{name:"from_address",type:"string",description:`Source token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from from_symbol.`,required:!1},{name:"from_amount",type:"string",description:'Quantity of the SOURCE token (the one being swapped FROM / spent) the user wants to SPEND. Set this when the amount sits next to the source token: "swap 10 USDC to USDT", "\u0111\u1ED5i 10 USDC sang ETH" \u2192 from_amount = the number next to USDC. May also be a PERCENT of the source balance ("swap 50% USDC to USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("swap $5 USDC to 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 from_symbol to the source token ("ETH" in "swap max ETH to USDC"). Mutually exclusive with to_amount \u2014 set at most ONE of the two.',required:!1},{name:"to_symbol",type:"string",description:'Symbol of the DESTINATION token the user wants to RECEIVE (e.g. "USDT"). Leave EMPTY when the user did not name a destination (e.g. "swap USDC") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"to_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 to_symbol.`,required:!1},{name:"to_amount",type:"string",description:`Quantity of the DESTINATION token (the one being received) the user wants to RECEIVE. Set this when the amount sits next to the destination token: "swap USDC to 5 USDT" \u2192 to_amount = the number next to USDT. May also be a USD value ("swap USDC to $5 USDT" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$"). Mutually exclusive with from_amount \u2014 set at most ONE.`,required:!1},{name:"limit",type:"number",description:"Only used when no destination is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"swap_from_prompt_template",type:"string",description:`A short "swap {token}" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the source picker when the user named NEITHER side (a bare "swap"). Use the exact placeholder "{token}" (do not translate the braces) for the source symbol; put the localized verb directly in the text. English example: "swap {token}". Vietnamese example: "\u0111\u1ED5i {token}". Japanese example: "{token} \u3092\u30B9\u30EF\u30C3\u30D7". Always include {token}. Do NOT write the chain name yourself \u2014 the chain these holdings are on is appended automatically as a "(<chain>)" suffix, e.g. "swap ETH (Base)".`,required:!0},{name:"swap_to_prompt_template",type:"string",description:`A short "swap X to Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the destination (trending) picker, the percentage-spend buttons, and the source picker whenever the user already named a destination ("swap to USDC"). Use these exact placeholders (do not translate the braces): "{from}" = source token, "{to}" = destination token, "{from_amount}" = quantity of the SOURCE token (place it next to {from}), "{to_amount}" = quantity of the DESTINATION token (place it next to {to}). Put the localized verb and the "to" preposition directly in the text. English example: "swap {from_amount} {from} to {to_amount} {to}". Vietnamese example: "\u0111\u1ED5i {from_amount} {from} sang {to_amount} {to}". Japanese example: "{from_amount} {from} \u3092 {to_amount} {to} \u306B\u30B9\u30EF\u30C3\u30D7". Always include {from} and {to}. Include both {from_amount} and {to_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount). Do NOT write the chain name yourself \u2014 the chain is appended automatically as a "(<chain>)" suffix, e.g. "swap ETH to USDC (Base)".`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:s,duration:Date.now()-r};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before swapping. Do NOT proceed."};let r=Lo(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to swap on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to swap on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can swap on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Io("swap",a)}return this.buildResult(e,t)}async buildResult(e,t){let n=typeof e.from_symbol=="string"?e.from_symbol.trim():"",r=typeof e.from_address=="string"?e.from_address.trim():"",s=typeof e.to_symbol=="string"?e.to_symbol.trim():"",a=this.requireChain(e,t)??void 0,i=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:a,walletAddress:i,hasMoralis:!!this.moralis}),!n&&!r){this.dbg("\u2192 Branch 0: source picker (no source token named)");let C=typeof e.to_address=="string"?e.to_address.trim():"",F=s||C;return await this.buildSourcePicker(e,t,F?{symbol:F,amount:this.normaliseAmount(e.to_amount)}:void 0)}let[l,c]=await Promise.all([this.resolveSide(e.from_address,n,a,i,"from"),this.resolveSide(e.to_address,s,a,i,"to")]),[d,u]=await yi(a,[l.address?{...l,address:l.address}:void 0,c.address?{...c,address:c.address}:void 0]),p=l.address,m=d?.symbol??n,f=d?.decimals,h=c.address,g=u?.symbol??s,b=u?.decimals,y=c.logo,w=await this.resolveToAmountSpec(e.to_amount,h,a,g),k=p?await this.resolveFromAmountSpec(e.from_amount,p,a,i,m,f??(p==="native"?18:void 0)):this.normaliseAmount(e.from_amount),v=xt(e.from_amount),A=!!v&&v.kind!=="token",S=null;if(this.dbg("resolved sides",{from:{fromContract:p,fromSym:m,fromDecimals:f},to:{toContract:h,toSym:g,toDecimals:b},fromAmount:k,toAmount:w}),!p)return this.dbg("\u2192 source token not resolved"),{error:"from_token_not_found",_instructions:`Could not find the token "${m||r}" to swap from 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(!h&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: destination picker (dest token missing)"),await this.buildToTrendingPicker({args:e,userContext:t,fromSym:m,fromContract:p,fromAmount:k,toAmount:w});if(!h)return{error:"to_token_missing",_instructions:`Ask the user, in their language, which token they want to receive when swapping ${m}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(w&&!k){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:w,fromSym:m,toSym:g});let C=await this.deriveFromAmountFromTo({chain:a,toAmount:w,toContract:h,toSym:g,fromContract:p,fromSym:m});if(!C)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs from amount"),{error:"needs_from_amount",_instructions:`Could not work out how much ${m??"of the source token"} equals ${w} ${g} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${m??"of the source token"} they want to swap instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};k=C,S=w,A=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:k,derivedFromTo:S})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:p,fromSym:m,fromAmount:k});let C=await this.checkFromBalance({args:e,userContext:t,chain:a,fromContract:p,fromSym:m,toSym:g,fromAmount:k,toAmount:w,derivedFromTo:S,amountSizedToBalance:A});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(!w&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{fromAmount:k});let C=await this.buildAmountForm({userContext:t,chain:a,fromContract:p,fromSym:m,fromDecimals:f,toContract:h,toSym:g,toDecimals:b,toLogo:y,fromAmount:k??void 0});if(C)return this.dbg("\u2192 Branch 1.5: amount form returned"),C;this.dbg("Branch 1.5: amount form null \u2014 needs a resolvable source token")}return this.dbg("\u2192 needs from amount"),{error:"needs_from_amount",_instructions:`Ask the user, in their language, how much ${m??"of the source token"} they want to swap to ${g}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return E(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}requireChain(e,t){return j(e.chain,t)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),s=E(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:Dt(c)}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:Dt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,n,r,s="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,d=m=>m.toLowerCase()===le?"native":m,u=l??c??(a||void 0);if(!u)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,n,r);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:n,key:u,lookup:p}),p?{address:d(p.address),symbol:p.symbolIsOnchain?p.symbol:c??p.symbol,decimals:p.decimals,logo:p.logo,symbolIsOnchain:p.symbolIsOnchain??!1}:l?{address:d(l),symbol:c}:{address:null,symbol:c}}async deriveFromAmountFromTo(e){let{chain:t,toAmount:n,toContract:r,fromContract:s}=e,[a,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(s,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:a,fromPrice:i}),!a||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,d=l*a/i;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?le:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),s=r.success?r.data?.usd_price:void 0;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}async resolveFromAmountSpec(e,t,n,r,s,a){let i=xt(e);if(!i)return null;let l=d=>a===void 0?d:Nt(d,a);if(i.kind==="token")return l(On(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let d=await this.readFromBalance(r,t,n);if(this.dbg("resolveFromAmountSpec: percent",{percent:i.percent,fromSym:s,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let u=d.decimals??a??18;return i.percent>=100?this.cleanAmountString(d.balanceFormatted):Mn(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,n);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,n,r){let s=xt(e);if(!s)return null;if(s.kind==="token")return On(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,n);return this.dbg("resolveToAmountSpec: usd",{usd:s.usd,toSym:r,price:a}),a?this.trimAmount(s.usd/a):null}async buildSourcePicker(e,t,n){if(!this.moralis||!t?.walletAddress)return{error:"source_unavailable",_instructions:"Cannot list the wallet holdings in this build. Tell the user briefly and ask them to name the token they want to swap from."};let r=this.requireChain(e,t)??void 0,s=t.walletAddress,a=await this.moralis.getWalletTokenBalances({address:s,chain:r,excludeSpam:!1,excludeUnverifiedContracts:!1}),l=(a.success?a.data?.result??[]:[]).filter(m=>m.symbol?m.native_token?!0:!!m.token_address:!1).sort((m,f)=>(f.usd_value??0)-(m.usd_value??0)).slice(0,8);if(l.length===0)return{error:"no_swap_holdings",_instructions:"The wallet holds no tokens to swap on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let c=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"",d=typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:"",u=l.map(m=>{let f=m.symbol,h=m.name?.trim()||f,g=m.balance_formatted?`${this.cleanAmountString(m.balance_formatted)} `:"",b=typeof m.usd_value=="number"&&m.usd_value>0?` ($${m.usd_value.toFixed(2)})`:"",y=`${h}: ${g}${f}${b}`,w=n?this.buildSwapToPrompt(d,f,n.symbol,null,n.amount??null,r):this.buildSwapFromPrompt(c,f,r);return{label:y,prompt:w}}),p=n?`state what the user wants to do, naming the destination they already gave (e.g., 'B\u1EA1n mu\u1ED1n swap sang ${n.symbol}.' / 'You want to swap to ${n.symbol}.')`:"state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n swap token.' / 'You want to swap a token.')";return{actionButtons:u,_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first ${p}, then ask them to choose which token to swap from in the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap.' / 'Please choose the token to swap from.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async buildToTrendingPicker(e){let{args:t,userContext:n,fromSym:r,fromContract:s}=e,a=this.requireChain(t,n)??void 0,i=this.pantograph,l=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,l)),d=await i.getTrendingTokens({chain:a,limit:c+2}),u=d.success?d.data??[]:[],p=s?.toLowerCase(),m=r.toLowerCase(),f=u.filter(v=>!(!v.symbol||p&&p!=="native"&&v.tokenAddress&&v.tokenAddress.toLowerCase()===p||v.symbol.toLowerCase()===m)).slice(0,c);if(f.length===0)return{error:"no_trending_tokens",_instructions:`No trending tokens are available to swap ${r} into on this chain right now. Tell the user briefly and suggest they name the token they want to receive directly. Do NOT mention tool names, UI, or forms.`};let h=e.fromAmount??this.normaliseAmount(t.from_amount),g=e.toAmount??this.normaliseAmount(t.to_amount),b=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",y=f.map(v=>{let A=v.symbol,S=h?this.buildSwapToPrompt(b,r,A,h,null,a):this.buildSwapToPrompt(b,r,A,null,g,a);return{label:A,prompt:S}}),k=f.map((v,A)=>{let S=v.name?.trim()||v.symbol,C=v.symbol,F=typeof v.usdPrice=="number"&&v.usdPrice>0?`$${this.formatPrice(v.usdPrice)}`:"N/A",R=v.pricePercentChange?.["24h"],me=typeof R=="number"&&Number.isFinite(R)?` (${R>0?"+":R<0?"-":""}${this.formatPercent(Math.abs(R))}%)`:"";return`${A+1}. ${S} (${C}) \u2014 ${F}${me}`}).join(`
|
|
216
216
|
`)+`
|
|
217
217
|
|
|
218
|
-
Which token do you want to receive?`;return{actionButtons:y,_instructions:`The user wants to swap ${
|
|
218
|
+
Which token do you want to receive?`;return{actionButtons:y,_instructions:`The user wants to swap ${r} into another token. The trending tokens are on ${a?T(a):"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 swap ${r} sang token kh\xE1c \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to swap ${r} \u2014 here are the tokens currently trending 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:
|
|
219
219
|
|
|
220
|
-
${k}`}}async checkFromBalance(e){let{args:t,userContext:n,chain:o,fromContract:s,fromAmount:a,derivedFromTo:i}=e,l=n.walletAddress,c=await this.readFromBalance(l,s,o),u=e.fromSym??c?.symbol??"the selected token";if(!c){this.dbg("checkFromBalance: NOT held \u2192 source picker fallback",{fromSym:u});let h=await this.buildSourcePicker(t,n,e.toSym?{symbol:e.toSym,amount:e.toAmount??null}:void 0);return"actionButtons"in h?{error:"no_from_balance",actionButtons:h.actionButtons,_instructions:`The user wanted to swap ${u}, but their wallet holds no ${u} 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 ${u} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${u} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to swap from (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to swap 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.`}:h}if(s.toLowerCase()!=="native"){let h=await Ns({chainId:o,gasKind:"swap",readNativeBalance:()=>this.readNativeHeldBalance(l,o)});if(h)return this.dbg("checkFromBalance: cannot cover gas",h),{error:"insufficient_native_for_gas",_instructions:`The wallet holds ${u} but cannot cover the network fee for this swap: it needs about ${h.shortfall} more ${h.nativeSymbol}. Tell the user in their language that they need roughly ${h.shortfall} more ${h.nativeSymbol} to pay the network fee before they can swap (e.g., 'B\u1EA1n c\u1EA7n th\xEAm kho\u1EA3ng ${h.shortfall} ${h.nativeSymbol} \u0111\u1EC3 tr\u1EA3 ph\xED m\u1EA1ng.'), and suggest they top up ${h.nativeSymbol} first. Do NOT open a form, do NOT invent a different number, and do NOT mention tool names, UI, or forms.`}}if(!a||e.amountSizedToBalance)return null;let d=c.decimals!==void 0?At(a,c.decimals):a;if(Yt(d,c.balanceFormatted)<=0)return null;let p=this.cleanAmountString(c.balanceFormatted),m=this.percentSpendButtons({balanceFormatted:c.balanceFormatted,balanceNum:c.balanceNum,decimals:c.decimals,fromSym:u,toSym:typeof t.to_symbol=="string"?t.to_symbol.trim():c.symbol??"the destination token",swapToTemplate:typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",...o===void 0?{}:{chain:o}}),g=i?`Receiving ${i} of the destination token needs about ${a} ${u}, but they only have ${p} ${u} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them this would cost about ${a} ${u}, which is more than their balance of ${p} ${u}, then ask them to choose a smaller amount \u2014 `:`The user wants to swap ${a} ${u}, but they only have ${p} ${u} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${a} ${u} exceeds their balance of ${p} ${u}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_from_balance",actionButtons:m,_instructions:g+'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 readFromBalance(e,t,n){return Us({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:n,kind:"swap",dbg:(o,s)=>this.dbg(o,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let n=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(n.success?n.data?.result??[]:[]).find(i=>i.native_token===!0),a=s?.balance_formatted!=null?Number(s.balance_formatted):0;return{balance:Number.isFinite(a)?a:0,...s?.symbol===void 0?{}:{symbol:s.symbol}}}catch{return{balance:0}}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,fromSym:o,toSym:s,swapToTemplate:a,chain:i}=e,l=n??18;return[25,50,75,100].map(u=>{let d=Cn(this.cleanAmountString(t),BigInt(u),100n,l);return{label:`${u}%`,prompt:this.buildSwapToPrompt(a,o,s,d,null,i)}})}async buildAmountForm(e){let{userContext:t,chain:n,fromContract:o,toContract:s,toSym:a,toDecimals:i,toLogo:l,fromAmount:c}=e,u=t.walletAddress;if(!n)return null;let d=ue(n);if(!d)return null;let p=await this.readFromBalance(u,o,n),m=e.fromSym??p?.symbol;if(!m)return null;let g=o==="native",h=p?.decimals??e.fromDecimals??(g?d.native.decimals??18:void 0);if(h===void 0)return null;let f=p?.balanceFormatted,b=p?.rawAmount??(f?Sn(f,h)?.toString():void 0);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:n,name:d.name},fromToken:{address:g?"native":o,symbol:m,decimals:h,amount:f,rawAmount:b??void 0,logo:p?.logo},toToken:{address:s,symbol:a,decimals:i,logo:l},walletAddress:u,intent:"swap",initialAmount:c}},_instructions:Za({action:"swap",fromSym:m,toSym:a,amount:c,spendable:f})}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildSwapFromPrompt(e,t,n){return(e&&e.includes("{token}")?e:"swap {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+Uo(n)}buildSwapToPrompt(e,t,n,o,s,a){return(e&&e.includes("{from}")&&e.includes("{to}")?e:"swap {from_amount} {from} to {to_amount} {to}").replace(/\{from\}/g,t).replace(/\{to\}/g,n).replace(/\{from_amount\}/g,o??"").replace(/\{to_amount\}/g,s??"").replace(/\s+/g," ").trim()+Uo(a)}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var Wl="{name}",Oo=class extends Ve{name="open-send-nft-form";actionType="send_nft";component="SendNftForm";userInputFields=[{key:"to_address",label:"the recipient address"}];description=`Open the SEND NFT form. Use for ANY NFT send/transfer intent: "send NFT", "transfer my Bored Ape", "send token id 1234 to 0x\u2026", "g\u1EEDi NFT". Call this tool EVEN IF the user did not name a contract, token id, NFT name, or recipient \u2014 the tool resolves missing identifiers from the wallet's NFT holdings and shows a pick-one gallery when more than one match exists. Do NOT use this for ERC-20s (use open-send-token-form) or the native coin (open-send-native-form).`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) \u2014 identifies WHICH NFT collection to send from. Only set this when the user explicitly named the collection/contract (e.g. "contract 0x\u2026", "collection 0x\u2026", "from 0x\u2026"). NEVER put the recipient address here. Omit when unknown.',required:!1},{name:"token_id",type:"string",description:'NFT token id as a decimal string (e.g. "1234"). When the message contains "Token id: <number>", that number IS this field \u2014 take it even though the NFT name before it may itself contain dashes, slashes and numbers (e.g. "Uniswap - 0.3% - LINK/WETH - 176.22<>239.30 Token id: 5118938" \u2192 "5118938"). Omit when unknown.',required:!1},{name:"nft_name",type:"string",description:'Free-form NFT or collection name as the user said it (e.g. "Bored Ape"). Used to look up the NFT in the wallet when no contract_address / token_id is provided. Omit when unknown.',required:!1},{name:"token_standard",type:"string",description:'NFT contract type ("ERC721" or "ERC1155"). Optional; the tool re-derives it from the wallet row.',required:!1},{name:"to_address",type:"string",description:'RECIPIENT EVM address (0x\u2026) \u2014 the wallet that will RECEIVE the NFT. Only set this when the user explicitly named a destination (e.g. "send to 0x\u2026", "to 0x\u2026", "g\u1EEDi \u0111\u1EBFn 0x\u2026", "cho 0x\u2026"). NEVER put the NFT collection / contract address here. Omit when unknown.',required:!1},{name:"amount",type:"string",description:"Number of editions to send. Only meaningful for ERC-1155; for ERC-721 the tool forces 1. Pass as a positive integer string. Omit when unknown \u2014 defaults to 1.",required:!1},{name:"pick_prompt_template",type:"string",description:`A short "send THIS NFT" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the user taps one NFT in the pick-one gallery. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with that NFT's name. English example: "send my {name}". Vietnamese example: "g\u1EEDi NFT {name} c\u1EE7a t\xF4i". Keep it to the action and the name only \u2014 the token id ("Token id: 5118938") and the collection contract, recipient and amount (parenthesised) are appended automatically.`,required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,o=t?.walletAddress,s=this.normaliseAddress(e.contract_address),a=this.normaliseTokenId(e.token_id),i=this.normaliseString(e.nft_name),l=this.normaliseAddress(e.to_address),c=this.normaliseString(e.token_standard),u=this.normaliseAmountInt(e.amount);if(!s&&!a&&!i)return{error:"nft_not_specified",_instructions:"The user wants to send an NFT but did not say which one. Ask them, in their language, to provide the NFT collection contract address, the token id, and the recipient address so the transfer can be prepared. Keep it to one short sentence. Do NOT open the form. Do NOT mention tool names, UI, or forms."};if(!this.moralis||!o)return this.paramsFromInputs({contract:s,tokenId:a,toAddress:l,standardArg:c,nftName:i,amountInt:u});let d=await this.moralis.getWalletNFTs({address:o,chain:n,limit:100,excludeSpam:!1}),p=d.success?d.data?.result??[]:[],m=this.matchNfts(p,{contract:s,tokenId:a,nftName:i});if(m.length===0){let g=i??(s&&a?`#${a}`:s??`#${a??""}`),h=T(n);return{error:"nft_not_owned",_instructions:`The user asked to send "${g}" but the wallet does not hold a matching NFT on ${h}. Tell them, in their language, that they do not own that NFT on ${h} and ask them to pick another one (by name, contract, or token id). Refer to the chain by this name \u2014 never as a hex id. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}return m.length===1?this.paramsFromNft(m[0],{toAddress:l,amountInt:u}):this.buildPicker(m,{chain:n,args:e,toAddress:l,amountInt:u,walletAddress:o,nftName:i})}async buildPicker(e,t){let{chain:n,args:o,toAddress:s,amountInt:a,walletAddress:i,nftName:l}=t,c=await this.resolveImages(e,n),u=this.normaliseString(o.pick_prompt_template),d=T(n),m=new Set(e.map(y=>y.token_address.toLowerCase())).size>1,g=e.map((y,w)=>{let k=this.nftDisplayName(y);return{name:k,tokenId:y.token_id,contractAddress:y.token_address,image:c[w]??In(y.normalized_metadata?.image||y.media?.original_media_url),chain:d,prompt:this.buildPickPrompt(u,{name:k,nft:y,toAddress:s,amountInt:a}),...m?{collectionName:this.collectionLabel(y)}:{}}}),h=new Set(e.map(y=>y.name?.trim()).filter(Boolean)),f=!m&&h.size===1?[...h][0]:l||"NFTs";return{ui:{component:"WalletNftList",props:{walletAddress:i,collectionName:f,nfts:g,mode:"picker"}},_instructions:`The user asked to send an NFT but ${e.length} of the NFTs they own match what they said, so it is not clear which one they mean. The matching NFTs are shown to the user as a tappable gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or repeat the individual NFTs, their images, token ids, or contract addresses yourself. Reply with ONE short sentence in the user's language asking them to choose which one they want to send. Do NOT mention tool names, UI, galleries, or components.`,matchCount:e.length}}buildPickPrompt(e,t){let{name:n,nft:o,toAddress:s,amountInt:a}=t,l=[`${(e?.includes(Wl)?e:`send my ${Wl}`).split(Wl).join(n).replace(/\s+/g," ").trim()} Token id: ${o.token_id}`,`(collection contract: ${o.token_address})`];return s&&l.push(`(to recipient: ${s})`),a&&(o.contract_type||"").toUpperCase()==="ERC1155"&&l.push(`(amount: ${a})`),l.join(" ")}async resolveImages(e,t){if(!t)return new Array(e.length).fill(null);try{let n=await qa(t,e.map(o=>({contract:o.token_address,tokenId:o.token_id})));return e.map((o,s)=>n[s]??null)}catch{return new Array(e.length).fill(null)}}normaliseString(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}normaliseTokenId(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?String(Math.trunc(e)):this.normaliseString(e)}normaliseAmountInt(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.trunc(e);if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}}nftDisplayName(e){return(e.normalized_metadata?.name||e.name||`#${e.token_id}`).toString()}collectionLabel(e){let t=e.name?.trim();if(t)return t;let n=e.token_address??"";return n.length>10?`${n.slice(0,6)}\u2026${n.slice(-4)}`:n}matchNfts(e,t){let n=t.contract?t.contract.toLowerCase():void 0,o=t.nftName?t.nftName.toLowerCase():void 0;return e.filter(s=>{if(n&&s.token_address.toLowerCase()!==n||t.tokenId&&s.token_id!==t.tokenId)return!1;if(o&&!n&&!t.tokenId){let a=(s.normalized_metadata?.name??"").toLowerCase(),i=(s.name??"").toLowerCase();if(!a.includes(o)&&!i.includes(o))return!1}return!0})}paramsFromInputs(e){let t={};return e.contract&&(t.contract_address=e.contract),e.tokenId&&(t.token_id=e.tokenId),e.toAddress&&(t.to_address=e.toAddress),e.standardArg&&(t.token_standard=e.standardArg.toUpperCase()),e.nftName&&(t.nft_name=e.nftName),e.amountInt&&(t.amount=String(e.amountInt)),t}paramsFromNft(e,t){let n=(e.contract_type||"").toUpperCase(),o=e.amount&&e.amount.trim()?e.amount.trim():"1",s=n==="ERC1155"?String(Math.min(t.amountInt??1,parseInt(o,10)||1)):"1",a={contract_address:e.token_address,token_id:e.token_id,token_standard:n||"ERC721",amount:s,maxAmount:o,nft_name:this.nftDisplayName(e)};t.toAddress&&(a.to_address=t.toAddress);let i=e.normalized_metadata?.image||e.media?.original_media_url||"";return i&&(a.nft_image=i),a}};var Is=class{name;description;category;parameters=[];message;constructor(e,t){this.name=e.name,this.description=e.description,this.category=e.category,this.message=t}async execute(){return{toolName:this.name,callId:`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,success:!0,data:{message:this.message,_instructions:`Reply with a SINGLE short sentence in the USER'S language that conveys the message below \u2014 translate it naturally rather than leaving it in its original language. Reproduce any URL in it byte-for-byte, and NEVER invent one that is not there. Output ONLY that sentence: no preamble, no second copy, no extra detail. Do NOT ask the user for any details (token, amount, recipient, \u2026) and do NOT mention tool names, forms, or UI. The message to convey:
|
|
220
|
+
${k}`}}async checkFromBalance(e){let{args:t,userContext:n,chain:r,fromContract:s,fromAmount:a,derivedFromTo:i}=e,l=n.walletAddress,c=await this.readFromBalance(l,s,r),d=e.fromSym??c?.symbol??"the selected token";if(!c){this.dbg("checkFromBalance: NOT held \u2192 source picker fallback",{fromSym:d});let h=await this.buildSourcePicker(t,n,e.toSym?{symbol:e.toSym,amount:e.toAmount??null}:void 0);return"actionButtons"in h?{error:"no_from_balance",actionButtons:h.actionButtons,_instructions:`The user wanted to swap ${d}, but their wallet holds no ${d} 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 ${d} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${d} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to swap from (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to swap 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.`}:h}if(s.toLowerCase()!=="native"){let h=await Ws({chainId:r,gasKind:"swap",readNativeBalance:()=>this.readNativeHeldBalance(l,r)});if(h)return this.dbg("checkFromBalance: cannot cover gas",h),{error:"insufficient_native_for_gas",_instructions:`The wallet holds ${d} but cannot cover the network fee for this swap: it needs about ${h.shortfall} more ${h.nativeSymbol}. Tell the user in their language that they need roughly ${h.shortfall} more ${h.nativeSymbol} to pay the network fee before they can swap (e.g., 'B\u1EA1n c\u1EA7n th\xEAm kho\u1EA3ng ${h.shortfall} ${h.nativeSymbol} \u0111\u1EC3 tr\u1EA3 ph\xED m\u1EA1ng.'), and suggest they top up ${h.nativeSymbol} first. Do NOT open a form, do NOT invent a different number, and do NOT mention tool names, UI, or forms.`}}if(!a||e.amountSizedToBalance)return null;let u=c.decimals!==void 0?Nt(a,c.decimals):a;if(Zt(u,c.balanceFormatted)<=0)return null;let p=this.cleanAmountString(c.balanceFormatted),m=this.percentSpendButtons({balanceFormatted:c.balanceFormatted,balanceNum:c.balanceNum,decimals:c.decimals,fromSym:d,toSym:typeof t.to_symbol=="string"?t.to_symbol.trim():c.symbol??"the destination token",swapToTemplate:typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",...r===void 0?{}:{chain:r}}),f=i?`Receiving ${i} of the destination token needs about ${a} ${d}, but they only have ${p} ${d} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them this would cost about ${a} ${d}, which is more than their balance of ${p} ${d}, then ask them to choose a smaller amount \u2014 `:`The user wants to swap ${a} ${d}, but they only have ${p} ${d} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${a} ${d} exceeds their balance of ${p} ${d}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_from_balance",actionButtons:m,_instructions:f+'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 readFromBalance(e,t,n){return Ys({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:n,kind:"swap",dbg:(r,s)=>this.dbg(r,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let n=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(n.success?n.data?.result??[]:[]).find(i=>i.native_token===!0),a=s?.balance_formatted!=null?Number(s.balance_formatted):0;return{balance:Number.isFinite(a)?a:0,...s?.symbol===void 0?{}:{symbol:s.symbol}}}catch{return{balance:0}}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,fromSym:r,toSym:s,swapToTemplate:a,chain:i}=e,l=n??18;return[25,50,75,100].map(d=>{let u=Mn(this.cleanAmountString(t),BigInt(d),100n,l);return{label:`${d}%`,prompt:this.buildSwapToPrompt(a,r,s,u,null,i)}})}async buildAmountForm(e){let{userContext:t,chain:n,fromContract:r,toContract:s,toSym:a,toDecimals:i,toLogo:l,fromAmount:c}=e,d=t.walletAddress;if(!n)return null;let u=we(n);if(!u)return null;let p=await this.readFromBalance(d,r,n),m=e.fromSym??p?.symbol;if(!m)return null;let f=r==="native",h=p?.decimals??e.fromDecimals??(f?u.native.decimals??18:void 0);if(h===void 0)return null;let g=p?.balanceFormatted,b=p?.rawAmount??(g?Dn(g,h)?.toString():void 0);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:n,name:u.name},fromToken:{address:f?"native":r,symbol:m,decimals:h,amount:g,rawAmount:b??void 0,logo:p?.logo},toToken:{address:s,symbol:a,decimals:i,logo:l},walletAddress:d,intent:"swap",initialAmount:c}},_instructions:gi({action:"swap",fromSym:m,toSym:a,amount:c,spendable:g})}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=r.split("."),c=i+l,d;if(a>=0){let u=i.length+a;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-a-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),n?`-${d}`:d}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildSwapFromPrompt(e,t,n){return(e&&e.includes("{token}")?e:"swap {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+Gr(n)}buildSwapToPrompt(e,t,n,r,s,a){return(e&&e.includes("{from}")&&e.includes("{to}")?e:"swap {from_amount} {from} to {to_amount} {to}").replace(/\{from\}/g,t).replace(/\{to\}/g,n).replace(/\{from_amount\}/g,r??"").replace(/\{to_amount\}/g,s??"").replace(/\s+/g," ").trim()+Gr(a)}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var dc="{name}",zr=class extends Ze{name="open-send-nft-form";actionType="send_nft";component="SendNftForm";userInputFields=[{key:"to_address",label:"the recipient address"}];description=`Open the SEND NFT form. Use for ANY NFT send/transfer intent: "send NFT", "transfer my Bored Ape", "send token id 1234 to 0x\u2026", "g\u1EEDi NFT". Call this tool EVEN IF the user did not name a contract, token id, NFT name, or recipient \u2014 the tool resolves missing identifiers from the wallet's NFT holdings and shows a pick-one gallery when more than one match exists. Do NOT use this for ERC-20s (use open-send-token-form) or the native coin (open-send-native-form).`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) \u2014 identifies WHICH NFT collection to send from. Only set this when the user explicitly named the collection/contract (e.g. "contract 0x\u2026", "collection 0x\u2026", "from 0x\u2026"). NEVER put the recipient address here. Omit when unknown.',required:!1},{name:"token_id",type:"string",description:'NFT token id as a decimal string (e.g. "1234"). When the message contains "Token id: <number>", that number IS this field \u2014 take it even though the NFT name before it may itself contain dashes, slashes and numbers (e.g. "Uniswap - 0.3% - LINK/WETH - 176.22<>239.30 Token id: 5118938" \u2192 "5118938"). Omit when unknown.',required:!1},{name:"nft_name",type:"string",description:'Free-form NFT or collection name as the user said it (e.g. "Bored Ape"). Used to look up the NFT in the wallet when no contract_address / token_id is provided. Omit when unknown.',required:!1},{name:"token_standard",type:"string",description:'NFT contract type ("ERC721" or "ERC1155"). Optional; the tool re-derives it from the wallet row.',required:!1},{name:"to_address",type:"string",description:'RECIPIENT EVM address (0x\u2026) \u2014 the wallet that will RECEIVE the NFT. Only set this when the user explicitly named a destination (e.g. "send to 0x\u2026", "to 0x\u2026", "g\u1EEDi \u0111\u1EBFn 0x\u2026", "cho 0x\u2026"). NEVER put the NFT collection / contract address here. Omit when unknown.',required:!1},{name:"amount",type:"string",description:"Number of editions to send. Only meaningful for ERC-1155; for ERC-721 the tool forces 1. Pass as a positive integer string. Omit when unknown \u2014 defaults to 1.",required:!1},{name:"pick_prompt_template",type:"string",description:`A short "send THIS NFT" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the user taps one NFT in the pick-one gallery. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with that NFT's name. English example: "send my {name}". Vietnamese example: "g\u1EEDi NFT {name} c\u1EE7a t\xF4i". Keep it to the action and the name only \u2014 the token id ("Token id: 5118938") and the collection contract, recipient and amount (parenthesised) are appended automatically.`,required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=t?.walletAddress,s=this.normaliseAddress(e.contract_address),a=this.normaliseTokenId(e.token_id),i=this.normaliseString(e.nft_name),l=this.normaliseAddress(e.to_address),c=this.normaliseString(e.token_standard),d=this.normaliseAmountInt(e.amount);if(!s&&!a&&!i)return{error:"nft_not_specified",_instructions:"The user wants to send an NFT but did not say which one. Ask them, in their language, to provide the NFT collection contract address, the token id, and the recipient address so the transfer can be prepared. Keep it to one short sentence. Do NOT open the form. Do NOT mention tool names, UI, or forms."};if(!this.moralis||!r)return this.paramsFromInputs({contract:s,tokenId:a,toAddress:l,standardArg:c,nftName:i,amountInt:d});let u=await this.moralis.getWalletNFTs({address:r,chain:n,limit:100,excludeSpam:!1}),p=u.success?u.data?.result??[]:[],m=this.matchNfts(p,{contract:s,tokenId:a,nftName:i});if(m.length===0){let f=i??(s&&a?`#${a}`:s??`#${a??""}`),h=T(n);return{error:"nft_not_owned",_instructions:`The user asked to send "${f}" but the wallet does not hold a matching NFT on ${h}. Tell them, in their language, that they do not own that NFT on ${h} and ask them to pick another one (by name, contract, or token id). Refer to the chain by this name \u2014 never as a hex id. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}return m.length===1?this.paramsFromNft(m[0],{toAddress:l,amountInt:d}):this.buildPicker(m,{chain:n,args:e,toAddress:l,amountInt:d,walletAddress:r,nftName:i})}async buildPicker(e,t){let{chain:n,args:r,toAddress:s,amountInt:a,walletAddress:i,nftName:l}=t,c=await this.resolveImages(e,n),d=this.normaliseString(r.pick_prompt_template),u=T(n),m=new Set(e.map(y=>y.token_address.toLowerCase())).size>1,f=e.map((y,w)=>{let k=this.nftDisplayName(y);return{name:k,tokenId:y.token_id,contractAddress:y.token_address,image:c[w]??Vn(y.normalized_metadata?.image||y.media?.original_media_url),chain:u,prompt:this.buildPickPrompt(d,{name:k,nft:y,toAddress:s,amountInt:a}),...m?{collectionName:this.collectionLabel(y)}:{}}}),h=new Set(e.map(y=>y.name?.trim()).filter(Boolean)),g=!m&&h.size===1?[...h][0]:l||"NFTs";return{ui:{component:"WalletNftList",props:{walletAddress:i,collectionName:g,nfts:f,mode:"picker"}},_instructions:`The user asked to send an NFT but ${e.length} of the NFTs they own match what they said, so it is not clear which one they mean. The matching NFTs are shown to the user as a tappable gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or repeat the individual NFTs, their images, token ids, or contract addresses yourself. Reply with ONE short sentence in the user's language asking them to choose which one they want to send. Do NOT mention tool names, UI, galleries, or components.`,matchCount:e.length}}buildPickPrompt(e,t){let{name:n,nft:r,toAddress:s,amountInt:a}=t,l=[`${(e?.includes(dc)?e:`send my ${dc}`).split(dc).join(n).replace(/\s+/g," ").trim()} Token id: ${r.token_id}`,`(collection contract: ${r.token_address})`];return s&&l.push(`(to recipient: ${s})`),a&&(r.contract_type||"").toUpperCase()==="ERC1155"&&l.push(`(amount: ${a})`),l.join(" ")}async resolveImages(e,t){if(!t)return new Array(e.length).fill(null);try{let n=await ti(t,e.map(r=>({contract:r.token_address,tokenId:r.token_id})));return e.map((r,s)=>n[s]??null)}catch{return new Array(e.length).fill(null)}}normaliseString(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}normaliseTokenId(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?String(Math.trunc(e)):this.normaliseString(e)}normaliseAmountInt(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.trunc(e);if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}}nftDisplayName(e){return(e.normalized_metadata?.name||e.name||`#${e.token_id}`).toString()}collectionLabel(e){let t=e.name?.trim();if(t)return t;let n=e.token_address??"";return n.length>10?`${n.slice(0,6)}\u2026${n.slice(-4)}`:n}matchNfts(e,t){let n=t.contract?t.contract.toLowerCase():void 0,r=t.nftName?t.nftName.toLowerCase():void 0;return e.filter(s=>{if(n&&s.token_address.toLowerCase()!==n||t.tokenId&&s.token_id!==t.tokenId)return!1;if(r&&!n&&!t.tokenId){let a=(s.normalized_metadata?.name??"").toLowerCase(),i=(s.name??"").toLowerCase();if(!a.includes(r)&&!i.includes(r))return!1}return!0})}paramsFromInputs(e){let t={};return e.contract&&(t.contract_address=e.contract),e.tokenId&&(t.token_id=e.tokenId),e.toAddress&&(t.to_address=e.toAddress),e.standardArg&&(t.token_standard=e.standardArg.toUpperCase()),e.nftName&&(t.nft_name=e.nftName),e.amountInt&&(t.amount=String(e.amountInt)),t}paramsFromNft(e,t){let n=(e.contract_type||"").toUpperCase(),r=e.amount&&e.amount.trim()?e.amount.trim():"1",s=n==="ERC1155"?String(Math.min(t.amountInt??1,parseInt(r,10)||1)):"1",a={contract_address:e.token_address,token_id:e.token_id,token_standard:n||"ERC721",amount:s,maxAmount:r,nft_name:this.nftDisplayName(e)};t.toAddress&&(a.to_address=t.toAddress);let i=e.normalized_metadata?.image||e.media?.original_media_url||"";return i&&(a.nft_image=i),a}};var Gs=class{name;description;category;parameters=[];message;constructor(e,t){this.name=e.name,this.description=e.description,this.category=e.category,this.message=t}async execute(){return{toolName:this.name,callId:`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,success:!0,data:{message:this.message,_instructions:`Reply with a SINGLE short sentence in the USER'S language that conveys the message below \u2014 translate it naturally rather than leaving it in its original language. Reproduce any URL in it byte-for-byte, and NEVER invent one that is not there. Output ONLY that sentence: no preamble, no second copy, no extra detail. Do NOT ask the user for any details (token, amount, recipient, \u2026) and do NOT mention tool names, forms, or UI. The message to convey:
|
|
221
221
|
|
|
222
|
-
`+this.message},duration:0}}};function
|
|
223
|
-
`),
|
|
222
|
+
`+this.message},duration:0}}};function bi(o,e,t){let n=t?.[e.name];o.register(n?new Gs(e,n):e)}var Xr=class{messages=[];fullMessages=[];summary=null;maxMessages;constructor(e=50){this.maxMessages=e}add(e){this.messages.push(e),this.fullMessages.push(e)}addMany(e){this.messages.push(...e),this.fullMessages.push(...e)}addUIOnly(e){this.fullMessages.push(e)}rollbackLastWorkingMessage(){this.messages.pop()}getAll(){return[...this.messages]}getAllFull(){return[...this.fullMessages]}getRecent(e){return this.messages.slice(-e)}getConversation(){let e=[];return this.summary&&e.push({role:"system",content:`[Previous conversation summary]: ${this.summary}`,timestamp:0}),e.push(...this.messages),e}get length(){return this.messages.length}needsSummary(){return this.messages.filter(t=>t.role==="user").length>this.maxMessages}getSummary(){return this.summary}compact(e,t=10){this.summary=e,this.messages=this.messages.slice(-t)}compactWith(e,t){this.summary=e,this.messages=[...t]}clear(){this.messages=[],this.fullMessages=[],this.summary=null}serialise(){return{messages:[...this.messages],summary:this.summary,fullMessages:[...this.fullMessages]}}restore(e){Array.isArray(e)?(this.messages=[...e],this.fullMessages=[...e],this.summary=null):(this.messages=[...e.messages],this.summary=e.summary??null,this.fullMessages=e.fullMessages?[...e.fullMessages]:[...e.messages])}};var Qr=class{llm;constructor(e){this.llm=e}async summarize(e){let t=e.filter(a=>a.role==="user"||a.role==="assistant");if(t.length===0)return"";let n=t.map(a=>`${a.role==="user"?"User":"Assistant"}: ${a.content}`).join(`
|
|
223
|
+
`),r=[{role:"system",content:"You are a conversation summarizer. Produce a concise summary of the conversation below. Keep key facts, decisions, and context that would be needed to continue the conversation. Reply with only the summary, no extra commentary. Respond in the same language as the conversation.",timestamp:0},{role:"user",content:`Summarise this conversation:
|
|
224
224
|
|
|
225
|
-
${n}`,timestamp:Date.now()}];return(await this.llm.chat(
|
|
225
|
+
${n}`,timestamp:Date.now()}];return(await this.llm.chat(r)).text}};var Oy=`You are a strict FAQ matcher. Given a user query and a list of FAQ entries, determine which FAQ entries the user is SPECIFICALLY asking about.
|
|
226
226
|
|
|
227
227
|
RULES:
|
|
228
228
|
- Only match when the user's question is CLEARLY about the same topic as the FAQ entry.
|
|
@@ -237,13 +237,13 @@ RULES:
|
|
|
237
237
|
- Return ONLY the JSON array, no other text.
|
|
238
238
|
|
|
239
239
|
FAQ ENTRIES:
|
|
240
|
-
`,
|
|
241
|
-
`),
|
|
240
|
+
`,Jr=class{entries=[];llm=null;constructor(e){e&&(this.entries=e)}setLLM(e){this.llm=e}setEntries(e){this.entries=e}addEntries(e){this.entries.push(...e)}getEntries(){return this.entries.slice()}get size(){return this.entries.length}async search(e,t=3){return this.entries.length===0?[]:this.llm?this.llmSearch(e,t):this.tokenSearch(e,t,.25)}async llmSearch(e,t){let n=this.entries.map((s,a)=>`[${a}] ${s.question}`).join(`
|
|
241
|
+
`),r=[{role:"user",content:Oy+n+`
|
|
242
242
|
|
|
243
|
-
USER QUERY: ${e}`,timestamp:0}];try{let i=(await this.llm.chat(
|
|
243
|
+
USER QUERY: ${e}`,timestamp:0}];try{let i=(await this.llm.chat(r)).text.trim().match(/\[[\s\S]*\]/);if(!i)return[];let l=JSON.parse(i[0]),c=[];for(let d of l)d.index>=0&&d.index<this.entries.length&&d.score>=.6&&c.push({entry:this.entries[d.index],score:d.score});return c.sort((d,u)=>u.score-d.score),c.slice(0,t)}catch{return this.tokenSearch(e,t,.25)}}tokenSearch(e,t,n){let r=this.tokenize(e);if(r.size===0)return[];let s=[];for(let a of this.entries){let i=this.tokenize(a.question),l=this.jaccardSimilarity(r,i);l>=n&&s.push({entry:a,score:l})}return s.sort((a,i)=>i.score-a.score),s.slice(0,t)}tokenize(e){let t=e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(n=>n.length>1);return new Set(t)}jaccardSimilarity(e,t){if(e.size===0||t.size===0)return 0;let n=0;for(let s of e)t.has(s)&&n++;let r=e.size+t.size-n;return r===0?0:n/r}};var Ks=require("@upstash/vector"),My="https://perfect-octopus-59684-us1-vector.upstash.io",Fy="ABkFMHBlcmZlY3Qtb2N0b3B1cy01OTY4NC11czFhZG1pbk56WXdOV0k0T0RndFpUaGtOeTAwWWpjMkxXRmtNRFV0WW1WaU9UaGtOMlV5T0ROaQ==",bn=class{index;namespace;minScore;defaultTopK;embedStrategy;fusionAlgorithm;debug;constructor(e={}){let t=e.url??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_URL:void 0)??My,n=e.token??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_TOKEN:void 0)??Fy;this.index=new Ks.Index({url:t,token:n}),this.namespace=e.namespace,this.minScore=e.minScore??1.3,this.defaultTopK=e.defaultTopK??3,this.embedStrategy=e.embedStrategy??"question",this.fusionAlgorithm=e.fusionAlgorithm==="RRF"?Ks.FusionAlgorithm.RRF:Ks.FusionAlgorithm.DBSF,this.debug=e.debug??!1}async search(e,t,n){let r=n?.applyMinScore??!0,s=t??this.defaultTopK;if(!e.trim())return[];let a=this.namespace?this.index.namespace(this.namespace):this.index,i;try{i=await a.query({data:e,topK:s,includeMetadata:!0,fusionAlgorithm:this.fusionAlgorithm})}catch(c){return this.debug&&console.warn("[UpstashKnowledgeBase] query failed:",c),[]}let l=[];for(let c of i){if(r&&c.score<this.minScore)continue;let d=c.metadata;!d?.question||!d?.answer||l.push({entry:{question:d.question,answer:d.answer},score:c.score})}return this.debug&&console.log(`[UpstashKnowledgeBase] query="${e}" \u2192 ${l.length}/${i.length} hit(s) `+(r?`above ${this.minScore}`:"(minScore bypassed)")+(l[0]?` (top: ${l[0].score.toFixed(3)})`:"")),l}async upsert(e){if(e.length===0)return{count:0};let t=this.namespace?this.index.namespace(this.namespace):this.index,n=await Promise.all(e.map(async r=>({id:r.id??await this.deriveId(r.question),data:this.buildEmbedText(r),metadata:{question:r.question,answer:r.answer,...r.metadata??{}}})));return await t.upsert(n),this.debug&&console.log(`[UpstashKnowledgeBase] upserted ${n.length} entr${n.length===1?"y":"ies"} (strategy=${this.embedStrategy})`),{count:n.length}}buildEmbedText(e){return this.embedStrategy==="question-and-answer"?`${e.question}
|
|
244
244
|
|
|
245
|
-
${e.answer}`:e.question}async delete(e){return e.length===0?{deleted:0}:{deleted:(await(this.namespace?this.index.namespace(this.namespace):this.index).delete(e)).deleted}}async reset(){this.namespace?await this.index.reset({namespace:this.namespace}):await this.index.reset()}async size(){let e=await this.index.info();return this.namespace?e.namespaces?.[this.namespace]?.vectorCount??0:e.vectorCount??0}async deriveId(e){let t=new TextEncoder().encode(e.trim().toLowerCase()),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(
|
|
246
|
-
`)}var
|
|
245
|
+
${e.answer}`:e.question}async delete(e){return e.length===0?{deleted:0}:{deleted:(await(this.namespace?this.index.namespace(this.namespace):this.index).delete(e)).deleted}}async reset(){this.namespace?await this.index.reset({namespace:this.namespace}):await this.index.reset()}async size(){let e=await this.index.info();return this.namespace?e.namespaces?.[this.namespace]?.vectorCount??0:e.vectorCount??0}async deriveId(e){let t=new TextEncoder().encode(e.trim().toLowerCase()),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("").slice(0,32)}};function Ct(o){return o.filter(e=>e.role!=="tool"&&!(e.role==="assistant"&&e.toolCalls&&e.toolCalls.length>0)&&!e._intermediate)}function up(o,e){let t=[];for(let n=0;n<o.length;n++){let r=o[n];if(r.role==="assistant"&&r.toolCalls&&r.toolCalls.length>0){if(r.toolCalls.every(l=>e.has(l.toolName))){t.push(r);continue}let a=r.toolCalls.map(l=>l.toolName).join(", ");t.push({role:"assistant",content:`(Previously called external tools: ${a} \u2014 results not visible here.)`,timestamp:r.timestamp});let i=new Set(r.toolCalls.map(l=>l.callId));for(;n+1<o.length;){let l=o[n+1];if(l.role==="tool"&&l.toolCallId&&i.has(l.toolCallId))n++;else break}continue}if(r.role==="tool"){r.toolName&&e.has(r.toolName)&&t.push(r);continue}t.push(r)}return t}function Ot(o,e){if(o.length<=e)return[...o];let t=o.length-e;for(;t>0;){if(o[t].role==="tool"){t--;continue}break}let n=o.slice(t),r=0;for(;r<n.length&&n[r].role==="tool";)r++;return n.slice(r)}function dp(o,e){return Ot(o,e)}function pp(o){for(let e=o.length-1;e>=0;e--){let t=o[e];if(t.role==="assistant"&&!(t.toolCalls&&t.toolCalls.length>0))return t.subagents&&t.subagents.length>0?[...t.subagents]:[]}return[]}function mp(o,e=5){let t=o.filter(a=>a.role==="tool").slice(-e);if(t.length===0)return"";let n=[],r=[];for(let a of t){let i;try{i=JSON.parse(a.content)}catch{continue}if(typeof i!="object"||i===null)continue;let l=i,c=l.pagination;c&&typeof c.cursor=="string"&&c.cursor&&r.push({toolName:a.toolName??"tool",cursor:c.cursor});let d=l.transactions??l.result??l.transfers;if(Array.isArray(d))for(let u of d)typeof u.hash=="string"&&u.hash.startsWith("0x")?n.push(u.hash):typeof u.transaction_hash=="string"&&u.transaction_hash.startsWith("0x")&&n.push(u.transaction_hash)}if(n.length===0&&r.length===0)return"";let s=["[Tool data available from previous calls:]"];if(n.length>0&&s.push(`Transaction hashes (use EXACT values): ${n.slice(0,10).join(", ")}`),r.length>0){let a=r[r.length-1];s.push(`Pagination cursor from ${a.toolName}: ${a.cursor}`)}return s.join(`
|
|
246
|
+
`)}var By=`You are a ROUTER for a multi-agent crypto/DeFi assistant. You do NOT talk to the user. You read ONE standalone user query (already contextualized upstream) plus a list of available subagents, and you emit ONE JSON object assigning the query to the right subagent(s).
|
|
247
247
|
|
|
248
248
|
OUTPUT CONTRACT \u2014 overrides everything below:
|
|
249
249
|
- Output EXACTLY ONE JSON object and nothing else: no prose, no greeting, no explanation, no markdown, no code fences \u2014 before or after.
|
|
@@ -280,33 +280,33 @@ User: "What's my USDC balance and is ETH up today?"
|
|
|
280
280
|
{"analysis":"Wallet balance + token price","assignments":[{"subagent":"wallet-agent","query":"USDC balance of my wallet","reasoning":"balance lookup"},{"subagent":"token-agent","query":"Is ETH up today?","reasoning":"price/market"}]}
|
|
281
281
|
|
|
282
282
|
User: "b\u1EA1n c\xF3 th\u1EC3 gi\xFAp g\xEC cho t\xF4i?"
|
|
283
|
-
{"analysis":"H\u1ECFi v\u1EC1 kh\u1EA3 n\u0103ng c\u1EE7a tr\u1EE3 l\xFD","assignments":[]}`,
|
|
283
|
+
{"analysis":"H\u1ECFi v\u1EC1 kh\u1EA3 n\u0103ng c\u1EE7a tr\u1EE3 l\xFD","assignments":[]}`,Zr=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??10,this.debug=t?.debug??!1}async route(e,t,n,r,s=[]){let a=n.map(k=>`### ${k.name} (domain: ${k.domain})
|
|
284
284
|
${k.description}`).join(`
|
|
285
285
|
|
|
286
|
-
`),i=[];
|
|
286
|
+
`),i=[];r?.walletAddress&&i.push(`Connected wallet: ${r.walletAddress}`),r?.chain&&i.push(`Current chain: ${r.chain}`);let l=i.length>0?`
|
|
287
287
|
|
|
288
288
|
User context:
|
|
289
289
|
${i.join(`
|
|
290
290
|
`)}`:"",c=s.length>0?`
|
|
291
291
|
|
|
292
|
-
Previous turn handled by: ${s.join(", ")}. If this query is a natural continuation (same topic), prefer the same subagent(s). Override only if the query clearly belongs to a different domain.`:"",
|
|
293
|
-
[Router] history window (${
|
|
292
|
+
Previous turn handled by: ${s.join(", ")}. If this query is a natural continuation (same topic), prefer the same subagent(s). Override only if the query clearly belongs to a different domain.`:"",d=Ct(t),u=Ot(d,this.historyMessages);this.debug&&(console.log(`
|
|
293
|
+
[Router] history window (${u.length} msg${u.length===1?"":"s"}):`),console.log(`[Router] user query: "${e}"`));let p=[{role:"system",content:By,timestamp:0},...u,{role:"user",content:`Available subagents:
|
|
294
294
|
${a}${l}${c}
|
|
295
295
|
|
|
296
|
-
User query: ${e}`,timestamp:Date.now()}],m=Date.now(),
|
|
297
|
-
[Router] (${b}ms)`),console.log(` analysis : ${
|
|
298
|
-
[Router] dispatching ${e.assignments.length} subagent(s) in parallel\u2026`);let s=Date.now(),a=e.assignments.map(async l=>{let c=t.get(l.subagent);if(!c)return this.debug&&console.log(`[Router] WARN: subagent "${l.subagent}" not registered`),{subagentName:l.subagent,steps:[],finalAnswer:`Subagent "${l.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let
|
|
296
|
+
User query: ${e}`,timestamp:Date.now()}],m=Date.now(),f=null,h="",g=null;for(let k=1;k<=2;k++){let v=await this.llm.chat(p,void 0,{maxOutputTokens:1024});h=v.text;try{f=this.parseJSON(v.text);break}catch(A){g=A,k<2&&(this.debug&&console.log(`[Router] JSON parse failed (attempt ${k}) \u2014 re-prompting for JSON`),p.push({role:"assistant",content:v.text||"",timestamp:Date.now()}),p.push({role:"user",content:'That response was not valid JSON. Do NOT answer the user and do NOT ask any questions. Reply with ONLY the routing JSON object ({"analysis": "...", "assignments": [...]}) and nothing else.',timestamp:Date.now()}))}}let b=Date.now()-m;if(!f)return this.debug&&(console.log(`[Router] JSON parse failed after retry: ${g}`),console.log(`[Router] raw response: ${h.slice(0,300)}`)),{analysis:"Router could not parse response.",assignments:[]};let y=new Set(n.map(k=>k.name)),w=Array.isArray(f.assignments)?f.assignments.filter(k=>!!k&&typeof k.subagent=="string").filter(k=>y.has(k.subagent)).map(k=>({subagent:k.subagent,query:typeof k.query=="string"&&k.query?k.query:e,reasoning:typeof k.reasoning=="string"?k.reasoning:""})):[];if(this.debug){let k=w.length>0?w.map(v=>v.subagent).join(", "):"(none \u2014 direct answer)";if(console.log(`
|
|
297
|
+
[Router] (${b}ms)`),console.log(` analysis : ${f.analysis??""}`),console.log(` dispatch : ${k}`),w.length>0)for(let v of w)console.log(` \u2192 ${v.subagent}: "${v.query}"`),console.log(` reason: ${v.reasoning}`)}return{analysis:typeof f.analysis=="string"?f.analysis:"",assignments:w}}async dispatch(e,t,n,r){if(e.assignments.length===0)return[];this.debug&&console.log(`
|
|
298
|
+
[Router] dispatching ${e.assignments.length} subagent(s) in parallel\u2026`);let s=Date.now(),a=e.assignments.map(async l=>{let c=t.get(l.subagent);if(!c)return this.debug&&console.log(`[Router] WARN: subagent "${l.subagent}" not registered`),{subagentName:l.subagent,steps:[],finalAnswer:`Subagent "${l.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let d=Date.now(),u=await c.run({query:l.query,reasoning:l.reasoning},n,r);if(this.debug){let p=u.toolResults.map(m=>m.toolName).join(", ")||"\u2014";console.log(`[Router] ${l.subagent} done in ${Date.now()-d}ms | tools: ${p}`)}return u}),i=await Promise.all(a);return this.debug&&console.log(`[Router] all subagents done in ${Date.now()-s}ms total`),i}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,"").trim());try{return JSON.parse(t)}catch(n){let r=t.match(/\{[\s\S]*\}/);if(r)return JSON.parse(r[0]);throw n}}};var qy=1024,hp=1536,$y=`
|
|
299
299
|
|
|
300
|
-
LANGUAGE-AGNOSTIC TOOL SELECTION: The user query may arrive in ANY language (English, Vietnamese, Japanese, Korean, Chinese, Thai, Spanish, Arabic, \u2026). Every intent\u2192tool mapping, verb, and example phrase in this prompt is ILLUSTRATIVE ONLY \u2014 written mostly in English for brevity, NOT a list of accepted words. Always pick the tool by the MEANING of the request, treating translated, transliterated, or mixed-language equivalents exactly like the English example (buy / send / swap / approve / show / search / trending / balance, etc. are the same intent in every language). Token symbols, contract addresses, and numbers are language-neutral \u2014 extract them verbatim. Never refuse, misroute, or fall back to plain text merely because the wording is not in English.`,
|
|
300
|
+
LANGUAGE-AGNOSTIC TOOL SELECTION: The user query may arrive in ANY language (English, Vietnamese, Japanese, Korean, Chinese, Thai, Spanish, Arabic, \u2026). Every intent\u2192tool mapping, verb, and example phrase in this prompt is ILLUSTRATIVE ONLY \u2014 written mostly in English for brevity, NOT a list of accepted words. Always pick the tool by the MEANING of the request, treating translated, transliterated, or mixed-language equivalents exactly like the English example (buy / send / swap / approve / show / search / trending / balance, etc. are the same intent in every language). Token symbols, contract addresses, and numbers are language-neutral \u2014 extract them verbatim. Never refuse, misroute, or fall back to plain text merely because the wording is not in English.`,Hy=`
|
|
301
301
|
|
|
302
|
-
OUTPUT FORMAT: Reply in plain text. NEVER draw tables or any column/pipe layout. When presenting multiple items, use a simple bullet or numbered list; otherwise just write short sentences.`,
|
|
302
|
+
OUTPUT FORMAT: Reply in plain text. NEVER draw tables or any column/pipe layout. When presenting multiple items, use a simple bullet or numbered list; otherwise just write short sentences.`,Vy=`
|
|
303
303
|
|
|
304
|
-
DATA INTEGRITY: NEVER invent, guess, round, or estimate on-chain or market values \u2014 prices, balances, amounts, holder counts, APRs, floor prices, contract or wallet addresses, transaction hashes, or token ids. Every such value MUST come verbatim from an actual tool result in this conversation. If the tools did not return it, say so plainly instead of filling it in.`,
|
|
305
|
-
[${this.name}] query: "${e.query}"`),console.log(` [${this.name}] tools available: ${
|
|
306
|
-
${
|
|
307
|
-
`)}`:"",m=e.language?`The user's current language is "${e.language}" (BCP-47). Write every user-facing string you produce \u2014 replies AND any localized tool arguments \u2014 in this language.`:"",
|
|
304
|
+
DATA INTEGRITY: NEVER invent, guess, round, or estimate on-chain or market values \u2014 prices, balances, amounts, holder counts, APRs, floor prices, contract or wallet addresses, transaction hashes, or token ids. Every such value MUST come verbatim from an actual tool result in this conversation. If the tools did not return it, say so plainly instead of filling it in.`,ee=class{name;description;domain;capability;toolNames;systemPrompt;cortexFallbackTool;mustCallTool;llm;registry;maxToolCalls;historyMessages;debug;constructor(e){if(this.name=e.name,this.description=e.description,this.domain=e.domain,this.capability=e.capability,this.toolNames=new Set(e.toolNames),this.systemPrompt=e.systemPrompt+$y+Hy+Vy,this.cortexFallbackTool=e.cortexFallbackTool,this.mustCallTool=e.mustCallTool??!1,this.cortexFallbackTool&&!this.toolNames.has(this.cortexFallbackTool))throw new Error(`Subagent "${e.name}": cortexFallbackTool "${this.cortexFallbackTool}" must be in toolNames.`);this.llm=e.llm,this.registry=e.registry,this.maxToolCalls=e.options?.maxToolCalls??5,this.historyMessages=e.options?.historyMessages??10,this.debug=e.options?.debug??!1}getCard(){return{name:this.name,description:this.description,domain:this.domain}}ownsTool(e){return this.toolNames.has(e)}getTools(){return this.registry.getDefinitions().filter(e=>this.toolNames.has(e.name))}async run(e,t,n){let r=this.getTools();if(this.debug&&(console.log(`
|
|
305
|
+
[${this.name}] query: "${e.query}"`),console.log(` [${this.name}] tools available: ${r.map(v=>v.name).join(", ")}`)),r.length===0)return{subagentName:this.name,steps:[],finalAnswer:`Subagent "${this.name}" has no registered tools available.`,toolResults:[],toolMessages:[]};let s=[],a=[],i=[],l=new Set,c=0,d=!1,u=[];if(n?.walletAddress&&u.push(`Connected wallet: ${n.walletAddress}`),n?.chain){let v=T(n.chain),A=xu(n.chain),S=A?`; native coin: ${A}`:"";u.push(`Current chain: ${v} (${n.chain})${S}`)}let p=u.length>0?`User context:
|
|
306
|
+
${u.join(`
|
|
307
|
+
`)}`:"",m=e.language?`The user's current language is "${e.language}" (BCP-47). Write every user-facing string you produce \u2014 replies AND any localized tool arguments \u2014 in this language.`:"",f=[p,m,`Routed query: ${e.query}`,e.reasoning?`Router reasoning: ${e.reasoning}`:"","Use only the tools you own. If you already have enough information, respond directly in the user's language."].filter(Boolean).join(`
|
|
308
308
|
|
|
309
|
-
`),h=
|
|
309
|
+
`),h=up(t,this.toolNames),g=Ot(h,this.historyMessages),b=[{role:"system",content:this.systemPrompt,timestamp:0},...g,{role:"user",content:f,timestamp:Date.now()}],y=6e3,w=this.maxToolCalls+1;for(let v=0;v<w;v++){let A=c<this.maxToolCalls,S=A?r:void 0,C=A&&this.mustCallTool&&c===0,F=S?qy:hp,R=await this.llm.chat(b,S,{maxOutputTokens:F,...C?{forceToolUse:!0}:{}});if(R.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&A){this.debug&&console.log(` [${this.name}] no tool called \u2014 re-prompting to act via a tool (AI fallback: ${this.cortexFallbackTool})`),b.push({role:"user",content:`You answered without calling any tool. This is not allowed for on-chain queries \u2014 you must act via a tool, not plain text. FIRST, if any of your structured tools matches the user's intent, call that ONE tool now \u2014 resolve any missing field with a sensible default (per the defaults in your instructions; chain = the connected chain, else Ethereum) instead of asking the user. ONLY if no structured tool fits \u2014 a broad, conceptual, or open-ended question \u2014 call "${this.cortexFallbackTool}" with a clear, self-contained English prompt that captures the user's intent. Do NOT answer in text \u2014 call a tool.`,timestamp:Date.now()});continue}if(c===0&&this.mustCallTool&&A&&!d){d=!0,this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing the LLM to pick a tool`),b.push({role:"user",content:"You answered in text without calling any tool. That is not allowed here: this request needs you to open a form. Call exactly ONE of your tools that matches the user's intent now. Pass only the fields the user actually gave; leave everything else blank \u2014 the tool/form collects the rest (including a token/amount picker when needed). Do NOT ask the user for missing fields. Do NOT answer in text \u2014 call the tool.",timestamp:Date.now()});continue}return this.debug&&console.log(` [${this.name}] done \u2014 ${c} tool call(s), answer: "${R.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:s,finalAnswer:R.text,toolResults:a,toolMessages:i}}let me={role:"assistant",content:R.text||"",toolCalls:R.toolCalls,timestamp:Date.now()};b.push(me);let H=[];for(let O of R.toolCalls){if(!this.toolNames.has(O.toolName)){let Ee=`Tool "${O.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${Ee}`),s.push({phase:"observe",content:Ee,timestamp:Date.now()}),b.push({role:"tool",content:Ee,toolName:O.toolName,toolCallId:O.callId,timestamp:Date.now()});continue}let he=`${O.toolName}::${JSON.stringify(O.args)}`;if(l.has(he)){let Ee=`Skipped duplicate call: ${O.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${O.toolName}`),s.push({phase:"observe",content:Ee,timestamp:Date.now()}),b.push({role:"tool",content:Ee,toolName:O.toolName,toolCallId:O.callId,timestamp:Date.now()});continue}l.add(he),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${O.toolName} ${JSON.stringify(O.args)}`),s.push({phase:"think",content:R.text||`Calling ${O.toolName}`,timestamp:Date.now()}),s.push({phase:"act",content:`Calling tool: ${O.toolName}`,toolCall:{toolName:O.toolName,args:O.args},timestamp:Date.now()});let Ve=Date.now(),Mt={...n,query:e.query},$=await this.registry.execute(O.toolName,O.args,Mt);a.push($);let De=$.success?JSON.stringify($.data):`Error: ${$.error}`;if(this.debug){let Ee=$.success?"OK":"ERR",kn=$.success?`${De.slice(0,120)}${De.length>120?"\u2026":""}`:$.error;console.log(` [${this.name}] ${Ee} (${Date.now()-Ve}ms): ${kn}`)}s.push({phase:"observe",content:De,toolResult:$,timestamp:Date.now()});let wn={role:"tool",content:De,toolName:O.toolName,toolCallId:O.callId,timestamp:Date.now()};b.push(wn),H.push({...wn,content:De.length>y?De.slice(0,y)+"\u2026[truncated]":De})}H.length>0&&(i.push(me),i.push(...H))}this.debug&&console.log(` [${this.name}] budget exhausted after ${c} calls, forcing final answer`),b.push({role:"user",content:"Tool budget reached. Give your best answer now based on the data gathered.",timestamp:Date.now()});let k=await this.llm.chat(b,void 0,{maxOutputTokens:hp});return{subagentName:this.name,steps:s,finalAnswer:k.text,toolResults:a,toolMessages:i}}};var Wy=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
|
|
310
310
|
|
|
311
311
|
SPECIALISED TOOLS (prefer these when intent matches):
|
|
312
312
|
- get-wallet-token-balances: token + native coin balances
|
|
@@ -375,7 +375,7 @@ PAGINATION:
|
|
|
375
375
|
pass the cursor from the LAST history response in conversation. Always tell the user
|
|
376
376
|
how many results were returned and whether more pages exist.
|
|
377
377
|
|
|
378
|
-
Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea \xB7 0x64 Gnosis \xB7 0x3e7 HyperEVM \xB7 0x1388 Mantle \xB7 0x8f Monad .`,
|
|
378
|
+
Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea \xB7 0x64 Gnosis \xB7 0x3e7 HyperEVM \xB7 0x1388 Mantle \xB7 0x8f Monad .`,wi=["get-wallet-token-balances","get-wallet-history","get-wallet-token-transfers","get-wallet-nft-transfers","get-wallet-pnl-summary","get-wallet-pnl","get-wallet-approvals","get-wallet-lending-positions","get-wallet-defi-positions","get-wallet-defi-protocol-positions","get-transaction-by-hash","gemini-search-ai"];function js(o,e,t){return new ee({name:"wallet-agent",domain:"wallet",capability:"check a wallet's token balances, portfolio, transaction history, PnL, DeFi positions and token approvals",description:["Wallet-scoped on-chain state. Specialised tools cover balances, net worth, transaction history,","single-tx lookup, ERC-20 / NFT transfers, PnL, DeFi positions, and approvals.","Owns READ-ONLY queries about a WALLET'S OWN DeFi positions of EVERY kind \u2014 supply/lending, LP, staking",'and borrow \u2014 both across all protocols AND within a specific NAMED protocol: "my positions", "my LP','positions", "my position on Uniswap", "what I have on Aave", "what am I earning on my USDC", "my Lido','staking", "my Pendle positions". The "my/their" (or connected-wallet) framing makes it wallet-scoped \u2014',"route it here even when a protocol like Uniswap or Aave is named.",'BUT listing the NFT TOKENS held in a named NFT collection \u2014 a "\u2026 NFTs" request carrying a 0x collection','contract address, even a collection named like "Uniswap V3 Positions" \u2014 is NFT holdings (\u2192 nft-agent), NOT',"a wallet LP-position query.","This is VIEWING only. An explicit request to ACT on an LP position \u2014 close / remove / withdraw the pair, or",'collect / claim earned fees ("close my pool", "remove liquidity", "collect my fees", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n") \u2014 is NOT in scope (\u2192 pool-agent).',"For wallet queries without a direct tool , this agent falls","back to a search-grounded Gemini model internally \u2014 it never refuses a wallet-scoped query","and always calls a tool.","NOT in scope: market-wide token data (\u2192 token-agent), NFT current holdings (\u2192 nft-agent),","pool analytics or a position looked up by its NUMERIC NFT id with no wallet (\u2192 pool-subgraph/pool-agent),",'and DISCOVERING lending markets to supply into \u2014 "where can I earn on USDC", "best/safest lending APY",','"promising lending DeFi" \u2014 which is the lending-agent, not a wallet lookup.'].join(" "),toolNames:[...wi],systemPrompt:Wy,cortexFallbackTool:"gemini-search-ai",llm:o,registry:e,options:t})}var Yy=`You are the Lending domain expert. You cover lending \u2014 supplying (depositing) an asset to a lending market to earn yield, and the markets available to supply to. Most markets are USDC, but not all: each one states its own asset, and the tools tell you which.
|
|
379
379
|
|
|
380
380
|
CHOOSING A TOOL \u2014 classify the request, do not pattern-match its wording.
|
|
381
381
|
Every lending message answers two questions. Read them off the message, then the tool follows:
|
|
@@ -471,7 +471,7 @@ RULES:
|
|
|
471
471
|
- Answer in the user's language. Do not mention tool names.
|
|
472
472
|
|
|
473
473
|
Common chain ids (not the full set \u2014 pass any chain the user names): 0x1 Ethereum \xB7 0xa Optimism \xB7
|
|
474
|
-
0x38 BSC \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum.`,
|
|
474
|
+
0x38 BSC \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum.`,fp=["get-lending-markets","get-lending-market-detail","get-wallet-lending-positions","open-supply-usdc-form","gemini-search-ai"];function pc(o,e,t){return new ee({name:"lending-agent",domain:"lending",capability:"find lending markets to supply into, describe any ONE of them in full (size, APY split, average, score), report what a wallet already supplies with APY and yield, and open the form to deposit into a chosen market (each market's own asset, usually USDC)",description:['LENDING / SUPPLY (deposit to earn yield, "savings", "earn"). Owns ALL of it:','DISCOVERY \u2014 which lending markets exist and what they pay: "promising lending DeFi", "where can I earn','on USDC", "best lending APY", "safest place to lend", "lending options on Base";','ONE market in depth \u2014 "tell me more about Aave v3 USDC", "is that Morpho vault safe", "how big is','Spark", "what is the real APY there", and any tapped "More detail" button;',`the WALLET'S OWN supply positions: "my lending positions", "where is my USDC earning",`,'"what APY am I getting", "how much am I earning on Aave/Compound/Spark/Morpho";',"and SUPPLYING ITSELF \u2014 any command to supply / deposit / lend into a named market, at any length and in",'any language ("supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare','"Supply Aave"), which opens the form the user fills in and signs.',"Covers Aave v3, Compound v3, Spark and Morpho vaults. The chains and assets are whatever the live","catalogue carries \u2014 mostly USDC on the major EVM chains \u2014 so route lending questions here even when","they name a chain or asset you do not expect, rather than assuming they are out of scope.","NOT in scope: liquidity-pool / LP / concentrated-liquidity yield (\u2192 pool agent), borrowing or a","wallet's LP / staking positions (\u2192 wallet-agent), token prices and rankings (\u2192 token-agent),","and WITHDRAWING a supply \u2014 supplying is supported, withdrawing is not."].join(" "),toolNames:[...fp],systemPrompt:Yy,cortexFallbackTool:"gemini-search-ai",llm:o,registry:e,options:t})}var Gy=`You are the Token domain expert. You answer market-wide token questions, not wallet-specific ones.
|
|
475
475
|
|
|
476
476
|
SPECIALISED TOOLS (prefer these when intent matches):
|
|
477
477
|
- get-token-info: metadata (name, symbol, decimals, address, logo)
|
|
@@ -512,7 +512,7 @@ GENERAL RULES:
|
|
|
512
512
|
- Never repeat a tool call with identical arguments.
|
|
513
513
|
- Answer in the user's language. Do not mention tool names.
|
|
514
514
|
|
|
515
|
-
Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea \xB7 0x64 Gnosis \xB7 0x3e7 HyperEVM \xB7 0x1388 Mantle \xB7 0x8f Monad. `,
|
|
515
|
+
Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea \xB7 0x64 Gnosis \xB7 0x3e7 HyperEVM \xB7 0x1388 Mantle \xB7 0x8f Monad. `,ki=["get-token-info","get-token-holders","get-token-analytics","get-token-score","get-trending-tokens","get-top-gainers","gemini-search-ai"];function zs(o,e,t){return new ee({name:"token-agent",domain:"token",capability:"look up token info, prices, analytics, holders, trending tokens and top gainers",description:["Market data for a SPECIFIC named token (by symbol or address): metadata, price, holders, analytics,","and risk score \u2014 plus market-wide RANKINGS: trending tokens and top gainers. For a token question","without a direct structured tool, this agent falls back to a search-grounded Gemini model internally \u2014","it never refuses a single-token query and always calls a tool.","NOT in scope: wallet balances or transfer history (\u2192 wallet-agent), NFT data (\u2192 nft-agent),",'broad CATEGORY / THEME discovery lists \u2014 "meme tokens", "AI tokens", "gaming / L2 / RWA tokens" (\u2192 ai-agent).'].join(" "),toolNames:[...ki],systemPrompt:Gy,cortexFallbackTool:"gemini-search-ai",llm:o,registry:e,options:t})}var Ky=`You are the NFT domain expert. You answer questions about NFT holdings and metadata, not transfer history.
|
|
516
516
|
|
|
517
517
|
SPECIALISED TOOLS (prefer these when intent matches):
|
|
518
518
|
- get-wallet-nfts: view / BROWSE the user's OWN NFT holdings \u2014 a two-step browser (collections \u2192 the NFTs inside a chosen collection). See below.
|
|
@@ -562,7 +562,7 @@ GENERAL RULES:
|
|
|
562
562
|
- get-wallet-nfts takes address / chain / contract_address / collection_name (all optional): pass contract_address + chain (+ collection_name) when the user picked or named a specific collection; omit them for a general "my NFTs" request. get-nft-metadata / get-nft-contract-info take only a \`prompt\` (no chain).
|
|
563
563
|
- For a specific NFT, use get-nft-metadata and build a prompt embedding its contract address + token id.
|
|
564
564
|
- One tool per turn. Never repeat a tool call with identical arguments.
|
|
565
|
-
- Answer in the user's language. Do not mention tool names.`,
|
|
565
|
+
- Answer in the user's language. Do not mention tool names.`,vi=["get-wallet-nfts","get-nft-metadata","get-nft-contract-info","gemini-search-ai"];function Xs(o,e,t){return new ee({name:"nft-agent",domain:"nft",capability:"look up NFT holdings, metadata and collection info",description:["Read-only NFT lookups: holdings, single-NFT metadata, and collection / contract info.",`Owns VIEWING the user's OWN NFT holdings: both the general "what NFTs do I own" (lists the wallet's`,"collections) AND listing the NFT tokens held in ONE specific collection identified by its name + 0x",'contract address \u2014 e.g. clicking a collection button, "show my <collection> NFTs on <chain> (0x\u2026)".','This INCLUDES collections whose name contains "Positions" or a protocol name (e.g. "Uniswap V3',`Positions"): a "\u2026 NFTs (0x\u2026)" holdings listing belongs HERE, not to wallet-agent's LP-position or`,"transfer tools.","For NFT category, theme, or market-wide questions without a direct tool, this agent falls back to a","search-grounded Gemini model internally \u2014 it never refuses an NFT query and always calls a tool.","NOT in scope: SENDING / transferring an NFT (the action \u2192 wallet-action-agent);","past NFT transfer history / events (\u2192 wallet-agent)."].join(" "),toolNames:[...vi],systemPrompt:Ky,cortexFallbackTool:"gemini-search-ai",llm:o,registry:e,options:t})}var jy=`You are the NFC tag expert. You speak naturally and conversationally, but with real depth \u2014 like
|
|
566
566
|
someone who genuinely understands the hardware. You handle ALL questions about NFC tags (the physical
|
|
567
567
|
near-field tags / stickers / keyfobs), NOT NFTs (NFT = digital collectible \u2014 that is the nft-agent).
|
|
568
568
|
|
|
@@ -586,7 +586,7 @@ ROUTING:
|
|
|
586
586
|
RULES:
|
|
587
587
|
- ALWAYS call exactly one tool every turn. Never repeat a tool call with identical arguments.
|
|
588
588
|
- Answer in the user's language, naturally and expertly. Do NOT mention tool names, references, or that
|
|
589
|
-
anything is canned.`,
|
|
589
|
+
anything is canned.`,Ti=["nfc-info","nfc-buy-link"];function Qs(o,e,t){return new ee({name:"nfc-agent",domain:"nfc",capability:"explain NFC tags (concept, how they work, what they store, how to use them) and point to where to buy one",description:["NFC-tag expert: explains what NFC tags are, how NFC works, what data a tag can store, tag types and","capacity, and how to read / write / use one \u2014 answering naturally but with real expertise. Also points","the user to their country's largest local marketplaces when they ask WHERE TO BUY an NFC tag.","USE THIS AGENT for any question about physical NFC tags / stickers / keyfobs / RFID-style near-field tags.","NOT in scope: NFTs (digital collectibles \u2192 nft-agent); contactless PAYMENT cards or wallet on-chain",'actions (\u2192 wallet / wallet-action agents). Distinguish "NFC" (hardware tag) from "NFT" carefully.'].join(" "),toolNames:[...Ti],systemPrompt:jy,cortexFallbackTool:"nfc-info",llm:o,registry:e,options:t})}var zy=`You are the Crypto AI fallback expert powered by a search-grounded Gemini model.
|
|
590
590
|
|
|
591
591
|
You answer ANY blockchain / crypto / token / NFT / DeFi / on-chain question that does not have a
|
|
592
592
|
direct structured tool in the other agents. The underlying model has live web-search grounding \u2014
|
|
@@ -605,7 +605,7 @@ ROUTING:
|
|
|
605
605
|
RULES:
|
|
606
606
|
- ALWAYS call the tool \u2014 NEVER refuse, NEVER answer without calling it.
|
|
607
607
|
- NEVER retry with the same prompt if the call fails \u2014 return what you have.
|
|
608
|
-
- Answer in the user's language. Do NOT mention tool names.`,
|
|
608
|
+
- Answer in the user's language. Do NOT mention tool names.`,Ai=["gemini-search-ai"];function Js(o,e,t){return new ee({name:"ai-agent",domain:"ai",capability:"answer general crypto, blockchain and DeFi questions, using up-to-date web search when needed",description:["Catch-all crypto / blockchain expert powered by a search-grounded Gemini model (live Google","Search). USE THIS AGENT whenever the query is about blockchain, crypto, tokens, NFTs, DeFi,","wallets, on-chain data, smart contracts, or any supported EVM chain BUT no other agent","(wallet-agent, token-agent, nft-agent, pool-agent) has a direct structured tool for it.","Scope examples: (1) token categories or themes \u2014 meme tokens, AI tokens, gaming tokens, L2 tokens, RWA;",'(2) protocol-specific questions \u2014 "how does X protocol work", "what happened to Y";',"(3) cross-contract or exploratory EVM analysis spanning many contracts;","(4) any open-ended on-chain question without a direct structured tool.","Prefer the specific agents when they clearly match (wallet balances \u2192 wallet-agent,","single-token info/analytics \u2192 token-agent, NFT holdings/metadata \u2192 nft-agent, DEX pools \u2192 pool-agent).","But for anything crypto-related that falls outside those, route HERE \u2014 do not return empty."].join(" "),toolNames:[...Ai],systemPrompt:zy,cortexFallbackTool:"gemini-search-ai",llm:o,registry:e,options:t})}function Pi(o){return`You are the Pool / DEX Liquidity domain expert.
|
|
609
609
|
|
|
610
610
|
You answer questions about decentralized exchange liquidity pools \u2014 specifically Uniswap V2/V3/V4 pools across EVM chains \u2014 AND you guide the user through providing liquidity to a pool.
|
|
611
611
|
|
|
@@ -621,58 +621,58 @@ CAPABILITIES (tools you own):
|
|
|
621
621
|
- Open the Add-Liquidity form for a specific pool ("add liquidity USDC/WETH 0.05% Base", "I want to provide liquidity", "farm this pool", "stake LP", "deposit into this pool", "cung c\u1EA5p thanh kho\u1EA3n", "th\xEAm thanh kho\u1EA3n")
|
|
622
622
|
- Preview the add-liquidity transaction once the user fills the form (amount + min/max price)
|
|
623
623
|
- Report the on-chain result after the user broadcasts the signed transaction
|
|
624
|
-
- Manage an EXISTING position \u2014 collect earnings / claim fees, or close / remove / withdraw the pair ("collect earnings", "claim my fees", "close the pair", "close my position", "remove liquidity", "thu ph\xED", "r\xFAt l\xE3i", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n") \u2192 call
|
|
624
|
+
- Manage an EXISTING position \u2014 collect earnings / claim fees, or close / remove / withdraw the pair ("collect earnings", "claim my fees", "close the pair", "close my position", "remove liquidity", "thu ph\xED", "r\xFAt l\xE3i", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n") \u2192 call ${o.tools.manageLiquidityRedirect} (it returns the CoinPool management link; the action is done there, not in-app)
|
|
625
625
|
|
|
626
626
|
AI FALLBACK (mandatory when no structured tool above fits):
|
|
627
627
|
- pool-fallback-ai \u2014 a search-grounded master liquidity-pool analyst that answers ANY Uniswap / DeFi pool question.
|
|
628
628
|
- Use it for broad, conceptual, strategic, or protocol-level pool questions none of the structured tools can serve ("how do Uniswap V3 pools work", "what is concentrated liquidity", "is Uniswap safe", "Uniswap vs Curve", "narrow vs wide range strategy").
|
|
629
629
|
- You MUST act via a tool every turn. NEVER answer a pool question from your own knowledge, and NEVER stop to ask "which chain?" \u2014 if a structured tool fits, call it (defaulting the chain); only if none fits, call pool-fallback-ai.
|
|
630
|
-
- EXCEPTION \u2014 earnings/yield projection: use
|
|
631
|
-
- EXCEPTION \u2014 price-range questions: use
|
|
630
|
+
- EXCEPTION \u2014 earnings/yield projection: use ${o.tools.estimateYield}, NEVER pool-fallback-ai.
|
|
631
|
+
- EXCEPTION \u2014 price-range questions: use ${o.tools.priceRanges}, NEVER pool-fallback-ai.
|
|
632
632
|
- Build the fallback prompt as a clear, self-contained English instruction with the chain and any token symbols / addresses embedded (the model does not see this conversation). Defaults when vague: chain = the connected chain (else Ethereum), count = top 10, time = last 24h, sort = 24h volume for "top / best / trending".
|
|
633
633
|
|
|
634
634
|
OUT OF SCOPE \u2014 do NOT handle these (route them elsewhere):
|
|
635
|
-
- "my LP positions", "my liquidity", "my DeFi positions" \u2192 wallet-agent owns wallet-scoped DeFi data (VIEWING position data only). NOTE: an explicit request to ACT on a position \u2014 collect earnings / close the pair / remove liquidity \u2014 is handled HERE via
|
|
635
|
+
- "my LP positions", "my liquidity", "my DeFi positions" \u2192 wallet-agent owns wallet-scoped DeFi data (VIEWING position data only). NOTE: an explicit request to ACT on a position \u2014 collect earnings / close the pair / remove liquidity \u2014 is handled HERE via ${o.tools.manageLiquidityRedirect}, NOT routed to wallet-agent.
|
|
636
636
|
- "what is USDC", "token price", "trending tokens" \u2192 token-agent
|
|
637
637
|
- "my NFTs", "NFT collection" \u2192 nft-agent
|
|
638
638
|
|
|
639
639
|
RULES:
|
|
640
640
|
- ALWAYS pass "chain" as a hex id; default to the connected chain (from User context), else "0x1" (Ethereum). NEVER ask the user "which chain?" \u2014 pick the default and call the tool.
|
|
641
|
-
- NEVER answer the first turn with a clarifying question or plain text. A bare, vague request \u2014 "show pool", "show pools", "pools", "show me pools", "xem pool", "danh s\xE1ch pool" with NO token and NO chain \u2014 maps to
|
|
642
|
-
- Default protocolVersion to "V3" for both
|
|
643
|
-
- Default sortBy to "tvl" unless the user asks about volume, activity, or yield. Use sortBy="apr" when the user asks about yield/APR/highest-earning pools (
|
|
641
|
+
- NEVER answer the first turn with a clarifying question or plain text. A bare, vague request \u2014 "show pool", "show pools", "pools", "show me pools", "xem pool", "danh s\xE1ch pool" with NO token and NO chain \u2014 maps to ${o.tools.topPools} on the default chain. Call it immediately; do NOT ask what chain or what pool they mean.
|
|
642
|
+
- Default protocolVersion to "V3" for both ${o.tools.topPools} and ${o.tools.searchPools} unless the user explicitly asks for V2, V4, or all versions ("ALL").
|
|
643
|
+
- Default sortBy to "tvl" unless the user asks about volume, activity, or yield. Use sortBy="apr" when the user asks about yield/APR/highest-earning pools (${o.tools.topPools} supports: ${o.sortKeys} \u2014 there is no transaction-count ranking; for "most active" use volume1Day).
|
|
644
644
|
- Use ONE tool per turn unless the query asks for genuinely independent data (e.g. two different chains).
|
|
645
645
|
- NEVER call the same tool twice with identical arguments.
|
|
646
646
|
- Answer in the user's language. Do NOT mention tool names or API endpoints.
|
|
647
647
|
- When showing pools, pair the two token symbols (e.g. "USDC / WETH") and include fee tier as a percentage.
|
|
648
648
|
|
|
649
|
-
TOOL SELECTION (
|
|
650
|
-
- "
|
|
651
|
-
- "
|
|
652
|
-
- "
|
|
653
|
-
- "
|
|
654
|
-
- Quick decision: count token symbols in the user's request. 0 symbols \u2192
|
|
649
|
+
TOOL SELECTION (${o.tools.topPools} vs ${o.tools.searchPools} vs ${o.tools.poolDetail}):
|
|
650
|
+
- "${o.tools.topPools}" \u2014 use ONLY when the user asks for the chain-wide ranking with NO specific token mentioned. Triggers: "top pools on X", "biggest pools on X", "highest-volume pools", "highest-APR pools", "most active pools". The result is the network-level leaderboard. ${o.tools.topPools} CANNOT filter by token.
|
|
651
|
+
- "${o.tools.searchPools}" \u2014 use whenever the user names ONE specific token (or a free-text query) and wants to see pools related to it. Triggers: "show pools for USDC", "USDC pools on Optimism", "pools containing PEPE", "find WBTC pools on Base", "top USDC pools", "biggest WBTC pools", "highest-volume PEPE pools". Words like "top", "biggest", "best", "highest" do NOT promote this to ${o.tools.topPools} \u2014 if any token symbol is named, it stays ${o.tools.searchPools} (then sort/rank the response yourself by 24h volume desc when the user asked for "top/biggest"). One-token queries ALWAYS map to ${o.tools.searchPools}, NEVER to ${o.tools.topPools}.
|
|
652
|
+
- "${o.tools.poolDetail}" \u2014 use when the user names a SPECIFIC POOL by token pair (and optionally fee tier): "USDC/WETH 0.05% on Base", "details of WBTC/USDC pool". Two symbols \u2192 pool detail.
|
|
653
|
+
- "${o.tools.priceRanges}" \u2014 use when the user names a token PAIR and asks specifically about PRICE RANGES / which range to pick / best concentrated range ("best range for ETH/USDC", "what price range should I use?", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1", "kho\u1EA3ng gi\xE1 n\xE0o t\u1ED1t nh\u1EA5t"). Pass tokens=[sym0, sym1] and chain. This is the CoinPool range-suggestion flow \u2014 NOT for "show me ETH/USDC pools" (that stays ${o.tools.poolDetail} / ${o.tools.searchPools}).
|
|
654
|
+
- Quick decision: count token symbols in the user's request. 0 symbols \u2192 ${o.tools.topPools}. 1 symbol \u2192 ${o.tools.searchPools} (regardless of words like "top"/"biggest"). 2 symbols \u2192 ${o.tools.poolDetail} (or ${o.tools.priceRanges} when the ask is explicitly about price ranges). A 0x address \u2192 ${o.tools.poolByAddress}.
|
|
655
655
|
|
|
656
|
-
COINPOOL RANGE GUIDANCE (when using
|
|
656
|
+
COINPOOL RANGE GUIDANCE (when using ${o.tools.priceRanges}):
|
|
657
657
|
- The APR in each entry is the APR earned ONLY within that specific price range. NEVER present it as the overall pool APR.
|
|
658
658
|
- Always show each entry's fee tier (the "fee" field, e.g. "0.3%") alongside its APR and min\u2013max range, e.g. "Fee 0.3% \xB7 APR 14.3% (range: 1800 \u2013 2200 USDC/ETH)".
|
|
659
659
|
- When suggesting the best range, point to the highest-APR entry and note that narrower ranges = higher concentration = higher returns but more risk of going out of range.
|
|
660
|
-
- If no CoinPool range data is returned, say so plainly and offer the pool's overall stats via
|
|
660
|
+
- If no CoinPool range data is returned, say so plainly and offer the pool's overall stats via ${o.tools.poolDetail} instead.
|
|
661
661
|
|
|
662
662
|
POOL DETAIL FLOW:
|
|
663
|
-
- "
|
|
663
|
+
- "${o.tools.poolDetail}" identifies the pool BY TOKEN PAIR, never by address. Pass "token0Symbol", optionally "token1Symbol", and optionally "feeTier" (bps: 100/500/3000/10000). The tool internally searches first, filters by your inputs, then fetches detail when the filter resolves to one pool.
|
|
664
664
|
- For "details of pool USDC/WETH 0.05% on Base" \u2192 call with token0Symbol="USDC", token1Symbol="WETH", feeTier=500, chain="0x2105".
|
|
665
665
|
- For incomplete input (only one symbol, or pair without fee tier), STILL call this tool with whatever you have. If the filter matches multiple pools, the tool returns { candidates: [...] } (no "pool" field). Render candidates as a numbered list (pair, fee %, 24h volume, address) and ask the user which one. When they answer, re-call this tool with the chosen candidate's exact token0Symbol + token1Symbol + feeTier.
|
|
666
|
-
- NEVER pass a pool address to "
|
|
666
|
+
- NEVER pass a pool address to "${o.tools.poolDetail}" \u2014 the tool does not accept one. NEVER fabricate pool stats from a candidates response.
|
|
667
667
|
|
|
668
668
|
ADDRESS LOOKUP FLOW:
|
|
669
|
-
- When the user pastes a single 0x address WITHOUT saying whether it is a pool or a token, use "
|
|
669
|
+
- When the user pastes a single 0x address WITHOUT saying whether it is a pool or a token, use "${o.tools.poolByAddress}" with "address" + "chain". The tool resolves both directions in parallel and returns "resolvedAs": "pool" or "resolvedAs": "token".
|
|
670
670
|
- "resolvedAs": "pool" \u2192 render the pool detail (pair, fee %, TVL, 24h volume + fees, APR, reserves, tx count). For V4 pools also mention tickSpacing, isDynamicFee, and the hook address if present. The tool auto-handles V2/V3/V4 \u2014 do NOT filter by protocol version yourself.
|
|
671
|
-
- "resolvedAs": "token" \u2192 tell the user which token it is (symbol + name) and render the returned pools as a numbered list. When the user picks one, re-call "
|
|
671
|
+
- "resolvedAs": "token" \u2192 tell the user which token it is (symbol + name) and render the returned pools as a numbered list. When the user picks one, re-call "${o.tools.poolByAddress}" with that pool's address.
|
|
672
672
|
- If the user already says "this is a pool address" or "this is a token address", you can still use this tool \u2014 it works for either case.
|
|
673
|
-
- Use "
|
|
673
|
+
- Use "${o.tools.poolDetail}" (token-pair flow) when the user describes a pool BY SYMBOLS, and "${o.tools.poolByAddress}" when they paste a raw address.
|
|
674
674
|
|
|
675
|
-
YIELD ESTIMATION FLOW (
|
|
675
|
+
YIELD ESTIMATION FLOW (${o.tools.estimateYield}):
|
|
676
676
|
|
|
677
677
|
Intent recognition \u2014 the user wants a yield estimate when they say things like:
|
|
678
678
|
"n\u1EBFu t\xF4i b\u1ECF X$ v\xE0o pool A/B th\xEC m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "if I put $X into pool A/B how much do I earn per day?",
|
|
@@ -680,7 +680,7 @@ Intent recognition \u2014 the user wants a yield estimate when they say things l
|
|
|
680
680
|
"daily/weekly/monthly earnings", "how much will I make if I deposit X dollars?", "l\u1EE3i nhu\u1EADn \u01B0\u1EDBc t\xEDnh", "yield estimate".
|
|
681
681
|
These are INFORMATION questions \u2014 the user has NOT asked to actually deposit yet.
|
|
682
682
|
|
|
683
|
-
CRITICAL \u2014 minimize back-and-forth. Call
|
|
683
|
+
CRITICAL \u2014 minimize back-and-forth. Call ${o.tools.estimateYield} IMMEDIATELY with whatever info the user gave you. The tool handles missing info on its own:
|
|
684
684
|
- ONE token mentioned (e.g. "ETH yield?", "l\u1EDDi bao nhi\xEAu khi farm USDC"): pass just token0Symbol. The tool auto-picks the highest-volume pool. Do NOT ask the user for the other token.
|
|
685
685
|
- TWO tokens, no fee tier (e.g. "USDC/WETH yield"): pass both symbols. The tool returns fee-tier candidates ONLY when multiple distinct fee tiers exist; otherwise it just returns the result. Ask the user to pick a fee tier ONLY when the tool returns candidates.
|
|
686
686
|
- No deposit amount: just call the tool. It defaults to $1000 and marks the result as a per-$1000 example. Do NOT ask the user for the deposit amount upfront.
|
|
@@ -698,41 +698,41 @@ Yield estimate presentation:
|
|
|
698
698
|
- Answer in the user's language. Format USD with 2 decimals.
|
|
699
699
|
- After showing the yield, you MAY offer to open the add-liquidity form if the user seems interested in depositing.
|
|
700
700
|
|
|
701
|
-
ADD-LIQUIDITY FLOW (
|
|
701
|
+
ADD-LIQUIDITY FLOW (${o.tools.openAddLiquidityForm} + build-add-liquidity-tx):
|
|
702
702
|
|
|
703
703
|
Intent recognition \u2014 the user wants to add liquidity whenever they say (in any language) things like:
|
|
704
704
|
"add liquidity", "provide liquidity", "add LP", "supply LP", "deposit into pool", "stake into pool", "farm this pool",
|
|
705
705
|
"th\xEAm thanh kho\u1EA3n", "cung c\u1EA5p thanh kho\u1EA3n", "b\u1ECF ti\u1EC1n v\xE0o pool", "farm pool", "v\xE0o pool", "add pool", "c\u1EA5p v\u1ED1n pool".
|
|
706
706
|
Treat all of these as the same intent. Words like "buy" / "swap" / "trade" are NOT this intent \u2014 those go to the token agent or to a swap flow.
|
|
707
|
-
A bare add-liquidity request with NO pool/pair named ("i want to add pool", "add pool", "add liquidity", "i want to add liquidity pool", "th\xEAm thanh kho\u1EA3n", "cung c\u1EA5p thanh kho\u1EA3n") is STILL this intent: NEVER reply in text asking which pool, and NEVER fall back to pool-fallback-ai for it \u2014 IMMEDIATELY call
|
|
707
|
+
A bare add-liquidity request with NO pool/pair named ("i want to add pool", "add pool", "add liquidity", "i want to add liquidity pool", "th\xEAm thanh kho\u1EA3n", "cung c\u1EA5p thanh kho\u1EA3n") is STILL this intent: NEVER reply in text asking which pool, and NEVER fall back to pool-fallback-ai for it \u2014 IMMEDIATELY call ${o.tools.topPools} with sortBy="apr" AND forAddLiquidity=true on the default chain, present the candidates with an expert "which pool to add" read, and ask the user to pick one to continue the add-liquidity flow. The forAddLiquidity=true flag makes the tool validate ADD-LIQUIDITY chain support (gateway chains) so a chain that can't add liquidity is reported up front, before the user picks a pool. When the user names exactly ONE token but not the pair ("add liquidity with USDC", "th\xEAm thanh kho\u1EA3n USDC"), call ${o.tools.searchPools} instead.
|
|
708
708
|
|
|
709
709
|
CHAIN SUPPORT \u2014 TWO SEPARATE LISTS:
|
|
710
|
-
\u2022 Pool INFO/data (
|
|
711
|
-
\u2022 ADD-LIQUIDITY works on a SMALLER, dynamic subset \u2014 only chains the app has a gateway configured for. You do NOT know that subset up front; the tools decide it at call time. So a chain can show full pool info yet not support adding liquidity. If add-liquidity is unavailable on a chain (
|
|
710
|
+
\u2022 Pool INFO/data (${o.tools.topPools}, ${o.tools.searchPools}, ${o.tools.poolDetail}, ${o.tools.poolByAddress}, ${o.tools.estimateYield}) works on: ${o.infoChains}.
|
|
711
|
+
\u2022 ADD-LIQUIDITY works on a SMALLER, dynamic subset \u2014 only chains the app has a gateway configured for. You do NOT know that subset up front; the tools decide it at call time. So a chain can show full pool info yet not support adding liquidity. If add-liquidity is unavailable on a chain (${o.tools.openAddLiquidityForm} returns error="no_gateway_configured" / "unsupported_chain"), tell the user add-liquidity isn't supported there yet \u2014 the pool INFO is still valid. Never promise add-liquidity on a chain just because its pool data showed up.
|
|
712
712
|
|
|
713
|
-
SUGGESTION BUTTONS (always on, where supported): whenever you show pools \u2014 a ranked list, a search result, a pair's fee-tier variants, OR a single pool's detail \u2014 a one-tap "Add liquidity" button renders under each pool automatically (capped at 5), BUT ONLY on chains that support add-liquidity (the tool omits the buttons on info-only chains). So you MUST supply add_button_label and add_prompt_template on EVERY pool tool call that returns pools:
|
|
713
|
+
SUGGESTION BUTTONS (always on, where supported): whenever you show pools \u2014 a ranked list, a search result, a pair's fee-tier variants, OR a single pool's detail \u2014 a one-tap "Add liquidity" button renders under each pool automatically (capped at 5), BUT ONLY on chains that support add-liquidity (the tool omits the buttons on info-only chains). So you MUST supply add_button_label and add_prompt_template on EVERY pool tool call that returns pools: ${o.tools.topPools}, ${o.tools.searchPools}, ${o.tools.poolDetail}, ${o.tools.poolByAddress}, and ${o.tools.openAddLiquidityForm}. There is NO intent flag any more \u2014 the buttons are shown for informational listings ("top pools on Base", "USDC pools") and pool-detail views alike, not only the add-liquidity pick step. Whether they actually render is decided by the tool based on add-liquidity chain support; do not assume they always appear and never list, number, or repeat these buttons in your prose. The default list size is 5; do not pass a larger limit/size unless the user explicitly asks for more.
|
|
714
714
|
- LANGUAGE (MANDATORY): both add_button_label and add_prompt_template MUST be written in the SAME language the user is currently writing in \u2014 NEVER English when the user is writing in another language. Translate the verb/phrase, keep the literal "{pair}" placeholder untranslated. Examples \u2014 user in English: label "Add liquidity to {pair}", prompt "add liquidity to {pair}"; user in Vietnamese: label "Th\xEAm thanh kho\u1EA3n {pair}", prompt "th\xEAm thanh kho\u1EA3n {pair}"; user in Japanese: label "{pair} \u306B\u6D41\u52D5\u6027\u3092\u8FFD\u52A0", prompt "{pair} \u306B\u6D41\u52D5\u6027\u3092\u8FFD\u52A0". The pair text inside {pair} (symbols + fee %) stays verbatim.
|
|
715
715
|
|
|
716
716
|
Context carry-over (IMPORTANT):
|
|
717
|
-
When the user says "add this pool", "farm this", "I want to add liquidity to this pool" \u2014 referring to a pool already shown in the CURRENT conversation \u2014 extract token0Symbol, token1Symbol, and feeTier directly from the previous tool result (pool.token0.symbol, pool.token1.symbol, pool.feeTierBps) WITHOUT calling any search tool again. Call
|
|
717
|
+
When the user says "add this pool", "farm this", "I want to add liquidity to this pool" \u2014 referring to a pool already shown in the CURRENT conversation \u2014 extract token0Symbol, token1Symbol, and feeTier directly from the previous tool result (pool.token0.symbol, pool.token1.symbol, pool.feeTierBps) WITHOUT calling any search tool again. Call ${o.tools.openAddLiquidityForm} immediately with those values.
|
|
718
718
|
|
|
719
|
-
Required inputs for
|
|
719
|
+
Required inputs for ${o.tools.openAddLiquidityForm}:
|
|
720
720
|
- token0Symbol, token1Symbol, feeTier (bps: 100/500/3000/10000), chain.
|
|
721
721
|
- Optional: prefillNativeAmountWei \u2014 pass when the user already named an amount (see "Amount-first inputs" below).
|
|
722
722
|
- If any required field is missing, do NOT call this tool yet. Resolve the missing piece first:
|
|
723
|
-
* Pair given but no fee tier ("i want add usdc/weth", "th\xEAm thanh kho\u1EA3n USDC/WETH") \u2192 call
|
|
724
|
-
* Only one symbol \u2192 call
|
|
725
|
-
* No pool at all ("I want to farm something on Base", "add pool") \u2192 call
|
|
723
|
+
* Pair given but no fee tier ("i want add usdc/weth", "th\xEAm thanh kho\u1EA3n USDC/WETH") \u2192 call ${o.tools.openAddLiquidityForm} with just the pair (no feeTier) AND pass add_button_label + add_prompt_template (localized, with the "{pair}" placeholder). If multiple fee tiers exist it returns candidates; present them with an expert read \u2014 a one-tap "Add liquidity" button is rendered per fee tier automatically, so do NOT also ask the user to type a tier. (Only fall back to ${o.tools.poolDetail} for a pure "show me this pool" info question.)
|
|
724
|
+
* Only one symbol \u2192 call ${o.tools.searchPools} (returns pools containing that token); list them and ask the user to pick. Do NOT ask the user to type the other token from scratch.
|
|
725
|
+
* No pool at all ("I want to farm something on Base", "add pool") \u2192 call ${o.tools.topPools} with sortBy="apr" AND forAddLiquidity=true first, present the candidates with an expert pick, and ask the user to choose.
|
|
726
726
|
|
|
727
727
|
Amount-first inputs (e.g. "add 0.1 ETH to a pool", "th\xEAm 0.5 ETH v\xE0o pool USDC/WETH 0.05% Base", "add $10 to this pool", "10 dollars"):
|
|
728
728
|
- The user often supplies the AMOUNT before (or together with) the pool. Remember it across turns.
|
|
729
729
|
- Native-token amount (ETH, BNB, MATIC, etc.): pass as prefillNativeAmountWei = floor(amount \xD7 10^18) as a decimal string. Example: 0.1 ETH \u2192 "100000000000000000". 0.5 ETH \u2192 "500000000000000000". Do NOT use scientific notation; emit a plain integer string.
|
|
730
730
|
- USD amount ("$10", "10 dollars", "10$", "10 USD"): pass as prefillUsdAmount = the numeric dollar value (e.g. 10, 25.5). The tool converts to native wei automatically. Do NOT compute the conversion yourself.
|
|
731
731
|
- If the user only said "add 0.1 ETH to a pool" (or "$10 to a pool") with no pool yet:
|
|
732
|
-
1. Call
|
|
733
|
-
2. Show 5\u201310 candidates. Once the user picks one, call
|
|
732
|
+
1. Call ${o.tools.topPools} with sortBy="apr" AND forAddLiquidity=true on the relevant chain (default to userContext.chain, else ask).
|
|
733
|
+
2. Show 5\u201310 candidates. Once the user picks one, call ${o.tools.openAddLiquidityForm} with the appropriate prefill parameter.
|
|
734
734
|
|
|
735
|
-
Price-range prefill (
|
|
735
|
+
Price-range prefill (${o.tools.openAddLiquidityForm}) \u2014 pass these to skip the user having to type min/max manually:
|
|
736
736
|
- Explicit numbers ("range 1800 to 2200", "min 0.0005 max 0.0008", "kho\u1EA3ng gi\xE1 1800-2200"): pass minPrice + maxPrice as plain decimals in the SAME unit as pool.currentPrice (token1 per token0). When both are present, the tool ignores rangeStrategy.
|
|
737
737
|
- Strategy keywords: pass rangeStrategy when the user signals a preference but does not name numbers:
|
|
738
738
|
* "stable" \u2014 narrow \xB13 tickSpacing around current price. Triggers: "safe", "tight", "narrow", "high yield", "stablecoin pool", "t\u1EADp trung", "h\u1EB9p", "ch\u1EB7t", "an to\xE0n".
|
|
@@ -742,24 +742,24 @@ Price-range prefill (open-add-liquidity-form) \u2014 pass these to skip the user
|
|
|
742
742
|
- The tool returns prefillRange in the form props; the FE pre-populates the inputs but keeps them editable.
|
|
743
743
|
|
|
744
744
|
2-turn flow overview:
|
|
745
|
-
Turn 1:
|
|
746
|
-
Turn 2:
|
|
745
|
+
Turn 1: ${o.tools.openAddLiquidityForm} \u2192 renders AddLiquidityForm UI (pool info + native input + price-range inputs)
|
|
746
|
+
Turn 2: ${o.tools.previewAddLiquidity} \u2192 renders ConfirmAddLiquidityTx UI (expected amounts + unsigned tx)
|
|
747
747
|
|
|
748
|
-
FAST PATH \u2014 skip the form and call
|
|
748
|
+
FAST PATH \u2014 skip the form and call ${o.tools.previewAddLiquidity} DIRECTLY (do NOT ${o.tools.openAddLiquidityForm} first) the moment you ALREADY have ALL of these, whether the user typed them in one message or they carry over from context:
|
|
749
749
|
\u2022 a concrete pool ADDRESS (0x\u2026 \u2014 given by the user OR from a prior tool result's pool.address), AND
|
|
750
750
|
\u2022 a native amount, AND
|
|
751
751
|
\u2022 BOTH min and max price.
|
|
752
|
-
The form's ONLY job is to COLLECT those inputs; when they are already provided, opening it just stalls the user. Example that MUST go straight to
|
|
753
|
-
Only when you do NOT have a concrete pool address (just token symbols / a fee tier) do you go through
|
|
752
|
+
The form's ONLY job is to COLLECT those inputs; when they are already provided, opening it just stalls the user. Example that MUST go straight to ${o.tools.previewAddLiquidity}: "add liquidity to USDC/WETH on Optimism with 0.0000174 ETH, price range 0.000533 to 0.000651, pool=0x\u2026". Pass poolAddress, chain, minPrice, maxPrice, nativeAmount as-is.
|
|
753
|
+
Only when you do NOT have a concrete pool address (just token symbols / a fee tier) do you go through ${o.tools.openAddLiquidityForm} first \u2014 ${o.tools.previewAddLiquidity} REQUIRES the exact pool address.
|
|
754
754
|
|
|
755
|
-
After
|
|
755
|
+
After ${o.tools.openAddLiquidityForm} returns (Turn 1):
|
|
756
756
|
- The FE renders the form. Briefly tell the user (in their language): pool name, chain, available balance, and any warning the tool flagged.
|
|
757
757
|
- Warning="no_balance" \u2192 tell them they must top up before they can add.
|
|
758
758
|
- Warning="insufficient_balance" \u2192 tell them the spendable balance is insufficient.
|
|
759
759
|
- Then WAIT. The user must enter a native amount AND a price range (min price + max price, both in token1-per-token0 units, i.e. the SAME unit as pool.currentPrice) before submitting.
|
|
760
760
|
- Reference values for the user: pool.currentPrice tells them where the price is right now. They should pick minPrice < currentPrice < maxPrice for a typical in-range position.
|
|
761
761
|
|
|
762
|
-
When the user submits the form (Turn 2 \u2192
|
|
762
|
+
When the user submits the form (Turn 2 \u2192 ${o.tools.previewAddLiquidity}):
|
|
763
763
|
- Required: poolAddress, chain, minPrice, maxPrice, nativeAmountWei.
|
|
764
764
|
- Convert the user's native amount to wei: floor(amount \xD7 10^18) as a plain integer string. Example: 0.1 \u2192 "100000000000000000".
|
|
765
765
|
- Pass minPrice and maxPrice as plain decimal numbers in the SAME unit as pool.currentPrice. Do NOT convert to ticks \u2014 the BE handles tick conversion.
|
|
@@ -768,19 +768,19 @@ When the user submits the form (Turn 2 \u2192 preview-add-liquidity):
|
|
|
768
768
|
|
|
769
769
|
NOTE: many chat clients submit form/confirm panels directly to the BE tool (agent.invokeTool, deterministic path), bypassing the LLM. When you DO see a conversational confirm like "OK, 0.1 ETH range 1500\u20132200" you handle it as above.
|
|
770
770
|
|
|
771
|
-
|
|
771
|
+
${o.tools.previewAddLiquidity} error handling:
|
|
772
772
|
- "invalid_price_range" \u2192 minPrice/maxPrice swapped, \u22640, or equal. Ask the user for a wider range.
|
|
773
773
|
- "invalid_range_after_alignment" \u2192 range collapsed when aligned to tickSpacing. Ask for a wider range.
|
|
774
774
|
- "insufficient_balance" \u2192 user lacks native + gas reserve. Tell them the shortfall.
|
|
775
775
|
|
|
776
776
|
State awareness:
|
|
777
777
|
- If the form is already open and the user asks an info question ("what's the current price?", "what range should I pick?"), answer in TEXT \u2014 do NOT re-open the form.
|
|
778
|
-
- If the user wants to switch pools mid-flow ("no, use 0.3% instead"), call
|
|
779
|
-
- If the user changes only the amount or range ("make it 0.2 ETH and tighter range 1700\u20131900"), call
|
|
778
|
+
- If the user wants to switch pools mid-flow ("no, use 0.3% instead"), call ${o.tools.openAddLiquidityForm} again with the new fee tier.
|
|
779
|
+
- If the user changes only the amount or range ("make it 0.2 ETH and tighter range 1700\u20131900"), call ${o.tools.previewAddLiquidity} again \u2014 do NOT re-open the form.
|
|
780
780
|
|
|
781
781
|
Never fabricate pool addresses, tick numbers, prices, or NFT ids. Every value must come from a tool call this turn or the immediately preceding turn.
|
|
782
782
|
|
|
783
|
-
Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea
|
|
783
|
+
Chain ids: ${o.chainIdList}.`}var Xy=Pi({infoChains:"Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea",chainIdList:"0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea",sortKeys:"tvl, volume1Day, volume30Day, apr",tools:{topPools:"uniswap-top-pools",searchPools:"uniswap-search-pools",poolDetail:"uniswap-pool-detail",poolByAddress:"uniswap-pool-by-address",estimateYield:"uniswap-estimate-pool-yield",priceRanges:"pool-price-ranges",openAddLiquidityForm:"pool-open-add-liquidity-form",previewAddLiquidity:"pool-preview-add-liquidity",manageLiquidityRedirect:"pool-manage-liquidity-redirect"}}),Si=["uniswap-top-pools","uniswap-pool-detail","uniswap-search-pools","uniswap-pool-by-address","pool-open-add-liquidity-form","pool-preview-add-liquidity","uniswap-estimate-pool-yield","pool-price-ranges","pool-manage-liquidity-redirect","pool-fallback-ai"];function Zs(o,e,t){return new ee({name:"pool-uniswap-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Handles questions about decentralized exchange liquidity pools \u2014 Uniswap V2/V3/V4 across EVM chains \u2014","AND walks the user through ADDING LIQUIDITY to a pool (provide LP / farm / stake / deposit / cung c\u1EA5p thanh kho\u1EA3n).","Scope: (1) top pools by chain \u2014 biggest pools ranked by TVL, volume, or transaction count;","(2) pool composition \u2014 which token pairs dominate liquidity on a given network;","(3) pool-level analytics \u2014 fee tier, rolling volume buckets (1d/1w/30d), tx count, both tokens;","(4) pool detail by token pair (and optional fee tier) \u2014 full stats for a single pool including TVL, 24h volume, fees, APR estimate, token reserves, and weekly volume history;","(5) pool search \u2014 find pools that match a free-text query (token symbol, token name, or pool address) on a given chain;","(6) single-address lookup \u2014 when the user pastes one 0x address without saying whether it is a pool or a token, resolve both;",'(7) YIELD ESTIMATION \u2014 estimate daily/weekly/monthly/yearly fee income for a given USD deposit into a specific pool ("if I put $1000 into USDC/WETH 0.05%, how much do I earn per day?", "b\u1ECF 500$ v\xE0o pool n\xE0y l\u1EDDi bao nhi\xEAu?");',"(8) ADD LIQUIDITY \u2014 open the AddLiquidityForm UI for a chosen pool, then build the unsigned mint transaction once the user confirms amount and price range.","(9) MANAGE / ACT ON AN EXISTING POSITION \u2014 closing / removing / withdrawing the pair OR collecting / claiming earned fees on the user's OWN position",'("close my pool", "close my position", "remove liquidity", "withdraw liquidity", "collect my fees", "claim earnings", "\u0111\xF3ng pool", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "thu ph\xED") \u2014 handled HERE (returns the CoinPool management link).',`NOT in scope: VIEWING a wallet's OWN LP / DeFi position DATA \u2014 "my positions", "my position on Uniswap", "my Uniswap positions",`,'"what I have on Aave", any read-only "my/their positions" query (with or without a protocol named) (\u2192 wallet-agent).',`IMPORTANT distinction: VIEWING / listing one's own positions \u2192 wallet-agent; ACTING on one (close / remove / withdraw / collect fees) \u2192 pool-agent (here), even when phrased as "my pool" / "my position".`,"token metadata or token-level market data (\u2192 token-agent), NFT data (\u2192 nft-agent).",'Key distinction from token-agent: pool-agent answers "which POOLS are biggest / most active" and handles "I want to add LP",','while token-agent answers "what is this TOKEN" and "what is the market doing for this TOKEN".'].join(" "),toolNames:[...Si],systemPrompt:Xy,cortexFallbackTool:"pool-fallback-ai",llm:o,registry:e,options:t})}var Qy=`You are the Uniswap V3 Subgraph DEX-pool expert.
|
|
784
784
|
|
|
785
785
|
You answer questions about Uniswap V3 liquidity pools using The Graph subgraphs. APR values are enriched from DefiLlama Yields. Concentrated-liquidity price-range data comes from the CoinPool platform.
|
|
786
786
|
|
|
@@ -870,7 +870,7 @@ YIELD / EARNINGS PROJECTION ("how much would I earn"):
|
|
|
870
870
|
FOLLOW-UPS / CONTINUATIONS:
|
|
871
871
|
- Short replies like "yes", "tell me more", "the first one", "show ranges" refer back to the previous turn. Extract tokens/chains/pool addresses from the prior assistant message and call the appropriate tool. NEVER ask for clarification when history clearly shows what was discussed.
|
|
872
872
|
|
|
873
|
-
NEVER fabricate pool addresses, token prices, APRs, or position ids. Every value must come from a tool call this turn or the immediately preceding turn.`,
|
|
873
|
+
NEVER fabricate pool addresses, token prices, APRs, or position ids. Every value must come from a tool call this turn or the immediately preceding turn.`,gp=["subgraph-search-pools","subgraph-trending-pools","subgraph-pool-by-address","subgraph-pool-by-position-id","subgraph-position-detail","subgraph-coinpool-pairs","subgraph-add-pool","pool-fallback-ai"];function mc(o,e,t){return new ee({name:"pool-subgraph-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Answers questions about Uniswap V3 liquidity pools using The Graph subgraphs as the primary source","(APR is enriched from DefiLlama Yields; concentrated-liquidity price ranges come from CoinPool).","Scope: (1) pool search by token symbols on one or more EVM chains, with TVL/APR/fee filters and sort by tvl/volume/apr/fee/liquidity;","(2) trending pools ranked by volume past day on a chain;","(3) pool detail for a specific 0x pool address;","(4) lookup the underlying pool for a Uniswap V3 NFT position id (numeric, e.g. 962961);","(5) full position detail (deposits, withdrawals, collected fees) for a numeric position id;","(6) CoinPool concentrated-liquidity price-range candidates with per-range APR for a token pair;","(7) the add-liquidity / add-pool / create-pair INTENT \u2014 resolves the pool (by address or token pair) and surfaces the add-liquidity website link.","Handles a position ONLY by its NUMERIC NFT id (e.g. 962961) \u2014 NEVER a wallet's own holdings.",'NOT in scope: ANY wallet-scoped LP/DeFi holdings \u2014 "my positions", "my Uniswap positions", "my position on Uniswap",','"what I have on Aave" and every "my/their" positions query (with or without a protocol named) belong to wallet-agent;',"also out of scope: sending/transferring LP NFTs, building/signing the add-liquidity transaction itself,","token metadata (\u2192 token-agent), NFT data (\u2192 nft-agent).","Prefer this subagent over pool-agent when the deployment is configured to use Subgraph data (the two are mutually exclusive at config time)."].join(" "),toolNames:[...gp],systemPrompt:Qy,cortexFallbackTool:"pool-fallback-ai",llm:o,registry:e,options:t})}var Jy=Pi({infoChains:"Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche",chainIdList:"0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche",sortKeys:"tvl, volume1Day, volume7Day, apr",tools:{topPools:"defillama-top-pools",searchPools:"defillama-search-pools",poolDetail:"defillama-pool-detail",poolByAddress:"defillama-pool-by-address",estimateYield:"defillama-estimate-pool-yield",priceRanges:"pool-price-ranges",openAddLiquidityForm:"pool-open-add-liquidity-form",previewAddLiquidity:"pool-preview-add-liquidity",manageLiquidityRedirect:"pool-manage-liquidity-redirect"}}),yp=["defillama-top-pools","defillama-pool-detail","defillama-search-pools","defillama-pool-by-address","pool-open-add-liquidity-form","pool-preview-add-liquidity","defillama-estimate-pool-yield","pool-price-ranges","pool-manage-liquidity-redirect","pool-fallback-ai"];function hc(o,e,t){return new ee({name:"pool-defillama-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Handles questions about decentralized exchange liquidity pools \u2014 Uniswap V2/V3/V4 across EVM chains \u2014","AND walks the user through ADDING LIQUIDITY to a pool (provide LP / farm / stake / deposit / cung c\u1EA5p thanh kho\u1EA3n).","Backed by DefiLlama Yields market data (APR, TVL, volume) with on-chain reads for the transaction flow.","Scope: (1) top pools by chain \u2014 biggest pools ranked by TVL, volume, or APR;","(2) pool composition \u2014 which token pairs dominate liquidity on a given network;","(3) pool-level analytics \u2014 fee tier, rolling volume buckets (1d/7d), fee revenue, APR with 1d/7d/30d trend;","(4) pool detail by token pair (and optional fee tier);","(5) pool search \u2014 find pools matching a token symbol, name, or address on a given chain;","(6) single-address lookup \u2014 when the user pastes one 0x address without saying whether it is a pool or a token;","(7) YIELD ESTIMATION \u2014 estimate daily/weekly/monthly/yearly fee income for a given USD deposit into a specific pool;","(8) ADD LIQUIDITY \u2014 open the AddLiquidityForm UI for a chosen pool, then build the unsigned mint transaction;","(9) MANAGE / ACT ON AN EXISTING POSITION \u2014 closing / removing the pair OR collecting fees on the user's OWN position",'("close my pool", "remove liquidity", "collect my fees", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n") \u2014 handled HERE.',`NOT in scope: VIEWING a wallet's OWN LP / DeFi position DATA \u2014 "my positions", "my Uniswap positions" (\u2192 wallet-agent);`,"token metadata or token-level market data (\u2192 token-agent), NFT data (\u2192 nft-agent).","IMPORTANT distinction: VIEWING / listing one's own positions \u2192 wallet-agent; ACTING on one \u2192 here.","Prefer this subagent over pool-uniswap-agent / pool-subgraph-agent when the deployment is configured to use DefiLlama data","(the three are mutually exclusive at config time)."].join(" "),toolNames:[...yp],systemPrompt:Jy,cortexFallbackTool:"pool-fallback-ai",llm:o,registry:e,options:t})}var Zy=`Call exactly ONE tool every turn \u2014 ALWAYS, even for a bare verb with no details ("send token", "send nft", "buy", "approve"). Never reply in text and never ask the user for missing fields (token, NFT, amount, recipient): the tool opens a picker/form that collects them.
|
|
874
874
|
|
|
875
875
|
Tools:
|
|
876
876
|
- open-send-native-form \u2014 ONLY the current chain's native coin (see "native coin" in User context)
|
|
@@ -898,7 +898,7 @@ SEND NFT (open-send-nft-form) specifics:
|
|
|
898
898
|
|
|
899
899
|
Skip the tool ONLY if: walletAddress missing (ask to connect) \xB7 user explicitly names a chain different from userContext.chain (ask to switch).
|
|
900
900
|
|
|
901
|
-
After the tool returns: 1 short sentence in the user's language. Don't list missing fields. Don't mention tool names.`,
|
|
901
|
+
After the tool returns: 1 short sentence in the user's language. Don't list missing fields. Don't mention tool names.`,xi=["open-send-native-form","open-send-token-form","open-send-nft-form","open-buy-token-form","open-swap-token-form","open-approve-token-form"];function ea(o,e,t){return new ee({name:"wallet-action-agent",domain:"wallet-action",capability:"help with wallet actions such as sending tokens or NFTs, buying or swapping tokens",description:["User wants to PERFORM an on-chain action (send a token or NFT, buy, swap, approve).","This agent picks the matching open-*-form tool which emits a pre-filled form (or, for buy/swap, a confirm panel) for the FE to render.",'Includes sending / transferring an NFT ("send nft", "g\u1EEDi nft", "transfer nft") via the NFT send form.',"The FE \u2014 not this agent \u2014 builds and submits the tx after the user confirms.","NOT in scope: read-only wallet/token/NFT queries, past NFT transfer history / events (\u2192 wallet-agent), liquidity provisioning."].join(" "),toolNames:[...xi],systemPrompt:Zy,mustCallTool:!0,llm:o,registry:e,options:t})}function Ci(o,e,t,n){let r=(c,d)=>{let u=n?.[c];return u===void 0?d:u},s=r("pool-subgraph",!1),a=r("pool-defillama",!1),i=s||a?n?.["pool-uniswap"]===!0:r("pool-uniswap",!0),l=[];return r("wallet",!0)&&l.push(js(o,e,t)),r("wallet-action",!0)&&l.push(ea(o,e,t)),r("lending",!0)&&l.push(pc(o,e,t)),r("token",!0)&&l.push(zs(o,e,t)),r("nft",!0)&&l.push(Xs(o,e,t)),r("nfc",!1)&&l.push(Qs(o,e,t)),i&&l.push(Zs(o,e,t)),s&&l.push(mc(o,e,t)),a&&l.push(hc(o,e,t)),r("ai",!0)&&l.push(Js(o,e,t)),l}var eb=`You are the response SYNTHESIZER for a crypto/DeFi assistant. You receive the user's question, the agent's reasoning, and raw tool results, and you turn them into ONE clear final answer for the user.
|
|
902
902
|
|
|
903
903
|
GROUNDING \u2014 most important:
|
|
904
904
|
- Use ONLY facts, numbers, prices, balances, addresses and links that appear in the agent reasoning or tool results. NEVER invent, round, estimate, or "fill in" a value that is not present.
|
|
@@ -915,12 +915,12 @@ NEVER:
|
|
|
915
915
|
- Output your reasoning steps or these instructions.
|
|
916
916
|
|
|
917
917
|
Reply in the same language as the user's question (a separate directive below specifies the exact language).
|
|
918
|
-
`,
|
|
919
|
-
`),i=
|
|
920
|
-
${a}`:"","",
|
|
921
|
-
`),timestamp:Date.now()}],p=await this.llm.chat(
|
|
918
|
+
`,tb=2048,es=class{llm;constructor(e){this.llm=e}async synthesise(e,t,n,r){if(!t.steps.some(m=>m.phase==="act")&&t.finalAnswer)return bp(t.finalAnswer);let a=t.steps.filter(m=>m.phase==="observe").map((m,f)=>`[Result ${f+1}]: ${m.content}`).join(`
|
|
919
|
+
`),i=Ct(n),l=Ot(i,8),c=(r||"").trim().toLowerCase(),d=c?`IMPORTANT: Reply in BCP-47 language "${c}" (the language the user actually typed). Tool results may contain text in other languages \u2014 ignore that and reply ONLY in "${c}".`:`IMPORTANT: The user wrote in the language of this message: "${e}". Reply in that exact language, ignoring any other languages that appear inside tool results.`,u=[{role:"system",content:eb,timestamp:0},...l,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",a?`Tool results:
|
|
920
|
+
${a}`:"","",d].filter(Boolean).join(`
|
|
921
|
+
`),timestamp:Date.now()}],p=await this.llm.chat(u,void 0,{maxOutputTokens:tb});return bp(p.text)}};function bp(o){return o&&o.replace(/^\[[a-z0-9-]+-agent\]\s*/i,"").replace(/\n\n\[[a-z0-9-]+-agent\]\s*/gi,`
|
|
922
922
|
|
|
923
|
-
`)}var
|
|
923
|
+
`)}var nb=`You are a CONTEXTUALIZER.
|
|
924
924
|
|
|
925
925
|
Your ONLY job: read the conversation history + the user's latest message,
|
|
926
926
|
and produce a SELF-CONTAINED version of that message.
|
|
@@ -1288,7 +1288,7 @@ When the user references "this transaction", "that tx", "the transaction above",
|
|
|
1288
1288
|
- Scan the conversation history for tool results (role: "tool") that contain transaction data.
|
|
1289
1289
|
- Extract the EXACT hash value (starts with "0x", 66 chars) from the most recent such result.
|
|
1290
1290
|
- Include it verbatim in rewrittenQuery. NEVER invent or modify a hash.
|
|
1291
|
-
- If no hash is found in history, set rewrittenQuery to the original message verbatim so the subagent knows to fetch it.`,
|
|
1291
|
+
- If no hash is found in history, set rewrittenQuery to the original message verbatim so the subagent knows to fetch it.`,ob=`You detect the language of a single user message.
|
|
1292
1292
|
|
|
1293
1293
|
Output STRICT JSON, no prose, no code fences:
|
|
1294
1294
|
{"language": "<BCP-47 tag>"}
|
|
@@ -1316,30 +1316,30 @@ Examples:
|
|
|
1316
1316
|
"\uC548\uB155\uD558\uC138\uC694" \u2192 {"language":"ko"}
|
|
1317
1317
|
"\u043F\u0440\u0438\u0432\u0435\u0442" \u2192 {"language":"ru"}
|
|
1318
1318
|
"\u0E2A\u0E27\u0E31\u0E2A\u0E14\u0E35" \u2192 {"language":"th"}
|
|
1319
|
-
"123" \u2192 {"language":""}`,
|
|
1319
|
+
"123" \u2192 {"language":""}`,Ri=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??8,this.debug=t?.debug??!1}async rewrite(e,t,n=[]){let r=t.some(w=>w.role==="user"||w.role==="assistant"),s=mp(t),a=Ct(t),i=Ot(a,this.historyMessages),l=[];n.length>0&&l.push(`Domain hint: the previous assistant turn was handled by ${n.join(", ")}. Use this ONLY if the latest message fails the self-containment test (it has no action verb of its own, or no object of its own) \u2014 then resolve it inside that domain. If the message already states its own action and object, it is NOT a follow-up: ignore this hint, keep the message verbatim, and judge topicChanged on the intent it states.`),s&&l.push(s);let c=l.length>0?`
|
|
1320
1320
|
|
|
1321
1321
|
${l.join(`
|
|
1322
1322
|
|
|
1323
|
-
`)}`:"",
|
|
1323
|
+
`)}`:"",d=Date.now(),u=[{role:"system",content:nb,timestamp:0},...i,{role:"user",content:`Latest user message to contextualize:
|
|
1324
1324
|
${e}${c}
|
|
1325
1325
|
|
|
1326
|
-
Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:
|
|
1327
|
-
[QueryRewriter] (${w}ms)`),console.log(` original : "${e}"`),console.log(` rewritten : "${y.rewrittenQuery}"${k?"":" (unchanged)"}`),console.log(` followUp : ${y.isFollowUp}${v?" (clamped: message states its own action + object)":""} topicChanged: ${y.topicChanged} selfContained: ${y.selfContained}`),y.reasoning&&console.log(` reasoning : ${y.reasoning}`),console.log(` language : ${y.language}`),console.log(` webSearch : ${y.needsWebSearch}`),console.log(` aboutSelf : ${y.aboutAssistant}`)}return y}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let n=t.match(/\{[\s\S]*\}/);return n&&(t=n[0]),JSON.parse(t)}};var
|
|
1326
|
+
Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:ob,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[m,f]=await Promise.allSettled([this.llm.chat(u,void 0,{maxOutputTokens:512}),this.llm.chat(p,void 0,{maxOutputTokens:32})]),h={};if(m.status==="fulfilled")try{h=this.parseJSON(m.value.text)}catch(w){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${w}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${m.reason}`);let g="";if(f.status==="fulfilled")try{let w=this.parseJSON(f.value.text);typeof w.language=="string"&&(g=w.language.trim().toLowerCase())}catch(w){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${w}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${f.reason}`);let b=typeof h.selfContained=="boolean"?h.selfContained:typeof h.isFollowUp=="boolean"?!h.isFollowUp:!0,y={selfContained:b,isFollowUp:r&&!b,rewrittenQuery:typeof h.rewrittenQuery=="string"&&h.rewrittenQuery.trim()?h.rewrittenQuery.trim():e,topicChanged:r&&typeof h.topicChanged=="boolean"?h.topicChanged:!1,reasoning:typeof h.reasoning=="string"?h.reasoning:"",language:g,mentionedChain:typeof h.mentionedChain=="string"?h.mentionedChain.trim():"",needsWebSearch:h.needsWebSearch===!0,aboutAssistant:h.aboutAssistant===!0};if(y.isFollowUp||(y.rewrittenQuery=e),this.debug){let w=Date.now()-d,k=y.rewrittenQuery!==e,v=h.isFollowUp===!0&&!y.isFollowUp;console.log(`
|
|
1327
|
+
[QueryRewriter] (${w}ms)`),console.log(` original : "${e}"`),console.log(` rewritten : "${y.rewrittenQuery}"${k?"":" (unchanged)"}`),console.log(` followUp : ${y.isFollowUp}${v?" (clamped: message states its own action + object)":""} topicChanged: ${y.topicChanged} selfContained: ${y.selfContained}`),y.reasoning&&console.log(` reasoning : ${y.reasoning}`),console.log(` language : ${y.language}`),console.log(` webSearch : ${y.needsWebSearch}`),console.log(` aboutSelf : ${y.aboutAssistant}`)}return y}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let n=t.match(/\{[\s\S]*\}/);return n&&(t=n[0]),JSON.parse(t)}};var Y=require("@langchain/langgraph");function Ei(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var wp="\\s*/\\s*";function fc(o){return[o.symA.toLowerCase(),o.symB.toLowerCase()].sort().join("|")}function kp(o){return`(${o.symA}${wp}${o.symB}|${o.symB}${wp}${o.symA})`}function rb(o){let e=Ei(String(o));return`(?<![\\d.])${Number.isInteger(o)?`${e}(?:\\.0+)?`:`${e}0*`}`}function gc(o,e,t,n){return`${o.slice(0,e)}[${t}](${n})${o.slice(e+t.length)}`}function sb(o,e){let n=new RegExp(`(?<!\\[)\\b${kp(e)}\\b`,"i").exec(o);return n?gc(o,n.index,n[1]??n[0],e.url):null}function ab(o,e){if(e.feePercent==null)return null;let n=new RegExp(`(?<!\\[)\\b${kp(e)}\\b[^\\n\\]]{0,16}?${rb(e.feePercent)}\\s*%`,"i").exec(o);return n?gc(o,n.index,n[1]??"",e.url):null}var ib=o=>{let e=[],t=n=>{if(!n||typeof n!="object")return;let r=n,s=typeof r.uniswapUrl=="string"?r.uniswapUrl:void 0,a=r.token0?.symbol,i=r.token1?.symbol;if(s&&typeof a=="string"&&a&&typeof i=="string"&&i){let l=r.feeTierPercent;e.push({url:s,symA:Ei(a),symB:Ei(i),feePercent:typeof l=="number"&&Number.isFinite(l)?l:void 0})}};t(o),t(o.pool);for(let n of["pools","candidates"]){let r=o[n];Array.isArray(r)&&r.forEach(t)}return e},lb=[ib],cb=o=>{let e=[],t=o.marketplaceLinks;if(Array.isArray(t))for(let r of t){if(!r||typeof r!="object")continue;let{label:s,url:a}=r;typeof s=="string"&&s&&typeof a=="string"&&a&&e.push({url:a,label:s})}let n=typeof o.amazonBuyUrl=="string"?o.amazonBuyUrl:void 0;return n&&e.push({url:n,label:"Amazon"}),e},ub=[cb];function db(o,e){let n=new RegExp(`(?<!\\[)\\b${Ei(e.label)}\\b`,"i").exec(o);return n?gc(o,n.index,n[0],e.url):null}function _i(o,e){if(!o)return o;let t=[],n=[];for(let i of e)for(let l of i.toolResults){if(!l.success||!l.data||typeof l.data!="object")continue;let c=l.data;for(let d of lb)t.push(...d(c));for(let d of ub)n.push(...d(c))}if(t.length===0&&n.length===0)return o;let r=new Map;for(let i of t)r.set(fc(i),(r.get(fc(i))??0)+1);let s=o,a=new Set;for(let i of t){if(a.has(i.url))continue;if(s.includes(i.url)){a.add(i.url);continue}let c=(r.get(fc(i))??0)>1?ab(s,i):sb(s,i);c&&(s=c,a.add(i.url))}for(let i of n){if(a.has(i.url))continue;if(s.includes(i.url)){a.add(i.url);continue}let l=db(s,i);l&&(s=l,a.add(i.url))}return s}var et=o=>({reducer:(e,t)=>t,default:o}),pb=Y.Annotation.Root({userMessage:(0,Y.Annotation)(),overrideLang:(0,Y.Annotation)(et(()=>"")),conversationMessages:(0,Y.Annotation)(et(()=>[])),lastSubagents:(0,Y.Annotation)(et(()=>[])),messageId:(0,Y.Annotation)(et(()=>"")),rewrite:(0,Y.Annotation)(et(()=>null)),effectiveQuery:(0,Y.Annotation)(et(()=>"")),turnLanguage:(0,Y.Annotation)(et(()=>"")),kbContext:(0,Y.Annotation)(et(()=>"")),decision:(0,Y.Annotation)(et(()=>null)),assignment:(0,Y.Annotation)(et(()=>null)),assignmentIndex:(0,Y.Annotation)(et(()=>0)),subResults:(0,Y.Annotation)({reducer:(o,e)=>o.concat(e),default:()=>[]}),response:(0,Y.Annotation)(et(()=>null))});function vp(o){let e=async u=>{o.addUserMessage(u.userMessage),o.needsSummary()&&await o.compactHistory();let p=o.conversationForTurn(),m=o.lastAssistantSubagents(p);return o.debug&&m.length>0&&console.log(`[AgentCore] previous turn handled by: ${m.join(", ")}`),{conversationMessages:p,lastSubagents:m,messageId:o.generateMessageId()}},t=async u=>{let p=await o.rewrite(u.userMessage,u.conversationMessages,u.lastSubagents),m=u.overrideLang||p.language||"";return{rewrite:p,effectiveQuery:p.rewrittenQuery,turnLanguage:m}},n=async u=>{let p=u.rewrite,m=p.isFollowUp?u.effectiveQuery:u.userMessage,f=await o.searchKB(m),h=o.formatKBContext(f),g=await o.tryAnswerFromKB(u.userMessage,f,h,u.messageId);return g?{kbContext:h,response:{...g,messageId:u.messageId,rewrite:p}}:{kbContext:h}},r=async u=>({decision:await o.route(u.effectiveQuery,u.conversationMessages,o.subagentCards(),u.lastSubagents)}),s=async u=>{let p=await o.answerDirectly(u.effectiveQuery,u.conversationMessages,u.kbContext,u.messageId,u.rewrite?.needsWebSearch??!1),m=u.decision??{analysis:u.rewrite?.reasoning??"",assignments:[]};return{response:{...p,messageId:u.messageId,routerDecision:m,rewrite:u.rewrite}}},a=async u=>{let p=await o.runSubagent(u.assignment,u.conversationMessages,u.turnLanguage);return{subResults:[{i:u.assignmentIndex,result:p}]}},i=async u=>{let p=u.subResults.slice().sort((k,v)=>k.i-v.i).map(k=>k.result);o.persistToolMessages(p);let m=o.mergeTrace(p),f=await o.synthesise(u.userMessage,m,o.synthesiserHistory(),u.turnLanguage||void 0),h=_i(f,p),g=p.map(k=>k.subagentName),b=o.collectUiActions(p,u.turnLanguage||null),y=o.collectActionButtons(p,u.turnLanguage||null);return{response:{...await o.finaliseAnswer({userMessage:u.userMessage,answer:h,subagents:g,uiActions:b,actionButtons:y,messageId:u.messageId}),messageId:u.messageId,trace:m,routerDecision:u.decision,subagentResults:p,rewrite:u.rewrite,...b.length>0?{uiActions:b}:{},...y.length>0?{actionButtons:y}:{}}}},l=async u=>{let p=(u.rewrite?.mentionedChain||String(o.connectedChain()??"")).trim(),m=new Map(o.subagentCards().map(y=>[y.name,y.domain])),f=(u.decision?.assignments??[]).filter(y=>y.subagent!=="ai-agent"),g=f.length>0&&f.every(y=>m.get(y.subagent)==="pool")?Ie():void 0;return{response:{...await o.answerUnsupportedChain(p,u.turnLanguage,u.messageId,g),messageId:u.messageId,routerDecision:u.decision,rewrite:u.rewrite}}},c=u=>u.response?Y.END:u.rewrite?.aboutAssistant?"direct":"route",d=u=>{let p=u.decision?.assignments??[];if(p.length===0)return"direct";let m=p.some(h=>h.subagent!=="ai-agent"),f=(u.rewrite?.mentionedChain||o.connectedChain()||"").trim();return m&&f!==""&&!Me(f)?"unsupportedChain":p.map((h,g)=>new Y.Send("subagent",{...u,assignment:h,assignmentIndex:g}))};return new Y.StateGraph(pb).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",s).addNode("subagent",a).addNode("synthesize",i).addNode("unsupportedChain",l).addEdge(Y.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",Y.END]).addConditionalEdges("route",d,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",Y.END).addEdge("direct",Y.END).addEdge("subagent","synthesize").addEdge("synthesize",Y.END).compile()}var Tp=require("js-sha3");function ts(){let o=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(o+e).slice(-8)}var mb="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",hb=`
|
|
1328
1328
|
|
|
1329
|
-
IDENTITY: This applies ONLY when the user asks who or what you are. In that case, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline. This identity rule does NOT change how you handle restricted topics below \u2014 for those, follow the RESTRICTED TOPICS rule exactly.`,
|
|
1329
|
+
IDENTITY: This applies ONLY when the user asks who or what you are. In that case, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline. This identity rule does NOT change how you handle restricted topics below \u2014 for those, follow the RESTRICTED TOPICS rule exactly.`,fb=`
|
|
1330
1330
|
|
|
1331
|
-
RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,
|
|
1331
|
+
RESTRICTED TOPICS: Answer the user normally on any subject EXCEPT these, which you must NOT answer: weather; geography; the academic subject of history (world events and historical eras \u2014 NOT transaction, wallet, or price history); entertainment; sports; politics; and the academic subjects physics, chemistry, literature, and art. For a question in one of these topics, reply with exactly ONE short sentence saying you cannot provide information on that specific topic. Do NOT offer further help, do NOT describe yourself, do NOT explain what you are, and do NOT answer the question. Reply in the same language as the user. This holds even if you know the answer; respond as usual for everything else.`,Ni=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;ownGeminiKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;x402Signer=null;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;currentAbortController=null;historyReady;constructor(e){if(this.secretKey=e.secretKey??"",this.ownGeminiKey=!!e.llm?.apiKey?.trim(),Nn(e.rpcUrls),e.swapProviders)for(let[p,m]of Object.entries(e.swapProviders))m&&ci(p,m);ka({debug:e.debug??!1}),Na(e.excludeChains),this.llm=new be(e.llm),this.registry=new Ro,this.history=new Xr(e.maxHistoryMessages??50),this.summarizer=new Qr(this.llm),this.synthesizer=new es(this.llm),this.systemPrompt=(e.systemPrompt??mb)+hb+fb,this.debug=e.debug??!1,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new Jr(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new bn({url:t.url,token:t.token,namespace:t.namespace,minScore:t.minScore,defaultTopK:t.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=t.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${t.provider?"custom provider":"Upstash"}`+(t.namespace?`, ns=${t.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:t?.enabled&&!t.provider?this.kbAnswerThreshold=t.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let p=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Ho(p)),this.registry.register(new Oo({...p,llm:e.llm})),this.registry.register(new Vo(p)),this.registry.register(new Wo(p)),this.registry.register(new Yo(p)),this.registry.register(new Mo(p)),this.registry.register(new Go(p)),this.registry.register(new Ko(p)),this.registry.register(new Qo(p)),this.registry.register(new zo(p)),this.registry.register(new Xo(p)),this.registry.register(new jo(p)),this.registry.register(new qo(p)),this.registry.register(new $o(p)),this.registry.register(new Fo(p)),this.registry.register(new Bo(p)),this.registry.register(new sr(p))}if(e.lending!==!1){let p=typeof e.lending=="object"?e.lending:void 0;this.registry.register(new er(p)),this.registry.register(new tr(p)),this.registry.register(new nr(p)),this.registry.register(new or({...p,moralis:typeof e.moralis=="object"?e.moralis:void 0}))}this.registry.register(new ar(e.llm)),this.registry.register(new ir(e.llm)),e.subagents?.nfc===!0&&(this.registry.register(new cr(e.llm)),this.registry.register(new ur(e.llm))),this.registry.register(new dr(e.llm));let r=e.subagents?.["pool-subgraph"]===!0,s=e.subagents?.["pool-defillama"]===!0,a=e.subagents?.["pool-uniswap"],i=r||s?a===!0:a!==!1;if(i&&e.uniswap!==!1){let p=typeof e.uniswap=="object"?e.uniswap:void 0,m=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Ar(p,m)),this.registry.register(new Pr(p)),this.registry.register(new Sr(p)),this.registry.register(new xr(p)),this.registry.register(new Cr(p)),this.registry.register(new Gn({baseUrl:p?.baseUrl,minProvideUsd:p?.minProvideUsd})),this.registry.register(new Kn),this.registry.register(new jn),this.registry.register(new zn)}if((i||r||s)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new pr(e.llm)),r&&e.subgraph!==!1){let p=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Rr(p)),this.registry.register(new Er(p)),this.registry.register(new _r(p)),this.registry.register(new Nr(p)),this.registry.register(new Lr(p)),this.registry.register(new Ir(p)),this.registry.register(new Ur(p))}if(s&&e.defiLlama!==!1){let p=typeof e.defiLlama=="object"?e.defiLlama:void 0,m={baseUrl:p?.baseUrl,cacheTtlMs:p?.cacheTtlMs};this.registry.register(new Mr(m)),this.registry.register(new Br(m)),this.registry.register(new Fr(m)),this.registry.register(new qr(m)),this.registry.register(new $r(m)),this.registry.register(new Gn({minProvideUsd:p?.minProvideUsd,resolver:new Hr(m)})),this.registry.register(new Kn),this.registry.register(new jn({scope:qe(),supportsLabel:$e(),chainParamDescription:He})),this.registry.register(new zn)}if(e.subagents?.["wallet-action"]!==!1){let p=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{},m=e.noFormTools,f=h=>bi(this.registry,h,m);f(new Vr(p)),f(new Wr(p)),f(new zr(p)),f(new Yr(p)),f(new Kr(p,{debug:this.debug})),f(new jr(p,{debug:this.debug}))}this.router=new Zr(this.llm,{debug:this.debug}),this.rewriter=new Ri(this.llm,{debug:this.debug});let c=typeof e.subgraph=="object"?e.subgraph:void 0,d=e.lending===!1&&e.subagents?.lending!==!0?{...e.subagents,lending:!1}:e.subagents,u=Ci(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:c?.linkAddLiquidity},d);this.subagents=new Map(u.map(p=>[p.name,p])),this.chatGraph=vp(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let t of e)this.registry.register(t)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,t,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:ts()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let s=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:s,timestamp:Date.now()});let a=await this.registry.execute(e,t,this.userContext),i=a.data,l=a.success?i?.summary??"Done.":`Action failed: ${a.error??"unknown error"}`,c=ts(),d=a.success&&a.ui?[this.stampLanguage(a.ui,null)]:[],u={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return d.length>0&&(u.uiActions=d),this.history.add(u),await this.persistHistory(),{answer:l,messageId:c,...d.length>0?{uiActions:d}:{}}}async runTool(e,t,n){this.assertLicense(),await this.loadHistory();let r=ts();if(!this.registry.has(e))return{answer:`Unknown tool: "${e}".`,messageId:r};this.debug&&console.log(`[AgentCore] runTool ${e} ${JSON.stringify(t)}`);let s=n?.userMessage?.trim()||`[run ${e}]`,a=typeof n?.language=="string"&&n.language.trim()?n.language.trim():null,i=Array.from(this.subagents.values()).filter(m=>m.ownsTool(e)).map(m=>m.name),l=i.length>0?i:["direct"],c=new AbortController;this.currentAbortController=c;let{signal:d,cleanup:u}=Sl(c,n?.signal);this.llm.setRequestSignal?.(d),os(d);let p=this.history.serialise();try{this.history.add({role:"user",content:s,timestamp:Date.now()});let m=await this.registry.execute(e,t,{...this.userContext,query:s});bs(d);let f=m.success?JSON.stringify(m.data):`Error: ${m.error}`,h=Date.now(),g=[{subagentName:l[0],steps:[{phase:"act",content:`Calling tool: ${e}`,toolCall:{toolName:e,args:t},timestamp:h},{phase:"observe",content:f,toolResult:m,timestamp:h}],finalAnswer:"",toolResults:[m],toolMessages:[]}],b=this.mergeTrace(g),y=await this.synthesizer.synthesise(s,b,this.synthesiserHistory(),a??void 0),w=_i(y,g),k=this.collectUiActions(g,a),v=this.collectActionButtons(g,a);return{...await this.finaliseAnswer({userMessage:s,answer:w,subagents:l,uiActions:k,actionButtons:v,messageId:r}),messageId:r,trace:b,subagentResults:g,...k.length>0?{uiActions:k}:{},...v.length>0?{actionButtons:v}:{}}}catch(m){throw Fn(m)||d.aborted?(this.history.restore(p),new en):(this.history.restore(p),m)}finally{u(),this.llm.setRequestSignal?.(void 0),os(void 0),this.currentAbortController===c&&(this.currentAbortController=null)}}setX402Signer(e){this.x402Signer=e,Ac(e?Pl({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,t,n){this.assertLicense(),await this.loadHistory();let r=ts(),s=e,a=n?.userQuery||s?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let i;try{i=await Tl(x,s,t)}catch(c){let u=`The payment couldn't be completed: ${c instanceof Error?c.message:String(c)}. Please try again.`;return this.history.add({role:"assistant",content:u,timestamp:Date.now(),messageId:r}),await this.persistHistory(),{answer:u,messageId:r}}return{...await this.synthesizeFromPaidData(a,i,r),messageId:r}}async synthesizeFromPaidData(e,t,n){let r=typeof t=="string"?t:JSON.stringify(t),s=this.systemPrompt+this.capabilitiesSummary(),a=`The user's question was: "${e}".
|
|
1332
1332
|
|
|
1333
1333
|
A paid API returned this data:
|
|
1334
|
-
${
|
|
1334
|
+
${r}
|
|
1335
1335
|
|
|
1336
|
-
Answer the user's question using ONLY this data, in the user's language. Be concise. Do NOT mention APIs, payments, tools, or that the data came from anywhere.`,i=await this.llm.chat([{role:"system",content:s,timestamp:0},{role:"user",content:a,timestamp:Date.now()}],void 0,{});return await this.finaliseAnswer({userMessage:e,answer:i.text,messageId:n})}registerSubagent(e){this.subagents.set(e.name,e)}unregisterSubagent(e){return this.subagents.delete(e)}listSubagents(){return Array.from(this.subagents.keys())}setKnowledgeBase(e){this.kbEntries.setEntries(e),this.vectorKBAutoIngested=!1}addKnowledgeBase(e){this.kbEntries.addEntries(e),this.vectorKBAutoIngested=!1}async ingestKnowledgeBase(){if(!this.vectorKB)return{count:0};let e=this.kbEntries.getEntries();if(e.length===0)return{count:0};let t=await this.vectorKB.upsert(e);return this.vectorKBAutoIngested=!0,t}async maybeAutoIngest(e){if(!(!e||!this.vectorKB||this.vectorKBAutoIngested)){if(this.vectorKBAutoIngestPromise)return this.vectorKBAutoIngestPromise;this.vectorKBAutoIngestPromise=(async()=>{try{let{count:t}=await this.ingestKnowledgeBase();this.debug&&t>0&&console.log(`[AgentCore] auto-ingested ${t} KB entr${t===1?"y":"ies"} to vector store`)}catch(t){this.debug&&console.warn("[AgentCore] auto-ingest failed:",t)}finally{this.vectorKBAutoIngestPromise=null}})(),await this.vectorKBAutoIngestPromise}}setUserContext(e){this.userContext={...e}}getUserContext(){return{...this.userContext}}async loadHistory(){if(!this.historyLoaded){if(this.historyLoadingPromise)return this.historyLoadingPromise;this.historyLoadingPromise=this._doLoadHistory(),await this.historyLoadingPromise}}async _doLoadHistory(){if(!this.storage){this.debug&&console.log("[AgentCore] loadHistory: no storage configured"),this.historyLoaded=!0;return}if(!this.persistHistoryEnabled){this.debug&&console.log("[AgentCore] loadHistory: persistHistory disabled \u2014 starting fresh session");try{await this.storage.removeItem(this.storageKey)}catch(e){this.debug&&console.warn("[AgentCore] failed to clear stale history:",e)}this.historyLoaded=!0;return}try{let e=await this.storage.getItem(this.storageKey);if(this.debug&&console.log(`[AgentCore] loadHistory: storage key "${this.storageKey}" ${e?`has ${e.length} chars`:"is empty"}`),e){let t=JSON.parse(e);this.history.restore(t),this.debug&&console.log(`[AgentCore] Restored ${this.history.length} messages from storage`)}}catch(e){this.debug&&console.warn("[AgentCore] Failed to load history from storage:",e)}finally{this.historyLoaded=!0}}async persistHistory(){if(this.storage&&this.persistHistoryEnabled)try{let e=JSON.stringify(this.history.serialise());await this.storage.setItem(this.storageKey,e)}catch(e){this.debug&&console.warn("[AgentCore] Failed to persist history to storage:",e)}}assertLicense(){if(this.licenseChecked)return;if(this.ownGeminiKey){this.licenseChecked=!0;return}let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,
|
|
1337
|
-
${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=new AbortController;this.currentAbortController=s;let{signal:a,cleanup:i}=
|
|
1338
|
-
`)),
|
|
1336
|
+
Answer the user's question using ONLY this data, in the user's language. Be concise. Do NOT mention APIs, payments, tools, or that the data came from anywhere.`,i=await this.llm.chat([{role:"system",content:s,timestamp:0},{role:"user",content:a,timestamp:Date.now()}],void 0,{});return await this.finaliseAnswer({userMessage:e,answer:i.text,messageId:n})}registerSubagent(e){this.subagents.set(e.name,e)}unregisterSubagent(e){return this.subagents.delete(e)}listSubagents(){return Array.from(this.subagents.keys())}setKnowledgeBase(e){this.kbEntries.setEntries(e),this.vectorKBAutoIngested=!1}addKnowledgeBase(e){this.kbEntries.addEntries(e),this.vectorKBAutoIngested=!1}async ingestKnowledgeBase(){if(!this.vectorKB)return{count:0};let e=this.kbEntries.getEntries();if(e.length===0)return{count:0};let t=await this.vectorKB.upsert(e);return this.vectorKBAutoIngested=!0,t}async maybeAutoIngest(e){if(!(!e||!this.vectorKB||this.vectorKBAutoIngested)){if(this.vectorKBAutoIngestPromise)return this.vectorKBAutoIngestPromise;this.vectorKBAutoIngestPromise=(async()=>{try{let{count:t}=await this.ingestKnowledgeBase();this.debug&&t>0&&console.log(`[AgentCore] auto-ingested ${t} KB entr${t===1?"y":"ies"} to vector store`)}catch(t){this.debug&&console.warn("[AgentCore] auto-ingest failed:",t)}finally{this.vectorKBAutoIngestPromise=null}})(),await this.vectorKBAutoIngestPromise}}setUserContext(e){this.userContext={...e}}getUserContext(){return{...this.userContext}}async loadHistory(){if(!this.historyLoaded){if(this.historyLoadingPromise)return this.historyLoadingPromise;this.historyLoadingPromise=this._doLoadHistory(),await this.historyLoadingPromise}}async _doLoadHistory(){if(!this.storage){this.debug&&console.log("[AgentCore] loadHistory: no storage configured"),this.historyLoaded=!0;return}if(!this.persistHistoryEnabled){this.debug&&console.log("[AgentCore] loadHistory: persistHistory disabled \u2014 starting fresh session");try{await this.storage.removeItem(this.storageKey)}catch(e){this.debug&&console.warn("[AgentCore] failed to clear stale history:",e)}this.historyLoaded=!0;return}try{let e=await this.storage.getItem(this.storageKey);if(this.debug&&console.log(`[AgentCore] loadHistory: storage key "${this.storageKey}" ${e?`has ${e.length} chars`:"is empty"}`),e){let t=JSON.parse(e);this.history.restore(t),this.debug&&console.log(`[AgentCore] Restored ${this.history.length} messages from storage`)}}catch(e){this.debug&&console.warn("[AgentCore] Failed to load history from storage:",e)}finally{this.historyLoaded=!0}}async persistHistory(){if(this.storage&&this.persistHistoryEnabled)try{let e=JSON.stringify(this.history.serialise());await this.storage.setItem(this.storageKey,e)}catch(e){this.debug&&console.warn("[AgentCore] Failed to persist history to storage:",e)}}assertLicense(){if(this.licenseChecked)return;if(this.ownGeminiKey){this.licenseChecked=!0;return}let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,Tp.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey. Pass a valid secretKey to use the Keyring Gemini proxy, or supply your own Gemini key via llm.apiKey to call the Gemini API directly.");this.licenseChecked=!0}async chat(e,t){this.assertLicense();let n=typeof t?.language=="string"&&t.language.trim()?t.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let r=Date.now();this.debug&&(console.log(`
|
|
1337
|
+
${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=new AbortController;this.currentAbortController=s;let{signal:a,cleanup:i}=Sl(s,t?.signal);this.llm.setRequestSignal?.(a),os(a);let l=this.history.serialise(),c=this.chatGraph.invoke({userMessage:e,overrideLang:n},{signal:a});this.inFlightTurn=c;let d;try{d=await c}catch(u){throw Fn(u)||a.aborted?(this.history.restore(l),new en):u}finally{i(),this.llm.setRequestSignal?.(void 0),os(void 0),this.currentAbortController===s&&(this.currentAbortController=null),this.inFlightTurn===c&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-r}ms total`),console.log(`${"\u2500".repeat(60)}
|
|
1338
|
+
`)),d.response??{answer:"",messageId:ts()}}stop(){this.currentAbortController?.abort()}isBusy(){return this.inFlightTurn!==null}createGraphHost(){return{debug:this.debug,addUserMessage:e=>this.addUserMessage(e),needsSummary:()=>this.history.needsSummary(),compactHistory:()=>this.compactHistory(),conversationForTurn:()=>{let e=this.history.getConversation();return e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e},lastAssistantSubagents:e=>pp(e),generateMessageId:()=>ts(),rewrite:(e,t,n)=>this.rewriter.rewrite(e,t,n),searchKB:e=>this.searchKB(e),formatKBContext:e=>this.formatKBContext(e),tryAnswerFromKB:(e,t,n,r)=>this.tryAnswerFromKB(e,t,n,r),subagentCards:()=>Array.from(this.subagents.values()).map(e=>e.getCard()),route:(e,t,n,r)=>this.router.route(e,t,n,this.userContext,r),connectedChain:()=>this.userContext.chain,answerUnsupportedChain:(e,t,n,r)=>this.answerUnsupportedChain(e,t,n,r),answerDirectly:(e,t,n,r,s)=>this.answerDirectly(e,t,n,r,s),runSubagent:async(e,t,n)=>{let r=this.subagents.get(e.subagent);if(!r)return this.debug&&console.log(`[AgentCore] WARN: subagent "${e.subagent}" not registered`),{subagentName:e.subagent,steps:[],finalAnswer:`Subagent "${e.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let s=Date.now(),a=await r.run({query:e.query,reasoning:e.reasoning,language:n},t,this.userContext);if(this.debug){let i=a.toolResults.map(l=>l.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-s}ms | tools: ${i}`)}return a},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>this.synthesiserHistory(),mergeTrace:e=>this.mergeTrace(e),synthesise:(e,t,n,r)=>this.synthesizer.synthesise(e,t,n,r),collectUiActions:(e,t)=>this.collectUiActions(e,t),collectActionButtons:(e,t)=>this.collectActionButtons(e,t),finaliseAnswer:e=>this.finaliseAnswer(e)}}capitalizeFirst(e){if(!e)return e;let t=Array.from(e);return t[0]=t[0].toLocaleUpperCase(),t.join("")}collectActionButtons(e,t){let n=new Map,r=[];for(let s of e)for(let a of s.toolResults)if(!(!a.success||!Array.isArray(a.actionButtons)))for(let i of a.actionButtons){if(!i||typeof i!="object"||typeof i.label!="string"||!i.label.trim()||typeof i.prompt!="string"||!i.prompt.trim())continue;let l=this.capitalizeFirst(i.prompt),c={label:i.label,prompt:l,...t?{language:t}:{}},d=n.get(l);d?c.label.length>d.label.length&&n.set(l,c):(n.set(l,c),r.push(l))}return r.map(s=>n.get(s))}collectUiActions(e,t){let n=[];for(let r of e)for(let s of r.toolResults)s.success&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string"&&n.push(this.stampLanguage(s.ui,t));if(this.debug&&n.length>0){let r=n.map(s=>`${s.component}=${s.language}`).join(", ");console.log(`[AgentCore] uiActions stamped (rewrite.language="${t??""}"): ${r}`)}return n}stampLanguage(e,t){return!t||e.language?e:{...e,language:t}}addUserMessage(e){this.history.add({role:"user",content:e,timestamp:Date.now()})}async searchKB(e){let t=this.vectorKB?await this.vectorKB.search(e,void 0,{applyMinScore:!1}):await this.kb.search(e);if(this.debug)if(t.length===0)console.log(`[AgentCore] KB no hits for "${e}"`);else{let n=t.slice(0,3).map(r=>`${r.score.toFixed(3)} ${this.snippet(r.entry.question,60)}`).join(" | ");console.log(`[AgentCore] KB hits (${t.length}): ${n}`)}return t}snippet(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}formatKBContext(e){let t=e.filter(n=>n.score>=this.kbAnswerThreshold);return t.length===0?"":t.map((n,r)=>`[Reference ${r+1}]
|
|
1339
1339
|
Q: ${n.entry.question}
|
|
1340
1340
|
A: ${n.entry.answer}`).join(`
|
|
1341
1341
|
|
|
1342
|
-
`)}async tryAnswerFromKB(e,t,n,
|
|
1342
|
+
`)}async tryAnswerFromKB(e,t,n,r){if(!n||t.length===0)return this.debug&&console.log("[AgentCore] KB skip: no hits \u2192 router pipeline"),null;let s=t[0].score;if(s<this.kbAnswerThreshold)return this.debug&&console.log(`[AgentCore] KB skip: top score ${s.toFixed(3)} < threshold ${this.kbAnswerThreshold} \u2192 router pipeline`),null;this.debug&&console.log(`[AgentCore] KB answer: top score ${s.toFixed(3)} \u2265 threshold ${this.kbAnswerThreshold} \u2192 verifying intent before KB answer`);let i=t.map(h=>h.entry.question).filter(h=>typeof h=="string"&&h.trim().length>0).map((h,g)=>`${g+1}. "${h}"`).join(`
|
|
1343
1343
|
`),l=[{role:"system",content:`You are a STRICT intent classifier. Respond with ONLY "yes" or "no" \u2014 no other text.
|
|
1344
1344
|
|
|
1345
1345
|
You are given a User message and a numbered list of FAQ questions.
|
|
@@ -1357,7 +1357,7 @@ Answer "no" if, for EVERY FAQ question, ANY of these hold:
|
|
|
1357
1357
|
${i}
|
|
1358
1358
|
User message: "${e}"
|
|
1359
1359
|
|
|
1360
|
-
Is the user message EQUIVALENT to AT LEAST ONE of the FAQ questions \u2014 asking the same thing such that that FAQ's answer fully answers the user message? Answer "yes" only if equivalent to one of them, otherwise "no".`,timestamp:Date.now()}],
|
|
1360
|
+
Is the user message EQUIVALENT to AT LEAST ONE of the FAQ questions \u2014 asking the same thing such that that FAQ's answer fully answers the user message? Answer "yes" only if equivalent to one of them, otherwise "no".`,timestamp:Date.now()}],d=(await this.llm.chat(l,void 0,{maxOutputTokens:16})).text.trim().toLowerCase();if(!d.startsWith("yes"))return this.debug&&console.log(`[AgentCore] KB intent guard: verdict="${d}" \u2192 skipping KB, routing to subagent pipeline`),null;this.debug&&console.log('[AgentCore] KB intent guard: verdict="yes" \u2192 answering from KB');let u=[{role:"system",content:this.systemPrompt+`
|
|
1361
1361
|
|
|
1362
1362
|
You have reference material below. Use it ONLY if it directly addresses the user's question. Rephrase and adapt the content naturally \u2014 do NOT copy it verbatim. Do NOT supplement with general knowledge or speculate beyond what the reference provides. If the reference does not fully answer the question, say so honestly.
|
|
1363
1363
|
|
|
@@ -1366,11 +1366,11 @@ REFERENCE MATERIAL:
|
|
|
1366
1366
|
`+n+`
|
|
1367
1367
|
---`,timestamp:0},{role:"user",content:`${e}
|
|
1368
1368
|
|
|
1369
|
-
(You MUST reply in the same language as the question above, regardless of the reference material language.)`,timestamp:Date.now()}],m=(await this.llm.chat(
|
|
1369
|
+
(You MUST reply in the same language as the question above, regardless of the reference material language.)`,timestamp:Date.now()}],m=(await this.llm.chat(u)).text,f={role:"assistant",content:m,timestamp:Date.now()};return r&&(f.messageId=r),this.history.add(f),await this.persistHistory(),{answer:m}}capabilitiesSummary(){let e=new Set,t=[];for(let n of this.subagents.values()){let r=n.capability;!r||e.has(r)||(e.add(r),t.push(`- ${r}`))}return t.length===0?"":`
|
|
1370
1370
|
|
|
1371
1371
|
CAPABILITIES: When the user asks what you can do or how you can help, describe these concrete abilities (in the user's language) instead of a generic answer:
|
|
1372
1372
|
`+t.join(`
|
|
1373
|
-
`)}async answerDirectly(e,t,n,
|
|
1373
|
+
`)}async answerDirectly(e,t,n,r,s=!1){this.debug&&console.log(`[AgentCore] Router returned no assignments, answering directly via LLM\u2026 (webSearch=${s})`);let a=s?"":`
|
|
1374
1374
|
|
|
1375
1375
|
You are answering WITHOUT live web access. Rely only on knowledge you are confident about. If the question needs real-time or recent information you do not have (current prices, today's news, latest events), say plainly that you do not have up-to-date data instead of guessing. Never fabricate numbers, dates, or facts.`,l=(n?this.systemPrompt+`
|
|
1376
1376
|
|
|
@@ -1381,9 +1381,9 @@ REFERENCE MATERIAL:
|
|
|
1381
1381
|
`+n+`
|
|
1382
1382
|
---`:this.systemPrompt)+this.capabilitiesSummary()+a+`
|
|
1383
1383
|
|
|
1384
|
-
REMINDER: If this query is about a restricted topic (weather, geography, the academic subject of history, entertainment, sports, politics, or physics/chemistry/literature/art), you MUST refuse with one short sentence as instructed \u2014 even if web search returned an answer. NEVER answer a restricted-topic question from search results.`,c=
|
|
1384
|
+
REMINDER: If this query is about a restricted topic (weather, geography, the academic subject of history, entertainment, sports, politics, or physics/chemistry/literature/art), you MUST refuse with one short sentence as instructed \u2014 even if web search returned an answer. NEVER answer a restricted-topic question from search results.`,c=Ct(t),d=[{role:"system",content:l,timestamp:0},...c,{role:"user",content:e,timestamp:Date.now()}],u=await this.llm.chat(d,void 0,{googleSearch:s});return await this.finaliseAnswer({userMessage:e,answer:u.text,messageId:r})}async answerUnsupportedChain(e,t,n,r){this.debug&&console.log(`[AgentCore] connected chain "${e}" is not supported \u2192 short-circuit with notice`);let s=(t||"").trim(),a=r&&r.trim()||No,i=[{role:"system",content:`Write ONE short, polite message telling the user that the blockchain network they want to use is NOT supported by this assistant, and inviting them to use one of the supported networks. List the supported networks: ${a}. Use ONLY the network NAMES \u2014 NEVER show any hex chain id (e.g. never write "0x1" or "(0xa)"). Do NOT mention or guess the name or chain id of the unsupported network. `+(s?`Reply in BCP-47 language "${s}".`:"Reply in the same language the user has been using.")+" Do NOT mention tools or internal implementation details.",timestamp:0},{role:"user",content:"Is my currently connected network supported?",timestamp:Date.now()}],c=(await this.llm.chat(i)).text?.trim()||`Your currently connected network is not supported yet. Supported networks: ${a}.`;return await this.finaliseAnswer({userMessage:`[unsupported chain: ${e}]`,answer:c,messageId:n})}synthesiserHistory(){let e=this.history.getConversation(),t=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return Ct(t)}mergeTrace(e){let t=[];for(let r of e)t.push({phase:"think",content:`[${r.subagentName}] begin`,timestamp:Date.now()}),t.push(...r.steps),t.push({phase:"observe",content:`[${r.subagentName}] answer: ${r.finalAnswer}`,timestamp:Date.now()});let n=e.map(r=>`[${r.subagentName}] ${r.finalAnswer}`).join(`
|
|
1385
1385
|
|
|
1386
|
-
`);return{steps:t,finalAnswer:n}}async finaliseAnswer(e){let{answer:t,subagents:n,uiActions:
|
|
1386
|
+
`);return{steps:t,finalAnswer:n}}async finaliseAnswer(e){let{answer:t,subagents:n,uiActions:r,actionButtons:s,messageId:a}=e??{},i={role:"assistant",content:t,timestamp:Date.now()};return n&&n.length>0&&(i.subagents=n),r&&r.length>0&&(i.uiActions=r),s&&s.length>0&&(i.actionButtons=s),a&&(i.messageId=a),this.history.add(i),await this.persistHistory(),{answer:t,...s&&s.length>0?{actionButtons:s}:{}}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),t=6,n=0,r=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(n++,n>=t)){r=p;break}let s=e.slice(r),a=dp(s,s.length),i=e.length-a.length,l=Ct(e.slice(0,i)),c=this.history.getSummary(),d=[];c&&d.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),d.push(...l);let u=await this.summarizer.summarize(d);this.history.compactWith(u,a)}persistToolMessages(e){for(let t of e)t.toolMessages.length>0&&(this.history.addMany(t.toolMessages),this.history.add({role:"assistant",content:t.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${t.toolMessages.length} tool message(s) + finalAnswer from ${t.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};var Pp=require("js-sha3"),gb="Every domain you analyze is the website of a service that integrates WalletConnect \u2014 i.e. a blockchain / Web3 application (DeFi, DEX, NFT marketplace, bridge, wallet, staking, launchpad, GameFi, etc.). Investigate it WITHIN that crypto/Web3 ecosystem FIRST: assume any brand it resembles is most likely a crypto/blockchain project, look up that brand's official domains within that ecosystem, and prioritize crypto-focused phishing/scam intelligence. This is a strong prior, NOT a guarantee \u2014 if the evidence shows it actually imitates a major NON-crypto brand or is a plain scam, still flag it. NEVER assume a domain is legitimate merely because it sits in the crypto space.",Ap='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',Li=class{llm;debug;ecosystem;secretKey;ownGeminiKey;licenseChecked=!1;constructor(e={}){this.llm=e.provider??new be({temperature:.5,...e.llm}),this.debug=e.debug??!1,this.ecosystem=e.ecosystemContext?.trim()||gb,this.secretKey=e.secretKey??"",this.ownGeminiKey=!!e.llm?.apiKey?.trim()}assertLicense(){if(this.licenseChecked)return;if(this.ownGeminiKey){this.licenseChecked=!0;return}let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,Pp.sha3_256)(this.secretKey)!==e))throw new Error("WebsiteTrustKeyringAgent: invalid or missing secretKey. Pass a valid secretKey to use the Keyring Gemini proxy, or supply your own Gemini key via llm.apiKey to call the Gemini API directly.");this.licenseChecked=!0}async chat(e){this.assertLicense();let t=(e?.url??"").trim();if(!t)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(t),r=e.language?.trim()||"English",s=e.signal;try{if(e.isMarkOfficial){let{description:m,keyFeatures:f}=await this.describeOfficial(t,s),{answer:h,keyFeatures:g}=await this.present(n,{isPhishing:!1,trusted:!0,description:m,reasons:[],keyFeatures:f},r,s),b={currentSite:t,isPhishing:!1};return g.length>0&&(b.keyFeatures=g),{answer:h,extraData:b}}let a=await this.investigate(t,n,s),i=this.buildVerdict(n,a),l=a.keyFeatures;!i.isPhishing&&l.length===0&&(l=await this.gatherKeyFeatures(t,s)),this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",n),console.log("[WebsiteTrustKeyringAgent] investigation:",a),console.log("[WebsiteTrustKeyringAgent] verdict:",i),console.log("[WebsiteTrustKeyringAgent] keyFeaturesEvidence:",l));let{answer:c,reasons:d,keyFeatures:u}=await this.present(n,{isPhishing:i.isPhishing,description:a.description,copiedSite:i.copiedSite,reasons:i.reasons,keyFeatures:l},r,s),p={currentSite:t,isPhishing:i.isPhishing};return i.copiedSite&&(p.copiedSite=i.copiedSite),i.isPhishing&&d.length>0&&(p.reasons=d),!i.isPhishing&&u.length>0&&(p.keyFeatures=u),{answer:c,extraData:p}}catch(a){throw new Error(`WebsiteTrustKeyringAgent.chat failed: ${a instanceof Error?a.message:String(a)}`,{cause:a})}}buildVerdict(e,t){let n=t.officialDomain,r=n?t.affiliatedDomains.filter(f=>!this.looksLikeSquatOf(f,n)):t.affiliatedDomains,s=[t.officialDomain,...r].filter(f=>!!f),a=s.length>0?s.some(f=>this.isSameRegistrableDomain(e,f)):t.exactMatchOfficial,l=(t.resemblesBrand||this.carriesBrandName(e,t.officialDomain,t.brand))&&!a&&t.brandIsWellKnown&&(s.length>0||!t.hasOwnLegitPresence),d=!(a||t.hasOwnLegitPresence&&!l)&&t.scamReports.length>0,u=l||d;if(!u)return{isPhishing:!1,reasons:[]};let p=[];if(l){let f=t.officialDomain?this.describeLookAlike(e,t.officialDomain):void 0;f&&p.push(f),t.impersonationEvidence.length>0?p.push(...t.impersonationEvidence):f||p.push(t.officialDomain?`This address (${e}) is not the official ${t.brand??"brand"} domain \u2014 the real one is ${t.officialDomain}; the look-alike is easy to miss at a glance.`:`This domain (${e}) imitates ${t.brand??"a known brand"} but is not its official site and has no legitimate presence of its own.`)}d&&p.push(...t.scamReports);let m=l?t.officialUrl??t.officialDomain??t.brand:void 0;return{isPhishing:u,copiedSite:m,reasons:this.dedupe(p)}}async investigate(e,t,n){let r=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${t}
|
|
1387
1387
|
URL: ${e}
|
|
1388
1388
|
|
|
1389
1389
|
Investigate, using web search, whether this EXACT domain is a legitimate official site or a phishing / look-alike / scam site. Work through:
|
|
@@ -1414,18 +1414,18 @@ Return ONLY this JSON:
|
|
|
1414
1414
|
"hasOwnLegitPresence": boolean, // does THIS exact domain have its own legitimate presence?
|
|
1415
1415
|
"impersonationEvidence": string[], // >=3 specific points if impersonating; [] otherwise
|
|
1416
1416
|
"scamReports": string[] // SOURCED findings (each with a markdown-link source) accusing THIS exact domain; [] if none/unsourced
|
|
1417
|
-
}`,s=await this.askJson(
|
|
1417
|
+
}`,s=await this.askJson(r,{signal:n,maxRetries:3,system:this.gatherSystem(),maxOutputTokens:4096,thinkingBudget:2048});return{description:this.cleanStr(s?.description)??"",keyFeatures:this.cleanStrArray(s?.keyFeatures),resemblesBrand:s?.resemblesBrand===!0,brand:this.cleanStr(s?.brand),brandIsWellKnown:s?.brandIsWellKnown===!0,officialDomain:this.cleanStr(s?.officialDomain),officialUrl:this.cleanStr(s?.officialUrl),exactMatchOfficial:s?.exactMatchOfficial===!0,affiliatedDomains:this.cleanStrArray(s?.affiliatedDomains),hasOwnLegitPresence:s?.hasOwnLegitPresence===!0,impersonationEvidence:this.cleanStrArray(s?.impersonationEvidence),scamReports:this.cleanStrArray(s?.scamReports)}}async describeOfficial(e,t){let n=`This website is officially verified as legitimate \u2014 established fact, not open to question: ${e}
|
|
1418
1418
|
Using web search, describe what this website / platform is and what it does \u2014 its Web3 category (DeFi, DEX, NFT, bridge, wallet, etc.) and blockchain(s) when identifiable, its purpose, and who runs it. Also list 3-5 concrete FEATURES it offers; for EACH, write a full informative sentence naming the feature and what the user can do with it \u2014 NOT one-word labels.
|
|
1419
1419
|
|
|
1420
1420
|
Describe the PRODUCT only. Do NOT re-verify the site or mention safety, trust, risk, scams, phishing or look-alike sites, even in passing.
|
|
1421
1421
|
|
|
1422
|
-
Return ONLY this JSON: { "description": string, "keyFeatures": string[] } // description: 1-3 concise sentences`,
|
|
1422
|
+
Return ONLY this JSON: { "description": string, "keyFeatures": string[] } // description: 1-3 concise sentences`,r=await this.askJson(n,{signal:t,maxRetries:3,system:this.gatherSystem(),maxOutputTokens:1024});return{description:this.cleanStr(r?.description)??"",keyFeatures:this.cleanStrArray(r?.keyFeatures)}}async gatherKeyFeatures(e,t){let n=`Website: ${e}
|
|
1423
1423
|
Using web search, list 3-5 concrete FEATURES this site offers. For EACH, write a full, informative sentence naming the feature AND what the user can do with it (its Web3 actions: swap, bridge, stake, mint, lend, etc.) \u2014 NOT one-word labels, NOT generic filler.
|
|
1424
1424
|
|
|
1425
|
-
Return ONLY this JSON: { "keyFeatures": string[] } // an array of full-sentence strings`,
|
|
1426
|
-
${t.keyFeatures.map((m,
|
|
1425
|
+
Return ONLY this JSON: { "keyFeatures": string[] } // an array of full-sentence strings`,r=await this.askJson(n,{signal:t,maxRetries:2,system:this.gatherSystem(),maxOutputTokens:768});return this.cleanStrArray(r?.keyFeatures)}async present(e,t,n,r){let s=this.languageLabel(n),a=!t.isPhishing&&t.keyFeatures.length>0,i=[`Website: ${e}`,t.trusted?"":`Assessment: ${t.isPhishing?"shows signs of a phishing / look-alike / scam site":"no phishing or scam signals found"}`,t.copiedSite?`Impersonates: ${t.copiedSite}`:"",`What the site is: ${t.description||"(could not be determined)"}`,a?`Features:
|
|
1426
|
+
${t.keyFeatures.map((m,f)=>`${f+1}. ${m}`).join(`
|
|
1427
1427
|
`)}`:"",t.reasons.length?`Evidence:
|
|
1428
|
-
${t.reasons.map((m,
|
|
1428
|
+
${t.reasons.map((m,f)=>`${f+1}. ${m}`).join(`
|
|
1429
1429
|
`)}`:""].filter(Boolean).join(`
|
|
1430
1430
|
`),l=(t.trusted?`Here are research notes about a website and what it offers (facts only \u2014 do not re-investigate):
|
|
1431
1431
|
${i}
|
|
@@ -1447,6 +1447,6 @@ ${i}
|
|
|
1447
1447
|
|
|
1448
1448
|
LANGUAGE (MANDATORY): write "answer", every "reasons" item AND every "keyFeatures" item ENTIRELY in ${s}. The facts above are in English ONLY as source material \u2014 your output prose MUST be in ${s}, not English (unless ${s} itself is English). Only domain names, URLs, markdown links and brand names stay verbatim.
|
|
1449
1449
|
|
|
1450
|
-
Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:
|
|
1450
|
+
Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:r,googleSearch:!1,system:this.presentationSystem(s),maxRetries:2,maxOutputTokens:1536}),d=this.cleanStr(c?.answer)??(t.description||e),u=this.cleanStrArray(c?.reasons),p=this.cleanStrArray(c?.keyFeatures);return{answer:d,reasons:u.length>0?u.slice(0,5):t.reasons.slice(0,5),keyFeatures:a?(p.length>0?p:t.keyFeatures).slice(0,5):[]}}languageLabel(e){let t={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return t[n]??t[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
|
|
1451
1451
|
|
|
1452
|
-
${
|
|
1452
|
+
${Ap}`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:s=Ap,maxRetries:a=2,maxOutputTokens:i,thinkingBudget:l}=t,c=Date.now(),d=[{role:"system",content:s,timestamp:c},{role:"user",content:e,timestamp:c}],u=await this.llm.chat(d,void 0,{googleSearch:r,maxRetries:a,maxOutputTokens:i,thinkingBudget:l,signal:n}),p=this.parseJson(u.text?.trim()??"");return this.debug&&!p&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(u.text??"").slice(0,200)),p}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(t).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(t=>t.startsWith("xn--")?this.punycodeDecodeLabel(t.slice(4)):t).join("."):e}punycodeDecodeLabel(e){let c=(u,p,m)=>{u=m?Math.floor(u/700):u>>1,u+=Math.floor(u/p);let f=0;for(;u>455;)u=Math.floor(u/35),f+=36;return f+Math.floor(36*u/(u+38))},d=u=>u-48<10?u-22:u-65<26?u-65:u-97<26?u-97:36;try{let u=[],p=e.lastIndexOf("-");for(let b=0;b<Math.max(0,p);b++){let y=e.charCodeAt(b);if(y>=128)return e;u.push(y)}let m=0,f=128,h=72,g=p<0?0:p+1;for(;g<e.length;){let b=m,y=1;for(let k=36;;k+=36){if(g>=e.length)return e;let v=d(e.charCodeAt(g++));if(v>=36)return e;m+=v*y;let A=k<=h?1:k>=h+26?26:k-h;if(v<A)break;y*=36-A}let w=u.length+1;h=c(m-b,w,b===0),f+=Math.floor(m/w),m%=w,u.splice(m,0,f),m++}return String.fromCodePoint(...u)}catch{return e}}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(t=>this.alnum(t)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let s=Array.from({length:r+1},(a,i)=>i);for(let a=1;a<=n;a++){let i=[a];for(let l=1;l<=r;l++){let c=e[a-1]===t[l-1]?0:1;i[l]=Math.min(s[l]+1,i[l-1]+1,s[l-1]+c)}s=i}return s[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let s=this.hostLabels(e);return[t?this.brandCore(t):"",this.alnum(n??"")].filter(i=>i.length>=4).some(i=>r.includes(i)||s.some(l=>this.isNearMiss(l,i)))}looksLikeSquatOf(e,t){if(this.isSameRegistrableDomain(e,t))return!1;let n=this.brandCore(t);if(n.length<4)return!1;let r=this.hostLabels(e);return r.includes(n)?!1:r.some(s=>this.isNearMiss(s,n)||s.length>n.length&&s.includes(n))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let s=n.lastIndexOf("."),a=r.lastIndexOf(".");if(s>0&&a>0){let c=n.slice(0,s),d=r.slice(0,a),u=n.slice(s+1),p=r.slice(a+1);if(c===d&&u!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${u}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.brandCore(r),l=this.hostLabels(n).find(c=>this.isNearMiss(c,i));if(l){let c=this.editDistance(l,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let s=this.coerceToStr(r);s&&n.push(s)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let t=e,n=this.cleanStr(t.feature)??this.cleanStr(t.name)??this.cleanStr(t.title),r=this.cleanStr(t.description)??this.cleanStr(t.detail)??this.cleanStr(t.text)??this.cleanStr(t.value);return n&&r?n===r?n:`${n} \u2014 ${r}`:n||r?n??r:Object.values(t).map(a=>this.cleanStr(a)).filter(a=>!!a).join(" \u2014 ")||void 0}dedupe(e){let t=new Set,n=[];for(let r of e){let s=r.toLowerCase();t.has(s)||(t.add(s),n.push(r))}return n}};var yb=o=>{let e=JSON.parse(o),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((n,r)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${r} is missing "question" or "answer"`);return n})};async function Sp(o,e){let t=o.entries??(o.json?yb(o.json):[]);return t.length===0?{count:0}:new bn(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseSwapProvider,BaseTool,BaseWalletActionTool,BuyTokenTool,CachedResource,ChatHistory,CoinpoolConfigApi,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DEFILLAMA_EXTRA_SIGNALS,DEFILLAMA_POOL_CHAIN_HEXES,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION,DebridgeProvider,DefiLlamaEstimatePoolYieldTool,DefiLlamaPoolByAddressTool,DefiLlamaPoolCandidateResolver,DefiLlamaPoolDetailTool,DefiLlamaPoolSearchTool,DefiLlamaPoolService,DefiLlamaTopPoolsTool,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KeyringSettingApi,KnowledgeBase,LendingMarketDetailTool,LendingMarketsTool,LendingReadService,LendingService,LendingSupplyService,MULTICALL3_ADDRESS,ManageLiquidityRedirectTool,MoralisService,NATIVE_GAS_LIMIT,NFC_AGENT_TOOL_NAMES,NFC_AMAZON_DEFAULT_DOMAIN,NFC_AMAZON_DOMAINS,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,NfcBuyTool,NfcInfoTool,NoFormTool,OpenAddLiquidityFormTool,OpenSupplyFormTool,POOL_UNISWAP_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PoolSwapRouter,PreviewAddLiquidityTool,PublicClient,RelayProvider,Router,SUPPLIABLE_TYPES,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapProviderFactory,SwapRouter,SwapRouterRegistry,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UNRESOLVED_ASSET,UpstashKnowledgeBase,UserSwapRouter,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletHistoryTool,WalletLendingPositionsTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustKeyringAgent,ZERO_ADDRESS,amazonDomainForLanguage,apiClient,applyYieldConversions,buildApprovals,buildChallenge,buildRangePresets,buildUniswapPoolUrl,call,canDeriveV3PoolAddress,chains,checkNativeGasAffordable,checksumAddress,clampTick,clearPublicClientCache,coinpoolConfigApi,compareDecimal,completeX402,configureSupportedChains,configureSwapProvider,convertSusdsShares,createAiAgent,createDefaultSubagents,createNfcAgent,createNftAgent,createPoolUniswapAgent,createPublicClient,createTokenAgent,createTransport,createWalletActionAgent,createWalletAgent,createX402SignatureProvider,decodeAbiParameters,decodeErrorResult,decodeFunctionData,decodeFunctionResult,defiLlamaPoolInfoScope,defiLlamaPoolSupportsLabel,deriveV3PoolAddress,displayFromChallenge,effectivePriceUSD,encodeAbiParameters,encodeApprove,encodeErrorResult,encodeFunctionData,encodeSignedHeader,erc1155Abi,erc20Abi,erc20Abi_bytes32,erc721Abi,estimateGas,estimateNativeGasReserveWei,estimateTransactionFeeWei,ethCallAt,ethCallByChain,exactAmountString,extractOutRaw,extractQuoteError,fallback,feeWeiToNative,fetchTopMarketplaces,floorToDecimals,formatDefiLlamaPool,getAbiItem,getAddress,getBalance,getBlock,getBlockNumber,getChain,getChainContractAddress,getChainId,getChainMeta,getCode,getDefaultRpcUrl,getGasPrice,getNativeTokenInfo,getPublicClient,getRevertReason,getRpcOverrides,getStorageAt,getTokenPriceUSD,getTransactionCount,http,humanToWei,ingestKnowledgeBase,isAbortError,isAddress,isAddressEqual,isPaymentRequired,isShareBasedProtocol,isShareBasedYieldToken,isSupplyChain,keyringSettingApi,listCandidateChains,listSupplyChains,mulDivFloor,multicall,multicall3Abi,multicallRaw,nativeGasShortfall,nfcAmazonSearchUrl,normaliseCountry,normalizeDecimal,normalizePriceRangeToPool,parseAbi,parseAbiItem,parseAbiParameters,pickLogo,planYieldTokenConversions,priceToTick,protocolLabelFor,psm3For,readContract,readPaymentError,readPaymentRequired,readProtocolFeeWei,readReceipt,readSpendableBalance,registerMaybeNoForm,requestWithX402,resolveGasLimit,resolveNfcShopLinks,resolveRpcUrl,resolveRpcUrls,resolveTokenPriceUSD,roundTickToSpacing,rpcCall,setRpcOverrides,spendableNative,swapProviderFactory,swapRouterRegistry,tickToPrice,toEventSelector,toFunctionSelector,toPantographChain,toPlainDecimal,valueYieldTokens,weiToHuman});
|